-
Notifications
You must be signed in to change notification settings - Fork 0
/
rare.cpp
6779 lines (6137 loc) · 240 KB
/
rare.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
#include <stdio.h>
#include <string>
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <set>
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <limits>
using namespace std;
struct WEIGHTS
{
int mode;
int betapar1;
int betapar2;
float logpar1;
float logpar2;
};
double *weightvec=NULL;
struct STATplus regGeneral(int x[27], //in this function just a dummy
int *cov, //indicates if covar is is used;
int sexcov,
struct PERSON *person, int nlinestfam,int ncases, int ncontrols, int nrest,
int a, int b, int c, // here just dummies
double inflationfactor, //dummy
double casecounts5[3][3][3][3][3], //int this function just a dummy
double *p, double **newbeta,
double **X, double **Xmod, double **Xt, double **A, double **UNNT,double **VNN,
double *S, double **Sinv, double **A0, double **Ainv, double **AinvXt, double *Y,
double **Yminusp,
int N, //dummy
int alt, double *Yhelp, int xtype, int female,
int male,
struct COUNTS counts, //dummy
double **Yt, double **YtX, double **YtXAinv,
double **YtXAinvXt,
int haplo, //dummy
double **D, double **T, double **U, double **Ut, double **sumPP,
double **sumPJ, double **sumPK, double **MMinv, int test,int thread,
char *hapfile, int dohapfile, char *hapstring, FILE *file1, //dummies
int skip, //dummy
int npplqc, int* PPLMap, uint64_t*** BinSNPs, struct PPLLOCATION* PplLocations,
int nMc,struct STATplus result,
int caseOnly, int secondSystem, //dummies
int numberOfAllCov,int ncov,
int liabilityCut, int singleMarkerTest, int covNum, //dummies
//new parameters:
int nSnps, //number of snps to be included with additive term
int nSnpsDom, //number of snps to be included with dominance term
int nEnvirons, // number of non-genetic parameters (for future extensions)
int nInters, // number of interaction terms to be used (under construction)
int *snps, // list of snps to be included with additive term, indices in BinSNPs
int *snpsDom, // list of snps to be included with dominance term, indices in BinSNPs
int *environs, // list of non-genetic parameters (for future extensions)
int *inters, // list of interaction terms to be used (coding under construction)
int nx, // total number of parameters in regression model. n=nSnps+nSnpsDom+nEnvirons+nInters+sexcov
int dim1, // maximum number of paramters allowed according to allocation in main
int collapseRare, // =1: do Morris rare-frac-method
int collcollapseRare, // =1: do Morris rare-coll-method
int qt,
double *weightvec,
int firstbinlastSNP
);
struct STATplus logRegGeneral(int x[27], //in this function just a dummy
int *cov, //indicates if covar is isused;
int sexcov,
struct PERSON *person, int nlinestfam,int ncases, int ncontrols, int nrest,
int a, int b, int c, // here just dummies
double inflationfactor, //dummy
double casecounts5[3][3][3][3][3], //int this function just a dummy
double *p, double **newbeta,
double **X, double **Xmod, double **Xt, double **A, double **UNNT,double **VNN,
double *S, double **Sinv, double **A0, double **Ainv, double **AinvXt, double *Y,
double **Yminusp,
int N, //dummy
int alt, double *Yhelp, int xtype, int female,
int male,
struct COUNTS counts, //dummy
double **Yt, double **YtX, double **YtXAinv,
double **YtXAinvXt,
int haplo, //dummy
double **D, double **T, double **U, double **Ut, double **sumPP,
double **sumPJ, double **sumPK, double **MMinv, int test,int thread,
char *hapfile, int dohapfile, char *hapstring, FILE *file1, //dummies
int skip, //dummy
int npplqc, int* PPLMap, uint64_t*** BinSNPs, struct PPLLOCATION* PplLocations,
int nMc,struct STATplus result,
int caseOnly, int secondSystem, //dummies
int numberOfAllCov,int ncov,
int liabilityCut, int singleMarkerTest, int covNum, //dummies
//new parameters:
int nSnps, //number of snps to be included with additive term
int nSnpsDom, //number of snps to be included with dominance term
int nEnvirons, // number of non-genetic parameters (for future extensions)
int nInters, // number of interaction terms to be used (under construction)
int *snps, // list of snps to be included with additive term, indices in BinSNPs
int *snpsDom, // list of snps to be included wit dominance term, indices in BinSNPs
int *environs, // list of non-genetic parameters (for future extensions)
int *inters, // list of interaction terms to be used (coding under construction)
int nx, // total number of parameters in regression model. n=nSnps+nSnpsDom+nEnvirons+nInters+sexcov
int dim1, // maximum number of paramters allowed according to allocation in main
int collapseRare, // =1: do Morris rare-method
int collcollapseRare, // =1: do Morris other rare-method
int qt,
double *weightvec,
int covariancematrix, //new logRegGeneral
int firstbinlastSNP,
int collinter
);
void resultCopy(struct STATplus *result1, struct STATplus result2);
void init(struct STATplus *result, int haplo, int n, int numberOfAllCov, int multi, int needArrays, int dim1, int dim2);
struct STATplus logreg( int x[27], //indicates which parameters are used
int *cov, //indicates if covar is isused;
int sexcov, //indicates if only males or females are counted; inidcates if sex is a covariate
struct PERSON *person, int nlinestfam, int ncases, int ncontrols, int nrest, //person info, helpful numbers
int a, int b, int c, // data matrix; a,b,c identify snps 1, 2 and 3
double inflationfactor,
double casecounts5[3][3][3][3][3],double controlcounts5[3][3][3][3][3], //3-dimgenocounts
double *p, double **newbeta, //likelihood per ind , betas
double **X, double **Xmod, double **Xt, double **A, double **UNNT,double **VNN, //empty matrices, vectors
double *S, double **Sinv, double **A0, double **Ainv, double **AinvXt, double *Y, //empty matrices, vectors
double **Yminusp,
int N, int alt, double *Yhelp, int xtype, int female, int male, struct COUNTS counts,
double **D, double **T, double **U, double **Ut, double **sumPP, double **sumPJ, double **sumPK, double **MMinv,int test,int thread, int npplqc, int* PPLMap, uint64_t*** BinSNPs,
struct PPLLOCATION* PplLocations,int nMc,struct STATplus result, int numberOfAllCov, int liabilityCut, int singleMarkerTest, int covNum,int covariancematrix, int df_L1, int df_L2, int dosage, float ***genoWeights);
// Neue qtreg-Funktion
struct STATplus qtreg( int x[27], //indicates which parameters are used
int *cov, //indicates if covar is isused;
int sexcov, //indicates if only males or females are counted; inidcates if sex is a covariate
struct PERSON *person, int nlinestfam,int ncases, int ncontrols, int nrest, //person info, helpful numbers
int a, int b, int c, // data matrix; a,b,c identify snps 1, 2 and 3
double inflationfactor, double casecounts5[3][3][3][3][3], //3-dimgenocounts
double *p, double **newbeta, //likelihood per ind , betas
double **X, double **Xmod, double **Xt, double **A, double **UNNT,double **VNN, //empty matrices, vectors
double *S, double **Sinv, double **A0, double **Ainv, double **AinvXt, double *Y, //empty matrices, vectors
double **Yminusp, int N, int alt, double *Yhelp, int xtype, int female,
int male, struct COUNTS counts, double **Yt, double **YtX, double **YtXAinv, double **YtXAinvXt, int haplo,
double **D, double **T, double **U, double **Ut, double **sumPP, double **sumPJ, double **sumPK, double **MMinv, int test,int thread, char *hapfile, int dohapfile, char *hapstring,
FILE *file1,int skip, int npplqc, int* PPLMap, uint64_t*** BinSNPs, struct PPLLOCATION* PplLocations,int nMc,struct STATplus result,int caseOnly, int secondSystem,
int numberOfAllCov,int liabilityCut, int singleMarkerTest,int covNum,int covariancematrix, int df_L1, int df_L2);
double betai(double a, double b, double x);
void freeResult(struct STATplus result1, int n)
{
if(n==0)
{
free(result1.betaNew_se);free(result1.betaNew_lcl);free(result1.betaNew_rcl);
free(result1.oddsRatio);free(result1.lcloddsRatio);free(result1.rcloddsRatio);
free(result1.sigma1);
}
free(result1.b);free(result1.bcv);free(result1.in);
};
struct WINDOW
{
// Pretest-Permutations
// Tests numbered as:
// FR CMAT COLL REG FRACREG COLLREG
int nperm[6];
// Number of tests (still) to be conducted
int ntests;
// Variant data
int **levelpos; // relative positions of SNPs in bim file, levelwise
int n_level;
// int start;
// int end;
// int start1,start2,end1,end2; // For RAREINTER
int *n_at_level; // how many SNPs per level
double *maf_at_level; // How high is MAF at level
};
struct WINDOW *window;
struct WINDOW_INTER
{
// Optimal Variable threshold per test
// Number of tests (still) to be conducted
// Variant data
int **levelpos; // relative positions of SNPs in bim file, levelwise
int n_level;
int start;
int end;
int start1,start2,end1,end2; // For RAREINTER
int *n_at_level; // how many SNPs per level
double *maf_at_level; // How high is MAF at level
};
struct WINDOW_INTER *window_inter;
int *FISHERnotconverged;
int *FISHERpretestpassed;
int *REGRESSIONpretestpassed;
int *FRACREGpretestpassed;
int *COLLREGpretestpassed;
int *CMATpretestpassed;
int *COLLpretestpassed;
// Confidence Intervals
double **FISHER_CI;
double **CMAT_CI;
double **COLL_CI;
double **REGRESSION_CI;
double **FRACREG_CI;
double **COLLREG_CI;
// betas, se
double *COLLREG_beta;
double *COLLREG_se;
double *FRACREG_beta;
double *FRACREG_se;
// optimal MAF_Level
int *MAF_Level_VT_FISHER;
int *MAF_Level_VT_CMAT;
int *MAF_Level_VT_COLL;
int *MAF_Level_VT_REGRESSION;
int *MAF_Level_VT_FRACREG;
int *MAF_Level_VT_COLLREG;
double *rarefFISHER=NULL;
double *rarefREGRESSION=NULL;
double *rarefFRACREG=NULL;
double *rarefCOLLREG=NULL;
double *rarefCOLL=NULL;
double *OR_COLL_vec=NULL;
double *OR_COLL_f_vec=NULL;
double *OR_CMAT_vec=NULL;
double *rarefCMAT=NULL;
int **windowPositions=NULL;
int **doublewindowcoord=NULL; // for RAREINTER
int **intervalfileWindows=NULL;
double *pCOLLvec=NULL;
double *pCMATvec=NULL;
double *pFISHERvec=NULL;
double *pREGRESSIONvec=NULL;
double *pFRACREGvec=NULL;
double *pCOLLREGvec=NULL;
double *pFISHERvecChi=NULL;
double **limitsStatCOLL=NULL;
double **limitsStatCMAT=NULL;
double **limitsStatFISHER=NULL;
double **limitsStatREGRESSION=NULL;
double **limitsStatFRACREG=NULL;
double **limitsStatCOLLREG=NULL;
int *nCarriers=NULL;
int *nSNPsInWindow=NULL;
int nRareSNPsPerChr[26];
int *nRareSNPs=NULL;
int *nRareSNPsCOLL=NULL;
int *nRareSNPsCMAT=NULL;
int *nRareSNPsFISHER=NULL;
int *nRareSNPsREGRESSION=NULL;
int *nRareSNPsFRACREG=NULL;
int *nRareSNPsCOLLREG=NULL;
double OR_COLL=0;
double OR_COLL_f=0;
double OR_CMAT=0;
// for RARE_TESTS
bool FISHERflag=1;
bool REGRESSIONflag=0;
bool FRACREGflag=0;
bool COLLREGflag=0;
bool COLLflag=1;
bool CMATflag=1;
// for RARE_PRETEST
int rarepretest=0;
float rarepretestlimit=0;
double rareregpretest=0;
double wilsonpretest=0;
int adaptive =0;
int currentn=0;
int *FISHERcount=NULL;
int *REGRESSIONcount=NULL;
int *FRACREGcount=NULL;
int *COLLREGcount=NULL;
int *COLLcount=NULL;
int *CMATcount=NULL;
int *completedFISHER=NULL;
int *completedREGRESSION=NULL;
int *completedFRACREG=NULL;
int *completedCOLLREG=NULL;
int *completedCOLL=NULL;
int *completedCMAT=NULL;
double *FISHERstats=NULL;
double *REGRESSIONstats=NULL;
double *FRACREGstats=NULL;
double *COLLREGstats=NULL;
double *COLLstats=NULL;
double *CMATstats=NULL;
double *FISHERpermstats=NULL;
double *REGRESSIONpermstats=NULL;
double *FRACREGpermstats=NULL;
double *COLLREGpermstats=NULL;
double *COLLpermstats=NULL;
double *CMATpermstats=NULL;
int bins2test=0;
void write_setid(int setid, string SetIDfile, int intervaleditor, float raref,int nwindowssinglebin, int **windowPositions,fstream &errorfile, fstream &logfile, INTERVALS *intervals,struct MAP *map, struct WINDOW *window, string intervalfile, int *nRareLimits){
fstream SetID;
SetID.open(SetIDfile.c_str(), ios::out);
for(int m=0; m<nwindowssinglebin; m++){
for(int j=0; j<window[m].n_at_level[nRareLimits[m]-1]; j++){
int i=window[m].levelpos[nRareLimits[m]-1][j];
SetID<<map[i].chr<<":"<<map[windowPositions[m][0]].pos<<"-"<<map[windowPositions[m][1]].pos;
if(intervalfile!=" " && featurecol!=-9){
SetID <<"("<<intervals[m].feature<<")"<<flush;
}
SetID << "\t"<< map[i].rs<<"\n";
}
}
SetID.close();
if(intervaleditor){
cout << "SetID file "<<SetIDfile<<" generated."<<endl;
logfile << "SetID file "<<SetIDfile<<" generated."<<endl;
exit(0);
}
};
double chiinv(double df, double p);
//struct WINDOW *window=NULL;
double pValueCalc(double a, double x);
int **calloc2Dint(int m, int n);
float **calloc2Dfloat(int m, int n);
double **calloc2Ddouble(int m, int n);
void free2Ddouble(double **matrix, int m);
void updateCounts(struct COUNTS*, int, uint64_t**, uint64_t**, uint64_t**, bool X);
void aff_permute_clusters(struct PERSON*, struct CLUSTERS*, uint32_t, int, int*, int*, int*);
// int comparator
int compareint (const void * a, const void * b){
return ( *(int*)a - *(int*)b );
}
// float comparator
int comparefloat(const void *a, const void *b){
const float *da = (const float *) a;
const float *db = (const float *) b;
return (*da > *db) - (*da < *db);
}
// double comparator
int comparedouble(const void *a, const void *b){
const double *da = (const double *) a;
const double *db = (const double *) b;
return (*da > *db) - (*da < *db);
}
int israre(int i, double maf, double raref, struct MAP *map){
if(map[i].analysis_in == 1 && ((raref-maf)>EPS || fabs(maf-raref)<EPS) && maf>EPS){
return 1;
}
else{
return 0;
}
}
int checkCovCathegories(int *cov, int nlinestfam,struct PERSON *person, int nCovCathegories){
cout << "Attempting to use the (first) covariate for the CMAT test with covariates"<<endl;
int dummycov[nlinestfam];
int sdummycov[nlinestfam];
nCovCathegories=1;
for(int i=0; i<nlinestfam; i++){
dummycov[i]=int(person[i].cov[0]);
sdummycov[i]=int(person[i].cov[0]);
}
qsort(sdummycov,nlinestfam,sizeof(int),compareint);
for(int i=1; i<nlinestfam; i++){
if(sdummycov[i-1]!=sdummycov[i]){
nCovCathegories++;
}
}
cout <<nCovCathegories<<" categories found\n"<<endl;
if(sdummycov[0]==0){
cout<<"Among them missings!"<<endl;
if( sdummycov[nlinestfam-1]!=nCovCathegories-1){
cout <<"Categoric covariates have to be numbered 1 through "<<nCovCathegories<<" for CMAT test!\n"<<endl;
exit(0);
}
}
else if( sdummycov[nlinestfam-1]!=nCovCathegories ){
cout <<"Categoric covariates have to be numbered 1 through "<<nCovCathegories<<" for CMAT test!\n"<<endl;
exit(0);
}
return nCovCathegories;
}
double wilson_lower(int ncount, int pcount){
// float z = 3.7190165; // for alpha=10^-4 one-sided
double z = 1.96;
double phat = pcount / double(ncount);
return max((double)0,((phat + z*z/(2*ncount) - z * sqrt((phat*(1-phat)+z*z/(4*ncount))/ncount))/(1+z*z/ncount)));
}
double wilson_upper(int ncount, int pcount){
double z = 1.96;
// float z = 3.7190165;
double phat = pcount / double(ncount);
return min((double)1,((phat + z*z/(2*ncount) + z * sqrt((phat*(1-phat)+z*z/(4*ncount))/ncount))/(1+z*z/ncount)));
}
double *get_weights(int nlinestped, struct WEIGHTS weights, struct MAP *map, double *weightvec){
int i=0;
for(i=0; i<nlinestped; i++){
if(weights.mode==1 && map[i].maf!=0){
weightvec[i]=(double)1/sqrt(map[i].mafr*(1-map[i].mafr));
}
else if(weights.mode==2 && map[i].maf!=0){
weightvec[i]=pow(map[i].mafr,weights.betapar1-1)*pow(1-map[i].mafr,weights.betapar2-1);
}
else if(weights.mode==3 && map[i].maf!=0){
weightvec[i]=(double)1/(1+exp((-weights.logpar1+map[i].mafr)*weights.logpar2));
}
else if(weights.mode==0){
weightvec[i]=1;
}
}
return weightvec;
}
/// Fisher test
double calcFISHERp(double stat, double raref, int start, int end, struct COUNTS *counts, int thread, struct MAP *map, struct WINDOW *window, int l, int m){
int i=0;
// int j=0;
double p=0;
// for(i=start; i<=end; i++){
// if( ((map[i].mafr-raref)<EPS || fabs(map[i].mafr-raref)<EPS) && map[i].mafr>EPS && map[i].analysis_in == 1){
// j++;
// }
// }
p=pValueCalc((double)window[l].n_at_level[m], stat/2);
return p;
}
double calcFISHER(int *cov, int sexcov, struct PERSON *person, int ncases, int ncontrols, int nrest, int thread, int nlinestfam, int nlinestped, int start, int end, struct COUNTS *counts, double raref, double inflationfactor, bool fisherCorrection, struct MAP *map, double *weightvec, struct WINDOW *window, int l, int m){
int i=0;
double sum=0;
double p=1;
double stat=0;
// for(i=start; i<=end; i++){
// if(map[i].analysis_in && ((map[i].mafr-raref)<EPS || fabs(map[i].mafr-raref)<EPS) && map[i].mafr>EPS && inflationfactor>EPS){
for(int j=0; j<window[l].n_at_level[m]; j++){
i=window[l].levelpos[m][j];
p=(double)counts[i].pSingle;
if(fisherCorrection){
stat=chiinv(1,p);
stat=stat/inflationfactor;
p=pValueCalc(0.5, stat/2);
}
sum=sum+weightvec[i]*log(p);
// }
}
return -2*sum;
}
void find_distinct_vb_vt(struct PERSON *person,struct MAP *map, int* PPLMap, struct PPLLOCATION* PplLocations, uint64_t*** BinSNPs, uint64_t** BinSNPsCCFlags, int nwords, int* SNPMapInverse, struct WINDOW *window, int *nRareLimits, int **rareLimitsNCT, int **rareLimitsNCTInverse, int nwindows, int minIndInBin, int maxIndInBin, int *nvbstartvt, int **vbstartvt, int nlinestfam, int nlinestped, int *nCarriers, int **nvblevel, int ***nchunks, int ****chunkpos, int ****chunklen, int optimalrare, int ****ndummyatlevel, int *****dummypos, int *****dummylevel, int ****dummyend, int ***ndummyends, int NCT, uint64_t ***BinCarriers, int ***nchunkcluster, int *****dummycluster){
int equivstartsnps=0;
// nvbstart=0;
int startcounter=0;
int shift=0; // shift is the number of variants on previous chromosomes
for(int l=0; l<nwindows; l++){
nvbstartvt[l]=1;
vbstartvt[l]=(int *)realloc(vbstartvt[l],(nvbstartvt[l])*sizeof(int));
if(!vbstartvt[l]) die("Memory allocation error in vbstartvt[l]!");
vbstartvt[l][0]=window[l].levelpos[nRareLimits[l]-1][0]; // index of first variant
int i1=window[l].levelpos[nRareLimits[l]-1][0];
uint64_t* dummy1 = new uint64_t[nwords]();
if(!dummy1) die("Memory allocation error in dummy1!");
int iMod = SNPMapInverse[i1];
if (iMod==-1) continue;
for (int p=0; p<nwords; p++){
dummy1[p] |= (BinSNPs[iMod][p][1] | BinSNPs[iMod][p][2]);
}
int m1=0;
// cout<<"vbstartvt["<<l<<"]["<<nvbstartvt[l]-1<<"] "<<vbstartvt[l][nvbstartvt[l]-1]<<" is pos of snp "<<nvbstartvt[l]-1<<" "<<map[vbstartvt[l][nvbstartvt[l]-1]].rs<<" "<<map[vbstartvt[l][nvbstartvt[l]-1]].pos<<" "<<" nCarriers[vbstartvt[i][vbstartvt[l]["<<nvbstartvt[l]-1<<"]] "<<nCarriers[vbstartvt[l][nvbstartvt[l]-1]]<<endl;
while(m1<window[l].n_at_level[nRareLimits[l]-1]-1){
int m2=m1+1;
while(m2<window[l].n_at_level[nRareLimits[l]-1]){
int nIndiff=0; // flag for distinctivness of next variant
int i2=window[l].levelpos[nRareLimits[l]-1][m2];
uint64_t* dummy2 = new uint64_t[nwords]();
if(!dummy2) die("Memory allocation error in dummy2!");
int iMod2 = SNPMapInverse[i2];
if (iMod2==-1) continue;
for (int p=0; p<nwords; p++){
dummy2[p] |= (BinSNPs[iMod2][p][1] | BinSNPs[iMod2][p][2]);
if(!nIndiff && dummy1[p]!=dummy2[p]){
nIndiff=1;
}
dummy1[p] = dummy2[p];
}
m1=m2;
if(nIndiff){
nvbstartvt[l]++;
vbstartvt[l]=(int *)realloc(vbstartvt[l],(nvbstartvt[l])*sizeof(int));
if(!vbstartvt[l]) die("Memory allocation error in vbstartvt[l]!");
vbstartvt[l][nvbstartvt[l]-1]=window[l].levelpos[nRareLimits[l]-1][m2];
// cout<<"vbstartvt["<<l<<"]["<<nvbstartvt[l]-1<<"] "<<vbstartvt[l][nvbstartvt[l]-1]<<" is pos of snp "<<nvbstartvt[l]-1<<" "<<map[vbstartvt[l][nvbstartvt[l]-1]].rs<<" "<<map[vbstartvt[l][nvbstartvt[l]-1]].pos<<" nCarriers[vbstartvt[i][vbstartvt[l]["<<nvbstartvt[l]-1<<"]] "<<nCarriers[vbstartvt[l][nvbstartvt[l]-1]]<<endl;
}
m2++;
delete[] dummy2;
}
}
shift+=window[l].n_at_level[nRareLimits[l]-1];
delete[] dummy1;
}
// allocate memory, compute BinCarriers
// all arrays ending with *atlevel (except for ndummyatlevel) are temporary and replaced later with arrays without "atlevel"
for(int l=0; l<nwindows; l++){
nvblevel[l] = new int[nvbstartvt[l]]();
if(!nvblevel[l]) die("Memory allocation error in nvblevel!");
chunkpos[l] = new int**[nvbstartvt[l]];
if(!chunkpos[l]) die("Memory allocation error in chunkpos!");
chunklen[l] = new int**[nvbstartvt[l]];
if(!chunklen[l]) die("Memory allocation error in chunklen!");
nchunks[l] = new int*[nvbstartvt[l]];
if(!nchunks[l]) die("Memory allocation error in nchunk!");
// dummy is the actual binary bin vector. this is used for reducing the number of positions kept in memory.
ndummyatlevel[l]=new int**[nvbstartvt[l]]; // ndummylevel is the number of dummys that are at the beginning of bins at higher levels
if(!ndummyatlevel[l]) die("Memory allocation error in ndummyatlevel!");
dummylevel[l]=new int***[nvbstartvt[l]];
if(!dummylevel[l]) die("Memory allocation error in dummylevel!");
dummypos[l]=new int***[nvbstartvt[l]];
if(!dummypos[l]) die("Memory allocation error in dummypos!");
dummycluster[l]=new int***[nvbstartvt[l]];
if(!dummycluster[l]) die("Memory allocation error in dummycluster!");
dummyend[l]=new int**[nvbstartvt[l]];
if(!dummyend[l]) die("Memory allocation error in dummyend!");
ndummyends[l]=new int*[nvbstartvt[l]];
if(!ndummyends[l]) die("Memory allocation error in ndummyends!");
nchunkcluster[l]=new int*[nvbstartvt[l]];
if(!nchunkcluster[l]) die("Memory allocation error in nchunkcluster!");
BinCarriers[l] = new uint64_t*[nvbstartvt[l]]; // BinCarriers[window][distinct variant][word] = binary vectors of carriers of distinct variants
if(!BinCarriers[l]) die("Memory allocation error in BinCarriers!");
for(int m=0; m<nvbstartvt[l]; m++){
BinCarriers[l][m] = new uint64_t[nwords]();
if(!BinCarriers[l][m]) die("Memory allocation error in BinCarriers!");
int i2=vbstartvt[l][m];
int iMod = SNPMapInverse[i2];
if (iMod==-1) continue;
for (int p=0; p<nwords; p++){
BinCarriers[l][m][p] = (BinSNPs[iMod][p][1] | BinSNPs[iMod][p][2]);
}
}
}
// find chunkpos, chunklen: chunks are contigous sequences of indices, each chunk has a position and a length
for(int l=0; l<nwindows; l++){
for(int m1=0; m1<nvbstartvt[l]; m1++){
int *ndummyendsatlevel=new int[nRareLimits[l]]();
int **dummyendatlevel=new int*[nRareLimits[l]];
int baselevel=0;
if(optimalrare){
baselevel=rareLimitsNCTInverse[l][nCarriers[vbstartvt[l][m1]]-1]; // baselevel is relative to chromosome. atlevelInverse[baselevel] relative to startposition is always 0
}
int *atlevel = new int[nRareLimits[l]](); // atlevel[level relative to startpos] = relative level, chromosome-wide
if(!atlevel) die("Memory allocation error in atlevel!");
int *atlevelInverse = new int[nRareLimits[l]]; // atlevelInverse[relative level, chromosome-wide] = level relative to startpos. in the beginning, set to -1, except atlevelInverse[baselevel]=0
if(!atlevelInverse) die("Memory allocation error in atlevelInverse!");
int *atlevelInverseStatus = new int[nRareLimits[l]](); // encoding: 0=never seen; 1=has been seen and active; 2=has been seen and inactive; 3=finished
if(!atlevelInverseStatus) die("Memory allocation error in atlevelInverseStatus!");
int *Ind1=new int[nRareLimits[l]]();
if(!Ind1) die("Memory allocation error in Ind1!");
int *Ind2=new int[nRareLimits[l]]();
if(!Ind2) die("Memory allocation error in Ind2!");
int *nRemaining=new int[nRareLimits[l]]();
if(!nRemaining) die("Memory allocation error in nRemaining!");
int *nchunksatlevel=new int[nlinestfam](); // temporary arrays
if(!nchunksatlevel) die("Memory allocation error in nchunksatlevel!");
int **chunkposatlevel=new int*[nRareLimits[l]];
if(!chunkposatlevel) die("Memory allocation error in chunkposatlevel!");
int **chunklenatlevel=new int*[nRareLimits[l]];
if(!chunklenatlevel) die("Memory allocation error in chunklenatlevel!");
// all variants with AND:
uint64_t **dummy1 = new uint64_t*[nRareLimits[l]];
if(!dummy1) die("Memory allocation error in dummy1!");
// basevariant minus following variants, if dummy2=0 then B_{i,j}=B_{i+1,j}
uint64_t **dummy2 = new uint64_t*[nRareLimits[l]];
if(!dummy2) die("Memory allocation error in dummy2!");
for(int i=0; i<nRareLimits[l]; i++){
// dummyendatlevel[i] is the first position that is not in cluster anymore
dummyendatlevel[i]=new int[nlinestfam]();
if(!dummyendatlevel[i]) die("Memory allocation error in dummyendatlevel[i]!");
chunkposatlevel[i]=new int[nlinestfam]();
if(!chunkposatlevel[i]) die("Memory allocation error in chunkposatlevel[i]!");
chunklenatlevel[i]=new int[nlinestfam]();
if(!chunklenatlevel[i]) die("Memory allocation error in chunklenatlevel[i]!");
dummy1[i]=new uint64_t[nwords]();
if(!dummy1) die("Memory allocation error in dummy1!");
dummy2[i]=new uint64_t[nwords]();
if(!dummy2) die("Memory allocation error in dummy2!");
atlevelInverse[i]=-1;
atlevel[i]=-1;
}
nvblevel[l][m1]++;
nchunksatlevel[0]++;
chunkposatlevel[0][0]=m1;
chunklenatlevel[0][0]=1;
atlevel[0]=baselevel;
if(optimalrare){
atlevelInverse[baselevel]=0;
atlevelInverseStatus[baselevel]=1;
}
else if(!optimalrare){
atlevelInverse[0]=0;
}
for (int p=0; p<nwords; p++){
dummy1[0][p] |= BinCarriers[l][m1][p];
dummy2[0][p] = dummy1[0][p];
Ind1[0]+=bitcount64(dummy1[0][p]);
}
for(int m2=m1+1; m2<nvbstartvt[l]; m2++){ // go through end positions
int currentlevel=0;
if(optimalrare){
currentlevel=rareLimitsNCTInverse[l][nCarriers[vbstartvt[l][m2]]-1]; // relative to chromsome
}
int newbin=0;
// with VT, check if a new higher (>baselevel) level exists:
if(currentlevel>baselevel){
int previouslevel=-2;
if(atlevelInverseStatus[currentlevel]==3){ // if level already satisfied row termination condition, skip variant
continue;
}
else if(atlevelInverseStatus[currentlevel]!=3){
if(atlevelInverseStatus[currentlevel]==1){ // level seen and active
previouslevel=atlevelInverse[currentlevel];
}
else if(atlevelInverseStatus[currentlevel]==0 || atlevelInverseStatus[currentlevel]==2){
for(int j=currentlevel-1; j>=baselevel; j--){ // find the largest known level < currentlevel:
if(atlevelInverseStatus[j]==3){ // a level below satisfied row termination condition
for(int j1=currentlevel; j1>j; j1--){ // all levels are terminated already
atlevelInverseStatus[j1]=3;
}
for(int j1=currentlevel+1; j1<nRareLimits[l]; j1++){ // all levels are terminated already
atlevelInverseStatus[j1]=3;
}
previouslevel=-2;
break;
}
else if(atlevelInverseStatus[j]==1){ // only if seen and active
previouslevel=atlevelInverse[j];
break;
}
}
}
if(previouslevel>=0){
uint64_t *dummy1_tmp=new uint64_t[nwords]();
if(!dummy1_tmp) die("Memory allocation error in dummy1_tmp!");
uint64_t *dummy2_tmp=new uint64_t[nwords]();
if(!dummy2_tmp) die("Memory allocation error in dummy2_tmp!");
int Ind1_tmp=Ind1[previouslevel];
int Ind2_tmp=0;
int nRemaining_tmp=0;
int i2=vbstartvt[l][m2];
int iMod2 = SNPMapInverse[i2];
// check if at currentlevel, B(m1,m2)==B(m1+1,m2) and B(m1,m2)==B(m1,m2+1):
for (int p=0; p<nwords; p++){
dummy1_tmp[p] = (dummy1[previouslevel][p] | BinCarriers[l][m2][p]);
dummy2_tmp[p] = (dummy2[previouslevel][p] & ~(BinCarriers[l][m2][p]));
Ind2_tmp+=bitcount64(dummy1_tmp[p]);
nRemaining_tmp+=bitcount64(dummy2_tmp[p]);
}
if(nRemaining_tmp==0 || Ind2_tmp==nlinestfam){ // this and higher levels are forbidden: row termination condition reached
for(int i=currentlevel; i<nRareLimits[l]; i++){
atlevelInverseStatus[i]=3;
}
delete[] dummy1_tmp;
delete[] dummy2_tmp;
continue;
}
else if(Ind1_tmp==Ind2_tmp){
delete[] dummy1_tmp;
delete[] dummy2_tmp;
continue;
}
// something new at this level
else if(Ind1_tmp!=Ind2_tmp){
// check if there is a higher open level and it is equivalent to this bin
newbin=1;
if(atlevelInverseStatus[currentlevel]==0){ // genuinely new level
nvblevel[l][m1]++;
nchunksatlevel[nvblevel[l][m1]-1]++;
atlevelInverseStatus[currentlevel]=1;
atlevelInverse[currentlevel]=nvblevel[l][m1]-1;
chunkposatlevel[nvblevel[l][m1]-1][nchunksatlevel[nvblevel[l][m1]-1]-1]=m2;
chunklenatlevel[nvblevel[l][m1]-1][nchunksatlevel[nvblevel[l][m1]-1]-1]=1;
atlevel[nvblevel[l][m1]-1]=currentlevel;
}
else if(atlevelInverseStatus[currentlevel]==1 || atlevelInverseStatus[currentlevel]==2){
if(atlevelInverseStatus[currentlevel]==2){ // if inactive, activate, because checked down already:Ind1!=Ind2, Ind1 is from previous level
atlevelInverseStatus[currentlevel]=1;
}
if(chunkposatlevel[atlevelInverse[currentlevel]][nchunksatlevel[atlevelInverse[currentlevel]]-1]+chunklenatlevel[atlevelInverse[currentlevel]][nchunksatlevel[atlevelInverse[currentlevel]]-1]==m2){
chunklenatlevel[atlevelInverse[currentlevel]][nchunksatlevel[atlevelInverse[currentlevel]]-1]++;
}
else if(chunkposatlevel[atlevelInverse[currentlevel]][nchunksatlevel[atlevelInverse[currentlevel]]-1]+chunklenatlevel[atlevelInverse[currentlevel]][nchunksatlevel[atlevelInverse[currentlevel]]-1]!=m2){
nchunksatlevel[atlevelInverse[currentlevel]]++;
chunkposatlevel[atlevelInverse[currentlevel]][nchunksatlevel[atlevelInverse[currentlevel]]-1]=m2;
chunklenatlevel[atlevelInverse[currentlevel]][nchunksatlevel[atlevelInverse[currentlevel]]-1]=1;
}
}
Ind1[atlevelInverse[currentlevel]]=Ind2_tmp;
for(int p=0; p<nwords; p++){
dummy1[atlevelInverse[currentlevel]][p]=dummy1_tmp[p];
dummy2[atlevelInverse[currentlevel]][p]=dummy2_tmp[p];
}
}
delete[] dummy1_tmp;
delete[] dummy2_tmp;
}
}
}
else if(currentlevel<=baselevel){
// case distinction: is this new at baselevel? atlevelInverse[basevel]=0:
Ind2[0]=0;
nRemaining[0]=0;
int i2=vbstartvt[l][m2];
int iMod2 = SNPMapInverse[i2];
// if (iMod2==-1) continue;
for (int p=0; p<nwords; p++){
dummy1[0][p] |= BinCarriers[l][m2][p];
dummy2[0][p] &= ~BinCarriers[l][m2][p];
Ind2[0]+=bitcount64(dummy1[0][p]);
nRemaining[0]+=bitcount64(dummy2[0][p]);
}
if(m1==0){
// cout<<"nRemaining[0]" <<nRemaining[0]<<endl;
}
if(nRemaining[0]==0 || Ind2[0]==nlinestfam){ // continue with next start position
break;
}
else if(Ind2[0]==Ind1[0]){ // continue with next end position
continue;
}
else if(Ind2[0]!=Ind1[0]){ // if something new at baselevel
newbin=1;
Ind1[0]=Ind2[0];
if(m2!=chunkposatlevel[0][nchunksatlevel[0]-1]+chunklenatlevel[0][nchunksatlevel[0]-1]){
nchunksatlevel[0]++;
chunkposatlevel[0][nchunksatlevel[0]-1]=m2;
}
chunklenatlevel[0][nchunksatlevel[0]-1]++;
}
currentlevel=baselevel;
}
// only if something new at currentlevel, check if at larger level, B(m1,m2)==B(m1+1,m2) and B(m1,m2)==B(m1,m2+1):
if(newbin==1){
int prevlevel=currentlevel; // if in level above something is found, check down at previouslevel
for(int m3=currentlevel+1; m3<nRareLimits[l]; m3++){
if(atlevelInverseStatus[m3]==3){
break;
}
else if(atlevelInverseStatus[m3]==1){
// sanity check
if(nCarriers[vbstartvt[l][chunkposatlevel[atlevelInverse[currentlevel]][0]]]>nCarriers[vbstartvt[l][chunkposatlevel[atlevelInverse[m3]][0]]] && atlevelInverseStatus[currentlevel]==1){
cout<<nCarriers[vbstartvt[l][chunkposatlevel[atlevelInverse[currentlevel]][0]]]<<" "<<nCarriers[vbstartvt[l][chunkposatlevel[atlevelInverse[m3]][0]]]<<endl;
cout<<"BUG in atlevelInverse["<<m3<<"] "<<atlevelInverse[m3]<<" "<<atlevelInverse[currentlevel]<<endl;
exit(1);
}
// prevlevel=m3;
// atlevelInverseStatus[m3]==1
nRemaining[atlevelInverse[m3]]=0;
// Ind1[atlevelInverse[m3]]=Ind1[atlevelInverse[prevlevel]];
Ind2[atlevelInverse[m3]]=0;
int i2=vbstartvt[l][m2];
int iMod2 = SNPMapInverse[i2];
// if (iMod2==-1) continue;
for (int p=0; p<nwords; p++){
dummy1[atlevelInverse[m3]][p] |= BinCarriers[l][m2][p];
dummy2[atlevelInverse[m3]][p] &= ~BinCarriers[l][m2][p];
Ind2[atlevelInverse[m3]]+=bitcount64(dummy1[atlevelInverse[m3]][p]);
nRemaining[atlevelInverse[m3]]+=bitcount64(dummy2[atlevelInverse[m3]][p]);
}
// B(m1,m2)==B(m1+1,m2): end of this and higher levels;
if(Ind2[atlevelInverse[m3]]==nlinestfam || nRemaining[atlevelInverse[m3]]==0){
atlevelInverseStatus[m3]=3;
for(int i=m3+1; i<nRareLimits[l]; i++){
// if(atlevelInverseStatus[i]==1 || atlevelInverseStatus[i]==2){
atlevelInverseStatus[i]=3;
// }
}
break;
}
else if(Ind2[atlevelInverse[m3]]!=Ind1[atlevelInverse[m3]]){ // existing open level
// check down if differrent from prevous level
if(Ind2[atlevelInverse[m3]]==Ind1[atlevelInverse[prevlevel]]){ // existing open level)
ndummyendsatlevel[atlevelInverse[m3]]++;
dummyendatlevel[atlevelInverse[m3]][ndummyendsatlevel[atlevelInverse[m3]]-1]=m2;
atlevelInverseStatus[m3]=2;
}
else if(Ind2[atlevelInverse[m3]]!=Ind1[atlevelInverse[prevlevel]]){ // existing open level
if(chunkposatlevel[atlevelInverse[m3]][nchunksatlevel[atlevelInverse[m3]]-1]+chunklenatlevel[atlevelInverse[m3]][nchunksatlevel[atlevelInverse[m3]]-1]!=m2){
nchunksatlevel[atlevelInverse[m3]]++;
chunkposatlevel[atlevelInverse[m3]][nchunksatlevel[atlevelInverse[m3]]-1]=m2;
}
chunklenatlevel[atlevelInverse[m3]][nchunksatlevel[atlevelInverse[m3]]-1]++;
Ind1[atlevelInverse[m3]]=Ind2[atlevelInverse[m3]];
prevlevel=m3;
}
}
}
}
} // new bin was found with m2 at lowest level
} // row termination position for baselevel is reached
// copy nchunks, chunkpos, chunklen
nchunks[l][m1]=new int[nvblevel[l][m1]];
if(!nchunks[l][m1]) die("Memory allocation error in nchunks[l][m1]!");
memcpy(nchunks[l][m1], nchunksatlevel, nvblevel[l][m1]*sizeof(int));
delete[] nchunksatlevel;
chunkpos[l][m1] = new int*[nvblevel[l][m1]];
if(!chunkpos[l][m1]) die("Memory allocation error in chunkpos[l][m1]!");
chunklen[l][m1] = new int*[nvblevel[l][m1]];
if(!chunklen[l][m1]) die("Memory allocation error in chunklen[l][m1]!");
for(int m3=0; m3<nvblevel[l][m1]; m3++){
chunkpos[l][m1][m3] = new int[nchunks[l][m1][m3]];
if(!chunkpos[l][m1][m3]) die("Memory allocation error in chunkpos[l][m1][m3]!");
chunklen[l][m1][m3] = new int[nchunks[l][m1][m3]];
if(!chunklen[l][m1][m3]) die("Memory allocation error in chunklen[l][m1][m3]!");
memcpy(chunkpos[l][m1][m3], chunkposatlevel[m3], nchunks[l][m1][m3]*sizeof(int));
memcpy(chunklen[l][m1][m3], chunklenatlevel[m3], nchunks[l][m1][m3]*sizeof(int));
}
for(int m=0; m<nRareLimits[l]; m++){
delete[] chunkposatlevel[m];
delete[] chunklenatlevel[m];
}
delete[] chunkposatlevel;
delete[] chunklenatlevel;
//consistency check:
for(int m2=0; m2<nvblevel[l][m1]; m2++){
for(int m3=0; m3<nchunks[l][m1][m2]; m3++){
// cout<<"nCarriers[vbstartvt["<<l<<"][chunkpos["<<l<<"]["<<m1<<"]["<<0<<"]["<<0<<"]]] "<<nCarriers[vbstartvt[l][chunkpos[l][m1][0][0]]]<<endl;
if(chunklen[l][m1][m2][m3]==0){
cout<<"BUG in chunklen!"<<endl;
exit(1);
}
for(int m4=0; m4<chunklen[l][m1][m2][m3]; m4++){
// cout<<"nCarriers[vbstartvt["<<l<<"][chunkpos["<<l<<"]["<<m1<<"]["<<m2<<"]["<<m3<<"]+"<<m4<<"]] "<<nCarriers[vbstartvt[l][chunkpos[l][m1][m2][m3]+m4]]<<endl;
if(optimalrare && nCarriers[vbstartvt[l][chunkpos[l][m1][m2][m3]+m4]]>nCarriers[vbstartvt[l][chunkpos[l][m1][m2][0]]]){
cout<<nCarriers[vbstartvt[l][chunkpos[l][m1][m2][0]]]<<" "<<nCarriers[vbstartvt[l][chunkpos[l][m1][m2][m3]+m4]]<<" "<<chunklen[l][m1][m2][m3]<<endl;
cout<<l<<" "<<m1<<" "<<m2<<" "<<m3<<" "<<m4<<" "<<map[vbstartvt[l][m1]].rs<<" "<<map[vbstartvt[l][chunkpos[l][m1][m2][m3]+m4]].rs<<endl;
cout<<"BUG in chunkpos, chunklen!"<<endl;
exit(1);
}
}
}
}
if(nvblevel[l][m1]==0){
cout<<"BUG in nvblevel[l][m1]"<<endl;
exit(1);
}
ndummyends[l][m1]=new int[nvblevel[l][m1]]();
if(!ndummyends[l][m1]) die("Memory allocation error in ndummyends[l][m1]!");
nchunkcluster[l][m1]=new int[nvblevel[l][m1]]();
if(!nchunkcluster[l][m1]) die("Memory allocation error in nchunkcluster[l][m1]!");
dummyend[l][m1]=new int*[nvblevel[l][m1]];
for(int m3=0; m3<nvblevel[l][m1]; m3++){
ndummyends[l][m1][m3]=ndummyendsatlevel[m3];
// cout<<"ndummyendsatlevel["<<m3<<"] "<<ndummyendsatlevel[m3]<<endl;
if(ndummyendsatlevel[m3]>0){
dummyend[l][m1][m3]=new int[ndummyendsatlevel[m3]]();
if(!dummyend[l][m1][m3]) die("Memory allocation error in ndummyends[l][m1][m3]!");
memcpy(dummyend[l][m1][m3],dummyendatlevel[m3], ndummyendsatlevel[m3]*sizeof(int));
}
else if(ndummyendsatlevel[m3]==0){
dummyend[l][m1][m3]=new int[1]();
if(!dummyend[l][m1][m3]) die("Memory allocation error in ndummyend[l][m1][m3]!");
}
}
for(int i=0; i<nRareLimits[l]; i++){
delete[] dummyendatlevel[i];
}
delete[] dummyendatlevel;
delete[] ndummyendsatlevel;
ndummyatlevel[l][m1]=new int*[nvblevel[l][m1]];
if(!ndummyatlevel[l][m1]) die("Memory allocation error in ndummyatlevel[l][m1]!");
dummypos[l][m1]= new int**[nvblevel[l][m1]];
if(!dummypos[l][m1]) die("Memory allocation error in dummypos[l][m1]!");
dummycluster[l][m1]= new int**[nvblevel[l][m1]];
if(!dummycluster[l][m1]) die("Memory allocation error in dummycluster[l][m1]!");
dummylevel[l][m1]= new int**[nvblevel[l][m1]];
if(!dummylevel[l][m1]) die("Memory allocation error in dummylevel[l][m1]!");
// count nchunkcluster: ndummyends[l][m1][m3]+1
// dummyends: if ndummyends>0, check if chunks extend beyond last end. if no, reduce nchunkcluster
for(int m3=0; m3<nvblevel[l][m1]; m3++){
nchunkcluster[l][m1][m3]=ndummyends[l][m1][m3]+1;
if(ndummyends[l][m1][m3]>0){
if(chunkpos[l][m1][m3][nchunks[l][m1][m3]-1]+chunklen[l][m1][m3][nchunks[l][m1][m3]-1]-1<=dummyend[l][m1][m3][ndummyends[l][m1][m3]-1]){
nchunkcluster[l][m1][m3]--;
}
// else if(chunkpos[l][m1][m3][nchunks[l][m1][m3]-1]+chunklen[l][m1][m3][nchunks[l][m1][m3]-1]-1==dummyend[l][m1][m3][ndummyends[l][m1][m3]-1]){
// cout<<"BUG in ndummyends!"<<endl;
// exit(1);
// }
}
if(nchunkcluster[l][m1][m3]==0){
cout<<"NCHUNKCLUSTER["<<l<<"]["<<m1<<"]["<<m3<<"] "<<nchunkcluster[l][m1][m3]<<endl;
}
//cout<<"nchunkcluster["<<l<<"]["<<m1<<"]["<<m3<<"] "<<nchunkcluster[l][m1][m3]<<endl;
ndummyatlevel[l][m1][m3]=new int[nchunkcluster[l][m1][m3]]();
if(!ndummyatlevel[l][m1][m3]) die("Memory allocation error in ndummyatlevel[l][m1][m3]!");
dummypos[l][m1][m3]= new int*[nchunkcluster[l][m1][m3]];
if(!dummypos[l][m1][m3]) die("Memory allocation error in dummypos[l][m1][m3]!");
dummycluster[l][m1][m3]= new int*[nchunkcluster[l][m1][m3]];
if(!dummycluster[l][m1][m3]) die("Memory allocation error in dummycluster[l][m1][m3]!");
dummylevel[l][m1][m3]= new int*[nchunkcluster[l][m1][m3]];
if(!dummylevel[l][m1][m3]) die("Memory allocation error in dummylevel[l][m1][m3]!");
}
int **startposatlevel=new int*[nvblevel[l][m1]];
if(!startposatlevel) die("Memory allocation error in startposatlevel!");
for(int m3=0; m3<nvblevel[l][m1]; m3++){
// cout<<"alloc "<<m1<<" "<<nvblevel[l][m1]<<" "<<m3<<" "<<nchunkcluster[l][m1][m3]<<endl;
startposatlevel[m3]=new int[nchunkcluster[l][m1][m3]]();
if(!startposatlevel[m3]) die("Memory allocation error in startposatlevel[m3]!");
}
// find startposatlevel[level][cluster]. startpos[level][>0] is first position after ndummyends
/*if(m1==1966){
cout<<"nvblevel["<<l<<"]["<<m1<<"] "<<nvblevel[l][m1]<<endl;
} */
for(int k=0; k<nvblevel[l][m1]; k++){
//atlevelCarriers[k]=nCarriers[vbstartvt[l][chunkpos[l][m1][k][0]]];