File: classifier_li.h

package info (click to toggle)
hisat2 2.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 13,756 kB
  • sloc: cpp: 86,309; python: 12,230; sh: 2,171; perl: 936; makefile: 375
file content (453 lines) | stat: -rw-r--r-- 13,979 bytes parent folder | download | duplicates (2)
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
/*
 * Copyright 2014, Daehwan Kim <infphilo@gmail.com>
 *
 * This file is part of HISAT.
 *
 * HISAT 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.
 *
 * HISAT 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 HISAT.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef CLASSIFIER_H_
#define CLASSIFIER_H_

#include "hi_aligner.h"

struct IDCount {
	uint32_t id;
	uint32_t count;
	uint32_t weightedCount;
	uint32_t timeStamp ;
};


/**
 * With a hierarchical indexing, SplicedAligner provides several alignment strategies
 * , which enable effective alignment of RNA-seq reads
 */
template <typename index_t, typename local_index_t>
class Classifier : public HI_Aligner<index_t, local_index_t> {
    
public:
	
	/**
	 * Initialize with index.
	 */
	Classifier(const Ebwt<index_t>& ebwt,
               const EList<string>& refnames) :
    HI_Aligner<index_t, local_index_t>(
                                       ebwt,
                                       0,    // don't make use of splice sites found by earlier reads
                                       true), // no spliced alignment
    _refnames(refnames)
    {
    }
    
    ~Classifier() {
    }
    
