Debian Codegraph @

samtools/sam_view.c.pysam.c

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