Debian Codegraph @

bcftools/bam_sample.c.pysam.c

raw symbols SCIP
1 #include "bcftools.pysam.h"
2
3 /* bam_sample.c -- group data by sample.
4
5 Copyright (C) 2010, 2011 Broad Institute.
6 Copyright (C) 2013, 2016-2022 Genome Research Ltd.
7
8 Author: Heng Li <[email protected]>, Petr Danecek <[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 notice 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 <stdlib.h>
29 #include <string.h>
30 #include <ctype.h>
31 #include <htslib/hts.h>
32 #include <htslib/kstring.h>
33 #include <htslib/khash_str2int.h>
34 #include <khash_str2str.h>
35 #include "bam_sample.h"
36 #include "bcftools.h"
37
38
39 typedef struct
40 {
41 char *fname;
42 void *rg2idx; // hash: read group name to BCF output sample index. Maintained by bsmpl_add_readgroup
43 int default_idx; // default BCF output sample index, set only when all readgroups are treated as one sample
44 }
45 file_t;
46
47 struct _bam_smpl_t
48 {
49 kstring_t tmp;
50 file_t *files;
51 int ignore_rg, nsmpl, nfiles;
52 char **smpl; // list of BCF output sample names. Maintained by bsmpl_add_readgroup
53 void *sample_list; // hash: BAM input sample name to BCF output sample name. This is the -s/-S list
54 int sample_logic; // the -s/-S logic, 1: include, 0: exclude
55 void *rg_list; // hash: BAM/rg_id to sample name or */rg_id for global ids. This is the -G list
56 int rg_logic; // the -G logic, 1: include, 0: exclude
57 void *name2idx; // hash: BCF output sample name to BCF output sample index. Maintained by bsmpl_add_readgroup
58 };
59
60 bam_smpl_t *bam_smpl_init(void)
61 {
62 bam_smpl_t *bsmpl;
63 bsmpl = (bam_smpl_t*) calloc(1, sizeof(bam_smpl_t));
64 bsmpl->name2idx = khash_str2int_init();
65 return bsmpl;
66 }
67
68 void bam_smpl_destroy(bam_smpl_t *bsmpl)
69 {
70 if ( !bsmpl ) return;
71 if ( bsmpl->name2idx ) khash_str2int_destroy_free(bsmpl->name2idx);
72 if ( bsmpl->sample_list ) khash_str2str_destroy_free_all(bsmpl->sample_list);
73 if ( bsmpl->rg_list ) khash_str2str_destroy_free_all(bsmpl->rg_list);
74 int i;
75 for (i=0; i<bsmpl->nfiles; i++)
76 {
77 file_t *file = &bsmpl->files[i];
78 if ( file->rg2idx ) khash_str2int_destroy_free(file->rg2idx);
79 free(file->fname);
80 }
81 free(bsmpl->smpl);
82 free(bsmpl->files);
83 free(bsmpl->tmp.s);
84 free(bsmpl);
85 }
86
87 void bam_smpl_ignore_readgroups(bam_smpl_t* bsmpl)
88 {
89 bsmpl->ignore_rg = 1;
90 }
91
92 static void bsmpl_add_readgroup(bam_smpl_t *bsmpl, file_t *file, const char *rg_id, const char *smpl_name)
93 {
94 int ismpl = -1;
95 if ( smpl_name )
96 {
97 if ( khash_str2int_get(bsmpl->name2idx,smpl_name,&ismpl) < 0 )
98 {
99 // new sample
100 bsmpl->nsmpl++;
101 bsmpl->smpl = (char**) realloc(bsmpl->smpl,sizeof(char*)*bsmpl->nsmpl);
102 bsmpl->smpl[bsmpl->nsmpl-1] = strdup(smpl_name);
103 ismpl = khash_str2int_inc(bsmpl->name2idx,bsmpl->smpl[bsmpl->nsmpl-1]);
104 }
105 }
106 if ( !strcmp("*",rg_id) )
107 {
108 // all read groups in the bam treated as the same sample
109 file->default_idx = ismpl;
110 return;
111 }
112 if ( !file->rg2idx ) file->rg2idx = khash_str2int_init();
113 if ( khash_str2int_has_key(file->rg2idx,rg_id) ) return; // duplicate @RG:ID
114 khash_str2int_set(file->rg2idx, strdup(rg_id), ismpl);
115 }
116 static int bsmpl_keep_readgroup(bam_smpl_t *bsmpl, file_t *file, const char *rg_id, const char **smpl_name)
117 {
118 char *rg_smpl = khash_str2str_get(bsmpl->rg_list,rg_id); // unique read group present in one bam only
119 if ( !rg_smpl )
120 {
121 // read group specific to this bam
122 bsmpl->tmp.l = 0;
123 ksprintf(&bsmpl->tmp,"%s\t%s",rg_id,file->fname);
124 rg_smpl = khash_str2str_get(bsmpl->rg_list,bsmpl->tmp.s);
125 }
126 if ( !rg_smpl )
127 {
128 // any read group in this file?
129 bsmpl->tmp.l = 0;
130 ksprintf(&bsmpl->tmp,"*\t%s",file->fname);
131 rg_smpl = khash_str2str_get(bsmpl->rg_list,bsmpl->tmp.s);
132 }
133 if ( !rg_smpl && bsmpl->rg_logic ) return 0;
134 if ( rg_smpl && !bsmpl->rg_logic ) return 0;
135
136 if ( rg_smpl && rg_smpl[0]!='\t' ) *smpl_name = rg_smpl; // rename the sample
137 return 1;
138 }
139
140 /*
141 The logic of this function is a bit complicated because we want to work
142 also with broken bams containing read groups that are not listed in the
143 header. The desired behavior is as follows:
144 - when -G is given, read groups which are not listed in the header must
145 be given explicitly using the "?" symbol in -G.
146 Otherwise:
147 - if the bam has no header, all reads in the file are assigned to a
148 single sample named after the file
149 - if there is at least one sample defined in the header, reads with no
150 read group id or with a read group id not listed in the header are
151 assigned to the first sample encountered in the header
152 */
153 int bam_smpl_add_bam(bam_smpl_t *bsmpl, char *bam_hdr, const char *fname)
154 {
155 bsmpl->nfiles++;
156 bsmpl->files = (file_t*) realloc(bsmpl->files,bsmpl->nfiles*sizeof(file_t));
157 file_t *file = &bsmpl->files[bsmpl->nfiles-1];
158 memset(file,0,sizeof(file_t));
159 file->fname = strdup(fname);
160 file->default_idx = -1;
161
162 if ( bsmpl->ignore_rg || !bam_hdr )
163 {
164 // The option --ignore-RG is set or there is no BAM header: use the file name as the sample name
165 bsmpl_add_readgroup(bsmpl,file,"*",file->fname);
166 return bsmpl->nfiles-1;
167 }
168
169 void *bam_smpls = khash_str2int_init();
170 int first_smpl = -1, nskipped = 0;
171 const char *p = bam_hdr, *q, *r;
172 while (p != NULL && (q = strstr(p, "@RG")) != 0)
173 {
174 char *eol = strchr(q + 3, '\n');
175 if (q > bam_hdr && *(q - 1) != '\n') { // @RG must be at start of line
176 p = eol;
177 continue;
178 }
179 p = q + 3;
180 if ((q = strstr(p, "\tID:")) != 0) q += 4;
181 if ((r = strstr(p, "\tSM:")) != 0) r += 4;
182 if (r && q)
183 {
184 char *u, *v;
185 int ioq, ior;
186 for (u = (char*)q; *u && *u != '\t' && *u != '\n'; ++u);
187 for (v = (char*)r; *v && *v != '\t' && *v != '\n'; ++v);
188 ioq = *u; ior = *v; *u = *v = '\0';
189
190 // q now points to a null terminated read group id
191 // r points to a null terminated sample name
192 if ( !strcmp("*",q) || !strcmp("?",q) )
193 error("Error: the read group IDs \"*\" and \"?\" have a special meaning in the mpileup code. Please fix the code or the bam: %s\n", fname);
194
195 int accept_rg = 1;
196 if ( bsmpl->sample_list )
197 {
198 // restrict samples based on the -s/-S options
199 char *name = khash_str2str_get(bsmpl->sample_list,r);
200 if ( bsmpl->sample_logic==0 )
201 accept_rg = name ? 0 : 1;
202 else if ( !name )
203 accept_rg = 0;
204 else
205 r = name;
206 }
207 if ( accept_rg && bsmpl->rg_list )
208 {
209 // restrict readgroups based on the -G option, possibly renaming the sample
210 accept_rg = bsmpl_keep_readgroup(bsmpl,file,q,&r);
211 }
212 if ( accept_rg )
213 bsmpl_add_readgroup(bsmpl,file,q,r);
214 else
215 {
216 bsmpl_add_readgroup(bsmpl,file,q,NULL); // ignore this RG but note that it was seen in the header
217 nskipped++;
218 }
219
220 if ( first_smpl<0 )
221 khash_str2int_get(bsmpl->name2idx,r,&first_smpl);
222 if ( !khash_str2int_has_key(bam_smpls,r) )
223 khash_str2int_inc(bam_smpls,strdup(r));
224
225 *u = ioq; *v = ior;
226 }
227 else
228 break;
229 p = eol;
230 }
231 int nsmpls = khash_str2int_size(bam_smpls);
232 khash_str2int_destroy_free(bam_smpls);
233
234 const char *smpl_name = NULL;
235 int accept_null_rg = 1;
236 if ( bsmpl->rg_list && !bsmpl_keep_readgroup(bsmpl,file,"?",&smpl_name) ) accept_null_rg = 0;
237 if ( bsmpl->sample_list && first_smpl==-1 ) accept_null_rg = 0;
238
239 if ( !accept_null_rg && first_smpl==-1 )
240 {
241 // no suitable read group is available in this bam: ignore the whole file.
242 free(file->fname);
243 if ( file->rg2idx ) khash_str2int_destroy_free(file->rg2idx);
244 bsmpl->nfiles--;
245 return -1;
246 }
247 if ( !accept_null_rg ) return bsmpl->nfiles-1;
248 if ( nsmpls==1 && !nskipped )
249 {
250 file->default_idx = first_smpl;
251 return bsmpl->nfiles-1;
252 }
253 if ( !smpl_name ) smpl_name = first_smpl==-1 ? file->fname : bsmpl->smpl[first_smpl];
254
255 bsmpl_add_readgroup(bsmpl,file,"?",smpl_name);
256 return bsmpl->nfiles-1;
257 }
258
259 const char **bam_smpl_get_samples(bam_smpl_t *bsmpl, int *nsmpl)
260 {
261 *nsmpl = bsmpl->nsmpl;
262 return (const char**)bsmpl->smpl;
263 }
264
265 int bam_smpl_get_sample_id(bam_smpl_t *bsmpl, int bam_id, bam1_t *bam_rec)
266 {
267 file_t *file = &bsmpl->files[bam_id];
268 if ( file->default_idx >= 0 ) return file->default_idx;
269
270 char *aux_rg = (char*) bam_aux_get(bam_rec, "RG");
271 aux_rg = aux_rg ? aux_rg+1 : "?";
272
273 int rg_id;
274 if ( khash_str2int_get(file->rg2idx, aux_rg, &rg_id)==0 ) return rg_id;
275 if ( khash_str2int_get(file->rg2idx, "?", &rg_id)==0 ) return rg_id;
276 return -1;
277 }
278
279 int bam_smpl_add_samples(bam_smpl_t *bsmpl, char *list, int is_file)
280 {
281 if ( list[0]!='^' ) bsmpl->sample_logic = 1;
282 else list++;
283
284 int i, nsamples = 0;
285 char **samples = hts_readlist(list, is_file, &nsamples);
286 if ( !samples || !nsamples ) return 0;
287
288 kstring_t ori = {0,0,0};
289 kstring_t ren = {0,0,0};
290
291 bsmpl->sample_list = khash_str2str_init();
292 for (i=0; i<nsamples; i++)
293 {
294 char *ptr = samples[i];
295 ori.l = ren.l = 0;
296 int escaped = 0;
297 while ( *ptr )
298 {
299 if ( *ptr=='\\' && !escaped ) { escaped = 1; ptr++; continue; }
300 if ( isspace(*ptr) && !escaped ) break;
301 kputc(*ptr, &ori);
302 escaped = 0;
303 ptr++;
304 }
305 if ( *ptr )
306 {
307 while ( *ptr && isspace(*ptr) ) ptr++;
308 while ( *ptr )
309 {
310 if ( *ptr=='\\' && !escaped ) { escaped = 1; ptr++; continue; }
311 if ( isspace(*ptr) && !escaped ) break;
312 kputc(*ptr, &ren);
313 escaped = 0;
314 ptr++;
315 }
316 }
317 khash_str2str_set(bsmpl->sample_list,strdup(ori.s),strdup(ren.l?ren.s:ori.s));
318 free(samples[i]);
319 }
320 free(samples);
321 free(ori.s);
322 free(ren.s);
323 return nsamples;
324 }
325
326 int bam_smpl_add_readgroups(bam_smpl_t *bsmpl, char *list, int is_file)
327 {
328 if ( list[0]!='^' ) bsmpl->rg_logic = 1;
329 else list++;
330
331 int i, nrows = 0;
332 char **rows = hts_readlist(list, is_file, &nrows);
333 if ( !rows || !nrows ) return 0;
334
335 kstring_t fld1 = {0,0,0};
336 kstring_t fld2 = {0,0,0};
337 kstring_t fld3 = {0,0,0};
338
339 bsmpl->rg_list = khash_str2str_init();
340 for (i=0; i<nrows; i++)
341 {
342 char *ptr = rows[i];
343 fld1.l = fld2.l = fld3.l = 0;
344 int escaped = 0;
345 while ( *ptr )
346 {
347 if ( *ptr=='\\' && !escaped ) { escaped = 1; ptr++; continue; }
348 if ( isspace(*ptr) && !escaped ) break;
349 kputc(*ptr, &fld1);
350 escaped = 0;
351 ptr++;
352 }
353 if ( *ptr )
354 {
355 while ( *ptr && isspace(*ptr) ) ptr++;
356 while ( *ptr )
357 {
358 if ( *ptr=='\\' && !escaped ) { escaped = 1; ptr++; continue; }
359 if ( isspace(*ptr) && !escaped ) break;
360 kputc(*ptr, &fld2);
361 escaped = 0;
362 ptr++;
363 }
364 }
365 if ( *ptr )
366 {
367 while ( *ptr && isspace(*ptr) ) ptr++;
368 while ( *ptr )
369 {
370 if ( *ptr=='\\' && !escaped ) { escaped = 1; ptr++; continue; }
371 if ( isspace(*ptr) && !escaped ) break;
372 kputc(*ptr, &fld3);
373 escaped = 0;
374 ptr++;
375 }
376 }
377 if ( fld3.l )
378 {
379 // ID FILE SAMPLE
380 kputc('\t',&fld1);
381 kputs(fld2.s,&fld1);
382 fld2.l = 0;
383 kputs(fld3.s,&fld2);
384 }
385 // fld2.s now contains a new sample name. If NULL, use \t to keep the bam header name
386 char *value = khash_str2str_get(bsmpl->rg_list,fld1.s);
387 if ( !value )
388 khash_str2str_set(bsmpl->rg_list,strdup(fld1.s),strdup(fld2.l?fld2.s:"\t"));
389 else if ( strcmp(value,fld2.l?fld2.s:"\t") )
390 error("Error: The read group \"%s\" was assigned to two different samples: \"%s\" and \"%s\"\n", fld1.s,value,fld2.l?fld2.s:"\t");
391 free(rows[i]);
392 }
393 free(rows);
394 free(fld1.s);
395 free(fld2.s);
396 free(fld3.s);
397 return nrows;
398 }
399
400