File: aligner_result.h

package info (click to toggle)
centrifuge 1.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 11,864 kB
  • sloc: cpp: 51,936; perl: 1,919; python: 1,538; makefile: 618; sh: 352
file content (469 lines) | stat: -rw-r--r-- 11,642 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
/*
 * Copyright 2011, Ben Langmead <langmea@cs.jhu.edu>
 *
 * This file is part of Bowtie 2.
 *
 * Bowtie 2 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.
 *
 * Bowtie 2 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 Bowtie 2.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef ALIGNER_RESULT_H_
#define ALIGNER_RESULT_H_

#include <utility>
#include <limits>
#include <vector>
#include "mem_ids.h"
#include "ref_coord.h"
#include "read.h"
#include "filebuf.h"
#include "ds.h"
#include "edit.h"
#include "limit.h"

typedef int64_t TAlScore;

#define VALID_AL_SCORE(x)   ((x).score_ > MIN_I64)
#define VALID_SCORE(x)      ((x) > MIN_I64)
#define INVALIDATE_SCORE(x) ((x) = MIN_I64)

/**
 * A generic score object for an alignment.  Used for accounting during
 * SW and elsewhere.  Encapsulates the score, the number of N positions
 * and the number gaps in the alignment.
 *
 * The scale for 'score' is such that a perfect alignment score is 0
 * and a score with non-zero penalty is less than 0.  So differences
 * between scores work as expected, but interpreting an individual
 * score (larger is better) as a penalty (smaller is better) requires
 * taking the absolute value.
 */
class AlnScore {

public:

	/**
	 * Gapped scores are invalid until proven valid.
	 */
	inline AlnScore() {
		reset();
		invalidate();
		assert(!valid());
	}

	/**
	 * Gapped scores are invalid until proven valid.
	 */
	inline AlnScore(TAlScore score) {
		score_ = score;
	}
	
	/**
	 * Reset the score.
	 */
	void reset() {
		score_ = 0;
	}

	/**
	 * Return an invalid SwScore.
	 */
	inline static AlnScore INVALID() {
		AlnScore s;
		s.invalidate();
		assert(!s.valid());
		return s;
	}
	
	/**
	 * Return true iff this score has a valid value.
	 */
	inline bool valid() const {
		return score_ != MIN_I64;
	}

	/**
	 * Make this score invalid (and therefore <= all other scores).
	 */
	inline void invalidate() {
		score_ = MIN_I64;
		assert(!valid());
	}
	

	/**
	 * Scores are equal iff they're bitwise equal.
	 */
	inline bool operator==(const AlnScore& o) const {
		// Profiling shows cache misses on following line
		return VALID_AL_SCORE(*this) && VALID_AL_SCORE(o) && score_ == o.score_;
	}

	/**
	 * Return true iff the two scores are unequal.
	 */
	inline bool operator!=(const AlnScore& o) const {
		return !(*this == o);
	}

	/**
	 * Return true iff this score is >= score o.
	 */
	inline bool operator>=(const AlnScore& o) const {
		if(!VALID_AL_SCORE(o)) {
			if(!VALID_AL_SCORE(*this)) {
				// both invalid
				return false;
			} else {
				// I'm valid, other is invalid
				return true;
			}
		} else if(!VALID_AL_SCORE(*this)) {
			// I'm invalid, other is valid
			return false;
		}
		return score_ >= o.score_;
	}

	/**
	 * Return true iff this score is < score o.
	 */
	inline bool operator<(const AlnScore& o) const {
		return !operator>=(o);
	}

	/**
	 * Return true iff this score is <= score o.
	 */
	inline bool operator<=(const AlnScore& o) const {
		return operator<(o) || operator==(o);
	}
    
    /**
     * Return true iff this score is < score o.
     */
    inline bool operator>(const AlnScore& o) const {
        return !operator<=(o);
    }

	TAlScore score()   const { return  score_; }

    // Score accumulated so far (penalties are subtracted starting at 0)
	TAlScore score_;
};

static inline ostream& operator<<(ostream& os, const AlnScore& o) {
	os << o.score();
	return os;
}

