-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdecluster.cpp
1537 lines (1297 loc) · 42.1 KB
/
decluster.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
//gpl thorfinn@binf.ku.dk
#include <htslib/hts.h>
#include <htslib/sam.h>
#include <htslib/thread_pool.h>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <map>
#include <vector>
#include <cmath>
#include <getopt.h>
#include <ctime>
#include <math.h>
#include "decluster.h"
#ifndef MIN
#define MIN(a,b) ((a)<(b)?(a):(b))
#endif
#ifndef MAX
#define MAX(a,b) ((a)>(b)?(a):(b))
#endif
size_t *histogram = NULL;
size_t histogram_l = 4096;
std::map<int,int> len_hist;
std::map<int,int> gc_hist;
std::map<int,int> cx_hist;
void printHist(std::map<int,int> myMap){
for (const auto& it:myMap){
fprintf(stderr,"\n%d\t%d",it.first,it.second);
}
}
int globalX(double x, int xlen, short int swath){
return ((swath-1)*(xlen))+(x);
}
int globalY(double y, int ylen, unsigned short int nTiles, unsigned short int tile){
return ((nTiles-tile)*(ylen))+(y);
}
typedef struct
{
uint16_t a;
uint16_t c;
uint16_t g;
uint16_t t;
uint16_t n;
uint16_t o; // o (others) = "=" + MRSVWYHKDB ambiguity codes
//percent values
int complexity;
int gcc; //gc content
}r_aux;
/* ====================================
* == sequence complexity estimation ==
* ====================================
*
* calculation method adapted from fastp => https://github.com/OpenGene/fastp/blob/424900e376a02033a32b623bc5c836897f6b7e5a/src/filter.cpp#L67
*
* (no of bases that are different from the next base) / (total number of comparisons)
* |__ read[basei] != read[basei+1]
*
* e.g.
* -> GATT
* 1+1+0
* = 2/3
*
*/
r_aux get_aux_stats(r_aux raux, uint8_t *qseq, int rLen, int aux_dostat){
// uint8_t coding:
// -12-4---8------5
// =ACMGRSVTWYHKDBN
int cx=0;
for (int i=0; i<rLen; i++){
//printf("\n myi %d\n",bam_seqi(qseq,i));
switch (bam_seqi(qseq, i)) {
case 1:
raux.a++;
//if different from next base, increase complexity
if (i==rLen-1) break;
if (bam_seqi(qseq,i+1) != 1) cx++;break;
break;
case 2:
raux.c++;
if (i==rLen-1) break;
if (bam_seqi(qseq,i+1) != 2) cx++;break;
break;
case 4:
raux.g++;
if (i==rLen-1) break;
if (bam_seqi(qseq,i+1) != 4) cx++;break;
break;
case 8:
raux.t++;
if (i==rLen-1) break;
if (bam_seqi(qseq,i+1) != 8) cx++;break;
break;
case 15:
raux.n++;
//no complexity check for Ns
//if (i==rLen-1) break;
//switch (bam_seqi(qseq,i+1)){
//case 15: break;
//default: cx++; break;
//}
break;
default:
raux.o++;
break;
}
}
//gc content of fragment
raux.gcc=round(((double)(raux.g+raux.c)/(double)rLen)*100);
raux.complexity=round(((float)cx/(float)(rLen-1))*100);
if(aux_dostat){
len_hist[rLen]++;
gc_hist[raux.gcc]++;
cx_hist[raux.complexity]++;
}
return raux;
}
void tsktsk(){
fprintf(stderr,"\t-> Incrementing histogram of duplicates from:%lu to %lu\n",histogram_l,2*histogram_l);
size_t *tmptmp = new size_t[2*histogram_l];
for(int i=0;i<2*histogram_l;i++)
tmptmp[i] = 0;
for(int i=0;i<histogram_l;i++)
tmptmp[i] = histogram[i];
histogram_l = 2*histogram_l;
histogram=tmptmp;
}
typedef struct{
bam1_t **d;//data
unsigned l;//at pos
unsigned m;//maxpos;
//int lid;//libid
}queue_t;
double pxdist=12000;
size_t totaldups=0;
size_t pcrdups=0;
size_t clustdups=0;
size_t nproc=0;
size_t nprocfilt=0;
size_t purecount=0;
int nreads_per_pos=4;//assuming this is the number reads per pos. If larger the program will reallocate
char out_mode[5]="wb";
//below is just the average/mean calculated fancy
double CMA =0; //cumulative moving average
queue_t *init_queue_t(int l){
// fprintf(stderr,"initializing queue with: %d elements\n",l);
queue_t *ret =(queue_t *) malloc(sizeof(queue_t));
ret->d =(bam1_t **) malloc(l*sizeof(bam1_t*));
ret->l=0;
ret->m=l;
//ret->lid=1;
for(int i=0;i<ret->m;i++){
// fprintf(stderr,"queue[%d] init\n",i);
ret->d[i] = bam_init1();
}
return ret;
}
void realloc_queue(queue_t *q){
// fprintf(stderr,"reallcing from: q:%d to q:%d\n",q->m,2*q->m);
for(int i=0;0&&i<q->l;i++)
fprintf(stderr,"inqueu[%d].pos:%d\n",i,(int)q->d[i]->core.pos);
bam1_t **d2 = (bam1_t **) malloc(2*q->m*sizeof(bam1_t*));
for(int i=0;i<q->l;i++)
d2[i] = q->d[i];
for(int i=q->l;i<2*q->m;i++){
d2[i] = bam_init1();
d2[i]->core.pos=-1;
}
free(q->d);
q->d=d2;
q->m=2*q->m;
for(int i=0;0&&i<q->m;i++)
fprintf(stderr,"onqueu[%d].pos:%d\n",i,(int)q->d[i]->core.pos);
}
htsFormat *dingding2 =(htsFormat*) calloc(1,sizeof(htsFormat));
//TODO?
// FIXME: we should also check the LB tag associated with each alignment
//unconstanted
char *bam_get_library(bam_hdr_t *h, const bam1_t *b)
{
//TODO?
// Slow and inefficient. Rewrite once we get a proper header API.
const char *rg;
char *cp = h->text;
rg = (char *)bam_aux_get(b, "RG");
if (!rg)
return NULL;
else
rg++;
// Header is guaranteed to be nul terminated, so this is valid.
while (*cp) {
char *ID, *LB;
char last = '\t';
// Find a @RG line
if (strncmp(cp, "@RG", 3) != 0) {
while (*cp && *cp != '\n') cp++; // skip line
if (*cp) cp++;
continue;
}
// Find ID: and LB: keys
cp += 4;
ID = LB = NULL;
while (*cp && *cp != '\n') {
if (last == '\t') {
if (strncmp(cp, "LB:", 3) == 0)
LB = cp+3;
else if (strncmp(cp, "ID:", 3) == 0)
ID = cp+3;
}
last = *cp++;
}
if (!ID || !LB)
continue;
// Check it's the correct ID
if (strncmp(rg, ID, strlen(rg)) != 0 || ID[strlen(rg)] != '\t')
continue;
// Valid until next qual
static char LB_text[1024];
for (cp = LB; *cp && *cp != '\t' && *cp != '\n'; cp++)
;
strncpy(LB_text, LB, MIN(cp-LB, 1023));
LB_text[MIN(cp-LB, 1023)] = 0;
// Return it; valid until the next qual.
return LB_text;
}
return NULL;
}
struct ltstr
{
bool operator()(const char* s1, const char* s2) const
{
return strcmp(s1, s2) < 0;
}
};
typedef std::map<char*,int,ltstr> aMap;
//doublemap
aMap char2int;
typedef struct{
bam1_t *d;
int64_t xs;
int64_t ys;
int seqlen;
}reldata;//<-releavant data
//typedef std::map<size_t,std::map<size_t,std::vector<reldata>> > dMap;
char *mystr =new char[2048];
double euc_dist(reldata &a,reldata &b){
double dx=a.xs-b.xs;
double dy=a.ys-b.ys;
double dist = sqrt(dx*dx+dy*dy);
return dist;
}
void print_clusters(std::vector<std::vector<int> > &clusters){
fprintf(stderr,"[print clusters] cluster.size():%lu\n",clusters.size());
for(int i=0;i<clusters.size();i++){
fprintf(stderr,"[print clusters] cluster:%i \n",i);
std::vector<int> &tmp = clusters[i];
for(int j=0;j<tmp.size();j++)
fprintf(stderr," %d ",tmp[j]);
fprintf(stderr,"\n");
}
}
void plugin(std::map<size_t,std::map<size_t,std::vector<reldata> >> &mymap, bam1_t *b,bam_hdr_t *hdr, char *coordtype, int xLength, int yLength, int nTiles){
reldata point;
point.d=b;
mystr = strncpy(mystr,bam_get_qname(b),2048);
// fprintf(stderr,"mystr: \'%s\'\n",mystr);
strtok(mystr,"\n\t:");//machine
strtok(NULL,"\n\t:");//runname
strtok(NULL,"\n\t:");//flowcell
unsigned short int lane = atoi(strtok(NULL,"\n\t:"));
int surf, swath,tile;
sscanf(strtok(NULL,"\n\t:"), "%1d%1d%2d", &surf, &swath, &tile);
#if 0
fprintf(stderr,"->->->%d %d %d\n\n",surf, swath, tile);
#endif
if( ! strcmp(coordtype,"g") || ! strcmp(coordtype,"global") ){
point.xs = globalX(atoi(strtok(NULL,"\n\t:")),xLength,swath);
point.ys = globalY(atoi(strtok(NULL,"\n\t:")),yLength,nTiles,tile);
// fprintf(stderr,"\n\npoint.xs point.ys!!!%d %d\n\n",point.xs,point.ys);
}else if (! strcmp(coordtype,"l") || ! strcmp(coordtype,"local") ){
point.xs = atoi(strtok(NULL,"\n\t:"));
point.ys = atoi(strtok(NULL,"\n\t:"));
}else{
fprintf(stderr,"\nUnknown coordinate type %s; will exit\n",coordtype);
exit(0);
}
point.seqlen = b->core.l_qseq;
int libid = 0;
char *lb = bam_get_library(hdr,b);
if(lb){
if(char2int.find(lb)==char2int.end())
char2int[strdup(lb)] = char2int.size();
libid = char2int.find(lb)->second;
if(char2int.size()>1){
fprintf(stderr,"cannot work with multiple libs; will exit\n");
exit(0);
//if(char2int.size()>998)
//fprintf(stderr,"number of libraries is almost above 998, program will exit. Program should be updated\n");
//exit(0);
}
}
#if 0
fprintf(stderr,"surface:%d, swath:%d, tile:%d, libid:%d lane:%d rlen:%d xs:%d ys:%d\n",surf,swath,tile,libid,lane,b->core.l_qseq,point.xs,point.ys);
#endif
//
// given tile id 1234
// surf, swath and tile are officially defined as following:
//
// 1 2 34
// - - --
// surface swath tile
//
size_t key = b->core.l_qseq;
size_t key2=surf;
key2 += lane*1e1;
if (! strcmp(coordtype,"l") || ! strcmp(coordtype,"local") ){
key2 += swath*1e2;
key2 += tile*1e4;
}
//mymap is the outer map
#if 0
fprintf(stderr,"\nkey:%d, key2:%d surface:%d, swath:%d, tile:%d, libid:%d lane:%d rlen:%d xs:%d ys:%d\n----\n\n",key,key2,surf,swath,tile,libid,lane,b->core.l_qseq,point.xs,point.ys);
#endif
std::map<size_t,std::map<size_t, std::vector<reldata>>>::iterator it= mymap.find(key);
//key not found
if(it==mymap.end()){
std::map<size_t,std::vector<reldata> > inmap;
std::vector<reldata> rd;
rd.push_back(point);
mymap[key][key2]=rd;
}else{
std::map<size_t,std::vector<reldata> >::iterator in =it->second.find(key2);
//key2 not found
if(in==it->second.end()){
std::vector<reldata> rd;
rd.push_back(point);
it->second[key2]=rd;
}else{
in->second.push_back(point);
}
}
}
/*
* ================
* = OUTPUT FILES =
* ================
*
* fp = noclusterdup = pure + non-cluster duplicates + one read from each cluster
* fp2 = onlyclusterdup = contains all reads in a cluster for each cluster
*
*/
void plugout(std::map<size_t,std::map<size_t,std::vector<reldata> >> &mymap, bam_hdr_t *hdr, samFile *fp, samFile *fp2,std::vector<size_t> &counter){
int n_readlen=0;
size_t dcount;
int plug=0;
for(std::map<size_t,std::map<size_t,std::vector<reldata> >>::iterator it=mymap.begin();it!=mymap.end();it++) {
//outer iteration:
//|__ same read length
// same mapping position is already a requirement before plugout is called
//dcount= observed fragment count, to give preseq
// NB this also includes non duplicates
dcount=0;
std::map<size_t,std::vector<reldata>>::iterator in;
in = it->second.begin();
std::vector<reldata> &rd_out=in->second;
for (in = it->second.begin();in !=it->second.end();++in){
//inner iteration:
//|__ same surface+same lane
std::vector<reldata> &rd=in->second;
//just a duplicate alone in a SURFACE+LANE pair
//first it came with its family
//but it is alone now because he has a unique length
if(rd.size()==1){
if(rd_out.size()==1){
dcount++;
if(fp){
ASSERT(sam_write1(fp, hdr,rd_out[0].d)>=0);
}
continue;
}
totaldups+=rd.size();
pcrdups++;
dcount++;
counter.push_back(dcount);
dcount=0;
if(fp){
ASSERT(sam_write1(fp, hdr,rd[0].d)>=0);
}
continue;
}
totaldups+=rd.size();
#if 0
for(int i=0;i<rd.size();i++){
fprintf(stderr,"\tcc key: out %lu in %lu/%lu val: xs:%d ys:%d pos:%d\n",it->first,in->first,rd.size(),rd[i].xs,rd[i].ys,rd[i].d->core.pos+1);
}
#endif
if(rd.size()==2){
double dist = euc_dist(rd[0],rd[1]);
//fprintf(stderr,"dist is:%f\n",dist);
if(dist>pxdist){
//not part of same cluster
//we have 2 pcr duplicates
dcount+=2;
pcrdups+=2 ;
if(fp){
ASSERT(sam_write1(fp, hdr,rd[0].d)>=0);
ASSERT(sam_write1(fp, hdr,rd[1].d)>=0);
}
}else{
//same cluster
//two reads form a cluster
//we have 1 pcr duplicate and 1 cluster duplicate
dcount++;
pcrdups++;
clustdups++ ;
if(fp){
ASSERT(sam_write1(fp, hdr,rd[0].d)>=0);
}
if(fp2){
//there are two reads in the cluster in total
ASSERT(sam_write1(fp2, hdr,rd[0].d)>=0);
ASSERT(sam_write1(fp2, hdr,rd[1].d)>=0);
}
}
continue;
}
if(rd.size()==3){
double dist[3] = {euc_dist(rd[0],rd[1]),euc_dist(rd[0],rd[2]),euc_dist(rd[1],rd[2])};
double d01=dist[0];
double d02=dist[1];
double d12=dist[2];
int val=0; //nr of reads within pxdist
for(int i=0;i<3;i++)
if(dist[i]<pxdist)
val++;
if(val==0){
// not part of the same cluster
// 3 pcr duplicates
dcount += 3;
pcrdups +=3 ;
if(fp){
ASSERT(sam_write1(fp, hdr,rd[0].d)>=0);
ASSERT(sam_write1(fp, hdr,rd[1].d)>=0);
ASSERT(sam_write1(fp, hdr,rd[2].d)>=0);
}
}else if (val>=2){
// 3 reads form a cluster
// one pcr duplicate + 2 cluster duplicates
dcount++;
pcrdups++;
clustdups+=2 ;
if(fp){
ASSERT(sam_write1(fp, hdr,rd[0].d)>=0);
}
if(fp2){
ASSERT(sam_write1(fp2, hdr,rd[0].d)>=0);
ASSERT(sam_write1(fp2, hdr,rd[1].d)>=0);
ASSERT(sam_write1(fp2, hdr,rd[2].d)>=0);
}
}else if (val==1){
//2 in cluster one outside
//1 pcr duplicate + (1 pcr duplicate+1cluster duplicate)
pcrdups +=2;
dcount +=2;
clustdups++ ;
if(d01<pxdist){
//rd0 and rd1 defines a cluster, rd2 outside
if(fp){
ASSERT(sam_write1(fp, hdr,rd[0].d)>=0);
ASSERT(sam_write1(fp, hdr,rd[2].d)>=0);
}
if(fp2){
ASSERT(sam_write1(fp2, hdr,rd[0].d)>=0);
ASSERT(sam_write1(fp2, hdr,rd[1].d)>=0);
}
}
else if(d02<pxdist){
//rd0 and rd2 defines a cluster, rd1 outside
if(fp){
ASSERT(sam_write1(fp, hdr,rd[0].d)>=0);
ASSERT(sam_write1(fp, hdr,rd[1].d)>=0);
}
if(fp2){
ASSERT(sam_write1(fp2, hdr,rd[0].d)>=0);
ASSERT(sam_write1(fp2, hdr,rd[2].d)>=0);
}
}
else if(d12<pxdist){
//rd1 and rd2 defines a cluster, rd0 outside
if(fp){
ASSERT(sam_write1(fp, hdr,rd[0].d)>=0);
ASSERT(sam_write1(fp, hdr,rd[1].d)>=0);
}
if(fp2){
ASSERT(sam_write1(fp2, hdr,rd[1].d)>=0);
ASSERT(sam_write1(fp2, hdr,rd[2].d)>=0);
}
}else{
fprintf(stderr,"never happens\n");
exit(0);
}
}else{
fprintf(stderr,"never happens");
exit(0);
}
continue;
}
//vector of vectors, containing ids for the reads that cluster together
std::vector<std::vector<int> > clusters;
for(int i=0;i<rd.size();i++) {
//print_clusters(clusters);
// fprintf(stderr,"analysing rd:%d\n",i);
char dingdongsong[rd.size()];//initialize a hit vector that tells us if the current read is close enough to the different clusters
memset(dingdongsong,0,rd.size());
for(int j=0;j<clusters.size();j++){//loop over the different clutsters
std::vector<int> aclust = clusters[j];
// fprintf(stderr,"aclust.size():%lu\n",aclust.size());
for(int jj=0;jj<aclust.size();jj++){//loop over every read for each cluster
double dist = euc_dist(rd[i],rd[aclust[jj]]);
// fprintf(stderr,"\t-> dist(%d,%d):%f\n",i,aclust[jj],dist);
if(dist<pxdist){
dingdongsong[j]=1;
continue;
}
}
}
#if 0
for(int i=0;i<rd.size();i++)
fprintf(stderr,"dingdong i:%d %d\n",i,dingdongsong[i]);
#endif
//now dingdongsong contains a 0/1 array indicating which existing clusters it belongs to.
int nclust=0;//counter for how many clusters
for(int s=0;s<rd.size();s++){
nclust += dingdongsong[s];
}
// fprintf(stderr,"nclust: %d\n",nclust);
if(nclust==0){//case where it is not within pixel dist to any
//fprintf(stderr,"\t-> creating new cluster\n");
std::vector<int> tmp;tmp.push_back(i);
clusters.push_back(tmp);
continue;
}if(nclust==1){//
// fprintf(stderr,"only close enough to one cluster put it back in that clusterlist\n");
for(int j=0;j<rd.size();j++)
if(dingdongsong[j]==1){
// fprintf(stderr,"pushing back i:%d at j:%d\n",i,j);
clusters[j].push_back(i);
continue;
}
}if(nclust>1){
// fprintf(stderr,"multiclust: nclust:%d\n",nclust);
// keep array is number of clusters long, and will contain which clusters to merge
int keep[nclust];
int at=0;
for(int j=0;j<rd.size();j++){
if(dingdongsong[j]){
// fprintf(stderr,"keep[%d]:%d\n",at,j);
keep[at++] = j;
}
}
for(int j=1;j<nclust;j++){
clusters[keep[0]].insert(clusters[keep[0]].end(),clusters[j].begin(),clusters[j].end());
}
//print_clusters(clusters);
for(int j=nclust-1;j>0;j--){
clusters.erase(clusters.begin()+keep[j]);
}
// we started with read i, and this caused us to merge clusters because it is within pixel distance to both
// , now we finally append the ith read into the merged cluster list
clusters[keep[0]].push_back(i);
// print_clusters(clusters);
}
}
//printf("\n\n---------printing clusters:\n\n");
//print_clusters(clusters);
//loop over groupings
for(int i=0;i<clusters.size();i++){
std::vector<int> &tmp = clusters[i];
if(tmp.size()>0){
//one cluster of cluster duplicates
//one pcr duplicate [founder]
//rest is its cluster duplicates
pcrdups++;
dcount++;
if(fp)
ASSERT(sam_write1(fp, hdr,rd[tmp[0]].d)>=0);
for(int j=0;j<tmp.size();j++){
//j not equal to 0; to exclude one from each cluster
if(j)
clustdups++;
if(fp2)
ASSERT(sam_write1(fp2, hdr,rd[tmp[j]].d)>=0);
}
}
}
}
counter.push_back(dcount);
dcount=0;
}
}
void printmap(FILE *fp,std::map<size_t,std::vector<reldata> > &mymap){
fprintf(fp,"std::map.size:%lu\n",mymap.size());
for(std::map<size_t,std::vector<reldata> >::iterator it=mymap.begin();it!=mymap.end();it++){
fprintf(fp,"key:%lu\n",it->first);
std::vector<reldata> &rd=it->second;
for(int i=0;i<rd.size();i++)
fprintf(fp,"\tval: xs:%ld ys:%ld\n",rd[i].xs,rd[i].ys);
}
}
void do_magic(queue_t *q,bam_hdr_t *hdr,samFile *fp,samFile *fp2,samFile *nodupFP, char *coordtype, int xLength, int yLength, int nTiles,samFile *out5){
// fprintf(stderr,"do_magic queue->l:%d queue->m:%d chr:%d pos:%ld\n",q->l,q->m,q->d[0]->core.tid,q->d[0]->core.pos);
//fprintf(stderr,"@@@@@@info\t%d\t%d\n",q->d[0]->core.pos+1,q->l);
//totaldups += q->l -1;
std::map<size_t,std::map<size_t,std::vector<reldata>> > mymapF;
std::map<size_t,std::map<size_t,std::vector<reldata>> > mymapR;
bam1_t *b = NULL;
//first loop over all reads(these have the same chr/pos, and group these into queues that are pertile,perlib,pereverything)
for(int i=0;i<q->l;i++) {
b = q->d[i];
if(out5)
ASSERT(sam_write1(out5, hdr,b)>=0);
if(0&&!(b->core.flag &BAM_FDUP)){//never do this,
if(fp)
ASSERT(sam_write1(fp, hdr,b)>=0);
continue;
}
if(bam_is_rev(b)){
plugin(mymapR,b,hdr,coordtype,xLength,yLength,nTiles);
}else{
plugin(mymapF,b,hdr,coordtype,xLength,yLength,nTiles);
}
}
std::vector<size_t> counter;
plugout(mymapF,hdr,fp,fp2,counter);
plugout(mymapR,hdr,fp,fp2,counter);
for (int c=0; c<counter.size();c++){
if(counter[c]>=histogram_l)
tsktsk();
histogram[counter[c]]++;
}
//ASSERT(sam_write1(fp3, hdr, q->d[lrand48() %q->l])>=0); //<- this one prints a random read as the represent of the dups
if(mymapF.size()>0){
for(std::map<size_t,std::map<size_t,std::vector<reldata>>>::iterator it=mymapF.begin();it!=mymapF.end();it++){
std::vector<reldata> &re = it->second.rbegin()->second;
if(nodupFP)
ASSERT(sam_write1(nodupFP, hdr,re[0].d));
purecount++;
// fprintf(stderr,"%f len:%d purecount:%d\n",CMA,re[0].d->core.l_qseq,purecount);
CMA = (re[0].d->core.l_qseq+(purecount-1)*CMA)/(1.0*purecount);
//fprintf(stderr,"%f len:%d purecount:%d\n",CMA,re[0].d->core.l_qseq,purecount);
}
}
if(mymapR.size()>0) {
for(std::map<size_t,std::map<size_t,std::vector<reldata>>>::iterator it=mymapR.begin();it!=mymapR.end();it++) {
std::vector<reldata> &re = it->second.rbegin()->second;
if(nodupFP)
ASSERT(sam_write1(nodupFP, hdr,re[0].d));
purecount++;
CMA = (re[0].d->core.l_qseq+(purecount-1)*CMA)/(1.0*purecount);
}
}
}
int usage(FILE *fp, int is_long_help)
{
fprintf(fp,
"\n"
"Usage: ./decluster [options] <in.bam>|<in.sam>|<in.cram> \n"
"\n"
"Options:\n"
// output options
" -b Output BAM\n"
" -C Output CRAM (requires reference fasta; use -T)\n"
" -o FILE Output file name\n"
" -p INT Pixel distance (default: 12000)\n"
" -T FILE Reference in the fasta format (required for reading and writing crams)\n"
" -@ INT Number of threads to use\n"
" -a Only use the single end part of the bam (default: 1 (enabled), use -a 0 to disable)\n"
"\n"
" -0 Only calculate statistics; do not run preseq (default: off)\n"
" -w Only calculate statistics and run preseq; do not output bam files (default: off)\n"
" -W Calculate additional statistics (default: 0, off)\n"
" Output summary table and frequency distribution tables\n"
" MSC - Mean sequence complexity\n"
" MGC - Mean GC content\n"
" MFS - Mean fragment size\n"
" SCD - Sequence complexity distribution\n"
" GCD - GC content distribution\n"
" FSD - Fragment size distribution\n"
" Example: To extract sequence complexity distribution, use:\n"
" `grep ^SCD out.dupstat.txt | cut -f 2-`\n"
"\n"
"\n"
" Filters\n"
" -------\n"
" -m Discard unmapped reads (default: off)\n"
" -q INT Mapping quality filter (default: off)\n"
" -X INT Sequence complexity filter, discard read if complexity<INT (0-100, default: off)\n"
" -G INT Maximum GC content allowed, discard read if GC content>INT (0-100, default: off)\n"
" -l INT Minimum read length allowed, discard read if read length<INT (default: off)\n"
" -L INT Maximum read length allowed, discard read if read length>INT (default: off)\n"
"\n"
"\n"
" Sequencing platform specifications\n"
" --------------------------------- \n"
" --getConf Infer sequencing platform specific configurations from data (xLength, yLength and nTiles)\n"
"\n"
" -d, --coordType STR\n"
" Coordinate calculation method used in decluster (local or global, default: global)\n"
" -A, --xLength INT\n"
" Length of each tile's x axis, to be used in global coordinate calculations (default: 32103)\n"
" -B, --yLength INT\n"
" Length of each tile's y axis, to be used in global coordinate calculations (default: 36059)\n"
" -E, --nTiles INT\n"
" Number of tiles, to be used in global coordinate calculations (default: 78)\n"
"\n"
"Options for performing extraplation (mirrored from preseq)\n"
" -D INT <1,2,3>\n"
" Defects mode to extrapolate without testing for defects\n"
" -D 0 Only do defect disabled lc extrap\n"
" -D 1 Only do defect enabled lc extrap (default)\n"
" -D 2 Do both defect enabled and defect disabled lc extrap (default)\n"
" -v Verbose mode\n"
" -e maximum extrapolation (default: 1e+10)\n"
" -s step size in extrapolations (default: 1e+06)\n"
" -n number of bootstraps (default: 100)\n"
" -c level for confidence intervals (default: 0.95)\n"
" -x maximum number of terms\n"
" -r, --seed seed for random number generator\n"
"\n"
"\nThe Preseq paper:\n Daley, T., Smith, A. Predicting the molecular complexity of sequencing libraries.\n Nat Methods 10, 325–327 (2013). https://doi.org/10.1038/nmeth.2375\n"
"\n"
"\n"
// read filters
);
if (is_long_help)
fprintf(fp,
"\nNotes:\n"
"\n"
"1. This program is useful for splitting a sorted bam/cram into two files\n"
" 1) file containing cluster duplicates\n"
" 2) file without any cluster duplicates, but including other kinds of duplicates\n"
"\n"
" Example: \n"
"\t ./decluster input.bam -o outfiles -p 5000\n"
"\n"
" Details:\n"
" It loops over input files, and reads with identical positions\n"
" are assumed to be duplicates. It stratifes the duplicates over tiles and lanes\n"
" and uses the euclidian distance (sqrt(da^2+db^2)) to 'find' clusters. Clusters being defined\n"
" as a group of reads that are within pxdist to another read within the cluster\n"
" program assumes read names (QNAME) look like: \'A00706:12:HGNY3DSXX:3:1110:11930:4867\'\n"
" assuming \'discarded:discarded:discared:lanenumber:tileinfo:xpos:ypos\'\n"
"\n"
" tileinfo is a 4 digit number including the identifiers for surface, swath and tile\n"
" for given tileinfo 1234, 1=surface, 2=swath, 34=tile\n"
" 1 2 34\n"
" - - --\n"
" surface swath tile\n"
"\n"
" For more details, see Illumina NovaSeq 6000 Sequencing System Guide \n"
" Document #1000000019358v14 Material #20023471\n"
"\n\n");
return 0;
}
void parse_platformconfig(char *fname){
samFile *in=NULL;
if((in=sam_open_format(fname,"r",dingding2))==NULL ){
fprintf(stderr,"[%s] nonexistant file: %s\n",__FUNCTION__,fname);
exit(0);
}
bam_hdr_t *hdr = sam_hdr_read(in);
bam1_t *b = bam_init1();
int8_t maxswath=0;
int8_t maxtile=0;
uint32_t minx=100000;
uint32_t miny=100000;
uint32_t maxx=0;
uint32_t maxy=0;
int ret;
int refId=-1;
purecount=0;
while(((ret=sam_read1(in,hdr,b)))>=0){
mystr = strncpy(mystr,bam_get_qname(b),2048);
strtok(mystr,"\n\t:");//machine
strtok(NULL,"\n\t:");//runname
strtok(NULL,"\n\t:");//flowcell
strtok(NULL,"\n\t:");//lane
//assuming swath tile counts are the same for all lanes
int surf, swath,tile;
sscanf(strtok(NULL,"\n\t:"), "%1d%1d%2d", &surf, &swath, &tile);
maxswath=MAX(swath,maxswath);
maxtile=MAX(tile,maxtile);
int32_t xs = atoi(strtok(NULL,"\n\t:"));
int32_t ys = atoi(strtok(NULL,"\n\t:"));
minx=MIN(minx,xs);
maxx=MAX(maxx,xs);
miny=MIN(miny,ys);
maxy=MAX(maxy,ys);
}
//assuming numbers start with 1; max observed value of tiles eq number of tiles
fprintf(stderr,
"\tMinimum x axis value observed: %d\n"
"\tMaximum x axis value observed: %d\n"
"\tMinimum y axis value observed: %d\n"
"\tMaximum y axis value observed: %d\n"
"\tEstimated length of x axis per tile: %d\n"
"\tEstimated length of y axis per tile: %d\n"
"\tNumber of swaths: %d\n"
"\tNumber of tiles: %d\n"
, minx, maxx, miny, maxy,maxx-minx, maxy-miny, maxswath,maxtile);
delete [] mystr;
bam_destroy1(b);
hts_opt_free((hts_opt *)dingding2->specific);
free(dingding2);
free(fname);
}
void parse_sequencingdata(char *fn_out,char *refName,char *fname, int stats_nopreseq,int stats_only,int nthreads,int mapped_only,int se_only,int mapq,char *onam3,FILE *fp, int complexity_thr, int gc_thr, int aux_stats, int min_rLen, int max_rLen, char *coordtype, int xLength, int yLength, int nTiles){
htsThreadPool p = {NULL, 0};
samFile *in=NULL;
samFile *out=NULL;
samFile *out2=NULL;
samFile *nodupFP=NULL;
samFile *out5=NULL;
char onam1[2048]="";
char onam2[2048]="";
char onam4[2048]="";
char onam5[2048]="";
strcat(onam1,fn_out);
strcat(onam2,fn_out);
strcat(onam4,fn_out);
strcat(onam5,fn_out);
if(out_mode[1]=='b'){
strcat(onam1,".noClusterDup.bam");
strcat(onam2,".clusterDupAssoc.bam");
strcat(onam4,".noDup.bam");
strcat(onam5,".dupAssoc.bam");
}else{
strcat(onam1,".noClusterDup.cram");
strcat(onam2,".clusterDupAssoc.cram");
strcat(onam4,".noDup.cram");
strcat(onam5,".dupAssoc.cram");
}
if(refName){
char *ref =(char*) malloc(10 + strlen(refName) + 1);
sprintf(ref, "reference=%s", refName);