-
Notifications
You must be signed in to change notification settings - Fork 8
/
DV-DPfunctions.h
1785 lines (1521 loc) · 54 KB
/
DV-DPfunctions.h
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
/*
*
* DV-DPfunctions.h
* Soap3(gpu)
*
* Copyright (C) 2011, HKU
*
* This program 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 2
* of the License, or (at your option) any later version.
*
* This program 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 this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _DP_FUNCTIONS_H
#define _DP_FUNCTIONS_H
#include "AlgnResult.h"
#include "alignment.h"
#include <cuda.h>
#include <sys/time.h>
#include <pthread.h>
#include <semaphore.h>
#include <string>
#include <stack>
#include <map>
#include <vector>
using namespace std;
#define DP_THREADS_PER_BLOCK 128
typedef unsigned char uchar;
typedef unsigned int uint;
typedef unsigned long long uint64;
//////////////////////////////////////////////////////////////////////////////////////
// Functions for the DP module //
//////////////////////////////////////////////////////////////////////////////////////
#define MC_MemberCopy(type,prefix,x) type x = prefix x
#define MC_MemberCopy2(type,prefix,x,y) MC_MemberCopy(type,prefix,x); MC_MemberCopy(type,prefix,y)
#define MC_MemberCopy3(type,prefix,x,y,z) MC_MemberCopy2(type,prefix,x,y); MC_MemberCopy(type,prefix,z)
#define MC_MemberCopy4(type,prefix,x,y,z,u) MC_MemberCopy3(type,prefix,x,y,z); MC_MemberCopy(type,prefix,u)
#define MC_MemberCopy5(type,prefix,x,y,z,u,v) MC_MemberCopy4(type,prefix,x,y,z,u); MC_MemberCopy(type,prefix,v)
#define MC_Max(x,y) (x > y ? x : y)
#define MC_CeilDivide8(x) ((x+7)>>3)
#define MC_CeilDivide16(x) ((x+15)>>4)
#define MCInner_RadixSort_32_16_OneRound(arr, item, auxArr, length, shift) { \
memset(count, 0, 65536 * sizeof(uint)); \
for(uint i = 0; i < length; i++) \
++count[(arr[i].item >> shift) & MASK]; \
position[0] = 0; \
for(uint i = 1; i < 65536; i++) \
position[i] = position[i-1] + count[i-1]; \
for(uint i = 0; i < length; i++) \
auxArr[position[(arr[i].item >> shift) & MASK]++] = arr[i]; \
}
#define MC_RadixSort_32_16(arr, item, auxArr, length) { \
uint count[65536]; \
uint position[65536]; \
uint MASK = 0xFFFF; \
MCInner_RadixSort_32_16_OneRound(arr, item, auxArr, length, 0) \
MCInner_RadixSort_32_16_OneRound(auxArr, item, arr, length, 16) \
}
#define MCInner_RadixSort_8_8_OneRound(arr, item, auxArr, length, shift) { \
memset(count, 0, 256 * sizeof(char)); \
for(uint i = 0; i < length; i++) \
++count[(arr[i].item >> shift) & MASK]; \
position[0] = 0; \
for(uint i = 1; i < 256; i++) \
position[i] = position[i-1] + count[i-1]; \
for(uint i = 0; i < length; i++) \
auxArr[position[(arr[i].item >> shift) & MASK]++] = arr[i]; \
}
#define MC_RadixSort_8_8(arr, item, auxArr, length) { \
unsigned char count[256]; \
unsigned char position[256]; \
unsigned char MASK = 0xFF; \
MCInner_RadixSort_8_8_OneRound(arr, item, auxArr, length, 0) \
}
static void * addr;
#define MC_CheckMalloc(var,type,size) \
addr = malloc((size) * sizeof(type)); \
if (addr == NULL) { \
fprintf(stderr, "[DPfunc] error: main memory allocation failed\n"); \
exit(-1); \
} \
var = (type *) addr; \
#define showGPUMemInfo(x) { \
size_t avail, total; \
cudaMemGetInfo(&avail, &total); \
printf("[%s] GPU memory: avail = %llu, total = %llu\n", x, (uint64)avail, (uint64)total); \
}
static cudaError_t gpuErr;
#define DP_HANDLE_ERROR(x) \
gpuErr = x; \
if (gpuErr!=cudaSuccess) { \
fprintf(stderr, "[CUDA ERROR] %s(%d)\n",cudaGetErrorString(gpuErr),gpuErr); \
exit(1); \
}
class SemiGlobalAligner
{
int n_conf, blockConf[16];
double coefConf[16];
int batchSize, maxReadLength, maxDNALength, maxDPTableLength;
DPParameters dpPara;
int alignmentScheme;
void * _DPTable;
uint * _packedDNASequence, *_DNALengths;
uint * _packedReadSequence, *_readLengths;
uint * _startLocs, *_startOffsets, *_hitLocs;
int * _scores, *_cutoffThresholds;
uint * _clipLtSizes, *_clipRtSizes;
uint * _anchorLeftLocs, *_anchorRightLocs;
uchar * _pattern;
uint * _maxScoreCounts;
uint estimateThreadSize ( int maxReadLength, int maxDNALength );
int tryAlloc ( size_t estimatedThreadSize, size_t numOfBlocks );
public:
SemiGlobalAligner ();
void decideConfiguration (
int maxReadLength, int maxDNALength,
int & maxDPTableLength, int & numOfBlocks,
int & patternLength, DPParameters & dpPara
);
void init (
int batchSize,
int maxReadLength, int maxDNALength, int maxDPTableLength,
DPParameters & dpPara
);
void performAlignment (
uint * packedDNASequence, uint * DNALengths,
uint * packedReadSequence, uint * readLengths,
int * cutoffThresholds, int * scores, uint * hitLocs,
uint * maxScoreCounts,
uchar * pattern, int numOfThreads,
uint * clipLtSizes = NULL, uint * clipRtSizes = NULL,
uint * anchorLeftLocs = NULL, uint * anchorRightLocs = NULL
);
void freeMemory ();
};
//////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////// For seeding ///////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
template <class T>
class SOAP3Wrapper
{
Soap3Index * index;
uint * _bwt, *_occ, *_lookupTable;
uint * _revBwt, *_revOcc, *_revLookupTable;
int indexInside;
public:
SOAP3Wrapper ( Soap3Index * index,
uint * _bwt, uint * _revBwt,
uint * _occ, uint * _revOcc,
int indexInside = 1 )
{
MC_MemberCopy ( this->, , index );
MC_MemberCopy4 ( this->, , _bwt, _revBwt, _occ, _revOcc );
this->indexInside = indexInside;
}
~SOAP3Wrapper ()
{
freeIndex ();
}
void copyIndex ()
{
if ( !indexInside )
{
GPUINDEXUpload ( index, &_bwt, &_occ,
&_revBwt, &_revOcc );
indexInside = 1;
}
}
void freeIndex ()
{
if ( indexInside )
{
cudaFree ( _bwt );
cudaFree ( _occ );
cudaFree ( _revBwt );
cudaFree ( _revOcc );
indexInside = 0;
}
}
void seeding ( uint * seeds, uint * lengths,
int maxSeedLength, int wordPerSeed, int batchSize,
int numQueries, uint64 & numOfAnswer, uint & numOfAlignedRead,
int numOfCPUForSeeding,
SingleAlgnResultArray * algnResultArray, int maxHitNum )
{
if ( !indexInside ) { copyIndex (); }
single_1_mismatch_alignment2 ( seeds, lengths,
maxSeedLength, wordPerSeed, batchSize,
numQueries,
index,
_bwt, _revBwt,
_occ, _revOcc,
numOfAnswer,
numOfAlignedRead, numOfCPUForSeeding,
algnResultArray, maxHitNum );
}
};
//////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////// For output ////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
template <class ResultType>
int ScoreCompare ( ResultType & a, ResultType & b );
template <class ResultType>
bool ResultCompare ( const ResultType & a, const ResultType & b );
template <class ResultType>
int isValid ( ResultType & a )
{
return 1;
}
template <class ResultType>
struct OutputBuffer
{
vector<ResultType> rawBuffer;
ResultType * elements;
int capacity;
int size;
int alignmentType;
OutputBuffer ()
{
// srand(time(NULL));
capacity = 128;
elements = ( ResultType * ) malloc ( capacity * sizeof ( ResultType ) );
clear ();
}
~OutputBuffer ()
{
free ( elements );
}
void clear ()
{
rawBuffer.clear ();
size = 0;
}
void setAlignmentType ( int alignmentType )
{
this->alignmentType = alignmentType;
}
void add ( ResultType & result )
{
rawBuffer.push_back ( result );
}
inline void filterBest ()
{
if ( size == 0 ) { return; }
ResultType maxElement = elements[0];
int arrSize = 1;
for ( int i = 1; i < size; i++ )
{
int retval = ScoreCompare ( elements[i], maxElement );
if ( retval > 0 )
{
maxElement = elements[i];
arrSize = 0;
}
else if ( retval < 0 )
{
continue;
}
elements[arrSize++] = elements[i];
}
size = arrSize;
}
inline void filterInvalid ()
{
int arrSize = 0;
for ( int i = 0; i < size; i++ )
{
if ( isValid ( elements[i] ) )
{
elements[arrSize++] = elements[i];
}
}
size = arrSize;
}
inline void arrayCopy ()
{
size = rawBuffer.size ();
if ( size > 0 )
{
if ( size >= capacity )
{
free ( elements );
capacity = size * 2;
elements = ( ResultType * ) malloc ( capacity * sizeof ( ResultType ) );
}
copy ( rawBuffer.begin (), rawBuffer.end (), elements );
}
}
inline void arrayCopyNRemoveDuplicate ()
{
size = rawBuffer.size ();
if ( size > 0 )
{
if ( size >= capacity )
{
free ( elements );
capacity = size * 2;
elements = ( ResultType * ) malloc ( capacity * sizeof ( ResultType ) );
}
int arrPointer = 0;
sort ( rawBuffer.begin (), rawBuffer.end (), ResultCompare<ResultType> );
elements[arrPointer] = rawBuffer[0];
for ( uint i = 1; i < rawBuffer.size (); i++ )
{
if ( ResultCompare ( elements[arrPointer], rawBuffer[i] ) )
{
elements[++arrPointer] = rawBuffer[i];
}
}
size = arrPointer + 1;
}
}
void ready ( int optionFlag = 0 )
{
// alignmentType : 1 -- all valid
// 2 -- all best
// 3 -- unique best
// 4 -- random best
//-----------------------------------
// alignmentType == 1 --> do nothing
#define DO_NOT_OUTPUT_HALF_ALIGNED 1
#define OUTPUT_AS_INPUT_ORDER 2
if ( optionFlag & OUTPUT_AS_INPUT_ORDER )
{ arrayCopy (); }
else
{ arrayCopyNRemoveDuplicate (); }
if ( size == 0 ) { return; }
if ( alignmentType == 1 )
{
if ( optionFlag & DO_NOT_OUTPUT_HALF_ALIGNED )
{
filterInvalid ();
}
}
else
{
/* alignmentType > 1 */
filterBest ();
if ( alignmentType == 2 )
{
// do nothing
}
else if ( alignmentType == 3 )
{
if ( size != 1 )
{ size = 0; }
}
else if ( alignmentType == 4 )
{
// elements[0] = elements[rand() % size];
size = 1;
}
}
}
};
struct AlgnmtFlags
{
uint MASK[32];
uint size;
uint * flags;
pthread_mutex_t occupy_mutex;
AlgnmtFlags ( uint range = 16777216 );
void clear ();
inline void increaseSize ( uint newSize );
inline void reserveSize ( AlgnmtFlags * algnFlags );
// set(int readID) uses mutex and is thread-safe
void set ( int readID );
void get ( vector<int> * diff );
void getXOR ( AlgnmtFlags * algnFlags, vector<int> * diff );
void XOR ( AlgnmtFlags * algnFlags );
void AND ( AlgnmtFlags * algnFlags );
~AlgnmtFlags ();
};
//////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////// Utility class declaration//////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////// class TimeRecorder ///////////////////////////////////
template <class T>
class TimeRecorder
{
private:
double referenceTime;
struct TimeLine
{
int state;
int length;
cudaEvent_t start, stop;
TimeLine ();
vector<double> startTime;
vector<double> endTime;
};
map<string, TimeLine> recorder;
private:
double setStartTime ();
double getElapsedTime ( double startTime );
public:
TimeRecorder ();
void reset ();
void appendStart ( string label = "default", string type = "CPU" );
void appendEnd ( string label = "default", string type = "CPU" );
double getTotalTime ( string label = "default" );
void printTimeLine ( string label = "default", FILE * output = stdout );
};
////////////////////////////////// class MultiThreadDelegator ////////////////////////////////
template <class T>
void * MultiThreadDelegator_call_func ( void * classRef );
template <class ArgType>
class MultiThreadDelegator
{
private:
typedef stack<int> ThreadPool;
int numOfThreads;
ArgType * argList;
pthread_t * threadHandles;
sem_t * threadSems;
ThreadPool * threadPool;
int * threadFlags;
sem_t availableSem, finishSem;
pthread_mutex_t occupy_mutex, finish_mutex;
int createThreadCnt;
int finishFlag;
void ( *funcWrapper ) ( int, ArgType & );
void ( *threadInit ) ( void );
void ( *threadFinalize ) ( void );
private:
void clear ();
int allocThread ();
void releaseThread ( int threadId );
int checkFinish ( int threadId );
protected:
void thread_run_func ();
template <class T>
friend void * MultiThreadDelegator_call_func ( void * classRef );
public:
MultiThreadDelegator ();
~MultiThreadDelegator ();
void init ( int numOfThreads, void ( *threadRunFunc ) ( int, ArgType & ),
void ( *threadInitFunc ) ( void ) = NULL, void ( *threadFinalizeFunc ) ( void ) = NULL );
int schedule ( ArgType & arg );
void finalize ();
};
////////////////////////////////// struct MyCigarStringEncoder ////////////////////////////////
template <class T>
struct CigarStringEncoder
{
char cigarType[4096];
int cigarCnt[4096];
char lastType;
int lastCnt;
int cIndex;
//Encoded results
char * cigarString;
int charCount[128], gapPenalty;
CigarStringEncoder ();
void append ( char type, int cnt );
void encodeCigarString ( int GapOpenScore, int GapExtendScore );
};
////////////////////////////////// struct CigarStringDecoder ////////////////////////////////
template <class T>
struct CigarStringDecoder
{
char * cigarString;
int index;
CigarStringDecoder ( char * cigarString );
bool isEmpty ();
void decodeNext ( char & cigarType, int & cigarCnt );
int totalCount ( char c1, char c2 = 'N' );
};
//////////////////////////////////// struct CigarStringEncoder //////////////////////////////
template <class T>
CigarStringEncoder<T>::CigarStringEncoder ()
{
lastType = 'N';
lastCnt = 0;
cIndex = 0;
}
template <class T>
void CigarStringEncoder<T>::append ( char type, int cnt )
{
if ( lastType == type )
{ lastCnt += cnt; }
else
{
cigarType[cIndex] = lastType;
cigarCnt[cIndex] = lastCnt;
++cIndex;
lastType = type;
lastCnt = cnt;
}
}
template <class T>
void CigarStringEncoder<T>::encodeCigarString ( int GapOpenScore, int GapExtendScore )
{
memset ( charCount, 0, 128 * sizeof ( int ) );
gapPenalty = 0;
char buf[1024];
int len = 0;
append ( 'N', 0 );
for ( int i = cIndex - 1; i > 0; i-- )
{
char type = cigarType[i];
int cnt = cigarCnt[i];
if ( cnt > 0 )
{
len += sprintf ( buf + len, "%u%c", cnt, type );
charCount[type] += cnt;
if ( type == 'I' || type == 'D' )
{
gapPenalty += GapOpenScore + ( cnt - 1 ) * GapExtendScore;
}
}
}
cigarString = ( char * ) malloc ( len + 1 );
memcpy ( cigarString, buf, len );
cigarString[len] = 0;
}
//////////////////////////////////// struct CigarStringDecoder //////////////////////////////
template <class T>
CigarStringDecoder<T>::CigarStringDecoder ( char * cigarString )
{
this->cigarString = cigarString;
index = 0;
}
template <class T>
bool CigarStringDecoder<T>::isEmpty ()
{
return ( cigarString[index] == 0 );
}
template <class T>
void CigarStringDecoder<T>::decodeNext ( char & cigarType, int & cigarCnt )
{
cigarCnt = 0;
char c = cigarString[index];
while ( c >= '0' && c <= '9' )
{
cigarCnt = cigarCnt * 10 + c - '0';
c = cigarString[++index];
}
cigarType = cigarString[index++];
}
template <class T>
int CigarStringDecoder<T>::totalCount ( char c1, char c2 )
{
char type;
int cnt;
uint total = 0;
while ( !isEmpty () )
{
decodeNext ( type, cnt );
if ( type == c1 || type == c2 )
{
total += cnt;
}
}
index = 0;
return total;
}
//////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Utility class definition ///////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////// class TimeRecorder /////////////////////////////////
template <class T>
TimeRecorder<T>::TimeLine::TimeLine ()
{
state = 0;
length = 0;
}
template <class T>
TimeRecorder<T>::TimeRecorder ()
{
reset ();
}
template <class T>
double TimeRecorder<T>::setStartTime ()
{
struct timeval tp;
gettimeofday ( &tp, NULL );
return ( double ) tp.tv_sec + ( double ) tp.tv_usec / ( double ) 1000000;
}
template <class T>
double TimeRecorder<T>::getElapsedTime ( double startTime )
{
struct timeval tp;
gettimeofday ( &tp, NULL );
return ( double ) tp.tv_sec + ( double ) tp.tv_usec / ( double ) 1000000 - startTime;
}
template <class T>
void TimeRecorder<T>::reset ()
{
referenceTime = setStartTime ();
}
template <class T>
void TimeRecorder<T>::appendStart ( string label, string type )
{
TimeLine & timeLine = recorder[label];
if ( timeLine.state == 1 )
{ return; }
if ( type == "GPU" )
{
cudaEventCreate ( &timeLine.start );
cudaEventCreate ( &timeLine.stop );
cudaEventRecord ( timeLine.start, 0 );
}
timeLine.startTime.push_back ( getElapsedTime ( referenceTime ) );
timeLine.state = 1;
}
template <class T>
void TimeRecorder<T>::appendEnd ( string label, string type )
{
TimeLine & timeLine = recorder[label];
if ( timeLine.state == 0 )
{ return; }
if ( type == "GPU" )
{
float elapsedTime;
cudaEventRecord ( timeLine.stop, 0 );
cudaEventSynchronize ( timeLine.stop );
cudaEventElapsedTime ( &elapsedTime, timeLine.start, timeLine.stop );
cudaEventDestroy ( timeLine.start );
cudaEventDestroy ( timeLine.stop );
timeLine.endTime.push_back ( timeLine.startTime[timeLine.length] + elapsedTime / 1000.0 );
}
else
{ timeLine.endTime.push_back ( getElapsedTime ( referenceTime ) ); }
timeLine.length += 1;
timeLine.state = 0;
}
template <class T>
double TimeRecorder<T>::getTotalTime ( string label )
{
TimeLine & timeLine = recorder[label];
double totalTime = 0;
for ( int i = 0; i < timeLine.length; i++ )
{
totalTime += timeLine.endTime[i] - timeLine.startTime[i];
}
return totalTime;
}
template <class T>
void TimeRecorder<T>::printTimeLine ( string label, FILE * output )
{
TimeLine & timeLine = recorder[label];
fprintf ( output, "Label: %s -- Total %d records.\n", label.c_str (), timeLine.length );
for ( uint i = 0; i < timeLine.length; i++ )
{
fprintf ( output, "[%u] %lf -> %lf\n", i, timeLine.startTime[i], timeLine.endTime[i] );
}
}
//////////////////////////////////// class MultiThreadDelegator //////////////////////////////
template <class T>
void * MultiThreadDelegator_call_func ( void * classRef )
{
MultiThreadDelegator<T> * delegator = ( MultiThreadDelegator<T> * ) classRef;
delegator -> thread_run_func ();
return NULL;
}
template <class ArgType>
MultiThreadDelegator<ArgType>::MultiThreadDelegator ()
{
threadHandles = NULL;
}
template <class ArgType>
MultiThreadDelegator<ArgType>::~MultiThreadDelegator ()
{
clear ();
}
template <class ArgType>
void MultiThreadDelegator<ArgType>::clear ()
{
if ( threadHandles != NULL )
{
delete[] threadHandles;
delete[] threadSems;
delete threadPool;
delete[] threadFlags;
delete[] argList;
}
threadHandles = NULL;
}
template <class ArgType>
int MultiThreadDelegator<ArgType>::allocThread ()
{
pthread_mutex_lock ( &occupy_mutex );
int threadId = threadPool->top ();
threadPool->pop ();
threadFlags[threadId] = 1;
pthread_mutex_unlock ( &occupy_mutex );
return threadId;
}
template <class ArgType>
void MultiThreadDelegator<ArgType>::releaseThread ( int threadId )
{
pthread_mutex_lock ( &occupy_mutex );
threadPool->push ( threadId );
threadFlags[threadId] = 0;
pthread_mutex_unlock ( &occupy_mutex );
}
template <class ArgType>
void MultiThreadDelegator<ArgType>::init ( int num, void ( *inFuncWrapper ) ( int, ArgType & ),
void ( *inThreadInit ) ( void ),
void ( *inThreadFinalize ) ( void ) )
{
clear ();
numOfThreads = num;
threadHandles = new pthread_t[numOfThreads];
threadSems = new sem_t[numOfThreads];
threadPool = new ThreadPool;
threadFlags = new int[numOfThreads];
argList = new ArgType[numOfThreads];
funcWrapper = inFuncWrapper;
threadInit = inThreadInit;
threadFinalize = inThreadFinalize;
finishFlag = 0;
for ( int i = 0; i < numOfThreads; i++ )
{
sem_init ( threadSems + i, 0, 0 );
threadFlags[i] = 0; // empty
}
sem_init ( &availableSem, 0, 0 );
sem_init ( &finishSem, 0, 0 );
pthread_mutex_init ( &occupy_mutex, NULL );
pthread_mutex_init ( &finish_mutex, NULL );
createThreadCnt = 0;
for ( int i = 0; i < numOfThreads; i++ )
{
pthread_create ( threadHandles + i, NULL, MultiThreadDelegator_call_func<ArgType>, this );
}
}
template <class ArgType>
int MultiThreadDelegator<ArgType>::checkFinish ( int threadId )
{
int flag;
pthread_mutex_lock ( &occupy_mutex );
flag = finishFlag && ( threadFlags[threadId] == 0 );
pthread_mutex_unlock ( &occupy_mutex );
return flag;
}
template <class ArgType>
void MultiThreadDelegator<ArgType>::thread_run_func ()
{
pthread_mutex_lock ( &occupy_mutex );
int threadId = createThreadCnt++;
pthread_mutex_unlock ( &occupy_mutex );
if ( threadInit != NULL )
{ threadInit (); }
releaseThread ( threadId );
sem_post ( &availableSem );
sem_t * pThreadSem = threadSems + threadId;
sem_wait ( pThreadSem );
while ( checkFinish ( threadId ) == 0 )
{
funcWrapper ( threadId, argList[threadId] );
releaseThread ( threadId );
sem_post ( &availableSem );
sem_wait ( pThreadSem );
}
if ( threadFinalize != NULL )
{ threadFinalize (); }
}
template <class ArgType>
int MultiThreadDelegator<ArgType>::schedule ( ArgType & arg )
{
sem_wait ( &availableSem );
int threadId = allocThread ();
argList[threadId] = arg;
sem_post ( threadSems + threadId );
return threadId;
}
template <class ArgType>
void MultiThreadDelegator<ArgType>::finalize ()
{
pthread_mutex_lock ( &occupy_mutex );
finishFlag = 1;
pthread_mutex_unlock ( &occupy_mutex );
for ( int i = 0; i < numOfThreads; i++ )
{ sem_post ( threadSems + i ); }
for ( int i = 0; i < numOfThreads; i++ )
{ pthread_join ( threadHandles[i], NULL ); }
clear ();
}
//////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Alignment modules //////////////////////////////////////
/////////////////// The following code better be placed in separate files ///////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////// standard space ///////////////////////////////////////
struct QueryIDStream
{
vector<int> * data;
QueryIDStream ();
QueryIDStream ( BothUnalignedPairsArrays * input );
~QueryIDStream ();
void append ( QueryIDStream * stream );
void setBuffer ( vector<int> * input );
};
/////////////////////////////////////// single-dp space //////////////////////////////////////
namespace SingleDP_Space
{
typedef vector<SingleAlgnmtResult> SingleDPResultBatch;
struct SeedPos
{
uint pos;
uint readID;
int strand;
};
typedef struct SeedPos CandidateInfo;
struct CandidateStream
{
vector<CandidateInfo> data;
pthread_mutex_t occupy_mutex;
CandidateStream ();
void append ( vector<CandidateInfo> * canInfo, AlgnmtFlags * alignFlags );
};
void SeedingCPUThread ( int threadId, void *& empty );
void SeedingGPUThreadInit ();
void SeedingGPUThread ( int threadId, int *& pCallThreadId );
void SeedingGPUThreadFinalize ();
class SingleEndSeedingEngine
{
protected:
#define DPS_DIVIDE_GAP 50
struct SingleEndSeedingBatch
{
/* SOAP3 seeding parameters
* *********************/
uint * queries;
uint * queryLengths;
int wordPerQuery;
int * seedPositions;
/* SOAP3 seeding, Input
* *********************/
int numOfCPUForSeeding, maxHitNum;
uint batchSize, maxSeedLength, wordPerSeed, numQueries;
uint * readIDs, *seeds, *lengths, *offsets;
/* SOAP3 seeding, Output
* *********************/
uint64 numOfAnswer;
uint numOfAlignedRead;
SingleAlgnResultArray * algnResultArray;
SingleEndSeedingBatch (
uint batchSize, DPParameters * dpPara,
uint * queries, uint * queryLengths, uint inputMaxReadLength
);
~SingleEndSeedingBatch ();
void clear ();
inline void pack ( uint readID, int off, int seedLength );
int packSeeds ( uint readID, int stage );
vector<CandidateInfo> * singleMerge ( SeedPos * readPos );
SeedPos * decodePositions ( BWT * bwt );
vector<CandidateInfo> * decodeMergePositions ( BWT * bwt );
};
struct SingleEndSeedingThreadContext
{
SingleEndSeedingBatch * batch;
sem_t ACKSem;
sem_t GPUFinishSem;
void init ( SingleEndSeedingBatch * batch );
void freeMemory ();
};
static SingleEndSeedingEngine * engine;
SingleEndSeedingEngine ();
QueryIDStream * queryIDStream;
DPParameters * dpPara;
uint * queries;
uint * queryLengths;
int inputMaxReadLength;
Soap3Index * index;