Debian Codegraph @

samtools/bam_samples.c

raw symbols SCIP
1 /* bam_samples -- print samples in a set of BAM files
2
3 Copyright (C) 2021 Pierre Lindenbaum
4 Institut du Thorax. u1087 Nantes. France.
5 @yokofakun
6
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
13
14 The above copyright notice and this permission notice shall be included in
15 all copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23 DEALINGS IN THE SOFTWARE. */
24
25 #include <config.h>
26 #include <htslib/hts.h>
27 #include <htslib/sam.h>
28 #include <htslib/faidx.h>
29 #include <htslib/khash.h>
30 #include <htslib/kseq.h>
31 #include <samtools.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <getopt.h>
36
37 KHASH_MAP_INIT_STR(sm, int)
38
39 /** and chained struct containing the faidx and the fasta filename
40 will be compared with the @SQ lines in the SAM header
41 */
42 typedef struct FaidxPath {
43 /** path to reference */
44 char* filename;
45 /** fasta index */
46 faidx_t* faidx;
47 struct FaidxPath* next;
48 } FaidxPath;
49
50 /** program parameters */
51 typedef struct Params {
52 /** output stream */
53 FILE* out;
54 /** tag in @RG line. default is "SM" */
55 char tag[3];
56 /** first faidx/path in chained list */
57 FaidxPath* faidx;
58 /** show whether the bam is indexed */
59 int test_index;
60 } Params;
61
62 /** print usage */
63 static void usage_samples(FILE *write_to) {
64 fprintf(write_to,
65 "Usage: samtools samples [options] <input> [...]\n"
66 " samtools samples [options] -X f1.bam f2.bam f1.bam.bai f2.bai \n"
67 " find dir1 dir2 -type f \\(-name \"*.bam\" -o -name \"*.cram\" \\) | samtools samples [options]\n"
68 " find dir1 dir2 -type f \\(-name \"*.bam\" -o -name \"*.bai\" \\) | sort | paste - - | samtools samples -X [options]\n"
69 "\n"
70 "Options:\n"
71 " -? print help and exit\n"
72 " -h add the columns header before printing the results\n"
73 " -i test if the file is indexed.\n"
74 " -T <tag> provide the sample tag name from the @RG line [SM].\n"
75 " -o <file> output file [stdout].\n"
76 " -f <file.fa> load an indexed fasta file in the collection of references. Can be used multiple times.\n"
77 " -F <file.txt> read a file containing the paths to indexed fasta files. One path per line.\n"
78 " -X use a custom index file.\n"
79 "\n"
80 " Using -f or -F will add a column containing the path to the reference or \".\" if the reference was not found.\n"
81 "\n"
82 );
83 }
84
85
86 /** loads fasta fai file into FaidxPath, add it to params->faidx */
87 static int load_dictionary(struct Params* params, const char* filename) {
88 FaidxPath* head = params->faidx;
89 FaidxPath* ptr = (FaidxPath*)malloc(sizeof(FaidxPath));
90 if (ptr == NULL) {
91 print_error_errno("samples", "Out of memory");
92 return EXIT_FAILURE;
93 }
94 ptr->filename = strdup(filename);
95 if (ptr->filename == NULL) {
96 free(ptr);
97 print_error_errno("samples", "Out of memory");
98 return EXIT_FAILURE;
99 }
100 ptr->faidx = fai_load(filename);
101 if (ptr->faidx == NULL) {
102 free(ptr->filename);
103 free(ptr);
104 print_error_errno("samples", "Cannot load index from \"%s\"", filename);
105 return EXIT_FAILURE;
106 }
107 /* insert at the beginning of the linked list */
108 params->faidx = ptr;
109 ptr->next = head;
110 return EXIT_SUCCESS;
111 }
112
113 /** load a faidx file and append it to params */
114 static int load_dictionaries(Params* params, const char* filename) {
115 int ret;
116 htsFile* in;
117 int status = EXIT_SUCCESS;
118
119 in = hts_open(filename, "r");
120 if (in == NULL) {
121 print_error_errno("samples", "Cannot open \"%s\"", filename);
122 status = EXIT_FAILURE;
123 } else {
124 kstring_t ks = KS_INITIALIZE;
125 while ((ret = hts_getline(in, KS_SEP_LINE, &ks)) >= 0) {
126 if (load_dictionary(params, ks_str(&ks)) != EXIT_SUCCESS) {
127 status = EXIT_FAILURE;
128 break;
129 }
130 }
131 ks_free(&ks);
132 hts_close(in);
133 }
134 return status;
135 }
136
137 /** print the sample information, search for a reference */
138 static int print_sample(
139 Params* params,
140 sam_hdr_t *header,
141 int has_index,
142 const char* sample,
143 const char* fname) {
144 fputs(sample, params->out);
145 fputc('\t', params->out);
146 fputs(fname, params->out);
147 if (params->test_index) {
148 fprintf(params->out, "\t%c", has_index ? 'Y' : 'N');
149 }
150 if (params->faidx != NULL) {
151 FaidxPath* ref = NULL;
152 FaidxPath* curr = params->faidx;
153 while (curr != NULL) {
154 /** check names and length are the same in the same order */
155 if (faidx_nseq(curr->faidx) == header->n_targets) {
156 int i;
157 for (i = 0; i < faidx_nseq(curr->faidx); i++) {
158 /** check name is the same */
159 if (strcmp(faidx_iseq(curr->faidx, i), header->target_name[i]) != 0) break;
160 /** check length is the same */
161 if (faidx_seq_len(curr->faidx, faidx_iseq(curr->faidx, i)) != header->target_len[i]) break;
162 }
163 /* the ref was found */
164 if (i == faidx_nseq(curr->faidx)) {
165 ref = curr;
166 break;
167 }
168 }
169 curr = curr->next;
170 }
171 fputc('\t', params->out);
172 if (ref == NULL) {
173 fputc('.', params->out);
174 } else {
175 fputs(curr->filename, params->out);
176 }
177 }
178 fputc('\n', params->out);
179 return 0;
180 }
181
182 /** open a sam file. Search for all samples in the @RG lines */
183 static int print_samples(Params* params, const char* fname, const char* baifname) {
184 samFile *in = 0;
185 sam_hdr_t *header = NULL;
186 int n_rg;
187 int status = EXIT_SUCCESS;
188 khash_t(sm) *sample_set = NULL;
189 khint_t k;
190 int count_samples = 0;
191 int has_index = 0;
192
193 if ((sample_set = kh_init(sm)) == NULL) {
194 print_error("samples", "Failed to initialise sample hash");
195 status = EXIT_FAILURE;
196 goto end_print;
197 }
198
199 if ((in = sam_open_format(fname, "r", NULL)) == 0) {
200 print_error_errno("samples", "Failed to open \"%s\" for reading", fname);
201 status = EXIT_FAILURE;
202 goto end_print;
203 }
204 if ((header = sam_hdr_read(in)) == 0) {
205 print_error("samples", "Failed to read the header from \"%s\"", fname);
206 status = EXIT_FAILURE;
207 goto end_print;
208 }
209
210 /* try to load index if required */
211 if (params->test_index) {
212 hts_idx_t *bam_idx;
213 /* path to bam index was specified */
214 if (baifname != NULL) {
215 bam_idx = sam_index_load3(in, fname, baifname, HTS_IDX_SILENT_FAIL);
216 }
217 /* get default index */
218 else {
219 bam_idx = sam_index_load3(in, fname, NULL, HTS_IDX_SILENT_FAIL);
220 }
221 has_index = bam_idx != NULL;
222 if (bam_idx != NULL) hts_idx_destroy(bam_idx);
223 /* and we continue... we have tested the index file but we always test for the samples and the references */
224 }
225
226 /* get the RG lines */
227 n_rg = sam_hdr_count_lines(header, "RG");
228 if (n_rg > 0) {
229 int i, r, ret;
230 char* sample;
231 kstring_t sm_val = KS_INITIALIZE;
232 for (i = 0; i < n_rg; i++) {
233 r = sam_hdr_find_tag_pos(header, "RG", i, params->tag, &sm_val);
234 if (r < 0) continue;
235 k = kh_get(sm, sample_set, ks_str(&sm_val));
236 if (k != kh_end(sample_set)) continue;
237 sample = strdup(ks_str(&sm_val));
238 if (sample == NULL) {
239 print_error_errno("samples", "Out of memory");
240 status = EXIT_FAILURE;
241 goto end_print;
242 }
243 kh_put(sm, sample_set, sample, &ret);
244 if (ret < 0) {
245 print_error("samples", "Failed to insert key '%s' into sample_set", sample);
246 free(sample);
247 status = EXIT_FAILURE;
248 goto end_print;
249 }
250 ++count_samples;
251 }
252 ks_free(&sm_val);
253 }
254 if (count_samples == 0) {
255 print_sample(params, header, has_index, ".", fname);
256 } else {
257 for (k = kh_begin(sample_set); k != kh_end(sample_set); ++k) {
258 if (kh_exist(sample_set, k)) {
259 char* sample = (char*)kh_key(sample_set, k);
260 print_sample(params, header, has_index, sample, fname);
261 }
262 }
263 }
264
265 end_print:
266 if (sample_set != NULL) {
267 for (k = kh_begin(sample_set); k != kh_end(sample_set); ++k) {
268 if (kh_exist(sample_set, k)) {
269 char* sample = (char*)kh_key(sample_set, k);
270 free(sample);
271 }
272 }
273 kh_destroy(sm, sample_set);
274 }
275 if (header != NULL) sam_hdr_destroy(header);
276 if (in != NULL) sam_close(in);
277
278 return status;
279 }
280
281
282 int main_samples(int argc, char** argv) {
283 int status = EXIT_SUCCESS;
284 int print_header = 0;
285 int has_index_file = 0;
286 Params params;
287 char* out_filename = NULL;
288 FaidxPath* fai;
289
290 strcpy(params.tag, "SM");
291 params.faidx = NULL;
292 params.test_index =0;
293
294 int opt;
295 while ((opt = getopt_long(argc, argv, "?hiXo:f:F:T:", NULL, NULL)) != -1) {
296 switch (opt) {
297 case 'h':
298 print_header = 1;
299 break;
300 case 'o':
301 out_filename = optarg;
302 break;
303 case 'i':
304 params.test_index = 1;
305 break;
306 case 'f':
307 if (load_dictionary(&params, optarg) != EXIT_SUCCESS) {
308 return EXIT_FAILURE;
309 }
310 break;
311 case 'F':
312 if (load_dictionaries(&params, optarg) != EXIT_SUCCESS) {
313 return EXIT_FAILURE;
314 }
315 break;
316 case 'T':
317 if (strlen(optarg) != 2) {
318 print_error("samples", "Length of tag \"%s\" is not 2.", optarg);
319 return EXIT_FAILURE;
320 }
321 strcpy(params.tag, optarg);
322 break;
323 case '?':
324 usage_samples(stdout);
325 return EXIT_SUCCESS;
326 case 'X':
327 has_index_file = 1;
328 break;
329 default:
330 usage_samples(stderr);
331 return EXIT_FAILURE;
332 }
333 }
334
335 /* if no file was provided and input is the terminal, print the usage and exit */
336 if (argc == optind && isatty(STDIN_FILENO)) {
337 usage_samples(stderr);
338 return EXIT_FAILURE;
339 }
340
341 if (out_filename != NULL) {
342 params.out = fopen(out_filename, "w");
343 if (params.out == NULL) {
344 print_error_errno("samples", "Cannot open \"%s\" for writing", out_filename);
345 return EXIT_FAILURE;
346 }
347 } else {
348 params.out = stdout;
349 }
350
351 if (print_header) {
352 fprintf(params.out, "#%s\tPATH", params.tag);
353 if (params.test_index) fprintf(params.out, "\tINDEX");
354 if (params.faidx != NULL) fprintf(params.out, "\tREFERENCE");
355 fprintf(params.out, "\n");
356 }
357
358 /* no file was provided, input is stdin, each line contains the path to a bam file */
359 if (argc == optind) {
360 htsFile* fp = hts_open("-", "r");
361 if (fp == NULL) {
362 print_error_errno("samples", "Cannot read from stdin");
363 status = EXIT_FAILURE;
364 } else {
365 kstring_t ks = KS_INITIALIZE;
366 int ret;
367 while ((ret = hts_getline(fp, KS_SEP_LINE, &ks)) >= 0) {
368 char* bai_path = NULL;
369 if (has_index_file) {
370 /* bam path and bam index file are separated by a tab */
371 char* tab = strchr(ks_str(&ks), '\t');
372 if (tab == NULL || *(tab+1) == '\0') {
373 print_error_errno("samples", "Expected path-to-bam(tab)path-to-index but got \"%s\"", ks_str(&ks));
374 status = EXIT_FAILURE;
375 break;
376 }
377 *tab=0;
378 bai_path = (tab + 1);
379 }
380 if (print_samples(&params, ks_str(&ks), bai_path) != EXIT_SUCCESS) {
381 status = EXIT_FAILURE;
382 break;
383 }
384 }
385 ks_free(&ks);
386 hts_close(fp);
387 }
388 }
389 /* loop over each file in argc/argv bam index provided */
390 else if (has_index_file) {
391 /* calculate number of input BAM files */
392 if ((argc - optind) % 2 != 0) {
393 print_error("samples","Odd number of filenames detected! Each BAM file should have an index file");
394 status = EXIT_FAILURE;
395 } else {
396 int i;
397 int n = (argc - optind ) / 2;
398 for (i = 0; i < n; i++) {
399 if (print_samples(&params, argv[optind+i], argv[optind+i+n]) != EXIT_SUCCESS) {
400 status = EXIT_FAILURE;
401 break;
402 }
403 }
404 }
405 } else {
406 int i;
407 for (i = optind; i < argc; i++) {
408 if (print_samples(&params, argv[i], NULL) != EXIT_SUCCESS) {
409 status = EXIT_FAILURE;
410 break;
411 }
412 }
413 }
414
415 fai = params.faidx;
416 while (fai != NULL) {
417 FaidxPath* next = fai -> next;
418 free(fai->filename);
419 fai_destroy(fai->faidx);
420 free(fai);
421 fai = next;
422 }
423
424 if (fflush(params.out) != 0) {
425 print_error_errno("samples", "Cannot flush output");
426 status = EXIT_FAILURE;
427 }
428 if (out_filename != NULL) {
429 fclose(params.out);
430 }
431
432 return status;
433 }