    /**
     * Aligns a read or a pair
     * This funcion is called per read or pair
     */
    virtual
    int go(
           const Scoring&           sc,
           const Ebwt<index_t>&     ebwtFw,
           const Ebwt<index_t>&     ebwtBw,
           const BitPairReference&  ref,
           SwAligner&               swa,
           SpliceSiteDB&            ssdb,
           WalkMetrics&             wlm,
           PerReadMetrics&          prm,
           SwMetrics&               swm,
           HIMetrics&               him,
           RandomSource&            rnd,
           AlnSinkWrap<index_t>&    sink)
    {
        _speciesMap.clear();
        _genusMap.clear();
        
        const index_t increment = 10;
        const index_t minPartialLen = 22;
	size_t bestScore = 0, secondBestScore = 0 ;
	for(index_t rdi = 0; rdi < (this->_paired ? 2 : 1); rdi++) {
		assert(this->_rds[rdi] != NULL);
		const Read& rd = *(this->_rds[rdi]);
		index_t rdlen = rd.length();
		index_t fwi;

		bool done[2] = {false, false};
		size_t cur[2] = {0, 0 } ;
		const size_t maxDiff = ( rdlen / 2 > 2 * minPartialLen ) ? rdlen / 2 : ( 2 * minPartialLen ) ;
		while(!done[0] || !done[1]) {
			for(fwi = 0; fwi < 2; fwi++) {
				if(done[fwi]) continue;
				size_t mineFw = 0, mineRc = 0;
				bool fw = (fwi == 0);
				ReadBWTHit<index_t>& hit = this->_hits[rdi][fwi];
				bool pseudogeneStop = false, anchorStop = false;
				this->partialSearch(
						ebwtFw,
						rd,
						sc,
						fw,
						0,
						mineFw,
						mineRc,
						hit,
						rnd,
						pseudogeneStop,
						anchorStop);
				if(hit.done()) {
					done[fwi] = true;
					cur[fwi] = rdlen ;
					continue;
				}
				cur[fwi] = hit.cur() ;

				BWTHit<index_t>& lastHit = hit.getPartialHit(hit.offsetSize() - 1);
				if(lastHit.len() > increment) {
					if ( lastHit.len() < minPartialLen )
						hit.setOffset(hit.cur() - increment);
					else
						hit.setOffset( hit.cur() + 1 ) ;
				}

				if(hit.cur() + minPartialLen >= rdlen) {
					hit.done(true);
					done[fwi] = true;
					continue;
				}
			}

			//ReadBWTHit<index_t>& lastHitForward = (this->_hits[rdi][0] ).getPartialHit(hit.offsetSize() - 1).cur() ;
			//ReadBWTHit<index_t>& lastHitBackward = (this->_hits[rdi][1] ).getPartialHit(hit.offsetSize() - 1).cur() ;
			//size_t curForward = this->_hits[rdi][0].cur()  ;
			//size_t curBackward = this->_hits[rdi][1].cur() ;
			//cout<< cur[0] << " " << cur[1] << " " << done[0] << " " << done[1] << endl ;

			if ( cur[0] > cur[1] + maxDiff )
			{
				this->_hits[rdi][1].done( true ) ;	
				done[1] = true ;
			}
			else if ( cur[1] > cur[0] + maxDiff )
			{
				this->_hits[rdi][0].done( true ) ;	
				done[0] = true ;
			}
		}

		// choose fw or rc of a read
		index_t avgHitLength[2] = {0, 0};
		index_t totalHitLength[2] = {0, 0};
		for(fwi = 0; fwi < 2; fwi++) {
			ReadBWTHit<index_t>& hit = this->_hits[rdi][fwi];
			index_t numHits = 0;
			for(size_t i = 0; i < hit.offsetSize(); i++) {
				if(hit.getPartialHit(i).len() < minPartialLen) continue;
				totalHitLength[fwi] += hit.getPartialHit(i).len();
				numHits++;
			}

			if(numHits > 0) {
				avgHitLength[fwi] = totalHitLength[fwi] / numHits;
			}
		}

		if(avgHitLength[0] > avgHitLength[1]) {
			fwi = 0;
		} else {
			fwi = 1;
		}

		bool fw = (fwi == 0);
		const ReportingParams& rp = sink.reportingParams();
		ReadBWTHit<index_t>& hit = this->_hits[rdi][fwi];
		assert(hit.done());
		// choose candidate partial alignments for further alignment
		const index_t maxGenomeHitSize = rp.khits;
		index_t offsetSize = hit.offsetSize();
		this->_genomeHits.clear();

		int hitLen[100] ;
		int hitSize[100] ;
		size_t hiMap[100] ;
		for ( size_t hi = 0 ; hi < offsetSize ; ++hi )
		{
			hitLen[hi] = hit.getPartialHit(hi).len() ;
			hitSize[hi] = hit.getPartialHit(hi).size() ;
			hiMap[hi] = hi ;
		}

		// Change to quicksort in future
		for ( size_t hi = 0 ; hi < offsetSize ; ++hi )
		{
			for ( size_t hj = hi + 1 ; hj < offsetSize ; ++hj )
			{
				//if ( hitLen[ hiMap[hi] ] < hitLen[ hiMap[hj] ] )
				if ( hitSize[ hiMap[hi] ] > hitSize[ hiMap[hj] ] ) // When use size()
				{
					size_t tmp = hiMap[hi] ;
					hiMap[hi] = hiMap[hj] ;
					hiMap[hj] = tmp ;
				}
				else if ( hitSize[ hiMap[hi] ] == hitSize[ hiMap[hj] ] && hitLen[ hiMap[hi] ] < hitLen[ hiMap[hj] ] )
				{
					size_t tmp = hiMap[hi] ;
					hiMap[hi] = hiMap[hj] ;
					hiMap[hj] = tmp ;
				}
			}
		}

		size_t usedPortion = 0 ;
		size_t genomeHitCnt = 0 ;
		for(size_t hi = 0; hi < offsetSize; hi++) {
			/*index_t hj = 0;
			  for(; hj < offsetSize; hj++) {
			  BWTHit<index_t>& partialHit_j = hit.getPartialHit(hj);
			  if(partialHit_j.empty() ||
			  partialHit_j.hasGenomeCoords() ||
			  partialHit_j.len() < minPartialLen) continue;
			  else break;
			  }
			  if(hj >= offsetSize) break;
			  for(index_t hk = hj + 1; hk < offsetSize; hk++) {
			  BWTHit<index_t>& partialHit_j = hit.getPartialHit(hj);
			  BWTHit<index_t>& partialHit_k = hit.getPartialHit(hk);
			  if(partialHit_k.empty() ||
			  partialHit_k.hasGenomeCoords() ||
			  partialHit_k.len() < minPartialLen) continue;

			  if(partialHit_j.size() > partialHit_k.size() ||
			  (partialHit_j.size() == partialHit_k.size() && partialHit_j.len() < partialHit_k.len())) {
			  hj = hk;
			  }
			  }*/
			BWTHit<index_t>& partialHit = hit.getPartialHit( hiMap[ hi ] );

			if ( partialHit.len() < minPartialLen )
				continue ;
				//break ;

			assert(!partialHit.hasGenomeCoords());
			usedPortion += partialHit.len() ;
			bool straddled = false;
			this->getGenomeIdx(
					ebwtFw,
					ref,
					rnd,
					partialHit._top,
					partialHit._bot,
					fw,
					maxGenomeHitSize - genomeHitCnt, // this->_genomeHits.size(),
					hit._len - partialHit._bwoff - partialHit._len,
					partialHit._len,
					partialHit._coords,
					wlm,
					prm,
					him,
					false, // reject straddled
					straddled);
			if(!partialHit.hasGenomeCoords()) continue;
			EList<Coord>& coords = partialHit._coords;
			assert_gt(coords.size(), 0);
			//const index_t genomeHit_size = this->_genomeHits.size();
			if(genomeHitCnt + coords.size() >= maxGenomeHitSize) {
				coords.shufflePortion(0, coords.size(), rnd);
			}
			for(index_t k = 0; k < coords.size(); k++, ++genomeHitCnt) {
				//cout << genomeHitCnt << " " << maxGenomeHitSize << endl ;
				if ( genomeHitCnt >= maxGenomeHitSize )
					break ;
				const Coord& coord = coords[k] ;

				assert_lt(coord.ref(), _refnames.size());
				const string& refName = _refnames[coord.ref()];
				uint64_t id = 0;
				for(size_t ni = 0; ni < refName.length(); ni++) {
					if(refName[ni] < '0' || refName[ni] > '9') break;
					id *= 10;
					id += (refName[ni] - '0');
				}

				uint32_t speciesID = (uint32_t)(id >> 32);
				uint32_t genusID = (uint32_t)(id & 0xffffffff);

				assert_gt(partialHit.len(), 15);
				uint32_t addWeight = (uint32_t)((partialHit.len() - 15) * (partialHit.len() - 15));

				bool found = false;
				uint32_t newScore = 0 ;
				for(size_t mi = 0; mi < _speciesMap.size(); mi++) {
					if(_speciesMap[mi].id == speciesID) {
						found = true;
						if ( _speciesMap[mi].timeStamp != hi )
						{
							_speciesMap[mi].count += 1;
							_speciesMap[mi].weightedCount += addWeight;
							_speciesMap[mi].timeStamp = hi;
							//newScore = _speciesMap[mi].weightedCount ;
						}
						break;
					}
				}

				if(!found) {
					_speciesMap.expand();
					_speciesMap.back().id = speciesID;
					_speciesMap.back().count = 1;
					_speciesMap.back().timeStamp = hi ;
					_speciesMap.back().weightedCount = addWeight;
					//newScore = addWeight ;
				}

				found = false;
				for(size_t mi = 0; mi < _genusMap.size(); mi++) {
					if(_genusMap[mi].id == genusID) {
						found = true;
						if(_genusMap[mi].timeStamp != hi ) {
							_genusMap[mi].count += 1;
							_genusMap[mi].weightedCount += addWeight;
							_genusMap[mi].timeStamp = hi ;
							newScore = _genusMap[mi].weightedCount ;
						}
						break;
					}
				}

				if(!found) {
					_genusMap.expand();
					_genusMap.back().id = genusID;
					_genusMap.back().count = 1;
					_genusMap.back().weightedCount = addWeight;
					_genusMap.back().timeStamp = hi ;
					newScore = addWeight ;
				}

				// classification of bacterial sequences
#ifndef NDEBUG
				cout << this->_rds[rdi]->name << "\t"
					// << refName << "\t"
					<< speciesID << "\t"
					<< genusID << "\t"
					<< genomeHit.refoff() << "\t"
					<< genomeHit.len() << "M" << endl;
#endif
				if ( newScore > bestScore )
				{
					secondBestScore = bestScore ; 
					bestScore = newScore ;
				}
				else if ( newScore > secondBestScore )
				{
					secondBestScore = newScore ;
				}

			} // for k
			if ( genomeHitCnt >= maxGenomeHitSize )
				break ;

			//cout<< bestScore << " " << secondBestScore << " " << totalHitLength[fwi] << " " << usedPortion << endl ;
			if ( rdi == (this->_paired ? 2: 1) - 1 && bestScore > secondBestScore + 
					( totalHitLength[fwi] - usedPortion - 15 ) * ( totalHitLength[fwi] - usedPortion - 15 ) )
			{
				//cout << "saved\n" ;
				break ;
			}
		} // for hi
	} // for rdi 
        
        uint32_t speciesID = 0xffffffff, genusID = 0xffffffff;
        uint32_t speciesWeightedCount = 0, genusWeightedCount = 0;
        
        for(size_t mi = 0; mi < _speciesMap.size(); mi++) {
            if(_speciesMap[mi].weightedCount > speciesWeightedCount) {
                speciesID = _speciesMap[mi].id;
                speciesWeightedCount = _speciesMap[mi].weightedCount;
            }
        }
        
        for(size_t mi = 0; mi < _genusMap.size(); mi++) {
            if(_genusMap[mi].weightedCount > genusWeightedCount) {
                genusID = _genusMap[mi].id;
                genusWeightedCount = _genusMap[mi].weightedCount;
            }
        }
        
        if(genusID != 0xffffffff) {
            cout << this->_rds[0]->name << "\t"
            << speciesID << "\t"
            << genusID << endl;
        }
        
        return EXTEND_POLICY_FULFILLED;
    }
    
