-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgeneric.c
More file actions
3060 lines (2965 loc) · 124 KB
/
Copy pathgeneric.c
File metadata and controls
3060 lines (2965 loc) · 124 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
#include "generic.h"
int8_t seq_comp_table[16] = { 0, 8, 4, 12, 2, 10, 9, 14, 1, 6, 5, 13, 3, 11, 7, 15 };
static int binOffsetsExtended[] =
{4096+512+64+8+1, 512+64+8+1, 64+8+1, 8+1, 1, 0};
#define _binFirstShift 17 /* How much to shift to get to finest bin. */
#define _binNextShift 3 /* How much to shift to get to next larger bin. */
char template_name[]="/tmp/methylQAXXXXXX";
char *cpglabel[19] = {"0","1","2","3","4","5","6","7","8","9","10","11-20","21-30","31-40","41-50","51-100","101-200","201-300","\\textgreater 300"};
char *cpglabel2[19] = {"0","1","2","3","4","5","6","7","8","9","10","11-20","21-30","31-40","41-50","51-100","101-200","201-300",">300"};
/* definitions of functions */
char *strrev(char *str){
int i = 0, j = strlen(str);
char *rev = malloc(sizeof(char)*(j + 1));
//while(str[i] != '\0')
while(j > 0)
rev[i++] = str[--j];
//printf("%i\n", i);
rev[i] = '\0';
return rev;
}
char *get_filename_without_ext(char *filename) {
char *s;
s = malloc(strlen(filename) + 1);
strcpy(s, filename);
char *dot = strrchr(s, '.');
if(!dot || dot == s) return s;
*dot = '\0';
return s;
}
char *get_filename_ext(char *filename) {
char *dot = strrchr(filename, '.');
if(!dot || dot == filename) return "";
return dot + 1;
}
char * texTitleEscape(char *title){
return replaceChars(title, "_", "\\_");
}
bool is_file(const char* path) {
struct stat buf;
stat(path, &buf);
return S_ISREG(buf.st_mode);
}
bool is_dir(const char* path) {
struct stat buf;
stat(path, &buf);
return S_ISDIR(buf.st_mode);
}
struct lineFile *lineFileOpen2(char *fileName, bool zTerm){
/* Open up a lineFile or die trying. */
if (is_dir(fileName))
errAbort("Error: %s is a directory not a file", fileName);
struct lineFile *lf = lineFileMayOpen(fileName, zTerm);
if (lf == NULL)
errAbort("Couldn't open %s , %s", fileName, strerror(errno));
return lf;
}
boolean binKeeperAnyInclude(struct binKeeper *bk, int start, int end){
/* Return TRUE if start/end includes any items in binKeeper. */
struct binElement *el;
int startBin, endBin;
int i,j, len;
if (start < bk->minPos) start = bk->minPos;
if (end > bk->maxPos) end = bk->maxPos;
if (start >= end) return FALSE;
startBin = (start>>_binFirstShift);
endBin = ((end-1)>>_binFirstShift);
for (i=0; i<ArraySize(binOffsetsExtended); ++i)
{
int offset = binOffsetsExtended[i];
for (j=startBin+offset; j<=endBin+offset; ++j)
{
for (el=bk->binLists[j]; el != NULL; el = el->next)
{
len = el->end - el->start;
if (rangeIntersection(el->start, el->end, start, end) >= len)
{
return TRUE;
}
}
}
startBin >>= _binNextShift;
endBin >>= _binNextShift;
}
return FALSE;
}
int binKeeperCpGstat(struct binKeeper *bk, int start, int end) {
/* get stat for cpg */
struct binElement *el;
int startBin, endBin;
int i,j, len, c=0;
//struct slInt *cc;
if (start < bk->minPos) start = bk->minPos;
if (end > bk->maxPos) end = bk->maxPos;
startBin = (start>>_binFirstShift);
endBin = ((end-1)>>_binFirstShift);
for (i=0; i<ArraySize(binOffsetsExtended); ++i){
int offset = binOffsetsExtended[i];
for (j=startBin+offset; j<=endBin+offset; ++j){
for (el=bk->binLists[j]; el != NULL; el = el->next){
len = el->end - el->start;
if (rangeIntersection(el->start, el->end, start, end) >= len){
struct cpgC *oc = (struct cpgC *) el->val;
(oc->c)++;
c++;
}
}
}
startBin >>= _binNextShift;
endBin >>= _binNextShift;
}
//cc = slIntNew(c);
//slAddHead(&cpgCount, cc);
return c;
//fprintf(stderr, "read have %d CpG\n", c);
}
void writeReportDensity(char *outfile, unsigned long long int *cnt, unsigned int mapQ){
FILE *f = mustOpen(outfile, "w");
fprintf(f, "total reads (pair): %llu\n", cnt[0]);
fprintf(f, " read ends 1: %llu\n", cnt[0]);
fprintf(f, " read ends 2: %llu\n", cnt[1]);
fprintf(f, " mapped read ends 1: %llu\n", cnt[2]);
fprintf(f, " mapped read ends 2: %llu\n", cnt[3]);
fprintf(f, " used read ends 1: %llu\n", cnt[4]);
fprintf(f, " used read ends 2: %llu\n", cnt[5]);
fprintf(f, "mappable reads (pair): %llu\n", cnt[6]);
//fprintf(f, "non-redundant mappable reads (pair): %llu\n", cnt[8]);
fprintf(f, "uniquely mapped reads (pair) (mapQ >= %u): %llu\n", mapQ, cnt[7]);
fprintf(f, "non-redundant uniquely mapped reads (pair): %llu\n", cnt[9]);
fprintf(f, "skipped supplementary alignments: %llu\n", cnt[10]);
carefulClose(&f);
}
void writeReportBismark(char *outfile, unsigned long long int *cnt, unsigned long long int *cnt2, int numFields, char *row[100], int bisMode, long long genomeBase){
FILE *f = mustOpen(outfile, "w");
int i;
fprintf(f, "files provided: %i\n", numFields);
for(i = 0; i < numFields; i++) fprintf(f, " %s\n", row[i]);
fprintf(f, "\n");
fprintf(f, "uniquely mappable reads (pair): %llu\n", cnt[0]);
fprintf(f, "quality failed mapped reads (pair) in the bismark bam: %llu\n", cnt[1]);
fprintf(f, "oversized mapped reads (pair) in the bismark bam: %llu\n", cnt[4]);
//fprintf(f, "duplicated mapped reads (pair) (per lane based): %llu\n", cnt[2]);
fprintf(f, "total base of uniquely mapped reads (pair): %llu\n", cnt[3]);
fprintf(f, "total base of uniquely mapped reads (pair) cover genome base (%lli): %.1fX\n", genomeBase, cnt[3]*1.0/genomeBase);
fprintf(f, "\n");
fprintf(f, "in all uniquely mapped reads (pair), found:\n");
fprintf(f, " number of methylated C in CHG context (was protected): %llu\n", cnt[5]); // X for
fprintf(f, " number of not methylated C in CHG context (was converted): %llu\n", cnt[6]); // x for
fprintf(f, " C->T convertion rate in CHG context: %.2f%%\n", cnt[6]*100.0/(cnt[6]+cnt[5]));
fprintf(f, " number of methylated C in CHH context (was protected): %llu\n", cnt[7]); // H for
fprintf(f, " number of not methylated C in CHH context (was converted): %llu\n", cnt[8]); // h for
fprintf(f, " C->T convertion rate in CHH context: %.2f%%\n", cnt[8]*100.0/(cnt[8]+cnt[7]));
fprintf(f, " number of methylated C in CpG context (was protected): %llu\n", cnt[9]); // Z for
fprintf(f, " number of not methylated C in CpG context (was converted): %llu\n", cnt[10]); // z for
fprintf(f, " C->T convertion rate in CpG context: %.2f%%\n", cnt[10]*100.0/(cnt[10]+cnt[9]));
fprintf(f, " number of methylated C in Unknown context (was protected): %llu\n", cnt[11]); // U for
fprintf(f, " number of not methylated C in Unknown context (was converted): %llu\n", cnt[12]); // u for
fprintf(f, " C->T convertion rate in Unknown context: %.2f%%\n", cnt[12]*100.0/(cnt[12]+cnt[11]));
fprintf(f, "\n");
if (cnt2 != NULL){
if (bisMode){
fprintf(f, "in the total %llu CpG Cytosine:\n", cnt2[19]);
} else {
fprintf(f, "in the total %llu CpG:\n", cnt2[19]);
}
fprintf(f, "%15s\t%15s\t%10s\t%c\n", "Times covered", "Count", "Percent", '|');
for(i = 0; i < 18; i++){
fprintf(f, "%15s\t%15llu\t%10.2f\t|%s\n", cpglabel[i], cnt2[i], cnt2[i]*100.0/cnt2[19], print_bar((int)(cnt2[i]*100.0/cnt2[19])));
}
fprintf(f, "%15s\t%15llu\t%10.2f\t|%s\n", ">300", cnt2[18], cnt2[18]*100.0/cnt2[19], print_bar((int)(cnt2[18]*100.0/cnt2[19])));
}
carefulClose(&f);
}
long long writeInsertsize(struct slInt *slPair, char *outfile){
struct slInt *c;
long long sum = 0;
FILE *f = mustOpen(outfile, "w");
for ( c = slPair; c != NULL; c = c->next){
fprintf(f, "%d\n", c->val);
sum += (long long) c->val;
}
carefulClose(&f);
return sum;
}
long long plotInsertsize(struct slInt *slPair, char *prefix){
long long sum = 0;
char tmpRfile[50], tmpifile[50];
strcpy(tmpRfile, template_name);
strcpy(tmpifile, template_name);
int fd = mkstemp(tmpRfile);
if (fd == -1)
errAbort("create temp file error.");
int fd2 = mkstemp(tmpifile);
if (fd2 == -1)
errAbort("create temp file error.");
sum = writeInsertsize(slPair, tmpifile);
FILE *fout = fdopen(fd, "w");
fprintf(fout, "dat <- read.table(\"%s\")\n", tmpifile);
fprintf(fout, "pdf('%s.insertdistro.pdf')\n", prefix);
fprintf(fout, "d <- density(dat$V1)\n");
fprintf(fout, "plot(d, main=\"Fragments Size Distribution\")\n");
fprintf(fout, "polygon(d, col=\"red\", border=\"blue\")\n");
fprintf(fout, "dev.off()\n");
fclose(fout);
char *command;
if (asprintf(&command, "Rscript %s", tmpRfile) < 0)
errAbort("Preparing command wrong");
if (system(command) == -1)
fprintf(stderr, "failed to call R for plotting");
unlink(tmpifile);
unlink(tmpRfile);
return sum;
}
void writecpgCount(struct slInt *cpgCount, char *outfile){
struct slInt *c;
//fprintf(stderr, "%d elements in cpgCount", slCount(cpgCount));
FILE *f = mustOpen(outfile, "w");
for ( c = cpgCount; c != NULL; c = c->next){
fprintf(f, "%d\n", c->val);
}
carefulClose(&f);
}
long long * plotcpgCount(struct slInt *Count, char *prefix){
long long *cnt = malloc(sizeof(long long)*20);
struct slInt *c;
long long sum = 0;
int i, j;
for(i=0;i<20;i++)
cnt[i] = 0;
for ( c = Count; c != NULL; c = c->next){
j = c->val;
sum += j;
if (j == 0) cnt[0] ++;
else if (j == 1) cnt[1]++;
else if (j == 2) cnt[2]++;
else if (j == 3) cnt[3]++;
else if (j == 4) cnt[4]++;
else if (j == 5) cnt[5]++;
else if (j == 6) cnt[6]++;
else if (j == 7) cnt[7]++;
else if (j == 8) cnt[8]++;
else if (j == 9) cnt[9]++;
else if (j == 10) cnt[10]++;
else if (j >=11 && j <= 20) cnt[11]++;
else if (j >=21 && j <= 30) cnt[12]++;
else if (j >=31 && j <= 40) cnt[13]++;
else if (j >=41 && j <= 50) cnt[14]++;
else if (j >=51 && j <= 100) cnt[15]++;
else if (j >=101 && j <= 200) cnt[16]++;
else if (j >=201 && j <= 300) cnt[17]++;
else cnt[18]++; // j >=301
}
cnt[19] = sum;
char tmpRfile[50];
strcpy(tmpRfile, template_name);
int fd = mkstemp(tmpRfile);
if (fd == -1)
errAbort("create temp file error.");
FILE *fout = fdopen(fd, "w");
fprintf(fout, "dat<-data.frame(label=c('0','1','2','3','4','5','6','7','8','9','10','11-20','21-30','31-40','41-50','51-100','101-200','201-300','>300'), \nvalue=c(");
for(i=0;i<19;i++){
fprintf(fout,"%lli", cnt[i]);
if (i<18) fprintf(fout, ",");
}
fprintf(fout, "))\n");
fprintf(fout, "dat <- subset(dat, value!=0)\n");
fprintf(fout, "pdf('%s.cpgCount.pdf')\n", prefix);
fprintf(fout, "op <- par(mar = c(5,7,4,2) + 0.1)\n");
fprintf(fout, "barplot(rev(dat$value), names=rev(dat$label), main=\"CpG Count\", xlab=\"Number of Fragments\", ylab=\"\", col=4, las=1, horiz=TRUE)\n");
fprintf(fout, "title(ylab = \"CpG Count in Fragments\", cex.lab = 1.5, line = 4.5)\n");
fprintf(fout, "par(op)\n");
fprintf(fout, "dev.off()\n");
fclose(fout);
char *command;
if (asprintf(&command, "Rscript %s", tmpRfile) < 0)
errAbort("Preparing command wrong");
if (system(command) == -1)
fprintf(stderr, "failed to call R for plotting");
unlink(tmpRfile);
return cnt;
}
int * plotcpgCov(struct hash *cpgHash, char *prefix){
struct hashEl *hel;
int *cnt = malloc(sizeof(int)*19);
int i, j;
for(i=0;i<19;i++)
cnt[i] = 0;
struct hashCookie cookie = hashFirst(cpgHash);
while ( (hel = hashNext(&cookie)) != NULL ) {
struct binKeeper *bk = (struct binKeeper *) hel->val;
struct binKeeperCookie becookie = binKeeperFirst(bk);
struct binElement *be;
while( (be = binKeeperNext(&becookie)) != NULL ){
struct cpgC *oc = (struct cpgC *) be->val;
j = oc->c;
if (j == 0) cnt[0] ++;
else if (j == 1) cnt[1]++;
else if (j == 2) cnt[2]++;
else if (j == 3) cnt[3]++;
else if (j == 4) cnt[4]++;
else if (j == 5) cnt[5]++;
else if (j == 6) cnt[6]++;
else if (j == 7) cnt[7]++;
else if (j == 8) cnt[8]++;
else if (j == 9) cnt[9]++;
else if (j == 10) cnt[10]++;
else if (j >=11 && j <= 20) cnt[11]++;
else if (j >=21 && j <= 30) cnt[12]++;
else if (j >=31 && j <= 40) cnt[13]++;
else if (j >=41 && j <= 50) cnt[14]++;
else if (j >=51 && j <= 100) cnt[15]++;
else if (j >=101 && j <= 200) cnt[16]++;
else if (j >=201 && j <= 300) cnt[17]++;
else cnt[18]++; // j >=301
}
binKeeperFree(&bk);
}
char tmpRfile[50];
strcpy(tmpRfile, template_name);
int fd = mkstemp(tmpRfile);
if (fd == -1)
errAbort("create temp file error.");
FILE *fout = fdopen(fd, "w");
fprintf(fout, "dat<-data.frame(label=c('0','1','2','3','4','5','6','7','8','9','10','11-20','21-30','31-40','41-50','51-100','101-200','201-300','>300'), \nvalue=c(");
for(i=0;i<19;i++){
fprintf(fout,"%i", cnt[i]);
if (i<18) fprintf(fout, ",");
}
fprintf(fout, "))\n");
fprintf(fout, "dat <- subset(dat, value!=0)\n");
fprintf(fout, "pdf('%s.cpgCoverage.pdf')\n", prefix);
fprintf(fout, "op <- par(mar = c(5,7,4,2) + 0.1)\n");
fprintf(fout, "barplot(rev(dat$value), names=rev(dat$label), main=\"CpG Coverage\", xlab=\"Number of CpG\", ylab=\"\", col=3, las=1, horiz=TRUE)\n");
fprintf(fout, "title(ylab = \"Times Covered\", cex.lab = 1.5, line = 4.5)\n");
fprintf(fout, "par(op)\n");
fprintf(fout, "dev.off()\n");
fclose(fout);
char *command;
if (asprintf(&command, "Rscript %s", tmpRfile) < 0 )
errAbort("Preparing command wrong");
if (system(command) == -1)
fprintf(stderr, "failed to call R for plotting");
unlink(tmpRfile);
return cnt;
}
void writecpgCov(struct hash *cpgHash, char *outfile){
struct hashEl *hel;
struct hashCookie cookie = hashFirst(cpgHash);
FILE *f = mustOpen(outfile, "w");
while ( (hel = hashNext(&cookie)) != NULL ) {
struct binKeeper *bk = (struct binKeeper *) hel->val;
struct binKeeperCookie becookie = binKeeperFirst(bk);
struct binElement *be;
while( (be = binKeeperNext(&becookie)) != NULL ){
struct cpgC *oc = (struct cpgC *) be->val;
fprintf(f, "%i\n", oc->c);
}
binKeeperFree(&bk);
}
carefulClose(&f);
}
unsigned long long int *writecpgBismark(struct hash *cpgHash, char *outfile, char *outcpg, int statsOnly, int covThres){
unsigned long long int *cnt = malloc(sizeof(unsigned long long int)*20);
int i, j = 0;
unsigned long long int tot=0; //tot will be the 20th element, which was not the coverage count, was the total C (in CpG) count
for(i=0;i<20;i++)
cnt[i] = 0;
struct hashEl *hel;
struct hashCookie cookie = hashFirst(cpgHash);
FILE *f = NULL, *f2 = NULL;
if(!statsOnly) {
f = mustOpen(outfile, "w");
f2 = mustOpen(outcpg, "w");
}
while ( (hel = hashNext(&cookie)) != NULL ) {
struct binKeeper *bk = (struct binKeeper *) hel->val;
struct binKeeperCookie becookie = binKeeperFirst(bk);
struct binElement *be;
while( (be = binKeeperNext(&becookie)) != NULL ){
tot++;
struct cpgC *oc = (struct cpgC *) be->val;
if (oc->mc > 0 || oc->umc > 0){
j = oc->mc + oc->umc;
if(!statsOnly) {
if (j >= covThres){
fprintf(f, "%s\t%i\t%i\t%i\n", hel->name, be->start, be->end, j);
fprintf(f2, "%s\t%i\t%i\t%.4f\n", hel->name, be->start, be->end, (float)(oc->mc)/j);
}
}
//if (j == 0) cnt[0] ++;
if (j == 1) cnt[1]++;
else if (j == 2) cnt[2]++;
else if (j == 3) cnt[3]++;
else if (j == 4) cnt[4]++;
else if (j == 5) cnt[5]++;
else if (j == 6) cnt[6]++;
else if (j == 7) cnt[7]++;
else if (j == 8) cnt[8]++;
else if (j == 9) cnt[9]++;
else if (j == 10) cnt[10]++;
else if (j >=11 && j <= 20) cnt[11]++;
else if (j >=21 && j <= 30) cnt[12]++;
else if (j >=31 && j <= 40) cnt[13]++;
else if (j >=41 && j <= 50) cnt[14]++;
else if (j >=51 && j <= 100) cnt[15]++;
else if (j >=101 && j <= 200) cnt[16]++;
else if (j >=201 && j <= 300) cnt[17]++;
else cnt[18]++; // j >=301
} else {
cnt[0]++;
}
}
binKeeperFree(&bk);
}
cnt[19] = tot;
if(!statsOnly) {
carefulClose(&f2);
carefulClose(&f);
}
return cnt;
}
void writecpgBismarkLite(struct hash *cpgHash, char *outfilefor, char *outfilerev, int covThres){
int j = 0;
struct hashEl *hel;
struct hashCookie cookie = hashFirst(cpgHash);
FILE *f = mustOpen(outfilefor, "w");
FILE *f2 = mustOpen(outfilerev, "w");
while ( (hel = hashNext(&cookie)) != NULL ) {
struct binKeeper *bk = (struct binKeeper *) hel->val;
struct binKeeperCookie becookie = binKeeperFirst(bk);
struct binElement *be;
while( (be = binKeeperNext(&becookie)) != NULL ){
struct cpgC *oc = (struct cpgC *) be->val;
if (oc->mc > 0 || oc->umc > 0){
j = oc->mc + oc->umc;
if (j >= covThres){
if (oc->strand == '+'){
fprintf(f, "%s\t%i\t%i\t%.4f\n", hel->name, be->start, be->end, (float)(oc->mc)/j);
//fprintf(f, "%s\t%i\t%i\t%i\t%i\t%.4f\n", hel->name, be->start, be->end, oc->mc, oc->umc, (float)(oc->mc)/j);
}else{
fprintf(f2, "%s\t%i\t%i\t%.4f\n", hel->name, be->start, be->end, (float)(oc->mc)/j);
//fprintf(f2, "%s\t%i\t%i\t%i\t%i\t%.4f\n", hel->name, be->start, be->end, oc->mc, oc->umc, (float)(oc->mc)/j);
}
}
}
}
binKeeperFree(&bk);
}
carefulClose(&f);
carefulClose(&f2);
}
void writecpgBismarkLiteHash(struct hash *cpgHash, char *outfilefor, char *outfilerev, int covThres){
int j = 0, k;
struct hashEl *hel, *hel2;
struct hashCookie cookie = hashFirst(cpgHash);
FILE *f = mustOpen(outfilefor, "w");
FILE *f2 = mustOpen(outfilerev, "w");
while ( (hel = hashNext(&cookie)) != NULL ) {
struct hash *hash2 = (struct hash *) hel->val;
struct hashCookie cookie2 = hashFirst(hash2);
while( (hel2 = hashNext(&cookie2)) != NULL ){
struct cpgC *oc = (struct cpgC *) hel2->val;
//if (oc->mc > 0 || oc->umc > 0){
if (oc->mc > 0){
j = oc->mc + oc->umc;
if (j >= covThres) {
k = (int)strtol(hel2->name, 0, 0);
if (oc->strand == '+'){
fprintf(f, "%s\t%i\t%i\t%.4f\n", hel->name, k, k+1, (float)(oc->mc)/j);
//fprintf(f, "%s\t%i\t%i\t%i\t%i\t%.4f\n", hel->name, be->start, be->end, oc->mc, oc->umc, (float)(oc->mc)/j);
}else{
fprintf(f2, "%s\t%i\t%i\t%.4f\n", hel->name, k, k+1, (float)(oc->mc)/j);
//fprintf(f2, "%s\t%i\t%i\t%i\t%i\t%.4f\n", hel->name, be->start, be->end, oc->mc, oc->umc, (float)(oc->mc)/j);
}
}
}
}
hashFree(&hash2);
}
carefulClose(&f);
carefulClose(&f2);
}
void writeGenomeCov(struct hash *cov, char *outfile){
struct hashEl *hel;
struct hashCookie cookie = hashFirst(cov);
FILE *f = mustOpen(outfile, "w");
while ( (hel = hashNext(&cookie)) != NULL ) {
struct gcov *g = (struct gcov *) hel->val;
fprintf(f, "%s\t%i\t%i\n", hel->name, g->total, g->cov);
}
carefulClose(&f);
}
void plotGenomeCov(struct hash *cov, char *prefix){
struct hashEl *hel;
struct hashCookie cookie = hashFirst(cov);
int i = 1;
int tot = hashNumEntries(cov);
char tmpRfile[50];
strcpy(tmpRfile, template_name);
int fd = mkstemp(tmpRfile);
if (fd == -1)
errAbort("create temp file error.");
FILE *fout = fdopen(fd, "w");
fprintf(fout, "dat <- data.frame(label=rep(NA, %d), total=rep(0, %d), cov=rep(0, %d), stringsAsFactors=FALSE)\n", tot, tot, tot);
while ( (hel = hashNext(&cookie)) != NULL ) {
struct gcov *g = (struct gcov *) hel->val;
fprintf(fout, "dat[%d, ] <- c('%s', %i, %i)\n", i, hel->name, g->total, g->cov);
i++;
}
fprintf(fout, "dat$total <- as.numeric(dat$total)\n");
fprintf(fout, "dat$cov <- as.numeric(dat$cov)\n");
fprintf(fout, "pdf('%s.genomeCov.pdf')\n", prefix);
fprintf(fout, "op <- par(mar = c(5,7,4,2) + 0.1)\n");
fprintf(fout, "barplot(rev(dat$cov/dat$total), names=rev(dat$label), main=\"Genome Coverage\", xlab=\"Coverage Percentage\", ylab=\"\", col=5, las=1, horiz=TRUE, xlim=c(0,1))\n");
fprintf(fout, "title(ylab = \"Chromosomes\", cex.lab = 1.5, line = 4.5)\n");
fprintf(fout, "par(op)\n");
fprintf(fout, "dev.off()\n");
fclose(fout);
char *command;
if (asprintf(&command, "Rscript %s", tmpRfile) < 0 )
errAbort("Preparing command wrong");
if (system(command) == -1)
fprintf(stderr, "failed to call R for plotting");
unlink(tmpRfile);
}
void plotMappingStat(unsigned long long int *cnt, char *prefix){
char tmpRfile[50];
strcpy(tmpRfile, template_name);
int fd = mkstemp(tmpRfile);
if (fd == -1)
errAbort("create temp file error.");
FILE *fout = fdopen(fd, "w");
fprintf(fout, "dat <- data.frame(count=c(%llu, %llu, %llu, %llu), label=c('total\\nfragments','mapped\\nfragments','uniquely\\nmapped\\nfragments', 'non-redundant\\nuniquely\\nmapped\\nfragments'))\n", cnt[0], cnt[6], cnt[7], cnt[9]);
fprintf(fout, "dat$count <- as.numeric(dat$count)\n");
fprintf(fout, "pdf('%s.mappingStat.pdf')\n", prefix);
fprintf(fout, "op <- par(mar = c(7,8,4,2) + 0.1)\n");
fprintf(fout, "bar <- barplot(dat$count, las=1, col=2:5, ylab='',xlab='', main='Mapping stats')\n");
fprintf(fout, "title(ylab = 'Fragments count', cex.lab = 1.5, line = 4.5)\n");
fprintf(fout, "axis(1, at=bar, labels=dat$label, padj=1, tick=FALSE)\n");
fprintf(fout, "par(op)\n");
fprintf(fout, "dev.off()\n");
fclose(fout);
char *command;
if (asprintf(&command, "Rscript %s", tmpRfile) < 0)
errAbort("Preparing command wrong");
if (system(command) == -1)
fprintf(stderr, "failed to call R for plotting");
unlink(tmpRfile);
}
void assignCpGcount(struct hash *chrHash, struct hash *cpgHash, struct hash *chgHash, struct hash *chhHash, char *chrom, int start, char *methycall, char strand, int left, int right, unsigned long long int *methyCnt, int fullMode){
int i, j;
char key[20];
struct binElement *hitList = NULL, *hit; // *hitList2 = NULL, *hit2;
struct hashEl *hel = hashLookup(cpgHash, chrom);
if (hel == NULL){
return;
}
for(i = 0; i < strlen(methycall); i++){
if (i < left) continue;
if (i >= right) continue;
j = methycall[i];
if(j == 'Z' || j == 'z'){
struct binKeeper *bk = (struct binKeeper *) hel->val;
hitList = binKeeperFind(bk, start+i, start+i+1); //bismark have methyl info on each site, not each cpg -- FIXing
if (hitList != NULL){
//fprintf(stdout, "found C: %s %i %i with status %c\n", chrom, start+i, start+i+1, j);
for (hit = hitList; hit !=NULL; hit = hit->next) {
//fprintf(stdout, "hit C: %s %i %i from hash\n", chrom, hit->start, hit->end);
struct cpgC *cg = (struct cpgC *) hit->val;
if (j == 'Z'){
(cg->mc)++;
methyCnt[4]++;
}else if(j == 'z'){
(cg->umc)++;
methyCnt[5]++;
}
//fprintf(stdout, "mC: %i umC: %i\n", cg->mc, cg->umc);
//break; // should be ok to comment out since just 1 CpG
}
}else{
warn("not a CpG Cytosine found: %s %i %i", chrom, start+i, start+i+1);
continue;
}
} else {
if(sprintf(key, "%i", start+i) < 0)
errAbort("Mem Error.\n");
if(j == 'X'){
methyCnt[0]++;
if (fullMode){
/*
struct hashEl *hel2 = hashLookup(chgHash, chrom);
if (hel2 != NULL) {
struct binKeeper *bk2 = (struct binKeeper *) hel2->val;
hitList2 = binKeeperFind(bk2, start+i, start+i+1);
if (hitList2 == NULL){
struct cpgC *c = malloc(sizeof(struct cpgC)); //change from each CpG to 2 base as bismark does this
c->c = 0;
c->mc = 1;
c->umc = 0;
c->strand = strand;
binKeeperAdd(bk2, start+i, start+i+1, c);
}else{
for (hit2 = hitList2; hit2 !=NULL; hit2 = hit2->next) {
struct cpgC *cg2 = (struct cpgC *) hit2->val;
(cg2->mc)++;
}
}
} else {
struct cpgC *c = malloc(sizeof(struct cpgC)); //change from each CpG to 2 base as bismark does this
c->c = 0;
c->mc = 1;
c->umc = 0;
c->strand = strand;
int size = hashIntValDefault(chrHash, chrom, 0);
if (size == 0) {
continue;
}
struct binKeeper *bk2 = binKeeperNew(0, size);
binKeeperAdd(bk2, start+i, start+i+1, c);
hashAdd(chgHash, chrom, bk2);
}
*/
struct hashEl *hel2 = hashLookup(chgHash, chrom);
if (hel2 != NULL) {
struct hash *hash2 = (struct hash *) hel2->val;
struct hashEl *hel3 = hashLookup(hash2, key);
if (hel3 == NULL){
struct cpgC *c = malloc(sizeof(struct cpgC)); //change from each CpG to 2 base as bismark does this
c->c = 0;
c->mc = 1;
c->umc = 0;
c->strand = strand;
hashAdd(hash2, key, c);
}else{
struct cpgC *cg2 = (struct cpgC *) hel3->val;
(cg2->mc)++;
}
} else {
struct cpgC *c = malloc(sizeof(struct cpgC)); //change from each CpG to 2 base as bismark does this
c->c = 0;
c->mc = 1;
c->umc = 0;
c->strand = strand;
struct hash *hash = newHash(0);
hashAdd(hash, key, c);
hashAdd(chgHash, chrom, hash);
}
}
}else if(j == 'x'){
methyCnt[1]++;
if (fullMode){
/*
struct hashEl *hel2 = hashLookup(chgHash, chrom);
if (hel2 != NULL) {
struct binKeeper *bk2 = (struct binKeeper *) hel2->val;
hitList2 = binKeeperFind(bk2, start+i, start+i+1);
if (hitList2 == NULL){
struct cpgC *c = malloc(sizeof(struct cpgC)); //change from each CpG to 2 base as bismark does this
c->c = 0;
c->mc = 0;
c->umc = 1;
c->strand = strand;
binKeeperAdd(bk2, start+i, start+i+1, c);
}else{
for (hit2 = hitList2; hit2 !=NULL; hit2 = hit2->next) {
struct cpgC *cg2 = (struct cpgC *) hit2->val;
(cg2->umc)++;
}
}
} else {
struct cpgC *c = malloc(sizeof(struct cpgC)); //change from each CpG to 2 base as bismark does this
c->c = 0;
c->mc = 0;
c->umc = 1;
c->strand = strand;
int size = hashIntValDefault(chrHash, chrom, 0);
if (size == 0) {
continue;
}
struct binKeeper *bk2 = binKeeperNew(0, size);
binKeeperAdd(bk2, start+i, start+i+1, c);
hashAdd(chgHash, chrom, bk2);
}
*/
struct hashEl *hel2 = hashLookup(chgHash, chrom);
if (hel2 != NULL) {
struct hash *hash2 = (struct hash *) hel2->val;
struct hashEl *hel3 = hashLookup(hash2, key);
if (hel3 == NULL){
struct cpgC *c = malloc(sizeof(struct cpgC)); //change from each CpG to 2 base as bismark does this
c->c = 0;
c->mc = 0;
c->umc = 1;
c->strand = strand;
hashAdd(hash2, key, c);
}else{
struct cpgC *cg2 = (struct cpgC *) hel3->val;
(cg2->umc)++;
}
} else {
struct cpgC *c = malloc(sizeof(struct cpgC)); //change from each CpG to 2 base as bismark does this
c->c = 0;
c->mc = 0;
c->umc = 1;
c->strand = strand;
struct hash *hash = newHash(0);
hashAdd(hash, key, c);
hashAdd(chgHash, chrom, hash);
}
}
}else if(j == 'H'){
methyCnt[2]++;
if (fullMode){
/*
struct hashEl *hel2 = hashLookup(chhHash, chrom);
if (hel2 != NULL) {
struct binKeeper *bk2 = (struct binKeeper *) hel2->val;
hitList2 = binKeeperFind(bk2, start+i, start+i+1);
if (hitList2 == NULL){
struct cpgC *c = malloc(sizeof(struct cpgC)); //change from each CpG to 2 base as bismark does this
c->c = 0;
c->mc = 1;
c->umc = 0;
c->strand = strand;
binKeeperAdd(bk2, start+i, start+i+1, c);
}else{
for (hit2 = hitList2; hit2 !=NULL; hit2 = hit2->next) {
struct cpgC *cg2 = (struct cpgC *) hit2->val;
(cg2->mc)++;
}
}
} else {
struct cpgC *c = malloc(sizeof(struct cpgC)); //change from each CpG to 2 base as bismark does this
c->c = 0;
c->mc = 1;
c->umc = 0;
c->strand = strand;
int size = hashIntValDefault(chrHash, chrom, 0);
if (size == 0) {
continue;
}
struct binKeeper *bk2 = binKeeperNew(0, size);
binKeeperAdd(bk2, start+i, start+i+1, c);
hashAdd(chhHash, chrom, bk2);
}
*/
struct hashEl *hel2 = hashLookup(chhHash, chrom);
if (hel2 != NULL) {
struct hash *hash2 = (struct hash *) hel2->val;
struct hashEl *hel3 = hashLookup(hash2, key);
if (hel3 == NULL){
struct cpgC *c = malloc(sizeof(struct cpgC)); //change from each CpG to 2 base as bismark does this
c->c = 0;
c->mc = 1;
c->umc = 0;
c->strand = strand;
hashAdd(hash2, key, c);
}else{
struct cpgC *cg2 = (struct cpgC *) hel3->val;
(cg2->mc)++;
}
} else {
struct cpgC *c = malloc(sizeof(struct cpgC)); //change from each CpG to 2 base as bismark does this
c->c = 0;
c->mc = 1;
c->umc = 0;
c->strand = strand;
struct hash *hash = newHash(0);
hashAdd(hash, key, c);
hashAdd(chhHash, chrom, hash);
}
}
}else if(j == 'h'){
methyCnt[3]++;
if (fullMode){
/*
struct hashEl *hel2 = hashLookup(chhHash, chrom);
if (hel2 != NULL) {
struct binKeeper *bk2 = (struct binKeeper *) hel2->val;
hitList2 = binKeeperFind(bk2, start+i, start+i+1);
if (hitList2 == NULL){
struct cpgC *c = malloc(sizeof(struct cpgC)); //change from each CpG to 2 base as bismark does this
c->c = 0;
c->mc = 0;
c->umc = 1;
c->strand = strand;
binKeeperAdd(bk2, start+i, start+i+1, c);
}else{
for (hit2 = hitList2; hit2 !=NULL; hit2 = hit2->next) {
struct cpgC *cg2 = (struct cpgC *) hit2->val;
(cg2->umc)++;
}
}
} else {
struct cpgC *c = malloc(sizeof(struct cpgC)); //change from each CpG to 2 base as bismark does this
c->c = 0;
c->mc = 0;
c->umc = 1;
c->strand = strand;
int size = hashIntValDefault(chrHash, chrom, 0);
if (size == 0) {
continue;
}
struct binKeeper *bk2 = binKeeperNew(0, size);
binKeeperAdd(bk2, start+i, start+i+1, c);
hashAdd(chhHash, chrom, bk2);
}
*/
struct hashEl *hel2 = hashLookup(chhHash, chrom);
if (hel2 != NULL) {
struct hash *hash2 = (struct hash *) hel2->val;
struct hashEl *hel3 = hashLookup(hash2, key);
if (hel3 == NULL){
struct cpgC *c = malloc(sizeof(struct cpgC)); //change from each CpG to 2 base as bismark does this
c->c = 0;
c->mc = 0;
c->umc = 1;
c->strand = strand;
hashAdd(hash2, key, c);
}else{
struct cpgC *cg2 = (struct cpgC *) hel3->val;
(cg2->umc)++;
}
} else {
struct cpgC *c = malloc(sizeof(struct cpgC)); //change from each CpG to 2 base as bismark does this
c->c = 0;
c->mc = 0;
c->umc = 1;
c->strand = strand;
struct hash *hash = newHash(0);
hashAdd(hash, key, c);
hashAdd(chhHash, chrom, hash);
}
}
}else if(j == 'U'){
methyCnt[6]++;
}else if(j == 'u'){
methyCnt[7]++;
}
}
}
}
unsigned long long int *bismarkBamParse(char *samfile, struct hash *chrHash, struct hash *cpgHash, struct hash *chgHash, struct hash *chhHash, char *forwardread, char *reverseread, int isSam, int addChr, int fullMode, unsigned int iSize) {
/*
### . for bases not involving cytosines ###
### X for methylated C in CHG context (was protected) ###
### x for not methylated C in CHG context (was converted) ###
### H for methylated C in CHH context (was protected) ###
### h for not methylated C in CHH context (was converted) ###
### Z for methylated C in CpG context (was protected) ###
### z for not methylated C in CpG context (was converted) ###
### U for methylated C in Unknown context (was protected) ###
### u for not methylated C in Unknown context (was converted) ###
default old_flag
=================== ===================
Read 1 Read 2 Read 1 Read 2
OT: 99 147 67 131
OB: 83 163 115 179
CTOT: 99 147 67 131
CTOB: 83 163 115 179
TODO: currently works only for bismark with bowtie1
FIXME: lack of process of CIGAR in order to support bowtie2
*/
char chr[100], strand, read_cove[4], genome_cove[4], methycall[1000], *row[100], cstrand;
//char key[100];
int fi, start, left, right, distance=0; //cutoff used for remove PCR duplication, single end as 1, paired end as 2
//int fstart, fend, fstrand, cutoff = 0;
unsigned long long int linecnt = 0, dupCount = 0, failCount = 0, totalbase = 0, oversizeCount = 0;
unsigned long long int *cnt = malloc(sizeof(unsigned long long int) * 13);
unsigned long long int *methyCnt = malloc(sizeof(unsigned long long int) * 8);
FILE *forward_f = NULL, *reverse_f = NULL;
int i, cend;
struct hash *nochr = newHash(0);
for(i = 0; i < 8; i++) cnt[i] = 0;
for(i = 0; i < 8; i++) methyCnt[i] = 0;
if (fullMode){
forward_f = mustOpen(forwardread, "w");
reverse_f = mustOpen(reverseread, "w");
}
//process sam/bam list
int numFields = chopByChar(samfile, ',', row, ArraySize(row));
for(fi = 0; fi < numFields; fi++){
fprintf(stderr, "\n* Processing %s\n", row[fi]);
samfile_t *samfp;
bam1_t *b;
bam_header_t *h;
struct hash *dup = newHash(0);
if (isSam) {
if ( (samfp = samopen(row[fi], "r", 0)) == 0) {
fprintf(stderr, "Fail to open SAM file %s\n", samfile);
errAbort("Error\n");
}
} else {
if ( (samfp = samopen(row[fi], "rb", 0)) == 0) {
fprintf(stderr, "Fail to open BAM file %s\n", samfile);
errAbort("Error\n");
}
}
h = samfp->header;
b = bam_init1();
while ( samread(samfp, b) >= 0) {
linecnt++;
totalbase += b->core.l_qseq;
if ((linecnt % 10000) == 0)
fprintf(stderr, "\r* Processed lines: %llu", linecnt);
//change chr name to chr1, chr2 ...
strcpy(chr, h->target_name[b->core.tid]);
if (addChr){
if (startsWith("GL", h->target_name[b->core.tid])) {
continue;
} else if (sameWord(h->target_name[b->core.tid], "MT")) {
strcpy(chr,"chrM");
} else if (!startsWith("chr", h->target_name[b->core.tid])) {
strcpy(chr, "chr");
strcat(chr, h->target_name[b->core.tid]);
}
}
//if (sameWord(chr, "chrM")){
// continue; //skip chrM
//}
//strand
//check Ref reads mapped to existed in chromosome size file or not
struct hashEl *he = hashLookup(nochr, chr);
if (he != NULL)
continue;
cend = (unsigned int) (hashIntValDefault(chrHash, chr, 2) - 1);
if (cend == 1){
hashAddInt(nochr, chr, 1);
warn("* Warning: read ends mapped to chromosome %s will be discarded as %s not existed in the chromosome size file", chr, chr);
continue;
}
strcpy(read_cove, bam_aux2Z(bam_aux_get(b, "XR")));
strcpy(genome_cove, bam_aux2Z(bam_aux_get(b, "XG")));
if (sameWord( genome_cove, read_cove )){
strand = '+';
}else{
strand = '-';
}
//read strand
cstrand = (b->core.flag&BAM_FREVERSE)? '-' : '+';
if ( (b->core.flag == 0) || (b->core.flag == 16)){
//single end
//cutoff = 1;
start = (int) b->core.pos;
//fend = (int) b->core.n_cigar? bam_calend(&b->core, bam1_cigar(b)) : b->core.pos + b->core.l_qseq;
//fstart = start;
//fstrand = strand;
left = 0;
right = b->core.l_qseq;
if (fullMode){
if (strand == '+'){
//fprintf(forward_f, "%s\t%u\t%u\t%s\t%i\t%c\n", chr, start, start+(b->core.l_qseq), bam1_qname(b), b->core.qual, strand);
fprintf(forward_f, "%s\t%u\t%u\t%s\t%i\t%c\n", chr, start, start+(b->core.l_qseq), "N", b->core.qual, strand);
}else{
//fprintf(reverse_f, "%s\t%u\t%u\t%s\t%i\t%c\n", chr, start, start+(b->core.l_qseq), bam1_qname(b), b->core.qual, strand);
fprintf(reverse_f, "%s\t%u\t%u\t%s\t%i\t%c\n", chr, start, start+(b->core.l_qseq), "N", b->core.qual, strand);
}
}
}else if((b->core.flag ==99) || (b->core.flag == 147) || (b->core.flag == 83) || (b->core.flag == 163) || (b->core.flag == 67) || (b->core.flag == 131) || (b->core.flag == 115) || (b->core.flag == 179) ){
if (abs(b->core.isize) > iSize || b->core.isize == 0){