Debian Codegraph @

samtools/sam_view.c

raw symbols SCIP
1 /* sam_view.c -- SAM<->BAM<->CRAM conversion.
2
3 Copyright (C) 2009-2024 Genome Research Ltd.
4 Portions copyright (C) 2009, 2011, 2012 Broad Institute.
5
6 Author: Heng Li <[email protected]>
7
8 Permission is hereby granted, free of charge, to any person obtaining a copy
9 of this software and associated documentation files (the "Software"), to deal
10 in the Software without restriction, including without limitation the rights
11 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 copies of the Software, and to permit persons to whom the Software is
13 furnished to do so, subject to the following conditions:
14
15 The above copyright notices and this permission notice shall be included in
16 all copies or substantial portions of the Software.
17
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 DEALINGS IN THE SOFTWARE. */
25
26 #include <config.h>
27
28 #include <stdlib.h>
29 #include <string.h>
30 #include <strings.h>
31 #include <stdio.h>
32 #include <unistd.h>
33 #include <math.h>
34 #include <inttypes.h>
35 #include <getopt.h>
36 #include "htslib/sam.h"
37 #include "htslib/faidx.h"
38 #include "htslib/khash.h"
39 #include "htslib/kstring.h"
40 #include "htslib/thread_pool.h"
41 #include "htslib/hts_expr.h"
42 #include "samtools.h"
43 #include "sam_opts.h"
44 #include "bam.h" // for bam_get_library and bam_remove_B
45 #include "bedidx.h"
46 #include "sam_utils.h"
47
48 KHASH_SET_INIT_STR(str)
49 typedef khash_t(str) *strhash_t;
50
51 // This structure contains the settings for a samview run
52 typedef struct samview_settings {
53 strhash_t rghash;
54 strhash_t rnhash;
55 strhash_t tvhash;
56 int min_mapQ;
57 int rghash_discard; // 0 keep, 1 discard
58 int rnhash_discard; // 0 keep, 1 discard
59
60 // Described here in the same terms as the usage statement.
61 // The code however always negates to "reject if" keep if:
62 int flag_on; // keep if (FLAG & N) == N (all on)
63 int flag_off; // keep if (FLAG & N) == 0 (all off)
64 int flag_anyon; // keep if (FLAG & N) != 0 (any on)
65 int flag_alloff; // reject if (FLAG & N) == N (any off)
66
67 int min_qlen;
68 int remove_B;
69 uint32_t subsam_seed;
70 double subsam_frac;
71 char* library;
72 void* bed;
73 size_t remove_aux_len;
74 char** remove_aux;
75 int multi_region;
76 char* tag;
77 hts_filter_t *filter;
78 int remove_flag;
79 int add_flag;
80 int unmap;
81 auxhash_t remove_tag;
82 auxhash_t keep_tag;
83
84 hts_idx_t *hts_idx;
85 sam_hdr_t *header;
86 samFile *in, *out, *un_out;
87 int64_t count;
88 int is_count;
89 char *fn_in, *fn_idx_in, *fn_out, *fn_fai, *fn_un_out, *fn_out_idx, *fn_un_out_idx;
90 int fetch_pairs, nreglist;
91 hts_reglist_t *reglist;
92 int sanitize;
93 int count_rf; // CRAM_OPT_REQUIRED_FIELDS for view -c
94 } samview_settings_t;
95
96 // Copied from htslib/sam.c.
97 // TODO: we need a proper interface to find the length of an aux tag,
98 // or at the very make exportable versions of these in htslib.
99 static inline int aux_type2size(uint8_t type)
100 {
101 switch (type) {
102 case 'A': case 'c': case 'C':
103 return 1;
104 case 's': case 'S':
105 return 2;
106 case 'i': case 'I': case 'f':
107 return 4;
108 case 'd':
109 return 8;
110 case 'Z': case 'H': case 'B':
111 return type;
112 default:
113 return 0;
114 }
115 }
116
117 // Copied from htslib/sam.c.
118 static inline uint8_t *skip_aux(uint8_t *s, uint8_t *end)
119 {
120 int size;
121 uint32_t n;
122 if (s >= end) return end;
123 size = aux_type2size(*s); ++s; // skip type
124 switch (size) {
125 case 'Z':
126 case 'H':
127 while (s < end && *s) ++s;
128 return s < end ? s + 1 : end;
129 case 'B':
130 if (end - s < 5) return NULL;
131 size = aux_type2size(*s); ++s;
132 n = le_to_u32(s);
133 s += 4;
134 if (size == 0 || end - s < size * n) return NULL;
135 return s + size * n;
136 case 0:
137 return NULL;
138 default:
139 if (end - s < size) return NULL;
140 return s + size;
141 }
142 }
143
144 // Returns 0 to indicate read should be output 1 otherwise,
145 // and -1 on error.
146 static int process_aln(const sam_hdr_t *h, bam1_t *b, samview_settings_t* settings)
147 {
148 if (settings->filter) {
149 int r = sam_passes_filter(h, b, settings->filter);
150 if (r < 0) // err
151 return -1;
152 if (r == 0) // filter-out
153 return 1;
154 }
155
156 if (settings->remove_B) bam_remove_B(b);
157 if (settings->min_qlen > 0) {
158 int k, qlen = 0;
159 uint32_t *cigar = bam_get_cigar(b);
160 for (k = 0; k < b->core.n_cigar; ++k)
161 if ((bam_cigar_type(bam_cigar_op(cigar[k]))&1) || bam_cigar_op(cigar[k]) == BAM_CHARD_CLIP)
162 qlen += bam_cigar_oplen(cigar[k]);
163 if (qlen < settings->min_qlen) return 1;
164 }
165 if (b->core.qual < settings->min_mapQ || ((b->core.flag & settings->flag_on) != settings->flag_on) || (b->core.flag & settings->flag_off))
166 return 1;
167 if (settings->flag_alloff && ((b->core.flag & settings->flag_alloff) == settings->flag_alloff))
168 return 1;
169 if (settings->flag_anyon && ((b->core.flag & settings->flag_anyon) == 0))
170 return 1;
171 if (!settings->multi_region && settings->bed && (b->core.tid < 0 || !bed_overlap(settings->bed, sam_hdr_tid2name(h, b->core.tid), b->core.pos, bam_endpos(b))))
172 return 1;
173 if (settings->subsam_frac > 0.) {
174 uint32_t k = __ac_Wang_hash(__ac_X31_hash_string(bam_get_qname(b)) ^ settings->subsam_seed);
175 if ((double)(k&0xffffff) / 0x1000000 >= settings->subsam_frac) return 1;
176 }
177 if (settings->rghash) {
178 uint8_t *s = bam_aux_get(b, "RG");
179 if (s) {
180 khint_t k = kh_get(str, settings->rghash, (char*)(s + 1));
181 if ((k == kh_end(settings->rghash)) != settings->rghash_discard)
182 return 1;
183 }
184 }
185 if (settings->tag) {
186 uint8_t *s = bam_aux_get(b, settings->tag);
187 if (s) {
188 if (settings->tvhash) {
189 char t[32], *val;
190 if (*s == 'i' || *s == 'I' || *s == 's' || *s == 'S' || *s == 'c' || *s == 'C') {
191 int ret = snprintf(t, 32, "%"PRId64, bam_aux2i(s));
192 if (ret > 0) val = t;
193 else return 1;
194 } else if (*s == 'A') {
195 t[0] = *(s+1);
196 t[1] = 0;
197 val = t;
198 } else {
199 val = (char *)(s+1);
200 }
201 khint_t k = kh_get(str, settings->tvhash, val);
202 if (k == kh_end(settings->tvhash)) return 1;
203 }
204 } else {
205 return 1;
206 }
207 }
208 if (settings->rnhash) {
209 const char* rn = bam_get_qname(b);
210 strhash_t h = settings->rnhash;
211 if (!rn && !settings->rnhash_discard)
212 return 1;
213 if ((kh_get(str, h, rn) == kh_end(h)) != settings->rnhash_discard)
214 return 1;
215 }
216 if (settings->library) {
217 const char *p = bam_get_library((sam_hdr_t*)h, b);
218 if (!p || strcmp(p, settings->library) != 0) return 1;
219 }
220 return 0;
221 }
222
223 static int adjust_tags(const sam_hdr_t *h, bam1_t *b,
224 samview_settings_t* settings) {
225 if (settings->keep_tag) {
226 uint8_t *s_from, *s_to, *end = b->data + b->l_data;
227 auxhash_t h = settings->keep_tag;
228
229 s_from = s_to = bam_get_aux(b);
230 while (s_from < end) {
231 int x = (int)s_from[0]<<8 | s_from[1];
232 uint8_t *s = skip_aux(s_from+2, end);
233 if (s == NULL) {
234 print_error("view", "malformed aux data for record \"%s\"",
235 bam_get_qname(b));
236 return -1;
237 }
238
239 if (kh_get(aux_exists, h, x) != kh_end(h) ) {
240 if (s_to != s_from) memmove(s_to, s_from, s - s_from);
241 s_to += s - s_from;
242 }
243 s_from = s;
244 }
245 b->l_data = s_to - b->data;
246
247 } else if (settings->remove_tag) {
248 uint8_t *s_from, *s_to, *end = b->data + b->l_data;
249 auxhash_t h = settings->remove_tag;
250
251 s_from = s_to = bam_get_aux(b);
252 while (s_from < end) {
253 int x = (int)s_from[0]<<8 | s_from[1];
254 uint8_t *s = skip_aux(s_from+2, end);
255 if (s == NULL) {
256 print_error("view", "malformed aux data for record \"%s\"",
257 bam_get_qname(b));
258 return -1;
259 }
260
261 if (kh_get(aux_exists, h, x) == kh_end(h) ) {
262 if (s_to != s_from) memmove(s_to, s_from, s - s_from);
263 s_to += s - s_from;
264 }
265 s_from = s;
266 }
267 b->l_data = s_to - b->data;
268 }
269
270 return 0;
271 }
272
273 static int usage(FILE *fp, int exit_status, int is_long_help);
274
275 static int populate_lookup_from_file(const char *subcmd, strhash_t lookup, char *fn)
276 {
277 FILE *fp;
278 char buf[1024];
279 int ret = 0;
280 fp = fopen(fn, "r");
281 if (fp == NULL) {
282 print_error_errno(subcmd, "failed to open \"%s\" for reading", fn);
283 return -1;
284 }
285
286 while (ret != -1 && !feof(fp) && fscanf(fp, "%1023s", buf) > 0) {
287 char *d = strdup(buf);
288 if (d != NULL) {
289 kh_put(str, lookup, d, &ret);
290 if (ret == 0) free(d); /* Duplicate */
291 } else {
292 ret = -1;
293 }
294 }
295 if (ferror(fp)) ret = -1;
296 if (ret == -1) {
297 print_error_errno(subcmd, "failed to read \"%s\"", fn);
298 }
299 fclose(fp);
300 return (ret != -1) ? 0 : -1;
301 }
302
303 static int add_read_group_single(const char *subcmd, samview_settings_t *settings, char *name)
304 {
305 char *d = strdup(name);
306 int ret = 0;
307
308 if (d == NULL) goto err;
309
310 if (settings->rghash == NULL) {
311 settings->rghash = kh_init(str);
312 if (settings->rghash == NULL) goto err;
313 } else if (settings->rghash_discard == 1) {
314 print_error("view", "cannot mix include and exclude read-group files in the same command line");
315 free(d);
316 return -1;
317 }
318 settings->rghash_discard = 0;
319
320 kh_put(str, settings->rghash, d, &ret);
321 if (ret == -1) goto err;
322 if (ret == 0) free(d); /* Duplicate */
323 return 0;
324
325 err:
326 print_error(subcmd, "Couldn't add \"%s\" to read group list: memory exhausted?", name);
327 free(d);
328 return -1;
329 }
330
331 static int add_read_names_file(const char *subcmd, samview_settings_t *settings, char *fn)
332 {
333 if (settings->rnhash == NULL) {
334 settings->rnhash = kh_init(str);
335 if (settings->rnhash == NULL) {
336 perror(NULL);
337 return -1;
338 }
339 } else if ((settings->rnhash_discard == 0 && *fn == '^') ||
340 (settings->rnhash_discard == 1 && *fn != '^')) {
341 print_error("view", "cannot mix include and exclude read-name files in the same command line");
342 return -1;
343 }
344 settings->rnhash_discard = (*fn == '^');
345 return populate_lookup_from_file(subcmd, settings->rnhash,
346 fn + (*fn == '^'));
347 }
348
349 static int add_read_groups_file(const char *subcmd, samview_settings_t *settings, char *fn)
350 {
351 if (settings->rghash == NULL) {
352 settings->rghash = kh_init(str);
353 if (settings->rghash == NULL) {
354 perror(NULL);
355 return -1;
356 }
357 } else if ((settings->rghash_discard == 0 && *fn == '^') ||
358 (settings->rghash_discard == 1 && *fn != '^')) {
359 print_error("view", "cannot mix include and exclude read-group files in the same command line");
360 return -1;
361 }
362 settings->rghash_discard = (*fn == '^');
363 return populate_lookup_from_file(subcmd, settings->rghash,
364 fn + (*fn == '^'));
365 }
366
367 static int add_tag_value_single(const char *subcmd, samview_settings_t *settings, char *name)
368 {
369 char *d = strdup(name);
370 int ret = 0;
371
372 if (d == NULL) goto err;
373
374 if (settings->tvhash == NULL) {
375 settings->tvhash = kh_init(str);
376 if (settings->tvhash == NULL) goto err;
377 }
378
379 kh_put(str, settings->tvhash, d, &ret);
380 if (ret == -1) goto err;
381 if (ret == 0) free(d); /* Duplicate */
382 return 0;
383
384 err:
385 print_error(subcmd, "Couldn't add \"%s\" to tag values list: memory exhausted?", name);
386 free(d);
387 return -1;
388 }
389
390 static int add_tag_values_file(const char *subcmd, samview_settings_t *settings, char *fn)
391 {
392 if (settings->tvhash == NULL) {
393 settings->tvhash = kh_init(str);
394 if (settings->tvhash == NULL) {
395 perror(NULL);
396 return -1;
397 }
398 }
399 return populate_lookup_from_file(subcmd, settings->tvhash, fn);
400 }
401
402 static inline int check_sam_write1(samFile *fp, const sam_hdr_t *h, const bam1_t *b, const char *fname, int *retp)
403 {
404 int r = sam_write1(fp, h, b);
405 if (r >= 0) return r;
406
407 if (fname) print_error_errno("view", "writing to \"%s\" failed", fname);
408 else print_error_errno("view", "writing to standard output failed");
409
410 *retp = EXIT_FAILURE;
411 return r;
412 }
413
414 static inline void change_flag(bam1_t *b, samview_settings_t *settings)
415 {
416 if (settings->add_flag)
417 b->core.flag |= settings->add_flag;
418
419 if (settings->remove_flag)
420 b->core.flag &= ~settings->remove_flag;
421 }
422
423 static int cmp_reglist_intervals(const void *aptr, const void *bptr)
424 {
425 hts_pair_pos_t *a = (hts_pair_pos_t*)aptr;
426 hts_pair_pos_t *b = (hts_pair_pos_t*)bptr;
427 if ( a->beg < b->beg ) return -1;
428 if ( a->beg > b->beg ) return 1;
429 if ( a->end < b->end ) return -1;
430 if ( a->end > b->end ) return 1;
431 return 0;
432 }
433 static int cmp_reglist_tids(const void *aptr, const void *bptr)
434 {
435 hts_reglist_t *a = (hts_reglist_t*)aptr;
436 hts_reglist_t *b = (hts_reglist_t*)bptr;
437 if ( b->tid==HTS_IDX_NOCOOR || a->tid < b->tid ) return -1;
438 if ( a->tid==HTS_IDX_NOCOOR || a->tid > b->tid ) return 1;
439 return 0;
440 }
441
442 static hts_reglist_t *_reglist_dup(sam_hdr_t *hdr, hts_reglist_t *src, int nsrc)
443 {
444 int i,j;
445 hts_reglist_t *dst = (hts_reglist_t*)calloc(nsrc,sizeof(hts_reglist_t));
446 if ( !dst ) {
447 print_error_errno("view", "[%s:%d] could not allocate region list"
448 ,__FILE__ ,__LINE__);
449 return NULL;
450 }
451 for (i=0; i<nsrc; i++)
452 {
453 // Assume tid is not set correctly, reg is informative but may not point to a long-lived memory
454 dst[i].tid = sam_hdr_name2tid(hdr,src[i].reg);
455 dst[i].min_beg = src[i].min_beg;
456 dst[i].max_end = src[i].max_end;
457 dst[i].count = src[i].count;
458 dst[i].intervals = (hts_pair_pos_t*)malloc(sizeof(hts_pair_pos_t)*dst[i].count);
459 if ( !dst[i].intervals ) {
460 print_error_errno("view", "[%s:%d] could not allocate region list",
461 __FILE__, __LINE__);
462 goto fail;
463 }
464 for (j=0; j<dst[i].count; j++)
465 dst[i].intervals[j] = src[i].intervals[j];
466 }
467 qsort(dst,nsrc,sizeof(*dst),cmp_reglist_tids);
468 return dst;
469
470 fail:
471 for (j = 0; j < i; j++)
472 free(dst[j].intervals);
473 free(dst);
474 return NULL;
475 }
476 static inline int _reglist_find_tid(hts_reglist_t *reg, int nreg, int tid) // binary search
477 {
478 int i = -1, imin = 0, imax = nreg - 1;
479 while ( imin <= imax )
480 {
481 i = (imin+imax)/2;
482 if ( tid==HTS_IDX_NOCOOR || reg[i].tid < tid ) imin = i + 1;
483 else if ( reg[i].tid==HTS_IDX_NOCOOR || reg[i].tid > tid ) imax = i - 1;
484 else break;
485 }
486 if ( i<0 || reg[i].tid < tid ) i++; // not found, i will be the index of the inserted element
487 return i;
488 }
489 static int _reglist_push(hts_reglist_t **_reg, int *_nreg, int tid, hts_pos_t beg, hts_pos_t end)
490 {
491 hts_reglist_t *reg = *_reg;
492 int nreg = *_nreg;
493 int i = _reglist_find_tid(reg,nreg,tid);
494 if ( i>=nreg || reg[i].tid!=tid ) {
495 nreg++;
496 reg = (hts_reglist_t*)realloc(reg,sizeof(hts_reglist_t)*nreg);
497 if ( !reg ) {
498 print_error_errno("view", "[%s:%d] could not extend region list",
499 __FILE__, __LINE__);
500 return -1;
501 }
502 if ( i+1 < nreg )
503 memmove(reg + i + 1, reg + i, sizeof(hts_reglist_t)*(nreg - i - 1));
504 reg[i].reg = NULL;
505 reg[i].tid = tid;
506 reg[i].min_beg = beg;
507 reg[i].max_end = end;
508 reg[i].intervals = NULL;
509 reg[i].count = 0;
510 }
511 *_reg = reg;
512 *_nreg = nreg;
513 if ( reg[i].count > 0
514 && reg[i].intervals[reg[i].count - 1].beg==beg
515 && reg[i].intervals[reg[i].count - 1].end==end ) {
516 return 0;
517 }
518 hts_pair_pos_t *new_intervals = realloc(reg[i].intervals, sizeof(hts_pair_pos_t)*(reg[i].count + 1));
519 if (!new_intervals) {
520 print_error_errno("view", "[%s:%d] could not extend region list",
521 __FILE__, __LINE__);
522 return -1;
523 }
524 reg[i].intervals = new_intervals;
525 reg[i].intervals[reg[i].count].beg = beg;
526 reg[i].intervals[reg[i].count].end = end;
527 reg[i].count++;
528 return 0;
529 }
530
531 static void _reglist_merge(hts_reglist_t *reg, int nreg)
532 {
533 int i,j;
534 for (i=0; i<nreg; i++)
535 {
536 qsort(reg[i].intervals,reg[i].count,sizeof(*reg[i].intervals),cmp_reglist_intervals);
537 int k = 1;
538 for (j=1; j<reg[i].count; j++)
539 {
540 if ( reg[i].intervals[k-1].end < reg[i].intervals[j].beg )
541 {
542 if ( k < j ) reg[i].intervals[k] = reg[i].intervals[j];
543 k++;
544 continue;
545 }
546 if ( reg[i].intervals[k-1].end < reg[i].intervals[j].end ) reg[i].intervals[k-1].end = reg[i].intervals[j].end;
547 }
548 reg[i].count = k;
549 reg[i].max_end = reg[i].intervals[k-1].end;
550 }
551 }
552 hts_itr_multi_t *multi_region_init(samview_settings_t *conf, char **regs, int nregs)
553 {
554 hts_itr_multi_t *iter = NULL;
555 int filter_state = ALL;
556 if ( nregs ) {
557 int filter_op = 0;
558 void *bed = bed_hash_regions(conf->bed, regs, 0, nregs, &filter_op); // insert(1) or filter out(0) the regions from the command line in the same hash table as the bed file
559 if (!bed) {
560 print_error_errno("view", "Couldn't %s region list",
561 filter_op ? "build" : "filter");
562 return NULL;
563 }
564 conf->bed = bed;
565 if ( !filter_op )
566 filter_state = FILTERED;
567 }
568 else
569 bed_unify(conf->bed);
570
571 // This check is probably redundant, but left just in case
572 if ( !conf->bed) { // index is unavailable or no regions have been specified
573 print_error("view", "No regions or BED file have been provided. Aborting.");
574 return NULL;
575 }
576
577 int regcount = 0;
578 hts_reglist_t *reglist = bed_reglist(conf->bed, filter_state, &regcount);
579 if (!reglist) {
580 print_error("view", "Region list is empty or could not be created. Aborting.");
581 return NULL;
582 }
583
584 if ( conf->fetch_pairs ) {
585 conf->reglist = _reglist_dup(conf->header,reglist,regcount);
586 if (!conf->reglist)
587 return NULL;
588 conf->nreglist = regcount;
589 }
590
591 iter = sam_itr_regions(conf->hts_idx, conf->header, reglist, regcount);
592 if ( !iter ) {
593 print_error("view", "Iterator could not be created. Aborting.");
594 return NULL;
595 }
596 return iter;
597 }
598
599 KHASH_SET_INIT_STR(names)
600
601 static int fetch_pairs_collect_mates(samview_settings_t *conf, hts_itr_multi_t *iter)
602 {
603 khint_t k;
604 int nunmap = 0, r = 0, nmates = 0, write_error = 0, retval = EXIT_FAILURE;
605 kh_names_t *mate_names = kh_init(names);
606 bam1_t *rec = bam_init1();
607
608 if (!mate_names) {
609 print_error_errno("view", "could not allocate mate names table");
610 goto out;
611 }
612 if (!rec) {
613 print_error_errno("view", "could not allocate bam record");
614 goto out;
615 }
616
617 while ((r =sam_itr_multi_next(conf->in, iter, rec))>=0) {
618 if ( (rec->core.flag & BAM_FPAIRED) == 0 ) continue;
619 if ( rec->core.mtid>=0 && bed_overlap(conf->bed, sam_hdr_tid2name(conf->header,rec->core.mtid), rec->core.mpos, rec->core.mpos) ) continue;
620 int p = process_aln(conf->header, rec, conf);
621 if (p < 0) goto out;
622 if (p == 1) continue;
623
624 nmates++;
625
626 k = kh_get(names,mate_names,bam_get_qname(rec));
627 if ( k == kh_end(mate_names) ) {
628 int ret = 0;
629 char *name_copy = strdup(bam_get_qname(rec));
630 if (!name_copy) {
631 print_error_errno("view", "[%s:%d] could not store sample name, %d elements", __FILE__,__LINE__,nmates);
632 goto out;
633 }
634 kh_put(names, mate_names, name_copy, &ret);
635 if ( ret<0 ) {
636 print_error_errno("view", "[%s:%d] could not store sample name, %d elements",__FILE__,__LINE__,nmates);
637 free(name_copy);
638 goto out;
639 }
640 }
641
642 if ( rec->core.mtid < 0 ) {
643 nunmap = 1;
644 } else {
645 if (_reglist_push(&conf->reglist, &conf->nreglist, rec->core.mtid, rec->core.mpos,rec->core.mpos+1) != 0)
646 goto out;
647 }
648 }
649
650 if (r < -1) {
651 print_error_errno("view", "error reading file \"%s\"", conf->fn_in);
652 goto out;
653 }
654
655 _reglist_merge(conf->reglist, conf->nreglist);
656 if ( nunmap ) {
657 if (_reglist_push(&conf->reglist,&conf->nreglist,HTS_IDX_NOCOOR,0,HTS_POS_MAX) != 0)
658 goto out;
659 }
660 hts_itr_multi_destroy(iter);
661 iter = sam_itr_regions(conf->hts_idx, conf->header, conf->reglist, conf->nreglist);
662 if ( !iter ) {
663 print_error_errno("view", "[%s:%d] iterator could not be created",__FILE__,__LINE__);
664 goto out;
665 }
666 while ((r = sam_itr_multi_next(conf->in, iter, rec))>=0) {
667 int drop = 1;
668 if (rec->core.tid >=0 &&
669 bed_overlap(conf->bed, sam_hdr_tid2name(conf->header,rec->core.tid), rec->core.pos, bam_endpos(rec))) drop = 0;
670 if ( drop ) {
671 k = kh_get(names,mate_names,bam_get_qname(rec));
672 if ( k != kh_end(mate_names) ) drop = 0;
673 }
674 int p = 0;
675 if (!drop && (p=process_aln(conf->header, rec, conf))== 0) {
676 if (adjust_tags(conf->header, rec, conf) != 0)
677 goto out;
678 if (check_sam_write1(conf->out, conf->header, rec, conf->fn_out,
679 &write_error) < 0)
680 goto out;
681 }
682 if (p < 0)
683 goto out;
684 }
685
686 if (r < -1) {
687 print_error_errno("view", "error reading file \"%s\"", conf->fn_in);
688 goto out;
689 }
690
691 retval = EXIT_SUCCESS;
692
693 out:
694 hts_itr_multi_destroy(iter);
695 hts_idx_destroy(conf->hts_idx); // destroy the BAM index
696 conf->hts_idx = NULL;
697 if (mate_names) {
698 // free khash keys
699 for (k = 0; k < kh_end(mate_names); ++k)
700 if ( kh_exist(mate_names,k) ) free((char*)kh_key(mate_names, k));
701 kh_destroy(names,mate_names);
702 }
703 bam_destroy1(rec);
704 return retval;
705 }
706
707 // Common code for processing and writing a record
708 static inline int process_one_record(samview_settings_t *conf, bam1_t *b,
709 int *write_error) {
710 if (conf->sanitize)
711 if (bam_sanitize(conf->header, b, conf->sanitize) < 0)
712 return -1;
713
714 int p;
715 if ((p = process_aln(conf->header, b, conf)) < 0) {
716 // error
717 return -1;
718 } else if (p == 0) {
719 // emit read
720 if (!conf->is_count) {
721 change_flag(b, conf);
722 if (adjust_tags(conf->header, b, conf) != 0)
723 return -1;
724 if (check_sam_write1(conf->out, conf->header,
725 b, conf->fn_out, write_error) < 0) {
726 return -1;
727 }
728 }
729 conf->count++;
730 } else if (conf->unmap) {
731 b->core.flag |= BAM_FUNMAP;
732 b->core.qual = 0;
733 b->core.isize = 0;
734
735 // remove CIGAR
736 if (b->core.n_cigar) {
737 memmove(bam_get_cigar(b), bam_get_seq(b),
738 b->data + b->l_data - bam_get_seq(b));
739 b->l_data -= 4*b->core.n_cigar;
740 b->core.n_cigar = 0;
741 }
742
743 if (check_sam_write1(conf->out, conf->header,
744 b, conf->fn_out, write_error) < 0) {
745 return -1;
746 }
747 } else {
748 if (conf->un_out) {
749 if (check_sam_write1(conf->un_out, conf->header,
750 b, conf->fn_un_out, write_error) < 0) {
751 return -1;
752 }
753 }
754 }
755 return 0;
756 }
757
758 static int stream_view(samview_settings_t *conf) {
759 bam1_t *b = bam_init1();
760 int write_error = 0, r, p = 0;
761 if (!b) {
762 print_error_errno("view", "could not allocate bam record");
763 return 1;
764 }
765 errno = 0; // prevent false error messages.
766 while ((r = sam_read1(conf->in, conf->header, b)) >= 0) {
767 if ((p = process_one_record(conf, b, &write_error)) < 0) break;
768 }
769 bam_destroy1(b);
770 if (r < -1 || p < 0) {
771 print_error_errno("view", "error reading file \"%s\"", conf->fn_in);
772 return 1;
773 }
774 return write_error;
775 }
776
777 static int multi_region_view(samview_settings_t *conf, hts_itr_multi_t *iter)
778 {
779 bam1_t *b = bam_init1();
780 int write_error = 0, result;
781 if (!b) {
782 print_error_errno("view", "could not allocate bam record");
783 return 1;
784 }
785 // fetch alignments
786 while ((result = sam_itr_multi_next(conf->in, iter, b)) >= 0) {
787 if (process_one_record(conf, b, &write_error) < 0) break;
788 }
789 bam_destroy1(b);
790
791 if (result < -1) {
792 print_error("view", "retrieval of region #%d failed", iter->curr_tid);
793 write_error = 1;
794 }
795 hts_itr_multi_destroy(iter);
796 return write_error;
797 }
798
799 // Make mnemonic distinct values for longoption-only options
800 #define LONGOPT(c) ((c) + 128)
801
802 // Check for ".sam" filenames as sam_open_mode cannot distinguish between
803 // foo.sam and foo.unknown, both getting mode "".
804 static int is_sam(const char *fn) {
805 if (!fn)
806 return 0;
807 size_t l = strlen(fn);
808 return (l >= 4 && strcasecmp(fn + l-4, ".sam") == 0);
809 }
810
811 static void aux_list_free(samview_settings_t *settings) {
812 if (settings->keep_tag)
813 kh_destroy(aux_exists, settings->keep_tag);
814 if (settings->remove_tag)
815 kh_destroy(aux_exists, settings->remove_tag);
816 }
817
818 int main_samview(int argc, char *argv[])
819 {
820 samview_settings_t settings;
821 int c, is_header = 0, is_header_only = 0, ret = 0, compress_level = -1, has_index_file = 0, no_pg = 0;
822 FILE *fp_out = NULL;
823 char out_mode[6] = {0}, out_un_mode[6] = {0};
824 char *out_format = "";
825 char *arg_list = NULL;
826 sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
827 htsThreadPool p = {NULL, 0};
828
829 memset(&settings,0,sizeof(settings));
830 settings.subsam_frac = -1.0;
831 settings.count_rf = SAM_FLAG; // don't want 0, and this is quick
832
833 static const struct option lopts[] = {
834 SAM_OPT_GLOBAL_OPTIONS('-', 0, 'O', 0, 'T', '@'),
835 {"add-flags", required_argument, NULL, LONGOPT('a')},
836 {"bam", no_argument, NULL, 'b'},
837 {"count", no_argument, NULL, 'c'},
838 {"cram", no_argument, NULL, 'C'},
839 {"customised-index", no_argument, NULL, 'X'},
840 {"customized-index", no_argument, NULL, 'X'},
841 {"excl-flags", required_argument, NULL, 'F'},
842 {"exclude-flags", required_argument, NULL, 'F'},
843 {"expr", required_argument, NULL, 'e'},
844 {"expression", required_argument, NULL, 'e'},
845 {"fai-reference", required_argument, NULL, 't'},
846 {"fast", no_argument, NULL, '1'},
847 {"fetch-pairs", no_argument, NULL, 'P'},
848 {"header-only", no_argument, NULL, 'H'},
849 {"help", no_argument, NULL, LONGOPT('?')},
850 {"incl-flags", required_argument, NULL, LONGOPT('g')},
851 {"include-flags", required_argument, NULL, LONGOPT('g')},
852 {"rf", required_argument, NULL, LONGOPT('g')}, // aka incl-flags
853 {"keep-tag", required_argument, NULL, LONGOPT('x') },
854 {"library", required_argument, NULL, 'l'},
855 {"min-mapq", required_argument, NULL, 'q'},
856 {"min-MQ", required_argument, NULL, 'q'},
857 {"min-mq", required_argument, NULL, 'q'},
858 {"min-qlen", required_argument, NULL, 'm'},
859 {"no-header", no_argument, NULL, LONGOPT('H')},
860 {"no-PG", no_argument, NULL, LONGOPT('P')},
861 {"output", required_argument, NULL, 'o'},
862 {"output-unselected", required_argument, NULL, 'U'},
863 {"QNAME-file", required_argument, NULL, 'N'},
864 {"qname-file", required_argument, NULL, 'N'},
865 {"read-group", required_argument, NULL, 'r'},
866 {"read-group-file", required_argument, NULL, 'R'},
867 {"readgroup", required_argument, NULL, 'r'},
868 {"readgroup-file", required_argument, NULL, 'R'},
869 {"region-file", required_argument, NULL, LONGOPT('L')},
870 {"regions-file", required_argument, NULL, LONGOPT('L')},
871 {"remove-B", no_argument, NULL, 'B'},
872 {"remove-flags", required_argument, NULL, LONGOPT('r')},
873 {"remove-tag", required_argument, NULL, 'x'},
874 {"require-flags", required_argument, NULL, 'f'},
875 {"subsample", required_argument, NULL, LONGOPT('s')},
876 {"subsample-seed", required_argument, NULL, LONGOPT('S')},
877 {"tag", required_argument, NULL, 'd'},
878 {"tag-file", required_argument, NULL, 'D'},
879 {"target-file", required_argument, NULL, 'L'},
880 {"targets-file", required_argument, NULL, 'L'},
881 {"uncompressed", no_argument, NULL, 'u'},
882 {"unmap", no_argument, NULL, 'p'},
883 {"unoutput", required_argument, NULL, 'U'},
884 {"use-index", no_argument, NULL, 'M'},
885 {"with-header", no_argument, NULL, 'h'},
886 {"sanitize", required_argument, NULL, 'z'},
887 {NULL, 0, NULL, 0}
888 };
889
890 /* parse command-line options */
891 strcpy(out_mode, "w");
892 strcpy(out_un_mode, "w");
893 if (argc == 1 && isatty(STDIN_FILENO))
894 return usage(stdout, EXIT_SUCCESS, 0);
895
896 // Suppress complaints about '?' being an unrecognised option. Without
897 // this we have to put '?' in the options list, which makes it hard to
898 // tell a bad long option from the use of '-?' (both return '?' and
899 // set optopt to '\0').
900 opterr = 0;
901
902 char *tmp;
903 int tmp_flag;
904
905 while ((c = getopt_long(argc, argv,
906 "SbBcCt:h1Ho:O:q:f:F:G:ul:r:T:R:N:d:D:L:s:@:m:x:U:MXe:pPz:",
907 lopts, NULL)) >= 0) {
908 switch (c) {
909 case 's':
910 settings.subsam_seed = strtol(optarg, &tmp, 10);
911 if (tmp && *tmp == '.') {
912 settings.subsam_frac = strtod(tmp, &tmp);
913 if (*tmp) ret = 1;
914 } else {
915 ret = 1;
916 }
917
918 if (ret == 1) {
919 print_error("view", "Incorrect sampling argument \"%s\"", optarg);
920 goto view_end;
921 }
922 settings.count_rf |= SAM_QNAME;
923 break;
924 case LONGOPT('s'):
925 settings.subsam_frac = strtod(optarg, &tmp);
926 if (*tmp || settings.subsam_frac < 0.0 || settings.subsam_frac > 1.0) {
927 print_error("view", "Incorrect sampling argument \"%s\"", optarg);
928 goto view_end;
929 }
930 settings.count_rf |= SAM_QNAME;
931 break;
932 case LONGOPT('S'): settings.subsam_seed = atoi(optarg); break;
933 case 'm':
934 settings.min_qlen = atoi(optarg);
935 settings.count_rf |= SAM_SEQ;
936 break;
937 case 'c': settings.is_count = 1; break;
938 case 'S': break;
939 case 'b': out_format = "b"; break;
940 case 'C': out_format = "c"; break;
941 case 't': settings.fn_fai = strdup(optarg); break;
942 case 'h': is_header = 1; break;
943 case 'H': is_header_only = 1; break;
944 case LONGOPT('H'): is_header = is_header_only = 0; break;
945 case 'o': settings.fn_out = strdup(optarg); break;
946 case 'U': settings.fn_un_out = strdup(optarg); break;
947 case 'X': has_index_file = 1; break;
948 case 'f':
949 tmp_flag = bam_str2flag(optarg);
950
951 if (tmp_flag < 0) {
952 print_error("view", "Unknown flag '%s'", optarg);
953 return 1;
954 }
955
956 settings.flag_on |= tmp_flag;
957 settings.count_rf |= SAM_FLAG | SAM_RNEXT;
958 break;
959 case 'F':
960 tmp_flag = bam_str2flag(optarg);
961
962 if (tmp_flag < 0) {
963 print_error("view", "Unknown flag '%s'", optarg);
964 return 1;
965 }
966
967 settings.flag_off |= tmp_flag;
968 settings.count_rf |= SAM_FLAG | SAM_RNEXT;
969 break;
970 case LONGOPT('g'):
971 tmp_flag = bam_str2flag(optarg);
972
973 if (tmp_flag < 0) {
974 print_error("view", "Unknown flag '%s'", optarg);
975 return 1;
976 }
977
978 settings.flag_anyon |= tmp_flag;
979 settings.count_rf |= SAM_FLAG | SAM_RNEXT;
980 break;
981 case 'G':
982 tmp_flag = bam_str2flag(optarg);
983
984 if (tmp_flag < 0) {
985 print_error("view", "Unknown flag '%s'", optarg);
986 return 1;
987 }
988
989 settings.flag_alloff |= tmp_flag;
990 settings.count_rf |= SAM_FLAG | SAM_RNEXT;
991 break;
992 case 'q':
993 settings.min_mapQ = atoi(optarg);
994 settings.count_rf |= SAM_MAPQ;
995 break;
996 case 'u': compress_level = 0; break;
997 case '1': compress_level = 1; break;
998 case 'l':
999 settings.library = strdup(optarg);
1000 settings.count_rf |= SAM_RGAUX;
1001 break;
1002 case 'p': settings.unmap = 1; break;
1003 case 'P': settings.fetch_pairs = 1; settings.multi_region = 1; break;
1004 case 'z':
1005 if ((settings.sanitize = bam_sanitize_options(optarg)) < 0) {
1006 ret = 1;
1007 goto view_end;
1008 }
1009 break;
1010 case LONGOPT('L'):
1011 settings.multi_region = 1;
1012 // fall through
1013 case 'L':
1014 if ((settings.bed = bed_read(optarg)) == NULL) {
1015 print_error_errno("view", "Could not read file \"%s\"", optarg);
1016 ret = 1;
1017 goto view_end;
1018 }
1019 settings.count_rf |= SAM_POS | SAM_RNAME | SAM_CIGAR;
1020 break;
1021 case 'r':
1022 if (add_read_group_single("view", &settings, optarg) != 0) {
1023 ret = 1;
1024 goto view_end;
1025 }
1026 settings.count_rf |= SAM_RGAUX;
1027 break;
1028 case 'R':
1029 if (add_read_groups_file("view", &settings, optarg) != 0) {
1030 ret = 1;
1031 goto view_end;
1032 }
1033 settings.count_rf |= SAM_RGAUX;
1034 break;
1035 case 'N':
1036 if (add_read_names_file("view", &settings, optarg) != 0) {
1037 ret = 1;
1038 goto view_end;
1039 }
1040 settings.count_rf |= SAM_QNAME;
1041 break;
1042
1043 case 'd':
1044 if (strlen(optarg) < 2 || (strlen(optarg) > 2 && optarg[2] != ':')) {
1045 print_error("view", "Invalid \"tag:value\" option: \"%s\"", optarg);
1046 ret = 1;
1047 goto view_end;
1048 }
1049
1050 if (settings.tag) {
1051 if (settings.tag[0] != optarg[0] || settings.tag[1] != optarg[1]) {
1052 print_error("view", "Different tag \"%s\" was specified before: \"%s\"", settings.tag, optarg);
1053 ret = 1;
1054 goto view_end;
1055 }
1056 } else {
1057 if (!(settings.tag = calloc(3, 1))) {
1058 print_error("view", "Could not allocate memory for tag: \"%s\"", optarg);
1059 ret = 1;
1060 goto view_end;
1061 }
1062 memcpy(settings.tag, optarg, 2);
1063 }
1064
1065 if (strlen(optarg) > 3 && add_tag_value_single("view", &settings, optarg+3) != 0) {
1066 print_error("view", "Could not add tag:value \"%s\"", optarg);
1067 ret = 1;
1068 goto view_end;
1069 }
1070 // Some tag filtering affects other fields
1071 if (memcmp(settings.tag, "NM", 2) == 0 ||
1072 memcmp(settings.tag, "MD", 2) == 0)
1073 settings.count_rf |= SAM_AUX | SAM_SEQ;
1074 else if (memcmp(settings.tag, "RG", 2) == 0)
1075 settings.count_rf |= SAM_RGAUX;
1076 else
1077 settings.count_rf |= SAM_AUX;
1078 break;
1079
1080 case 'D':
1081 // Allow ";" as delimiter besides ":" to support MinGW CLI POSIX
1082 // path translation as described at:
1083 // http://www.mingw.org/wiki/Posix_path_conversion
1084 if (strlen(optarg) < 4 || (optarg[2] != ':' && optarg[2] != ';')) {
1085 print_error("view", "Invalid \"tag:file\" option: \"%s\"", optarg);
1086 ret = 1;
1087 goto view_end;
1088 }
1089
1090 if (settings.tag) {
1091 if (settings.tag[0] != optarg[0] || settings.tag[1] != optarg[1]) {
1092 print_error("view", "Different tag \"%s\" was specified before: \"%s\"", settings.tag, optarg);
1093 ret = 1;
1094 goto view_end;
1095 }
1096 } else {
1097 if (!(settings.tag = calloc(3, 1))) {
1098 print_error("view", "Could not allocate memory for tag: \"%s\"", optarg);
1099 ret = 1;
1100 goto view_end;
1101 }
1102 memcpy(settings.tag, optarg, 2);
1103 }
1104
1105 if (add_tag_values_file("view", &settings, optarg+3) != 0) {
1106 ret = 1;
1107 goto view_end;
1108 }
1109 // Some tag filtering affects other fields
1110 if (memcmp(settings.tag, "NM", 2) == 0 ||
1111 memcmp(settings.tag, "MD", 2) == 0)
1112 settings.count_rf |= SAM_AUX | SAM_SEQ;
1113 else if (memcmp(settings.tag, "RG", 2) == 0)
1114 settings.count_rf |= SAM_RGAUX;
1115 else
1116 settings.count_rf |= SAM_AUX;
1117 break;
1118
1119 case LONGOPT('?'):
1120 return usage(stdout, EXIT_SUCCESS, 1);
1121 case '?':
1122 if (optopt == '?') { // '-?' appeared on command line
1123 return usage(stdout, EXIT_SUCCESS, 1);
1124 } else {
1125 if (optopt) { // Bad short option
1126 print_error("view", "invalid option -- '%c'", optopt);
1127 } else { // Bad long option
1128 // Do our best. There is no good solution to finding
1129 // out what the bad option was.
1130 // See, e.g. https://stackoverflow.com/questions/2723888/where-does-getopt-long-store-an-unrecognized-option
1131 if (optind > 0 && strncmp(argv[optind - 1], "--", 2) == 0) {
1132 print_error("view", "unrecognised option '%s'",
1133 argv[optind - 1]);
1134 }
1135 }
1136 return usage(stderr, EXIT_FAILURE, 0);
1137 }
1138 case 'B': settings.remove_B = 1; break;
1139
1140 case 'M': settings.multi_region = 1; break;
1141 case LONGOPT('P'): no_pg = 1; break;
1142 case 'e':
1143 if (!(settings.filter = hts_filter_init(optarg))) {
1144 print_error("main_samview", "Couldn't initialise filter");
1145 return 1;
1146 }
1147 settings.count_rf = INT_MAX; // no way to know what we need
1148 break;
1149 case LONGOPT('r'):
1150 tmp_flag = bam_str2flag(optarg);
1151
1152 if (tmp_flag < 0) {
1153 print_error("view", "Unknown flag '%s'", optarg);
1154 return 1;
1155 }
1156
1157 settings.remove_flag |= tmp_flag;
1158 break;
1159
1160 case LONGOPT('a'):
1161 tmp_flag = bam_str2flag(optarg);
1162
1163 if (tmp_flag < 0) {
1164 print_error("view", "Unknown flag '%s'", optarg);
1165 return 1;
1166 }
1167
1168 settings.add_flag |= tmp_flag;
1169 break;
1170
1171 case 'x':
1172 if (*optarg == '^') {
1173 if (parse_aux_list(&settings.keep_tag, optarg+1, "main_samview")) {
1174 aux_list_free(&settings);
1175 return usage(stderr, EXIT_FAILURE, 0);
1176 }
1177 } else {
1178 if (parse_aux_list(&settings.remove_tag, optarg, "main_samview")) {
1179 aux_list_free(&settings);
1180 return usage(stderr, EXIT_FAILURE, 0);
1181 }
1182 }
1183 break;
1184
1185 case LONGOPT('x'):
1186 if (parse_aux_list(&settings.keep_tag, optarg, "main_samview")) {
1187 aux_list_free(&settings);
1188 return usage(stderr, EXIT_FAILURE, 0);
1189 }
1190 break;
1191
1192 default:
1193 if (parse_sam_global_opt(c, optarg, lopts, &ga) != 0)
1194 return usage(stderr, EXIT_FAILURE, 0);
1195 break;
1196 }
1197 }
1198 if (settings.is_count && settings.fetch_pairs)
1199 {
1200 print_error("view","The options -P and -c cannot be combined\n");
1201 return 1;
1202 }
1203 if (settings.fn_fai == 0 && ga.reference) settings.fn_fai = fai_path(ga.reference);
1204 if (is_header_only) is_header = 1;
1205 // File format auto-detection first
1206 if (settings.fn_out) sam_open_mode(out_mode+1, settings.fn_out, NULL);
1207 if (settings.fn_un_out) sam_open_mode(out_un_mode+1, settings.fn_un_out, NULL);
1208
1209 // -1 or -u without an explicit format (-b, -C) => check fn extensions
1210 if (!*out_format && compress_level >= 0) {
1211 if (compress_level == 0 &&
1212 (out_mode[strlen(out_mode)-1] == 'z' ||
1213 out_un_mode[strlen(out_un_mode)-1] == 'z'))
1214 // z, fz, Fz sanity check
1215 fprintf(stderr, "[view] Warning option -u ignored due to"
1216 " filename suffix\n");
1217
1218 // If known extension, use it, otherwise BAM
1219 if (!(out_mode[1] || is_sam(settings.fn_out)))
1220 out_mode[1] = 'b';
1221
1222 if (!(out_un_mode[1] || is_sam(settings.fn_un_out)))
1223 out_un_mode[1] = 'b';
1224 } else if (*out_format) {
1225 out_mode[1] = out_un_mode[1] = *out_format;
1226 }
1227
1228 if (compress_level >= 0) {
1229 char tmp[2];
1230 tmp[0] = compress_level + '0'; tmp[1] = '\0';
1231 strcat(out_mode, tmp);
1232 strcat(out_un_mode, tmp);
1233 }
1234 if (argc == optind && isatty(STDIN_FILENO)) {
1235 print_error("view", "No input provided or missing option argument.");
1236 return usage(stderr, EXIT_FAILURE, 0); // potential memory leak...
1237 }
1238
1239 if (settings.unmap && settings.fn_un_out) {
1240 print_error("view", "Options --unoutput and --unmap are mutually exclusive.");
1241 ret = 1;
1242 goto view_end;
1243 }
1244
1245 if (settings.subsam_seed != 0) {
1246 // Convert likely user input 1,2,... to pseudo-random
1247 // values with more entropy and more bits set
1248 srand(settings.subsam_seed);
1249 settings.subsam_seed = rand();
1250 }
1251
1252 settings.fn_in = (optind < argc)? argv[optind] : "-";
1253 if ((settings.in = sam_open_format(settings.fn_in, "r", &ga.in)) == 0) {
1254 print_error_errno("view", "failed to open \"%s\" for reading", settings.fn_in);
1255 ret = 1;
1256 goto view_end;
1257 }
1258
1259 if (settings.fn_fai) {
1260 if (hts_set_fai_filename(settings.in, settings.fn_fai) != 0) {
1261 fprintf(stderr, "[main_samview] failed to use reference \"%s\".\n", settings.fn_fai);
1262 ret = 1;
1263 goto view_end;
1264 }
1265 }
1266 if ((settings.header = sam_hdr_read(settings.in)) == 0) {
1267 fprintf(stderr, "[main_samview] fail to read the header from \"%s\".\n", settings.fn_in);
1268 ret = 1;
1269 goto view_end;
1270 }
1271 if (settings.rghash) {
1272 sam_hdr_remove_lines(settings.header, "RG", "ID", settings.rghash);
1273 }
1274 if (!settings.is_count) {
1275 if ((settings.out = sam_open_format(settings.fn_out? settings.fn_out : "-", out_mode, &ga.out)) == 0) {
1276 print_error_errno("view", "failed to open \"%s\" for writing", settings.fn_out? settings.fn_out : "standard output");
1277 ret = 1;
1278 goto view_end;
1279 }
1280 if (settings.fn_fai) {
1281 if (hts_set_fai_filename(settings.out, settings.fn_fai) != 0) {
1282 fprintf(stderr, "[main_samview] failed to use reference \"%s\".\n", settings.fn_fai);
1283 ret = 1;
1284 goto view_end;
1285 }
1286 }
1287 autoflush_if_stdout(settings.out, settings.fn_out);
1288
1289 if (!no_pg) {
1290 if (!(arg_list = stringify_argv(argc+1, argv-1))) {
1291 print_error("view", "failed to create arg_list");
1292 ret = 1;
1293 goto view_end;
1294 }
1295 if (sam_hdr_add_pg(settings.header, "samtools",
1296 "VN", samtools_version(),
1297 arg_list ? "CL": NULL,
1298 arg_list ? arg_list : NULL,
1299 NULL)) {
1300 print_error("view", "failed to add PG line to the header");
1301 ret = 1;
1302 goto view_end;
1303 }
1304 }
1305
1306 if (ga.write_index || is_header ||
1307 out_mode[1] == 'b' || out_mode[1] == 'c' ||
1308 (ga.out.format != sam && ga.out.format != unknown_format)) {
1309 if (sam_hdr_write(settings.out, settings.header) != 0) {
1310 fprintf(stderr, "[main_samview] failed to write the SAM header\n");
1311 ret = 1;
1312 goto view_end;
1313 }
1314 }
1315 if (ga.write_index) {
1316 if (!(settings.fn_out_idx = auto_index(settings.out, settings.fn_out, settings.header))) {
1317 ret = 1;
1318 goto view_end;
1319 }
1320 }
1321
1322 if (settings.fn_un_out) {
1323 if ((settings.un_out = sam_open_format(settings.fn_un_out, out_un_mode, &ga.out)) == 0) {
1324 print_error_errno("view", "failed to open \"%s\" for writing", settings.fn_un_out);
1325 ret = 1;
1326 goto view_end;
1327 }
1328 if (settings.fn_fai) {
1329 if (hts_set_fai_filename(settings.un_out, settings.fn_fai) != 0) {
1330 fprintf(stderr, "[main_samview] failed to use reference \"%s\".\n", settings.fn_fai);
1331 ret = 1;
1332 goto view_end;
1333 }
1334 }
1335 autoflush_if_stdout(settings.un_out, settings.fn_un_out);
1336 if (ga.write_index || is_header ||
1337 out_un_mode[1] == 'b' || out_un_mode[1] == 'c' ||
1338 (ga.out.format != sam && ga.out.format != unknown_format)) {
1339 if (sam_hdr_write(settings.un_out, settings.header) != 0) {
1340 fprintf(stderr, "[main_samview] failed to write the SAM header\n");
1341 ret = 1;
1342 goto view_end;
1343 }
1344 }
1345 if (ga.write_index) {
1346 if (!(settings.fn_un_out_idx = auto_index(settings.un_out, settings.fn_un_out, settings.header))) {
1347 ret = 1;
1348 goto view_end;
1349 }
1350 }
1351 }
1352 }
1353 else {
1354 if (settings.fn_out) {
1355 fp_out = fopen(settings.fn_out, "w");
1356 if (fp_out == NULL) {
1357 print_error_errno("view", "can't create \"%s\"", settings.fn_out);
1358 ret = EXIT_FAILURE;
1359 goto view_end;
1360 }
1361 }
1362 settings.unmap = 0; // Not valid in counting mode
1363 }
1364
1365 if (ga.nthreads > 0) {
1366 if (!(p.pool = hts_tpool_init(ga.nthreads))) {
1367 fprintf(stderr, "Error creating thread pool\n");
1368 ret = 1;
1369 goto view_end;
1370 }
1371 hts_set_opt(settings.in, HTS_OPT_THREAD_POOL, &p);
1372 if (settings.out) hts_set_opt(settings.out, HTS_OPT_THREAD_POOL, &p);
1373 }
1374 if (is_header_only) goto view_end; // no need to print alignments
1375
1376
1377 // Initialize BAM/CRAM index
1378 char **regs = NULL;
1379 int nregs = 0;
1380 if ( has_index_file && optind <= argc - 2 ) {
1381 regs = optind < argc-2 ? &argv[optind+2] : NULL;
1382 nregs = argc - optind - 2;
1383 settings.fn_idx_in = argv[optind+1];
1384 } else if (!has_index_file && optind < argc - 1 ) {
1385 regs = &argv[optind+1];
1386 nregs = argc - optind - 1;
1387 } else if ( has_index_file && argc-optind < 2) {
1388 print_error("view", "Incorrect number of arguments for -X option. Aborting.");
1389 return 1;
1390 }
1391 if (regs)
1392 settings.count_rf |= SAM_POS | SAM_RNAME | SAM_CIGAR;
1393
1394 if ( settings.fn_idx_in || nregs || settings.multi_region )
1395 {
1396 settings.hts_idx = settings.fn_idx_in ? sam_index_load2(settings.in, settings.fn_in, settings.fn_idx_in) : sam_index_load(settings.in, settings.fn_in);
1397 if ( !settings.hts_idx )
1398 {
1399 print_error("view", "Random alignment retrieval only works for indexed SAM.gz, BAM or CRAM files.");
1400 return 1;
1401 }
1402 }
1403
1404 if (settings.is_count)
1405 // Won't fail, but also wouldn't matter if it did
1406 hts_set_opt(settings.in, CRAM_OPT_REQUIRED_FIELDS, settings.count_rf);
1407
1408 if ( settings.fetch_pairs )
1409 {
1410 hts_itr_multi_t *iter = multi_region_init(&settings, regs, nregs);
1411 ret = iter ? fetch_pairs_collect_mates(&settings, iter) : 1;
1412 if (ret) goto view_end;
1413 }
1414 else if ( settings.multi_region )
1415 {
1416 hts_itr_multi_t *iter = multi_region_init(&settings, regs, nregs);
1417 ret = iter ? multi_region_view(&settings, iter) : 1;
1418 if (ret) goto view_end;
1419 }
1420 else if ( !settings.hts_idx || optind+1 >= argc-has_index_file ) {
1421 // stream through the entire file
1422 ret = stream_view(&settings);
1423 if (ret) goto view_end;
1424 } else { // retrieve alignments in specified regions
1425 int i;
1426 for (i = (has_index_file)? optind+2 : optind+1; i < argc; ++i) {
1427 hts_itr_t *iter = sam_itr_querys(settings.hts_idx, settings.header, argv[i]); // parse a region in the format like `chr2:100-200'
1428 if (iter == NULL) { // region invalid or reference name not found
1429 fprintf(stderr, "[main_samview] region \"%s\" specifies an invalid region or unknown reference. Continue anyway.\n", argv[i]);
1430 continue;
1431 }
1432 // fetch alignments
1433 ret = multi_region_view(&settings, iter);
1434 if (ret) goto view_end;
1435 }
1436 }
1437
1438 if (ga.write_index) {
1439 if (sam_idx_save(settings.out) < 0) {
1440 print_error_errno("view", "writing index failed");
1441 ret = 1;
1442 }
1443 if (settings.un_out && sam_idx_save(settings.un_out) < 0) {
1444 print_error_errno("view", "writing index failed");
1445 ret = 1;
1446 }
1447 }
1448
1449 view_end:
1450 if ( settings.hts_idx ) hts_idx_destroy(settings.hts_idx);
1451
1452 if (settings.is_count && ret == 0) {
1453 if (fprintf(settings.fn_out? fp_out : stdout, "%" PRId64 "\n", settings.count) < 0) {
1454 if (settings.fn_out) print_error_errno("view", "writing to \"%s\" failed", settings.fn_out);
1455 else print_error_errno("view", "writing to standard output failed");
1456 ret = EXIT_FAILURE;
1457 }
1458 }
1459
1460 // close files, free and return
1461 if (settings.in) check_sam_close("view", settings.in, settings.fn_in, "standard input", &ret);
1462 if (settings.out) check_sam_close("view", settings.out, settings.fn_out, "standard output", &ret);
1463 if (settings.un_out) check_sam_close("view", settings.un_out, settings.fn_un_out, "file", &ret);
1464 if (fp_out) fclose(fp_out);
1465
1466 free(settings.fn_fai); free(settings.fn_out); free(settings.library); free(settings.fn_un_out);
1467 sam_global_args_free(&ga);
1468 if ( settings.header ) sam_hdr_destroy(settings.header);
1469 if (settings.bed) bed_destroy(settings.bed);
1470 if (settings.rghash) {
1471 khint_t k;
1472 for (k = 0; k < kh_end(settings.rghash); ++k)
1473 if (kh_exist(settings.rghash, k)) free((char*)kh_key(settings.rghash, k));
1474 kh_destroy(str, settings.rghash);
1475 }
1476 if (settings.rnhash) {
1477 khint_t k;
1478 for (k = 0; k < kh_end(settings.rnhash); ++k)
1479 if (kh_exist(settings.rnhash, k)) free((char*)kh_key(settings.rnhash, k));
1480 kh_destroy(str, settings.rnhash);
1481 }
1482 if (settings.tvhash) {
1483 khint_t k;
1484 for (k = 0; k < kh_end(settings.tvhash); ++k)
1485 if (kh_exist(settings.tvhash, k)) free((char*)kh_key(settings.tvhash, k));
1486 kh_destroy(str, settings.tvhash);
1487 }
1488
1489 if (settings.remove_aux_len) {
1490 free(settings.remove_aux);
1491 }
1492 if (settings.tag) {
1493 free(settings.tag);
1494 }
1495 if (settings.filter)
1496 hts_filter_free(settings.filter);
1497
1498 if (p.pool)
1499 hts_tpool_destroy(p.pool);
1500
1501 if (settings.fn_out_idx)
1502 free(settings.fn_out_idx);
1503 if (settings.fn_un_out_idx)
1504 free(settings.fn_un_out_idx);
1505 free(arg_list);
1506
1507 aux_list_free(&settings);
1508
1509 return ret;
1510 }
1511
1512 static int usage(FILE *fp, int exit_status, int is_long_help)
1513 {
1514 fprintf(fp,
1515 "\n"
1516 "Usage: samtools view [options] <in.bam>|<in.sam>|<in.cram> [region ...]\n"
1517 "\n"
1518
1519 "Output options:\n"
1520 " -b, --bam Output BAM\n"
1521 " -C, --cram Output CRAM (requires -T)\n"
1522 " -1, --fast Use fast BAM compression (and default to --bam)\n"
1523 " -u, --uncompressed Uncompressed BAM output (and default to --bam)\n"
1524 " -h, --with-header Include header in SAM output\n"
1525 " -H, --header-only Print SAM header only (no alignments)\n"
1526 " --no-header Print SAM alignment records only [default]\n"
1527 " -c, --count Print only the count of matching records\n"
1528 " -o, --output FILE Write output to FILE [standard output]\n"
1529 " -U, --unoutput FILE, --output-unselected FILE\n"
1530 " Output reads not selected by filters to FILE\n"
1531 " -p, --unmap Set flag to UNMAP on reads not selected\n"
1532 " then write to output file.\n"
1533 " -P, --fetch-pairs Retrieve complete pairs even when outside of region\n"
1534 "Input options:\n"
1535 " -t, --fai-reference FILE FILE listing reference names and lengths\n"
1536 " -M, --use-index Use index and multi-region iterator for regions\n"
1537 " --region[s]-file FILE Use index to include only reads overlapping FILE\n"
1538 " -X, --customized-index Expect extra index file argument after <in.bam>\n"
1539 "\n"
1540 "Filtering options (Only include in output reads that...):\n"
1541 " -L, --target[s]-file FILE ...overlap (BED) regions in FILE\n"
1542 " -N, --qname-file [^]FILE ...whose read name is listed in FILE (\"^\" negates)\n"
1543 " -r, --read-group STR ...are in read group STR\n"
1544 " -R, --read-group-file [^]FILE\n"
1545 " ...are in a read group listed in FILE\n"
1546 " -d, --tag STR1[:STR2] ...have a tag STR1 (with associated value STR2)\n"
1547 " -D, --tag-file STR:FILE ...have a tag STR whose value is listed in FILE\n"
1548 " -q, --min-MQ INT ...have mapping quality >= INT\n"
1549 " -l, --library STR ...are in library STR\n"
1550 " -m, --min-qlen INT ...cover >= INT query bases (as measured via CIGAR)\n"
1551 " -e, --expr STR ...match the filter expression STR\n"
1552 " -f, --require-flags FLAG ...have all of the FLAGs present\n" // F&x == x
1553 " -F, --excl[ude]-flags FLAG ...have none of the FLAGs present\n" // F&x == 0
1554 " --rf, --incl-flags, --include-flags FLAG\n"
1555 " ...have some of the FLAGs present\n"
1556 " -G FLAG EXCLUDE reads with all of the FLAGs present\n" // !(F&x == x) TODO long option
1557 " --subsample FLOAT Keep only FLOAT fraction of templates/read pairs\n"
1558 " --subsample-seed INT Influence WHICH reads are kept in subsampling [0]\n"
1559 " -s INT.FRAC Same as --subsample 0.FRAC --subsample-seed INT\n"
1560 "\n"
1561 "Processing options:\n"
1562 " --add-flags FLAG Add FLAGs to reads\n"
1563 " --remove-flags FLAG Remove FLAGs from reads\n"
1564 " -x, --remove-tag STR\n"
1565 " Comma-separated read tags to strip (repeatable) [null]\n"
1566 " --keep-tag STR\n"
1567 " Comma-separated read tags to preserve (repeatable) [null].\n"
1568 " Equivalent to \"-x ^STR\"\n"
1569 " -B, --remove-B Collapse the backward CIGAR operation\n"
1570 " -z, --sanitize FLAGS Perform sanitity checking and fixing on records.\n"
1571 " FLAGS is comma separated (see manual). [off]\n"
1572 "\n"
1573 "General options:\n"
1574 " -?, --help Print long help, including note about region specification\n"
1575 " -S Ignored (input format is auto-detected)\n"
1576 " --no-PG Do not add a PG line\n");
1577
1578 sam_global_opt_help(fp, "-.O.T@..");
1579 fprintf(fp, "\n");
1580
1581 if (is_long_help)
1582 fprintf(fp,
1583 "Notes:\n"
1584 "\n"
1585 "1. This command now auto-detects the input format (BAM/CRAM/SAM).\n"
1586 " Further control over the CRAM format can be specified by using the\n"
1587 " --output-fmt-option, e.g. to specify the number of sequences per slice\n"
1588 " and to use avoid reference based compression:\n"
1589 "\n"
1590 "\tsamtools view -C --output-fmt-option seqs_per_slice=5000 \\\n"
1591 "\t --output-fmt-option no_ref -o out.cram in.bam\n"
1592 "\n"
1593 " Options can also be specified as a comma separated list within the\n"
1594 " --output-fmt value too. For example this is equivalent to the above\n"
1595 "\n"
1596 "\tsamtools view --output-fmt cram,seqs_per_slice=5000,no_ref \\\n"
1597 "\t -o out.cram in.bam\n"
1598 "\n"
1599 "2. The file supplied with `-t' is SPACE/TAB delimited with the first\n"
1600 " two fields of each line consisting of the reference name and the\n"
1601 " corresponding sequence length. The `.fai' file generated by \n"
1602 " `samtools faidx' is suitable for use as this file. This may be an\n"
1603 " empty file if reads are unaligned.\n"
1604 "\n"
1605 "3. SAM->BAM conversion: samtools view -bT ref.fa in.sam.gz\n"
1606 "\n"
1607 "4. BAM->SAM conversion: samtools view -h in.bam\n"
1608 "\n"
1609 "5. A region should be presented in one of the following formats:\n"
1610 " `chr1', `chr2:1,000' and `chr3:1000-2,000'. When a region is\n"
1611 " specified, the input alignment file must be a sorted and indexed\n"
1612 " alignment (BAM/CRAM) file.\n"
1613 "\n"
1614 "6. Option `-u' is preferred over `-b' when the output is piped to\n"
1615 " another samtools command.\n"
1616 "\n"
1617 "7. Option `-M`/`--use-index` causes overlaps with `-L` BED file regions and\n"
1618 " command-line region arguments to be computed using the multi-region iterator\n"
1619 " and an index. This increases speed, omits duplicates, and outputs the reads\n"
1620 " as they are ordered in the input SAM/BAM/CRAM file.\n"
1621 "\n"
1622 "8. Options `-L`/`--target[s]-file` and `--region[s]-file` may not be used\n"
1623 " together. `--region[s]-file FILE` is simply equivalent to `-M -L FILE`,\n"
1624 " so using both causes one of the specified BED files to be ignored.\n"
1625 "\n");
1626
1627 return exit_status;
1628 }
1629
1630 static int head_usage(FILE *fp, int exit_status)
1631 {
1632 fprintf(fp,
1633 "Usage: samtools head [OPTION]... [FILE]\n"
1634 "Options:\n"
1635 " -h, --headers INT Display INT header lines [all]\n"
1636 " -n, --records INT Display INT alignment record lines [none]\n"
1637 );
1638 sam_global_opt_help(fp, "-.--T@-.");
1639 return exit_status;
1640 }
1641
1642 int main_head(int argc, char *argv[])
1643 {
1644 static const struct option lopts[] = {
1645 SAM_OPT_GLOBAL_OPTIONS('-', 0, '-', '-', 'T', '@'),
1646 { "headers", required_argument, NULL, 'h' },
1647 { "records", required_argument, NULL, 'n' },
1648 { NULL, 0, NULL, 0 }
1649 };
1650 sam_global_args ga = SAM_GLOBAL_ARGS_INIT;
1651
1652 int all_headers = 1;
1653 uint64_t nheaders = 0;
1654 uint64_t nrecords = 0;
1655
1656 int c, nargs;
1657 while ((c = getopt_long(argc, argv, "h:n:T:@:", lopts, NULL)) >= 0)
1658 switch (c) {
1659 case 'h': all_headers = 0; nheaders = strtoull(optarg, NULL, 0); break;
1660 case 'n': nrecords = strtoull(optarg, NULL, 0); break;
1661 default:
1662 if (parse_sam_global_opt(c, optarg, lopts, &ga) == 0) break;
1663 /* else fall-through */
1664 case '?':
1665 return head_usage(stderr, EXIT_FAILURE);
1666 }
1667
1668 nargs = argc - optind;
1669 if (nargs == 0 && isatty(STDIN_FILENO))
1670 return head_usage(stdout, EXIT_SUCCESS);
1671 else if (nargs > 1)
1672 return head_usage(stderr, EXIT_FAILURE);
1673
1674 samFile *fp = NULL;
1675 sam_hdr_t *hdr = NULL;
1676 kstring_t str = KS_INITIALIZE;
1677 bam1_t *b = NULL;
1678
1679 const char *fname = (nargs == 1)? argv[optind] : "-";
1680 fp = sam_open_format(fname, "r", &ga.in);
1681 if (fp == NULL) {
1682 if (strcmp(fname, "-") != 0)
1683 print_error_errno("head", "failed to open \"%s\" for reading", fname);
1684 else
1685 print_error_errno("head", "failed to open standard input for reading");
1686 goto err;
1687 }
1688
1689 if (ga.nthreads > 0) hts_set_threads(fp, ga.nthreads);
1690
1691 hdr = sam_hdr_read(fp);
1692 if (hdr == NULL) {
1693 if (strcmp(fname, "-") != 0)
1694 print_error("head", "failed to read the header from \"%s\"", fname);
1695 else
1696 print_error("head", "failed to read the header");
1697 goto err;
1698 }
1699
1700 if (all_headers) {
1701 fputs(sam_hdr_str(hdr), stdout);
1702 }
1703 else if (nheaders > 0) {
1704 const char *text = sam_hdr_str(hdr);
1705 const char *lim = text;
1706 uint64_t n;
1707 for (n = 0; n < nheaders; n++) {
1708 lim = strchr(lim, '\n');
1709 if (lim) lim++;
1710 else break;
1711 }
1712 if (lim) fwrite(text, lim - text, 1, stdout);
1713 else fputs(text, stdout);
1714 }
1715
1716 if (nrecords > 0) {
1717 b = bam_init1();
1718 uint64_t n;
1719 int r = 0;
1720 for (n = 0; n < nrecords && (r = sam_read1(fp, hdr, b)) >= 0; n++) {
1721 if (sam_format1(hdr, b, &str) < 0) {
1722 print_error_errno("head", "couldn't format record");
1723 goto err;
1724 }
1725 puts(ks_str(&str));
1726 }
1727 if (r < -1) {
1728 print_error("head", "\"%s\" is truncated", fname);
1729 goto err;
1730 }
1731 bam_destroy1(b);
1732 ks_free(&str);
1733 }
1734
1735 sam_hdr_destroy(hdr);
1736 sam_close(fp);
1737 sam_global_args_free(&ga);
1738
1739 return EXIT_SUCCESS;
1740
1741 err:
1742 if (fp) sam_close(fp);
1743 sam_hdr_destroy(hdr);
1744 bam_destroy1(b);
1745 ks_free(&str);
1746 sam_global_args_free(&ga);
1747 return EXIT_FAILURE;
1748 }