Debian Codegraph @

samtools/bam_ampliconclip.c

raw symbols SCIP
1 /* bam_ampliconclip.c -- loads amplicon primers from a BED file and cuts reads
2 from the 5' end.
3
4 Copyright (C) 2020-2024 Genome Research Ltd.
5
6 Authors: Andrew Whitwham <[email protected]>
7 Rob Davies <[email protected]>
8
9 Permission is hereby granted, free of charge, to any person obtaining a copy
10 of this software and associated documentation files (the "Software"), to deal
11 in the Software without restriction, including without limitation the rights
12 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 copies of the Software, and to permit persons to whom the Software is
14 furnished to do so, subject to the following conditions:
15
16 The above copyright notice and this permission notice shall be included in
17 all copies or substantial portions of the Software.
18
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25 DEALINGS IN THE SOFTWARE
26 */
27
28 #include <config.h>
29
30 #include <assert.h>
31 #include <stdbool.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <errno.h>
36 #include "htslib/thread_pool.h"
37 #include "sam_opts.h"
38 #include <htslib/hts.h>
39 #include "htslib/hfile.h"
40 #include "htslib/kstring.h"
41 #include "htslib/sam.h"
42 #include "samtools.h"
43 #include "bam_ampliconclip.h"
44
45 typedef enum {
46 soft_clip,
47 hard_clip
48 } clipping_type;
49
50 typedef struct {
51 int add_pg;
52 int use_strand;
53 int write_clipped;
54 int mark_fail;
55 int both;
56 int fail_len;
57 int filter_len;
58 int unmapped;
59 int oa_tag;
60 int del_tag;
61 int tol;
62 int unmap_len;
63 char *arg_list;
64 char *stats_file;
65 char *primer_counts_file;
66 char *rejects_file;
67 } cl_param_t;
68
69
70 static int bed_entry_sort(const void *av, const void *bv) {
71 bed_entry_t *a = (bed_entry_t *) av;
72 bed_entry_t *b = (bed_entry_t *) bv;
73 return a->right < b->right ? -1 : (a->right == b->right ? 0 : 1);
74 }
75
76 int load_bed_file_multi_ref(char *infile, int get_strand, int sort_by_pos, khash_t(bed_list_hash) *bed_lists, char ***ref_list, size_t *num_refs_out) {
77 hFILE *fp;
78 int line_count = 0, ret;
79
80 //variables to store the bed file data for each record
81 char ref[1024] = "";
82 int64_t left, right;
83 char name[1024] = "", score[1024] = "";
84 char strand;
85
86 //hash table to store clipping results and bed file data
87 kstring_t line = KS_INITIALIZE;
88 bed_entry_list_t *list;
89 khiter_t bed_itr;
90
91 //ordered ref names list
92 size_t ref_list_sz = 0;
93 size_t num_refs = 0;
94
95 if (ref_list)
96 *ref_list = NULL;
97
98 if (num_refs_out)
99 *num_refs_out = 0;
100
101 if ((fp = hopen(infile, "r")) == NULL) {
102 print_error_errno("amplicon", "unable to open file %s.", infile);
103 return 1;
104 }
105
106
107 while (line.l = 0, kgetline(&line, (kgets_func *)hgets, fp) >= 0) {
108 line_count++;
109 int hret;
110
111 if (line.l == 0 || *line.s == '#') continue;
112 if (strncmp(line.s, "track ", 6) == 0) continue;
113 if (strncmp(line.s, "browser ", 8) == 0) continue;
114
115 // A list of the maximal number of columns we may want to parse.
116 // There may be more, but we don't use the ones beyond these.
117 const char *const scanf_str =
118 "%1023s %"SCNd64" %"SCNd64" %1023s %1023s %c";
119
120 // Extract the data from the line into the variables.
121 // Variables corresponding to any missing columns will remain
122 // uninitialised. We asked for all columns, but cols_parsed will
123 // return how many we found which can be validated against num_columns.
124 int cols_parsed = sscanf(line.s, scanf_str, ref,
125 &left, &right, name, score, &strand);
126 if (cols_parsed < (get_strand ? 6 : 3)) {
127 fprintf(stderr, "[amplicon] error: invalid bed file format in line %d of %s.\n"
128 "Parsed %d columns, but need at least %d\n"
129 "(N.B. ref/chrom name limited to 1023 characters.)\n",
130 line_count, infile, cols_parsed, get_strand ? 6 : 3);
131 ret = 1;
132 goto error;
133 }
134
135 bed_itr = kh_get(bed_list_hash, bed_lists, ref);
136
137 if (bed_itr == kh_end(bed_lists)) { // new ref entry
138 char *ref_name = strdup(ref); // need a copy for the hash key
139
140 if (!ref_name) {
141 fprintf(stderr, "[amplicon] error: unable to allocate memory for ref name.\n");
142 ret = 1;
143 goto error;
144 }
145
146 if (ref_list) {
147 if (hts_resize(char **, num_refs + 1, &ref_list_sz, ref_list, 0) < 0) {
148 fprintf(stderr, "[amplicon] error: unable to allocate memory for ref name list.\n");
149 ret = 1;
150 goto error;
151 }
152 (*ref_list)[num_refs++] = ref_name;
153 }
154 bed_itr = kh_put(bed_list_hash, bed_lists, ref_name, &hret);
155
156 if (hret > 0) {
157 list = &kh_val(bed_lists, bed_itr);
158
159 // initialise the new hash entry
160 list->longest = 0;
161 list->size = 0;
162 list->length = 0;
163 list->bp = NULL;
164 } else {
165 fprintf(stderr, "[amplicon] error: ref hashing failure.\n");
166 ret = 1;
167 goto error;
168 }
169 } else { // existing ref
170 list = &kh_val(bed_lists, bed_itr);
171 }
172
173 // add the bed entry to the list, growing the list if necessary
174 if (list->length == list->size) {
175 bed_entry_t *tmp;
176
177 list->size += list->size / 2 + 256;
178
179 if ((tmp = realloc(list->bp, list->size * sizeof(bed_entry_t))) == NULL) {
180 fprintf(stderr, "[amplicon] error: unable to allocate more memory for bed data.\n");
181 ret = 1;
182 goto error;
183 }
184
185 list->bp = tmp;
186 }
187
188 list->bp[list->length].left = left;
189 list->bp[list->length].right = right;
190 list->bp[list->length].name = NULL;
191 list->bp[list->length].score = NULL;
192 if (cols_parsed >= 4) {
193 list->bp[list->length].name = strdup(name);
194 if (list->bp[list->length].name == NULL) {
195 fprintf(stderr, "[amplicon] error: unable to allocate memory for name in line %d of %s: %s.\n", line_count, infile, line.s);
196 ret = 1;
197 goto error;
198 }
199 }
200 if (cols_parsed >= 5) {
201 list->bp[list->length].score = strdup(score);
202 if (list->bp[list->length].score == NULL) {
203 fprintf(stderr, "[amplicon] error: unable to allocate memory for score in line %d of %s: %s\n", line_count, infile, line.s);
204 ret = 1;
205 goto error;
206 }
207 }
208
209 list->bp[list->length].num_reads = 0;
210
211 if (get_strand) {
212 if (strand == '+') {
213 list->bp[list->length].rev = 0;
214 } else if (strand == '-') {
215 list->bp[list->length].rev = 1;
216 } else {
217 fprintf(stderr, "[amplicon] error: bad strand value in line %d, expecting '+' or '-', found '%c'.\n",
218 line_count, strand);
219 ret = 1;
220 goto error;
221 }
222 }
223
224 if (right - left > list->longest)
225 list->longest = right - left;
226
227 list->length++;
228 }
229
230 if (sort_by_pos) {
231 for (bed_itr = kh_begin(bed_lists); bed_itr != kh_end(bed_lists); ++bed_itr) {
232 if (kh_exist(bed_lists, bed_itr)) {
233 list = &kh_val(bed_lists, bed_itr);
234 qsort(list->bp, list->length, sizeof(list->bp[0]), bed_entry_sort);
235 }
236 }
237 }
238
239 if (kh_size(bed_lists) > 0) {// any entries
240 ret = 0;
241 } else {
242 ret = 1;
243 }
244
245 if (num_refs_out)
246 *num_refs_out = num_refs;
247
248 error:
249 ks_free(&line);
250
251 if (hclose(fp) != 0) {
252 fprintf(stderr, "[amplicon] warning: failed to close %s", infile);
253 }
254
255 return ret;
256 }
257
258
259 void destroy_bed_hash(khash_t(bed_list_hash) *hash) {
260 khiter_t itr;
261
262 for (itr = kh_begin(hash); itr != kh_end(hash); ++itr) {
263 if (kh_exist(hash, itr)) {
264 bed_entry_list_t list = kh_val(hash, itr);
265 for (int i = 0; i < list.length; i++) {
266 free(list.bp[i].name);
267 free(list.bp[i].score);
268 }
269 free(list.bp);
270 free((char *)kh_key(hash, itr));
271 kh_key(hash, itr) = NULL;
272 }
273 }
274
275 kh_destroy(bed_list_hash, hash);
276 }
277
278
279 static int matching_clip_site(bed_entry_list_t *sites, hts_pos_t pos,
280 int is_rev, int use_strand, int64_t longest,
281 cl_param_t *param) {
282 int i, size, used_i;
283 int tol = param->tol;
284 int l = 0, mid = sites->length / 2, r = sites->length;
285 int pos_tol = is_rev ? (pos > tol ? pos - tol : 0) : pos;
286
287 while (r - l > 1) {
288 if (sites->bp[mid].right <= pos_tol) {
289 l = mid;
290 } else {
291 r = mid;
292 }
293 mid = (l + r) / 2;
294 }
295
296 size = 0;
297 used_i = -1;
298
299 for (i = l; i < sites->length; i++) {
300 hts_pos_t mod_left, mod_right;
301
302 if (use_strand && is_rev != sites->bp[i].rev)
303 continue;
304
305 if (is_rev) {
306 mod_left = sites->bp[i].left;
307 mod_right = sites->bp[i].right + tol;
308 } else {
309 if (sites->bp[i].left > tol) {
310 mod_left = sites->bp[i].left - tol;
311 } else {
312 mod_left = 0;
313 }
314 mod_right = sites->bp[i].right;
315 }
316
317 if (pos + longest + tol < mod_right)
318 break;
319
320 if (pos >= mod_left && pos <= mod_right) {
321 if (is_rev) {
322 if (size < pos - sites->bp[i].left) {
323 size = pos - sites->bp[i].left;
324 used_i = i;
325 }
326 } else {
327 if (size < sites->bp[i].right - pos) {
328 size = sites->bp[i].right - pos;
329 used_i = i;
330 }
331 }
332 }
333 }
334 if (used_i >= 0) {
335 sites->bp[used_i].num_reads++;
336 }
337 return size;
338 }
339
340
341 static int bam_trim_left(bam1_t *rec, bam1_t *rec_out, uint32_t bases,
342 clipping_type clipping) {
343 uint32_t *orig_cigar = bam_get_cigar(rec);
344 uint8_t *orig_seq = bam_get_seq(rec);
345 uint8_t *orig_qual = bam_get_qual(rec);
346 uint8_t *orig_aux = bam_get_aux(rec);
347 uint32_t *new_cigar;
348 uint8_t *new_qual;
349 size_t orig_l_aux = bam_get_l_aux(rec);
350 uint32_t i, j;
351 uint32_t ref_remove = bases, qry_removed = 0, hardclip = 0;
352 hts_pos_t new_pos = rec->core.pos;
353 uint32_t cig_type, cig_op;
354
355 if (rec->l_data + 8 > rec_out->m_data) {
356 uint8_t *new_data = realloc(rec_out->data, rec->l_data + 8);
357 if (!new_data) {
358 fprintf(stderr, "[ampliconclip] error: could not allocate memoy for new bam record\n");
359 return 1;
360 }
361 rec_out->data = new_data;
362 rec_out->m_data = rec->l_data + 8;
363 }
364
365 // Copy core data & name
366 memcpy(&rec_out->core, &rec->core, sizeof(rec->core));
367 memcpy(rec_out->data, rec->data, rec->core.l_qname);
368
369 // Modify CIGAR
370 new_cigar = bam_get_cigar(rec_out);
371
372 for (i = 0; i < rec->core.n_cigar; i++) {
373 cig_op = bam_cigar_op(orig_cigar[i]);
374 cig_type = bam_cigar_type(cig_op);
375
376 if (cig_op == BAM_CHARD_CLIP) {
377 hardclip += bam_cigar_oplen(orig_cigar[i]);
378 } else {
379 if (cig_type & 2) {
380 if (bam_cigar_oplen(orig_cigar[i]) <= ref_remove) {
381 ref_remove -= bam_cigar_oplen(orig_cigar[i]);
382 } else {
383 break;
384 }
385 new_pos += bam_cigar_oplen(orig_cigar[i]);
386 }
387 if (cig_type & 1) {
388 qry_removed += bam_cigar_oplen(orig_cigar[i]);
389 }
390 }
391 }
392
393 if (i < rec->core.n_cigar) {
394 cig_type = bam_cigar_type(bam_cigar_op(orig_cigar[i]));
395
396 // account for the last operation
397 if (cig_type & 2) {
398 new_pos += ref_remove;
399 }
400 if (cig_type & 1) {
401 qry_removed += ref_remove;
402 }
403 } else {
404 if (clipping == hard_clip) {
405
406 rec_out->core.l_qseq = 0;
407 rec_out->core.n_cigar = 0;
408
409 if (orig_l_aux)
410 memcpy(bam_get_aux(rec_out), orig_aux, orig_l_aux);
411
412 rec_out->l_data = bam_get_aux(rec_out) - rec_out->data + orig_l_aux;
413
414 return 0;
415 }
416
417 qry_removed = rec->core.l_qseq;
418 }
419
420 j = 0;
421 if (clipping == hard_clip && hardclip + qry_removed > 0) {
422 new_cigar[j++] = bam_cigar_gen(hardclip + qry_removed, BAM_CHARD_CLIP);
423 }
424 if (clipping == soft_clip) {
425 if (hardclip > 0) {
426 new_cigar[j++] = bam_cigar_gen(hardclip, BAM_CHARD_CLIP);
427 }
428 if (qry_removed > 0) {
429 new_cigar[j++] = bam_cigar_gen(qry_removed, BAM_CSOFT_CLIP);
430 }
431 }
432
433 if (i < rec->core.n_cigar
434 && bam_cigar_oplen(orig_cigar[i]) > ref_remove) {
435 new_cigar[j++] = bam_cigar_gen(bam_cigar_oplen(orig_cigar[i]) - ref_remove, bam_cigar_op(orig_cigar[i]));
436
437 // fill in the rest of the cigar
438 i++;
439
440 for (; i < rec->core.n_cigar; i++) {
441 new_cigar[j++] = orig_cigar[i];
442 }
443 }
444
445 rec_out->core.n_cigar = j;
446
447 if (clipping == soft_clip) {
448 qry_removed = 0; // Copy all the sequence and confidence values
449 }
450
451 new_qual = bam_get_seq(rec_out) + (rec->core.l_qseq - qry_removed + 1) / 2;
452 // Copy remaining SEQ
453 if ((qry_removed & 1) == 0) {
454 memcpy(bam_get_seq(rec_out), orig_seq + (qry_removed / 2),
455 (rec->core.l_qseq - qry_removed + 1) / 2); // +1 to account for odd numbers
456 } else {
457 uint8_t *in = orig_seq + qry_removed / 2;
458 uint8_t *out = bam_get_seq(rec_out);
459 uint32_t i;
460 for (i = qry_removed; i < rec->core.l_qseq - 1; i += 2) {
461 *out++ = ((in[0] & 0x0f) << 4) | ((in[1] & 0xf0) >> 4);
462 in++;
463 }
464 if (i < rec->core.l_qseq) {
465 *out++ = (in[0] & 0x0f) << 4;
466 }
467 assert(out == new_qual);
468 }
469
470 // Copy remaining QUAL
471 memmove(new_qual, orig_qual + qry_removed, rec->core.l_qseq - qry_removed);
472
473 // Set new l_qseq
474 rec_out->core.l_qseq -= qry_removed;
475
476 // Move AUX
477 if (orig_l_aux)
478 memcpy(bam_get_aux(rec_out), orig_aux, orig_l_aux);
479
480 // Set new l_data
481 rec_out->l_data = bam_get_aux(rec_out) - rec_out->data + orig_l_aux;
482
483 // put in new pos
484 rec_out->core.pos = new_pos;
485
486 return 0;
487 }
488
489
490 static int bam_trim_right(bam1_t *rec, bam1_t *rec_out, uint32_t bases,
491 clipping_type clipping) {
492 uint32_t *orig_cigar = bam_get_cigar(rec);
493 uint8_t *orig_seq = bam_get_seq(rec);
494 uint8_t *orig_qual = bam_get_qual(rec);
495 uint8_t *orig_aux = bam_get_aux(rec);
496 uint32_t *new_cigar;
497 uint32_t new_n_cigar = 0;
498 uint8_t *new_qual;
499 size_t orig_l_aux = bam_get_l_aux(rec);
500 int32_t i;
501 int32_t j;
502 uint32_t ref_remove = bases, qry_removed = 0, hardclip = 0;
503 uint32_t cig_type, cig_op;
504
505 if (rec->l_data + 8 > rec_out->m_data) {
506 uint8_t *new_data = realloc(rec_out->data, rec->l_data + 8);
507 if (!new_data) {
508 fprintf(stderr, "[ampliconclip] error: could not allocate memoy for new bam record\n");
509 return 1;
510 }
511 rec_out->data = new_data;
512 rec_out->m_data = rec->l_data + 8;
513 }
514
515 // Copy core data & name
516 memcpy(&rec_out->core, &rec->core, sizeof(rec->core));
517 memcpy(rec_out->data, rec->data, rec->core.l_qname);
518
519 // Modify CIGAR here
520 new_cigar = bam_get_cigar(rec_out);
521
522 for (i = rec->core.n_cigar - 1; i >= 0; --i) {
523 cig_op = bam_cigar_op(orig_cigar[i]);
524 cig_type = bam_cigar_type(cig_op);
525
526 if (cig_op == BAM_CHARD_CLIP) {
527 hardclip += bam_cigar_oplen(orig_cigar[i]);
528 } else {
529 if (cig_type & 2) {
530 if (bam_cigar_oplen(orig_cigar[i]) <= ref_remove) {
531 ref_remove -= bam_cigar_oplen(orig_cigar[i]);
532 } else {
533 break;
534 }
535 }
536 if (cig_type & 1) {
537 qry_removed += bam_cigar_oplen(orig_cigar[i]);
538 }
539 }
540 }
541
542 if (i >= 0) {
543 cig_type = bam_cigar_type(bam_cigar_op(orig_cigar[i]));
544 if (cig_type & 1) {
545 qry_removed += ref_remove;
546 }
547 j = i;
548 if (qry_removed > 0) j++;
549 if (hardclip > 0 && (clipping == soft_clip || qry_removed == 0)) j++;
550 } else {
551 if (clipping == hard_clip) {
552
553 rec_out->core.l_qseq = 0;
554 rec_out->core.n_cigar = 0;
555
556 if (orig_l_aux)
557 memcpy(bam_get_aux(rec_out), orig_aux, orig_l_aux);
558
559 rec_out->l_data = bam_get_aux(rec_out) - rec_out->data + orig_l_aux;
560
561 return 0;
562 }
563
564 qry_removed = rec->core.l_qseq;
565 j = 0;
566 if (hardclip > 0 && clipping == soft_clip) j++;
567 }
568
569 if (clipping == hard_clip && hardclip + qry_removed > 0) {
570 new_cigar[j] = bam_cigar_gen(hardclip + qry_removed, BAM_CHARD_CLIP);
571 new_n_cigar++;
572 }
573 if (clipping == soft_clip) {
574 if (hardclip > 0) {
575 new_cigar[j] = bam_cigar_gen(hardclip, BAM_CHARD_CLIP);
576 new_n_cigar++;
577 if (qry_removed > 0) --j;
578 }
579 if (qry_removed > 0) {
580 new_cigar[j] = bam_cigar_gen(qry_removed, BAM_CSOFT_CLIP);
581 new_n_cigar++;
582 }
583 }
584
585 if (j > 0) {
586 new_cigar[--j] = bam_cigar_gen(bam_cigar_oplen(orig_cigar[i]) - ref_remove, bam_cigar_op(orig_cigar[i]));
587 new_n_cigar++;
588 }
589
590 // fill in the rest of the cigar
591 while (j > 0) {
592 new_cigar[--j] = orig_cigar[--i];
593 new_n_cigar++;
594 }
595
596 rec_out->core.n_cigar = new_n_cigar;
597
598 if (clipping == soft_clip)
599 qry_removed = 0; // Copy all the sequence and confidence values
600
601 new_qual = bam_get_seq(rec_out) + (rec->core.l_qseq - qry_removed + 1) / 2;
602 // Copy remaining SEQ
603 memcpy(bam_get_seq(rec_out), orig_seq, (rec->core.l_qseq - qry_removed + 1) / 2);
604
605 // Copy remaining QUAL
606 memcpy(new_qual, orig_qual, rec->core.l_qseq - qry_removed);
607
608 // Set new l_qseq
609 rec_out->core.l_qseq -= qry_removed;
610
611 // Copy AUX
612 if (orig_l_aux)
613 memcpy(bam_get_aux(rec_out), orig_aux, orig_l_aux);
614
615 // Set new l_data
616 rec_out->l_data = bam_get_aux(rec_out) - rec_out->data + orig_l_aux;
617
618 return 0;
619 }
620
621
622 static hts_pos_t active_query_len(bam1_t *b) {
623 uint32_t *cigar = bam_get_cigar(b);
624 uint32_t cig_type, cig_op;
625 hts_pos_t len = 0;
626 int i;
627
628 for (i = 0; i < b->core.n_cigar; i++) {
629 cig_op = bam_cigar_op(cigar[i]);
630 cig_type = bam_cigar_type(cig_op);
631
632 if ((cig_type & 1) && (cig_op != BAM_CSOFT_CLIP)) {
633 len += bam_cigar_oplen(cigar[i]);
634 }
635 }
636
637 return len;
638 }
639
640
641 static inline void swap_bams(bam1_t **a, bam1_t **b) {
642 bam1_t *tmp = *a;
643 *a = *b;
644 *b = tmp;
645 }
646
647
648 // Format OA:Z:(RNAME,POS,strand,CIGAR,MAPQ,NM;
649 static inline int tag_original_data(bam1_t *orig, kstring_t *oa_tag) {
650 char strand;
651 uint8_t *nm_tag, *old_oa_tag;
652 uint32_t *cigar;
653 int64_t nm = 0;
654 int i, res = 0;
655
656 ks_clear(oa_tag);
657
658 // if there is an existing OA tag the new one gets appended to it
659 if ((old_oa_tag = bam_aux_get(orig, "OA"))) {
660 res |= ksprintf(oa_tag, "%s", bam_aux2Z(old_oa_tag)) < 0;
661 }
662
663 if (orig->core.flag & BAM_FREVERSE)
664 strand = '-';
665 else
666 strand = '+';
667
668 if ((nm_tag = bam_aux_get(orig, "NM"))) {
669 nm = bam_aux2i(nm_tag);
670 }
671
672 res |= ksprintf(oa_tag, "%s,%"PRIhts_pos",%c,", bam_get_qname(orig), orig->core.pos + 1, strand) < 0;
673
674 for (i = 0, cigar = bam_get_cigar(orig); i < orig->core.n_cigar && res == 0; ++i) {
675 res |= kputw(bam_cigar_oplen(cigar[i]), oa_tag) < 0;
676 res |= kputc(bam_cigar_opchr(cigar[i]), oa_tag) < 0;
677 }
678
679 if (nm_tag) {
680 res |= ksprintf(oa_tag, ",%d,%"PRId64";", orig->core.qual, nm) < 0;
681 } else {
682 res |= ksprintf(oa_tag, "%d,;", orig->core.qual) < 0;
683 }
684
685 return res;
686 }
687
688
689 static int bam_clip(samFile *in, samFile *out, samFile *reject, char *bedfile,
690 clipping_type clipping, cl_param_t *param) {
691 int ret = 1, r, file_open = 0;
692
693 bam_hdr_t *header = NULL;
694 bam1_t *b = NULL, *b_tmp = NULL;
695 long f_count = 0, r_count = 0, n_count = 0, l_count = 0, l_exclude = 0, b_count = 0;
696 long filtered = 0, written = 0, failed = 0;
697 kstring_t str = KS_INITIALIZE;
698 kstring_t oat = KS_INITIALIZE;
699 kstring_t seq = KS_INITIALIZE;
700 bed_entry_list_t *sites;
701 FILE *stats_fp = stderr;
702 FILE *bed_count_summary_fp = stderr;
703 khash_t(bed_list_hash) *bed_hash = kh_init(bed_list_hash);
704 char **bed_ref_list = NULL;
705 size_t num_bed_refs = 0;
706
707 if (load_bed_file_multi_ref(bedfile, param->use_strand, 1, bed_hash,
708 &bed_ref_list, &num_bed_refs)) {
709 fprintf(stderr, "[ampliconclip] error: unable to load bed file.\n");
710 goto fail;
711 }
712
713 if ((header = sam_hdr_read(in)) == NULL) {
714 fprintf(stderr, "[ampliconclip] error: could not read header\n");
715 goto fail;
716 }
717
718 // changing pos can ruin coordinate sort order
719 if (sam_hdr_find_tag_hd(header, "SO", &str) == 0 && str.s && strcmp(str.s, "coordinate") == 0) {
720 const char *new_order = "unknown";
721
722 if (sam_hdr_update_hd(header, "SO", new_order) == -1) {
723 fprintf(stderr, "[ampliconclip] error: unable to change sort order to 'SO:%s'\n", new_order);
724 goto fail;
725 }
726 }
727
728 ks_free(&str);
729
730 if (param->add_pg && sam_hdr_add_pg(header, "samtools", "VN", samtools_version(),
731 param->arg_list ? "CL" : NULL,
732 param->arg_list ? param->arg_list : NULL,
733 NULL) != 0) {
734 fprintf(stderr, "[ampliconclip] warning: unable to add @PG line to header.\n");
735 }
736 if (sam_hdr_write(out, header) < 0) {
737 fprintf(stderr, "[ampliconclip] error: could not write header.\n");
738 goto fail;
739 }
740
741 if (reject) {
742 if (sam_hdr_write(reject, header) < 0) {
743 fprintf(stderr, "[ampliconclip] error: could not write header to rejects file.\n");
744 goto fail;
745 }
746 }
747
748 b = bam_init1();
749 b_tmp = bam_init1();
750 if (!b || !b_tmp) {
751 fprintf(stderr, "[ampliconclip] error: out of memory when trying to create record.\n");
752 goto fail;
753 }
754
755 int32_t last_tid = -1;
756 int ref_found = 0;
757
758 while ((r = sam_read1(in, header, b)) >= 0) {
759 hts_pos_t pos;
760 int is_rev;
761 int p_size;
762 int been_clipped = 0, filter = 0;
763 int exclude = (BAM_FUNMAP | BAM_FQCFAIL);
764 khiter_t itr;
765
766 l_count++;
767
768 if (b->core.tid != last_tid) {
769 const char *ref_name;
770
771 ref_found = 0;
772 last_tid = b->core.tid;
773
774 if ((ref_name = sam_hdr_tid2name(header, b->core.tid)) != NULL) {
775 itr = kh_get(bed_list_hash, bed_hash, ref_name);
776
777 if (itr != kh_end(bed_hash)) {
778 sites = &kh_val(bed_hash, itr);
779 ref_found = 1;
780 }
781 }
782 }
783
784 if (!(b->core.flag & exclude) && ref_found) {
785 if (param->oa_tag)
786 if (tag_original_data(b, &oat))
787 goto fail;
788
789 if (!param->both) {
790 if (bam_is_rev(b)) {
791 pos = bam_endpos(b);
792 is_rev = 1;
793 } else {
794 pos = b->core.pos;
795 is_rev = 0;
796 }
797
798 if ((p_size = matching_clip_site(sites, pos, is_rev, param->use_strand, sites->longest, param))) {
799 if (is_rev) {
800 if (bam_trim_right(b, b_tmp, p_size, clipping) != 0)
801 goto fail;
802
803 swap_bams(&b, &b_tmp);
804 r_count++;
805 } else {
806 if (bam_trim_left(b, b_tmp, p_size, clipping) != 0)
807 goto fail;
808
809 swap_bams(&b, &b_tmp);
810 f_count++;
811 }
812
813 if (param->oa_tag) {
814 if (bam_aux_update_str(b, "OA", oat.l + 1, (const char *)oat.s))
815 goto fail;
816 }
817
818 if (param->del_tag) {
819 uint8_t *tag;
820
821 if ((tag = bam_aux_get(b, "NM")))
822 bam_aux_del(b, tag);
823
824 if ((tag = bam_aux_get(b, "MD")))
825 bam_aux_del(b, tag);
826 }
827
828 been_clipped = 1;
829 } else {
830 if (param->mark_fail) {
831 b->core.flag |= BAM_FQCFAIL;
832 }
833
834 n_count++;
835 }
836 } else {
837 int left = 0, right = 0;
838
839 // left first
840 pos = b->core.pos;
841 is_rev = 0;
842
843 if ((p_size = matching_clip_site(sites, pos, is_rev, param->use_strand, sites->longest, param))) {
844 if (bam_trim_left(b, b_tmp, p_size, clipping) != 0)
845 goto fail;
846
847 swap_bams(&b, &b_tmp);
848 f_count++;
849 left = 1;
850 been_clipped = 1;
851 }
852
853 // the right
854 pos = bam_endpos(b);
855 is_rev = 1;
856
857 if ((p_size = matching_clip_site(sites, pos, is_rev, param->use_strand, sites->longest, param))) {
858 if (bam_trim_right(b, b_tmp, p_size, clipping) != 0)
859 goto fail;
860
861 swap_bams(&b, &b_tmp);
862 r_count++;
863 right = 1;
864 been_clipped = 1;
865 }
866
867 if (left || right) {
868 uint8_t *tag;
869
870 if (param->oa_tag) {
871 if (bam_aux_update_str(b, "OA", oat.l + 1, (const char *)oat.s))
872 goto fail;
873 }
874
875 if (param->del_tag) {
876 if ((tag = bam_aux_get(b, "NM")))
877 bam_aux_del(b, tag);
878
879 if ((tag = bam_aux_get(b, "MD")))
880 bam_aux_del(b, tag);
881 }
882 }
883
884 if (left && right) {
885 b_count++;
886 } else if (!left && !right) {
887 if (param->mark_fail) {
888 b->core.flag |= BAM_FQCFAIL;
889 }
890
891 n_count++;
892 }
893 }
894
895 if (param->fail_len >= 0 || param->filter_len >= 0 || param->unmap_len >= 0) {
896 hts_pos_t aql = active_query_len(b);
897
898 if (param->fail_len >= 0 && aql <= param->fail_len) {
899 b->core.flag |= BAM_FQCFAIL;
900 }
901
902 if (param->filter_len >= 0 && aql <= param->filter_len) {
903 filter = 1;
904 }
905
906 if (param->unmap_len >= 0 && aql <= param->unmap_len) {
907
908 if (ks_resize(&seq, b->core.l_qseq) < 0) {
909 fprintf(stderr, "[ampliconclip] error: allocate memory for sequence %s\n", bam_get_seq(b));
910 goto fail;
911 }
912
913 ks_clear(&seq);
914 char *sb = ks_str(&seq);
915 uint8_t *sequence = bam_get_seq(b);
916 int i;
917
918 for (i = 0; i < b->core.l_qseq ; ++i) {
919 *sb++ = seq_nt16_str[bam_seqi(sequence, i)];
920 }
921
922 if (bam_set1(b_tmp, b->core.l_qname - b->core.l_extranul - 1, bam_get_qname(b),
923 (b->core.flag | BAM_FUNMAP), b->core.tid, b->core.pos, 0,
924 0, NULL, b->core.mtid, b->core.mpos, b->core.isize,
925 b->core.l_qseq, seq.s, (const char *)bam_get_qual(b),
926 bam_get_l_aux(b)) < 0) {
927 fprintf(stderr, "[ampliconclip] error: could not unmap read %s\n", bam_get_seq(b));
928 goto fail;
929 }
930
931 memcpy(bam_get_aux(b_tmp), bam_get_aux(b), bam_get_l_aux(b));
932 b_tmp->l_data += bam_get_l_aux(b);
933 swap_bams(&b, &b_tmp);
934 }
935 }
936
937 if (b->core.flag & BAM_FQCFAIL) {
938 failed++;
939 }
940
941 if (param->write_clipped && !been_clipped) {
942 filter = 1;
943 }
944
945 } else {
946 l_exclude++;
947
948 if (param->unmapped) {
949 filter = 1;
950 }
951 }
952
953 if (!filter) {
954 if (sam_write1(out, header, b) < 0) {
955 fprintf(stderr, "[ampliconclip] error: could not write line %ld.\n", l_count);
956 goto fail;
957 }
958
959 written++;
960 } else {
961 if (reject) {
962 if (sam_write1(reject, header, b) < 0) {
963 fprintf(stderr, "[ampliconclip] error: could not write to reject file %s\n",
964 param->rejects_file);
965 goto fail;
966 }
967 }
968
969 filtered++;
970 }
971 }
972
973 if (r < -1) {
974 fprintf(stderr, "[ampliconclip] error: failed to read input.\n");
975 goto fail;
976 }
977
978 if (param->stats_file) {
979 if ((stats_fp = fopen(param->stats_file, "w")) == NULL) {
980 fprintf(stderr, "[ampliconclip] warning: cannot write stats to %s.\n", param->stats_file);
981 } else {
982 file_open = 1;
983 }
984 }
985
986 fprintf(stats_fp, "COMMAND: %s\n"
987 "TOTAL READS: %ld\n"
988 "TOTAL CLIPPED: %ld\n"
989 "FORWARD CLIPPED: %ld\n"
990 "REVERSE CLIPPED: %ld\n"
991 "BOTH CLIPPED: %ld\n"
992 "NOT CLIPPED: %ld\n"
993 "EXCLUDED: %ld\n"
994 "FILTERED: %ld\n"
995 "FAILED: %ld\n"
996 "WRITTEN: %ld\n", param->arg_list, l_count, f_count + r_count,
997 f_count, r_count, b_count, n_count, l_exclude,
998 filtered, failed, written);
999
1000 if (file_open) {
1001 fclose(stats_fp);
1002 file_open = 0;
1003 }
1004
1005 if (param->primer_counts_file) {
1006 if ((bed_count_summary_fp = fopen(param->primer_counts_file, "w")) == NULL) {
1007 fprintf(stderr, "[ampliconclip] warning: cannot write count summary to %s.\n", param->primer_counts_file);
1008 } else {
1009 file_open = 1;
1010 }
1011
1012 //print out the number of reads for each bed entry, bedgraph format
1013 fprintf(bed_count_summary_fp, "#CHR\tLEFT\tRIGHT\tNAME\tSCORE\tSTRAND\tNUM_CLIPPED\n");
1014 size_t refidx;
1015 for (refidx = 0; refidx < num_bed_refs; refidx++) {
1016 khiter_t itr = kh_get(bed_list_hash, bed_hash, bed_ref_list[refidx]);
1017 if (itr >= kh_end(bed_hash)) {
1018 fprintf(stderr, "[ampliconclip] error: %s has gone missing from the hash table\n", bed_ref_list[refidx]);
1019 goto fail;
1020 }
1021 sites = &kh_val(bed_hash, itr);
1022 int i;
1023 for (i = 0; i < sites->length; i++) {
1024 char* strand_out = param->use_strand ? (sites->bp[i].rev ? "-" : "+") : ".";
1025 fprintf(bed_count_summary_fp, "%s\t%"PRId64"\t%"PRId64"\t%s\t%s\t%s\t%"PRId64"\n",
1026 kh_key(bed_hash, itr), sites->bp[i].left, sites->bp[i].right, sites->bp[i].name,
1027 sites->bp[i].score, strand_out, sites->bp[i].num_reads);
1028 }
1029 }
1030 if (file_open) {
1031 fclose(bed_count_summary_fp);
1032 }
1033 }
1034
1035 ret = 0;
1036
1037 fail:
1038 free(bed_ref_list);
1039 destroy_bed_hash(bed_hash);
1040 ks_free(&oat);
1041 ks_free(&seq);
1042 sam_hdr_destroy(header);
1043 bam_destroy1(b);
1044 bam_destroy1(b_tmp);
1045 return ret;
1046 }
1047
1048
1049 static void usage(void) {
1050 fprintf(stderr, "Usage: samtools ampliconclip -b BED file <input.bam> -o <output.bam>\n\n");
1051 fprintf(stderr, "Option: \n");
1052 fprintf(stderr, " -b FILE BED file of regions (eg amplicon primers) to be removed.\n");
1053 fprintf(stderr, " -o FILE output file name (default: stdout).\n");
1054 fprintf(stderr, " -f FILE write stats to file name (default: stderr)\n");
1055 fprintf(stderr, " -u Output uncompressed data\n");
1056 fprintf(stderr, " --soft-clip soft clip amplicon primers from reads (default)\n");
1057 fprintf(stderr, " --hard-clip hard clip amplicon primers from reads.\n");
1058 fprintf(stderr, " --both-ends clip on both 5' and 3' ends.\n");
1059 fprintf(stderr, " --strand use strand data from BED file to match read direction.\n");
1060 fprintf(stderr, " --clipped only output clipped reads.\n");
1061 fprintf(stderr, " --fail mark unclipped, mapped reads as QCFAIL.\n");
1062 fprintf(stderr, " --filter-len INT do not output reads INT size or shorter.\n");
1063 fprintf(stderr, " --fail-len INT mark as QCFAIL reads INT size or shorter.\n");
1064 fprintf(stderr, " --unmap-len INT unmap reads INT size or shorter, default 0.\n");
1065 fprintf(stderr, " --no-excluded do not write excluded reads (unmapped or QCFAIL).\n");
1066 fprintf(stderr, " --rejects-file FILE file to write filtered reads.\n");
1067 fprintf(stderr, " --primer-counts FILE file to write read counts per bed entry (bedgraph format).\n");
1068 fprintf(stderr, " --original for clipped entries add an OA tag with original data.\n");
1069 fprintf(stderr, " --keep-tag for clipped entries keep the old NM and MD tags.\n");
1070 fprintf(stderr, " --tolerance match region within this number of bases, default 5.\n");
1071 fprintf(stderr, " --no-PG do not add an @PG line.\n");
1072 sam_global_opt_help(stderr, "-.O..@-.");
1073 fprintf(stderr, "\nAbout: Soft clips read alignments where they match BED file defined regions.\n"
1074 "Default clipping is only on the 5' end.\n\n");
1075 }
1076
1077
1078 int amplicon_clip_main(int argc, char **argv) {
1079 int c, ret;
1080 char wmode[4] = {'w', 'b', 0, 0};
1081 char *bedfile = NULL, *fnout = "-";
1082 sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
1083 htsThreadPool p = {NULL, 0};
1084 samFile *in = NULL, *out = NULL, *reject = NULL;
1085 clipping_type clipping = soft_clip;
1086 cl_param_t param = {1, 0, 0, 0, 0, -1, -1, 0, 0, 1, 5, 0, NULL, NULL, NULL};
1087
1088 static const struct option lopts[] = {
1089 SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 0, '@'),
1090 {"no-PG", no_argument, NULL, 1002},
1091 {"soft-clip", no_argument, NULL, 1003},
1092 {"hard-clip", no_argument, NULL, 1004},
1093 {"strand", no_argument, NULL, 1005},
1094 {"clipped", no_argument, NULL, 1006},
1095 {"fail", no_argument, NULL, 1007},
1096 {"both-ends", no_argument, NULL, 1008},
1097 {"filter-len", required_argument, NULL, 1009},
1098 {"fail-len", required_argument, NULL, 1010},
1099 {"no-excluded", no_argument, NULL, 1011},
1100 {"rejects-file", required_argument, NULL, 1012},
1101 {"primer-counts", required_argument, NULL, 1013},
1102 {"original", no_argument, NULL, 1014},
1103 {"keep-tag", no_argument, NULL, 1015},
1104 {"tolerance", required_argument, NULL, 1016},
1105 {"unmap-len", required_argument, NULL, 1017},
1106 {NULL, 0, NULL, 0}
1107 };
1108
1109 while ((c = getopt_long(argc, argv, "b:@:o:O:f:u", lopts, NULL)) >= 0) {
1110 switch (c) {
1111 case 'b': bedfile = optarg; break;
1112 case 'o': fnout = optarg; break;
1113 case 'f': param.stats_file = optarg; break;
1114 case 'u': wmode[2] = '0'; break;
1115 case 1002: param.add_pg = 0; break;
1116 case 1003: clipping = soft_clip; break;
1117 case 1004: clipping = hard_clip; break;
1118 case 1005: param.use_strand = 1; break;
1119 case 1006: param.write_clipped = 1; break;
1120 case 1007: param.mark_fail = 1; break;
1121 case 1008: param.both = 1; break;
1122 case 1009: param.filter_len = atoi(optarg); break;
1123 case 1010: param.fail_len = atoi(optarg); break;
1124 case 1011: param.unmapped = 1; break;
1125 case 1012: param.rejects_file = optarg; break;
1126 case 1013: param.primer_counts_file = optarg; break;
1127 case 1014: param.oa_tag = 1; break;
1128 case 1015: param.del_tag = 0; break;
1129 case 1016: param.tol = atoi(optarg); break;
1130 case 1017: param.unmap_len = atoi(optarg); break;
1131 default: if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
1132 /* else fall-through */
1133 case '?': usage(); exit(1);
1134 }
1135 }
1136
1137 if (!bedfile) {
1138 usage();
1139 return 1;
1140 }
1141
1142 if (optind + 1 > argc) {
1143 usage();
1144 return 1;
1145 }
1146
1147 if (param.tol < 0) {
1148 fprintf(stderr, "[ampliconclip] warning: invalid tolerance of %d,"
1149 " resetting tolerance to default of 5.\n", param.tol);
1150 param.tol = 5;
1151 }
1152
1153 if ((in = sam_open_format(argv[optind], "rb", &ga.in)) == NULL) {
1154 print_error_errno("ampliconclip", "cannot open input file");
1155 return 1;
1156 }
1157
1158 sam_open_mode(wmode+1, fnout, NULL);
1159
1160 if ((out = sam_open_format(fnout, wmode, &ga.out)) == NULL) {
1161 print_error_errno("ampliconclip", "cannot open output file");
1162 return 1;
1163 }
1164
1165 if (param.rejects_file) {
1166 sam_open_mode(wmode+1, param.rejects_file, NULL);
1167
1168 if ((reject = sam_open_format(param.rejects_file, wmode, &ga.out)) == NULL) {
1169 print_error_errno("ampliconclip", "cannot open rejects file");
1170 return 1;
1171 }
1172 }
1173
1174 if (ga.nthreads > 0) {
1175 if (!(p.pool = hts_tpool_init(ga.nthreads))) {
1176 fprintf(stderr, "[ampliconclip] error: cannot create thread pool.\n");
1177 return 1;
1178 }
1179 hts_set_opt(in, HTS_OPT_THREAD_POOL, &p);
1180 hts_set_opt(out, HTS_OPT_THREAD_POOL, &p);
1181
1182 if (reject) {
1183 hts_set_opt(reject, HTS_OPT_THREAD_POOL, &p);
1184 }
1185 }
1186
1187 param.arg_list = stringify_argv(argc + 1, argv - 1);
1188
1189 ret = bam_clip(in, out, reject, bedfile, clipping, &param);
1190
1191 // cleanup
1192 sam_close(in);
1193
1194 if (sam_close(out) < 0) {
1195 fprintf(stderr, "[ampliconclip] error: error while closing output file %s.\n", argv[optind+1]);
1196 ret = 1;
1197 }
1198
1199 if (reject) {
1200 if (sam_close(reject) < 0) {
1201 fprintf(stderr, "[ampliconclip] error: error while closing reject file %s.\n", param.rejects_file);
1202 ret = 1;
1203 }
1204 }
1205
1206 if (p.pool) hts_tpool_destroy(p.pool);
1207
1208 sam_global_args_free(&ga);
1209 free(param.arg_list);
1210
1211 return ret;
1212 }
1213