-
Notifications
You must be signed in to change notification settings - Fork 49
/
bamdst.c
1743 lines (1623 loc) · 63.5 KB
/
bamdst.c
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
/* The MIT License
Copyright (c) 2022, 2023, 2024 Authors
Copyright (c) 2013-2014 Beijing Genomics Institution (BGI)
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "bedutil.h"
#include "commons.h"
#include "count.h"
// bam.h and sam_header.h are standard header from samtools
#include "bam.h"
#include "sam_header.h"
// khash, kstring and knetfile are standard utils of klib
#include "bgzf.h" // write tabix-able depth.gz file
#include "khash.h"
#include "knetfile.h"
#include "kstring.h"
#include <sys/stat.h>
static char const *program_name = "bamdst";
static char const *Version = "1.1.0";
/* flank region will be stat in the coverage report file,
* this value can be set by -f / --flank */
static int flank_reg = 200;
/* extern bedHand from bedutil.c, it is a collection of functions*/
extern bedHandle_t *bedHand;
/* only accepted one stdin pipeline */
static bool stdin_lock = FALSE;
/* the bed file is zero based */
static bool zero_based = TRUE;
/* 定义 max cutoff 最大值为10 */
static const int MAX_CUTOFFS = 10;
/* The number of threads after which there are
diminishing performance gains. */
// enum { DEFAULT_MAX_THREADS = 8 };
/* duplicate will be removed if rmdup_mark is TRUE
* this option is removed since version 1.0.0
*/
// static bool rmdup_mark = FALSE;
/* export target reads to a specitified bam file */
static char *export_target_bam = NULL;
bamFile bamoutfp;
int check_filename_isbam(char *name)
{
int length = strlen(name);
if (strcmp(name + length - 4, ".bam"))
return 1;
return 0;
}
// static const int WINDOW_SIZE = 102400;
// force replace the existed files
// static bool is_forced = TRUE;
static char *outdir = NULL;
// init hash struct to store uncover regions
static int uncover_cutoff = 5;
static regHash_t *h_uncov;
void h_uncov_init()
{
h_uncov = kh_init(reg);
}
// init hash struct to store chromosome length
static chrHash_t *h_chrlen;
void h_chrlength_init()
{
h_chrlen = kh_init(chr);
}
// warp bamheader to retrieve chromosome legth hash
void header2chrhash(bam_header_t *h)
{
int i, n, ret;
khiter_t k;
h->dict = sam_header_parse2(h->text);
const char *tags[] = {"SN", "LN", "UR", "M5", NULL};
char **tbl = sam_header2tbl_n(h->dict, "SQ", tags, &n);
for (i = 0; i < n; i++)
{
k = kh_put(chr, h_chrlen, strdup(tbl[4 * i]), &ret);
kh_val(h_chrlen, k).length = atoi(tbl[4 * i + 1]);
}
if (tbl)
free(tbl);
}
void chrhash_destroy()
{
khiter_t k;
if (h_chrlen)
{
for (k = 0; k < kh_end(h_chrlen); ++k)
{
if (kh_exist(h_chrlen, k))
freemem((char *)kh_key(h_chrlen, k));
// skip destroy void data...
}
kh_destroy(chr, h_chrlen);
}
}
/* @FLANK_REGION coverage of flank region list in report.
@INSERTSIZE_LIMIT the insert size bigger than this will not be calculated.
@MAXDEPTH_LIMIT the depth bigger than this will not be calculated,
0 means no limit.
@CUTOFF if you want know coverage of specity depth, set this value.
@MAPQ_LIMIT >=mapQ_limit list in report.
*/
struct opt_aux
{
int nfiles;
char **inputs;
int isize_lim;
// int cutoff;
bool cutoff;
int num_cutoffs;
int max_cutoffs; // 最大允许的 cutoff 数量
int *cutoffs; // 指向 cutoff 数组的指针
int mapQ_lim;
int maxdepth;
};
// 一个函数来初始化 opt_aux 结构体
struct opt_aux init_opt_aux()
{
struct opt_aux opt;
memset(&opt, 0, sizeof(opt)); // 初始化所有成员为0
opt.num_cutoffs = 0;
opt.max_cutoffs = MAX_CUTOFFS; // 设置最大 cutoff 数量
opt.cutoff = FALSE;
opt.cutoffs = malloc(opt.max_cutoffs * sizeof(int)); // 分配内存
if (opt.cutoffs == NULL)
{
// 处理内存分配失败
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
// 其他成员的初始化...
opt.inputs = NULL;
opt.isize_lim = 2000;
opt.mapQ_lim = 20;
return opt;
}
struct depnode
{
unsigned len; // len will be set to 0, if not allocated memory
unsigned start;
unsigned stop;
unsigned *vals; // raw depth
unsigned *cnts; // reads count in this position
unsigned *rmdupdep; // clean depth, rmdup, mapQ > 20, primary hit
unsigned *covdep; // coverage depth
struct depnode *next;
};
// debug the depnode list init
static const char *init_debugmsg[] = {"Success", "Trying to allocated an unempty node",
"Trying to allocated a zero memory", "END of list"};
// debug macro, I think it is a good way to find memeory problem
#define INIT_DEBUG(x) \
do \
{ \
int _a = x; \
if (_a > 0 && _a < 3) \
{ \
warnings("%s : %d %s", __FILE__, __LINE__, init_debugmsg[_a]); \
} \
} while (0)
/* node->vals is the depth value of each loc
* node->cnts is the count of covered reads
* init the memory before use it */
static int depnode_init(struct depnode *node)
{
if (isNull(node))
return 3;
if (node->len)
return 1;
node->len = node->stop - node->start + 1;
if (isZero(node->len))
return 2;
node->vals = (unsigned *)needmem((node->len) * sizeof(unsigned));
node->cnts = (unsigned *)needmem((node->len) * sizeof(unsigned));
node->rmdupdep = (unsigned *)needmem((node->len) * sizeof(unsigned));
node->covdep = (unsigned *)needmem((node->len) * sizeof(unsigned));
memset(node->vals, 0, node->len * sizeof(unsigned));
memset(node->cnts, 0, node->len * sizeof(unsigned));
memset(node->rmdupdep, 0, node->len * sizeof(unsigned));
memset(node->covdep, 0, node->len * sizeof(unsigned));
return 0;
}
/* delete node and make the node point to the next node */
#define del_node(node) \
do \
{ \
if (node) \
{ \
struct depnode *tmpnode = node; \
node = node->next; \
freemem(tmpnode->vals); \
freemem(tmpnode->cnts); \
freemem(tmpnode->rmdupdep); \
freemem(tmpnode->covdep); \
freemem(tmpnode); \
} \
} while (0)
/* construct the bed struct array to a list , return the header node */
static struct depnode *bed_depnode_list(bedreglist_t *bed)
{
struct depnode *node;
struct depnode *header = NULL;
struct depnode *tmpnode = NULL;
int i;
for (i = 0; i < bed->m; ++i)
{
node = (struct depnode *)needmem(sizeof(struct depnode));
node->start = (uint32_t)(bed->a[i] >> 32);
node->stop = (uint32_t)bed->a[i];
if (node->start < node->stop)
node->start++; // 0-based to 1-based, sametimes inertion variation have
// same beg and end pos
/* the length of this region should be zero if not allocated memory yet
* Assign the length value when init the vals and cnts */
node->len = 0;
if (isZero(i))
header = node;
else
tmpnode->next = node;
tmpnode = node;
}
INIT_DEBUG(depnode_init(header));
return header;
}
struct _aux
{
/* nchr, total num of chromsome
* ndata, total num of bam struct
* maxdepth, the maxmium of depth */
int nchr, ndata, maxdep;
/* tgt_len, length of target region
* flk_len, length of flank region
* tgt_nreg, total target regions */
uint64_t tgt_len, flk_len;
unsigned tgt_nreg;
/* data, array of bam struct
* h, point to bam header */
bamFile *data;
bam_header_t *h;
/* h_tgt, target bed hash
* h_flk, flank bed hash */
regHash_t *h_tgt;
regHash_t *h_flk;
// count struct of depths, insertsize, flank depths, target regions
count32_t *c_dep;
count32_t *c_rmdupdep;
count32_t *c_isize;
count32_t *c_flkdep;
count32_t *c_reg;
};
typedef struct _aux aux_t;
struct _aux *aux_init()
{
struct _aux *a;
a = calloc(1, sizeof(struct _aux));
a->nchr = a->maxdep = a->ndata = 0;
a->data = NULL; // bamFile
a->h = NULL; // bam header
a->h_tgt = kh_init(reg);
a->h_flk = kh_init(reg);
count32_init(a->c_dep);
count32_init(a->c_rmdupdep);
count32_init(a->c_isize);
count32_init(a->c_flkdep);
count32_init(a->c_reg);
return a;
}
void destroy_data(void *data)
{
count32_t *cnt = (count32_t *)data;
count_destroy(cnt);
}
void aux_destroy(struct _aux *a)
{
free(a->data);
bedHand->destroy((void *)a->h_tgt, destroy_data);
bedHand->destroy((void *)a->h_flk, destroy_void);
bam_header_destroy(a->h);
/* if (a->c_dep->n > 0) count_destroy(a->c_dep); */
/* if (a->c_rmdupdep->n > 0) count_destroy(a->c_rmdupdep); */
/* if (a->c_flkdep->n > 0) count_destroy(a->c_flkdep); */
/* if (a->c_isize->n > 0) count_destroy(a->c_isize); */
/* if (a->c_reg->n > 0) count_destroy(a->c_reg); */
count_destroy(a->c_dep);
count_destroy(a->c_rmdupdep);
count_destroy(a->c_flkdep);
count_destroy(a->c_isize);
count_destroy(a->c_reg);
free(a);
}
typedef struct bamflag
{
uint64_t n_reads, n_mapped, n_pair_map, n_pair_all, n_pair_good;
uint64_t n_sgltn, n_read1, n_read2;
uint64_t n_dup, n_rmdup1, n_rmdup2;
uint64_t n_diffchr, n_pstrand, n_mstrand;
uint64_t n_qcfail;
uint64_t n_data, n_mdata;
uint64_t n_qual;
/* delete n_uniq
* ref: https://www.biostars.org/p/59281/ */
uint64_t n_tgt, n_flk, n_tdata, n_fdata;
uint64_t n_trmdat; // target rmdup data
} bamflag_t;
/*
* flag:
* 0 qc failed
* 1 clean read
* 2 duplicate
* 3 secondary alignment
* -1 normal end
* -2 trancate
* -3 unmap
*/
// use this macro to stat the flags
#define flagstat(s, c, ret) \
do \
{ \
++(s)->n_reads; \
(s)->n_data += (c)->l_qseq; \
if ((c)->flag & BAM_FQCFAIL) \
{ \
++(s)->n_qcfail; \
ret = 0; \
} \
else \
{ \
ret = 1; \
if ((c)->flag & BAM_FPAIRED) \
{ \
++(s)->n_pair_all; \
if (((c)->flag & BAM_FPROPER_PAIR) && !((c)->flag & BAM_FUNMAP)) \
++(s)->n_pair_good; \
if ((c)->flag & BAM_FREAD1) \
++(s)->n_read1; \
if ((c)->flag & BAM_FREAD2) \
++(s)->n_read2; \
if (((c)->flag & BAM_FMUNMAP) && !((c)->flag & BAM_FUNMAP)) \
++(s)->n_sgltn; \
if (!((c)->flag & BAM_FUNMAP) && !((c)->flag & BAM_FMUNMAP)) \
{ \
++(s)->n_pair_map; \
if ((c)->mtid != (c)->tid) \
++(s)->n_diffchr; \
} \
} \
if (!((c)->flag & BAM_FUNMAP)) \
{ \
++(s)->n_mapped; \
(s)->n_mdata += (c)->l_qseq; \
if ((c)->flag & BAM_FREVERSE) \
++(s)->n_mstrand; \
else \
++(s)->n_pstrand; \
if ((c)->flag & BAM_FDUP) \
{ \
++(s)->n_dup; \
ret = 2; \
} \
} \
else \
{ \
ret = -3; \
} \
} \
} while (0)
static void emit_try_help(void)
{
fprintf(stderr, "out dir and bed file are mandatory!\n");
fprintf(stderr, "Try '%s --help' for more information.\n", program_name);
}
void usage(int status)
{
if (status == 0)
emit_try_help();
else
{
printf("\n\
bamdst version: %s\n\
USAGE : %s [OPTION] -p <probe.bed> -o <output_dir> [in1.bam [in2.bam ... ]]\n\
or : %s [OPTION] -p <probe.bed> -o <output_dir> -\n\
",
Version, program_name, program_name);
puts("\
Option -o and -p are mandatory:\n\
-o, --outdir output dir\n\
-p, --bed probe or target regions file, the region file will \n\
be merged before calculate depths\n\
");
puts("\
Optional parameters:\n\
-f, --flank [200] flank n bp of each region\n\
-q [20] map quality cutoff value, greater or equal to the value will be count\n\
--maxdepth [0] set the max depth to stat the cumu distribution.\n\
--cutoffdepth [0,0] list the coverage of above these depths, allow maximal 10 cutoffs.\n\
--isize [2000] stat the inferred insert size under this value\n\
--uncover [5] region will included in uncover file if below it\n\
--bamout BAMFILE target reads will be exported to this bam file\n\
-1 begin position of bed file is 1-based\n\
-h, --help print this help info\n\
\n");
puts("\
* Five essential files would be created in the output dir. \n\
* region.tsv.gz and depth.tsv.gz are zipped by bgzip, so you can use tabix \n\
index these files.\n\n\
- coverage.report a report of the coverage information and reads \n\
information of whole target regions\n\
- cumu.plot distribution data of depth values\n\
- insert.plot distribution data of inferred insert size \n\
- chromosome.report coverage information for each chromosome\n\
- region.tsv.gz mean depth, median depth and coverage of each region\n\
- depth.tsv.gz raw depth, rmdup depth, coverage depth of each position\n\
- uncover.bed the bad covered or uncovered region in the probe file\n\
\n\
* About depth.tsv.gz:\n\
* There are five columns in this file, including chromosome, position, raw\n\
* depth, rmdep depth, coverage depth\n\
- chromosome the chromosome name\n\
- position 1-based position of each chromosome\n\
- raw depth raw depth of position, not filter\n\
- rmdup depth remove duplication, and only calculate the reads which\n\
are primary mapped and mapQ >= cutoff_mapQ (default 20)\n\
- coverage depth calculate the deletions (CIGAR level) into depths,\n\
for coverage use.\n\
");
puts("============\n");
puts(" HOMEPAGE: \n\
https://github.com/shiquan/bamdst\n");
}
exit(EXIT_SUCCESS);
}
/**
* @brief 如果文件夹路径不存在则创建该路径
* @param path
* @param mode
* @return
*/
int mkdirp(const char *path, mode_t mode)
{
char tmp[256];
char *p;
// 确保路径不以 '/' 结束,除非它是根目录
snprintf(tmp, sizeof(tmp), "%.*s", (int)(strlen(path) < sizeof(tmp) - 1) ? strlen(path) : sizeof(tmp) - 1, path);
for (p = &tmp[1]; *p; p++)
{
if (*p == '/')
{
*p = '\0'; // 分割点
if (mkdir(tmp, mode) != 0 && errno != EEXIST)
{
fprintf(stderr, "Failed to create directory '%s': %s\n", tmp, strerror(errno));
return -1;
}
*p = '/'; // 恢复路径
}
}
// 创建最后的目录
if (mkdir(tmp, mode) != 0 && errno != EEXIST)
{
fprintf(stderr, "Failed to create directory '%s': %s\n", tmp, strerror(errno));
return -1;
}
return 0;
}
#include "ksort.h"
KSORT_INIT_GENERIC(uint32_t)
static float median_cal(const uint32_t *array, int l)
{
if (l == 0)
return 0;
if (l == 1)
return (float)array[0];
if (l == 2)
return (float)(array[0] + array[1]) / 2;
uint32_t *tmp;
tmp = (uint32_t *)needmem(l * sizeof(uint32_t));
memcpy(tmp, array, l * sizeof(uint32_t));
ks_introsort(uint32_t, l, tmp);
float med = l & 1 ? tmp[(l >> 1) + 1] : (float)(tmp[l >> 1] + tmp[(l >> 1) - 1]) / 2;
mustfree(tmp);
return med;
}
static float avg_cal(const uint32_t *array, int l)
{
if (isNull(l))
return 0;
float avg = 0;
int i;
for (i = 0; i < l; ++i)
avg += (float)array[i];
avg /= (float)l;
return avg;
}
static float coverage_cal(const uint32_t *array, int l)
{
if (isNull(l))
return 0;
float cov = 0;
int i;
for (i = 0; i < l; ++i)
if (array[i])
cov++;
cov /= (float)l;
return cov * 100;
}
// FIXME: need broken when bed file is truncated
int load_bed_init(char const *fn, aux_t *a)
{
int ret = 0;
bedHand->read(fn, a->h_tgt, 0, 0, &ret);
if (zero_based && ret)
{
warnings("This region is not a standard bed format.\n"
"Please use parameter \"-1\" if your bed file is 1-based!");
}
if (!zero_based)
bedHand->base1to0(a->h_tgt);
bedHand->merge(a->h_tgt);
int nchr;
nchr = bedHand->check_length(a->h_tgt, h_chrlen);
if (nchr != -1)
{
errabort(" The bed region is out the range of this chromosome %s. The max "
"length is %u ..",
(char *)kh_key(h_chrlen, (khiter_t)nchr), kh_val(h_chrlen, (khiter_t)nchr).length);
;
}
inf_t *inf1 = bedHand->stat(a->h_tgt);
a->tgt_len = inf1->length;
a->tgt_nreg = inf1->total;
bedHand->read(fn, a->h_flk, flank_reg, flank_reg, &ret);
if (!zero_based)
bedHand->base1to0(a->h_flk);
bedHand->merge(a->h_flk);
bedHand->check_length(a->h_tgt, h_chrlen); // warp the length accord to the chromosome length
// bedHand->diff(a->h_flk, a->h_tgt);
inf_t *inf2 = bedHand->stat(a->h_flk);
a->flk_len = inf2->length;
mustfree(inf1);
mustfree(inf2);
return 0;
}
// this function used to add an region to the bedregion struct
// use this struct to store the uncovered region
int push_bedreg(bedreglist_t *bed, uint32_t begin, uint32_t end)
{
if (isZero(bed->n))
{
bed->n = 2;
bed->a = (uint64_t *)needmem(bed->n * sizeof(uint64_t));
}
else if (bed->m == bed->n)
{
bed->n = bed->n + 1024;
bed->a = (uint64_t *)enlarge_empty_mem((void *)bed->a, bed->m * sizeof(uint64_t), bed->n * sizeof(uint64_t));
}
bed->a[bed->m++] = (uint64_t)begin << 32 | (uint32_t)end;
return 0;
}
typedef enum
{
CMATCH,
CDEL,
CDUP,
CLOWQ, // low quality, bug report by TOM MORRIS
UNKNOWN
} cntstat_t;
int match_pos(struct depnode *header, uint32_t pos, cntstat_t state)
{
struct depnode *tmp = header;
while (tmp && pos > tmp->stop)
{
tmp = tmp->next;
}
if (isNull(tmp))
return 1; // this chromosome is finished, skip in next loop
// debug("pos: %u\tstart: %u\tstop: %u", pos, tmp->start, tmp->stop);
if (pos >= tmp->start)
{
if (isZero(tmp->len))
depnode_init(tmp);
if (state == CMATCH)
{
tmp->vals[pos - tmp->start]++;
tmp->rmdupdep[pos - tmp->start]++;
tmp->covdep[pos - tmp->start]++;
}
else if (state == CDEL)
{
tmp->covdep[pos - tmp->start]++;
}
else
{
tmp->vals[pos - tmp->start]++;
tmp->covdep[pos - tmp->start]++;
}
return 0;
}
return 1; // not reachable
}
/* when deal with a read struct, check the begin of this read and the last
* position of this read, if this read is overlap with target region, sum up the
* depth of each related position */
int readcore(struct depnode *header, bam1_t const *b, cntstat_t state)
{
struct depnode *tmp = header;
cntstat_t tmp_state = state;
int i;
bam1_core_t const *c = &b->core;
int pos = c->pos + 1;
/* while (tmp && pos > tmp->stop) */
/* { */
/* tmp= tmp->next; */
/* } */
/* header = tmp; */
if (isNull(tmp))
return 0;
uint32_t *cigar = bam1_cigar(b);
uint32_t end = bam_calend(c, cigar);
if (end >= tmp->start)
{
int j = 0, l, s;
if (pos >= tmp->start)
{
if (isZero(tmp->len))
depnode_init(tmp);
tmp->cnts[pos - tmp->start]++;
}
for (i = 0; i < c->n_cigar; ++i)
{
s = cigar[i] & 0xf;
l = cigar[i] >> BAM_CIGAR_SHIFT;
if (s == BAM_CDEL)
tmp_state = CDEL;
// else if (s == BAM_CMATCH) tmp_state = state;
else if (s == BAM_CMATCH || s == BAM_CEQUAL || s == BAM_CDIFF)
tmp_state = state;
else
continue;
for (j = 0; j < l; ++j)
{
if (pos >= tmp->start)
match_pos(tmp, pos, tmp_state);
pos++;
}
}
return 1;
}
return 0;
}
typedef struct
{
int tid;
int lstpos;
bedreglist_t *tar;
bedreglist_t *flk;
bedreglist_t *ucreg;
count32_t *depvals_of_chr;
char *name;
struct depnode *tgt_node;
struct depnode *flk_node;
kstring_t *pdepths;
kstring_t *rcov;
BGZF *fdep; // write depth to this file
BGZF *freg; // write coverage of each region to this file
} loopbams_parameters_t;
loopbams_parameters_t *init_loopbams_parameters()
{
loopbams_parameters_t *para;
para = (loopbams_parameters_t *)needmem(sizeof(loopbams_parameters_t));
*para = (loopbams_parameters_t){.tid = -1};
para->pdepths = (kstring_t *)needmem(sizeof(kstring_t));
para->rcov = (kstring_t *)needmem(sizeof(kstring_t));
para->pdepths->l = para->pdepths->m = 0;
para->rcov->l = para->rcov->m = 0;
if (outdir) chdir(outdir);
para->fdep = bgzf_open("depth.tsv.gz", "w");
if (isNull(para->fdep))
errabort("failed to open file depth.tsv.gz");
para->freg = bgzf_open("region.tsv.gz", "w");
if (isNull(para->freg))
errabort("failed to open file region.tsv.gz");
return para;
}
int close_loopbam_parameters(loopbams_parameters_t *para)
{
if (para->tgt_node)
{
while (para->tgt_node)
{
debug("length: %d\tstart:%u\tend:%u\n", para->tgt_node->len, para->tgt_node->start, para->tgt_node->stop);
para->tgt_node = para->tgt_node->next;
}
errabort("[close loopbam] target node is still reachable");
}
if (para->flk_node)
errabort("[close loopbam] flank node is still reachable");
freemem(para->pdepths->s);
freemem(para->rcov->s);
mustfree(para->pdepths);
mustfree(para->rcov);
bgzf_close(para->fdep);
bgzf_close(para->freg);
mustfree(para);
return 0;
}
int write_buffer_bgzf(kstring_t *str, BGZF *fp)
{
int write_size;
if (str->l)
{
bgzf_flush_try(fp, str->l);
write_size = bgzf_write(fp, str->s, str->l);
str->l = 0;
return write_size;
}
return 0;
}
int stat_each_region(loopbams_parameters_t *para, aux_t *a)
{
struct depnode *node = para->tgt_node;
if (isNull(node))
return 0;
int j;
float avg, med, cov1, cov2;
uint32_t lst_start = 0; // uncover region start
uint32_t lst_stop = 0; // uncover region stop
if (node->len)
{
avg = avg_cal(node->vals, node->len);
med = median_cal(node->vals, node->len);
cov1 = coverage_cal(node->vals, node->len);
cov2 = coverage_cal(node->covdep, node->len);
for (j = 0; j < node->len; ++j)
{
ksprintf(para->pdepths, "%s\t%d\t%u\t%u\t%u\n", para->name, node->start + j, node->vals[j],
node->rmdupdep[j], node->covdep[j]);
// count_increase will alloc memory space automatically
// use covdep to calculate coverage and averge depth
count_increase(para->depvals_of_chr, node->covdep[j], uint32_t);
count_increase(a->c_dep, node->covdep[j], uint32_t);
count_increase(a->c_rmdupdep, node->rmdupdep[j], uint32_t);
/* store the uncover region */
if (node->covdep[j] < uncover_cutoff)
{
if (isZero(lst_start) && isZero(lst_stop))
{
lst_start = node->start + j;
lst_stop = lst_start;
}
else
{
lst_stop = node->start + j;
}
}
else if (lst_start > 0)
{
push_bedreg(para->ucreg, lst_start, lst_stop);
lst_start = 0;
lst_stop = 0;
}
}
if (lst_start > 0)
{
push_bedreg(para->ucreg, lst_start, lst_stop);
}
write_buffer_bgzf(para->pdepths, para->fdep);
}
else
{
avg = med = cov1 = cov2 = 0.0;
for (j = 0; j < node->len; ++j)
{
ksprintf(para->pdepths, "%s\t%d\t0\t0\t0\n", para->name, node->start + j);
write_buffer_bgzf(para->pdepths, para->fdep);
}
push_bedreg(para->ucreg, node->start, node->stop); // store uncover region
count_increaseN(para->depvals_of_chr, 0, node->len, uint32_t);
count_increaseN(a->c_dep, 0, node->len, uint32_t);
}
// ksprintf(para->pdepths,"\n");
count_increase(a->c_reg, (int)avg, uint32_t);
ksprintf(para->rcov, "%s\t%u\t%u\t%.2f\t%.1f\t%.2f\t%.2f\n", para->name, node->start - 1, node->stop, avg, med,
cov1, cov2);
// if (para->rcov->l > WINDOW_SIZE)
write_buffer_bgzf(para->rcov, para->freg);
return 0;
}
// if bam files not contained all chromosomes in the bed file
int check_reachable_regions(loopbams_parameters_t *para, aux_t *a)
{
khiter_t k;
khiter_t l;
int ret = 0;
for (k = 0; k < kh_end(a->h_tgt); ++k)
{
if (kh_exist(a->h_tgt, k))
{
para->name = (char *)kh_key(a->h_tgt, k);
para->tar = &kh_val(a->h_tgt, k);
if (para->tar->flag == 1)
continue; // already reach
warnings("%s is not contained in this bam file.", para->name);
count32_init(para->depvals_of_chr);
para->tar->data = (void *)para->depvals_of_chr;
para->flk = &kh_val(a->h_flk, k);
para->tgt_node = bed_depnode_list(para->tar);
para->flk_node = bed_depnode_list(para->flk);
l = kh_put(reg, h_uncov, strdup(para->name), &ret);
if (!ret)
errabort("this chromosome should be empty! please contact developer to "
"report this bug!");
bedreglist_t *ucreg_tmp;
ucreg_tmp = (bedreglist_t *)needmem(sizeof(bedreglist_t));
kh_val(h_uncov, l) = *ucreg_tmp;
para->ucreg = &kh_val(h_uncov, l);
while (para->tgt_node)
{
int length = para->tgt_node->stop - para->tgt_node->start + 1;
count_increaseN(a->c_dep, 0, length, uint32_t);
stat_each_region(para, a);
del_node(para->tgt_node); // no need allocate memory for these nodes
}
// count_merge(a->c_dep, para->depvals_of_chr, uint32_t);
while (para->flk_node)
{
int length = para->flk_node->stop - para->flk_node->start + 1;
count_increaseN(a->c_flkdep, 0, length, uint32_t);
del_node(para->flk_node); // no need allocate memory for these nodes
}
}
}
return 0;
}
int stat_flk_depcnt(loopbams_parameters_t *para, aux_t *a)
{
int j;
struct depnode *node = para->flk_node;
for (j = 0; j < node->len; ++j)
count_increase(a->c_flkdep, node->vals[j], uint32_t);
del_node(para->flk_node);
depnode_init(para->flk_node);
return 0;
}
void write_unover_file()
{
if (outdir) chdir(outdir);
bedHand->merge(h_uncov);
bedHand->base1to0(h_uncov);
bedHand->save("uncover.bed", h_uncov);
bedHand->destroy(h_uncov, destroy_data);
}
// load bam files and stat the depths
// huge function, need IMPROVE it!!
int load_bamfiles(struct opt_aux *f, aux_t *a, bamflag_t *fs)
{
// get the chromosome name from header
bam_header_t *h = a->h;
loopbams_parameters_t *para = init_loopbams_parameters();
ksprintf(para->pdepths, "#Chr\tPos\tRaw Depth\tRmdup depth\tCover depth\n");
ksprintf(para->rcov, "#Chr\tStart\tStop\tAvg depth\tMedian\tCoverage\tCoverage(FIX)\n");
if (outdir) chdir(outdir);
h_uncov_init();
int i;
for (i = 0; i < a->ndata; ++i)
{
bamFile dat = a->data[i];
bool goto_next_chromosome = FALSE;
int ret;
cntstat_t state;
// main loop
bam1_t *b;
b = (bam1_t *)needmem(sizeof(bam1_t));
while (1)
{
state = CMATCH;
ret = bam_read1(dat, b);
if (ret == -1)
{
break; // normal end
}
if (ret == -2)
{
errabort("%d bam file is truncated!\n", i + 1);
}
bam1_core_t *c = &b->core;
// skip secondary and supplement alignment first
if (c->flag & BAM_FSECONDARY || c->flag & BAM_FSUPPLEMENTARY)
continue;
flagstat(fs, c, ret);
// People usually want to know how many aligned reads with mapping quality
// greater than or equally to 10 or 20.. if (c->qual > f->mapQ_lim)
// fs->n_qual++;
if (c->qual >= f->mapQ_lim)
fs->n_qual++;
else
state = CLOWQ;
if (c->tid == -1 || ret == -3)
continue; // goto endcore; // unmapped~