forked from adigenova/fast-sg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFastSG.cpp
2559 lines (2359 loc) · 106 KB
/
FastSG.cpp
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
//
// Created by Alex Di Genova on 16/10/2016.
//
//external libraries
#include "kseqcpp/kseq.hpp"
#include "BBHash/BooPHF.h"
#include "ntHash/nthash.hpp"
#include "quasi_dictionary/src/probabilistic_set.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <sys/types.h>
#include <random>
#include <algorithm>
#include <fstream>
#include <fcntl.h>
#include <iostream>
#include <map>
#include <sstream>
#include <iterator>
#include <thread>
using namespace std;
//Custom fake hasher for Boophf because the values are already hashed into int64_t using nthash
class Custom_uint64_Hasher
{
public:
uint64_t operator () (uint64_t key, uint64_t seed=0) const
{
return key;
}
};
//we define the perfect hash funtion datatypes
typedef boomphf::mphf< u_int64_t, Custom_uint64_Hasher > boophf_t;
//to work in file instead of memory, code from Boophf
// iterator from disk file of u_int64_t with buffered read, todo template
class bfile_iterator : public std::iterator<std::forward_iterator_tag, u_int64_t>{
public:
bfile_iterator()
: _is(nullptr)
, _pos(0) ,_inbuff (0), _cptread(0)
{
_buffsize = 10000;
_buffer = (u_int64_t *) malloc(_buffsize*sizeof(u_int64_t));
}
bfile_iterator(const bfile_iterator& cr)
{
_buffsize = cr._buffsize;
_pos = cr._pos;
_is = cr._is;
_buffer = (u_int64_t *) malloc(_buffsize*sizeof(u_int64_t));
memcpy(_buffer,cr._buffer,_buffsize*sizeof(u_int64_t) );
_inbuff = cr._inbuff;
_cptread = cr._cptread;
_elem = cr._elem;
}
bfile_iterator(FILE* is): _is(is) , _pos(0) ,_inbuff (0), _cptread(0)
{
_buffsize = 10000;
_buffer = (u_int64_t *) malloc(_buffsize*sizeof(u_int64_t));
int reso = fseek(_is,0,SEEK_SET);
advance();
}
~bfile_iterator()
{
if(_buffer!=NULL)
free(_buffer);
}
u_int64_t const& operator*() { return _elem; }
bfile_iterator& operator++()
{
advance();
return *this;
}
friend bool operator==(bfile_iterator const& lhs, bfile_iterator const& rhs)
{
if (!lhs._is || !rhs._is) { if (!lhs._is && !rhs._is) { return true; } else { return false; } }
assert(lhs._is == rhs._is);
return rhs._pos == lhs._pos;
}
friend bool operator!=(bfile_iterator const& lhs, bfile_iterator const& rhs) { return !(lhs == rhs); }
private:
void advance()
{
_pos++;
if(_cptread >= _inbuff)
{
int res = fread(_buffer,sizeof(u_int64_t),_buffsize,_is);
_inbuff = res; _cptread = 0;
if(res == 0)
{
_is = nullptr;
_pos = 0;
return;
}
}
_elem = _buffer[_cptread];
_cptread ++;
}
u_int64_t _elem;
FILE * _is;
unsigned long _pos;
u_int64_t * _buffer; // for buffered read
int _inbuff, _cptread;
int _buffsize;
};
//binary file to store uint64_t in file
class file_binary{
public:
file_binary(const char* filename)
{
_is = fopen(filename, "rb");
if (!_is) {
throw std::invalid_argument("Error opening " + std::string(filename));
}
}
~file_binary()
{
fclose(_is);
}
bfile_iterator begin() const
{
return bfile_iterator(_is);
}
bfile_iterator end() const {return bfile_iterator(); }
size_t size () const { return 0; }//todo ?
private:
FILE * _is;
};
//global array for to compute revcomp
char comp_tab[] = {
0, 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, 'T', 'V', 'G', 'H', 'E', 'F', 'C', 'D', 'I', 'J', 'M', 'L', 'K', 'N', 'O',
'P', 'Q', 'Y', 'S', 'A', 'A', 'B', 'W', 'X', 'R', 'Z', 91, 92, 93, 94, 95,
64, 't', 'v', 'g', 'h', 'e', 'f', 'c', 'd', 'i', 'j', 'm', 'l', 'k', 'n', 'o',
'p', 'q', 'y', 's', 'a', 'a', 'b', 'w', 'x', 'r', 'z', 123, 124, 125, 126, 127
};
/*structure to store the results of lookup in the PHF*/
struct hit{
bool map;
uint ctg;
uint pos;
bool strand;
string kseqm;//kmer matching
string seqname;
int score;
//constructor of the hit structure
hit(){
map=0;
ctg=0;
pos=0;
strand=0;
kseqm="";
seqname="";
score=0;
}
};
//class declaration
class KmerDB;
class Illumina;
class LongReads;
//threads varibales
struct parallelref {
pthread_mutex_t mut;
pthread_mutex_t pin;
vector<string> *pfiles;
KmerDB *db;
uint64_t *counter;
};
//thread function declaration
void * threaded_ref (void* args);//map in parallel bases from the reference
void * threaded_shortmap2 (void* args);//map in parallel short illumina reads
void * threaded_longmap (void* args);//map in parallel long PacBio/ONT reads
//Kmer database store Kmers in a MPHF and contigs coordinates for each key
class KmerDB
{
private :
uint KmerSize;
u_int64_t numberOfKmers;
int bytesPerKmer;
uint8_t* Kmers;//arrays of Kmers for exact mapping
//reference related variables
map< uint , string > id2seq;
map< string , uint > seq2id;
map< uint , uint > id2len;
vector <uint> pos;
vector <uint> ctg;
vector <bool> strand;
//MPHF related variables
hash<string> hash_fn;//hash function for strings to numbers
boophf_t * bphf ;//perfect hash function to ask in constant time to the array of Kmers
string infile;
probabilisticSet *ps;//array that store a finger print of the kmer for probabilistic search with FP rate of ~ 1/k*2
public:
pthread_mutex_t mutex;//to access to read files
pthread_mutex_t pinfo;//to print information from the threads
KmerDB(string kmerfile,uint kmerSize,string rfasta,uint threads){
//we read the file of kmers
KmerSize=kmerSize;
//allocate the array
ifstream readFile(kmerfile);
string line;
uint64_t nelem = 0;
FILE * key_file = NULL;
printf("Hashing uniq kmers...\n");
double t_begin,t_end; struct timeval timet;
gettimeofday(&timet, NULL); t_begin = timet.tv_sec +(timet.tv_usec/1000000.0);
//to obtain a unique tmp number for the uniq file that we use
infile=kmerfile+"."+to_string(getpid())+".hash64";
key_file = fopen(infile.c_str(),"w+");
u_int64_t current = 0;
while(getline(readFile,line)){
istringstream iss(line);
vector<string> tokens ( (istream_iterator<string>(iss)),istream_iterator< string > ());
current=getFhval(tokens[0].c_str(),kmerSize);;//we hash the current kmer
fwrite(¤t, sizeof(u_int64_t), 1, key_file);
pos.push_back(0);//we made the initialization of associated variables
ctg.push_back(0);//
strand.push_back(0);//
nelem++;
}
readFile.close();
//we close and then we remove the key file
fclose(key_file);
//cout << "File has " << nelem<<" kmers"<<endl;
gettimeofday(&timet, NULL); t_end = timet.tv_sec +(timet.tv_usec/1000000.0);
double elapsed = t_end - t_begin;
numberOfKmers=nelem;
printf("time to hash %llu kmers in %.2fs\n", numberOfKmers,elapsed);
//create the probabilistic structure with an error rate of 1/2^16 = 0,00001525878906 or 99,9999847412 effectiveneess
ps=new probabilisticSet(numberOfKmers,16);
//we build the perfect hash funtion
build_mphf(threads);
//we load the coordiantes for each kmer stored in the MPHF
load_reference_data(rfasta,threads);
}
uint64_t get_number_kmers(void){
return numberOfKmers;
}
void build_mphf(uint number_cpu){
double t_begin,t_end; struct timeval timet;
bphf = NULL;
printf("Construct a BooPHF with %lli elements \n",numberOfKmers);
gettimeofday(&timet, NULL); t_begin = timet.tv_sec +(timet.tv_usec/1000000.0);
double gammaFactor = 4.0; // lowest bit/elem is achieved with gamma=1, higher values lead to larger mphf but faster construction/query
//build the mphf from file
auto data_iterator = file_binary(infile.c_str());
bphf = new boomphf::mphf<u_int64_t,Custom_uint64_Hasher>(numberOfKmers,data_iterator,number_cpu,gammaFactor);
//we store a fingerprint for each key in the database
for (auto it = data_iterator.begin(); it != data_iterator.end(); ++it ){
uint64_t key=*(it);
//cout << *(it) <<endl;
uint64_t idx = bphf->lookup(key);
if(idx > numberOfKmers){
cout <<"Error building MPHF function key: "<<key<<" having an index larger than total number of kmers"<<endl;
exit(1);
}else{
//add a finger print to the probabilistic set
ps->add(idx,key);
}
}
//we remove temporary file
if( remove(infile.c_str()) != 0 ) {
cout << "Error deleting file "<< infile <<endl;
}
gettimeofday(&timet, NULL); t_end = timet.tv_sec +(timet.tv_usec/1000000.0);
double elapsed = t_end - t_begin;
printf("BooPHF constructed perfect hash for %llu keys in %.2fs\n", numberOfKmers,elapsed);
printf("boophf bits/elem : %f\n",(float) (bphf->totalBitSize())/numberOfKmers);
}
vector<uint64_t> mapkmer(string k){
vector<uint64_t>map;
uint64_t ifwd = bphf->lookup(getFhval(k.c_str(),KmerSize));
if(ifwd < numberOfKmers){
//if(compareKmer(k,hdata[ifwd])){
if(ps->exists(ifwd,getFhval(k.c_str(),KmerSize))){
map.push_back(ifwd);//kmer id
map.push_back(0);//kmers corresponde to foward
return map;
}
}
//we try the reverse kmer
string rk=revcomp(k);
uint64_t irev = bphf->lookup(getFhval(rk.c_str(),KmerSize));
if(irev < numberOfKmers){
//if(compareKmer(rk,hdata[irev])){
if(ps->exists(irev,getFhval(rk.c_str(),KmerSize))){
map.push_back(irev);//kmer id
map.push_back(1);//kmers correspond to reverse
return map;
}
}
//no mapping in fwd or rev kmer dont belong to the datase
map.push_back(ULLONG_MAX);
return map;
}
//we ask if a value exist in the database
vector<uint64_t> mapkmer(uint64_t hfwd, uint64_t hrev){
vector<uint64_t> map;
uint64_t ifwd = bphf->lookup(hfwd);
if(ifwd < numberOfKmers){
if(ps->exists(ifwd,hfwd)){
map.push_back(ifwd);//kmer id
map.push_back(0);//kmers corresponde to foward
return map;
}
}
//we try the reverse kmer
uint64_t irev = bphf->lookup(hrev);
if(irev < numberOfKmers){
if(ps->exists(irev,hrev)){
map.push_back(irev);//kmer id
map.push_back(1);//kmers correspond to reverse
return map;
}
}
//no mapping in fwd or rev kmer dont belong to the datase
map.push_back(ULLONG_MAX);
return map;
}
//heng li revcomp this is for printing only
string revcomp(string kmer){
int c0, c1;
int klen=kmer.length();
for (int i = 0; i < klen>>1; ++i) { // reverse complement sequence
c0 = comp_tab[(int)kmer[i]];
c1 = comp_tab[(int)kmer[klen - 1 - i]];
kmer[i] = c1;
kmer[klen - 1 - i] = c0;
}
if (klen & 1) // complement the remaining base
kmer[klen>>1] = comp_tab[(int)kmer[klen>>1]];
return kmer;
}
//I need to paralize this step because with big genomes take a lot of time
void load_reference_data(string fastafile, uint ntreads){
//to reads the fasta file we expect the fastafile uncompressed
kseq seq;
gzFile fp1 = gzopen(fastafile.c_str(),"r");
FunctorZlib r1;
kstream<gzFile, FunctorZlib> ks1(fp1, r1);
int l=0;
uint seqid=0;
double t_begin,t_end; struct timeval timet;
uint64_t query=0;
gettimeofday(&timet, NULL); t_begin = timet.tv_sec +(timet.tv_usec/1000000.0);
uint64_t length=0;
ofstream fastq;
vector<string> pfiles;//vector that save the name of fastq files;
int part=0;
string pid=to_string(::getpid());
fastq.open("refseq"+to_string(part)+"."+pid+".txt");
pfiles.push_back("refseq"+to_string(part)+"."+pid+".txt");
while((l = ks1.read(seq)) >= 0) {
if(seq.seq.length() < KmerSize){
continue;
}
if(length > 10000000){
length=0;
fastq.close();
part++;
fastq.open("refseq"+to_string(part)+"."+pid+".txt");
pfiles.push_back("refseq"+to_string(part)+"."+pid+".txt");
}
//we write to the file and then we store the variables
fastq << seqid <<" "<<seq.seq<<endl;
id2seq[seqid]=seq.name;//store contig name
id2len[seqid]=seq.seq.length();//store contig length
seq2id[seq.name]=seqid;
seqid++;
length+=seq.seq.length();
}
gzclose(fp1);
//multithreading version of database building
//we create the threads for concurrency in the alignments step
pthread_t *tab_threads= new pthread_t [ntreads];
//we create the mutex to reads sequence from fasta file in an atomic way
pthread_mutex_init(&mutex, NULL);
pthread_mutex_init(&pinfo, NULL);
parallelref tmp;
tmp.mut=mutex;//MUTEX to control access to files
tmp.pin=pinfo;//MUTEX to control the ouput fo files
tmp.pfiles=&pfiles;
//tmp.ks1=&ks2;
tmp.db=this;//pointer to MPHF
tmp.counter=&query;
//create the threads
for(int ii=0;ii<ntreads;ii++) {
pthread_create(&tab_threads[ii], NULL, threaded_ref, &tmp);
}
//wait for thread to finish
for(int ii=0;ii<ntreads;ii++)
{
pthread_join(tab_threads[ii], NULL);
}
gettimeofday(&timet, NULL); t_end = timet.tv_sec +(timet.tv_usec/1000000.0);
double elapsed = t_end - t_begin;
printf("Total time population database %.2fs\n",elapsed);
printf("A total of %llu kmers were indexed \n", query);
}
uint getKmerSize(void){
return KmerSize;
}
//return the position contig strand of the hit
hit lookup_kmer(string k){
vector< uint64_t > map=mapkmer(k);
hit h;
if(map[0] < numberOfKmers){
h.map=1;
h.ctg=ctg[map[0]];//contig position
h.pos=pos[map[0]];//mapping position
h.strand=0;//means foward
h.kseqm=k;
if(map[1] != strand[map[0]]){
h.strand=1;//means reverse strand
h.kseqm=revcomp(k);//we return the mapped kmer in reverse
}
//due to the probabilistic structure the pos can be 0
if(h.pos == 0){
h.map=0;
}
}
return h;
}
//return the position in contig strands of the hit
hit lookup_kmer(uint64_t hfwd, uint64_t hrev,string k){
vector< uint64_t > map=mapkmer(hfwd,hrev);
hit h;
if(map[0] < numberOfKmers){
h.map=1;
h.ctg=ctg[map[0]];//contig position
h.pos=pos[map[0]];//mapping position
h.strand=0;//means foward
h.kseqm=k;
if(map[1] != strand[map[0]]){
h.strand=1;//means reverse strand
h.kseqm=revcomp(k);//we return the mapped kmer in reverse
//we now that the kmer was mapped in reverse but we put in the sam file the kmer in foward, just to wing a little in speed
//h.kseqm=k;
}
//due to the probabilistic structure the pos can be 0 we says that the kmer is unmap
/*if(h.pos == 0){
h.map=0; reduce the speed a lot
}*/
}
return h;
}
//return the position in contig strands of the hit
hit lookup_kmer(uint64_t hfwd, uint64_t hrev){
vector< uint64_t > map=mapkmer(hfwd,hrev);
hit h;
if(map[0] < numberOfKmers){
h.map=1;
h.ctg=ctg[map[0]];//contig position
h.pos=pos[map[0]];//mapping position
h.strand=0;//means foward
h.kseqm="";
if(map[1] != strand[map[0]]){
h.strand=1;//means reverse strand
h.kseqm="";//we return the mapped kmer in reverse
}
//due to the probabilistic structure the pos can be 0 we says that the kmer is unmap
if(h.pos == 0){
h.map=0;
}
}
return h;
}
//return the number of sequences stored in the database
uint get_number_seq(void){
return id2seq.size();
}
//return the name of the sequence from the id
string get_seq_name(uint id){
return id2seq[id];
}
//return the length of the sequence from the id
uint get_seq_len(uint id){
return id2len[id];
}
uint get_seq_id(string name){
return seq2id[name];
}
//set references values
void set_references_values(uint ctgid, uint posctg, bool strandk, uint64_t index){
ctg[index]=ctgid;
pos[index]=posctg;
strand[index]=strandk;
}
void dump_database(void){
for (int i = 0; i < ctg.size() ; i++) {
cerr << i<<" "<<ctg[i]<<" "<<pos[i]<<" "<<strand[i]<<endl;
}
}
};
//we defined the parallel funtion to ask for reference basess in parallel
//todo:add variable to count how many uniq kmers were mapped
void * threaded_ref (void* args)
{
//casting of variables
parallelref *tmp = (parallelref*) args;
pthread_mutex_t *mutex = &tmp->mut;
pthread_mutex_t *pinfo = &tmp->pin;
KmerDB *dbt=(KmerDB *)tmp->db;
//kstream<int, FunctorRead> *ks1= (kstream<int, FunctorRead> *) tmp->ks1;
uint64_t *gcounter=(uint64_t *)tmp->counter;
vector <string> *files = ( vector<string> *) tmp->pfiles;
//we start the pthred execution
bool dojob=1;//variable to control thread execution
//we check the time spent
uint kmer_size;
kmer_size = dbt->getKmerSize();
uint64_t same=0;
uint64_t query=0;
double t_begin,t_end; struct timeval timet;
gettimeofday(&timet, NULL); t_begin = timet.tv_sec +(timet.tv_usec/1000000.0);
string file_to_process="";
while(dojob) {
//we try to get a file to process
pthread_mutex_lock(mutex);
if(files->size() > 0) {
file_to_process = files->back();
files->pop_back();
}else{
dojob=0;
}
pthread_mutex_unlock(mutex);
if(dojob) {
ifstream readFile2(file_to_process);
string line="";
while(getline(readFile2,line)) {
istringstream iss(line);
vector<string> tokens((istream_iterator<string>(iss)), istream_iterator<string>());
//we iterate the stored bases
int max_i = tokens[1].length() - kmer_size;
uint seqid = (uint)atoi(tokens[0].c_str());
//string seq=tokens[1];
uint64_t hfwd = 0, hrev = 0;
//we get both kmers in foward and reverse mers
uint64_t hVal = 0;
//int max_i= seq.seq.length() - KmerSize;
hVal = NTPC64(tokens[1].substr(0, kmer_size).c_str(), kmer_size, hfwd, hrev); // initial hash value
for (uint i = 0; i <= max_i; i++) {
vector<uint64_t> idx = dbt->mapkmer(hfwd, hrev);
if (idx[0] < ULLONG_MAX) {
dbt->set_references_values(seqid, i + 1, bool(idx[1]), idx[0]);
same++;
}
//get next kmer hash
hVal = NTPC64(tokens[1][i], tokens[1][i + kmer_size], kmer_size, hfwd, hrev); //recursive hash k+L
query++;
}
}
//we remove the tmp file
if( remove(file_to_process.c_str()) != 0 ) {
pthread_mutex_lock(pinfo);
cout << "Error deleting file "<< file_to_process <<endl;
pthread_mutex_unlock(pinfo);
}
}
}
gettimeofday(&timet, NULL); t_end = timet.tv_sec +(timet.tv_usec/1000000.0);
double elapsed3 = t_end - t_begin;
//we print some stats from thread information
pthread_mutex_lock(pinfo);
cout << "End of mapping in thread\n";
printf("Query of %llu kmer in %.2fs rate %.2f per second\n", query,elapsed3,query/elapsed3);
//adding variable to count the number of matched kmers
(*gcounter)+=same;
pthread_mutex_unlock(pinfo);
return NULL;
}
//thread related variables
struct targ{
pthread_mutex_t mut;
pthread_mutex_t pin;
pthread_mutex_t *pinm;
//to control samout
ofstream *sam;
uint *samflag;
uint *samp;
//file pointer to fastq/fasta file for reading
kstream<gzFile, FunctorZlib> *ks1;
kstream<gzFile, FunctorZlib> *ks2;
//parallel files names
vector<string> *pfiles;
//to control access to kmer database
KmerDB* db;
//to control access to illumina object
Illumina* ill;
//to control access to longRead object
LongReads* lon;
};
//funtion to sort a pair of kmers in a vector
bool compare_by_ctg_pos(const hit& ihs, const hit& rhs) {
return ((ihs.ctg < rhs.ctg) || (ihs.ctg == rhs.ctg && ihs.pos < rhs.pos));
}
//funtion to sort a pair of kmers by score
bool compare_score(const hit& ihs, const hit& rhs) {
return ((ihs.score > rhs.score));
}
//class to handle illumina paired reads
class Illumina{
private:
//variables related to library
int inferred_insert_size;
int inferred_orientation;
int inferred_std;
//advanced options for illumina
int vhs_ill;
int ms_ill;
int msr_ill;
vector<bool> obs_ori;
string fwdfile;
string revfile;
string prefix;
int compresed;
//return the reverse complement of a given orientation
uint get_rev_ori(uint ori){
switch(ori)
{
case 0: //FF -> RR
return 3;
case 1://RF -> FR
return 2;
case 2://FR->RF
return 1;
case 3://RR->FF
return 0;
default:
cout << "error in orientation "<<ori<<" unknow value"<<endl;
exit(1);
}
}
//return the orientation given two contigs
uint get_orientation(int a, int b){
switch(a){
case 0:
switch(b){
case 0:
return 0; //FF
case 1:
return 2; //FR
default:
cout << "error in orientation "<<a<<" "<<b<<" unknow value"<<endl;
exit(1);
}
case 1:
switch(b){
case 0://RF
return 1;
case 1:
return 3;//RR
default:
cout << "error in orientation "<<a<<" "<<b<<" unknow value"<<endl;
exit(1);
}
default:
cout << "error in orientation "<<a<<" "<<b<<" unknow value"<<endl;
exit(1);
}
}
vector<bool> get_ori_fwdrev(void){
vector<bool> ori(2,0);
switch(inferred_orientation){
case 0:
return ori;
case 1:
ori[0]=1;
return ori;
case 2:
ori[1]=1;
return ori;
case 3:
ori[0]=1;
ori[1]=1;
return ori;
default:
cout << "error in orientation "<<inferred_orientation<<" unknow value"<<endl;
exit(1);
}
}
//funtion to estimate the orienation and insert size given from a number of pairs
void get_pairs_dist_orientation(uint number_pairs){
//we open the fastq files
kseq fwd;
gzFile fp1 = gzopen(fwdfile.c_str(),"r");
FunctorZlib r1;
kstream<gzFile, FunctorZlib> ks1(fp1, r1);
kseq rev;
gzFile fp2 = gzopen(revfile.c_str(),"r");
FunctorZlib r2;
kstream<gzFile, FunctorZlib> ks2(fp2, r2);
int l=0,c=0;
uint64_t spairs=0;//mapped kmers pairs
uint64_t tpairs=0;//mapped total pairs
uint64_t asking=0;
uint64_t dist=0;//distance
map< uint, uint64_t > ori_insert; //to infer orientation
map< uint, uint64_t > ori_count; //
map<uint, vector<int> > values;
cout << "Estimating insert-size and orientation using "<<number_pairs<<" number of read pairs"<<endl;
double t_begin,t_end; struct timeval timet;
gettimeofday(&timet, NULL); t_begin = timet.tv_sec +(timet.tv_usec/1000000.0);
uint kmer_size;
kmer_size = kdb->getKmerSize();
hit indexs,indexf;
while(((l = ks1.read(fwd)) >= 0) && ((c = ks2.read(rev)) >= 0) && (tpairs < number_pairs)) {
int max_i= fwd.seq.length() - kmer_size;
int max_j= rev.seq.length() - kmer_size;
//we skypt pairs of reads shorter than the kmer length
if(max_i < 0 || max_j < 0){
continue;
}
tpairs++;
uint64_t hVal1=0,hfwd1=0,hrev1=0;
hVal1 = NTPC64(fwd.seq.substr(0, kmer_size).c_str(), kmer_size, hfwd1, hrev1); // initial hash value for fwd
vector<hit> tfwd;
int max_h=0;
for (int i = 0; i <= max_i; i++) {
indexf = kdb->lookup_kmer(hfwd1, hrev1);
if (indexf.map) {
tfwd.push_back(indexf);
max_h++;
if(max_h > 9){
break;
}
}
hVal1 = NTPC64(fwd.seq[i], fwd.seq[i + kmer_size], kmer_size, hfwd1, hrev1); //recursive hash k+L
asking++;
}
//we try to map the reverse if we mapped the forward read
if(tfwd.size() > 9){
uint64_t hVal2=0,hfwd2=0,hrev2=0;
hVal2 = NTPC64(rev.seq.substr(0, kmer_size).c_str(), kmer_size, hfwd2, hrev2); // initial hash value for rev
vector<hit> trev;
int max_h=0;
for (int i = 0; i <= max_j; i++) {
indexf = kdb->lookup_kmer(hfwd2, hrev2);
if (indexf.map) {
trev.push_back(indexf);
max_h++;
if (max_h > 9) {
break;
}
}
hVal2 = NTPC64(rev.seq[i], rev.seq[i + kmer_size], kmer_size, hfwd2, hrev2); //recursive hash k+L
asking++;
}
//we got the maximum score using the function
if(trev.size() > 9){
//we sort the hits by contig and post
sort(tfwd.begin(),tfwd.end(),compare_by_ctg_pos);
sort(trev.begin(),trev.end(),compare_by_ctg_pos);
//now we get the mayority or in the case of no mayority the max
hit bfwd=compute_maj_max(tfwd,fwd.seq.length());
hit brev=compute_maj_max(trev,rev.seq.length());
//we fill the insert size and the orientation if we had a good pairs of reads
if(bfwd.score > 7 && brev.score > 7){
if(bfwd.ctg == brev.ctg){
//we check if they are in foward or reverse
uint64_t insert_size=0;
uint ori=get_orientation((int)bfwd.strand,(int)brev.strand);
if(bfwd.pos > brev.pos){
insert_size=(bfwd.pos-brev.pos);
ori=get_rev_ori(ori);
}else{
insert_size=(brev.pos-bfwd.pos);
}
//we define a maximum insert size
ori_count[ori]++;
ori_insert[ori] += insert_size;
dist += insert_size; //both contigs are in reverse
values[ori].push_back(int(insert_size));
spairs++;
}
}
}
}
}
gzclose(fp1);//closing file descriptors
gzclose(fp2);//closing file descriptors
gettimeofday(&timet, NULL); t_end = timet.tv_sec +(timet.tv_usec/1000000.0);
double elapsed3 = t_end - t_begin;
cout << "End of insert-size and orientation inference\n";
printf("Query of %llu kmer-pairs in %.2fs\n", asking,elapsed3);
printf("Query of %llu pairs in %.2fs\n", tpairs,elapsed3);
printf("found %llu kmer-pairs at average dist=%f\n",spairs,float(dist/spairs));
//we infer the orientaton of the librery
uint64_t max_count=0;
for (map< uint , uint64_t>::iterator it=ori_count.begin(); it!=ori_count.end(); ++it){
cout << "Orientation "<<it->first << " " << it->second << " average_insert_size= "<< int(ori_insert[it->first]/it->second) << endl;
if(max_count < it->second){
max_count=it->second;
inferred_orientation=it->first;
}
}
//to compute average and insert size we will use [Q2,Q3] of sorted array from observations
sort(values[inferred_orientation].begin(),values[inferred_orientation].end());
//we discard 10% outlayers from begin and end
int lower=int(0.1 * values[inferred_orientation].size());
int upper=int(0.9 * values[inferred_orientation].size());
uint64_t q2q3_avg=0;
for (int i = lower; i < upper ; i++) {
q2q3_avg+=values[inferred_orientation][i];
}
q2q3_avg=uint64_t(q2q3_avg/(upper - lower));
//cout << "inferred average from [Q2,Q3] " << q2q3_avg<<" lower="<<lower<<" upper="<<upper<<" total obs="<<upper-lower<<endl;
inferred_insert_size=int(q2q3_avg);
//compute std
double sqtotal=0;
for(int i=lower;i<upper; i++){
// cout << values[inferred_orientation][i]<<" "<<inferred_insert_size<<" "<<inferred_insert_size-values[inferred_orientation][i]<<endl;
sqtotal+=pow((inferred_insert_size-values[inferred_orientation][i]),2);
//cout << sqtotal <<endl;
}
//cout << "inferred std from [Q2,Q3] "<< sqrt(sqtotal2/(upper-lower)) <<endl;
//we split the orientation in fwd and rev
obs_ori=get_ori_fwdrev();
inferred_std=int(sqrt(sqtotal/(upper-lower)));
//the maximal std that we allow is 15% of the inferred insert_size
if(((float)inferred_std/(float)inferred_insert_size) > 0.15){
cout << "adjusting inferred_std to 10% of inferred insert_size due that std > 0.15 "<< inferred_std <<endl;
//we adjust the inferred_std to 10% of the average insert_size distribution
inferred_std=int((float)inferred_insert_size * 0.1);
cout << "new adjusted std = "<< inferred_std <<endl;
}
cout << "Inferred Orientation = " << inferred_orientation <<endl;
cout << "Inferred average insert size = " << inferred_insert_size<<endl;
cout <<"Inferred std of insert size = " << inferred_std<<endl;
cout << "Number of pairs to infer avg/std = "<<upper-lower<<endl;
}
public:
pthread_mutex_t mutex;//to access to read files
pthread_mutex_t pinfo;//to print information from the threads
//variables related to KmerDB
KmerDB *kdb;//pointer to KmerDB for get mapping positions
//constructor of the class
Illumina(string fprefix, string file1, string file2, int vhs_ill1, int ms_ill1, int msr_ill1, KmerDB *kmer_db){
fwdfile=file1;
revfile=file2;
if((fwdfile.find(".gz")!=string::npos && revfile.find(".gz") !=string::npos) || (fwdfile.find(".gzip")!=string::npos && revfile.find(".gzip")!=string::npos)){
cout << fwdfile <<" "<<revfile<<" has file extension of gzip files(*.gz or *.gzip)\n";
compresed=1;//not compressed
}else{
if((fwdfile.find(".fq")!=string::npos && revfile.find(".fq") !=string::npos) || (fwdfile.find(".fastq")!=string::npos && revfile.find(".fastq")!=string::npos)){
cout << fwdfile <<" "<<revfile<<" are text based *.fq or *.fastq\n";
compresed=2;//gzip compressed
}else{
cout << fwdfile <<" "<<revfile<<" has not the file extension .gz or .fq or *.fastq\n";
cout << "not supported fastq file\n";
exit(1);
}
}
prefix=fprefix;
//we obtain a connector to KmerDB
kdb=kmer_db;
cout << "Total Kmers stored in datase "<<kdb->get_number_kmers()<<endl;
//set the advanced options
vhs_ill=vhs_ill1;
ms_ill=ms_ill1;
msr_ill=msr_ill1;
//we compute the insert size distribution and orientation using 10000 pairs
get_pairs_dist_orientation(100000);
}
void mapshortreads(uint samout, uint ntreads){
gzFile fp1 = gzopen(fwdfile.c_str(),"r");
FunctorZlib r1;
kstream<gzFile, FunctorZlib> ks1(fp1, r1);
gzFile fp2 = gzopen(revfile.c_str(),"r");
FunctorZlib r2;
kstream<gzFile, FunctorZlib> ks2(fp2, r2);
//we close the fastq file because we already split the files into other structures
//we create the threads for concurrency in the alignments step
pthread_t *tab_threads= new pthread_t [ntreads];
//we create the mutex to reads sequence from fasta file in an atomic way
pthread_mutex_init(&mutex, NULL);
pthread_mutex_init(&pinfo, NULL);
ofstream samfile;
uint kmer_size=kdb->getKmerSize();
samfile.open(prefix+".FastSG_K"+to_string(kmer_size)+".sam");
//we need to output sam header to the samfile
samfile <<"@HD\tVN:1.0\tSO:unsorted"<<endl;
for (int i=0; i < kdb->get_number_seq(); i++){
string seqn=kdb->get_seq_name(i);
uint seql=kdb->get_seq_len(i);
samfile <<"@SQ\tSN:" << seqn <<"\tLN:"<< seql <<endl;
}
samfile <<"@PG\tID:" << prefix << "\tPN:FAST-SG\tVN:1.0\tCL:FAST-SG pair-end modes"<<endl;
targ tmp;//struct to share data whit threads
tmp.mut=mutex;//MUTEX to control access to files
tmp.pin=pinfo;//MUTEX to control the ouput fo files
tmp.db=kdb;//pointer to MPHF
tmp.ks1=&ks1;//pointer to fastq files fwd
tmp.ks2=&ks2;//pointer to fastq files reverse
tmp.ill=this;
//we need to create samoutput
uint sampc=1;
tmp.sam=&samfile;
tmp.samflag=&samout;
tmp.samp=&sampc;//we init the counter in 0
//create the threads
for(int ii=0;ii<ntreads;ii++) {
pthread_create(&tab_threads[ii], NULL, threaded_shortmap2, &tmp);
}
//wait for thread to finish
for(int ii=0;ii<ntreads;ii++)
{
pthread_join(tab_threads[ii], NULL);
}
//closing samfile
samfile.close();
gzclose(fp1);
gzclose(fp2);