Repository navigation
Expand file tree
/
Copy pathzip_align.cpp
More file actions
2072 lines (1970 loc) · 91 KB
/
Copy pathzip_align.cpp
File metadata and controls
2072 lines (1970 loc) · 91 KB
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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
zip_align.cpp -- spec step 4: the aligner runner, PAF/CIGAR verification, blocks, the left-snap
projection P, feasibility cuts, the chain DP (frames F/R), the island rule, rule U and the
fragmentation gate. See zip_align.hpp for coordinates, outcomes and the --inject-chains format.
Runner (per distinct window = per distinct target, written once as w.fa):
1. screen (pass 1): minimap2 -x <preset> -N 50 -p 0.01 --secondary=yes -t 1 [-X] w.fa q.fa
on the first --screen-sample queries in canonical order; if at least half pass, every query
goes to pass 2, otherwise every query is screened and the failures are 'prefiltered'.
A query passes if its records' nmatch (column 10) sums to >= N and one record has
nmatch / block length (column 11) >= F (--prefilter N,F).
2. pass 2: the same with -c --eqx.
There is no index file: each process indexes w.fa in memory (0.2 s for a 5 Mb window), because
minimap2 -d does not check its writes and a short index silently maps nothing.
Each phase splits its queries over up to -j processes (largest first onto the lightest batch);
per-query PAF does not depend on batching (checked: minimap2 2.30, batched vs single, .mmi vs
FASTA target, byte-identical) as long as the query keeps its name, because minimap2 seeds its
tie-breaking hash with the name: queries are named q<k> by their index in the window's query
list, so results do not depend on -j or -t.
Failures: a non-zero exit or unparseable output -> the window's units are 'aligner-failed'
(stderr tail logged); a signal (OOM kill included) -> the window is retried once, alone (it
takes the whole -j budget); a second failure -> ZipError(EXIT_ALIGNER). minimap2 reporting
that it could not write or read its files (a full --tmpdir) -> ZipError(EXIT_IO); a process
that cannot be started (process limits) -> ZipError(EXIT_ALIGNER): outcomes never depend on
transient resources. check_failure_rate(): more than 5% of windows failed ->
ZipError(EXIT_ALIGNER). No timeouts. Once an abort is requested (another thread's fatal
error, a stop signal) nothing new starts and the running processes get SIGTERM.
Timing (stderr only): every process records when it asked for a -j slot, when it got one and
when it ended, and minimap2's own "Real time" and "CPU" (its last stderr line). A window's log
line splits its wall time into minimap2 running and waiting for a slot (with none of the
window's processes running), and gives minimap2's own figures; the calls made on a thread add
their windows to its AlignTimingScope (main: one per site).
Verification: every record is checked column by column against both sequences, and minimap2's
nmatch (column 10) and block length (column 11) against a recount. Column 11 leaves out every
ambiguous base: =/X columns with an ambiguous base on either side, ambiguous query bases of I
runs and ambiguous target bases of D runs (a deletion over a reference N gap).
Chain (one per unit, on feasible sub-records; mirrors the design's Python prototype):
elements: blocks cut to feasible runs, each >= --min-piece, with its own exact '=' count;
identical sub-records (same coordinates and ops, from different records) are kept once;
sorted by (qs, qe, ts, strand, te, record, block); the 500 best by '=' are kept.
DP per frame, O(n^2): a predecessor a of b needs a.qe <= b.qs + G and
frame F: ++ collinear (b.ts >= a.te - G); -- collinear (b.te <= a.ts + G) and above the floor
(b.ts >= floor - G); a strand switch starts a new segment after the current
segment's hull (b.ts >= seg.hi - G; floor := seg.hi)
frame R: mirrored (-- collinear; ++ collinear and below the floor b.te <= floor + G; a switch
needs b.te <= seg.lo + G; floor := seg.lo)
Every DP end's chain gets the island rule; a frame's chain is the best one after the island
rule, then the best DP score before it, then the lower chain target start, then the lower end
index. The higher-scoring frame wins, ties to F.
U: C* = best chain. For every element x outside C* whose bound (best prefix to x + relaxed
suffix) reaches (1 - delta) S*, C_x = best chain forced through x; C_x ties if its part not
shared with C* scores >= (1 - delta) x C*'s part not shared with C_x. Among C* and its ties,
keep the fewest out-of-place stretches E; differing strand strings -> 'ambiguous-strand';
otherwise phase ties (one stretch of the window covered by this unit's sub-records with no gap
> G) take the lowest target start, then the lowest query start; copy ties take the highest
score, then the lowest target start, then the lowest query start.
Fragmentation: internal stretches >= G on either axis > max(2, frag x aligned / 5000) refuses.
*/
#include "zip_align.hpp"
#include <dirent.h>
#include <array>
#include <chrono>
#include <map>
#include <set>
#include <unordered_map>
namespace zip {
namespace {
const size_t MAX_CHAIN_PARTS = 500; // spec: keep the 500 highest-scoring sub-records
const int REPEAT_K = 16; // k-mer size of the repeat-fraction diagnostic
// ================================================================ bases
// minimap2's seq_nt4_table: A/C/G/T(U) -> 0..3, everything else (N, IUPAC) -> 4; case-insensitive
struct Nt4Table {
uint8_t t[256];
Nt4Table() {
for (int i = 0; i < 256; ++i) t[i] = 4;
t[(uint8_t)'A'] = t[(uint8_t)'a'] = 0;
t[(uint8_t)'C'] = t[(uint8_t)'c'] = 1;
t[(uint8_t)'G'] = t[(uint8_t)'g'] = 2;
t[(uint8_t)'T'] = t[(uint8_t)'t'] = t[(uint8_t)'U'] = t[(uint8_t)'u'] = 3;
}
};
const Nt4Table NT4;
inline uint8_t nt4(char c) { return NT4.t[(uint8_t)c]; }
inline uint8_t nt4_comp(char c) {
uint8_t x = nt4(c);
return x < 4 ? (uint8_t)(3 - x) : (uint8_t)4;
}
inline void push_op(std::vector<CigarOp>& ops, char op, int64_t len) {
if (len <= 0) return;
if (!ops.empty() && ops.back().op == op) ops.back().len += (uint32_t)len;
else {
CigarOp c;
c.len = (uint32_t)len;
c.op = op;
ops.push_back(c);
}
}
// "12=3X5D..." (ops =, X, I, D; M too when allow_m); adjacent equal ops are merged
bool parse_cigar(const std::string& s, bool allow_m, std::vector<CigarOp>& ops) {
ops.clear();
uint64_t len = 0;
bool have = false;
for (char c : s) {
if (c >= '0' && c <= '9') {
len = len * 10 + (uint64_t)(c - '0');
if (len > 0x7fffffffULL) return false;
have = true;
continue;
}
if (!have || len == 0) return false;
if (!(c == '=' || c == 'X' || c == 'I' || c == 'D' || (allow_m && c == 'M'))) return false;
push_op(ops, c, (int64_t)len);
len = 0;
have = false;
}
return !have && !ops.empty();
}
std::string cigar_str(const std::vector<CigarOp>& ops) {
std::string s;
for (const CigarOp& o : ops) {
s += std::to_string(o.len);
s.push_back(o.op);
}
return s;
}
// ================================================================ files and directories
// RAII temporary directory <parent>/rgfa-zip.XXXXXX, removed with everything in it (registered
// with the Runtime, so a stop signal removes it too)
class TempDir {
public:
explicit TempDir(const std::string& parent) {
std::string tmpl = parent + "/rgfa-zip.XXXXXX";
std::vector<char> buf(tmpl.begin(), tmpl.end());
buf.push_back('\0');
if (!mkdtemp(buf.data())) fail(EXIT_IO, strf("cannot create a temporary directory under %s: %s", parent.c_str(), strerror(errno)));
path_ = buf.data();
Runtime::get().add_path(path_, true);
}
~TempDir() {
if (!path_.empty()) {
remove_tree(path_);
Runtime::get().remove_path(path_);
}
}
TempDir(const TempDir&) = delete;
TempDir& operator=(const TempDir&) = delete;
const std::string& path() const { return path_; }
private:
std::string path_;
};
void write_file(const std::string& path, const std::string& content) {
int fd = open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
if (fd < 0) fail(EXIT_IO, strf("cannot create %s: %s", path.c_str(), strerror(errno)));
const char* p = content.data();
size_t n = content.size();
while (n > 0) {
ssize_t w = ::write(fd, p, n);
if (w < 0) {
if (errno == EINTR) continue;
int e = errno;
::close(fd);
fail(EXIT_IO, strf("write %s: %s", path.c_str(), strerror(e)));
}
p += w;
n -= (size_t)w;
}
if (::close(fd) != 0) fail(EXIT_IO, strf("close %s: %s", path.c_str(), strerror(errno)));
}
bool read_file(const std::string& path, std::string& out) {
out.clear();
int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd < 0) return false;
char buf[1 << 16];
while (true) {
ssize_t r = ::read(fd, buf, sizeof(buf));
if (r < 0) {
if (errno == EINTR) continue;
::close(fd);
return false;
}
if (r == 0) break;
out.append(buf, (size_t)r);
}
::close(fd);
return true;
}
std::vector<std::string> split_ws(const std::string& s) {
std::vector<std::string> out;
std::string cur;
for (char c : s) {
if (c == ' ' || c == '\t' || c == '\n') {
if (!cur.empty()) { out.push_back(cur); cur.clear(); }
} else {
cur.push_back(c);
}
}
if (!cur.empty()) out.push_back(cur);
return out;
}
std::string sanitize(const std::string& s) {
std::string o;
for (char c : s) o.push_back((isalnum((unsigned char)c) || c == '.' || c == '_' || c == '-') ? c : '_');
return o;
}
// ================================================================ the process budget (-j)
// At most `total` minimap2 processes at once. acquire_all() takes the whole budget for a retry
// that must run alone; while it waits, ordinary acquires are held back so it cannot starve.
// Waiting stops with Aborted once an abort is requested (checked every 100 ms).
class ProcessBudget {
public:
explicit ProcessBudget(int total) : total_(std::max(1, total)), free_(std::max(1, total)) {}
void acquire() {
std::unique_lock<std::mutex> lk(m_);
while (!(free_ > 0 && !exclusive_)) {
if (aborting()) throw Aborted();
cv_.wait_for(lk, std::chrono::milliseconds(100));
}
if (aborting()) throw Aborted();
--free_;
}
void release() {
{ std::lock_guard<std::mutex> lk(m_); ++free_; }
cv_.notify_all();
}
void acquire_all() {
excl_.lock();
std::unique_lock<std::mutex> lk(m_);
exclusive_ = true;
while (free_ != total_ || aborting()) {
if (aborting()) {
exclusive_ = false;
lk.unlock();
cv_.notify_all();
excl_.unlock();
throw Aborted();
}
cv_.wait_for(lk, std::chrono::milliseconds(100));
}
free_ = 0;
}
void release_all() {
{
std::lock_guard<std::mutex> lk(m_);
free_ = total_;
exclusive_ = false;
}
cv_.notify_all();
excl_.unlock();
}
int total() const { return total_; }
private:
std::mutex m_, excl_;
std::condition_variable cv_;
const int total_;
int free_;
bool exclusive_ = false;
};
// minimap2's own peak RSS ("[M::main] Real time: ...; Peak RSS: 0.537 GB", GiB) in KB; 0 if absent
long mm2_peak_rss_kb(const std::string& tail) {
size_t p = tail.rfind("Peak RSS: ");
if (p == std::string::npos) return 0;
double gb = strtod(tail.c_str() + p + 10, nullptr);
return gb > 0 ? (long)(gb * 1048576.0 + 0.5) : 0;
}
// minimap2's own wall and CPU seconds ("[M::main] Real time: 0.537 sec; CPU: 0.524 sec; ..."); 0 if absent
void mm2_times(const std::string& tail, double& real, double& cpu) {
real = cpu = 0;
size_t p = tail.rfind("Real time: ");
if (p == std::string::npos) return;
real = strtod(tail.c_str() + p + 11, nullptr);
size_t c = tail.find("CPU: ", p);
if (c != std::string::npos) cpu = strtod(tail.c_str() + c + 5, nullptr);
if (!(real > 0)) real = 0;
if (!(cpu > 0)) cpu = 0;
}
// the sorted union of intervals [a, b)
std::vector<std::pair<double, double>> iv_union(std::vector<std::pair<double, double>> v) {
std::sort(v.begin(), v.end());
std::vector<std::pair<double, double>> out;
for (const auto& x : v) {
if (x.second <= x.first) continue;
if (!out.empty() && x.first <= out.back().second) out.back().second = std::max(out.back().second, x.second);
else out.push_back(x);
}
return out;
}
AlignTimingScope*& timing_top() {
thread_local AlignTimingScope* top = nullptr;
return top;
}
// minimap2's error lines in a stderr tail ("[ERROR] ..." / "ERROR: ..."), else its last line
std::string mm2_error_lines(const std::string& tail) {
std::string out, last;
size_t p = 0;
while (p < tail.size()) {
size_t e = tail.find('\n', p);
if (e == std::string::npos) e = tail.size();
std::string line = tail.substr(p, e - p);
p = e + 1;
if (line.empty()) continue;
last = line;
if (line.find("ERROR") != std::string::npos) out += (out.empty() ? "" : " | ") + line;
}
return out.empty() ? last : out;
}
// Does minimap2's stderr report that it could not write its output or read its input -- an I/O
// problem of --tmpdir (full disk, quota, a vanished directory), not an alignment failure?
bool mm2_io_error(const std::string& tail) {
for (const char* m : {"failed to write", "failed to read data", "failed to open file", "failed to map the query file"})
if (tail.find(m) != std::string::npos) return true;
for (int e : {ENOSPC, EDQUOT, EIO, EROFS})
if (tail.find(strerror(e)) != std::string::npos) return true;
return false;
}
// ================================================================ PAF
struct RawRec {
uint32_t q = 0; // query index within the window's query list
int64_t qlen = 0, qs = 0, qe = 0, tlen = 0, ts = 0, te = 0, nmatch = 0, blen = 0;
char strand = '+';
bool has_cigar = false;
std::string cigar;
};
// Parse minimap2's PAF. Queries are named q<k>, k = the query's index in its window's query list
// (n_queries of them); in_batch[k] says which of them this process was given. False on
// unparseable output (the window is then aligner-failed).
bool parse_paf(const std::string& text, size_t n_queries, const std::vector<uint8_t>& in_batch, bool want_cigar, std::vector<RawRec>& out,
std::string& why) {
size_t p = 0;
std::vector<std::string> f;
uint64_t lineno = 0;
while (p < text.size()) {
size_t e = text.find('\n', p);
if (e == std::string::npos) {
why = "the last PAF line has no newline (truncated output)";
return false;
}
std::string line = text.substr(p, e - p);
p = e + 1;
++lineno;
if (line.empty()) { why = strf("empty PAF line %llu", (unsigned long long)lineno); return false; }
split_tabs(line, f);
if (f.size() < 12) { why = strf("PAF line %llu has %zu columns", (unsigned long long)lineno, f.size()); return false; }
RawRec r;
int64_t qi = -1;
if (f[0].size() < 2 || f[0][0] != 'q' || !parse_int64(f[0].substr(1), qi) || qi < 0 || (size_t)qi >= n_queries ||
!in_batch[(size_t)qi]) {
why = strf("PAF line %llu: unknown query '%s'", (unsigned long long)lineno, f[0].c_str());
return false;
}
r.q = (uint32_t)qi;
if (f[5] != "t") { why = strf("PAF line %llu: unknown target '%s'", (unsigned long long)lineno, f[5].c_str()); return false; }
if (f[4] != "+" && f[4] != "-") { why = strf("PAF line %llu: strand '%s'", (unsigned long long)lineno, f[4].c_str()); return false; }
r.strand = f[4][0];
if (!parse_int64(f[1], r.qlen) || !parse_int64(f[2], r.qs) || !parse_int64(f[3], r.qe) || !parse_int64(f[6], r.tlen) ||
!parse_int64(f[7], r.ts) || !parse_int64(f[8], r.te) || !parse_int64(f[9], r.nmatch) || !parse_int64(f[10], r.blen)) {
why = strf("PAF line %llu: a numeric column does not parse", (unsigned long long)lineno);
return false;
}
for (size_t k = 12; k < f.size(); ++k)
if (f[k].compare(0, 5, "cg:Z:") == 0) { r.cigar = f[k].substr(5); r.has_cigar = true; }
if (want_cigar && !r.has_cigar) { why = strf("PAF line %llu has no cg:Z: tag", (unsigned long long)lineno); return false; }
out.push_back(std::move(r));
}
return true;
}
// Verify a record against both sequences and its own coordinates, and build the PafRecord
// (target shifted by tlo; '=' columns over ambiguous bases rewritten as 'X'). check_counts:
// minimap2's nmatch and block length must equal the recount. False (with why) if inconsistent.
//
// minimap2's block length (PAF column 11; mm_update_extra in align.c) leaves out every ambiguous
// (non-ACGT) base: in =/X columns where either base is ambiguous, in I runs the ambiguous query
// bases, in D runs the ambiguous target bases. So a D run over a reference N gap is shorter in
// column 11 than in the CIGAR. Only this consistency check sees those bases; nmatch, the record's
// '=' count (an N is never '=': minimap2's N-vs-N '=' columns become 'X') and the identity
// '=' / ('=' + 'X' + bases in I/D runs shorter than G) are as the spec defines them, Ns included.
bool verify_record(const RawRec& r, const std::string& qseq, const std::string& tseq, int64_t tlo, bool allow_m, bool check_counts,
int64_t G, PafRecord& out, std::string& why) {
const int64_t qlen = (int64_t)qseq.size(), tlen = (int64_t)tseq.size();
if (r.qlen != qlen) { why = strf("query length %lld, PAF says %lld", (long long)qlen, (long long)r.qlen); return false; }
if (r.tlen != tlen) { why = strf("target length %lld, PAF says %lld", (long long)tlen, (long long)r.tlen); return false; }
if (!(0 <= r.qs && r.qs < r.qe && r.qe <= qlen)) { why = strf("query interval %lld-%lld", (long long)r.qs, (long long)r.qe); return false; }
if (!(0 <= r.ts && r.ts < r.te && r.te <= tlen)) { why = strf("target interval %lld-%lld", (long long)r.ts, (long long)r.te); return false; }
std::vector<CigarOp> ops;
if (!r.has_cigar || !parse_cigar(r.cigar, allow_m, ops)) { why = "CIGAR does not parse as =/X/I/D"; return false; }
int64_t qc = 0, tc = 0;
for (const CigarOp& o : ops) {
if (o.op != 'D') qc += o.len;
if (o.op != 'I') tc += o.len;
}
if (qc != r.qe - r.qs || tc != r.te - r.ts) {
why = strf("CIGAR consumes %lld query / %lld target bases, the record spans %lld / %lld", (long long)qc, (long long)tc,
(long long)(r.qe - r.qs), (long long)(r.te - r.ts));
return false;
}
out = PafRecord();
out.qs = r.qs;
out.qe = r.qe;
out.ts = tlo + r.ts;
out.te = tlo + r.te;
out.strand = r.strand;
const bool fwd = r.strand == '+';
int64_t qi = fwd ? r.qs : r.qe - 1; // next query base ('-': read downward, complemented)
int64_t ti = r.ts;
int64_t unamb_cols = 0, small = 0;
int64_t amb_ins = 0, amb_del = 0; // ambiguous query bases in I runs, target bases in D runs
for (const CigarOp& o : ops) {
const int64_t L = o.len;
if (o.op == '=' || o.op == 'X' || o.op == 'M') {
for (int64_t k = 0; k < L; ++k) {
uint8_t cq = fwd ? nt4(qseq[(size_t)qi]) : nt4_comp(qseq[(size_t)qi]);
uint8_t ct = nt4(tseq[(size_t)ti]);
bool eq = cq == ct;
if (o.op == '=' && !eq) {
why = strf("'=' column at query %lld / target %lld: %c vs %c%s", (long long)qi, (long long)(tlo + ti), qseq[(size_t)qi],
tseq[(size_t)ti], fwd ? "" : " (query complemented)");
return false;
}
if (o.op == 'X' && eq) {
why = strf("'X' column at query %lld / target %lld: %c vs %c%s", (long long)qi, (long long)(tlo + ti), qseq[(size_t)qi],
tseq[(size_t)ti], fwd ? "" : " (query complemented)");
return false;
}
bool unamb = cq < 4 && ct < 4;
if (unamb) ++unamb_cols;
bool match = eq && unamb;
push_op(out.ops, match ? '=' : 'X', 1);
if (match) ++out.n_eq;
else ++out.n_x;
qi += fwd ? 1 : -1;
++ti;
}
} else if (o.op == 'I') {
// the run's query bases: [qi, qi + L) ('+'), or qi, qi - 1, ..., qi - L + 1 ('-')
for (int64_t k = 0; k < L; ++k)
if (nt4(qseq[(size_t)(fwd ? qi + k : qi - k)]) > 3) ++amb_ins;
push_op(out.ops, 'I', L);
out.n_ins += L;
if (L < G) small += L;
qi += fwd ? L : -L;
} else {
for (int64_t k = 0; k < L; ++k)
if (nt4(tseq[(size_t)(ti + k)]) > 3) ++amb_del;
push_op(out.ops, 'D', L);
out.n_del += L;
if (L < G) small += L;
ti += L;
}
}
if (check_counts) {
if (r.nmatch != out.n_eq) {
why = strf("nmatch %lld, recount %lld", (long long)r.nmatch, (long long)out.n_eq);
return false;
}
const int64_t blen = unamb_cols + (out.n_ins - amb_ins) + (out.n_del - amb_del);
if (r.blen != blen) {
why = strf("block length %lld, recount %lld (%lld ambiguous base(s) in I runs, %lld in D runs left out)", (long long)r.blen,
(long long)blen, (long long)amb_ins, (long long)amb_del);
return false;
}
}
int64_t den = out.n_eq + out.n_x + small;
out.gci = den > 0 ? (double)out.n_eq / (double)den : 0.0;
return true;
}
bool record_less(const PafRecord& a, const PafRecord& b) {
if (a.qs != b.qs) return a.qs < b.qs;
if (a.qe != b.qe) return a.qe < b.qe;
if (a.ts != b.ts) return a.ts < b.ts;
if (a.te != b.te) return a.te < b.te;
if (a.strand != b.strand) return a.strand < b.strand;
if (a.ops.size() != b.ops.size()) return a.ops.size() < b.ops.size();
for (size_t i = 0; i < a.ops.size(); ++i) {
if (a.ops[i].op != b.ops[i].op) return a.ops[i].op < b.ops[i].op;
if (a.ops[i].len != b.ops[i].len) return a.ops[i].len < b.ops[i].len;
}
return false;
}
bool record_equal(const PafRecord& a, const PafRecord& b) { return !record_less(a, b) && !record_less(b, a); }
// sort records canonically and drop exact duplicates, so nothing depends on minimap2's output order
void canonical_records(std::vector<PafRecord>& recs) {
std::sort(recs.begin(), recs.end(), record_less);
recs.erase(std::unique(recs.begin(), recs.end(), record_equal), recs.end());
}
// ================================================================ parts
double part_identity(const ChainPart& p, int64_t G) {
int64_t eq = 0, x = 0, small = 0;
for (const CigarOp& o : p.ops) {
if (o.op == '=') eq += o.len;
else if (o.op == 'X') x += o.len;
else if ((int64_t)o.len < G) small += o.len;
}
int64_t den = eq + x + small;
return den > 0 ? (double)eq / (double)den : 0.0;
}
// The sub-part [qa, qb) of a block: target [P(qa), P(qb)) ('+') or [P(qb), P(qa)) ('-'), and the
// ops between them (a D run at the start point is inside, one at the end point is not; this is
// exactly P's left-snap convention). n_eq is recounted.
ChainPart slice_part(const ChainPart& blk, int64_t qa, int64_t qb) {
ChainPart p;
p.record = blk.record;
p.block = blk.block;
p.strand = blk.strand;
p.qs = qa;
p.qe = qb;
const bool fwd = blk.strand == '+';
int64_t c0 = fwd ? qa - blk.qs : blk.qe - qb;
int64_t c1 = fwd ? qb - blk.qs : blk.qe - qa;
std::vector<int64_t> P = project_points(blk, {qa, qb});
p.ts = fwd ? P[0] : P[1];
p.te = fwd ? P[1] : P[0];
int64_t q = 0, tsum = 0;
for (const CigarOp& o : blk.ops) {
const int64_t L = o.len;
if (o.op == 'D') {
if (c0 <= q && q < c1) { push_op(p.ops, 'D', L); tsum += L; }
continue;
}
int64_t lo = std::max(q, c0), hi = std::min(q + L, c1);
if (hi > lo) {
push_op(p.ops, o.op, hi - lo);
if (o.op != 'I') tsum += hi - lo;
if (o.op == '=') p.n_eq += hi - lo;
}
q += L;
}
if (tsum != p.te - p.ts)
fail(EXIT_INVARIANT, strf("internal: slice [%lld,%lld) of a block spans %lld target bases, P gives %lld", (long long)qa,
(long long)qb, (long long)tsum, (long long)(p.te - p.ts)));
return p;
}
// handles of the walk overlapping [qs, qe): (k, a0, a1) in walk coordinates
void overlapping_handles(const QueryLayout& ql, int64_t qs, int64_t qe, std::vector<std::array<int64_t, 3>>& out) {
out.clear();
if (qe <= qs || ql.walk.empty()) return;
size_t k = (size_t)(std::upper_bound(ql.off.begin(), ql.off.end() - 1, qs) - ql.off.begin());
k = k == 0 ? 0 : k - 1;
for (; k < ql.walk.size() && ql.off[k] < qe; ++k) {
int64_t a0 = std::max(ql.off[k], qs), a1 = std::min(ql.off[k + 1], qe);
if (a1 > a0) out.push_back({{(int64_t)k, a0, a1}});
}
}
// Cut a block to its maximal runs of consecutive pieces whose targets are feasible; keep runs of
// at least min_piece query bases.
void feasible_parts(const ChainPart& blk, const QueryLayout& ql, const FeasibleFn& feasible, int64_t min_piece,
std::vector<ChainPart>& out) {
std::vector<std::array<int64_t, 3>> hs;
overlapping_handles(ql, blk.qs, blk.qe, hs);
if (hs.empty()) return;
std::vector<int64_t> xs;
xs.reserve(hs.size() * 2);
for (auto& h : hs) { xs.push_back(h[1]); xs.push_back(h[2]); }
std::vector<int64_t> P = project_points(blk, xs);
const bool fwd = blk.strand == '+';
int64_t run_a = -1, run_b = -1;
auto close = [&]() {
if (run_a >= 0 && run_b - run_a >= min_piece) out.push_back(slice_part(blk, run_a, run_b));
run_a = run_b = -1;
};
for (size_t i = 0; i < hs.size(); ++i) {
NodeId node = handle_node(ql.walk[(size_t)hs[i][0]]);
int64_t ta = fwd ? P[2 * i] : P[2 * i + 1];
int64_t tb = fwd ? P[2 * i + 1] : P[2 * i];
bool ok = !feasible || feasible(node, ta, tb);
if (ok) {
if (run_a < 0) run_a = hs[i][1];
run_b = hs[i][2];
} else {
close();
}
}
close();
}
bool part_less(const ChainPart& a, const ChainPart& b) {
if (a.qs != b.qs) return a.qs < b.qs;
if (a.qe != b.qe) return a.qe < b.qe;
if (a.ts != b.ts) return a.ts < b.ts;
if (a.strand != b.strand) return a.strand < b.strand;
if (a.te != b.te) return a.te < b.te;
if (a.record != b.record) return a.record < b.record;
return a.block < b.block;
}
std::string strand_string(const std::vector<ChainPart>& parts) {
std::string s;
for (const ChainPart& p : parts)
if (s.empty() || s.back() != p.strand) s.push_back(p.strand);
return s;
}
// internal unaligned stretches >= G between consecutive parts (query order), on either axis
int64_t internal_stretches(const std::vector<ChainPart>& parts, int64_t G) {
std::vector<const ChainPart*> v;
for (const ChainPart& p : parts) v.push_back(&p);
std::sort(v.begin(), v.end(), [](const ChainPart* a, const ChainPart* b) {
if (a->qs != b->qs) return a->qs < b->qs;
if (a->qe != b->qe) return a->qe < b->qe;
if (a->ts != b->ts) return a->ts < b->ts;
return a->te < b->te;
});
int64_t n = 0;
for (size_t i = 1; i < v.size(); ++i) {
const ChainPart& a = *v[i - 1];
const ChainPart& b = *v[i];
if (b.qs - a.qe >= G || std::max(a.ts, b.ts) - std::min(a.te, b.te) >= G) ++n;
}
return n;
}
// ================================================================ the chainer
struct Chain {
bool valid = false;
std::vector<uint32_t> el; // element indices (canonical order = query order)
int frame = 0; // 0 = F, 1 = R
int64_t score = 0, aq = 0, hlo = 0, qlo = 0, thi = 0;
std::vector<std::pair<int64_t, int64_t>> islands;
int64_t island_bp = 0;
};
class Chainer {
public:
Chainer(const std::vector<ChainPart>& c, const Options& opt) : c_(c), n_(c.size()), G_(opt.G), B_(opt.b), ISL_(opt.island) {
for (int fr = 0; fr < 2; ++fr) {
alloc(base_[fr]);
alloc(work_[fr]);
fill(fr, -1, 0, base_[fr]);
}
}
// the best chain (forced through element `force` when >= 0), island rule applied; invalid if
// no frame keeps >= b aligned query
Chain best(int force) {
Chain best;
for (int fr = 0; fr < 2; ++fr) {
DP* d = &base_[fr];
if (force >= 0) {
work_[fr] = base_[fr];
fill(fr, force, (size_t)force + 1, work_[fr]);
d = &work_[fr];
}
// every DP end is a candidate chain; the island rule runs on each, and the frame's chain is
// the one with the best score AFTER the island rule, then the best DP score before it (so
// the DP's own chain, and its island-below-b report, win whenever the island rule does not
// change the winner), then the lower chain target start, then the lower end index. Taking
// the best end before the island rule can pick a chain whose islands are then stripped,
// below a chain the DP also holds (chr15:101.75 VNTR).
Chain bf;
int64_t bf_dp = 0;
std::vector<uint32_t> el;
for (size_t j = force >= 0 ? (size_t)force : 0; j < n_; ++j) {
if (!d->ok[j]) continue;
// the island rule can only lower a chain's score: skip ends that cannot beat the best so far
if (bf.valid && d->sc[j] < bf.score) continue;
if (bf.valid && d->sc[j] == bf.score && bf_dp > d->sc[j]) continue;
el.clear();
for (int k = (int)j; k >= 0; k = d->prv[(size_t)k]) el.push_back((uint32_t)k);
std::reverse(el.begin(), el.end());
if (force >= 0 && !std::binary_search(el.begin(), el.end(), (uint32_t)force)) continue;
Chain ch;
ch.frame = fr;
island_rule(el, ch);
if (ch.el.empty()) continue;
bool better = !bf.valid || ch.score > bf.score ||
(ch.score == bf.score && (d->sc[j] > bf_dp || (d->sc[j] == bf_dp && ch.hlo < bf.hlo)));
if (better) {
bf = std::move(ch);
bf_dp = d->sc[j];
}
}
if (!bf.valid) continue;
if (!best.valid || bf.score > best.score) best = std::move(bf);
}
if (best.valid && best.aq < B_) best = Chain();
return best;
}
// upper bound on the score of any chain through element x (for rule U's pruning)
std::vector<int64_t> bounds() const {
std::vector<int64_t> suf(n_, 0), out(n_, 0);
for (size_t i = n_; i-- > 0;) {
int64_t best = 0;
for (size_t j = i + 1; j < n_; ++j)
if (c_[i].qe <= c_[j].qs + G_) best = std::max(best, suf[j]);
suf[i] = c_[i].n_eq + best;
}
for (size_t x = 0; x < n_; ++x) out[x] = std::max(base_[0].sc[x], base_[1].sc[x]) + suf[x] - c_[x].n_eq;
return out;
}
private:
struct DP {
std::vector<int64_t> sc, flo, slo, shi, hlo;
std::vector<int32_t> prv;
std::vector<uint8_t> ok, has_flo;
};
void alloc(DP& d) const {
d.sc.assign(n_, 0); d.flo.assign(n_, 0); d.slo.assign(n_, 0); d.shi.assign(n_, 0); d.hlo.assign(n_, 0);
d.prv.assign(n_, -1); d.ok.assign(n_, 0); d.has_flo.assign(n_, 0);
}
// DP entries j >= from (entries < from are already filled); with force >= 0 only chains that
// contain c[force] (a chain may start at j only if j <= force, and no transition skips force)
void fill(int fr, int force, size_t from, DP& d) const {
const int64_t TOL = G_;
for (size_t j = from; j < n_; ++j) {
const ChainPart& b = c_[j];
bool start = force < 0 || (int64_t)j <= force;
d.ok[j] = start ? 1 : 0;
d.sc[j] = start ? b.n_eq : -1;
d.prv[j] = -1;
d.has_flo[j] = 0;
d.flo[j] = 0;
d.slo[j] = b.ts;
d.shi[j] = b.te;
d.hlo[j] = b.ts;
size_t i0 = (force >= 0 && (int64_t)j > force) ? (size_t)force : 0;
for (size_t i = i0; i < j; ++i) {
if (!d.ok[i]) continue;
const ChainPart& a = c_[i];
if (a.qe > b.qs + TOL) continue;
bool same = false;
if (fr == 0) {
if (a.strand == '+' && b.strand == '+') {
if (b.ts < a.te - TOL) continue;
same = true;
} else if (a.strand == '-' && b.strand == '-') {
if (b.te > a.ts + TOL) continue;
if (d.has_flo[i] && b.ts < d.flo[i] - TOL) continue;
same = true;
} else if (b.ts < d.shi[i] - TOL) {
continue;
}
} else {
if (a.strand == '-' && b.strand == '-') {
if (b.te > a.ts + TOL) continue;
same = true;
} else if (a.strand == '+' && b.strand == '+') {
if (b.ts < a.te - TOL) continue;
if (d.has_flo[i] && b.te > d.flo[i] + TOL) continue;
same = true;
} else if (b.te > d.slo[i] + TOL) {
continue;
}
}
int64_t s2 = d.sc[i] + b.n_eq;
if (s2 > d.sc[j]) {
d.sc[j] = s2;
d.prv[j] = (int32_t)i;
d.ok[j] = 1;
d.hlo[j] = std::min(d.hlo[i], b.ts);
if (same) {
d.has_flo[j] = d.has_flo[i];
d.flo[j] = d.flo[i];
d.slo[j] = std::min(d.slo[i], b.ts);
d.shi[j] = std::max(d.shi[i], b.te);
} else {
d.has_flo[j] = 1;
d.flo[j] = fr == 0 ? d.shi[i] : d.slo[i];
d.slo[j] = b.ts;
d.shi[j] = b.te;
}
}
}
}
}
// groups split where consecutive elements are >= --island apart on both axes; groups with
// < b aligned query are removed
void island_rule(const std::vector<uint32_t>& el, Chain& ch) const {
std::vector<std::vector<uint32_t>> groups;
for (size_t k = 0; k < el.size(); ++k) {
if (k == 0) { groups.push_back({el[0]}); continue; }
const ChainPart& a = c_[el[k - 1]];
const ChainPart& b = c_[el[k]];
int64_t tgap = std::max<int64_t>(0, std::max(a.ts, b.ts) - std::min(a.te, b.te));
if (b.qs - a.qe >= ISL_ && tgap >= ISL_) groups.push_back({el[k]});
else groups.back().push_back(el[k]);
}
ch.el.clear();
ch.islands.clear();
ch.island_bp = 0;
for (const std::vector<uint32_t>& gr : groups) {
int64_t aq = 0;
for (uint32_t e : gr) aq += c_[e].qe - c_[e].qs;
if (aq >= B_) ch.el.insert(ch.el.end(), gr.begin(), gr.end());
else {
ch.islands.push_back(std::make_pair(c_[gr.front()].qs, c_[gr.back()].qe));
ch.island_bp += aq;
}
}
ch.score = ch.aq = 0;
ch.hlo = INT64_MAX;
ch.thi = INT64_MIN;
ch.qlo = ch.el.empty() ? 0 : c_[ch.el.front()].qs;
for (uint32_t e : ch.el) {
ch.score += c_[e].n_eq;
ch.aq += c_[e].qe - c_[e].qs;
ch.hlo = std::min(ch.hlo, c_[e].ts);
ch.thi = std::max(ch.thi, c_[e].te);
}
ch.valid = !ch.el.empty();
}
const std::vector<ChainPart>& c_;
size_t n_;
int64_t G_, B_, ISL_;
DP base_[2], work_[2];
};
std::vector<ChainPart> chain_parts(const std::vector<ChainPart>& c, const Chain& ch) {
std::vector<ChainPart> v;
for (uint32_t e : ch.el) v.push_back(c[e]);
return v;
}
} // namespace
// ================================================================ P
int64_t project_left_snap(const ChainPart& p, int64_t x) {
int64_t c = p.strand == '+' ? x - p.qs : p.qe - x; // query bases consumed
int64_t t = p.ts, q = 0;
if (c <= 0) return t;
for (const CigarOp& op : p.ops) {
if (op.op == '=' || op.op == 'X' || op.op == 'M') {
if (c <= q + (int64_t)op.len) return t + (c - q);
q += op.len;
t += op.len;
} else if (op.op == 'I') {
if (c <= q + (int64_t)op.len) return t;
q += op.len;
} else if (op.op == 'D') {
t += op.len;
}
}
return t;
}
std::vector<int64_t> project_points(const ChainPart& p, const std::vector<int64_t>& xs) {
const size_t n = xs.size();
std::vector<int64_t> out(n, p.ts);
std::vector<std::pair<int64_t, size_t>> cs(n);
for (size_t i = 0; i < n; ++i) cs[i] = std::make_pair(p.strand == '+' ? xs[i] - p.qs : p.qe - xs[i], i);
std::sort(cs.begin(), cs.end());
size_t i = 0;
while (i < n && cs[i].first <= 0) out[cs[i++].second] = p.ts;
int64_t t = p.ts, q = 0;
for (const CigarOp& op : p.ops) {
if (i >= n) break;
const int64_t L = op.len;
if (op.op == '=' || op.op == 'X' || op.op == 'M') {
while (i < n && cs[i].first <= q + L) { out[cs[i].second] = t + (cs[i].first - q); ++i; }
q += L;
t += L;
} else if (op.op == 'I') {
while (i < n && cs[i].first <= q + L) { out[cs[i].second] = t; ++i; }
q += L;
} else if (op.op == 'D') {
t += L;
}
}
while (i < n) out[cs[i++].second] = t;
return out;
}
// ================================================================ chaining API
QueryLayout QueryLayout::of(const Graph& g, const std::vector<Handle>& walk) {
QueryLayout ql;
ql.walk = walk;
ql.off.resize(walk.size() + 1);
int64_t o = 0;
for (size_t k = 0; k < walk.size(); ++k) {
ql.off[k] = o;
o += g.len(handle_node(walk[k]));
}
ql.off[walk.size()] = o;
return ql;
}
std::vector<ChainPart> record_blocks(const PafRecord& r, uint32_t record_index, int64_t G) {
std::vector<ChainPart> out;
const bool fwd = r.strand == '+';
int64_t q = fwd ? r.qs : r.qe, t = r.ts, q0 = 0;
bool open = false, aligned = false;
ChainPart cur;
uint32_t bi = 0;
auto close = [&]() {
if (!open) return;
if (fwd) { cur.qs = q0; cur.qe = q; }
else { cur.qs = q; cur.qe = q0; }
cur.te = t;
if (aligned) {
cur.block = bi++;
out.push_back(cur);
}
open = false;
};
for (const CigarOp& o : r.ops) {
const int64_t L = o.len;
if ((o.op == 'I' || o.op == 'D') && L >= G) {
close();
if (o.op == 'I') q += fwd ? L : -L;
else t += L;
continue;
}
if (!open) {
cur = ChainPart();
cur.record = record_index;
cur.strand = r.strand;
cur.ts = t;
q0 = q;
open = true;
aligned = false;
}
push_op(cur.ops, o.op, L);
if (o.op == '=' || o.op == 'X') {
q += fwd ? L : -L;
t += L;
aligned = true;
if (o.op == '=') cur.n_eq += L;
} else if (o.op == 'I') {
q += fwd ? L : -L;
} else {
t += L;
}
}
close();
return out;
}
int64_t chain_E(const std::vector<ChainPart>& parts, int64_t qlen, int64_t tlo, int64_t thi, int64_t G) {
int64_t e = 0;
std::vector<std::pair<int64_t, int64_t>> iv;
for (int axis = 0; axis < 2; ++axis) {
iv.clear();
for (const ChainPart& p : parts) iv.push_back(axis == 0 ? std::make_pair(p.qs, p.qe) : std::make_pair(p.ts, p.te));
std::sort(iv.begin(), iv.end());
int64_t pos = axis == 0 ? 0 : tlo, end = axis == 0 ? qlen : thi;
for (auto& x : iv) {
if (x.first - pos > G) ++e;
pos = std::max(pos, x.second);
}
if (end - pos > G) ++e;
}
std::string s = strand_string(parts);
return e + (s.empty() ? 0 : (int64_t)s.size() - 1);
}
void make_pieces(const QueryLayout& ql, ChainResult& ch) {
ch.pieces.clear();
std::vector<std::array<int64_t, 3>> hs;
std::vector<int64_t> xs;
for (uint32_t pi = 0; pi < (uint32_t)ch.parts.size(); ++pi) {
const ChainPart& p = ch.parts[pi];
overlapping_handles(ql, p.qs, p.qe, hs);
xs.clear();
for (auto& h : hs) { xs.push_back(h[1]); xs.push_back(h[2]); }
std::vector<int64_t> P = project_points(p, xs);
const bool fwd = p.strand == '+';
for (size_t i = 0; i < hs.size(); ++i) {
size_t k = (size_t)hs[i][0];