-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSparsePainter.cpp
3906 lines (3419 loc) · 140 KB
/
SparsePainter.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
// please compile with "make"
// g++ -I./armadillo-12.6.5/include SparsePainter.cpp -o SparsePainter -lz -fopenmp -lpthread -L./armadillo-12.6.5 -larmadillo -llapack -lblas -std=c++0x -g -O3 -Wl,-rpath=./armadillo-12.6.5
#ifdef _OPENMP
#include <omp.h>
#else
#define omp_get_thread_num() 0
#endif
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <regex>
#include <unordered_map>
#include <algorithm>
#include <random>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <sstream>
#include <utility>
#include <armadillo>
#include <set>
#include "gzstream.h"
#include "gzstream.C"
using namespace std;
using namespace arma;
class hVec { // A sparse vector format
public:
vector<int> k; // the keys that are in the vector
unordered_map<int, double> v; // the values, stored as a map from keys to values
int len; // nominal length of the vector; currently unused
double x0; // default value for entries
hVec(){
// Create an empty vector
len=0;
x0=0;
};
hVec(int len,
double x0){
// Create a vector of length len filled with x0
this->len=len;
this->x0=x0;
};
hVec(vector<int> idx,
vector<double> val,
int len,
double x0){
// Create a vector of length len filled with x0 except at idx which contains val
this->len=len;
this->x0=x0;
for(int i=0;i<idx.size();++i){
k.push_back(idx[i]);
v[idx[i]]=val[i];
}
};
void setdefault(double x0){
// Change the default value
this->x0=x0;
};
void setnocheck(int p,
double val){
// Set a value, should be known to be in the keys
v[p]=val;
};
void set(int p,
double val){
//Safely set a value
if(!in(p)) k.push_back(p);
setnocheck(p,val);
};
void setall(vector<int> p,
vector<double> val){
for(int i=0; i<p.size();++i){
if(!in(p[i])) k.push_back(p[i]);
setnocheck(p[i],val[i]);
}
}
bool in(int p){
// Check if a value has a non-default entry
if(v.find(p)==v.end()) return(false);
return(true);
};
double get(int p){
// Get a value from the vector: either its set value or the default if not present
if(!in(p)){
return(x0);
}else{
return(v[p]);
}
};
vector<double> getall(const vector<int>& idx){
// Get values from the vector: either its set value or the default if not present
vector<double> values(idx.size());
for(int i=0;i<idx.size();++i){
if(!in(idx[i])) {
values[i]=x0;
} else {
values[i]=v[idx[i]];
}
}
return(values);
}
};
class hMat {
public:
vector<hVec> m; // sparse matrix, i.e. a vector of hVec's
int d1; // number of rows; currently nominal
int d2; // Number of columns; should be equal to length(m)
hMat(int d1){
// Empty matrix with d1 rows (can append columns)
this->d1=d1;
d2=0;
};
hMat(int d1,
int d2,
double x0=0.0){
// Create a d1 by d2 matrix taking value x0
this->d1=d1;
this->d2=d2;
for(int i=0;i<d2;++i){
// each element in m is a column vector
m.push_back(hVec(d1,x0));
}
};
void appendColumn(double x0){
// Append a default column
++d2;
m.push_back(hVec(d1,x0));
};
void appendColumn(vector<int> idx,
vector<double> vals,
double x0){
// Append a filled column
++d2;
m.push_back(hVec(idx,vals,d1,x0));
};
};
class hAnc {
public:
//use hashmap to find the positions (rows) of each ancestry
unordered_map<int, vector<int>> pos;
hAnc(const vector<int>& ref) {
// Traverse the ref vector and store the row position corresponding to each value in unordered_map
for (int i = 0; i < ref.size(); i++) {
int value = ref[i];
if (pos.find(value) == pos.end()) { //if this value doesn't exist
pos[value] = vector<int>{i};
} else {
pos[value].push_back(i);
}
}
};
vector<int> findrows(int value) const {
// here the class of it is unordered_map<int, vector<int>>::const_iterator
// we use auto to simplify
auto it = pos.find(value);
if (it != pos.end()) {
return it->second;
} else { // if the value doesn't exist, return an empty vector
return vector<int>();
}
};
};
/////////////////////beginning of pbwt contents///////////////////////////
void free_PBWT_memory(vector<vector<bool>> &panel, int** &prefix, int** &divergence, int** &u, int** &v) {
// First, delete the inner arrays of prefix, divergence, u, and v
// Note: Since temp1, temp2, temp3, and temp4 are continuous blocks of memory
// you only need to delete their base pointers (the pointers originally returned by 'new').
delete[] prefix[0]; // which is temp1
delete[] divergence[0]; // which is temp2
delete[] u[0]; // which is temp3
delete[] v[0]; // which is temp4
// Now, delete the outer arrays of prefix, divergence, u, and v
delete[] prefix;
delete[] divergence;
delete[] u;
delete[] v;
// Clear the panel vector and minimize its memory usage
panel.clear();
vector<vector<bool>>().swap(panel); // This technique is used to shrink the vector's capacity to fit its size.
// Nullify the pointers to ensure that they don't dangle.
prefix = nullptr;
divergence = nullptr;
u = nullptr;
v = nullptr;
}
void PBWT(vector<vector<bool>> &panel, int **prefix, int **divergence,
int **u, int **v, int num, int N){
for (int i = 0; i<num; ++i){
prefix[i][0] = i;
divergence[i][0] = 0;
}
for (int k = 0; k<N; ++k){
int u2 = 0, v2 = 0, p = k+1, q = k+1;
vector<int> a,b,d,e;
for (int i = 0; i<num; ++i){
u[i][k] = u2;
v[i][k] = v2;
if (divergence[i][k] > p) { p = divergence[i][k];}
if (divergence[i][k] > q) { q = divergence[i][k];}
if (!panel[prefix[i][k]][k]){
a.push_back(prefix[i][k]);
d.push_back(p);
++u2;
p = 0;
}
else{
b.push_back(prefix[i][k]);
e.push_back(q);
++v2;
q = 0;
}
}
for (int i = 0; i<num; ++i){
v[i][k] += a.size();
if (i < a.size()){
prefix[i][k+1] = a[i];
divergence[i][k+1] = d[i];
}
else{
prefix[i][k+1] = b[i-a.size()];
divergence[i][k+1] = e[i-a.size()];
}
}
}
}
void ReadVCF(const string inFile,
const string qinFile,
vector<vector<bool>> &panel,
const int N,
const int M,
const int qM,
const bool haploid){
cout << "Read reference data with "<<N<<" SNPs for "<<M-qM<<" haploptypes";
if(inFile!=qinFile){
cout<<" and target data with "<<N<<" SNPs for "<<qM<<" haploptypes" << endl;
}else{
cout<<endl;
}
igzstream in,qin;
if(inFile==qinFile){
string line = "##";
in.open(inFile.c_str());
if (!in) {
cerr << "Error: unable to open file: " << inFile << endl;
abort();
}
stringstream linestr;
int x = 0;
char y = 0;
while (line[1] == '#')
getline(in, line);
for(int j = 0; j<N; ++j){
getline(in, line);
linestr.str(line);
linestr.clear();
for (int i = 0; i<9; ++i){
linestr >> line;
}
if(!haploid){
for (int i = 0; i<(M-qM)/2; ++i){
linestr >> x >> y;
if(x==0 || x==1){
panel[i*2][j] = (bool)x;
}else{
cerr << "Error: Genotypes are not represented as 0 or 1 in " << inFile << endl;
abort();
}
linestr >> x;
if(x==0 || x==1){
panel[i*2 + 1][j] = (bool)x;
}else{
cerr << "Error: Genotypes are not represented as 0 or 1 in " << inFile << endl;
abort();
}
}
}else{
for (int i = 0; i<M-qM; ++i){
linestr >> x;
if(x==0 || x==1){
panel[i][j] = (bool)x;
}else{
cerr << "Error: Genotypes are not represented as 0 or 1 in " << inFile << endl;
abort();
}
}
}
}
in.close();
}else{
string line = "##", qline = "##";
in.open(inFile.c_str());
if (!in) {
cerr << "Error: unable to open file: " << inFile << endl;
abort();
}
qin.open(qinFile.c_str());
if (!qin) {
cerr << "Error: unable to open file: " << qinFile << endl;
abort();
}
stringstream linestr, qlinestr;
int x = 0;
char y = 0;
while (line[1] == '#')
getline(in, line);
while (qline[1] == '#')
getline(qin, qline);
for(int j = 0; j<N; ++j){
getline(in, line);
getline(qin, qline);
linestr.str(line);
linestr.clear();
qlinestr.str(qline);
qlinestr.clear();
for (int i = 0; i<9; ++i){
linestr >> line;
qlinestr >> qline;
}
if(!haploid){
for (int i = 0; i<(M-qM)/2; ++i){
linestr >> x >> y;
if(x==0 || x==1){
panel[i*2][j] = (bool)x;
}else{
cerr << "Error: Genotypes are not represented as 0 or 1 in " << inFile << endl;
abort();
}
linestr >> x;
if(x==0 || x==1){
panel[i*2 + 1][j] = (bool)x;
}else{
cerr << "Error: Genotypes are not represented as 0 or 1 in " << inFile << endl;
abort();
}
}
for (int i = (M-qM)/2; i < M/2; ++i){
qlinestr >> x >> y;
if(x==0 || x==1){
panel[i*2][j] = (bool)x;
}else{
cerr << "Error: Genotypes are not represented as 0 or 1 in " << qinFile << endl;
abort();
}
qlinestr >> x;
if(x==0 || x==1){
panel[i*2 + 1][j] = (bool)x;
}else{
cerr << "Error: Genotypes are not represented as 0 or 1 in " << qinFile << endl;
abort();
}
}
}else{
for (int i = 0; i<M-qM; ++i){
linestr >> x;
if(x==0 || x==1){
panel[i][j] = (bool)x;
}else{
cerr << "Error: Genotypes are not represented as 0 or 1 in " << inFile << endl;
abort();
}
}
for (int i = (M-qM); i < M; ++i){
qlinestr >> x;
if(x==0 || x==1){
panel[i][j] = (bool)x;
}else{
cerr << "Error: Genotypes are not represented as 0 or 1 in " << qinFile << endl;
abort();
}
}
}
}
in.close();
qin.close();
}
}
void Readphase_donor(const string inFile,
vector<vector<bool>> &panel,
const int N,
const int M,
const int qM) {
cout << "Read reference data with "<<N<<" SNPs for "<<M-qM<<" haploptypes." << endl;
// read the data
igzstream in;
in.open(inFile.c_str());
if (!in) {
cerr << "Error: unable to open file: " << inFile << endl;
abort();
}
string line;
// Read and discard the first three lines
for (int i = 0; i < 3; ++i) {
getline(in, line);
}
// Read the remaining lines and store the binary data of each line in 'panel'
// We are reading the first M-qM haplotypes
for(int i=0; i<M-qM; ++i) {
// i indicates which sample we are looking at
getline(in, line);
vector<bool> panelsnp;
// convert SNP data to binary
for (char c : line) {
panelsnp.push_back(c == '1');
}
int Oid = i;
// add snps to the panel
panel.push_back(vector<bool>());
panel[i].resize(N);
for (int k = 0; k<N; ++k){ // for every SNP
panel[i][k] = panelsnp[k];
} // end loop over snps
}
cout<<"Finish reading reference data"<<endl;
in.close();
}
vector<int> getorder(const vector<double>& vec) {
vector<int> order(vec.size());
iota(order.begin(), order.end(), 0);
stable_sort(order.begin(), order.end(), [&vec](int i, int j) {
return vec[i] < vec[j];
});
unordered_map<double, vector<int>> groups;
for (int i : order) {
groups[vec[i]].push_back(i);
}
random_device rd;
mt19937 g(rd());
for (auto& group : groups) {
shuffle(group.second.begin(), group.second.end(), g);
}
vector<int> randomized_order;
for (int i : order) {
randomized_order.push_back(groups[vec[i]].back());
groups[vec[i]].pop_back();
}
return randomized_order;
}
bool containsIndex(const vector<int>& fullidx,
int starttemp,
int endtemp) {
bool contain=false;
for(int i : fullidx) {
if(i >= starttemp && i <= endtemp) {
contain=true;
break;
}
}
return(contain);
}
tuple<vector<int>,vector<int>,vector<int>,vector<int>> longMatchpbwt(const int L_initial,
vector<vector<bool>> &panel,
int **prefix,
int **divergence,
int **u,
int **v,
int minmatch,
vector<double> &gd,
vector<int>& queryidx,
const int N,
const int M,
const int qM,
const int L_minmatch,
const int ncores,
const bool samefile,
const bool phase,
const string qinFile){
igzstream in;
string line;
if(phase & !samefile){
in.open(qinFile.c_str());
if (!in) {
cerr << "Error: unable to open file: " << qinFile << endl;
abort();
}
// Read and discard the first three lines
for (int i = 0; i < 3; ++i) {
getline(in, line);
}
}
// match of which query sample
vector<int> queryidall={0};
// match to which reference sample (donor)
vector<int> donorid;
// start position of match
vector<int> startpos;
// end position of match
vector<int> endpos;
struct LoopResult {
vector<int> donorid;
vector<int> startpos;
vector<int> endpos;
int queryid;
};
// define a results vector
vector<LoopResult> allResults(queryidx.size());
//read data for target haplotypes
// store ncores lines of target data
// paneltarget has ncore rows and N columns
int nind=queryidx.size();
int nind_left=nind;
omp_set_num_threads(ncores);
if(samefile){
minmatch++;
}
while(nind_left>0){
int ncores_use = (ncores < nind_left) ? ncores : nind_left;
vector<vector<bool>> panelsnp;
if(samefile){
panelsnp=vector<vector<bool>>(ncores_use,vector<bool>(N));
for(int i=nind-nind_left; i<nind-nind_left+ncores_use; ++i) {
for(int j=0;j<N;++j){
panelsnp[i-nind+nind_left][j]=panel[i][j];
}
}
}else{
if(!phase){
panelsnp=vector<vector<bool>>(ncores_use,vector<bool>(N));
for(int i=nind-nind_left; i<nind-nind_left+ncores_use; ++i) {
for(int j=0;j<N;++j){
panelsnp[i-nind+nind_left][j]=panel[M-qM+i][j];
}
}
}else{
panelsnp=vector<vector<bool>>(ncores_use);
for(int i=nind-nind_left; i<nind-nind_left+ncores_use; ++i) {
getline(in, line);
for (char c : line) {
panelsnp[i-nind+nind_left].push_back(c == '1');
}
}
}
}
cout<<"Finding matches with PBWT for target haplotypes "<<nind-nind_left<<"-"<<nind-nind_left+ncores_use-1<<endl;
#pragma omp parallel for
for (int idx=nind-nind_left; idx<nind-nind_left+ncores_use; ++idx) {
int *dZ;
dZ = new int[M];
for (int i = 0; i<M; i++){
dZ[i] = 0;
}
int *t = new int[N+1];
int *zd = new int[N+2], *bd = new int[N+2];
int i = queryidx[idx];
int L=L_initial;
int prevL=L;
int Oid = i;
t[0] = 0;
for (int k=0; k<N; ++k){
if (t[k]!=M-qM)
if (!panelsnp[Oid-nind+nind_left][k])
t[k+1] = u[t[k]][k];
else
t[k+1] = v[t[k]][k];
else
if (!panelsnp[Oid-nind+nind_left][k])
t[k+1] = v[0][k];
else
t[k+1] = M-qM;
}
zd[N+1] = bd[N+1] = N;
for (int k = N; k>=0; --k){
zd[k] = min(zd[k+1],k);
bd[k] = min(bd[k+1],k);
if (t[k]!=0)
while(zd[k]>0 &&
panelsnp[Oid-nind+nind_left][zd[k]-1]
== panel[prefix[t[k]-1][k]][zd[k]-1])
zd[k]--;
else
zd[k] = k;
if (t[k]!=M-qM)
while(bd[k]>0 &&
panelsnp[Oid-nind+nind_left][bd[k]-1]
== panel[prefix[t[k]][k]][bd[k]-1])
bd[k]--;
else
bd[k] = k;
}
// below using while loop to update L and ensure at least minmatch matches at each SNP
vector<int> donoridtemp;
vector<int> startpostemp;
vector<int> endpostemp;
vector<int> nomatchsnp;
vector<int> nmatch(N,0);
int times=0;
bool allsnpmatches=false;
vector<int> local_donorid;
vector<int> local_startpos;
vector<int> local_endpos;
while(!allsnpmatches){
vector<bool> addmatch(N,false);
if(times!=0){
for(int w=0;w<nomatchsnp.size();++w){
for(int s=0;s<prevL;++s){
int pos=nomatchsnp[w]+s;
if(pos>=N) break;
addmatch[pos]=true;
}
}
}
int f, g, ftemp, gtemp;
f = g = t[0];
for(int k = 0; k<N; ++k){
if (g == M-qM){
if (f == M-qM){
if (!panelsnp[Oid-nind+nind_left][k]){
ftemp = M-qM;
f = v[0][k];
}
else{
ftemp = v[0][k];
f = M-qM;
}
}
else{
if (!panelsnp[Oid-nind+nind_left][k]){
ftemp = v[f][k];
f = u[f][k];
}
else{
ftemp = u[f][k];
f = v[f][k];
}
}
if (!panelsnp[Oid-nind+nind_left][k]){
gtemp = M-qM;
g = v[0][k];
}
else{
gtemp = v[0][k];
g = M-qM;
}
}
else
if (!panelsnp[Oid-nind+nind_left][k]){
ftemp = v[f][k];
gtemp = v[g][k];
f = u[f][k];
g = u[g][k];
}
else{
ftemp = u[f][k];
gtemp = u[g][k];
f = v[f][k];
g = v[g][k];
}
while (ftemp != gtemp){
int end=k-1;
if(times==0){
int start=dZ[prefix[ftemp][k+1]];
donoridtemp.push_back(prefix[ftemp][k+1]);
startpostemp.push_back(start);
endpostemp.push_back(end);
for(int q=start;q<=end;++q){
nmatch[q]++;
}
++ftemp;
}else{
if(addmatch[end]){
int start=dZ[prefix[ftemp][k+1]];
//add new matches with new L
if(end-start+1<prevL){
donoridtemp.push_back(prefix[ftemp][k+1]);
startpostemp.push_back(start);
endpostemp.push_back(end);
++ftemp;
for(int q=start;q<=end;++q){
nmatch[q]++;
}
}else{
++ftemp;
}
}else{
++ftemp;
}
}
}
if (f==g){
if (k+1-zd[k+1] == L){
--f;
//store divergence
dZ[prefix[f][k+1]] = k+1-L;
}
if (k+1-bd[k+1] == L){
//store divergence
dZ[prefix[g][k+1]] = k+1-L;
++g;
}
}
if (f!=g) {
while (divergence[f][k+1] <= k+1 - L){
--f;
//store divergence
dZ[prefix[f][k+1]] = k+1-L;
}
while (g<M-qM && divergence[g][k+1] <= k+1-L){
//store divergence
dZ[prefix[g][k+1]] = k+1-L;
++g;
}
}
}
while (f != g){
int end2=N-1;
if(times==0){
int start2=dZ[prefix[f][N]];
donoridtemp.push_back(prefix[f][N]);
startpostemp.push_back(start2);
endpostemp.push_back(end2);
for(int q=start2;q<=end2;++q){
nmatch[q]++;
}
++f;
}else{
if(addmatch[end2]){
int start2=dZ[prefix[f][N]];
//add new matches with new L
if(end2-start2+1<prevL){
donoridtemp.push_back(prefix[f][N]);
startpostemp.push_back(start2);
endpostemp.push_back(end2);
++f;
for(int q=start2;q<=end2;++q){
nmatch[q]++;
}
}else{
++f;
}
}else{
++f;
}
}
}
if(L<=L_minmatch){
allsnpmatches = true;
}else{
if(times==0){
// find which SNPs don't have minmatch matches
for(int j=0;j<N;++j){
if (nmatch[j] < minmatch) {
nomatchsnp.push_back(j);
}
}
}else{
vector<int> nomatchsnptemp=nomatchsnp;
nomatchsnp.clear();
// find which SNPs still don't have minmatch matches
for(int j=0;j<nomatchsnptemp.size();++j){
if (nmatch[nomatchsnptemp[j]] < minmatch) {
nomatchsnp.push_back(nomatchsnptemp[j]);
}
}
}
if(nomatchsnp.size()==0){
// stop when all SNPs have minmatch matches
allsnpmatches = true;
}else{
// update L
prevL=L;
L=(prevL+1)/2;
if(L<L_minmatch) L=L_minmatch;
times++;
}
}
}
delete [] t;
delete [] zd;
delete [] bd;
//below we remove shorter matches while ensuring at least minmatch matches at each SNP
//information of matches is stored in donoridtemp, startpostemp and endpostemp
//number of matches at each SNP are stored in nmatch
//we first sort the genetic distance of each match
vector<double> gdmatch(startpostemp.size());
for(int mi=0; mi<startpostemp.size();++mi){
gdmatch[mi]=gd[endpostemp[mi]]-gd[startpostemp[mi]];
}
vector<int> length_order=getorder(gdmatch);
vector<int> fullidx; // record which SNP fewer than only minmatch matches
vector<int> nmatch_output(N, 0);
for(int q=0;q<N;++q){
fullidx.push_back(q);
}
for(int mi=length_order.size()-1;mi>=0;--mi){
int starttemp=startpostemp[length_order[mi]];
int endtemp=endpostemp[length_order[mi]];
if(containsIndex(fullidx,starttemp,endtemp)){
local_startpos.push_back(starttemp);
local_endpos.push_back(endtemp);
local_donorid.push_back(donoridtemp[length_order[mi]]);
for(int q=starttemp;q<=endtemp;++q){
nmatch_output[q]++;
if(nmatch_output[q]==minmatch){
auto it = remove(fullidx.begin(), fullidx.end(), q);
fullidx.erase(it, fullidx.end());
}
}
}
if(fullidx.size()==0) {
break;
}
}
//record the position of the next start position of query haplotype
//such that we know how many matches are there for this query haplotype
LoopResult result;
result.donorid = local_donorid;
result.startpos = local_startpos;
result.endpos = local_endpos;
result.queryid = local_startpos.size();
allResults[idx] = result;
}
nind_left=nind_left-ncores_use;
}
for (const auto& result : allResults) {
donorid.insert(donorid.end(), result.donorid.begin(), result.donorid.end());
startpos.insert(startpos.end(), result.startpos.begin(), result.startpos.end());
endpos.insert(endpos.end(), result.endpos.begin(), result.endpos.end());
queryidall.push_back(queryidall.back() + result.queryid);
}
tuple<vector<int>,vector<int>,vector<int>,vector<int>> results(queryidall,donorid,startpos,endpos);
return(results);
}
tuple<vector<int>,vector<int>,vector<int>,vector<int>> do_pbwt(int& L_initial,
vector<double> gd,
vector<int>& queryidx,
int ncores,
const int M,
const int N,
const int qM,
int minmatch,
int L_minmatch,
const string reffile,
const string targetfile,
const bool haploid,
const bool phase){
int nrow_panel;
bool samefile;
if(reffile==targetfile){
nrow_panel=M-qM;
samefile=true;
}else{
nrow_panel=M;
samefile=false;
}
vector<vector<bool>> panel;
int **prefix, **divergence, **u, **v;
if (!phase) {
panel = vector<vector<bool>>(nrow_panel, vector<bool>(N));
ReadVCF(reffile,targetfile,panel,N,M,qM,haploid);
}else{
Readphase_donor(reffile,panel,N,M,qM);
}
cout<<"Begin building PBWT for reference haplotypes"<<endl;
prefix = new int*[M-qM];
divergence = new int*[M-qM];
u = new int*[M-qM];
v = new int*[M-qM];
int *temp1 = new int[(long long)(M-qM)*(N+1)];
int *temp2 = new int[(long long)(M-qM)*(N+1)];
int *temp3 = new int[(long long)(M-qM)*(N)];
int *temp4 = new int[(long long)(M-qM)*(N)];
for (long long i = 0; i<M-qM; i++){
prefix[i] = &(temp1[i*(N+1)]);
divergence[i] = &(temp2[i*(N+1)]);
u[i] = &(temp3[i*(N)]);
v[i] = &(temp4[i*(N)]);
}
PBWT(panel, prefix, divergence, u, v, M-qM, N);
cout<<"Finish building PBWT for reference haplotypes"<<endl;
while(L_initial>N){
L_initial=ceil(L_initial/2);
cout<<"Initial L cannot be greater than N, reducing L to "<<L_initial<<endl;
}
tuple<vector<int>,vector<int>,vector<int>,vector<int>> matchresults=longMatchpbwt(L_initial,panel,prefix,
divergence,u,v,minmatch,
gd,queryidx,N,M,qM,
L_minmatch,ncores,samefile,
phase,targetfile);
free_PBWT_memory(panel, prefix, divergence, u, v);
return(matchresults);