// Forward declaration
class BitPairReference;


/**
 * Encapsulates an alignment result.  The result comprises:
 *
 * 1. All the nucleotide edits for both mates ('ned').
 * 2. All "edits" where an ambiguous reference char is resolved to an
 *    unambiguous char ('aed').
 * 3. The score for the alginment, including summary information about the
 *    number of gaps and Ns involved.
 * 4. The reference id, strand, and 0-based offset of the leftmost character
 *    involved in the alignment.
 * 5. Information about trimming prior to alignment and whether it was hard or
 *    soft.
 * 6. Information about trimming during alignment and whether it was hard or
 *    soft.  Local-alignment trimming is usually soft when aligning nucleotide
 *    reads.
 *
 * Note that the AlnRes, together with the Read and an AlnSetSumm (*and* the
 * opposite mate's AlnRes and Read in the case of a paired-end alignment),
 * should contain enough information to print an entire alignment record.
 *
 * TRIMMING
 *
 * Accounting for trimming is tricky.  Trimming affects:
 *
 * 1. The values of the trim* and pretrim* fields.
 * 2. The offsets of the Edits in the EList<Edit>s.
 * 3. The read extent, if the trimming is soft.
 * 4. The read extent and the read sequence and length, if trimming is hard.
 *
 * Handling 1. is not too difficult.  2., 3., and 4. are handled in setShape().
 */
class AlnRes {

public:

	AlnRes()
	{
		reset();
	}
    
    AlnRes(const AlnRes& other)
    {
        score_ = other.score_;
        max_score_ = other.max_score_;
        uid_ = other.uid_;
        tid_ = other.tid_;
        taxRank_ = other.taxRank_;
        summedHitLen_ = other.summedHitLen_;
		readPositions_ = other.readPositions_;
		isFw_ = other.isFw_;
    }
    
    AlnRes& operator=(const AlnRes& other) {
        if(this == &other) return *this;
        score_ = other.score_;
        max_score_ = other.max_score_;
        uid_ = other.uid_;
        tid_ = other.tid_;
        taxRank_ = other.taxRank_;
        summedHitLen_ = other.summedHitLen_;
		readPositions_ = other.readPositions_;
		isFw_ = other.isFw_;
        return *this;
    }
    
    ~AlnRes() {}

	/**
	 * Clear all contents.
	 */
	void reset() {
        score_ = 0;
        max_score_ = 0;
        uid_ = "";
        tid_ = 0;
        taxRank_ = RANK_UNKNOWN;
        summedHitLen_ = 0.0;
		readPositions_.clear();
    }
    
	/**
	 * Set alignment score for this alignment.
	 */
	void setScore(TAlScore score) {
		score_ = score;
	}

	TAlScore           score()          const { return score_;     }
    TAlScore           max_score()      const { return max_score_; }
    string             uid()            const { return uid_;   }
    uint64_t           taxID()          const { return tid_;   }
    uint8_t            taxRank()        const { return taxRank_; }
    double             summedHitLen()   const { return summedHitLen_; }

	const EList<pair<uint32_t,uint32_t> >& readPositionsPtr() const { return readPositions_; }

	const pair<uint32_t,uint32_t> readPositions(size_t i) const { return readPositions_[i]; }
	size_t nReadPositions() const { return readPositions_.size(); }

	bool               isFw()           const { return isFw_;      }
    
   /**
	 * Print the sequence for the read that aligned using A, C, G and
	 * T.  This will simply print the read sequence (or its reverse
	 * complement).
	 */
 	void printSeq(
		const Read& rd,
		const BTDnaString* dns,
		BTString& o) const
    {
        assert(!rd.patFw.empty());
        ASSERT_ONLY(size_t written = 0);
        // Print decoded nucleotides
        assert(dns != NULL);
        size_t len = dns->length();
        size_t st = 0;
        size_t en = len;
        for(size_t i = st; i < en; i++) {
            int c = dns->get(i);
            assert_range(0, 3, c);
            o.append("ACGT"[c]);
            ASSERT_ONLY(written++);
        }
    }

