-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtagbam.c
276 lines (230 loc) · 6.95 KB
/
tagbam.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
#include <zlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <getopt.h>
#include "cgranges.h"
#include "htslib/sam.h"
#include "kseq.h"
KSTREAM_INIT(gzFile, gzread, 0x10000)
struct amp {
char *name;
int strand;
int32_t st, en;
};
// parse a bed entry
char *parse_bed(char *s, int32_t *st_, int32_t *en_, struct amp *a_)
{
char *p, *q, *ctg = 0;
int32_t i, st = -1, en = -1, score;
char *name;
int strand;
for (i = 0, p = q = s;; ++q) {
if (*q == '\t' || *q == '\0') {
int c = *q;
*q = 0;
if (i == 0) ctg = p;
else if (i == 1) st = atol(p);
else if (i == 2) en = atol(p);
else if (i == 3) name = strdup(p);
else if (i == 4) score = atoi(p);
else if (i == 5) strand = strcmp(p,"+")==0 ? 1 : 0;
++i, p = q + 1;
if (c == '\0') break;
}
}
a_->name = name;
a_->strand = strand;
a_->st = st;
a_->en = en;
*st_ = st, *en_ = en;
return i >= 3? ctg : 0;
}
// read bed file into a cgranges object and also store an array of structs w/ amplicon name and strand.
cgranges_t *read_bed(const char *fn, struct amp *a)
{
gzFile fp;
cgranges_t *cr;
kstream_t *ks;
kstring_t str = {0,0,0};
int32_t k = 0;
if ((fp = gzopen(fn, "r")) == 0){
fprintf(stderr,"cannot open bed file: %s\n",fn);
return 0;
}
ks = ks_init(fp);
cr = cr_init();
while (ks_getuntil(ks, KS_SEP_LINE, &str, 0) >= 0) {
char *ctg;
struct amp a1;
int32_t st, en;
ctg = parse_bed(str.s, &st, &en, &a1);
if (ctg) cr_add(cr, ctg, st, en, k);
a[k] = a1;
k++;
}
free(str.s);
ks_destroy(ks);
gzclose(fp);
return cr;
}
int main(int argc, char *argv[])
{
int maxDist = 6;
int verbose = 0;
int c;
opterr = 0;
while ((c = getopt (argc, argv, "vd:")) != -1)
switch (c)
{
case 'v':
verbose = 1;
break;
case 'd':
maxDist = atoi(optarg);
break;
case '?':
if (optopt == 'd')
fprintf (stderr, "Option -%c requires an integer argument.\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
return 1;
default:
abort ();
}
if (argc - optind < 3) {
printf("Usage: tagbam [options] <input.bam> <amplicon.bed> <output.bam>\n");
printf("Options:\n");
printf(" -d <int> maximum sum of the distance bt amplicon and read ends (default=6)\n");
printf(" -v verbose\n");
return 0;
}
char *inbam = argv[optind];
char *inbed = argv[optind+1];
char *outbam = argv[optind+2];
// pointer array of structs to store amplicons
struct amp *amplicons = (struct amp*)malloc(1000000*sizeof(struct amp));
// read in bed file and store as a cgranges object + array of amplicons
cgranges_t *cr;
cr = read_bed(inbed,amplicons);
assert(cr);
cr_index(cr);
fprintf(stderr,"loaded %d amplicon bed entries\n",(int)cr->n_r);
fprintf(stderr,"loading %s\n",inbam);
// now open bam file
samFile *fpin;
if (!(fpin = sam_open(inbam, "rb"))) {
exit(1);
}
hts_idx_t *idx;
if (!(idx = sam_index_load(fpin, inbam))) {
fprintf(stderr, "Couldn't index for: %s\n",inbam);
exit(1);
}
bam_hdr_t *h;
if (!(h = sam_hdr_read(fpin))) {
fprintf(stderr, "Couldn't read header for: %s\n",inbam);
exit(1);
}
bam1_t *b = bam_init1();
hts_itr_t *itr = sam_itr_querys(idx, h, ".");
// make output bam file
samFile *fpout = sam_open(outbam, "wb");
if (sam_hdr_write(fpout, h) != 0){
fprintf(stderr,"cannot create bam file: %s",outbam);
goto clean;
}
int readcounter = 0;
int readstagged = 0;
// iterate through bam file one at a time
while (sam_itr_next(fpin, itr, b) >= 0){
int strand;
hts_pos_t st, en;
const char *ref = sam_hdr_tid2name(h,b->core.tid); //h->target_name[b->core.tid];
// dist = sum of distances between starts and ends of read and amplicon
int dist = -1;
// the index of hit that minimizes the sum of end distances
int besthit = -1;
// helper function to get end position of read
if (!(b->core.flag & BAM_FREVERSE)){
st = b->core.pos;
en = st + llabs(b->core.isize) - 1;
} else {
st = b->core.mpos;
en = st + llabs(b->core.isize) - 1;
}
// strand of read source molecule/probe: read1 is + = 1, read1 is - = 0
if (((b->core.flag & BAM_FREAD1) && !(b->core.flag & BAM_FREVERSE)) || ((b->core.flag & BAM_FREAD2) && (b->core.flag & BAM_FREVERSE))){
strand = 1;
} else {
strand = 0;
}
int numhits = 0;
// only tag properly paired reads with amplicons
if(b->core.flag & BAM_FPROPER_PAIR){
int64_t i, n, *d = 0, max_d = 0;
n = cr_overlap(cr, ref, st, en, &d, &max_d);
numhits = (int)n;
for (i = 0; i < n; ++i){ // traverse overlapping intervals and find
if(amplicons[cr_label(cr, d[i])].strand != strand)
continue;
if(amplicons[cr_label(cr, d[i])].st != cr_start(cr, d[i]) || amplicons[cr_label(cr, d[i])].en != cr_end(cr, d[i]))
fprintf(stderr,"coordinate mismatch...\n");
// make this hit the best one if the end distance sum is smaller
if(dist < 0 || dist > llabs(cr_start(cr, d[i]) - st) + llabs(cr_end(cr, d[i]) - en)){
dist = llabs(cr_start(cr, d[i]) - st) + llabs(cr_end(cr, d[i]) - en);
besthit = cr_label(cr, d[i]);
}
}
// cleanup
free(d);
// if dist is <= maxDist then assign the read to the amplicon
if (dist > 0 && dist <= maxDist){
readstagged++;
// delete the XN tag, if present
uint8_t *data;
if ((data = bam_aux_get(b,"XN")) != NULL)
bam_aux_del(b, data);
bam_aux_append(b, "XN", 'Z', strlen(amplicons[besthit].name)+1, (uint8_t*)amplicons[besthit].name);
}
}
if(verbose==1){
// this is for development purposes--read in the XN tag, if present, and then print out the read data.
char *xn = ".";
uint8_t* dat;
if ((dat = bam_aux_get(b,"XN")) != NULL)
xn = bam_aux2Z(dat);
if(b->core.flag & BAM_FUNMAP) {
fprintf(stdout,"*\t*\t*\t%s\t%s\n", bam_get_qname(b),xn);
} else {
fprintf(stdout,"%s\t%lld\t%lld\t%s\t%s\n",sam_hdr_tid2name(h,b->core.tid),st,en,bam_get_qname(b),xn);
}
}
// write to new bam
if (sam_write1(fpout, h, b) < 0){
fprintf(stderr,"error writing to bam file\n");
goto clean;
}
// progress counter
readcounter++;
if (readcounter % 10000 == 0)
fprintf(stderr,"processed %d reads...\n",readcounter);
}
fprintf(stderr,"tagged %d reads out of %d (%.2f%%) with maxDist=%d\n",readstagged,readcounter, (double)readstagged / (double)readcounter * 100.0, maxDist);
clean:
for (int i=0; i<1000000; i++) {
free(amplicons[i].name);
}
free(amplicons);
cr_destroy(cr);
bam_destroy1(b);
hts_itr_destroy(itr);
bam_hdr_destroy(h);
sam_close(fpin);
sam_close(fpout);
}