-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSparsePainter.cpp
More file actions
4567 lines (4033 loc) · 163 KB
/
SparsePainter.cpp
File metadata and controls
4567 lines (4033 loc) · 163 KB
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
#ifndef DEBUG
#define DEBUG 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<int>> &panel, int** &prefix, int** &divergence, int** &u, int** &v, int ** &w) {
// 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
delete[] w[0]; // which is temp5
// Now, delete the outer arrays of prefix, divergence, u, and v
delete[] prefix;
delete[] divergence;
delete[] u;
delete[] v;
delete[] w;
// Clear the panel vector and minimize its memory usage
panel.clear();
vector<vector<int>>().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;
w = nullptr;
}
void reversePBWT(vector<vector<int>> &recon,
int **prefix, int **u, int **v, int **w,
int num, int N)
{
recon.assign(num, std::vector<int>(N, -1));
for (int k = 0; k < N; ++k) {
// totals for this column (after your forward v/w shifts)
const int zeros_total = v[0][k];
const int ones_total = w[0][k] - v[0][k];
// const int twos_total = num - w[0][k]; // not needed explicitly
for (int i = 0; i < num; ++i) {
int seq = prefix[i][k];
int allele;
if (i < num - 1) {
if (u[i+1][k] > u[i][k]) allele = 0;
else if (v[i+1][k] > v[i][k]) allele = 1;
else allele = 2;
} else {
// last row: compare to totals
if (zeros_total - u[i][k] == 1) allele = 0;
else if (w[0][k] - v[i][k] == 1) allele = 1; // same as: ones_total - (v[i]-v0) == 1
else allele = 2;
}
recon[seq][k] = (allele == 0 ? 0 : (allele == 1 ? 1 : 9));
}
}
#if DEBUG
cout<<"Reconstructed sequence data:"<<endl;
for (int i = 0; i < num; ++i) {
for (int k = 0; k < N; ++k) {
cout<<recon[i][k]<<" ";
}
cout<<endl;
}
#endif
}
void PBWT(vector<vector<int>> &panel, int **prefix, int **divergence,
int **u, int **v, int **w, int num, int N){
for (int i = 0; i<num; ++i){
prefix[i][0] = i;
divergence[i][0] = 0;
}
// Made multi-allelic following https://bmcbioinformatics.biomedcentral.com/articles/10.1186/s12859-019-2821-6
for (int k = 0; k<N; ++k) {
int u2 = 0, v2 = 0, w2=0,
p = k+1, q = k+1, r=k+1;
vector<int> a,b,c, d,e,f;
for (int i = 0; i<num; ++i) {
u[i][k] = u2;
v[i][k] = v2;
w[i][k] = w2;
if (divergence[i][k] > p) { p = divergence[i][k];}
if (divergence[i][k] > q) { q = divergence[i][k];}
if (divergence[i][k] > r) { r = divergence[i][k];}
int seq = prefix[i][k];
int allele = panel[seq][k];
if (allele==0){
a.push_back(seq);
d.push_back(p);
++u2;
p = 0;
}else if (allele==1){
b.push_back(seq);
e.push_back(q);
++v2;
q = 0;
}else{
c.push_back(seq);
f.push_back(r);
++w2;
r = 0;
}
}
for (int i = 0; i<num; ++i){
v[i][k] += a.size(); // number of 0's
w[i][k] += a.size() + b.size(); // number of 0's + 1's
if (i < a.size()){
prefix[i][k+1] = a[i];
divergence[i][k+1] = d[i];
}else if (i < a.size()+b.size()){
prefix[i][k+1] = b[i-a.size()];
divergence[i][k+1] = e[i-a.size()];
}else{
prefix[i][k+1] = c[i-a.size()-b.size()];
divergence[i][k+1] = f[i-a.size()-b.size()];
}
}
}
#if DEBUG
cout<<"Divergence:"<<endl;
for (int i = 0; i<num; ++i){
for (int k = 0; k<N; ++k) {
cout<<divergence[i][k]<<" ";
}
cout<<endl;
}
cout<<"Prefix:"<<endl;
for (int i = 0; i<num; ++i){
for (int k = 0; k<N; ++k) {
cout<<prefix[i][k]<<" ";
}
cout<<endl;
}
cout<<"u:"<<endl;
for (int i = 0; i<num; ++i){
for (int k = 0; k<N; ++k) {
cout<<u[i][k]<<" ";
}
cout<<endl;
}
cout<<"v:"<<endl;
for (int i = 0; i<num; ++i){
for (int k = 0; k<N; ++k) {
cout<<v[i][k]<<" ";
}
cout<<endl;
}
cout<<"w:"<<endl;
for (int i = 0; i<num; ++i){
for (int k = 0; k<N; ++k) {
cout<<w[i][k]<<" ";
}
cout<<endl;
}
vector<vector<int>> recon; // empty at first
reversePBWT(recon,prefix,u,v,w,num,N);
#endif
}
void ReadVCF(const string inFile,
const string qinFile,
vector<vector<int>> &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;
}
long nummissing=0; // counter of missing alleles read
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;
char tx = 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 >> tx >> y;
if((tx != '0')&&(tx!='1')){
tx='9';++nummissing;
}
x=tx-'0';
panel[i*2][j] = (int)x;
linestr >> tx;
if((tx != '0')&&(tx!='1')){
tx='9';++nummissing;
}
x=tx-'0';
panel[i*2 + 1][j] = (int)x;
}
}else{
for (int i = 0; i<M-qM; ++i){
linestr >> tx;
if((tx != '0')&&(tx!='1')){
tx='9';++nummissing;
}
x=tx-'0';
panel[i][j] = (int)x;
}
}
}
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; // int valued allele read
char y = 0; // a separator detector
char tx =0; // the raw allele read
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 >> tx >> y;
if((tx != '0')&&(tx!='1')){
tx='9';++nummissing;
}
x=tx-'0';
panel[i*2][j] = (int)x;
linestr >> tx;
if((tx != '0')&&(tx!='1')){
tx='9';++nummissing;
}
x=tx-'0';
panel[i*2 + 1][j] = (int)x;
}
for (int i = (M-qM)/2; i < M/2; ++i){
qlinestr >> tx >> y;
if((tx != '0')&&(tx!='1')){
tx='9';
}
x=tx-'0';
panel[i*2][j] = (int)x;
qlinestr >> tx;
if((tx != '0')&&(tx!='1')){
tx='9';
}
x=tx-'0';
panel[i*2 + 1][j] = (int)x;
}
}else{
for (int i = 0; i<M-qM; ++i) {
linestr >> tx;
if((tx != '0')&&(tx!='1')){
tx='9';++nummissing;
}
x=tx-'0';
panel[i][j] = (int)x;
}
for (int i = (M-qM); i < M; ++i){
qlinestr >> tx;
if((tx != '0')&&(tx!='1')){
tx='9';
}
x=tx-'0';
panel[i][j] = (int)x;
}
}
}
in.close();
qin.close();
}
if(nummissing>0){
cout<<"IMPORTANT NOTE! "<<nummissing<<" sites were TREATED AS MISSING in the reference."<<endl;
cout<<" Missing sites are defined as any non 0/1 allele."<<endl;
cout<<" References that are missing are removed from consideration as a match."<<endl;
cout<<" This is intended behavior to represent structural missingness, but for short"<<endl;
cout<<" missing regions, you should impute beforehand."<<endl;
cout<<" Additionally, if you have multi-allelic sites they are treated as missing which is not desirable."<<endl;
cout<<" The least-bad option is to remove multi-allelic sites and re-impute their painting from binary sites."<<endl;
}
}
void Readphase_donor(const string inFile,
vector<vector<int>> &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;
long nummissing=0;
// 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<int> panelsnp;
// convert SNP data to binary
for (char c : line) {
if((c != '0')&&(c!='1')){
c='9';++nummissing;
}
int x=c-'0';
panelsnp.push_back(x);
}
int Oid = i;
// add snps to the panel
panel.push_back(vector<int>());
panel[i].resize(N);
for (int k = 0; k<N; ++k){ // for every SNP
panel[i][k] = panelsnp[k];
} // end loop over snps
if(nummissing>0){
cout<<"IMPORTANT NOTE! "<<nummissing<<" sites were TREATED AS MISSING in the REFERENCE file."<<endl;
cout<<" Missing sites are defined as any non 0/1 allele."<<endl;
cout<<" References that are missing are removed from consideration as a match."<<endl;
cout<<" This is intended behavior to represent structural missingness, but for short"<<endl;
cout<<" missing regions, you should impute beforehand."<<endl;
cout<<" Additionally, if you have multi-allelic sites they are treated as missing which is not desirable."<<endl;
cout<<" The least-bad option is to remove multi-allelic sites and re-impute their painting from binary sites."<<endl;
}
}
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);
}
/*
// returns: (seq_i, seq_j, start_pos, end_pos)
tuple<vector<int>, vector<int>, vector<int>, vector<int>>
singleseqsiteMultialleleLongMatchpbwt(const int L_initial,
const vector<int>& xk, // alleles at site k (N entries from panelsnp)
const vector<int>& ak, // PBWT ordering at site k
const vector<int>& dk, // divergence array at site k
int minmatch,
int k, // site index
int N, int M)
{
// Output vectors
vector<int> out_i;
vector<int> out_j;
vector<int> out_start;
vector<int> out_end;
// Convenience: minimal L to use (length threshold)
const int L = L_initial;//std::max(L_initial, L_minmatch);
if (L <= 0) {
// nothing to do if L <= 0; early return
return make_tuple(out_i, out_j, out_start, out_end);
}
// We'll sweep over all columns k (0..N-1)
// For each column we run the algorithm to find all matches > L ending at k
for (int k = 0; k < N; ++k) {
// We'll create a small mapping from allele value -> index [0..t-1] used by m[]
// but algorithm only needs to know whether two different alleles exist inside the run.
// Instead of a fixed-size m[], we'll use an unordered_map<int,bool> to mark seen alleles.
// However the paper uses small t and clears m[0..t-1]; we mimic equivalent behaviour here.
// We'll implement the exact loop of Algorithm 3:
// m: map allele -> seen (bool)
unordered_map<int, bool> m;
// zero the map: not necessary (constructed empty)
// i0 = 0
int i0 = 0;
// iterate i over PBWT order at column k
for (int i = 0; i < M; ++i) {
cout<<"CHECK i="<<i<<endl;
// check divergence condition
// The paper checks if d_k[i] > k - L then treat as candidate group
int dval = divergence[i][k];
if (dval > k - L) {
// The candidate group (i0 .. i) is not yet closed; update m for this row
int seqIndex = prefix[i][k]; // a_k[i]
int allele = panel[seqIndex][k]; // x_k[a_k[i]]
m[allele] = true; // mark allele seen
// move on to next i until group closed
} else {
// When we reach a row whose divergence <= k - L, we need to process the group
// from i0 .. i-1 (if any). The paper's logic is:
// if there are at least two different alleles present in the group:
// report = true; then do inner two-loop block to find dmin and report matches
// then reset i0 = i and clear m
int groupStart = i0;
int groupEnd = i - 1; // inclusive; if i == i0 then group is empty and skip
if (groupEnd >= groupStart) {
// check if more than one allele exists in m
if (m.size() >= 2) {
// We have polymorphism in the group -> potential matches
// Now implement the part:
// for ia = i0 to i do
// dmin = 0
// for ib = ia+1 to i do
// if d_k[ib] > dmin then dmin = d_k[ib]
// if x_k[a_k[ia]] != x_k[a_k[ib]] then report match from dmin to k
//
// This nested loop is O(groupSize^2). For large group sizes you may want
// to optimise (e.g., bucket by allele and then cross-product).
//
// We'll implement a safe nested loop but avoid repeated work where possible.
int ia = groupStart;
while (ia <= groupEnd) {
int seq_ia = prefix[ia][k];
int allele_ia = panel[seq_ia][k];
// inner loop ib = ia+1..groupEnd
for (int ib = ia+1; ib <= groupEnd; ++ib) {
int seq_ib = prefix[ib][k];
int allele_ib = panel[seq_ib][k];
if (allele_ia == allele_ib) continue; // only interested in different alleles
// compute dmin = max over d_k[ia+1..ib]
// (paper sets dmin=0 and then updates to d_k[ib] if larger)
// To follow the paper precisely we compute:
int dmin = 0;
for (int iz = ia+1; iz <= ib; ++iz) {
int dv = divergence[iz][k];
if (dv > dmin) dmin = dv;
}
// Now check the extra condition from the paper:
// if x_k[a_k[ia]] != x_k[a_k[ib]] then report match from dmin to k
// (we already ensured alleles differ)
// But the paper also has a small conditional: "if report then
// for ia = i0 to i do
// for ib = ia+1 to i do
// if dk[ib] > dmin then dmin = dk[ib]
// if xk[ak[ia]] != xk[ak[ib]] then report match from dmin to k"
//
// We'll follow this and append matches (seq_ia, seq_ib, dmin, k)
out_i.push_back(seq_ia);
out_j.push_back(seq_ib);
out_start.push_back(dmin); // dmin is start of match (per paper's definition)
out_end.push_back(k);
}
++ia;
}
} // end if polymorphic group
// reset group
i0 = i;
m.clear();
} else {
// group was empty, just move i0 forward
i0 = i;
m.clear();
}
// continue loop; we still need to process row i itself (since divergence[i] <= k-L,
// we do not include it in next group unless d_k[i] > k-L). So just continue.
}
} // end for i
// process the final group from i0..M-1 (if any)
if (i0 <= M-1) {
if (m.size() >= 2) {
int groupStart = i0;
int groupEnd = M - 1;
for (int ia = groupStart; ia <= groupEnd; ++ia) {
int seq_ia = prefix[ia][k];
int allele_ia = panel[seq_ia][k];
for (int ib = ia+1; ib <= groupEnd; ++ib) {
int seq_ib = prefix[ib][k];
int allele_ib = panel[seq_ib][k];
if (allele_ia == allele_ib) continue;
int dmin = 0;
for (int iz = ia+1; iz <= ib; ++iz) {
int dv = divergence[iz][k];
if (dv > dmin) dmin = dv;
}
out_i.push_back(seq_ia);
out_j.push_back(seq_ib);
out_start.push_back(dmin);
out_end.push_back(k);
}
}
}
}
} // end for k
return make_tuple(out_i, out_j, out_start, out_end);
}
*/
/*
tuple<vector<int>,vector<int>,vector<int>,vector<int>> multialleleLongMatchpbwt(const int L_initial,
vector<vector<int>> &panel,
int **prefix,
int **divergence,
int **u,
int **v,
int **w,
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;
long nummissing=0;
omp_set_num_threads(ncores);
if(samefile){
minmatch++;
}
while(nind_left>0) {
int ncores_use = (ncores < nind_left) ? ncores : nind_left;
vector<vector<int>> panelsnp;
if(samefile){
panelsnp=vector<vector<int>>(ncores_use,vector<int>(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<int>>(ncores_use,vector<int>(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];
nummissing+=(panel[M-qM+i][j]==9);
}
}
}else{
panelsnp=vector<vector<int>>(ncores_use);
for(int i=nind-nind_left; i<nind-nind_left+ncores_use; ++i) {
getline(in, line);
for (char c : line) {
if((c != '0')&&(c!='1')){
c='9';++nummissing;
}
int x=c-'0';
panelsnp[i-nind+nind_left].push_back(x);
}
}
}
}
///////////////
#if DEBUG
for(int i=nind-nind_left; i<nind-nind_left+ncores_use; ++i) {
cout<<"panelsnp:"<<i<<endl;
for(int j=0;j<N;++j){
cout<<panelsnp[i-nind+nind_left][j]<<" ";
}
cout<<endl;
}
#endif
///////////////
cout<<"Finding matches with PBWT for target haplotypes "<<nind-nind_left<<"-"<<nind-nind_left+ncores_use-1<<endl;
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;
#pragma omp parallel for
for (int idx=nind-nind_left; idx<nind-nind_left+ncores_use; ++idx) {
auto [startpos, endpos, left, right] = singleseqsiteMultialleleLongMatchpbwt(
L_initial,
panelsnp[idx], // alleles at site k
prefix[k], // a_k
divergence[k], // d_k
minmatch,
k, N, M);
}
} // end while(nind_left>0)
}
*/
tuple<vector<int>,vector<int>,vector<int>,vector<int>> longMatchpbwt(const int L_initial,
vector<vector<int>> &panel,
int **prefix,
int **divergence,
int **u,
int **v,
int **w,
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;
long nummissing=0;
omp_set_num_threads(ncores);
if(samefile){
minmatch++;
}
while(nind_left>0) {
int ncores_use = (ncores < nind_left) ? ncores : nind_left;
vector<vector<int>> panelsnp;
if(samefile){
panelsnp=vector<vector<int>>(ncores_use,vector<int>(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<int>>(ncores_use,vector<int>(N));
for(int i=nind-nind_left; i<nind-nind_left+ncores_use; ++i) {
for(int j=0;j<N;++j){