Debian Codegraph @

samtools/bam_ampliconclip.c.pysam.c

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