nail 0.5.0

nail is an alignment inference tool
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
use self::consts::*;

use std::{
    fs::File,
    io::{BufRead, BufReader, Read, Seek, Write},
    path::{Path, PathBuf},
    process::Command,
};

use libnail::{align::Nats, alphabet::UTF8_TO_DIGITAL_AMINO, structs::Profile};

use crate::{
    args::SearchArgs,
    io::{Database, Fasta, ReadSeekExt, ReadState},
    util::{CommandExt, PathExt},
};

use anyhow::Context;
use anyhow::{anyhow, bail};
use regex::Regex;

pub mod consts {
    pub const AMINO_DBTYPE: &[u8] = &[0, 0, 0, 0];
    pub const PROFILE_DBTYPE: &[u8] = &[2, 0, 0, 0];
    pub const ALIGN_DBTYPE: &[u8] = &[5, 0, 0, 0];
    pub const PREFILTER_DBTYPE: &[u8] = &[7, 0, 0, 0];
    pub const GENERIC_DBTYPE: &[u8] = &[12, 0, 0, 0];
}

pub enum ByteBuffer<'a> {
    Complete(&'a [u8]),
    Partial(&'a [u8], usize),
    Empty,
}

#[derive(Clone, Copy)]
struct Descriptor {
    file_idx: usize,
    offset: u64,
    length: u64,
}

pub struct PrefilterDb {
    file: File,
    paths: Vec<PathBuf>,
    descriptors: Vec<Descriptor>,
    checkpoints: Vec<u64>,
    buf: Vec<u8>,
}

impl PrefilterDb {
    pub fn from_path<P>(path: P) -> anyhow::Result<Self>
    where
        P: AsRef<Path>,
    {
        let path = path.as_ref();
        let dir = path.parent().context("path has no parent dir")?;
        let name = path
            .file_stem()
            .context("no file stem")?
            .to_str()
            .context("invalid utf8")?;

        // ---

        let index_path = path.with_extension("index");
        let index_reader =
            BufReader::new(File::open(&index_path).with_context(|| format!("{:?}", index_path))?);

        let mut offsets = vec![];
        let mut lengths = vec![];
        for line in index_reader.lines() {
            let line = line?;

            let tokens = line
                .split('\t')
                .map(|s| s.parse::<u64>().expect("failed to parse index line"))
                .collect::<Vec<_>>();

            offsets.push(tokens[1]);
            // -1 because the index lengths include a null byte
            lengths.push(tokens[2] - 1);
        }

        offsets.shrink_to_fit();
        lengths.shrink_to_fit();

        // ---

        let re = Regex::new(&format!(r"^{}\.\d+$", regex::escape(name)))?;
        let mut paths = std::fs::read_dir(dir)?
            .filter_map(Result::ok)
            .map(|e| e.path())
            .filter(|p| {
                p.file_name()
                    .and_then(|s| s.to_str())
                    .map(|s| re.is_match(s))
                    .unwrap_or(false)
            })
            .collect::<Vec<_>>();

        paths.sort_by_key(|p| {
            p.extension()
                .and_then(|e| e.to_str())
                .and_then(|s| s.parse::<usize>().ok())
                .expect("bad DB split suffix")
        });

        // if we have no paths here, that
        // means the prefilter is one file
        if paths.is_empty() {
            paths.push(path.to_path_buf())
        }

        let file_sizes: Vec<u64> = paths
            .iter()
            .map(|p| p.metadata().map(|m| m.len()))
            .collect::<Result<_, _>>()?;

        let prefix_sum = file_sizes
            .into_iter()
            .scan(0u64, |acc, x| {
                let cur = *acc;
                *acc += x;
                Some(cur)
            })
            .collect::<Vec<_>>();

        // --

        let mut descriptors = offsets
            .into_iter()
            .zip(lengths)
            .map(|(offset, length)| {
                let file_idx = match prefix_sum.binary_search(&offset) {
                    // this means the binary search found the exact offset
                    Ok(idx) => idx,
                    // this means the binary search landed between offsets
                    Err(idx) => idx.saturating_sub(1),
                };

                let relative_offset = offset - prefix_sum[file_idx];
                Descriptor {
                    file_idx,
                    offset: relative_offset,
                    length,
                }
            })
            .collect::<Vec<_>>();

        for desc in descriptors.iter_mut() {
            let mut file = File::open(&paths[desc.file_idx])?;
            file.seek(std::io::SeekFrom::Start(desc.offset + desc.length))?;

            let mut b = [0u8; 1];
            file.read_exact(&mut b)?;
            let byte = b[0];
            assert!(byte == 0);
        }

        let file = File::open(&paths[0])?;
        let checkpoints = vec![0; descriptors.len()];
        let buf = Vec::with_capacity(2 << 11);

        Ok(Self {
            file,
            paths,
            descriptors,
            checkpoints,
            buf,
        })
    }

    pub fn open_file(&mut self, file_idx: usize) -> anyhow::Result<()> {
        self.file = File::open(&self.paths[file_idx])?;
        Ok(())
    }

    pub fn get(&mut self, prf_idx: usize) -> anyhow::Result<&[u8]> {
        let desc = self.descriptors[prf_idx];

        if desc.length == 0 {
            return Ok(&[]);
        }

        self.open_file(desc.file_idx)?;

        self.file.seek(std::io::SeekFrom::Start(desc.offset))?;
        let mut taken = (&mut self.file).take(desc.length);

        self.buf.clear();
        self.buf.resize(desc.length as usize, 0);

        match taken.read_with_state(&mut self.buf)? {
            ReadState::Final(_) => Ok(&self.buf),
            _ => unreachable!(),
        }
    }

    pub fn next_n(&'_ mut self, prf_idx: usize, n: usize) -> anyhow::Result<ByteBuffer<'_>> {
        if n == 0 {
            return Ok(ByteBuffer::Empty);
        }

        let desc = self.descriptors[prf_idx];
        self.open_file(desc.file_idx)?;

        let checkpoint = &mut self.checkpoints[prf_idx];

        let start = desc.offset + *checkpoint;
        let end = desc.offset + desc.length;
        let remaining = end.saturating_sub(start);

        if remaining == 0 {
            return Ok(ByteBuffer::Empty);
        }

        self.file.seek(std::io::SeekFrom::Start(start))?;
        let mut taken = (&mut self.file).take(remaining);

        self.buf.clear();

        const CHUNK_SZ: usize = 2 << 12;
        let mut record_cnt = 0;
        loop {
            let old_len = self.buf.len();
            self.buf.resize(old_len + CHUNK_SZ, 0);

            let n_read = match taken.read_with_state(&mut self.buf[old_len..])? {
                ReadState::Reading(n) | ReadState::Final(n) => n,
                ReadState::Done => {
                    self.buf.truncate(old_len);
                    *checkpoint = desc.length;
                    return Ok(ByteBuffer::Partial(&self.buf, record_cnt));
                }
            };

            self.buf.truncate(old_len + n_read);

            for (pos, &b) in self.buf.iter().enumerate().skip(old_len) {
                if b == b'\n' {
                    record_cnt += 1;
                }

                if record_cnt == n {
                    *checkpoint += (pos + 1) as u64;
                    self.buf.truncate(pos + 1);
                    return Ok(ByteBuffer::Complete(&self.buf));
                }
            }
        }
    }
}

pub struct MmseqsDbPaths {
    pub query_db: PathBuf,
    pub target_db: PathBuf,
    pub prefilter_db: PathBuf,
    pub align_db: PathBuf,
    pub prog_dir: PathBuf,
}

impl MmseqsDbPaths {
    pub fn new(dir: impl AsRef<Path>) -> Self {
        let dir = dir.as_ref().to_path_buf();
        Self {
            query_db: dir.join("query-db/qdb"),
            target_db: dir.join("target-db/tdb"),
            prefilter_db: dir.join("prefilter-db/pdb"),
            align_db: dir.join("align-db/adb"),
            prog_dir: dir.join("prog-seed/"),
        }
    }

    pub fn destroy(&self) -> anyhow::Result<()> {
        Self::remove_db(&self.query_db).context("failed to remove mmseqs query DB")?;
        Self::remove_db(&self.target_db).context("failed to remove mmseqs target DB")?;
        Self::remove_db(&self.prefilter_db).context("failed to remove mmseqs prefilter DB")?;
        Self::remove_db(&self.align_db).context("failed to remove mmseqs align DB")?;

        if self
            .prog_dir
            .try_exists()
            .with_context(|| format!("failed to check existence of: {:?}", self.prog_dir))?
        {
            let re = Regex::new(r"^\d+$")?;
            std::fs::read_dir(&self.prog_dir)
                .with_context(|| format!("failed to open dir: {:?}", &self.prog_dir))?
                .try_for_each(|entry| -> anyhow::Result<()> {
                    let entry = entry.with_context(|| {
                        format!("failed to access a file in dir: {:?}", &self.prog_dir)
                    })?;

                    let path = entry.path();

                    let ft = entry
                        .file_type()
                        .with_context(|| format!("failed to stat {path:?}"))?;

                    if ft.is_dir()
                        && path
                            .file_name()
                            .and_then(|s| s.to_str())
                            .is_some_and(|s| re.is_match(s))
                    {
                        std::fs::remove_dir_all(&path)
                            .with_context(|| format!("failed to remove {path:?}"))?;
                    }

                    Ok(())
                })?;
        }

        Ok(())
    }

    pub fn check(&self) -> anyhow::Result<()> {
        if Self::db_exists(&self.query_db)? {
            bail!("mmseqs query DB already exists");
        } else if Self::db_exists(&self.target_db)? {
            bail!("mmseqs target DB already exists");
        } else if Self::db_exists(&self.prefilter_db)? {
            bail!("mmseqs prefilter DB already exists");
        } else if Self::db_exists(&self.align_db)? {
            bail!("mmseqs align DB already exists");
        }
        Ok(())
    }

    fn db_exists<P: AsRef<Path>>(path: P) -> anyhow::Result<bool> {
        let path = path.as_ref();
        let db_dir = path.parent().context("DB path has no parent dir")?;

        if !db_dir
            .try_exists()
            .with_context(|| format!("failed to check existence of: {db_dir:?}"))?
        {
            return Ok(false);
        }

        let db_name = path
            .file_stem()
            .and_then(|s| s.to_str())
            .context("failed to get db name from path")?;

        let re = Regex::new(&format!(r"^{}.*", regex::escape(db_name)))?;

        std::fs::read_dir(db_dir)
            .with_context(|| format!("failed to open dir: {db_dir:?}"))?
            .try_fold(false, |_, entry| {
                let p = entry
                    .with_context(|| format!("failed to access a file in dir: {db_dir:?}"))?
                    .path();

                Ok(p.file_name()
                    .and_then(|s| s.to_str())
                    .is_some_and(|s| re.is_match(s)))
            })
    }

    fn remove_db<P: AsRef<Path>>(path: P) -> anyhow::Result<()> {
        let path = path.as_ref();
        let db_dir = path.parent().context("DB path has no parent dir")?;

        if !db_dir
            .try_exists()
            .with_context(|| format!("failed to check existence of: {db_dir:?}"))?
        {
            return Ok(());
        }

        if !db_dir.is_dir() {
            bail!("DB parent is not a directory");
        }

        if !db_dir
            .file_name()
            .and_then(|s| s.to_str())
            .is_some_and(|s| s.ends_with("-db"))
        {
            bail!("DB parent dir name is supposed to end with -db");
        }

        let db_name = path
            .file_stem()
            .and_then(|s| s.to_str())
            .context("failed to get db name from path")?;

        if db_name.is_empty() {
            bail!("empty DB prefix")
        }

        let re = Regex::new(&format!(
            r"^{}(\.\d+|\.index|\.dbtype|_h|_h\.index|_h\.dbtype)?$",
            regex::escape(db_name)
        ))?;

        std::fs::read_dir(db_dir)
            .with_context(|| format!("failed to open dir: {db_dir:?}"))?
            .try_for_each(|entry| -> anyhow::Result<()> {
                let entry =
                    entry.with_context(|| format!("failed to access a file in dir: {db_dir:?}"))?;

                let path = entry.path();

                let ft = entry
                    .file_type()
                    .with_context(|| format!("failed to stat {path:?}"))?;

                if ft.is_dir() {
                    return Ok(());
                }

                if path
                    .file_name()
                    .and_then(|s| s.to_str())
                    .is_some_and(|s| re.is_match(s))
                {
                    std::fs::remove_file(&path)
                        .with_context(|| format!("failed to remove {path:?}"))?;
                }

                Ok(())
            })?;

        Ok(())
    }
}

pub fn write_mmseqs_sequence_database(
    sequences: &Fasta,
    path: impl AsRef<Path>,
) -> anyhow::Result<()> {
    let db_path = path.as_ref().to_owned();
    let db_name = db_path.file_name().unwrap().to_str().unwrap();
    let db_index_path = db_path.with_file_name(format!("{db_name}.index"));
    let db_dbtype_path = db_path.with_file_name(format!("{db_name}.dbtype"));

    let header_path = db_path.with_file_name(format!("{db_name}_h"));
    let header_index_path = db_path.with_file_name(format!("{db_name}_h.index"));
    let header_dbtype_path = db_path.with_file_name(format!("{db_name}_h.dbtype"));

    let db_dir = db_path
        .parent()
        .context("failed to produce mmseqs sequence DB directory path")?;

    db_dir.create_dir()?;

    db_dbtype_path.open(true)?.write_all(AMINO_DBTYPE)?;
    header_dbtype_path.open(true)?.write_all(GENERIC_DBTYPE)?;

    let mut db = db_path.open(true)?;
    let mut db_index = db_index_path.open(true)?;
    let mut db_header = header_path.open(true)?;
    let mut db_header_index = header_index_path.open(true)?;

    let mut db_offset = 0usize;
    let mut header_offset = 0usize;

    for (seq_count, seq) in sequences.values().enumerate() {
        db.write_all(&seq.utf8_bytes[1..])?;
        db.write_all(&[10u8, 0u8])?;

        let db_byte_length = seq.length + 2;
        writeln!(db_index, "{}\t{}\t{}", seq_count, db_offset, db_byte_length,)?;

        writeln!(db_header, "{}", seq.name)?;
        db_header.write_all(&[0u8])?;

        let header_byte_length = seq.name.len() + 2;
        writeln!(
            db_header_index,
            "{}\t{}\t{}",
            seq_count, header_offset, header_byte_length
        )?;

        db_offset += db_byte_length;
        header_offset += header_byte_length;
    }

    Ok(())
}

pub fn write_mmseqs_profile_database(
    profiles: impl Iterator<Item = Profile>,
    path: impl AsRef<Path>,
) -> anyhow::Result<()> {
    let db_path = path.as_ref().to_owned();
    let db_name = db_path.file_name().unwrap().to_str().unwrap();
    let db_index_path = db_path.with_file_name(format!("{db_name}.index"));
    let db_dbtype_path = db_path.with_file_name(format!("{db_name}.dbtype"));

    let header_path = db_path.with_file_name(format!("{db_name}_h"));
    let header_index_path = db_path.with_file_name(format!("{db_name}_h.index"));
    let header_dbtype_path = db_path.with_file_name(format!("{db_name}_h.dbtype"));

    let db_dir = db_path
        .parent()
        .context("failed to produce mmseqs profile DB directory path")?;

    db_dir.create_dir()?;

    db_dbtype_path.open(true)?.write_all(PROFILE_DBTYPE)?;
    header_dbtype_path.open(true)?.write_all(GENERIC_DBTYPE)?;

    let mut db = db_path.open(true)?;
    let mut db_index = db_index_path.open(true)?;
    let mut db_header = header_path.open(true)?;
    let mut db_header_index = header_index_path.open(true)?;

    let mut db_offset = 0usize;
    let mut header_offset = 0usize;

    for (prf_cnt, prf) in profiles.enumerate() {
        for prf_idx in 1..=prf.length {
            for byte in (0..20)
                .map(|residue| Nats(prf.match_score(residue, prf_idx)))
                .map(|nats| nats.to_bits())
                .map(|bits| bits.value())
                // multiply the bits by 8.0 just because
                // that's what they do in mmseqs
                .map(|s| (s * 8.0) as i8)
                .map(|s| s as u8)
            {
                db.write_all(&[byte])?;
            }

            let consensus_byte_digital = *UTF8_TO_DIGITAL_AMINO
                .get(&prf.consensus_seq_bytes_utf8[prf_idx])
                .unwrap();

            // query sequence byte?
            // still not sure what this is, so we'll just put the consensus
            db.write_all(&[consensus_byte_digital])?;

            // consensus sequence byte
            db.write_all(&[consensus_byte_digital])?;

            // neff value
            db.write_all(&[0u8])?;

            // something
            db.write_all(&[0u8])?;
            // something
            db.write_all(&[0u8])?;
        }

        let db_byte_length = prf.length * 25;

        writeln!(db_index, "{}\t{}\t{}", prf_cnt, db_offset, db_byte_length,)?;

        // for some reason, the header has newlines and 0-byte separators?
        writeln!(db_header, "{}", prf.name)?;
        db_header.write_all(&[0u8])?;

        // +1 for the 0 byte, +1 for the newline
        let header_byte_length = prf.name.len() + 2;

        writeln!(
            db_header_index,
            "{}\t{}\t{}",
            prf_cnt, header_offset, header_byte_length
        )?;

        db_offset += db_byte_length;
        header_offset += header_byte_length;
    }

    Ok(())
}

pub fn run_mmseqs_prefilter(
    query_db_path: impl AsRef<Path>,
    target_db_path: impl AsRef<Path>,
    prefilter_db_path: impl AsRef<Path>,
    // TODO: generics make this annoying
    score_mx_path: Option<PathBuf>,
    args: &SearchArgs,
) -> anyhow::Result<()> {
    let mut prefilter = Command::new("mmseqs");

    let qdb = query_db_path.as_ref();
    let tdb = target_db_path.as_ref();
    let pdb = prefilter_db_path.as_ref();

    let pdb_dir = pdb
        .parent()
        .context("failed to produce mmseqs prefilter DB directory path")?;

    pdb_dir.create_dir()?;

    prefilter
        .arg("prefilter")
        .arg(qdb)
        .arg(tdb)
        .arg(pdb)
        .args(["--threads", &args.num_threads.to_string()])
        .args(["-k", &args.mmseqs_args.k.to_string()])
        .args(["-s", &args.mmseqs_args.s.to_string()])
        .args(["--max-seqs", &args.mmseqs_args.max_seqs.to_string()]);

    if let Some(v) = args.mmseqs_args.comp_bias_corr {
        prefilter.args(["--comp-bias-corr", &v.to_string()]);
    }

    if let Some(ref path) = score_mx_path {
        prefilter.arg("--sub-mat");
        prefilter.arg(path);
    };

    prefilter.run()?;

    Ok(())
}

pub fn run_mmseqs_align(
    query_db_path: impl AsRef<Path>,
    target_db_path: impl AsRef<Path>,
    prefilter_db_path: impl AsRef<Path>,
    align_db_path: impl AsRef<Path>,
    // TODO: generics make this annoying
    score_mx_path: Option<PathBuf>,
    args: &SearchArgs,
) -> anyhow::Result<()> {
    let effective_e_value = args.pipeline_args.seed_pvalue_threshold
        * args
            .expert_args
            .target_database_size
            .ok_or(anyhow!("no target database size"))? as f64;

    let qdb = query_db_path.as_ref();
    let tdb = target_db_path.as_ref();
    let pdb = prefilter_db_path.as_ref();
    let adb = align_db_path.as_ref().to_path_buf();

    let adb_dir = adb
        .parent()
        .context("failed to produce mmseqs align DB directory path")?;

    adb_dir.create_dir()?;

    let mut align = Command::new("mmseqs");
    align
        .arg("align")
        .arg(qdb)
        .arg(tdb)
        .arg(pdb)
        .arg(&adb)
        .args(["--threads", &args.num_threads.to_string()])
        .args(["-e", &effective_e_value.to_string()])
        // the '-a' argument enables alignment backtraces in mmseqs2
        // it is required to get start positions for alignments
        .args(["-a", "1"]);

    if let Some(v) = args.mmseqs_args.comp_bias_corr {
        align.args(["--comp-bias-corr", &v.to_string()]);
    }

    if let Some(ref path) = score_mx_path {
        align.arg("--sub-mat");
        align.arg(path);
    };

    align.run()?;

    Ok(())
}

pub fn run_mmseqs_convertalis(
    query_db_path: impl AsRef<Path>,
    target_db_path: impl AsRef<Path>,
    align_db_path: impl AsRef<Path>,
    align_tsv_path: impl AsRef<Path>,
    args: &SearchArgs,
) -> anyhow::Result<()> {
    let qdb = query_db_path.as_ref();
    let tdb = target_db_path.as_ref();
    let adb = align_db_path.as_ref().to_path_buf();
    let align_tsv = align_tsv_path.as_ref();

    Command::new("mmseqs")
        .arg("convertalis")
        .arg(qdb)
        .arg(tdb)
        .arg(adb)
        .arg(align_tsv)
        .args(["--threads", &args.num_threads.to_string()])
        .args([
            "--format-output",
            "qheader,theader,qstart,qend,tstart,tend,bits,evalue",
        ])
        .run()?;

    Ok(())
}