Repository navigation
Expand file tree
/
Copy pathrealign_cm.cpp
More file actions
1903 lines (1815 loc) · 63.8 KB
/
Copy pathrealign_cm.cpp
File metadata and controls
1903 lines (1815 loc) · 63.8 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
/**** std library ****/
#include <iostream>
#include <string>
#include <map>
#include <cassert>
#include <math.h>
#include <vector>
#include <set>
#include <fstream>
#include <algorithm>
/**** zlib ****/
#include <zlib.h>
/**** htslib ****/
#include "htslib/hts.h"
#include "htslib/hfile.h"
#include "htslib/sam.h"
#include "htslib/kseq.h"
#include "htslib/regidx.h"
#include "htslib/thread_pool.h"
#include "htslib/hts_log.h"
/**** edlib ****/
#include "utils/edlib.h"
/**** custom codes ****/
#include "utils/incr_array.h"
#include "utils/MultiThread.h"
/* ************************************************************************
*
* @section: utils
*
*************************************************************************/
KSEQ_INIT(gzFile, gzread)
inline float round2(float var)
{
return float( (int)(var * 100 + .5) ) / float(100) ;
}
// prob <--> phred
static double g_qual2prob[256];
#define Phred2Prob(p) g_qual2prob[int(p)]
void InitQual2Prob()
{
for (int i = 0; i < 256; ++i)
g_qual2prob[i] = pow(10, -i/10.0);
}
#define bam_is_r1(b) (((b)->core.flag&BAM_FREAD1) != 0)
#define bam_is_r2(b) (((b)->core.flag&BAM_FREAD2) != 0)
#define bam_is_unmap(b) (((b)->core.flag&BAM_FUNMAP) != 0)
#define bam_is_munmap(b) (((b)->core.flag&BAM_FMUNMAP) != 0)
#define bam_is_secondary(b) (((b)->core.flag&BAM_FSECONDARY) != 0)
#define bam_is_supplementary(b) (((b)->core.flag&BAM_FSUPPLEMENTARY) != 0)
#define BLOCK_SIZE 1024*1024
/*
* @abstract: return true if S in cigar string
*/
bool is_softclip_read(const bam1_t *b)
{
uint32_t* cigar_data = bam_get_cigar(b);
for( unsigned int i = 0 ; i< (b)->core.n_cigar; i++)
if( bam_cigar_op(cigar_data[i]) == BAM_CSOFT_CLIP )
return true;
return false;
}
/*
* Get the 60 from MQ:i:60
*/
int bam_get_MQ(const bam1_t *b)
{
uint8_t * data = NULL;
data = bam_aux_get(b,"MQ");
if ( data == NULL ) return 0;
return bam_aux2i(data);
}
/*
* @param: bam1_t [in] alignment
* sc_len [out] the length of softclip
*
* @return: 1 for head softclip
* 2 for tail softclip
* 0 for no head or tail softclip
*/
inline int sc_type(const bam1_t *b, int * sc_len)
{
if( b==NULL || sc_len == NULL) return 0;
uint32_t* cigar_data = bam_get_cigar(b);
if((b)->core.n_cigar == 1) return 0;
bool begin = bam_cigar_op(cigar_data[0]) == BAM_CSOFT_CLIP;
int blen = bam_cigar_oplen(cigar_data[0]);
bool end = bam_cigar_op(cigar_data[(b)->core.n_cigar-1]) == BAM_CSOFT_CLIP ;
int elen = bam_cigar_oplen(cigar_data[(b)->core.n_cigar-1]);
if ( ! begin && ! end ) return 0;
if ( begin && !end )
{
*sc_len = blen;
return 1;
}
else if (!begin && end)
{
*sc_len = elen;
return 2;
}
else
{
*sc_len = blen<elen?elen:blen;
return blen<elen?2: (blen>elen?1:0);
}
}
/*
* @abstract: get the longest softclip only from
* head or tail softclip
*/
inline int longest_softcliped_base(const bam1_t *b)
{
uint32_t* cigar_data = bam_get_cigar(b);
assert((b)->core.n_cigar >1);
bool begin = bam_cigar_op(cigar_data[0]) == BAM_CSOFT_CLIP;
int blen = bam_cigar_oplen(cigar_data[0]);
bool end = bam_cigar_op(cigar_data[(b)->core.n_cigar-1]) == BAM_CSOFT_CLIP ;
int elen = bam_cigar_oplen(cigar_data[(b)->core.n_cigar-1]);
assert( begin || end );
if ( begin && !end )
return blen;
else if (!begin && end)
return elen;
else
return blen>elen?blen:elen;
}
/*
* @abstract: return the total length of M/X/=/I, exculde H/S/D
*
* @parm: bam1_t structure and cigar in binary format.
*/
inline int infer_mapped_query_length(const bam1_t *b)
{
int ret = 0;
uint32_t* cigar_data = bam_get_cigar(b);
//return bam_cigar2qlen((b)->core.n_cigar,cigar_data);
for( unsigned int i = 0 ; i< (b)->core.n_cigar; i++)
if( bam_cigar_op(cigar_data[i]) != BAM_CSOFT_CLIP
&& bam_cigar_op(cigar_data[i]) != BAM_CHARD_CLIP
&& bam_cigar_op(cigar_data[i]) != BAM_CDEL)
ret += bam_cigar_oplen(cigar_data[i]);
return ret;
}
/*
* @abstract: return the total length of M/X/=/D, exculde H/S/I
*
* @parm: bam1_t structure and cigar in binary format.
*/
inline int infer_mapped_ref_length(const bam1_t *b)
{
int ret = 0;
uint32_t* cigar_data = bam_get_cigar(b);
//return bam_cigar2rlen((b)->core.n_cigar,cigar_data);
for( unsigned int i = 0 ; i< (b)->core.n_cigar; i++)
if( bam_cigar_op(cigar_data[i]) != BAM_CSOFT_CLIP
&& bam_cigar_op(cigar_data[i]) != BAM_CHARD_CLIP
&& bam_cigar_op(cigar_data[i]) != BAM_CINS)
ret += bam_cigar_oplen(cigar_data[i]);
return ret;
}
/*
* @abstract: return the total length of M/X/=/D, exculde H/S/I
*
* @param: cigar in char[] format like 100M4I5D35H.
*/
int infer_mapped_ref_length_from_cigar(const char * cigar)
{
int ret = 0;
char len_buff[4]={0,0,0,0};
int len_index = 0 ;
for(int i = 0;i<1000;i++)
{
char c = cigar[i];
if( c>='0' && c<='9')
{
len_buff[len_index++]=c;
}
else if (c != 0)
{
if(c == 'M' || c=='=' || c== 'X' || c=='D')
{
int op_len = atoi(len_buff);
ret += op_len;
}
len_buff[0]=0;
len_buff[1]=0;
len_buff[2]=0;
len_buff[3]=0;
len_index = 0;
}
else if( c== 0)
{
break;
}
}
return ret;
}
/*
* @abstract: ternimate the program if bam is not sorted by reference
*/
void guarentee_bam_format(sam_hdr_t * h)
{
kstring_t tmp = { 0, 0, NULL };
if( sam_hdr_find_line_id(h,"HD","SO","coordinate",&tmp) < 0)
{
hts_log_error("input bam is not sort by reference coordinate. exit... ");
exit(1);
}
free(tmp.s);
}
inline float adaptative_myers_k(int sc_len, float edit_frac)
{
return float(sc_len)*edit_frac;
}
inline bool non_colinearity(bool headclip, hts_pos_t pos, hts_pos_t realign_begin, hts_pos_t realign_end)
{
if (headclip)
return pos<realign_end /*|| pos<realign_begin*/;
else
return pos>realign_begin /*|| pos>realign_end*/;
}
std::string upper(const char *line, int size)
{
if (size <= 0)
return "";
std::string ret ;
ret.resize(size,'N');
for(int i = 0 ; i<size ; i++)
{
switch(line[i])
{
case 'a': ret[i]='A'; break;
case 'g': ret[i]='G'; break;
case 'c': ret[i]='C'; break;
case 't': ret[i]='T'; break;
case 'A': ret[i]='A'; break;
case 'G': ret[i]='G'; break;
case 'C': ret[i]='C'; break;
case 'T': ret[i]='T'; break;
default : break;
}
}
return ret;
}
std::string seq_complementary_reverse(const std::string & line)
{
std::string ret ;
ret.resize(line.size(),'N');
int index = 0;
for( auto i = line.rbegin() ; i!= line.rend() ; i++)
{
if( *i == 'A' || *i == 'a' )
ret[index++] = 'T';
else if( *i == 'G' || *i == 'g' )
ret[index++] = 'C';
else if( *i == 'C' || *i == 'c' )
ret[index++] = 'G';
else if( *i == 'T' || *i == 't' )
ret[index++] = 'A';
else
ret[index++] = 'N';
}
return ret;
}
void copy_hts_seq(std::string &str, const unsigned char *hts_seq, int start , int len)
{
str.resize(len);
for(int i = 0 ; i<len;i++)
{
switch(bam_seqi(hts_seq,(start+i)))
{
case 1: str[i]='A';break;
case 2: str[i]='C';break;
case 4: str[i]='G';break;
case 8: str[i]='T';break;
default: str[i]='N';break;
}
}
}
void copy_hts_qual(std::vector<uint8_t> & qual , const unsigned char *qual_p,int start , int len)
{
qual.resize(len);
for(int i = 0 ; i<len;i++)
qual[i] = qual_p[start+i];
}
/* ************************************************************************
*
* @section: global options
*
*************************************************************************/
//struct global_options
//{
static int threadnum = 8;
static int min_mapq = 20 ;
static int min_sc_len = 8 ;
static float edit_distance_frac= 0.05 ;
static double interval_prob_cutoff = 0.01 ;
static int nhit = 10 ;
static int gap_open = 5 ;
static int gap_extend = 1 ;
static float prob_cutoff = 0.99;
static float insert_mean = 317.87756;
static float insert_sd = 85.6517543804352;
static int std_fac = 4;
//} gopts;
/* ************************************************************************
*
* @section: strucures and functions to load and store discordant intervels.
*
* @feature: discordant intervels are stored in ordered array
*
*************************************************************************/
enum MateType
{
LeftHook = 0, // This read (R1) mapped at the end of eccDNA
RightHook = 1, // This read (R2) mapped at the begin of eccDNA
BothHook = 2, // Used for when merge L and R to one interval
Unkown=999
};
struct MateInterval
{
MateType type;
hts_pos_t reference_start; // 0-base coordinate, include
hts_pos_t reference_end; // 0-base coordinate, exclude
hts_pos_t next_reference_start; // 0-base coordinate, include
hts_pos_t next_reference_end; // 0-base coordinate, exclude
double prob; // prob = 1 - error rate
bool is_softclip; // true if this alignment contain soft-clip part
// only non-sa mate-interval will be considered in only-discordant results
// incorrect r1/r2 for discordant pair also marked as true!
// for discordant interval
hts_pos_t reference_end_q; // 0-base coordinate, exclude
hts_pos_t next_reference_end_q; // 0-base coordinate, exclude
std::string qname;
// for sort algorithm
// @NOTICE: ordered by next_reference_xxx, not reference_xxx
bool operator <(const MateInterval & o) const
{
return next_reference_start < o.next_reference_start ||
(next_reference_start == o.next_reference_start && next_reference_end < o.next_reference_end) ;
}
// for sort algorithm
// @NOTICE: ordered by next_reference_xxx, not reference_xxx
bool operator == (const MateInterval & o) const
{
return next_reference_start == o.next_reference_start &&
next_reference_end == o.next_reference_end ;
}
// for sort algorithm
// @NOTICE: ordered by next_reference_xxx, not reference_xxx
bool operator > (const MateInterval & o) const
{
return next_reference_start > o.next_reference_start ||
(next_reference_start == o.next_reference_start && next_reference_end > o.next_reference_end) ;
}
/*
* create mate interval
*
* @param item: input alignment of one read
*
* Return 0 if this read is not discordant read,
* 1 if success
* -1 on error
*/
int parse_mate_interval(const bam1_t * item)
{
if( !item ) return -1;
if( bam_is_unmap(item) || bam_is_munmap(item) ) return 0;
int mq = bam_get_MQ(item);
//if( mq == 0 ) return 0;
if( item->core.tid != item->core.mtid ) return 0;
// keep only_discordant == True
is_softclip = is_softclip_read(item);
if( is_softclip && bam_aux_get(item,"SA") != NULL ) return 0;
// check discordant reads (R2F1 orientation, R2 read)
if( bam_is_rev(item) && ! bam_is_mrev(item) && item->core.pos < item->core.mpos )
{
type = MateType::RightHook;
reference_start = item->core.pos;
reference_end = reference_start + infer_mapped_ref_length(item);
int infer_read_len = infer_mapped_query_length(item);
reference_end_q = reference_start + infer_read_len;
next_reference_start = item->core.mpos;
next_reference_end = next_reference_start + item->core.l_qseq;
next_reference_end_q = next_reference_start + infer_read_len;
prob = 1.0 - Phred2Prob(mq);
qname=std::string(bam_get_qname(item));
if(bam_is_r1(item)) is_softclip = true;
//@debug
//std::cerr<<qname<<'\t'<<reference_start<<'\t'<<reference_end<<'\t'
// <<next_reference_start<<'\t'<<next_reference_end<<'\n';
return 1;
}
// R2F1 when iterating trough R1 read
if( ! bam_is_rev(item) && bam_is_mrev(item) && item->core.pos > item->core.mpos )
{
type = MateType::LeftHook;
reference_start = item->core.pos;
reference_end = reference_start + infer_mapped_ref_length(item);
int infer_read_len = infer_mapped_query_length(item);
reference_end_q = reference_start + infer_read_len;
next_reference_start = item->core.mpos;
next_reference_end = next_reference_start + item->core.l_qseq;
next_reference_end_q = next_reference_start + infer_read_len;
prob = 1.0 - Phred2Prob(mq);
qname=std::string(bam_get_qname(item));
if(bam_is_r2(item)) is_softclip = true;
//@debug
//std::cerr<<qname<<'\t'<<reference_start<<'\t'<<reference_end<<'\t'
// <<next_reference_start<<'\t'<<next_reference_end<<'\n';
return 1;
}
return 0;
}
};
/* ************************************************************************
*
* @section: strucures and functions to load and store eccDNA datas.
*
*************************************************************************/
struct eccTemp
{
std::string qname;
hts_pos_t pos_begin;
hts_pos_t pos_end;
hts_pos_t leftmost_sa;
hts_pos_t cut_begin; // 0base include
hts_pos_t cut_end; // 0base exclude
float score;// score = round(xxx,2)
// for sort algorithm
// @NOTICE: ordered by cut_xxx
bool operator <(const eccTemp & o) const
{
return cut_begin < o.cut_begin ||
(cut_begin == o.cut_begin && cut_end < o.cut_end) ;
}
// for sort algorithm
// @NOTICE: ordered by cut_xxx
bool operator == (const eccTemp & o) const
{
return cut_begin == o.cut_begin &&
cut_end == o.cut_end;
}
// for sort algorithm
// @NOTICE: ordered by cut_xxx
bool operator > (const eccTemp& o) const
{
return cut_begin > o.cut_begin ||
( cut_begin == o.cut_end && cut_end> o.cut_end ) ;
}
/*
* create ecc proof
*
* @param item: input alignment of one read
*
* Return 0 if this read is not split reads,
* 1 if success
* -1 on error
*/
int parse_ecc( const bam1_t * item, bam_hdr_t* header )
{
if( !item ) return -1;
uint8_t * data = bam_aux_get(item,"SA");
if( !is_softclip_read(item) || data == NULL ) return 0;
kstring_t sa_tmp = { 0, 0, NULL };
kputs( bam_aux2Z(data),&sa_tmp );
int *offset = NULL;
int num_item = 0;
// SA:Z:chr8,66989,-,89M61S,0,0;
if ((offset = ksplit(&sa_tmp, ',', &num_item)) == NULL) return -1;
if (num_item <5) return -1;
char sa_orientation = *(sa_tmp.s + offset[2]);
if( sa_orientation == '+' && bam_is_rev(item) ) return 0;
if( sa_orientation == '-' && !bam_is_rev(item) ) return 0;
if( item->core.tid != sam_hdr_name2tid(header,sa_tmp.s + offset[0]) )
return 0;
int sq = atoi(sa_tmp.s + offset[4]);
//@NOTICE: in python code, here is sa > min_mapq
if ( sq <= min_mapq )
{
free(sa_tmp.s);
free(offset);
return 0;
}
qname=std::string(bam_get_qname(item));
pos_begin = item->core.pos;
pos_end = pos_begin + infer_mapped_ref_length(item);
leftmost_sa = atol(sa_tmp.s + offset[1]); // 1base
score = round2( float( longest_softcliped_base(item) ) *(1-Phred2Prob(sq)) );
if( pos_begin < leftmost_sa )
{
cut_begin = pos_begin;
const char * cigar = sa_tmp.s + offset[3];
cut_end = leftmost_sa -1 + infer_mapped_ref_length_from_cigar(cigar) ;
}
else if( pos_begin > leftmost_sa )
{
cut_begin = leftmost_sa -1 ; // 0base
cut_end = pos_end;
}
else
{
free(sa_tmp.s);
free(offset);
return 0;
}
free(sa_tmp.s);
free(offset);
return 1;
}
};
/* ************************************************************************
*
* @section: strucures and functions to handle Soft-Clip reads.
*
*************************************************************************/
struct scRead
{
struct sc_part
{
bool headclip ;
std::string seqs;
std::vector<uint8_t> qual;
} sc_info;
std::string qname;
bool is_reverse;
hts_pos_t pos_begin;
hts_pos_t pos_end;
/*
* create Softclip reads
*
* @param item: input alignment of one read
*
* Return 0 if this read is not softclip reads,
* 1 if success
* -1 on error
*/
int parse_sc(const bam1_t * item, const bam_hdr_t* header,int min_sc_len)
{
if( !item ) return -1;
int sc_len = 0;
int sctp = sc_type(item,&sc_len);
uint8_t * data = bam_aux_get(item,"SA");
if( sctp == 0 || data != NULL ) return 0;
if(sc_len < min_sc_len ) return 0;
// A true softclip reads here
pos_begin = item->core.pos;
pos_end = pos_begin + infer_mapped_ref_length(item);
is_reverse = bam_is_rev(item);
qname=std::string(bam_get_qname(item));
assert(sc_len>0);
if( sctp == 1 )
{
sc_info.headclip = true;
copy_hts_seq(sc_info.seqs ,bam_get_seq(item),0,sc_len);
copy_hts_qual(sc_info.qual,bam_get_qual(item),0,sc_len);
}
else
{
sc_info.headclip = false;
copy_hts_seq(sc_info.seqs ,bam_get_seq(item),(item)->core.l_qseq-sc_len,sc_len);
copy_hts_qual(sc_info.qual,bam_get_qual(item),(item)->core.l_qseq-sc_len,sc_len);
}
return 1;
}
};
/* ************************************************************************
*
* @section: global caching structure.
*
*************************************************************************/
typedef BGIQD::INCRARRAY::IncrArray<MateInterval> MateArray;
typedef BGIQD::INCRARRAY::IncrArray<eccTemp> eccArray;
typedef BGIQD::INCRARRAY::IncrArray<scRead> scArray;
struct all_caches
{
std::map<std::string, MateArray> chromesomes_mates;
std::map<std::string, eccArray> chromesomes_eccs;
std::map<std::string, scArray> chromesomes_scs;
std::map<std::string, kstring_t> chromesomes;
private:
// add mate interval into cache
inline void add_mate(const std::string & chrname, const MateInterval & tmp)
{
auto itr = chromesomes_mates.find(chrname);
if( itr == chromesomes_mates.end() )
{
chromesomes_mates[chrname].Init(BLOCK_SIZE);
chromesomes_mates[chrname].push_back(tmp);
}
else
itr->second.push_back(tmp);
}
inline void add_ecc(const std::string & chrname, const eccTemp& tmp)
{
auto itr = chromesomes_eccs.find(chrname);
if( itr == chromesomes_eccs.end() )
{
chromesomes_eccs[chrname].Init(BLOCK_SIZE);
chromesomes_eccs[chrname].push_back(tmp);
}
else
itr->second.push_back(tmp);
}
inline void add_sc(const std::string & chrname, const scRead & tmp)
{
auto itr = chromesomes_scs.find(chrname);
if( itr == chromesomes_scs.end() )
{
chromesomes_scs[chrname].Init(BLOCK_SIZE);
chromesomes_scs[chrname].push_back(tmp);
}
else
itr->second.push_back(tmp);
}
inline void add_chr(const kseq_t *ks)
{
chromesomes[std::string(ks->name.s)] = {0,0,NULL};
kputsn(ks->seq.s,ks->seq.l, &(chromesomes[std::string(ks->name.s)]));
}
public:
void free_mates()
{
for(auto & chr : chromesomes_mates)
chr.second.deep_clean();
}
void free_eccs()
{
for(auto & chr : chromesomes_eccs)
chr.second.deep_clean();
}
void free_scs()
{
for(auto & chr : chromesomes_scs)
chr.second.deep_clean();
}
void load_genome(const char * filename)
{
gzFile fp_fa = gzopen(filename, "r");
kseq_t *ks;
ks = kseq_init(fp_fa);
while ( kseq_read(ks) >= 0)
add_chr(ks);
kseq_destroy(ks);
gzclose(fp_fa);
}
/*
* @abstract: get sequence slice from interval chrname -- [start,end)
*
* @notice: all bases are capitalized
*
*/
std::string get_genome_slice(const std::string & chrname, hts_pos_t start, hts_pos_t end)
{
const auto & itr = chromesomes.find(chrname);
if( itr == chromesomes.end() )
{
hts_log_error("Warning : genome not match bam! \"%s\" not found. Ignore it ... ", chrname.c_str());
return "";
}
if (end<= start) return "";
if(start < 0 ) return "";
if(end >= hts_pos_t(itr->second.l)) end = hts_pos_t(itr->second.l)-1;
if (end<= start) return "";
return upper(itr->second.s + start , end-start);
}
//
// @abstract: load candidate eccDNA.bam and cache
// a) mate intervals from discordant reads pair
// b) soft-clip reads from SA reads.
// c) ecc intervals from split reads
//
// @notice: input bam must be sorted by mapping position.
//
// @param: sort_candidates_bam_filename -- the input bam filename
//
void load_mates_sa_sr(const std::string & sort_candidates_bam_filename)
{
htsThreadPool p = {NULL,0};
// try to open bam file
samFile *in = 0;
if ((in = sam_open(sort_candidates_bam_filename.c_str(), "r")) == 0)
{
hts_log_error("Failed to open sorted bam : \"%s\" for reading", sort_candidates_bam_filename.c_str());
exit(1);
}
// prepare thread pool
if( threadnum > 1 )
{
if (!(p.pool = hts_tpool_init(threadnum ) ) )
{
hts_log_error("Create tpool failed");
exit(1);
}
hts_set_opt(in, HTS_OPT_THREAD_POOL, &p);
}
// handle alignment one by one
bam1_t *b = bam_init1();
bam_hdr_t * header = NULL;
header = sam_hdr_read(in);
if (! header )
{
hts_log_error("Failed to load header from : \"%s\"", sort_candidates_bam_filename.c_str());
exit(1);
}
guarentee_bam_format(header);
int r;
MateInterval temp;
eccTemp etemp;
scRead stemp;
while ((r = sam_read1(in, header, b)) >= 0)
{ // read one alignment from `in'
if( b->core.qual >= min_mapq )
{
if (temp.parse_mate_interval(b) >0 ) // handle discordant reads
add_mate(std::string(sam_hdr_tid2name(header,b->core.tid)),temp);
if ( etemp.parse_ecc(b,header)>0 )
add_ecc(std::string(sam_hdr_tid2name(header,b->core.tid)),etemp);
if ( stemp.parse_sc(b,header,min_sc_len)>0 )
add_sc(std::string(sam_hdr_tid2name(header,b->core.tid)),stemp);
}
}
// release resources
sam_hdr_destroy(header);
bam_destroy1(b);
sam_close(in);
if( threadnum > 1 )
hts_tpool_destroy(p.pool);
// handle sam_read1 return after release resources
if (r < -1)
{
hts_log_error("Error reading file : \"%s\"", sort_candidates_bam_filename.c_str());
exit(1);
}
// print log
long long total = 0;
for( const auto &itr : chromesomes_mates)
total += itr.second.size();
hts_log_info("total mate intervals : %llu ",total);
return ;
}
} caches;
/* ************************************************************************
*
* @section: strucures and functions to store and manage peaks.
*
* @feature: peaks are stored in a ordered array.
*
*************************************************************************/
struct eccFinal
{
hts_pos_t cut_begin;
hts_pos_t cut_end;
int split_read_count;
int discordant_read_count;
float score;
std::set<std::string> s_qnames;
void init(const eccTemp & temp)
{
cut_begin = temp.cut_begin;
cut_end = temp.cut_end;
score = temp.score;
//assert(temp.score>0);
discordant_read_count = 0;
split_read_count = 1;
s_qnames.clear();
s_qnames.insert(temp.qname);
}
/*
* @abstract: check if temp is exact same with this
*
* @notice: please add ordered data
*
* @return: true if add succ due to temp equal with this.
* false otherwise.
*/
bool try_add_next(const eccTemp & temp)
{
//check overlap
if ( temp.cut_begin != cut_begin
|| temp.cut_end != cut_end ) return false;
split_read_count ++ ;
s_qnames.insert(temp.qname);
score += temp.score;
return true;
}
};
struct discordant
{
hts_pos_t cut_begin;
hts_pos_t cut_end;
int discordant_read_count;
std::set<std::string> qnames;
void init(const MateInterval & temp)
{
discordant_read_count = 0;
qnames.clear();
if( temp.is_softclip ) return;
discordant_read_count = 1;
qnames.insert(temp.qname);
if( temp.reference_start < temp.next_reference_start )
{
cut_begin = temp.reference_start;
cut_end = temp.next_reference_end_q;
}
else if (temp.reference_start >temp.next_reference_start)
{
cut_begin = temp.next_reference_start;
cut_end = temp.reference_end_q;
}
else
{
discordant_read_count=0;
qnames.clear();
}
}
/*
* @abstract: check if temp is overlap with this
*
* @notice: please add ordered data
*
* @return: true if add succ due to temp overlap with this.
* false otherwise.
*/
bool try_add_next(const MateInterval & temp)
{
if( temp.is_softclip ) return true ; // skip all softclip pair
if( discordant_read_count == 0 )
{
init(temp);
return true;
}
if( temp.reference_start < temp.next_reference_start )
{
if( temp.reference_start < cut_end )
{
discordant_read_count ++ ;
//if ( temp.next_reference_end_q > cut_end )
cut_end = temp.next_reference_end_q;
qnames.insert(temp.qname);
return true;
}
}
else if ( temp.reference_start > temp.next_reference_start )
{
if( temp.next_reference_start < cut_end )
{
discordant_read_count ++ ;
//if ( temp.reference_end_q > cut_end )
cut_end = temp.reference_end_q;
qnames.insert(temp.qname);
return true;
}
}
return false;
}
};
/*
* @abstract: details of one candidate interval.
* core structure of this realign algorithm.
*
*/
struct ReAlignItem
{
public:
ReAlignItem(){}
ReAlignItem(hts_pos_t b,hts_pos_t e):begin(b),end(e){}
hts_pos_t begin; //0 base. The same as `bedtools genomecov -bg`
hts_pos_t end; //0 base. The same as `bedtools genomecov -bg`
/***********************************************************************************/
std::vector<MateInterval> mate_intervals; // mate interval by discordant reads
std::vector<MateInterval> realign_interval; // realign interval that merged and filted by mate intevals
std::vector<scRead> scs; // softclip reads that waiting to realign
std::vector<eccFinal> final_eccs; // final ecc intervals
std::vector<discordant> only_discordant; // discordant interval if no final eccs found.
std::vector<eccTemp> eccs; // intermidate ecc intervals
/***********************************************************************************/
int realign_interval_valid;
private:
MateType all_type ;
public:
// for sort algorithm
bool operator <(const ReAlignItem & o) const { return begin < o.begin || (begin==o.begin && end < o.end) ; }
bool operator == (const ReAlignItem & o) const { return begin == o.begin && end == o.end ; }
bool operator > (const ReAlignItem & o) const { return begin > o.begin || (begin==o.begin && end > o.end) ; }
/*
* @abstract: set realign interval by mate_intervals
*
* @pram: interval_prob_cutoff -- only consider realign interval if prob > interval_prob_cutoff
*
* @return: 0 if no >99% probility interval,
* 1 otherwise
*
* @warn: this function should NOT be called twice.
*/
int set_realign_interval(double interval_prob_cutoff)
{
realign_interval_valid = 0;
if ( mate_intervals.empty() )
return 0;
if ( mate_intervals.size() == 1 )
{
if( mate_intervals[0].prob == 0 ) return 0;
realign_interval_valid = 1;
realign_interval.push_back(mate_intervals[0]);
realign_interval[0].prob = 1.0;
all_type = realign_interval[0].type;
return 1;
}
// sort by mate_reference_pos
std::sort(mate_intervals.begin(), mate_intervals.end());
// merge overlaped intervals and sum their probabilites
std::vector<MateInterval> candidate_mate_intervals;
MateInterval temp = mate_intervals.at(0);
all_type = temp.type;
for(size_t i = 1; i < mate_intervals.size(); i++)
{
const auto & curr = mate_intervals.at(i);
if ( curr.type != all_type ) all_type = MateType::BothHook;
//if ( curr.next_reference_start >= temp.next_reference_end ) // new candidate mate interval
if ( curr.next_reference_start > temp.next_reference_end ) // new candidate mate interval
{
candidate_mate_intervals.push_back(temp);
temp = curr ;
}
else
{
// merge into previous mate interval
temp.prob += curr.prob;
//the python code use last instead of max
if( curr.next_reference_end > temp.next_reference_end )
temp.next_reference_end = curr.next_reference_end;
if( curr.type != temp.type )
temp.type = MateType::BothHook;
}
}
candidate_mate_intervals.push_back(temp);
double total_prob = 0.0f;
for( const auto & mi : candidate_mate_intervals)
total_prob += mi.prob;
if( total_prob == 0 ) return 0;
for( auto & mi : candidate_mate_intervals)
mi.prob = float(mi.prob)/float(total_prob);