    bool getGenomeIdx(
                      const Ebwt<index_t>&       ebwt,
                      const BitPairReference&    ref,
                      RandomSource&              rnd,
                      index_t                    top,
                      index_t                    bot,
                      bool                       fw,
                      index_t                    maxelt,
                      index_t                    rdoff,
                      index_t                    rdlen,
                      EList<Coord>&              coords,
                      WalkMetrics&               met,
                      PerReadMetrics&            prm,
                      HIMetrics&                 him,
                      bool                       rejectStraddle,
                      bool&                      straddled)
    {
        straddled = false;
        assert_gt(bot, top);
        index_t nelt = bot - top;
        nelt = min<index_t>(nelt, maxelt);
        coords.clear();
        him.globalgenomecoords += (bot - top);
        this->_offs.resize(nelt);
        this->_offs.fill(std::numeric_limits<index_t>::max());
        this->_sas.init(top, rdlen, EListSlice<index_t, 16>(this->_offs, 0, nelt));
        this->_gws.init(ebwt, ref, this->_sas, rnd, met);
        for(index_t off = 0; off < nelt; off++) {
            WalkResult<index_t> wr;
            this->_gws.advanceElement(
                                off,
                                ebwt,         // forward Bowtie index for walking left
                                ref,          // bitpair-encoded reference
                                this->_sas,   // SA range with offsets
                                this->_gwstate,     // GroupWalk state; scratch space
                                wr,           // put the result here
                                met,          // metrics
                                prm);         // per-read metrics
            // Coordinate of the seed hit w/r/t the pasted reference string
            coords.expand();
            coords.back().init(wr.toff, 0, fw);
        }
        
        return true;
    }
 
private:
        
    EList<string>   _refnames;
    EList<IDCount>  _speciesMap;
    EList<IDCount>  _genusMap;
};



#endif /*CLASSIFIER_H_*/