forked from lh3/bwa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bwt_gen.c
1632 lines (1391 loc) · 52.7 KB
/
bwt_gen.c
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
/*
BWTConstruct.c BWT-Index Construction
This module constructs BWT and auxiliary data structures.
Copyright (C) 2004, Wong Chi Kwong.
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.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdint.h>
#include <errno.h>
#include "QSufSort.h"
#ifdef USE_MALLOC_WRAPPERS
# include "malloc_wrap.h"
#endif
typedef uint64_t bgint_t;
typedef int64_t sbgint_t;
#define ALPHABET_SIZE 4
#define BIT_PER_CHAR 2
#define CHAR_PER_WORD 16
#define CHAR_PER_BYTE 4
#define BITS_IN_WORD 32
#define BITS_IN_BYTE 8
#define BYTES_IN_WORD 4
#define ALL_ONE_MASK 0xFFFFFFFF
#define DNA_OCC_CNT_TABLE_SIZE_IN_WORD 65536
#define BITS_PER_OCC_VALUE 16
#define OCC_VALUE_PER_WORD 2
#define OCC_INTERVAL 256
#define OCC_INTERVAL_MAJOR 65536
#define TRUE 1
#define FALSE 0
#define BWTINC_INSERT_SORT_NUM_ITEM 7
#define MIN_AVAILABLE_WORD 0x10000
#define average(value1, value2) ( ((value1) & (value2)) + ((value1) ^ (value2)) / 2 )
#define min(value1, value2) ( ((value1) < (value2)) ? (value1) : (value2) )
#define max(value1, value2) ( ((value1) > (value2)) ? (value1) : (value2) )
#define med3(a, b, c) ( a<b ? (b<c ? b : a<c ? c : a) : (b>c ? b : a>c ? c : a))
#define swap(a, b, t); t = a; a = b; b = t;
#define truncateLeft(value, offset) ( (value) << (offset) >> (offset) )
#define truncateRight(value, offset) ( (value) >> (offset) << (offset) )
#define DNA_OCC_SUM_EXCEPTION(sum) ((sum & 0xfefefeff) == 0)
typedef struct BWT {
bgint_t textLength; // length of the text
bgint_t inverseSa0; // SA-1[0]
bgint_t *cumulativeFreq; // cumulative frequency
unsigned int *bwtCode; // BWT code
unsigned int *occValue; // Occurrence values stored explicitly
bgint_t *occValueMajor; // Occurrence values stored explicitly
unsigned int *decodeTable; // For decoding BWT by table lookup
bgint_t bwtSizeInWord; // Temporary variable to hold the memory allocated
bgint_t occSizeInWord; // Temporary variable to hold the memory allocated
bgint_t occMajorSizeInWord; // Temporary variable to hold the memory allocated
} BWT;
typedef struct BWTInc {
BWT *bwt;
unsigned int numberOfIterationDone;
bgint_t *cumulativeCountInCurrentBuild;
bgint_t availableWord;
bgint_t buildSize;
bgint_t initialMaxBuildSize;
bgint_t incMaxBuildSize;
unsigned int firstCharInLastIteration;
unsigned int *workingMemory;
unsigned int *packedText;
unsigned char *textBuffer;
unsigned int *packedShift;
} BWTInc;
static bgint_t TextLengthFromBytePacked(bgint_t bytePackedLength, unsigned int bitPerChar,
unsigned int lastByteLength)
{
return (bytePackedLength - 1) * (BITS_IN_BYTE / bitPerChar) + lastByteLength;
}
static void initializeVAL(unsigned int *startAddr, const bgint_t length, const unsigned int initValue)
{
bgint_t i;
for (i=0; i<length; i++) startAddr[i] = initValue;
}
static void initializeVAL_bg(bgint_t *startAddr, const bgint_t length, const bgint_t initValue)
{
bgint_t i;
for (i=0; i<length; i++) startAddr[i] = initValue;
}
static void GenerateDNAOccCountTable(unsigned int *dnaDecodeTable)
{
unsigned int i, j, c, t;
for (i=0; i<DNA_OCC_CNT_TABLE_SIZE_IN_WORD; i++) {
dnaDecodeTable[i] = 0;
c = i;
for (j=0; j<8; j++) {
t = c & 0x00000003;
dnaDecodeTable[i] += 1 << (t * 8);
c >>= 2;
}
}
}
// for BWTIncCreate()
static bgint_t BWTOccValueMajorSizeInWord(const bgint_t numChar)
{
bgint_t numOfOccValue;
unsigned numOfOccIntervalPerMajor;
numOfOccValue = (numChar + OCC_INTERVAL - 1) / OCC_INTERVAL + 1; // Value at both end for bi-directional encoding
numOfOccIntervalPerMajor = OCC_INTERVAL_MAJOR / OCC_INTERVAL;
return (numOfOccValue + numOfOccIntervalPerMajor - 1) / numOfOccIntervalPerMajor * ALPHABET_SIZE;
}
// for BWTIncCreate()
static bgint_t BWTOccValueMinorSizeInWord(const bgint_t numChar)
{
bgint_t numOfOccValue;
numOfOccValue = (numChar + OCC_INTERVAL - 1) / OCC_INTERVAL + 1; // Value at both end for bi-directional encoding
return (numOfOccValue + OCC_VALUE_PER_WORD - 1) / OCC_VALUE_PER_WORD * ALPHABET_SIZE;
}
// for BWTIncCreate()
static bgint_t BWTResidentSizeInWord(const bgint_t numChar) {
bgint_t numCharRoundUpToOccInterval;
// The $ in BWT at the position of inverseSa0 is not encoded
numCharRoundUpToOccInterval = (numChar + OCC_INTERVAL - 1) / OCC_INTERVAL * OCC_INTERVAL;
return (numCharRoundUpToOccInterval + CHAR_PER_WORD - 1) / CHAR_PER_WORD;
}
static void BWTIncSetBuildSizeAndTextAddr(BWTInc *bwtInc)
{
bgint_t maxBuildSize;
if (bwtInc->bwt->textLength == 0) {
// initial build
// Minus 2 because n+1 entries of seq and rank needed for n char
maxBuildSize = (bwtInc->availableWord - (2 + OCC_INTERVAL / CHAR_PER_WORD) * (sizeof(bgint_t) / 4))
/ (2 * CHAR_PER_WORD + 1) * CHAR_PER_WORD / (sizeof(bgint_t) / 4);
if (bwtInc->initialMaxBuildSize > 0) {
bwtInc->buildSize = min(bwtInc->initialMaxBuildSize, maxBuildSize);
} else {
bwtInc->buildSize = maxBuildSize;
}
} else {
// Minus 3 because n+1 entries of sorted rank, seq and rank needed for n char
// Minus numberOfIterationDone because bwt slightly shift to left in each iteration
maxBuildSize = (bwtInc->availableWord - bwtInc->bwt->bwtSizeInWord - bwtInc->bwt->occSizeInWord
- (3 + bwtInc->numberOfIterationDone * OCC_INTERVAL / BIT_PER_CHAR) * (sizeof(bgint_t) / 4))
/ 3 / (sizeof(bgint_t) / 4);
if (maxBuildSize < CHAR_PER_WORD) {
fprintf(stderr, "BWTIncSetBuildSizeAndTextAddr(): Not enough space allocated to continue construction!\n");
exit(1);
}
if (bwtInc->incMaxBuildSize > 0) {
bwtInc->buildSize = min(bwtInc->incMaxBuildSize, maxBuildSize);
} else {
bwtInc->buildSize = maxBuildSize;
}
if (bwtInc->buildSize < CHAR_PER_WORD)
bwtInc->buildSize = CHAR_PER_WORD;
}
if (bwtInc->buildSize < CHAR_PER_WORD) {
fprintf(stderr, "BWTIncSetBuildSizeAndTextAddr(): Not enough space allocated to continue construction!\n");
exit(1);
}
bwtInc->buildSize = bwtInc->buildSize / CHAR_PER_WORD * CHAR_PER_WORD;
bwtInc->packedText = bwtInc->workingMemory + 2 * (bwtInc->buildSize + 1) * (sizeof(bgint_t) / 4);
bwtInc->textBuffer = (unsigned char*)(bwtInc->workingMemory + (bwtInc->buildSize + 1) * (sizeof(bgint_t) / 4));
}
// for ceilLog2()
unsigned int leadingZero(const unsigned int input)
{
unsigned int l;
const static unsigned int leadingZero8bit[256] = {8,7,6,6,5,5,5,5,4,4,4,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
if (input & 0xFFFF0000) {
if (input & 0xFF000000) {
l = leadingZero8bit[input >> 24];
} else {
l = 8 + leadingZero8bit[input >> 16];
}
} else {
if (input & 0x0000FF00) {
l = 16 + leadingZero8bit[input >> 8];
} else {
l = 24 + leadingZero8bit[input];
}
}
return l;
}
// for BitPerBytePackedChar()
static unsigned int ceilLog2(const unsigned int input)
{
if (input <= 1) return 0;
return BITS_IN_WORD - leadingZero(input - 1);
}
// for ConvertBytePackedToWordPacked()
static unsigned int BitPerBytePackedChar(const unsigned int alphabetSize)
{
unsigned int bitPerChar;
bitPerChar = ceilLog2(alphabetSize);
// Return the largest number of bit that does not affect packing efficiency
if (BITS_IN_BYTE / (BITS_IN_BYTE / bitPerChar) > bitPerChar)
bitPerChar = BITS_IN_BYTE / (BITS_IN_BYTE / bitPerChar);
return bitPerChar;
}
// for ConvertBytePackedToWordPacked()
static unsigned int BitPerWordPackedChar(const unsigned int alphabetSize)
{
return ceilLog2(alphabetSize);
}
static void ConvertBytePackedToWordPacked(const unsigned char *input, unsigned int *output, const unsigned int alphabetSize,
const bgint_t textLength)
{
bgint_t i;
unsigned int j, k, c;
unsigned int bitPerBytePackedChar;
unsigned int bitPerWordPackedChar;
unsigned int charPerWord;
unsigned int charPerByte;
unsigned int bytePerIteration;
bgint_t byteProcessed = 0;
bgint_t wordProcessed = 0;
unsigned int mask, shift;
unsigned int buffer[BITS_IN_WORD];
bitPerBytePackedChar = BitPerBytePackedChar(alphabetSize);
bitPerWordPackedChar = BitPerWordPackedChar(alphabetSize);
charPerByte = BITS_IN_BYTE / bitPerBytePackedChar;
charPerWord = BITS_IN_WORD / bitPerWordPackedChar;
bytePerIteration = charPerWord / charPerByte;
mask = truncateRight(ALL_ONE_MASK, BITS_IN_WORD - bitPerWordPackedChar);
shift = BITS_IN_WORD - BITS_IN_BYTE + bitPerBytePackedChar - bitPerWordPackedChar;
while ((wordProcessed + 1) * charPerWord < textLength) {
k = 0;
for (i=0; i<bytePerIteration; i++) {
c = (unsigned int)input[byteProcessed] << shift;
for (j=0; j<charPerByte; j++) {
buffer[k] = c & mask;
c <<= bitPerBytePackedChar;
k++;
}
byteProcessed++;
}
c = 0;
for (i=0; i<charPerWord; i++) {
c |= buffer[i] >> bitPerWordPackedChar * i;
}
output[wordProcessed] = c;
wordProcessed++;
}
k = 0;
for (i=0; i < (textLength - wordProcessed * charPerWord - 1) / charPerByte + 1; i++) {
c = (unsigned int)input[byteProcessed] << shift;
for (j=0; j<charPerByte; j++) {
buffer[k] = c & mask;
c <<= bitPerBytePackedChar;
k++;
}
byteProcessed++;
}
c = 0;
for (i=0; i<textLength - wordProcessed * charPerWord; i++) {
c |= buffer[i] >> bitPerWordPackedChar * i;
}
output[wordProcessed] = c;
}
BWT *BWTCreate(const bgint_t textLength, unsigned int *decodeTable)
{
BWT *bwt;
bwt = (BWT*)calloc(1, sizeof(BWT));
bwt->textLength = 0;
bwt->cumulativeFreq = (bgint_t*)calloc((ALPHABET_SIZE + 1), sizeof(bgint_t));
initializeVAL_bg(bwt->cumulativeFreq, ALPHABET_SIZE + 1, 0);
bwt->bwtSizeInWord = 0;
// Generate decode tables
if (decodeTable == NULL) {
bwt->decodeTable = (unsigned*)calloc(DNA_OCC_CNT_TABLE_SIZE_IN_WORD, sizeof(unsigned int));
GenerateDNAOccCountTable(bwt->decodeTable);
} else {
bwt->decodeTable = decodeTable;
}
bwt->occMajorSizeInWord = BWTOccValueMajorSizeInWord(textLength);
bwt->occValueMajor = (bgint_t*)calloc(bwt->occMajorSizeInWord, sizeof(bgint_t));
bwt->occSizeInWord = 0;
bwt->occValue = NULL;
return bwt;
}
BWTInc *BWTIncCreate(const bgint_t textLength, unsigned int initialMaxBuildSize, unsigned int incMaxBuildSize)
{
BWTInc *bwtInc;
unsigned int i, n_iter;
if (textLength < incMaxBuildSize) incMaxBuildSize = textLength;
if (textLength < initialMaxBuildSize) initialMaxBuildSize = textLength;
bwtInc = (BWTInc*)calloc(1, sizeof(BWTInc));
bwtInc->numberOfIterationDone = 0;
bwtInc->bwt = BWTCreate(textLength, NULL);
bwtInc->initialMaxBuildSize = initialMaxBuildSize;
bwtInc->incMaxBuildSize = incMaxBuildSize;
bwtInc->cumulativeCountInCurrentBuild = (bgint_t*)calloc((ALPHABET_SIZE + 1), sizeof(bgint_t));
initializeVAL_bg(bwtInc->cumulativeCountInCurrentBuild, ALPHABET_SIZE + 1, 0);
// Build frequently accessed data
bwtInc->packedShift = (unsigned*)calloc(CHAR_PER_WORD, sizeof(unsigned int));
for (i=0; i<CHAR_PER_WORD; i++)
bwtInc->packedShift[i] = BITS_IN_WORD - (i+1) * BIT_PER_CHAR;
n_iter = (textLength - initialMaxBuildSize) / incMaxBuildSize + 1;
bwtInc->availableWord = BWTResidentSizeInWord(textLength) + BWTOccValueMinorSizeInWord(textLength) // minimal memory requirement
+ OCC_INTERVAL / BIT_PER_CHAR * n_iter * 2 * (sizeof(bgint_t) / 4) // buffer at the end of occ array
+ incMaxBuildSize/5 * 3 * (sizeof(bgint_t) / 4); // space for the 3 temporary arrays in each iteration
if (bwtInc->availableWord < MIN_AVAILABLE_WORD) bwtInc->availableWord = MIN_AVAILABLE_WORD; // lh3: otherwise segfaul when availableWord is too small
fprintf(stderr, "[%s] textLength=%ld, availableWord=%ld\n", __func__, (long)textLength, (long)bwtInc->availableWord);
bwtInc->workingMemory = (unsigned*)calloc(bwtInc->availableWord, BYTES_IN_WORD);
return bwtInc;
}
// for BWTIncConstruct()
static void BWTIncPutPackedTextToRank(const unsigned int *packedText, bgint_t* __restrict rank,
bgint_t* __restrict cumulativeCount, const bgint_t numChar)
{
bgint_t i;
unsigned int j;
unsigned int c, t;
unsigned int packedMask;
bgint_t rankIndex;
bgint_t lastWord;
unsigned int numCharInLastWord;
lastWord = (numChar - 1) / CHAR_PER_WORD;
numCharInLastWord = numChar - lastWord * CHAR_PER_WORD;
packedMask = ALL_ONE_MASK >> (BITS_IN_WORD - BIT_PER_CHAR);
rankIndex = numChar - 1;
t = packedText[lastWord] >> (BITS_IN_WORD - numCharInLastWord * BIT_PER_CHAR);
for (i=0; i<numCharInLastWord; i++) {
c = t & packedMask;
cumulativeCount[c+1]++;
rank[rankIndex] = c;
rankIndex--;
t >>= BIT_PER_CHAR;
}
for (i=lastWord; i--;) { // loop from lastWord - 1 to 0
t = packedText[i];
for (j=0; j<CHAR_PER_WORD; j++) {
c = t & packedMask;
cumulativeCount[c+1]++;
rank[rankIndex] = c;
rankIndex--;
t >>= BIT_PER_CHAR;
}
}
// Convert occurrence to cumulativeCount
cumulativeCount[2] += cumulativeCount[1];
cumulativeCount[3] += cumulativeCount[2];
cumulativeCount[4] += cumulativeCount[3];
}
static void ForwardDNAAllOccCountNoLimit(const unsigned int* dna, const bgint_t index,
bgint_t* __restrict occCount, const unsigned int* dnaDecodeTable)
{
static const unsigned int truncateRightMask[16] = { 0x00000000, 0xC0000000, 0xF0000000, 0xFC000000,
0xFF000000, 0xFFC00000, 0xFFF00000, 0xFFFC0000,
0xFFFF0000, 0xFFFFC000, 0xFFFFF000, 0xFFFFFC00,
0xFFFFFF00, 0xFFFFFFC0, 0xFFFFFFF0, 0xFFFFFFFC };
bgint_t iteration, i;
unsigned int wordToCount, charToCount;
unsigned int j, c, sum;
occCount[0] = 0;
occCount[1] = 0;
occCount[2] = 0;
occCount[3] = 0;
iteration = index / 256;
wordToCount = (index - iteration * 256) / 16;
charToCount = index - iteration * 256 - wordToCount * 16;
for (i=0; i<iteration; i++) {
sum = 0;
for (j=0; j<16; j++) {
sum += dnaDecodeTable[*dna >> 16];
sum += dnaDecodeTable[*dna & 0x0000FFFF];
dna++;
}
if (!DNA_OCC_SUM_EXCEPTION(sum)) {
occCount[0] += sum & 0x000000FF; sum >>= 8;
occCount[1] += sum & 0x000000FF; sum >>= 8;
occCount[2] += sum & 0x000000FF; sum >>= 8;
occCount[3] += sum;
} else {
// only some or all of the 3 bits are on
// in reality, only one of the four cases are possible
if (sum == 0x00000100) {
occCount[0] += 256;
} else if (sum == 0x00010000) {
occCount[1] += 256;
} else if (sum == 0x01000000) {
occCount[2] += 256;
} else if (sum == 0x00000000) {
occCount[3] += 256;
} else {
fprintf(stderr, "ForwardDNAAllOccCountNoLimit(): DNA occ sum exception!\n");
exit(1);
}
}
}
sum = 0;
for (j=0; j<wordToCount; j++) {
sum += dnaDecodeTable[*dna >> 16];
sum += dnaDecodeTable[*dna & 0x0000FFFF];
dna++;
}
if (charToCount > 0) {
c = *dna & truncateRightMask[charToCount]; // increase count of 'a' by 16 - c;
sum += dnaDecodeTable[c >> 16];
sum += dnaDecodeTable[c & 0xFFFF];
sum += charToCount - 16; // decrease count of 'a' by 16 - positionToProcess
}
occCount[0] += sum & 0x000000FF; sum >>= 8;
occCount[1] += sum & 0x000000FF; sum >>= 8;
occCount[2] += sum & 0x000000FF; sum >>= 8;
occCount[3] += sum;
}
static void BWTIncBuildPackedBwt(const bgint_t *relativeRank, unsigned int* __restrict bwt, const bgint_t numChar,
const bgint_t *cumulativeCount, const unsigned int *packedShift) {
bgint_t i, r;
unsigned int c;
bgint_t previousRank, currentRank;
bgint_t wordIndex, charIndex;
bgint_t inverseSa0;
inverseSa0 = previousRank = relativeRank[0];
for (i=1; i<=numChar; i++) {
currentRank = relativeRank[i];
// previousRank > cumulativeCount[c] because $ is one of the char
c = (previousRank > cumulativeCount[1]) + (previousRank > cumulativeCount[2])
+ (previousRank > cumulativeCount[3]);
// set bwt for currentRank
if (c > 0) {
// c <> 'a'
r = currentRank;
if (r > inverseSa0) {
// - 1 because $ at inverseSa0 is not encoded
r--;
}
wordIndex = r / CHAR_PER_WORD;
charIndex = r - wordIndex * CHAR_PER_WORD;
bwt[wordIndex] |= c << packedShift[charIndex];
}
previousRank = currentRank;
}
}
static inline bgint_t BWTOccValueExplicit(const BWT *bwt, const bgint_t occIndexExplicit,
const unsigned int character)
{
bgint_t occIndexMajor;
occIndexMajor = occIndexExplicit * OCC_INTERVAL / OCC_INTERVAL_MAJOR;
if (occIndexExplicit % OCC_VALUE_PER_WORD == 0) {
return bwt->occValueMajor[occIndexMajor * ALPHABET_SIZE + character] +
(bwt->occValue[occIndexExplicit / OCC_VALUE_PER_WORD * ALPHABET_SIZE + character] >> 16);
} else {
return bwt->occValueMajor[occIndexMajor * ALPHABET_SIZE + character] +
(bwt->occValue[occIndexExplicit / OCC_VALUE_PER_WORD * ALPHABET_SIZE + character] & 0x0000FFFF);
}
}
static unsigned int ForwardDNAOccCount(const unsigned int* dna, const unsigned int index, const unsigned int character,
const unsigned int* dnaDecodeTable)
{
static const unsigned int truncateRightMask[16] = { 0x00000000, 0xC0000000, 0xF0000000, 0xFC000000,
0xFF000000, 0xFFC00000, 0xFFF00000, 0xFFFC0000,
0xFFFF0000, 0xFFFFC000, 0xFFFFF000, 0xFFFFFC00,
0xFFFFFF00, 0xFFFFFFC0, 0xFFFFFFF0, 0xFFFFFFFC };
unsigned int wordToCount, charToCount;
unsigned int i, c;
unsigned int sum = 0;
wordToCount = index / 16;
charToCount = index - wordToCount * 16;
for (i=0; i<wordToCount; i++) {
sum += dnaDecodeTable[dna[i] >> 16];
sum += dnaDecodeTable[dna[i] & 0x0000FFFF];
}
if (charToCount > 0) {
c = dna[i] & truncateRightMask[charToCount]; // increase count of 'a' by 16 - c;
sum += dnaDecodeTable[c >> 16];
sum += dnaDecodeTable[c & 0xFFFF];
sum += charToCount - 16; // decrease count of 'a' by 16 - positionToProcess
}
return (sum >> (character * 8)) & 0x000000FF;
}
static unsigned int BackwardDNAOccCount(const unsigned int* dna, const unsigned int index, const unsigned int character,
const unsigned int* dnaDecodeTable)
{
static const unsigned int truncateLeftMask[16] = { 0x00000000, 0x00000003, 0x0000000F, 0x0000003F,
0x000000FF, 0x000003FF, 0x00000FFF, 0x00003FFF,
0x0000FFFF, 0x0003FFFF, 0x000FFFFF, 0x003FFFFF,
0x00FFFFFF, 0x03FFFFFF, 0x0FFFFFFF, 0x3FFFFFFF };
unsigned int wordToCount, charToCount;
unsigned int i, c;
unsigned int sum = 0;
wordToCount = index / 16;
charToCount = index - wordToCount * 16;
dna -= wordToCount + 1;
if (charToCount > 0) {
c = *dna & truncateLeftMask[charToCount]; // increase count of 'a' by 16 - c;
sum += dnaDecodeTable[c >> 16];
sum += dnaDecodeTable[c & 0xFFFF];
sum += charToCount - 16; // decrease count of 'a' by 16 - positionToProcess
}
for (i=0; i<wordToCount; i++) {
dna++;
sum += dnaDecodeTable[*dna >> 16];
sum += dnaDecodeTable[*dna & 0x0000FFFF];
}
return (sum >> (character * 8)) & 0x000000FF;
}
bgint_t BWTOccValue(const BWT *bwt, bgint_t index, const unsigned int character)
{
bgint_t occValue;
bgint_t occExplicitIndex, occIndex;
// $ is supposed to be positioned at inverseSa0 but it is not encoded
// therefore index is subtracted by 1 for adjustment
if (index > bwt->inverseSa0)
index--;
occExplicitIndex = (index + OCC_INTERVAL / 2 - 1) / OCC_INTERVAL; // Bidirectional encoding
occIndex = occExplicitIndex * OCC_INTERVAL;
occValue = BWTOccValueExplicit(bwt, occExplicitIndex, character);
if (occIndex == index)
return occValue;
if (occIndex < index) {
return occValue + ForwardDNAOccCount(bwt->bwtCode + occIndex / CHAR_PER_WORD, index - occIndex, character, bwt->decodeTable);
} else {
return occValue - BackwardDNAOccCount(bwt->bwtCode + occIndex / CHAR_PER_WORD, occIndex - index, character, bwt->decodeTable);
}
}
static bgint_t BWTIncGetAbsoluteRank(BWT *bwt, bgint_t* __restrict absoluteRank, bgint_t* __restrict seq,
const unsigned int *packedText, const bgint_t numChar,
const bgint_t* cumulativeCount, const unsigned int firstCharInLastIteration)
{
bgint_t saIndex;
bgint_t lastWord;
unsigned int packedMask;
bgint_t i;
unsigned int c, t, j;
bgint_t rankIndex;
unsigned int shift;
bgint_t seqIndexFromStart[ALPHABET_SIZE];
bgint_t seqIndexFromEnd[ALPHABET_SIZE];
for (i=0; i<ALPHABET_SIZE; i++) {
seqIndexFromStart[i] = cumulativeCount[i];
seqIndexFromEnd[i] = cumulativeCount[i+1] - 1;
}
shift = BITS_IN_WORD - BIT_PER_CHAR;
packedMask = ALL_ONE_MASK >> shift;
saIndex = bwt->inverseSa0;
rankIndex = numChar - 1;
lastWord = numChar / CHAR_PER_WORD;
for (i=lastWord; i--;) { // loop from lastWord - 1 to 0
t = packedText[i];
for (j=0; j<CHAR_PER_WORD; j++) {
c = t & packedMask;
saIndex = bwt->cumulativeFreq[c] + BWTOccValue(bwt, saIndex, c) + 1;
// A counting sort using the first character of suffix is done here
// If rank > inverseSa0 -> fill seq from end, otherwise fill seq from start -> to leave the right entry for inverseSa0
if (saIndex > bwt->inverseSa0) {
seq[seqIndexFromEnd[c]] = rankIndex;
absoluteRank[seqIndexFromEnd[c]] = saIndex;
seqIndexFromEnd[c]--;
} else {
seq[seqIndexFromStart[c]] = rankIndex;
absoluteRank[seqIndexFromStart[c]] = saIndex;
seqIndexFromStart[c]++;
}
rankIndex--;
t >>= BIT_PER_CHAR;
}
}
absoluteRank[seqIndexFromStart[firstCharInLastIteration]] = bwt->inverseSa0; // representing the substring of all preceding characters
seq[seqIndexFromStart[firstCharInLastIteration]] = numChar;
return seqIndexFromStart[firstCharInLastIteration];
}
static void BWTIncSortKey(bgint_t* __restrict key, bgint_t* __restrict seq, const bgint_t numItem)
{
#define EQUAL_KEY_THRESHOLD 4 // Partition for equal key if data array size / the number of data with equal value with pivot < EQUAL_KEY_THRESHOLD
int64_t lowIndex, highIndex, midIndex;
int64_t lowPartitionIndex, highPartitionIndex;
int64_t lowStack[32], highStack[32];
int stackDepth;
int64_t i, j;
bgint_t tempSeq, tempKey;
int64_t numberOfEqualKey;
if (numItem < 2) return;
stackDepth = 0;
lowIndex = 0;
highIndex = numItem - 1;
for (;;) {
for (;;) {
// Sort small array of data
if (highIndex - lowIndex < BWTINC_INSERT_SORT_NUM_ITEM) { // Insertion sort on smallest arrays
for (i=lowIndex+1; i<=highIndex; i++) {
tempSeq = seq[i];
tempKey = key[i];
for (j = i; j > lowIndex && key[j-1] > tempKey; j--) {
seq[j] = seq[j-1];
key[j] = key[j-1];
}
if (j != i) {
seq[j] = tempSeq;
key[j] = tempKey;
}
}
break;
}
// Choose pivot as median of the lowest, middle, and highest data; sort the three data
midIndex = average(lowIndex, highIndex);
if (key[lowIndex] > key[midIndex]) {
tempSeq = seq[lowIndex];
tempKey = key[lowIndex];
seq[lowIndex] = seq[midIndex];
key[lowIndex] = key[midIndex];
seq[midIndex] = tempSeq;
key[midIndex] = tempKey;
}
if (key[lowIndex] > key[highIndex]) {
tempSeq = seq[lowIndex];
tempKey = key[lowIndex];
seq[lowIndex] = seq[highIndex];
key[lowIndex] = key[highIndex];
seq[highIndex] = tempSeq;
key[highIndex] = tempKey;
}
if (key[midIndex] > key[highIndex]) {
tempSeq = seq[midIndex];
tempKey = key[midIndex];
seq[midIndex] = seq[highIndex];
key[midIndex] = key[highIndex];
seq[highIndex] = tempSeq;
key[highIndex] = tempKey;
}
// Partition data
numberOfEqualKey = 0;
lowPartitionIndex = lowIndex + 1;
highPartitionIndex = highIndex - 1;
for (;;) {
while (lowPartitionIndex <= highPartitionIndex && key[lowPartitionIndex] <= key[midIndex]) {
numberOfEqualKey += (key[lowPartitionIndex] == key[midIndex]);
lowPartitionIndex++;
}
while (lowPartitionIndex < highPartitionIndex) {
if (key[midIndex] >= key[highPartitionIndex]) {
numberOfEqualKey += (key[midIndex] == key[highPartitionIndex]);
break;
}
highPartitionIndex--;
}
if (lowPartitionIndex >= highPartitionIndex) {
break;
}
tempSeq = seq[lowPartitionIndex];
tempKey = key[lowPartitionIndex];
seq[lowPartitionIndex] = seq[highPartitionIndex];
key[lowPartitionIndex] = key[highPartitionIndex];
seq[highPartitionIndex] = tempSeq;
key[highPartitionIndex] = tempKey;
if (highPartitionIndex == midIndex) {
// partition key has been moved
midIndex = lowPartitionIndex;
}
lowPartitionIndex++;
highPartitionIndex--;
}
// Adjust the partition index
highPartitionIndex = lowPartitionIndex;
lowPartitionIndex--;
// move the partition key to end of low partition
tempSeq = seq[midIndex];
tempKey = key[midIndex];
seq[midIndex] = seq[lowPartitionIndex];
key[midIndex] = key[lowPartitionIndex];
seq[lowPartitionIndex] = tempSeq;
key[lowPartitionIndex] = tempKey;
if (highIndex - lowIndex + BWTINC_INSERT_SORT_NUM_ITEM <= EQUAL_KEY_THRESHOLD * numberOfEqualKey) {
// Many keys = partition key; separate the equal key data from the lower partition
midIndex = lowIndex;
for (;;) {
while (midIndex < lowPartitionIndex && key[midIndex] < key[lowPartitionIndex]) {
midIndex++;
}
while (midIndex < lowPartitionIndex && key[lowPartitionIndex] == key[lowPartitionIndex - 1]) {
lowPartitionIndex--;
}
if (midIndex >= lowPartitionIndex) {
break;
}
tempSeq = seq[midIndex];
tempKey = key[midIndex];
seq[midIndex] = seq[lowPartitionIndex - 1];
key[midIndex] = key[lowPartitionIndex - 1];
seq[lowPartitionIndex - 1] = tempSeq;
key[lowPartitionIndex - 1] = tempKey;
midIndex++;
lowPartitionIndex--;
}
}
if (lowPartitionIndex - lowIndex > highIndex - highPartitionIndex) {
// put the larger partition to stack
lowStack[stackDepth] = lowIndex;
highStack[stackDepth] = lowPartitionIndex - 1;
stackDepth++;
// sort the smaller partition first
lowIndex = highPartitionIndex;
} else {
// put the larger partition to stack
lowStack[stackDepth] = highPartitionIndex;
highStack[stackDepth] = highIndex;
stackDepth++;
// sort the smaller partition first
if (lowPartitionIndex > lowIndex) {
highIndex = lowPartitionIndex - 1;
} else {
// all keys in the partition equals to the partition key
break;
}
}
continue;
}
// Pop a range from stack
if (stackDepth > 0) {
stackDepth--;
lowIndex = lowStack[stackDepth];
highIndex = highStack[stackDepth];
continue;
} else return;
}
}
static void BWTIncBuildRelativeRank(bgint_t* __restrict sortedRank, bgint_t* __restrict seq,
bgint_t* __restrict relativeRank, const bgint_t numItem,
bgint_t oldInverseSa0, const bgint_t *cumulativeCount)
{
bgint_t i, c;
bgint_t s, r;
bgint_t lastRank, lastIndex;
bgint_t oldInverseSa0RelativeRank = 0;
bgint_t freq;
lastIndex = numItem;
lastRank = sortedRank[numItem];
if (lastRank > oldInverseSa0) {
sortedRank[numItem]--; // to prepare for merging; $ is not encoded in bwt
}
s = seq[numItem];
relativeRank[s] = numItem;
if (lastRank == oldInverseSa0) {
oldInverseSa0RelativeRank = numItem;
oldInverseSa0++; // so that this segment of code is not run again
lastRank++; // so that oldInverseSa0 become a sorted group with 1 item
}
c = ALPHABET_SIZE - 1;
freq = cumulativeCount[c];
for (i=numItem; i--;) { // from numItem - 1 to 0
r = sortedRank[i];
if (r > oldInverseSa0)
sortedRank[i]--; // to prepare for merging; $ is not encoded in bwt
s = seq[i];
if (i < freq) {
if (lastIndex >= freq)
lastRank++; // to trigger the group across alphabet boundary to be split
c--;
freq = cumulativeCount[c];
}
if (r == lastRank) {
relativeRank[s] = lastIndex;
} else {
if (i == lastIndex - 1) {
if (lastIndex < numItem && (sbgint_t)seq[lastIndex + 1] < 0) {
seq[lastIndex] = seq[lastIndex + 1] - 1;
} else {
seq[lastIndex] = (bgint_t)-1;
}
}
lastIndex = i;
lastRank = r;
relativeRank[s] = i;
if (r == oldInverseSa0) {
oldInverseSa0RelativeRank = i;
oldInverseSa0++; // so that this segment of code is not run again
lastRank++; // so that oldInverseSa0 become a sorted group with 1 item
}
}
}
}
static void BWTIncBuildBwt(unsigned int* insertBwt, const bgint_t *relativeRank, const bgint_t numChar,
const bgint_t *cumulativeCount)
{
unsigned int c;
bgint_t i;
bgint_t previousRank, currentRank;
previousRank = relativeRank[0];
for (i=1; i<=numChar; i++) {
currentRank = relativeRank[i];
c = (previousRank >= cumulativeCount[1]) + (previousRank >= cumulativeCount[2])
+ (previousRank >= cumulativeCount[3]);
insertBwt[currentRank] = c;
previousRank = currentRank;
}
}
static void BWTIncMergeBwt(const bgint_t *sortedRank, const unsigned int* oldBwt, const unsigned int *insertBwt,
unsigned int* __restrict mergedBwt, const bgint_t numOldBwt, const bgint_t numInsertBwt)
{
unsigned int bitsInWordMinusBitPerChar;
bgint_t leftShift, rightShift;
bgint_t o;
bgint_t oIndex, iIndex, mIndex;
bgint_t mWord, mChar, oWord, oChar;
bgint_t numInsert;
bitsInWordMinusBitPerChar = BITS_IN_WORD - BIT_PER_CHAR;
oIndex = 0;
iIndex = 0;
mIndex = 0;
mWord = 0;
mChar = 0;
mergedBwt[0] = 0; // this can be cleared as merged Bwt slightly shift to the left in each iteration
while (oIndex < numOldBwt) {
// copy from insertBwt
while (iIndex <= numInsertBwt && sortedRank[iIndex] <= oIndex) {
if (sortedRank[iIndex] != 0) { // special value to indicate that this is for new inverseSa0
mergedBwt[mWord] |= insertBwt[iIndex] << (BITS_IN_WORD - (mChar + 1) * BIT_PER_CHAR);
mIndex++;
mChar++;
if (mChar == CHAR_PER_WORD) {
mChar = 0;
mWord++;
mergedBwt[mWord] = 0; // no need to worry about crossing mergedBwt boundary
}
}
iIndex++;
}
// Copy from oldBwt to mergedBwt
if (iIndex <= numInsertBwt) {
o = sortedRank[iIndex];
} else {
o = numOldBwt;
}
numInsert = o - oIndex;
oWord = oIndex / CHAR_PER_WORD;
oChar = oIndex - oWord * CHAR_PER_WORD;
if (oChar > mChar) {
leftShift = (oChar - mChar) * BIT_PER_CHAR;
rightShift = (CHAR_PER_WORD + mChar - oChar) * BIT_PER_CHAR;
mergedBwt[mWord] = mergedBwt[mWord]