forked from gpertea/stringtie
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrlink.cpp
18403 lines (16077 loc) · 676 KB
/
rlink.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 "rlink.h"
#include "GBitVec.h"
#include <float.h>
//#define GMEMTRACE 1 //debugging memory allocation
#ifdef GMEMTRACE
#include "proc_mem.h"
#endif
#define BSIZE 10000 // bundle size
//import globals from main program:
//extern GffNames* gseqNames;
extern FILE *c_out; // file handle for the input transcripts that are fully covered by reads
extern bool trim;
extern bool eonly;
extern bool nomulti;
extern bool viral;
extern bool mixedMode;
extern bool guided;
extern int allowed_nodes;
extern float isofrac;
extern bool isunitig;
extern bool longreads;
extern bool rawreads;
extern float mcov;
extern int mintranscriptlen; // minimum number for a transcript to be printed
extern uint junctionsupport; // anchor length for junction to be considered well supported <- consider shorter??
extern uint sserror;
extern int junctionthr; // number of reads needed to support a particular junction
extern float readthr; // read coverage per bundle bp to accept it; otherwise considered noise
extern float singlethr; // read coverage per bundle bp to accept it; otherwise considered noise
extern uint bundledist; // reads at what distance should be considered part of separate bundles
// <- this is not addressed everywhere, e.g. in infer_transcripts -> look into this
extern bool includesource;
extern bool geneabundance; // need to compute the gene abundance
extern float fpkm_thr;
extern float tpm_thr;
extern bool enableNames;
extern bool includecov;
extern bool retained_intron;
extern FILE* f_out;
extern GStr label;
static GStr _id("", 256); //to prevent repeated reallocation for each parsed read
//not thread safe -- to only be used in processRead() as long as that's the unique producer
CJunction* add_junction(int start, int end, GList<CJunction>& junction, char strand) {
int oidx=-1;
CJunction *nj=NULL;
CJunction jn(start, end, strand);
if (junction.Found(&jn, oidx)) {
nj=junction.Get(oidx);
}
else {
nj=new CJunction(start, end, strand);
junction.Add(nj);
}
return nj;
}
void printTime(FILE* f) {
time_t ltime; /* calendar time */
ltime=time(NULL);
struct tm *t=localtime(<ime);
fprintf(f, "[%02d/%02d %02d:%02d:%02d]",t->tm_mon+1, t->tm_mday,
t->tm_hour, t->tm_min, t->tm_sec);
}
void printBitVec(GBitVec& bv) {
for (uint i=0;i<bv.size();i++) {
fprintf(stderr, "%c", bv.test(i)?'1':'0');
}
}
void cov_edge_add(GVec<float> *bpcov, int sno, int start, int end, float v) {
bool neutral=false;
if(sno!=1) neutral=true; // why is neutral true here: because if the sno is -/+ than I want to add their counts to bpcov[1] too
bpcov[sno][start+1]+=v; // if sno==1 then I add v to it here
bpcov[sno][end+1]-=v;
if(neutral) { // if neutral (i.e. stranded) gets added to bpcov[1] here too => bpcov[1]=all coverage
bpcov[1][start+1]+=v;
bpcov[1][end+1]-=v;
}
}
void add_read_to_cov(GList<CReadAln>& rd,int n,GVec<float> *bpcov,int refstart) {
int sno=(int)rd[n]->strand+1; // 0(-),1(.),2(+)
float single_count=rd[n]->read_count;
for(int i=0;i<rd[n]->pair_idx.Count();i++) {
single_count-=rd[n]->pair_count[i];
if(rd[n]->pair_idx[i]<=n) { // pair comes before
int np=rd[n]->pair_idx[i];
int pcount=rd[np]->segs.Count();
int rcount=rd[n]->segs.Count();
int snop=(int)rd[np]->strand+1; //v6
int p=0;
int r=0;
int nsegs=pcount+rcount;
while(nsegs) {
int start;
int end;
if(r<rcount) {
if(p==pcount || rd[np]->segs[p].start>rd[n]->segs[r].end) { // no more pair segments or pair segment comes after read segment
start=rd[n]->segs[r].start;
end=rd[n]->segs[r].end;
r++;
nsegs--;
}
else if(rd[np]->segs[p].end<rd[n]->segs[r].start) {
start=rd[np]->segs[p].start;
end=rd[np]->segs[p].end;
p++;
nsegs--;
}
else { // segments overlap
start=rd[np]->segs[p].start;
end=rd[np]->segs[p].end;
if((int)rd[n]->segs[r].start<start) start=rd[n]->segs[r].start;
p++;
nsegs--;
bool cont=true;
while(cont) {
cont=false;
if(r<rcount && (int)(rd[n]->segs[r].start)<=end) {
if((int)rd[n]->segs[r].end>end) end=rd[n]->segs[r].end;
r++;
nsegs--;
cont=true;
}
if(p<pcount && (int)(rd[np]->segs[p].start)<=end) {
if((int)rd[np]->segs[p].end>end) end=rd[np]->segs[p].end;
p++;
nsegs--;
cont=true;
}
}
}
}
else {
start=rd[np]->segs[p].start;
end=rd[np]->segs[p].end;
p++;
nsegs--;
}
int strand=sno;
if(sno!=snop) {
if(sno==1) strand=snop;
else if(snop!=1) strand=1;
}
cov_edge_add(bpcov,strand,start-refstart,end-refstart+1,rd[n]->pair_count[i]);
}
}
}
if(single_count>epsilon) {
for(int i=0;i<rd[n]->segs.Count();i++) {
cov_edge_add(bpcov,sno,rd[n]->segs[i].start-refstart,rd[n]->segs[i].end-refstart+1,single_count);
}
}
}
void countFragment(BundleData& bdata, GSamRecord& brec, int nh) {
static uint32_t BAM_R2SINGLE = BAM_FREAD2 | BAM_FMUNMAP ;
for (int i=0;i<brec.exons.Count();i++) {
bdata.frag_len+=float(1)*brec.exons[i].len()/nh;
}
if (!brec.isPaired() || ((brec.flags()&BAM_FREAD1)!=0) ||
((brec.flags()&BAM_R2SINGLE)==BAM_R2SINGLE ) ) {
bdata.num_fragments+=float(1)/nh;
}
}
bool deljuncmatch(CReadAln *rd,GVec<GSeg> &jd) {
if(rd->juncs.Count()!=jd.Count()) return(false);
for(int i=0;i<rd->juncs.Count();i++) {
uint startj=rd->segs[i].end-rd->juncs[i]->start;
uint endj=rd->juncs[i]->end-rd->segs[i+1].start;
if(startj!=jd[i].start || endj!=jd[i].end) return(false);
}
return(true);
}
bool exonmatch(GVec<GSeg> &prevexons, GVec<GSeg> &exons) {
if(prevexons.Count() != exons.Count()) return false;
for(int i=0;i<exons.Count();i++) {
if(prevexons[i].end!=exons[i].end || prevexons[i].start!=exons[i].start) return false;
}
return true;
}
bool mismatch_anchor(CReadAln *rd,char *mdstr,int refstart, bam1_t *b) {
if(mdstr==NULL) return false;
//--make a copy of the string, in case the original is a const string
// (because the parseUInt() function modifies the string temporarily
char* mdstring=Gstrdup(mdstr);
char *p=mdstring;
int i=0;
int parsedlen=refstart;
int rdlen=0;
while (*p!='\0') {
unsigned int num_matches=0;
if (*p>='0' && *p<='9') {
parseUInt(p,num_matches);
//if (num_matches>0) GMessage("%d matching bases\n", num_matches);
parsedlen+=num_matches;
continue;
}
if (*p=='^') { //deletion --> found a problem with deletion
//GDynArray<char> deletion; //deletion string accumulates here (if needed)
int del_length=0;//tracking deletion length
char delbase=*(++p);
while (delbase>='A' && delbase<='Z') {
//deletion.Add(delbase);
del_length++;
delbase=*(++p);
}
while(i<rd->segs.Count() && rdlen+(int)rd->segs[i].len()<parsedlen) {
rdlen+=rd->segs[i].len();
i++;
}
if(i==rd->segs.Count()) break;
if((i && parsedlen-rd->segs[i].start<junctionsupport) || (i<rd->segs.Count()-1 && rd->segs[i].end+1-parsedlen-del_length<junctionsupport)) {
GFREE(mdstring);
return true;
}
parsedlen+=del_length;
/*GMessage("%d base(s) deletion [", del_length);
for (uint i=0;i<deletion.Count();++i) GMessage("%c",deletion[i]);
GMessage("]\n");*/
continue;
}
if (*p>='A' && *p<='Z') {
//GMessage("base mismatch [%c]\n",*p);
while(i<rd->segs.Count() && rdlen+(int)rd->segs[i].len()<parsedlen) {
rdlen+=rd->segs[i].len();
i++;
}
if(i==rd->segs.Count()) break;
if((i && parsedlen-rd->segs[i].start<junctionsupport) || (i<rd->segs.Count()-1 && rd->segs[i].end-parsedlen<junctionsupport)) {
GFREE(mdstring);
return true;
}
parsedlen++;
}
p++;
}
GFREE(mdstring);
uint32_t *cigar = bam_get_cigar(b);
rdlen=0;
parsedlen=0;
i=0;
for (uint j = 0; j < b->core.n_cigar; ++j) {
int op = bam_cigar_op(cigar[j]);
if (op == BAM_CMATCH || op==BAM_CEQUAL ||
op == BAM_CDIFF || op == BAM_CDEL) {
parsedlen += bam_cigar_oplen(cigar[j]);
}
else if(op == BAM_CINS) {
while(i<rd->segs.Count() && rdlen+(int)rd->segs[i].len()<parsedlen) {
rdlen+=rd->segs[i].len();
i++;
}
if(i==rd->segs.Count()) break;
if((i && parsedlen-rd->segs[i].start<junctionsupport) || (i<rd->segs.Count()-1 && rd->segs[i].end-parsedlen<junctionsupport)) {
return true;
}
}
}
return false;
}
void processRead(int currentstart, int currentend, BundleData& bdata,
GHash<int>& hashread, GReadAlnData& alndata) { // some false positives should be eliminated here in order to break the bundle
GSamRecord& brec=*(alndata.brec); // bam record
if((longreads || (mixedMode && brec.uval)) && (brec.flags() & BAM_FSECONDARY)) return;
GList<CReadAln>& readlist = bdata.readlist; // list of reads gathered so far
GList<CJunction>& junction = bdata.junction; // junctions added so far
char strand=alndata.strand;
int nh=alndata.nh;
int hi=alndata.hi;
int readstart=brec.start;
CReadAln* readaln=NULL; // readaln is initialized with NULL
//bool covSaturated=false; // coverage is set to not saturated
/*
{ // DEBUG ONLY
fprintf(stderr,"Process read %s with strand=%d and exons:",brec.name(),strand);
for (int i=0;i<brec.exons.Count();i++) {
fprintf(stderr," %d-%d", brec.exons[i].start, brec.exons[i].end);
}
fprintf(stderr,"\n");
}
*/
double nm=(double)brec.tag_int("NM"); // read mismatch
float unitig_cov=0;
unitig_cov=brec.tag_float("YK");
bool longr=false;
if(longreads|| brec.uval) longr=true; // second alignment is always from mixed reads
bool match=false; // true if current read matches a previous read
int n=readlist.Count()-1;
if(!mergeMode) while(n>-1 && readlist[n]->start==brec.start) {
if(strand==readlist[n]->strand && (readlist[n]->longread==longr) && (!isunitig || (unitig_cov>0) == readlist[n]->unitig)) {
match=exonmatch(readlist[n]->segs,brec.exons);
if(match && (longreads || mixedMode)) match=deljuncmatch(readlist[n],brec.juncsdel); //DEL AWARE
}
//if(strand==readlist[n]->strand) match=exonmatch(readlist[n]->segs,brec.exons);
if(match) break; // this way I make sure that I keep the n of the matching readlist
n--;
}
else if((alndata.tinfo->cov>=0 && alndata.tinfo->cov<readthr) || (alndata.tinfo->fpkm>=0 && alndata.tinfo->fpkm<fpkm_thr) ||
(alndata.tinfo->tpm>=0 && alndata.tinfo->tpm < tpm_thr)) return; // do not store 'read' if it doesn't meet minimum criteria; this is mergeMode
else { //mergeMode but the read is above thresholds
if(alndata.tinfo->cov>=0) bdata.covflags |= IS_COV_FLAG;
if(alndata.tinfo->fpkm>=0) bdata.covflags |= IS_FPKM_FLAG;
if(alndata.tinfo->tpm>=0) bdata.covflags |= IS_TPM_FLAG;
}
if (bdata.end<currentend) {// I am not sure why this is done here?
bdata.start=currentstart;
bdata.end=currentend;
}
bdata.numreads++; // number of reads gets increased no matter what
//bdata.wnumreads+=float(1)/nh;
if (!match) { // if this is a new read I am seeing I need to set it up
if(mergeMode && mintranscriptlen) {
int len=0;
for (int i=0;i<brec.exons.Count();i++) len+=brec.exons[i].len();
if(len<mintranscriptlen) return;
}
readaln=new CReadAln(strand, nh, brec.start, brec.end, alndata.tinfo);
readaln->longread=longr;
alndata.tinfo=NULL; //alndata.tinfo was passed to CReadAln
for (int i=0;i<brec.exons.Count();i++) {
readaln->len+=brec.exons[i].len();
if(i) {
if(!junction.Count()) { // always add null junction first
CJunction *nullj=new CJunction(0, 0, 0);
junction.Add(nullj);
}
int jstrand=strand;
uint jstart=brec.exons[i-1].end;
uint jend=brec.exons[i].start;
//fprintf(stderr,"exon count=%d junctiondel count=%d exonend=%d exonstart=%d\n",brec.exons.Count(),brec.juncsdel.Count(),jstart,jend);
if((longreads || mixedMode) && (brec.juncsdel[i-1].start || brec.juncsdel[i-1].end)) { // deletion at the junction start/end //DEL AWARE
if(!alndata.juncs.Count() || !alndata.juncs[i-1]->guide_match) { // if this junction matches a guide, I do not need to do anything
jstrand=0;
jstart-=brec.juncsdel[i-1].start;
jend+=brec.juncsdel[i-1].end;
}
}
CJunction* nj=junction.AddIfNew(new CJunction(jstart, jend, jstrand), true);
if (alndata.juncs.Count())
nj->guide_match=alndata.juncs[i-1]->guide_match;
if (nj) {
readaln->juncs.Add(nj);
}
}
readaln->segs.Add(brec.exons[i]);
}
n=readlist.Add(readaln); // reset n for the case there is no match
}
else { //redundant read alignment matching a previous alignment
// keep shortest nh so that I can see for each particular read the multi-hit proportion
if(nh<readlist[n]->nh) readlist[n]->nh=nh;
/*
//for mergeMode, we have to free the transcript info:
if (alndata.tinfo!=NULL) {
delete alndata.tinfo;
alndata.tinfo=NULL;
}
*/
}
/*
{ // DEBUG ONLY
fprintf(stderr,"Add read %s with strand=%d and exons:",brec.name(),strand);
for (int i=0;i<brec.exons.Count();i++) {
fprintf(stderr," %d-%d", brec.exons[i].start, brec.exons[i].end);
}
fprintf(stderr,"\n");
//fprintf(stderr,"Read %s is at n=%d with unitig_cov=%f and strand=%d\n",brec.name(),n,unitig_cov,strand);
}
*/
if((int)brec.end>currentend) {
currentend=brec.end;
bdata.end=currentend;
}
float rdcount=(float)brec.tag_int("YC"); // alignment count
if(!rdcount) rdcount=1;
if(unitig_cov) {
rdcount=unitig_cov;
if(isunitig) readlist[n]->unitig=true; // treat unitig reads differently when -U is set
}
if(!nomulti) rdcount/=nh;
readlist[n]->read_count+=rdcount; // increase single count just in case I don't see the pair
// store the mismatch count per junction so that I can eliminate it later
if(!nm) {
nm=(double)brec.tag_int("nM"); // paired mismatch : big problem with STAR alignments
if(brec.isPaired()) nm/=2;
}
if(brec.clipL) nm++;
if(brec.clipR) nm++;
//nm+=brec.clipL; Note: this clippings were to aggressive
//nm+=brec.clipR;
if(readlist[n]->juncs.Count()) {
bool mismatch=false;
if(readlist[n]->longread) mismatch=true;
else if(nm/readlist[n]->len>mismatchfrac) mismatch=true;
else if(nm && readlist[n]->juncs.Count()) {
if(brec.clipL && readlist[n]->segs[0].len()<junctionsupport+brec.clipL) mismatch=true; // penalize mismatch that's too close to ss
else if(brec.clipR && readlist[n]->segs.Last().len()<junctionsupport+brec.clipR) mismatch=true;
else if(mismatch_anchor(readlist[n],brec.tag_str("MD"),currentstart,brec.get_b())) mismatch=true; // this line was not initially present in vs1 or vs3 but I noticed it doesn't do any difference in real data, so far it only helped with the SR in simulation -> I might want to take it out
}
for(int i=0;i<readlist[n]->juncs.Count();i++) { // if read is PacBio I might want to increase the mismatch fraction, although the nm only gets used for longintrons
if(mismatch || nh>2) readlist[n]->juncs[i]->nm+=rdcount;
if(readlist[n]->segs[i].len()>longintronanchor && readlist[n]->segs[i+1].len()>longintronanchor)
readlist[n]->juncs[i]->mm+=rdcount;
//if(nh>2) readlist[n]->juncs[i]->mm+=rdcount; // vs3; vs2 only has nh>1
readlist[n]->juncs[i]->nreads+=rdcount;
}
}
// now set up the pairing
if (brec.refId()==brec.mate_refId()) { //only consider mate pairing data if mates are on the same chromosome/contig and are properly paired
//if (brec.refId()==brec.mate_refId() && brec.isProperlyPaired()) { //only consider mate pairing data if mates are on the same chromosome/contig and are properly paired
//if (brec.isProperlyPaired()) { //only consider mate pairing data if mates are properly paired
int pairstart=brec.mate_start();
if (currentstart<=pairstart) { // if pairstart is in a previous bundle I don't care about it
//GStr readname();
//GStr id(brec.name(), 16); // init id with readname
_id.assign(brec.name()); //assign can be forced to prevent shrinking of the string
if(pairstart<=readstart) { // if I've seen the pair already <- I might not have seen it yet because the pair starts at the same place
_id+='-';_id+=pairstart;
_id+=".=";_id+=hi; // (!) this suffix actually speeds up the hash by improving distribution!
const int* np=hashread[_id.chars()];
if(np) { // the pair was stored --> why wouldn't it be? : only in the case that the pair starts at the same position
if(readlist[*np]->nh>nh && !nomulti) rdcount=float(1)/readlist[*np]->nh;
bool notfound=true;
for(int i=0;i<readlist[*np]->pair_idx.Count();i++)
if(readlist[*np]->pair_idx[i]==n) {
readlist[*np]->pair_count[i]+=rdcount;
notfound=false;
break;
}
if(notfound) { // I didn't see the pairing before
readlist[*np]->pair_idx.Add(n);
readlist[*np]->pair_count.Add(rdcount);
}
notfound=true;
for(int i=0;i<readlist[n]->pair_idx.Count();i++)
if(readlist[n]->pair_idx[i]==*np) {
readlist[n]->pair_count[i]+=rdcount;
notfound=false;
break;
}
if(notfound) { // I didn't see the pairing before
int i=*np;
readlist[n]->pair_idx.Add(i);
readlist[n]->pair_count.Add(rdcount);
}
hashread.Remove(_id.chars());
}
}
else { // I might still see the pair in the future
_id+='-';_id+=readstart; // this is the correct way
_id+=".=";_id+=hi;
hashread.Add(_id.chars(), n);
}
}
} //<-- if mate is mapped on the same chromosome
}
int get_min_start(CGroup **currgroup) {
int nextgr=0;
if(currgroup[0]!=NULL) {
if(currgroup[1]!=NULL) {
if(currgroup[2]!=NULL) {
int twogr = currgroup[0]->start < currgroup[1]->start ? 0 : 1;
nextgr = currgroup[twogr]->start < currgroup[2]->start ? twogr : 2;
return(nextgr);
}
else {
nextgr = currgroup[0]->start < currgroup[1]->start ? 0 : 1;
return(nextgr);
}
}
else {
if(currgroup[2]!=NULL) {
nextgr = currgroup[0]->start < currgroup[2]->start ? 0 : 2;
return(nextgr);
}
else {
return(0);
}
}
} // end if(currgroup[0]!=NULL)
else {
if(currgroup[1]!=NULL) {
if(currgroup[2]!=NULL) {
nextgr = currgroup[1]->start < currgroup[2]->start ? 1 : 2;
return(nextgr);
}
else {
return(1);
}
}
else {
return(2);
}
}
return(nextgr);
}
void set_strandcol(CGroup *prevgroup, CGroup *group, int grcol, GVec<int>& eqcol, GVec<int>& equalcolor){
int zerocol=eqcol[prevgroup->color];
if(zerocol>-1) {
while(eqcol[zerocol]!=-1 && eqcol[zerocol]!=zerocol) {
zerocol=eqcol[zerocol];
}
int tmpcol=zerocol;
while(equalcolor[zerocol]!=zerocol) {
zerocol=equalcolor[zerocol];
}
eqcol[prevgroup->color]=zerocol;
eqcol[tmpcol]=zerocol;
if(zerocol<grcol) {
equalcolor[grcol]=zerocol;
group->color=zerocol;
}
else if(grcol<zerocol) {
equalcolor[zerocol]=grcol;
eqcol[prevgroup->color]=grcol;
}
} // if(zerocol>-1)
else {
eqcol[prevgroup->color]=grcol;
}
}
void add_group_to_bundle(CGroup *group, CBundle *bundle, GPVec<CBundlenode>& bnode, uint localdist){
CBundlenode *currlastnode=bnode[bundle->lastnodeid];
int bid=bnode.Count();
if(group->start > currlastnode->end + localdist) { // group after last bnode
CBundlenode *currbnode=new CBundlenode(group->start,group->end,group->cov_sum,bid);
currlastnode->nextnode=currbnode;
bnode.Add(currbnode);
bundle->lastnodeid=bid;
bundle->len+=group->end-group->start+1;
bundle->cov+=group->cov_sum;
bundle->multi+=group->multi;
}
else { // group overlaps bnode within bundledist
if(currlastnode->end < group->end) {
bundle->len+= group->end - currlastnode->end;
currlastnode->end= group->end;
}
bundle->cov+=group->cov_sum;
bundle->multi+=group->multi;
currlastnode->cov+=group->cov_sum;
}
}
int create_bundle(GPVec<CBundle>& bundle,CGroup *group,GPVec<CBundlenode>& bnode) {
int bid=bnode.Count();
int bno=bundle.Count();
CBundlenode *startbnode=new CBundlenode(group->start,group->end,group->cov_sum,bid);
CBundle *newbundle=new CBundle(group->end-group->start+1,group->cov_sum,group->multi,bid,bid);
bundle.Add(newbundle);
bnode.Add(startbnode);
return(bno);
}
int setCmp(const pointer p1, const pointer p2) {
CTrInfo *a=(CTrInfo*)p1;
CTrInfo *b=(CTrInfo*)p2;
if(a->trno<b->trno) return -1;
if(a->trno>b->trno) return 1;
return 0;
}
int capCmp(const pointer p1, const pointer p2) {
CTrInfo *a=(CTrInfo*)p1;
CTrInfo *b=(CTrInfo*)p2;
if(a->abundance<b->abundance) return -1;
if(a->abundance>b->abundance) return 1;
return 0;
}
int longtrCmp(const pointer p1, const pointer p2) {
CTransfrag *a=(CTransfrag*)p1;
CTransfrag *b=(CTransfrag*)p2;
if(!a->guide && b->guide) return 1;
if(a->guide && !b->guide) return -1;
if(a->abundance<b->abundance) return 1; // most abundant transcript comes first (I want to keep the one that clearly dominates)
if(a->abundance>b->abundance) return -1;
if(a->nodes.Count()<b->nodes.Count()) return 1; // transfrag with more nodes comes first
if(a->nodes.Count()>b->nodes.Count()) return -1;
if(a->pattern.count()<b->pattern.count()) return 1; // more complete transfrag comes first
if(a->pattern.count()>b->pattern.count()) return -1;
return 0;
}
int trCmp(const pointer p1, const pointer p2) {
CTransfrag *a=(CTransfrag*)p1;
CTransfrag *b=(CTransfrag*)p2;
if(a->nodes.Last()-a->nodes[0]<b->nodes.Last()-b->nodes[0]) return 1; // transfrag with further reach comes first
if(a->nodes.Last()-a->nodes[0]>b->nodes.Last()-b->nodes[0]) return -1;
if(a->nodes.Count()<b->nodes.Count()) return 1; // transfrag with more nodes comes first
if(a->nodes.Count()>b->nodes.Count()) return -1;
if(a->pattern.count()<b->pattern.count()) return 1;
if(a->pattern.count()>b->pattern.count()) return -1;
if(a->abundance<b->abundance) return 1;
if(a->abundance>b->abundance) return -1;
return 0;
}
int mgtrnodeCmp(const pointer p1, const pointer p2) {
CMTransfrag *a=(CMTransfrag*)p1;
CMTransfrag *b=(CMTransfrag*)p2;
if(a->transfrag->pattern.count()<b->transfrag->pattern.count()) return 1;
if(a->transfrag->pattern.count()>b->transfrag->pattern.count()) return -1;
if(!a->transfrag->real && b->transfrag->real) return -1;
if(a->transfrag->real && !b->transfrag->real) return 1;
/*if(a->transfrag->abundance<b->transfrag->abundance) return 1;
if(a->transfrag->abundance>b->transfrag->abundance) return -1;*/
return 0;
}
int mgtrabundCmp(const pointer p1, const pointer p2) {
CMTransfrag *a=(CMTransfrag*)p1;
CMTransfrag *b=(CMTransfrag*)p2;
if(!a->transfrag->real && b->transfrag->real) return 1; // guides come first
if(a->transfrag->real && !b->transfrag->real) return -1;
if(a->transfrag->abundance<b->transfrag->abundance) return 1; // most abundant transcript comes first
if(a->transfrag->abundance>b->transfrag->abundance) return -1;
if(a->transfrag->pattern.count()<b->transfrag->pattern.count()) return 1; // the one with largest pattern comes first
if(a->transfrag->pattern.count()>b->transfrag->pattern.count()) return -1;
// something to decide equal cases
if(a->transfrag->nodes.Count()<b->transfrag->nodes.Count()) return 1; // the one with most nodes comes first
if(a->transfrag->nodes.Count()>b->transfrag->nodes.Count()) return -1;
int i=0;
while(i<a->transfrag->nodes.Count()) {
if(a->transfrag->nodes[i]<b->transfrag->nodes[i]) return 1; // the transcript starting more to the left comes first
if(a->transfrag->nodes[i]>b->transfrag->nodes[i]) return -1;
i++;
}
return 0;
}
int partguideCmp(const pointer p1, const pointer p2) { // sorting partial guides in order of preference
CPartGuide *a=(CPartGuide*)p1;
CPartGuide *b=(CPartGuide*)p2;
if(a->cov<b->cov) return 1;
if(a->cov>b->cov) return -1;
if(a->gcount<b->gcount) return 1;
if(a->gcount>b->gcount) return -1;
if(a->olen<b->olen) return 1;
if(a->olen>b->olen) return -1;
if(a->allolen<b->allolen) return 1;
if(a->allolen>b->allolen) return -1;
if(a->glen<b->glen) return 1;
if(a->glen>b->glen) return -1;
return 0;
}
int edgeCmp(const pointer p1, const pointer p2) {
CNetEdge *a=(CNetEdge*)p1;
CNetEdge *b=(CNetEdge*)p2;
if(a->rate<b->rate) return 1;
if(a->rate>b->rate) return -1;
return 0;
}
int pointCmp(const pointer p1, const pointer p2) {
CTrimPoint *a=(CTrimPoint*)p1;
CTrimPoint *b=(CTrimPoint*)p2;
if(a->start && !b->start) return -1;
if(!a->start && b->start) return 1;
if(a->abundance<b->abundance) return 1;
if(a->abundance>b->abundance) return -1;
return 0;
}
int edgeCmpEM(const pointer p1, const pointer p2) {
CNetEdge *a=(CNetEdge*)p1;
CNetEdge *b=(CNetEdge*)p2;
if(a->fake && !b->fake) return 1; // check if this is right -> I want the fake one to come last
if(!a->fake && b->fake) return -1;
if(a->rate<b->rate) return 1;
if(a->rate>b->rate) return -1;
return 0;
}
int guideabundCmp(const pointer p1, const pointer p2) {
CTransfrag *a=(CTransfrag*)p1;
CTransfrag *b=(CTransfrag*)p2;
if(a->abundance<b->abundance) return 1;
if(a->abundance>b->abundance) return -1;
if(a->pattern.count()<b->pattern.count()) return 1;
if(a->pattern.count()>b->pattern.count()) return -1;
return 0;
}
int guidedabundCmp(const pointer p1, const pointer p2) {
CGuide *a=(CGuide*)p1;
CGuide *b=(CGuide*)p2;
if(a->trf->real && !b->trf->real) return 1; // this ensures included guides are treated last
if(!a->trf->real && b->trf->real) return -1;
if(a->trf->abundance<b->trf->abundance) return 1; // most abundant guide takes precedence
if(a->trf->abundance>b->trf->abundance) return -1;
if(a->trf->pattern.count()<b->trf->pattern.count()) return 1; // longest guide takes precedence
if(a->trf->pattern.count()>b->trf->pattern.count()) return -1;
return 0;
}
int guideCmp(const pointer p1, const pointer p2) {
CGuide *a=(CGuide*)p1;
CGuide *b=(CGuide*)p2;
if(a->trf->pattern.count()<b->trf->pattern.count()) return 1; // longest guide takes precedence
if(a->trf->pattern.count()>b->trf->pattern.count()) return -1;
return 0;
}
int juncCmpEnd(const pointer p1, const pointer p2) {
CJunction* a=(CJunction*)p1;
CJunction* b=(CJunction*)p2;
if (a->end<b->end) return -1;
if (a->end>b->end) return 1;
if (a->start<b->start) return -1;
if (a->start>b->start) return 1;
return 0;
}
void merge_fwd_groups(GPVec<CGroup>& group, CGroup *group1, CGroup *group2, GVec<int>& merge, GVec<int>& eqcol) {
//fprintf(stderr,"merge group=%d into group=%d\n",group2->grid,group1->grid);
// get end of group (group1 is assumed to come before group2)
group1->end=group2->end;
// get smallest color of group
while(eqcol[group1->color]!=group1->color) {
group1->color=eqcol[group1->color];
}
while(eqcol[group2->color]!=group2->color) {
group2->color=eqcol[group2->color];
}
if(group1->color<group2->color) {
eqcol[group2->color]=group1->color;
}
else if(group1->color>group2->color) {
eqcol[group1->color]=group2->color;
group1->color=group2->color;
}
group1->cov_sum+=group2->cov_sum;
group1->next_gr=group2->next_gr; // this is possible because group1->next_gr=group2
merge[group2->grid]=group1->grid;
group1->multi+=group2->multi;
// delete group2
group.freeItem(group2->grid);
}
int merge_read_to_group(int n,int np, int p, float readcov, int sno,int readcol,GList<CReadAln>& readlist,int color,GPVec<CGroup>& group,
CGroup **allcurrgroup,CGroup **startgroup,GVec<int> *readgroup,GVec<int>& eqcol,GVec<int>& merge,int *usedcol) {
//fprintf(stderr,"merge readcol=%d for read=%d:%d-%d with paird=%d and sno=%d\n",readcol,n,readlist[n]->start,readlist[n]->end,np,sno);
// check if read was processed before as a fragment
uint localdist=0;
if(!longreads && !mixedMode) localdist=bundledist+longintronanchor;
//if(!longreads) localdist=bundledist+longintronanchor;
if(np>-1 && np<n && readlist[np]->end<readlist[n]->start && readlist[np]->end+localdist>readlist[n]->start &&
(readlist[np]->segs.Last().len()>=junctionsupport || (readlist[np]->juncs.Count() && readlist[np]->juncs.Last()->strand))
&& (readlist[n]->segs[0].len()>=junctionsupport || (readlist[n]->juncs.Count() && readlist[n]->juncs[0]->strand))) { // valid last/first exon and close
return color;
}
bool first=true;
CGroup *currgroup=allcurrgroup[sno]; // currgroup will be the group that contains readlist[n]->start; initially is the group where the previous read on this strand was added
if(currgroup != NULL) { // this type of group - negative, unknown, or positive - was created before
//set currgroup first
CGroup *lastgroup=NULL;
while(currgroup!=NULL && readlist[n]->start > currgroup->end) { // while read start after the current group's end advance group -> I might have more groups leaving from current group due to splicing
lastgroup=currgroup;
currgroup=currgroup->next_gr;
}
if(currgroup==NULL || readlist[n]->segs[0].end < currgroup->start) // currgroup is null only if we reached end of currgroup list
// because currgroup is not NULL initially and it starts BEFORE read
currgroup=lastgroup; // making sure read comes after currgroup
// now process each group of coordinates individually
CGroup *thisgroup=currgroup;
int ncoord=readlist[n]->segs.Count(); // number of "exons" in read
int lastpushedgroup=-1;
// bool added=false;
int i=0;
while(i<ncoord) {
bool keep=true;
// determine if this exon is good enough to be kept (it is big enough and has good junctions)
if(readlist[n]->segs[i].len()<junctionsupport || (readlist[n]->longread && readlist[n]->segs[i].len()<CHI_THR && readlist[n]->segs[i].len()<DROP*readlist[n]->len)) { // exon is too small to keep
if(i<readlist[n]->juncs.Count()) {
if(!readlist[n]->juncs[i]->strand) { // check first exon
// see if first exon is big enough
if(!i || !readlist[n]->juncs[i-1]->strand) {
keep=false;
if(!i && lastgroup) currgroup=lastgroup;
}
}
}
else if(readlist[n]->juncs.Count()){ // this is last exon
if(!readlist[n]->juncs[i-1]->strand) keep=false;
}
}
if(keep) {
// skip groups that are left behind
while(thisgroup!=NULL && readlist[n]->segs[i].start > thisgroup->end) { // find the group where "exon" fits
lastgroup=thisgroup;
thisgroup=thisgroup->next_gr;
}
if(thisgroup && readlist[n]->segs[i].end + localdist >= thisgroup->start) { // read overlaps group or it's close enough -> it should get group color
// I need to split pairs here if color didn't reach this group: it means there is a gap between these groups and no reads joining them
if(!i) {
int gr=thisgroup->grid;
while(merge[gr]!=gr) {
gr=merge[gr];
}
thisgroup->grid=gr;
for(int g=0;g<readgroup[n].Count();g++) {
gr=readgroup[n][g];
while(merge[gr]!=gr) {
gr=merge[gr];
}
if(gr==thisgroup->grid) {
first=false; // I did see this groups before
break;
}
}
if(np>-1 && readlist[np]->nh && np<n) { // I only consider first exon here because the rest of the groups need to get the same color if the read is still paired
int thiscol=thisgroup->color;
while(eqcol[thiscol]!=thiscol) { // get smallest color
thiscol=eqcol[thiscol];
}
thisgroup->color=thiscol;
if(thiscol!=readcol) { // pair color didn't reach this group
//fprintf(stderr,"Split pairs: %d-%d and %d-%d on strand %d thiscol=%d readcol=%d\n",readlist[np]->start,readlist[np]->end,readlist[n]->start,readlist[n]->end,readlist[n]->strand,thiscol,readcol);
readlist[n]->pair_idx[p]=-1;
for(int j=0;j<readlist[np]->pair_idx.Count();j++)
if(readlist[np]->pair_idx[j]==n) {
readlist[np]->pair_idx[j]=-1;
break;
}
readcol=usedcol[sno]; // readcol gets back the new color
if(readcol<0) {
usedcol[sno]=color;
readcol=color;
eqcol.Add(color);
color++;
}
}
}
}
if(readlist[n]->nh>1) {
thisgroup->multi+=readcov*readlist[n]->segs[i].len(); // where do I add readcov to group coverage -> see below at the end of '}'
}
if(readlist[n]->segs[i].start<thisgroup->start) {
thisgroup->start=readlist[n]->segs[i].start;
}
// find end of new group
CGroup *nextgroup=thisgroup->next_gr;
while(nextgroup!=NULL && readlist[n]->segs[i].end >= nextgroup->start) {
merge_fwd_groups(group,thisgroup,nextgroup,merge,eqcol);
nextgroup=thisgroup->next_gr;
}
if(readlist[n]->segs[i].end > thisgroup->end) {
thisgroup->end=readlist[n]->segs[i].end;
}
// get smallest color of group
while(eqcol[thisgroup->color]!=thisgroup->color) {
thisgroup->color=eqcol[thisgroup->color];
}
if(readcol!=thisgroup->color) { // read color is different from group color
if(i && !readlist[n]->juncs[i-1]->strand) { // bad junction before this exon
// before I equal readcol to thisgroup->color, I need to make sure that the read is not interrupted
// readcol for next exons should still be the color of thisgroup
readcol=thisgroup->color;
}
else {
if(readcol<thisgroup->color) { // set group color to current read color
eqcol[thisgroup->color]=readcol;
thisgroup->color=readcol;
}
else { // read color is bigger than group
eqcol[readcol]=thisgroup->color;
readcol=thisgroup->color;
}
}
}
if(thisgroup->grid != lastpushedgroup) {
//fprintf(stderr,"Assign group %d:%d-%d with color=%d to read %d\n",thisgroup->grid,thisgroup->start,thisgroup->end,thisgroup->color,n);
if(first) readgroup[n].Add(thisgroup->grid); // readgroup for read n gets the id of group
lastpushedgroup=thisgroup->grid;
}
thisgroup->cov_sum+=(readlist[n]->segs[i].end-readlist[n]->segs[i].start+1)*readcov; // coverage is different than number of reads