File: SASearcher.hpp

package info (click to toggle)
rapmap 0.12.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 5,388 kB
  • sloc: cpp: 38,057; ansic: 2,754; sh: 209; python: 82; makefile: 15
file content (652 lines) | stat: -rw-r--r-- 23,902 bytes parent folder | download
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
//
// RapMap - Rapid and accurate mapping of short reads to transcriptomes using
// quasi-mapping.
// Copyright (C) 2015, 2016 Rob Patro, Avi Srivastava, Hirak Sarkar
//
// This file is part of RapMap.
//
// RapMap is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// RapMap is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with RapMap.  If not, see <http://www.gnu.org/licenses/>.
//

#ifndef SA_SEARCHER_HPP
#define SA_SEARCHER_HPP

#include <vector>
#include <algorithm>
#include <iterator>
#include "Kmer.hpp"

#include "RapMapUtils.hpp"
#include "RapMapSAIndex.hpp"

template <typename RapMapIndexT>
class SASearcher {
    public:
        using OffsetT = typename RapMapIndexT::IndexType;

        SASearcher(RapMapIndexT* rmi) :
            rmi_(rmi), seq_(&rmi->seq), sa_(&rmi->SA) {}

        int cmp(std::string::iterator abeg,
                std::string::iterator aend,
                std::string::iterator bbeg,
                std::string::iterator bend) {
            auto ait = abeg;
            auto bit = bbeg;
            //size_t la = a.length();
            //size_t lb = b.length();
            while (ait < aend and bit < bend) {
                if (*ait < *bit) {
                    return -1;
                } else if (*ait > *bit) {
                    return 1;
                }
                ++ait;
                ++bit;
            }
            if (bit == bend and ait < aend) {
                return 1;
            }
            return 0;
        }

        enum class SearchDirection : uint8_t {
            UP = 0, DOWN
        };
    
        template <typename IndexT>
        struct BoundSearchResult {
            IndexT maxLen;
            IndexT bound;
            SearchDirection dir;
        };