	/**
	 * Print the quality string for the read that aligned.  This will
	 * simply print the read qualities (or their reverse).
	 */
 	void printQuals(
		const Read& rd,
		const BTString* dqs,
		BTString& o) const
    {
        assert(dqs != NULL);
        size_t len = dqs->length();
        // Print decoded qualities from upstream to downstream Watson
        for(size_t i = 1; i < len-1; i++) {
            o.append(dqs->get(i));
        }
    }
	

	/**
	 * Initialize new AlnRes.
	 */
	void init(
              TAlScore score,           // alignment score
              TAlScore max_score,
              const string& uniqueID,
              uint64_t taxID,
              uint8_t taxRank,
			  double summedHitLen,
			  const EList<pair<uint32_t, uint32_t> >& readPositions,
			  bool isFw)
    {
        score_  = score;
        max_score_ = max_score;
        uid_ = uniqueID;
        tid_ = taxID;
        taxRank_ = taxRank;
        summedHitLen_ = summedHitLen;
		readPositions_ = readPositions;
		isFw_ = isFw;
    }

protected:
	TAlScore     score_;        //
    TAlScore     max_score_;
    string       uid_;
    uint64_t     tid_;
    uint8_t      taxRank_;
    double       summedHitLen_; // sum of the length of all partial hits, divided by the number of genome matches
	bool         isFw_;
  
	EList<pair<uint32_t, uint32_t> > readPositions_;
};

typedef uint64_t TNumAlns;

/**
 * Encapsulates a concise summary of a set of alignment results for a
 * given pair or mate.  Referring to the fields of this object should
 * provide enough information to print output records for the read.
 */
class AlnSetSumm {

public:

	AlnSetSumm() { reset(); }

	/**
	 * Given an unpaired read (in either rd1 or rd2) or a read pair
	 * (mate 1 in rd1, mate 2 in rd2).
	 */
	explicit AlnSetSumm(
		const Read* rd1,
		const Read* rd2,
		const EList<AlnRes>* rs)
	{
		init(rd1, rd2, rs);
	}

	explicit AlnSetSumm(
		AlnScore best,
		AlnScore secbest)
	{
		init(best, secbest);
	}
	
	/**
	 * Set to uninitialized state.
	 */
	void reset() {
		best_.invalidate();
		secbest_.invalidate();
	}
	
    /**
     * Given all the paired and unpaired results involving mates #1 and #2,
     * calculate best and second-best scores for both mates.  These are
     * used for future MAPQ calculations.
     */
	void init(
		const Read* rd1,
		const Read* rd2,
		const EList<AlnRes>* rs)
    {
        assert(rd1 != NULL || rd2 != NULL);
        assert(rs != NULL);
        AlnScore best, secbest;
        size_t szs = 0;
        best.invalidate();    secbest.invalidate();
        szs = rs->size();
        //assert_gt(szs[j], 0);
        for(size_t i = 0; i < rs->size(); i++) {
            AlnScore sc = (*rs)[i].score();
            if(sc > best) {
                secbest = best;
                best = sc;
                assert(VALID_AL_SCORE(best));
            } else if(sc > secbest) {
                secbest = sc;
                assert(VALID_AL_SCORE(best));
                assert(VALID_AL_SCORE(secbest));
            }
        }
        if(szs > 0) {
            init(best, secbest);
        } else {
            reset();
        }
    }

	
	/**
	 * Initialize given fields.  See constructor for how fields are set.
	 */
	void init(
		AlnScore best,
		AlnScore secbest)
	{
		best_         = best;
		secbest_      = secbest;
		assert(repOk());
	}
	
	/**
	 * Return true iff there is at least a best alignment
	 */
	bool empty() const {
		assert(repOk());
		return !VALID_AL_SCORE(best_);
	}
	
#ifndef NDEBUG
	/**
	 * Check that the summary is internally consistent.
	 */
	bool repOk() const {
		return true;
	}
#endif
	
	AlnScore best()         const { return best_;         }
	AlnScore secbest()      const { return secbest_;      }


protected:
	
	AlnScore best_;         // best full-alignment score found for this read
	AlnScore secbest_;      // second-best
};

#endif