	/**
	 * OK!  It should be (is) possible to figure out what we need with only two binary
	 * searches.  However, that seems to have some tricky corner cases and has been
	 * somewhat illusive so far.  This "naive" version performs *3* binary searches.
	 * The first determines the length of the maximum mappable prefix (MMP).  The second
	 * finds the lower bound for the query interval and the third finds the upper bound.
	 * The final binary search *is* optimized (it has a lower bound given by the value)
	 * returned by second search.  However, this method is likely a bit slower than the
	 * one above (when it can be made to work correctly at all times).
	 */
        template <typename IteratorT>
        std::tuple<OffsetT, OffsetT, OffsetT> extendSearchNaive(
                OffsetT lbIn, // The lower bound for the search
                OffsetT ubIn, // The upper bound for the search
                OffsetT startAt, // The offset at which to start looking
                IteratorT qb, // Iterator to the beginning of the query
                IteratorT qe, // Iterator to the end of the query
                bool complementBases=false // True if bases should be complemented
                                           // before comparison
                ) {

            std::vector<OffsetT>& SA = *sa_;
            std::string& seq = *seq_;

            int64_t m = std::distance(qb, qe);
            int64_t n = static_cast<int64_t>(seq.length());

            auto sb = seq.begin();
            //auto se = seq.end();

            // If the bounds are already trivial, just figure how long
            // of a prefix we share and return the interval.
            if (ubIn - lbIn == 2) {
                lbIn += 1;
                auto i = startAt;
                while (i < m and SA[lbIn] + i < n) {
                    char queryChar = ::toupper(*(qb + i));
                    // If we're reverse complementing
                    if (complementBases) {
                        queryChar = combinelib::kmers::complement(queryChar);
                    }
                    if ( queryChar < *(sb + SA[lbIn] + i) ) {
                        break;
                    } else if ( queryChar > *(sb + SA[lbIn] + i)) {
                        break;
                    }
                    ++i;
                }
                return std::make_tuple(lbIn, ubIn, static_cast<OffsetT>(i));
            }

            BoundSearchResult<OffsetT> res1, res2;

            char smallest = '#';
            //char largest = '}';
            char sentinel = smallest;

            // FIX: these have to be large enough to hold the *sum* of the boundaries!
            int64_t l = lbIn, r = ubIn;
            int64_t lcpLP = startAt, lcpRP = startAt;
            int64_t c{0};
            int64_t i{0};

            int64_t maxI{startAt};
            //int64_t prevI = startAt;
            int64_t prevILow = startAt;
            int64_t prevIHigh = startAt;
            int64_t validBoundLow = ubIn;
            int64_t validBoundHigh = lbIn;
            //int64_t validBound = 0;
            bool plt{true};
            // Reduce the search interval until we hit a border
            // i.e. until c == r - 1 or c == l + 1
            while (true) {
                c = (l + r) / 2;
                plt = true;
                i = std::min(lcpLP, lcpRP);
                while (i < m and SA[c] + i < n) {
                    char queryChar = ::toupper(*(qb + i));
                    // If we're reverse complementing
                    if (complementBases) {
                        queryChar = combinelib::kmers::complement(queryChar);
                    }

                    if ( queryChar < *(sb + SA[c] + i) ) {
                        if (i > prevIHigh) {
                            prevIHigh = i;
                            validBoundHigh = c;
                        } else if (i == prevIHigh) {
                            validBoundHigh = c < validBoundHigh ? c : validBoundHigh;
                        }

                        break;
                    } else if ( queryChar > *(sb + SA[c] + i)) {
                        if (i > prevILow) {
                            prevILow = i;
                            validBoundLow = c;
                        } else if (i == prevILow) {
                            validBoundLow = c > validBoundLow ? c : validBoundLow;
                        }
                        plt = false;
                        break;
                    }

                    ++i;
                }
                if (i == m or SA[c] + i == n) {
                    if (i > prevIHigh) {
                        prevIHigh = i;
                        validBoundHigh = c;
                    } else if (i == prevIHigh) {
                        validBoundHigh = c < validBoundHigh ? c : validBoundHigh;
                    }
                }

                if (plt) {
                    if (c == l + 1) {
                        auto maxI = std::max(std::max(i, prevILow), prevIHigh);
                        res1.maxLen = maxI;
                        break;
                    }
                    r = c;
                    lcpRP = i;
                } else {
                    if (c == r - 1) {
                        maxI = std::max(std::max(i, prevILow), prevIHigh);
                        res1.maxLen = maxI;
                        break;
                    }
                    l = c;
                    lcpLP = i;
                }
            }

            //bool knownValid{true};
            m = res1.maxLen + 1;

            // first search for the lower bound
            sentinel = '#';
            l = lbIn;
            r = ubIn;

            lcpLP = startAt;
            lcpRP = startAt;
            c = 0;
            plt = true;
            i = startAt;
            while (true) {
                c = (l + r) / 2;
                plt = true;
                i = std::min(lcpLP, lcpRP);
                while (i < m and SA[c] + i < n) {
                    char queryChar = (i < m - 1) ? ::toupper(*(qb + i)) : sentinel;
                    // If we're reverse complementing
                    if (queryChar != sentinel and complementBases) {
                        queryChar = combinelib::kmers::complement(queryChar);
                    }

                    if ( queryChar < *(sb + SA[c] + i) ) {
                     	break;
                    } else if ( queryChar > *(sb + SA[c] + i)) {
                        plt = false;
                        break;
                    }
                    ++i;
                }
                if (plt) {
                    if (c == l + 1) {
                        res1.bound = c;
                        break;
                    }
                    r = c;
                    lcpRP = i;
                } else {
                    if (c == r - 1) {
                        res1.bound = r;
                        break;
                    }
                    l = c;
                    lcpLP = i;
                }
            }

            // then search for the upper bound
            sentinel = '{';
            l = res1.bound - 1;
            r = ubIn;

            lcpLP = startAt;
            lcpRP = startAt;
            c = 0;
            plt = true;
            i = startAt;
            while (true) {
                c = (l + r) / 2;
                plt = true;
                i = std::min(lcpLP, lcpRP);
                while (i < m and SA[c] + i < n) {
                    char queryChar = (i < m - 1) ? ::toupper(*(qb + i)) : sentinel;
                    // If we're reverse complementing
                    if (queryChar != sentinel and complementBases) {
                        queryChar = combinelib::kmers::complement(queryChar);
                    }

                    if ( queryChar < *(sb + SA[c] + i) ) {
                     	break;
                    } else if ( queryChar > *(sb + SA[c] + i)) {
                        plt = false;
                        break;
                    }
                    ++i;
                }
                if (plt) {
                    if (c == l + 1) {
                        res2.bound = c;
                        break;
                    }
                    r = c;
                    lcpRP = i;
                } else {
                    if (c == r - 1) {
                        res2.bound = r;
                        break;
                    }
                    l = c;
                    lcpLP = i;
                }
            }

            // Must occur at least once!
            if (res1.bound == res2.bound) { res2.bound += 1; }
            return std::make_tuple(static_cast<OffsetT>(res1.bound), static_cast<OffsetT>(res2.bound), static_cast<OffsetT>(res1.maxLen));
        }


        /**
         * Compute the longest common extension between the suffixes
         * at T[SA[p1]] and T[SA[p2]].  Start the comparison at `startAt`
         * positions into the suffix, and only consider an extension
         * going to at most position `stopAt`.
         */
        OffsetT lce(OffsetT p1, OffsetT p2,
                    OffsetT startAt=0,
                    OffsetT stopAt=std::numeric_limits<OffsetT>::max(),
                    bool verbose=false) {
            std::string& seq = *seq_;
            std::vector<OffsetT>& SA = *sa_;
            OffsetT len = static_cast<OffsetT>(startAt);
            auto o1 = SA[p1] + startAt;
            auto o2 = SA[p2] + startAt;
            auto maxIndex = std::max(o1, o2);
            while (maxIndex + len < textLen_ and seq[o1+len] == seq[o2+len]) {
                if (seq[o1+len] == '$') { break; }
                if (len >= stopAt) { break; }
                ++len;
            }
            return len;
        }

    private:
        RapMapIndexT* rmi_;
        std::string* seq_;
        std::vector<OffsetT>* sa_;
        OffsetT textLen_;
};


        /*
        // http://www.cs.jhu.edu/~langmea/resources/lecture_notes/suffix_arrays.pdf
        std::tuple<int, int> querySimpleAccel(std::string::iterator qb,
                                              std::string::iterator qe) {
            std::vector<int>& SA = *sa_;
            std::string& seq = *seq_;
            //ForwardIt it;
            auto sb = seq.begin();
            auto se = seq.end();

            size_t n = seq.length();
            size_t m = std::distance(qb, qe);
            size_t l = 0, r = n;
            size_t lcpLP = 0, lcpRP = 0;
            size_t c{0};
            size_t i{0};
            bool plt{true};
            size_t lower{0};
            while (true) {
                c = (l + r) / 2;
                plt = true;
                i = std::min(lcpLP, lcpRP);
                while (i < m and SA[c] + i < n) {
                    if ( *(qb + i) < *(sb + SA[c] + i) ) {
                        break;
                    } else if ( *(qb + i) > *(sb + SA[c] + i)) {
                        plt = false;
                        break;
                    }
                    ++i;
                }
                if (plt) {
                    if (c == l + 1) { lower = c; break; }
                    r = c;
                    lcpRP = i;
                } else {
                    if (c == r - 1) { lower = r; break; }
                    l = c;
                    lcpLP = i;
                }
            }

            i = 0;
            l = 0;
            r = n;
            lcpLP = 0;
            lcpRP = 0;
            size_t upper{0};
            while (true) {
                c = (l + r) / 2;
                plt = true;
                i = std::min(lcpLP, lcpRP);
                while (i < m and SA[c] + i < n) {
                    if ( *(qb + i) < *(sb + SA[c] + i) ) {
                        break;
                    } else if ( *(qb + i) > *(sb + SA[c] + i)) {
                        plt = false;
                        break;
                    }
                    ++i;
                }
                if (plt) {
                    if (c == l + 1) { upper = c; break; }
                    r = c;
                    lcpRP = i;
                } else {
                    if (c == r - 1) { upper = r; break; }
                    l = c;
                    lcpLP = i;
                }
            }
            return std::make_tuple(lower, upper);
        }


        // http://www.cs.jhu.edu/~langmea/resources/lecture_notes/suffix_arrays.pdf
        // templated on the iterator type so we can use a forward or revers iterator
        template <typename IteratorT>
        std::tuple<int, int, int> extendSearch(
                int lbIn, // The lower bound for the search
                int ubIn, // The upper bound for the search
                int startAt, // The offset at which to start looking
                IteratorT qb, // Iterator to the beginning of the query
                IteratorT qe, // Iterator to the end of the query
                bool complementBases=false // True if bases should be complemented
                                           // before comparison
                ) {

            std::vector<int>& SA = *sa_;
            std::string& seq = *seq_;

            int m = std::distance(qb, qe);
            size_t n = seq.length();

            auto sb = seq.begin();
            auto se = seq.end();

            // If the bounds are already trivial, just figure how long
            // of a prefix we share and return the interval.
            if (ubIn - lbIn == 2) {
                lbIn += 1;
                auto i = startAt;
                while (i < m and SA[lbIn] + i < n) {
                    char queryChar = ::toupper(*(qb + i));
                    // If we're reverse complementing
                    if (complementBases) {
                        queryChar = combinelib::kmers::complement(queryChar);
                    }
                    if ( queryChar < *(sb + SA[lbIn] + i) ) {
                        break;
                    } else if ( queryChar > *(sb + SA[lbIn] + i)) {
                        break;
                    }
                    ++i;
                }
                return std::make_tuple(lbIn, ubIn, i);
            }

            BoundSearchResult res1, res2;

            char smallest = '#';
            char largest = '}';
            char sentinel = smallest;

            int l = lbIn, r = ubIn;
            int lcpLP = startAt, lcpRP = startAt;
            int c{0};
            int i{0};
            int maxI{startAt};
            int prevI = startAt;
            int prevILow = startAt;
            int prevIHigh = startAt;
            int validBoundLow = ubIn;
            int validBoundHigh = lbIn;
            int validBound = 0;
            bool plt{true};
            bool prevPLT{true};
            //std::cerr << "lbIn = " << lbIn << ", ubIn = " << ubIn << "\n";
            // Reduce the search interval until we hit a border
            // i.e. until c == r - 1 or c == l + 1
            while (true) {
                c = (l + r) / 2;
                //std::cerr << "l = " << l << ", r = " << r << ", c = " << c << '\n';
                plt = true;
                i = std::min(lcpLP, lcpRP);
                while (i < m and SA[c] + i < n) {
                    char queryChar = ::toupper(*(qb + i));
                    // If we're reverse complementing
                    if (complementBases) {
                        queryChar = combinelib::kmers::complement(queryChar);
                    }

                    if ( queryChar < *(sb + SA[c] + i) ) {
                        if (i > prevIHigh) {
                            prevIHigh = i;
                            validBoundHigh = c;
                        } else if (i == prevIHigh) {
                            validBoundHigh = c < validBoundHigh ? c : validBoundHigh;
                        }
                        //std::cerr << "(l = " << l << ", r = " << r << ") pattern < SA[" << c << "]\n";
                        //std::cerr << "(i = " << i << ", m = " << m << ") " << queryChar << " < " <<  *(sb + SA[c] + i) << "\n";

                        break;
                    } else if ( queryChar > *(sb + SA[c] + i)) {
                        if (i > prevILow) {
                            prevILow = i;
                            validBoundLow = c;
                        } else if (i == prevILow) {
                            validBoundLow = c > validBoundLow ? c : validBoundLow;
                        }
                        //std::cerr << "(l = " << l << ", r = " << r << ") pattern > SA[" << c << "]\n";
                        //std::cerr << "(i = " << i << ", m = " << m << ") " << queryChar << " > " <<  *(sb + SA[c] + i) << "\n";
                        plt = false;
                        break;
                    }

                    ++i;
		}
		if (i == m or SA[c] + i == n) {
			if (i > prevIHigh) {
				prevIHigh = i;
				validBoundHigh = c;
			} else if (i == prevIHigh) {
				validBoundHigh = c < validBoundHigh ? c : validBoundHigh;
			}
		}

                if (plt) {
                    if (c == l + 1) {
                        std::cerr << "path 1\n";
                        auto maxI = std::max(std::max(i, prevILow), prevIHigh);
                        res1.maxLen = maxI;
                        if (maxI == m) {
                            res1.dir = SearchDirection::DOWN;
                            res1.bound = c;
                        } else {
                            validBound = (prevILow >= prevIHigh) ? validBoundLow : validBoundHigh;
                            res1.bound = validBound;
                            res1.dir = (res1.bound == validBoundLow) ? SearchDirection::DOWN : SearchDirection::UP;
                        }
                        break;
                    }
                    r = c;
                    lcpRP = i;
                } else {
                    if (c == r - 1) {
                        std::cerr << "path 2\n";
                        maxI = std::max(std::max(i, prevILow), prevIHigh);
                        res1.maxLen = maxI;
                        validBound = (prevILow >= prevIHigh) ? validBoundLow : validBoundHigh;
                        if (maxI == m) {
                            res1.bound = r;
                        } else {
                            res1.bound = validBound;
                        }
                        res1.dir = (res1.bound == validBoundLow) ? SearchDirection::DOWN : SearchDirection::UP;
                        break;
                    }
                    l = c;
                    lcpLP = i;
                }
            }


            bool knownValid{true};
            m = res1.maxLen + 1;

            switch (res1.dir) {
                case SearchDirection::UP:
                    sentinel = '#';
                    r = res1.bound;
                    l = lbIn;
                    std::cerr << "direction was UP; lb = " << l << ", ub = " << r << "\n";
                    std::cerr << "direction was UP; origLb = " << lbIn << ", origUb = " << ubIn << "\n";
                    break;
                case SearchDirection::DOWN:
                    sentinel = '{';
                    r = ubIn;
                    l = res1.bound;
                    std::cerr << "direction was DOWN; lb = " << l << ", ub = " << r << "\n";
                    std::cerr << "direction was UP; origLb = " << lbIn << ", origUb = " << ubIn << "\n";
                    break;
            }

            if (r - l < 2) {
                if (r == l) { r += 1; }
                //std::cerr << "early exit!\n";
                return std::make_tuple(l, r, res1.maxLen);
            }


            lcpLP = startAt;
            lcpRP = startAt;
            c = 0;
            plt = true;
            prevPLT = true;
            prevI = 0;
            prevILow = 0;
            prevIHigh = 0;
            i = startAt;
            validBound = 0;
            validBoundLow = ubIn;
            validBoundHigh = lbIn;
            while (true) {
                c = (l + r) / 2;
                plt = true;
                i = std::min(lcpLP, lcpRP);
                while (i < m and SA[c] + i < n) {
                    char queryChar = (i < m - 1) ? ::toupper(*(qb + i)) : sentinel;
                    // If we're reverse complementing
                    if (queryChar != sentinel and complementBases) {
                        queryChar = combinelib::kmers::complement(queryChar);
                    }

                    if ( queryChar < *(sb + SA[c] + i) ) {
                     	break;
                    } else if ( queryChar > *(sb + SA[c] + i)) {
                        plt = false;
                        break;
                    }
                    ++i;
                }
                if (plt) {
                    if (c == l + 1) {
                        res2.dir = SearchDirection::DOWN;
                        res2.bound = c;
                        break;
                    }
                    r = c;
                    lcpRP = i;
                } else {
                    if (c == r - 1) {
                        res2.bound = r;
                        break;
                    }
                    l = c;
                    lcpLP = i;
                }
            }

            auto bound1 = std::min(res1.bound, res2.bound);
            auto bound2 = std::max(res1.bound, res2.bound);
            // Must occur at least once!
            if (bound1 == bound2) { bound2 += 1; }
            return std::make_tuple(bound1, bound2, res1.maxLen);
        }
        */

#endif //SA_SEARCHER_HPP