Debian Codegraph @

bcftools/filter.c

raw symbols SCIP
1 /* filter.c -- filter expressions.
2
3 Copyright (C) 2013-2024 Genome Research Ltd.
4
5 Author: Petr Danecek <[email protected]>
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 THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 THE SOFTWARE. */
24
25 #include <ctype.h>
26 #include <stdlib.h>
27 #include <strings.h>
28 #include <assert.h>
29 #include <errno.h>
30 #include <math.h>
31 #include <sys/types.h>
32 #include <stdint.h>
33 #include <inttypes.h>
34 #ifndef _WIN32
35 #include <pwd.h>
36 #endif
37 #include <regex.h>
38 #include <htslib/khash_str2int.h>
39 #include <htslib/hts_defs.h>
40 #include <htslib/vcfutils.h>
41 #include <htslib/kfunc.h>
42 #include <htslib/hts_endian.h>
43 #include "config.h"
44 #include "filter.h"
45 #include "bcftools.h"
46
47 #if ENABLE_PERL_FILTERS
48 // Work around clang warning problems
49 # if defined(__clang__)
50 # define PERL_GCC_BRACE_GROUPS_FORBIDDEN
51 # endif
52
53 # define filter_t perl_filter_t
54 # include <EXTERN.h>
55 # include <perl.h>
56 # undef filter_t
57 # define my_perl perl
58
59 static int filter_ninit = 0;
60 #endif
61
62
63 #ifndef __FUNCTION__
64 # define __FUNCTION__ __func__
65 #endif
66
67 typedef struct _token_t
68 {
69 // read-only values, same for all VCF lines
70 int tok_type; // one of the TOK_* keys below
71 int nargs; // with TOK_PERLSUB the first argument is the name of the subroutine
72 char *key; // set only for string constants, otherwise NULL
73 char *tag; // for debugging and printout only, VCF tag name
74 double threshold; // filtering threshold
75 int is_constant; // the threshold is set
76 int hdr_id, hl_type, ht_type; // BCF header lookup ID and one of BCF_HL_* types and BCF_HT_* types
77 int idx; // 0-based index to VCF vectors,
78 // -2: list (e.g. [0,1,2] or [1..3] or [1..] or any field[*], which is equivalent to [0..])
79 // -3: select indices on the fly based on values in GT
80 int *idxs; // set indexes to 0 to exclude, to 1 to include, and last element negative if unlimited; used by VCF retrievers only
81 int nidxs, nuidxs; // size of idxs array and the number of elements set to 1
82 uint8_t *usmpl; // bitmask of used samples as set by idx, set for FORMAT fields, NULL otherwise
83 int nsamples; // number of samples for format fields, 0 for info and other fields
84 void (*setter)(filter_t *, bcf1_t *, struct _token_t *);
85 int (*func)(filter_t *, bcf1_t *, struct _token_t *rtok, struct _token_t **stack, int nstack);
86 void (*comparator)(struct _token_t *, struct _token_t *, struct _token_t *rtok, bcf1_t *);
87 void *hash; // test presence of str value in the hash via comparator
88 regex_t *regex; // precompiled regex for string comparison
89 int iext; // for the use with filter_test_ext(), 1-based index to external values, 0=don't use
90
91 // modified on filter evaluation at each VCF line
92 double *values;
93 kstring_t str_value;
94 int is_str, is_missing; // is_missing is set only for constants, variables are controlled via nvalues
95 int pass_site; // -1 not applicable, 0 fails, >0 pass
96 uint8_t *pass_samples; // status of individual samples
97 int nvalues, mvalues; // number of used values: n=0 for missing values, n=1 for scalars, for strings n=str_value.l
98 int nval1; // number of per-sample fields or string length
99 }
100 token_t;
101
102 struct _filter_t
103 {
104 bcf_hdr_t *hdr;
105 char *str;
106 int nfilters;
107 token_t *filters, **flt_stack; // filtering input tokens (in RPN) and evaluation stack
108 int32_t *tmpi;
109 float *tmpf;
110 kstring_t tmps;
111 int max_unpack, mtmpi, mtmpf, nsamples;
112 struct {
113 bcf1_t *line;
114 int32_t *buf, nbuf, mbuf; // GTs as obtained by bcf_get_genotypes()
115 uint64_t *mask; // GTs as mask, e.g 0/0 is 1; 0/1 is 3, max 63 unique alleles
116 } cached_GT;
117 #if ENABLE_PERL_FILTERS
118 PerlInterpreter *perl;
119 #endif
120 char **undef_tag, **used_tag;
121 int nundef_tag, nused_tag;
122 int status, exit_on_error;
123 int n_ext; // number of external values to fill via filter_test_ext()
124 int *ext; // types of external values to fill via filter_test_ext()
125 };
126
127
128 #define TOK_VAL 0
129 #define TOK_LFT 1 // (
130 #define TOK_RGT 2 // )
131 #define TOK_LE 3 // less or equal
132 #define TOK_LT 4 // less than
133 #define TOK_EQ 5 // equal
134 #define TOK_BT 6 // bigger than
135 #define TOK_BE 7 // bigger or equal
136 #define TOK_NE 8 // not equal
137 #define TOK_OR 9 // |
138 #define TOK_AND 10 // &
139 #define TOK_ADD 11 // +
140 #define TOK_SUB 12 // -
141 #define TOK_MULT 13 // *
142 #define TOK_DIV 14 // /
143 #define TOK_MAX 15
144 #define TOK_MIN 16
145 #define TOK_AVG 17
146 #define TOK_AND_VEC 18 // && (operator applied in samples)
147 #define TOK_OR_VEC 19 // || (operator applied in samples)
148 #define TOK_LIKE 20 // ~ regular expression
149 #define TOK_NLIKE 21 // !~ regular expression
150 #define TOK_SUM 22
151 #define TOK_ABS 23
152 #define TOK_LEN 24
153 #define TOK_FUNC 25
154 #define TOK_CNT 26
155 #define TOK_PERLSUB 27
156 #define TOK_BINOM 28
157 #define TOK_PHRED 29
158 #define TOK_MEDIAN 30
159 #define TOK_STDEV 31
160 #define TOK_sMAX 32
161 #define TOK_sMIN 33
162 #define TOK_sAVG 34
163 #define TOK_sMEDIAN 35
164 #define TOK_sSTDEV 36
165 #define TOK_sSUM 37
166 #define TOK_IN 38 // contains, e.g. FILTER~"A"
167 #define TOK_NOT_IN 39 // does not contain, e.g. FILTER!~"A"
168 #define TOK_MODULO 40 // %
169 #define TOK_EXT 41 // external values set before each filter_test_ext() call, can be one of {},{str},{int},{float}
170
171 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
172 // ( ) [ < = > ] ! | & + - * / M m a A O ~ ^ S . l f c p b P i s %
173 static int op_prec[] = {0,1,1,5,5,5,5,5,5,2,3, 6, 6, 7, 7, 8, 8, 8, 3, 2, 5, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 0};
174 #define TOKEN_STRING "x()[<=>]!|&+-*/MmaAO~^S.lfcpis" // this is only for debugging, not maintained diligently
175
176 static void cmp_vector_strings(token_t *atok, token_t *btok, token_t *rtok);
177 inline static void tok_init_samples(token_t *atok, token_t *btok, token_t *rtok);
178
179
180 // Return negative values if it is a function with variable number of arguments
181 static int filters_next_token(char **str, int *len)
182 {
183 char *tmp = *str;
184 while ( *tmp && isspace(*tmp) ) tmp++;
185 *str = tmp;
186 *len = 0;
187
188 // test for doubles: d.ddde[+-]dd
189 if ( isdigit(*str[0]) || *str[0]=='.' ) // strtod would eat +/-
190 {
191 double HTS_UNUSED v = strtod(*str, &tmp);
192 if ( *str!=tmp && (!tmp[0] || !isalnum(tmp[0])) )
193 {
194 *len = tmp - (*str);
195 return TOK_VAL;
196 }
197 tmp = *str;
198 }
199
200 if ( !strncasecmp(tmp,"SMPL_MAX(",9) ) { (*str) += 8; return TOK_sMAX; }
201 if ( !strncasecmp(tmp,"SMPL_MIN(",9) ) { (*str) += 8; return TOK_sMIN; }
202 if ( !strncasecmp(tmp,"SMPL_MEAN(",10) ) { (*str) += 9; return TOK_sAVG; }
203 if ( !strncasecmp(tmp,"SMPL_MEDIAN(",12) ) { (*str) += 11; return TOK_sMEDIAN; }
204 if ( !strncasecmp(tmp,"SMPL_AVG(",9) ) { (*str) += 8; return TOK_sAVG; }
205 if ( !strncasecmp(tmp,"SMPL_STDEV(",11) ) { (*str) += 10; return TOK_sSTDEV; }
206 if ( !strncasecmp(tmp,"SMPL_SUM(",9) ) { (*str) += 8; return TOK_sSUM; }
207 if ( !strncasecmp(tmp,"sMAX(",5) ) { (*str) += 4; return TOK_sMAX; }
208 if ( !strncasecmp(tmp,"sMIN(",5) ) { (*str) += 4; return TOK_sMIN; }
209 if ( !strncasecmp(tmp,"sMEAN(",6) ) { (*str) += 5; return TOK_sAVG; }
210 if ( !strncasecmp(tmp,"sMEDIAN(",8) ) { (*str) += 7; return TOK_sMEDIAN; }
211 if ( !strncasecmp(tmp,"sAVG(",5) ) { (*str) += 4; return TOK_sAVG; }
212 if ( !strncasecmp(tmp,"sSTDEV(",7) ) { (*str) += 6; return TOK_sSTDEV; }
213 if ( !strncasecmp(tmp,"sSUM(",5) ) { (*str) += 4; return TOK_sSUM; }
214 if ( !strncasecmp(tmp,"MAX(",4) ) { (*str) += 3; return TOK_MAX; }
215 if ( !strncasecmp(tmp,"MIN(",4) ) { (*str) += 3; return TOK_MIN; }
216 if ( !strncasecmp(tmp,"MEAN(",5) ) { (*str) += 4; return TOK_AVG; }
217 if ( !strncasecmp(tmp,"MEDIAN(",7) ) { (*str) += 6; return TOK_MEDIAN; }
218 if ( !strncasecmp(tmp,"AVG(",4) ) { (*str) += 3; return TOK_AVG; }
219 if ( !strncasecmp(tmp,"STDEV(",6) ) { (*str) += 5; return TOK_STDEV; }
220 if ( !strncasecmp(tmp,"SUM(",4) ) { (*str) += 3; return TOK_SUM; }
221 if ( !strncasecmp(tmp,"ABS(",4) ) { (*str) += 3; return TOK_ABS; }
222 if ( !strncasecmp(tmp,"COUNT(",4) ) { (*str) += 5; return TOK_CNT; }
223 if ( !strncasecmp(tmp,"STRLEN(",7) ) { (*str) += 6; return TOK_LEN; }
224 if ( !strncasecmp(tmp,"BINOM(",6) ) { (*str) += 5; return -TOK_BINOM; }
225 if ( !strncasecmp(tmp,"PHRED(",6) ) { (*str) += 5; return TOK_PHRED; }
226 if ( !strncasecmp(tmp,"%MAX(",5) ) { (*str) += 4; return TOK_MAX; } // for backward compatibility
227 if ( !strncasecmp(tmp,"%MIN(",5) ) { (*str) += 4; return TOK_MIN; } // for backward compatibility
228 if ( !strncasecmp(tmp,"%AVG(",5) ) { (*str) += 4; return TOK_AVG; } // for backward compatibility
229 if ( !strncasecmp(tmp,"%SUM(",5) ) { (*str) += 4; return TOK_SUM; } // for backward compatibility
230 if ( !strncasecmp(tmp,"INFO/",5) ) tmp += 5;
231 if ( !strncasecmp(tmp,"FORMAT/",7) ) tmp += 7;
232 if ( !strncasecmp(tmp,"FMT/",4) ) tmp += 4;
233 if ( !strncasecmp(tmp,"PERL.",5) ) { (*str) += 5; return -TOK_PERLSUB; }
234 if ( !strncasecmp(tmp,"N_PASS(",7) ) { *len = 6; (*str) += 6; return -TOK_FUNC; }
235 if ( !strncasecmp(tmp,"F_PASS(",7) ) { *len = 6; (*str) += 6; return -TOK_FUNC; }
236 if ( !strncasecmp(tmp,"%ILEN",5) ) { *len = 5; return TOK_VAL; } // to be able to distinguish between INFO/ILEN and on-the-fly ILEN
237 if ( !strncasecmp(tmp,"{}",2) ) { *len = 2; return TOK_EXT; }
238 if ( !strncasecmp(tmp,"{STR}",5) ) { *len = 5; return TOK_EXT; }
239 if ( !strncasecmp(tmp,"{INT}",5) ) { *len = 5; return TOK_EXT; }
240 if ( !strncasecmp(tmp,"{FLOAT}",7) ) { *len = 7; return TOK_EXT; }
241
242 if ( tmp[0]=='@' ) // file name
243 {
244 while ( *tmp && !isspace(*tmp) && *tmp!='=' && *tmp!='!' ) tmp++;
245 *len = tmp - (*str);
246 return TOK_VAL;
247 }
248
249 int square_brackets = 0;
250 while ( tmp[0] )
251 {
252 if ( !square_brackets )
253 {
254 if ( tmp[0]=='"' ) break;
255 if ( tmp[0]=='\'' ) break;
256 if ( isspace(tmp[0]) ) break;
257 if ( tmp[0]=='<' ) break;
258 if ( tmp[0]=='>' ) break;
259 if ( tmp[0]=='=' ) break;
260 if ( tmp[0]=='!' ) break;
261 if ( tmp[0]=='&' ) break;
262 if ( tmp[0]=='|' ) break;
263 if ( tmp[0]=='(' ) break;
264 if ( tmp[0]==')' ) break;
265 if ( tmp[0]=='+' ) break;
266 if ( tmp[0]=='*' ) break;
267 if ( tmp[0]=='-' ) break;
268 if ( tmp[0]=='/' ) break;
269 if ( tmp[0]=='~' ) break;
270 if ( tmp[0]=='%' ) break;
271 }
272 if ( tmp[0]==']' ) { if (square_brackets) tmp++; break; }
273 if ( tmp[0]=='[' ) square_brackets++;
274 tmp++;
275 }
276 if ( tmp > *str )
277 {
278 *len = tmp - (*str);
279 return TOK_VAL;
280 }
281 if ( tmp[0]=='"' || tmp[0]=='\'' )
282 {
283 int quote = tmp[0];
284 tmp++;
285 while ( *tmp && tmp[0]!=quote ) tmp++;
286 if ( !*tmp ) return -1; // missing quotes
287 *len = tmp - (*str) + 1;
288 return TOK_VAL;
289 }
290 if ( tmp[0]=='!' )
291 {
292 if ( tmp[1]=='=' ) { (*str) += 2; return TOK_NE; }
293 if ( tmp[1]=='~' ) { (*str) += 2; return TOK_NLIKE; }
294 }
295 if ( tmp[0]=='<' )
296 {
297 if ( tmp[1]=='=' ) { (*str) += 2; return TOK_LE; }
298 (*str) += 1; return TOK_LT;
299 }
300 if ( tmp[0]=='>' )
301 {
302 if ( tmp[1]=='=' ) { (*str) += 2; return TOK_BE; }
303 (*str) += 1; return TOK_BT;
304 }
305 if ( tmp[0]=='=' )
306 {
307 if ( tmp[1]=='=' ) { (*str) += 2; return TOK_EQ; }
308 (*str) += 1; return TOK_EQ;
309 }
310 if ( tmp[0]=='(' ) { (*str) += 1; return TOK_LFT; }
311 if ( tmp[0]==')' ) { (*str) += 1; return TOK_RGT; }
312 if ( tmp[0]=='&' && tmp[1]=='&' ) { (*str) += 2; return TOK_AND_VEC; }
313 if ( tmp[0]=='|' && tmp[1]=='|' ) { (*str) += 2; return TOK_OR_VEC; }
314 if ( tmp[0]=='&' ) { (*str) += 1; return TOK_AND; }
315 if ( tmp[0]=='|' ) { (*str) += 1; return TOK_OR; }
316 if ( tmp[0]=='+' ) { (*str) += 1; return TOK_ADD; }
317 if ( tmp[0]=='-' ) { (*str) += 1; return TOK_SUB; }
318 if ( tmp[0]=='*' ) { (*str) += 1; return TOK_MULT; }
319 if ( tmp[0]=='/' ) { (*str) += 1; return TOK_DIV; }
320 if ( tmp[0]=='~' ) { (*str) += 1; return TOK_LIKE; }
321 if ( tmp[0]=='%' ) { (*str) += 1; return TOK_MODULO; }
322
323 *len = tmp - (*str);
324 return TOK_VAL;
325 }
326
327 #define FILTER_OK 0
328 #define FILTER_ERR_UNKN_TAGS 1
329 #define FILTER_ERR_OTHER 2
330
331 static void filter_add_undef_tag(filter_t *filter, char *str)
332 {
333 int i;
334 for (i=0; i<filter->nundef_tag; i++)
335 if ( !strcmp(str,filter->undef_tag[i]) ) break;
336 if ( i<filter->nundef_tag ) return;
337 filter->nundef_tag++;
338 filter->undef_tag = (char**)realloc(filter->undef_tag,sizeof(*filter->undef_tag)*filter->nundef_tag);
339 if ( !filter->undef_tag ) error("Could not allocate memory\n");
340 filter->undef_tag[filter->nundef_tag-1] = strdup(str);
341 if ( !filter->undef_tag[filter->nundef_tag-1] ) error("Could not allocate memory\n");
342 }
343 const char **filter_list_undef_tags(filter_t *filter, int *ntags)
344 {
345 *ntags = filter->nundef_tag;
346 return (const char**)filter->undef_tag;
347 }
348 static void filter_add_used_tag(filter_t *filter, const char *prefix, char *str)
349 {
350 int i;
351 kstring_t tmp = {0,0,0};
352 if ( prefix ) kputs(prefix,&tmp);
353 kputs(str,&tmp);
354 for (i=0; i<filter->nused_tag; i++)
355 if ( !strcmp(tmp.s,filter->used_tag[i]) ) break;
356 if ( i<filter->nused_tag )
357 {
358 free(tmp.s);
359 return;
360 }
361
362 filter->nused_tag++;
363 filter->used_tag = (char**)realloc(filter->used_tag,sizeof(*filter->used_tag)*filter->nused_tag);
364 if ( !filter->used_tag ) error("Could not allocate memory\n");
365 filter->used_tag[filter->nused_tag-1] = tmp.s;
366 if ( !filter->used_tag[filter->nused_tag-1] ) error("Could not allocate memory\n");
367 }
368 const char **filter_list_used_tags(filter_t *filter, int *ntags)
369 {
370 *ntags = filter->nused_tag;
371 return (const char**)filter->used_tag;
372 }
373
374
375
376 /*
377 Simple path expansion, expands ~/, ~user, $var. The result must be freed by the caller.
378
379 Based on jkb's staden code with some adjustments.
380 https://sourceforge.net/p/staden/code/HEAD/tree/staden/trunk/src/Misc/getfile.c#l123
381 */
382 char *expand_path(char *path)
383 {
384 kstring_t str = {0,0,0};
385
386 if ( path[0] == '~' )
387 {
388 if ( !path[1] || path[1] == '/' )
389 {
390 #ifdef _WIN32
391 kputs(getenv("HOMEDRIVE"), &str);
392 kputs(getenv("HOMEPATH"), &str);
393 #else
394 // ~ or ~/path
395 kputs(getenv("HOME"), &str);
396 if ( path[1] ) kputs(path+1, &str);
397 #endif
398 }
399 #ifndef _WIN32
400 else
401 {
402 // user name: ~pd3/path
403 char *end = path;
404 while ( *end && *end!='/' ) end++;
405 kputsn(path+1, end-path-1, &str);
406 struct passwd *pwentry = getpwnam(str.s);
407 str.l = 0;
408
409 if ( !pwentry ) kputsn(path, end-path, &str);
410 else kputs(pwentry->pw_dir, &str);
411 kputs(end, &str);
412 }
413 #endif
414 return ks_release(&str);
415 }
416 if ( path[0] == '$' )
417 {
418 char *var = getenv(path+1);
419 if ( var ) {
420 kputs(var, &str);
421 return ks_release(&str);
422 }
423 }
424
425 return strdup(path);
426 }
427 static int filters_cache_genotypes(filter_t *flt, bcf1_t *line)
428 {
429 if ( flt->cached_GT.line==line ) return flt->cached_GT.nbuf > 0 ? 0 : -1;
430 flt->cached_GT.line = line;
431 flt->cached_GT.nbuf = bcf_get_genotypes(flt->hdr, line, &flt->cached_GT.buf, &flt->cached_GT.mbuf);
432 if ( flt->cached_GT.nbuf<=0 ) return -1;
433 if ( !flt->cached_GT.mask )
434 {
435 flt->cached_GT.mask = (uint64_t*) malloc(sizeof(*flt->cached_GT.mask)*flt->nsamples);
436 if ( !flt->cached_GT.mask ) error("Could not alloc %zu bytes\n",sizeof(*flt->cached_GT.mask)*flt->nsamples);
437 }
438 int i,j, ngt1 = flt->cached_GT.nbuf / line->n_sample;
439 for (i=0; i<line->n_sample; i++)
440 {
441 int32_t *ptr = flt->cached_GT.buf + i*ngt1;
442 flt->cached_GT.mask[i] = 0;
443 for (j=0; j<ngt1; j++)
444 {
445 if ( bcf_gt_is_missing(ptr[j]) ) continue;
446 if ( ptr[j]==bcf_int32_vector_end ) break;
447 int allele = bcf_gt_allele(ptr[j]);
448 if ( allele > 63 )
449 {
450 static int warned = 0;
451 if ( !warned )
452 {
453 fprintf(stderr,"Too many alleles, skipping GT filtering at this site %s:%"PRId64". "
454 "(This warning is printed only once.)\n", bcf_seqname(flt->hdr,line),line->pos+1);
455 warned = 1;
456 }
457 flt->cached_GT.nbuf = 0;
458 return -1;
459 }
460 flt->cached_GT.mask[i] |= 1<<allele;
461 }
462 }
463 return 0;
464 }
465
466 static void filters_set_qual(filter_t *flt, bcf1_t *line, token_t *tok)
467 {
468 float *ptr = &line->qual;
469 if ( bcf_float_is_missing(*ptr) )
470 bcf_double_set_missing(tok->values[0]);
471 else
472 tok->values[0] = (double)line->qual;
473 tok->nvalues = 1;
474 }
475 static void filters_set_type(filter_t *flt, bcf1_t *line, token_t *tok)
476 {
477 tok->values[0] = bcf_get_variant_types(line);
478 if ( !tok->values[0] ) tok->values[0] = 1; // mistake in htslib: VCF_* should start with 1
479 else tok->values[0] = ((int)tok->values[0]) << 1;
480 tok->nvalues = 1;
481 }
482 static void filters_set_info(filter_t *flt, bcf1_t *line, token_t *tok)
483 {
484 assert( tok->hdr_id >=0 );
485 int i;
486 for (i=0; i<line->n_info; i++)
487 if ( line->d.info[i].key == tok->hdr_id ) break;
488
489 if ( i==line->n_info )
490 tok->nvalues = tok->str_value.l = 0;
491 else if ( line->d.info[i].type==BCF_BT_CHAR )
492 {
493 int n = line->d.info[i].len;
494 if ( n >= tok->str_value.m )
495 {
496 tok->str_value.m = n + 1;
497 tok->str_value.s = (char*) realloc(tok->str_value.s, tok->str_value.m);
498 if ( !tok->str_value.s ) error("Failed to alloc %d bytes\n", (int)tok->str_value.m);
499 }
500 memcpy(tok->str_value.s, line->d.info[i].vptr, n);
501 tok->str_value.s[n] = 0;
502 tok->nvalues = tok->str_value.l = n;
503 }
504 else if ( line->d.info[i].type==BCF_BT_FLOAT )
505 {
506 if ( bcf_float_is_missing(line->d.info[i].v1.f) ) tok->nvalues = 0;
507 else
508 {
509 tok->values[0] = line->d.info[i].v1.f;
510 tok->nvalues = 1;
511 }
512 tok->str_value.l = 0;
513 }
514 else
515 {
516 tok->str_value.l = 0;
517 if ( line->d.info[i].type==BCF_BT_INT8 && line->d.info[i].v1.i==bcf_int8_missing ) tok->nvalues = 0;
518 else if ( line->d.info[i].type==BCF_BT_INT16 && line->d.info[i].v1.i==bcf_int16_missing ) tok->nvalues = 0;
519 else if ( line->d.info[i].type==BCF_BT_INT32 && line->d.info[i].v1.i==bcf_int32_missing ) tok->nvalues = 0;
520 else
521 {
522 tok->values[0] = line->d.info[i].v1.i;
523 tok->nvalues = 1;
524 }
525 }
526 }
527 static void filters_cmp_bit_and(token_t *atok, token_t *btok, token_t *rtok, bcf1_t *line)
528 {
529 int a = (int)(atok->nvalues?atok->values[0]:atok->threshold);
530 int b = (int)(btok->nvalues?btok->values[0]:btok->threshold);
531 if ( rtok->tok_type==TOK_LIKE )
532 rtok->pass_site = a&b ? 1 : 0;
533 else
534 rtok->pass_site = a&b ? 0 : 1;
535 }
536 static void filters_cmp_filter(token_t *atok, token_t *btok, token_t *rtok, bcf1_t *line)
537 {
538 // the btok values contain FILTER ids obtained by parsing the user expression
539 int i,j;
540 if ( rtok->tok_type==TOK_NOT_IN ) // fail if the query expression is a subset of the VCF FILTER
541 {
542 if ( !btok->nvalues ) // the query expression is ".", pass everything unless the VCF is also "."
543 {
544 if ( line->d.n_flt ) rtok->pass_site = 1;
545 return;
546 }
547 if ( !line->d.n_flt ) // no filters at this VCF line and the query expression has a value
548 {
549 rtok->pass_site = 1;
550 return;
551 }
552 for (j=0; j<btok->nvalues; j++) // some query expression value must be absent from VCF in order to pass
553 {
554 for (i=0; i<line->d.n_flt; i++)
555 if ( btok->values[j]==line->d.flt[i] ) break;
556 if ( i==line->d.n_flt ) break; // the query is not in the VCF
557 }
558 if ( j!=btok->nvalues ) rtok->pass_site = 1;
559 return;
560 }
561 else if ( rtok->tok_type==TOK_IN )
562 {
563 if ( !btok->nvalues ) // the query expression is ".", fail everything unless the VCF is also "."
564 {
565 if ( !line->d.n_flt ) rtok->pass_site = 1;
566 return;
567 }
568 if ( !line->d.n_flt ) return; // no filters at this VCF line and the query expression has a value
569 for (j=0; j<btok->nvalues; j++) // all of the query values must be present in the VCF in order to pass
570 {
571 for (i=0; i<line->d.n_flt; i++)
572 if ( btok->values[j]==line->d.flt[i] ) break;
573 if ( i==line->d.n_flt ) break; // the query is not in the VCF
574 }
575 if ( j==btok->nvalues ) rtok->pass_site = 1;
576 return;
577 }
578 else if ( rtok->tok_type==TOK_NE ) // require anything but exact match
579 {
580 if ( btok->nvalues != line->d.n_flt )
581 {
582 rtok->pass_site = 1;
583 return;
584 }
585 if ( !btok->nvalues ) return;
586 for (j=0; j<btok->nvalues; j++) // some of the query values must be absent from the VCF in order to pass
587 {
588 for (i=0; i<line->d.n_flt; i++)
589 if ( btok->values[j]==line->d.flt[i] ) break;
590 if ( i==line->d.n_flt ) break; // the query is not in the VCF
591 }
592 if ( j!=btok->nvalues ) rtok->pass_site = 1;
593 return;
594 }
595 else if ( rtok->tok_type==TOK_EQ ) // require exact match
596 {
597 if ( btok->nvalues != line->d.n_flt ) return;
598 if ( !btok->nvalues )
599 {
600 rtok->pass_site = 1;
601 return;
602 }
603 for (j=0; j<btok->nvalues; j++) // all of the query values must be present in the VCF in order to pass
604 {
605 for (i=0; i<line->d.n_flt; i++)
606 if ( btok->values[j]==line->d.flt[i] ) break;
607 if ( i==line->d.n_flt ) break; // the query is not in the VCF
608 }
609 if ( j==btok->nvalues ) rtok->pass_site = 1;
610 return;
611 }
612 else
613 error("Only ==, !=, ~, and !~ operators are supported for FILTER\n");
614 return;
615 }
616 static void filters_cmp_string_hash(token_t *atok, token_t *btok, token_t *rtok, bcf1_t *line)
617 {
618 if ( btok->hash )
619 {
620 token_t *tmp = atok; atok = btok; btok = tmp;
621 }
622 if ( rtok->tok_type!=TOK_EQ && rtok->tok_type!=TOK_NE )
623 error("Only == and != operators are supported for strings read from a file\n");
624
625 // INFO
626 if ( !btok->nsamples )
627 {
628 // there is only one string value, e.g. STR[1][email protected]
629 if ( btok->idx >= 0 )
630 {
631 int ret = btok->str_value.s ? khash_str2int_has_key(atok->hash, btok->str_value.s) : 0;
632 if ( rtok->tok_type==TOK_NE ) ret = ret ? 0 : 1;
633 rtok->pass_site = ret;
634 return;
635 }
636
637 // there can be multiple comma-separated string values, e.g. [email protected] or STR[*][email protected]
638 int ret = 0;
639 char *ptr = btok->str_value.s;
640 while ( *ptr )
641 {
642 char *eptr = ptr + 1;
643 while ( *eptr && *eptr!=',' ) eptr++;
644 char keep = *eptr;
645 *eptr = 0;
646 ret |= khash_str2int_has_key(atok->hash, ptr);
647 *eptr = keep;
648 if ( !keep ) break;
649 ptr = eptr + 1;
650 }
651 if ( rtok->tok_type==TOK_NE ) ret = ret ? 0 : 1;
652 rtok->pass_site = ret;
653 return;
654 }
655
656
657 // FORMAT
658 tok_init_samples(atok, btok, rtok);
659 rtok->pass_site = 0;
660 int i;
661
662 // there is only one string value, e.g. FMT/STR[*:1][email protected]
663 if ( btok->idx >= 0 )
664 {
665 for (i=0; i<btok->nsamples; i++)
666 {
667 if ( !rtok->usmpl[i] ) continue;
668 char *str = btok->str_value.s + i*btok->nval1;
669 char keep = str[btok->nval1];
670 str[btok->nval1] = 0;
671 int ret = khash_str2int_has_key(atok->hash, str);
672 str[btok->nval1] = keep;
673 if ( rtok->tok_type==TOK_NE ) ret = ret ? 0 : 1;
674 rtok->pass_samples[i] = ret;
675 rtok->pass_site |= ret;
676 }
677 return;
678 }
679
680 // there can be multiple comma-separated string values, e.g. FMT/[email protected]
681 for (i=0; i<btok->nsamples; i++)
682 {
683 if ( !rtok->usmpl[i] ) continue;
684 char *str = btok->str_value.s + i*btok->nval1;
685 char keep = str[btok->nval1];
686 str[btok->nval1] = 0;
687
688 // now str contains the block of per-sample comma-separated strings to loop over
689 int ret = 0;
690 char *ptr = str;
691 while ( *ptr )
692 {
693 char *eptr = ptr + 1;
694 while ( *eptr && *eptr!=',' ) eptr++;
695 char keep0 = *eptr;
696 *eptr = 0;
697 ret |= khash_str2int_has_key(atok->hash, ptr);
698 *eptr = keep0;
699 if ( !keep0 ) break;
700 ptr = eptr + 1;
701 }
702 str[btok->nval1] = keep;
703 if ( rtok->tok_type==TOK_NE ) ret = ret ? 0 : 1;
704 rtok->pass_samples[i] = ret;
705 rtok->pass_site |= ret;
706 }
707 }
708 static void filters_cmp_id(token_t *atok, token_t *btok, token_t *rtok, bcf1_t *line)
709 {
710 if ( btok->hash )
711 {
712 token_t *tmp = atok; atok = btok; btok = tmp;
713 }
714
715 char *id = line->d.id;
716 int pass = 0;
717
718 while ( id )
719 {
720 char *ep = strchr(id,';');
721 if ( ep ) *ep = 0;
722
723 if ( atok->hash )
724 {
725 if ( rtok->tok_type!=TOK_EQ && rtok->tok_type!=TOK_NE )
726 error("Only == and != operators are supported for strings read from a file\n");
727
728 pass = khash_str2int_has_key(atok->hash, id);
729 }
730 else
731 {
732 if ( !btok->str_value.l ) error("Error occurred while evaluating the expression\n");
733
734 if ( rtok->tok_type==TOK_EQ || rtok->tok_type==TOK_NE )
735 pass = strcmp(btok->str_value.s,id) ? 0 : 1;
736 else
737 {
738 if ( rtok->tok_type!=TOK_LIKE && rtok->tok_type!=TOK_NLIKE )
739 error("Only the following operators are supported for querying ID: ==, !=, ~, !~; the operator type %d is not supported (%p %p)\n",
740 rtok->tok_type,atok->regex,btok->regex);
741
742 regex_t *regex = atok->regex ? atok->regex : (btok->regex ? btok->regex : NULL);
743 if ( !regex ) error("fixme: regex initialization failed\n");
744 pass = regexec(regex,id, 0,NULL,0) ? 0 : 1;
745 }
746 }
747 if ( ep )
748 {
749 *ep = ';';
750 id = ep + 1;
751 }
752 if ( pass || !ep ) break;
753 }
754 if ( rtok->tok_type==TOK_NE || rtok->tok_type==TOK_NE) pass = pass ? 0 : 1;
755 rtok->pass_site = pass;
756 }
757
758 /**
759 * bcf_get_info_value() - get single INFO value, int64_t or double
760 * @line: BCF line
761 * @info_id: tag ID, as returned by bcf_hdr_id2int
762 * @ivec: 0-based index to retrieve, -1 when single value is expected
763 * @vptr: pointer to memory location of sufficient size to accommodate
764 * info_id's type
765 *
766 * The returned value is -1 if tag is not present, 0 if present but
767 * values is missing or ivec is out of range, and 1 on success.
768 */
769 static int bcf_get_info_value(bcf1_t *line, int info_id, int ivec, void *value)
770 {
771 int j;
772 for (j=0; j<line->n_info; j++)
773 if ( line->d.info[j].key == info_id ) break;
774 if ( j==line->n_info ) return -1;
775
776 bcf_info_t *info = &line->d.info[j];
777 if ( info->len == 1 )
778 {
779 if ( info->type==BCF_BT_FLOAT ) *((double*)value) = info->v1.f;
780 else if ( info->type==BCF_BT_INT8 || info->type==BCF_BT_INT16 || info->type==BCF_BT_INT32 ) *((int64_t*)value) = info->v1.i;
781 return 1;
782 }
783
784 if ( ivec<0 ) ivec = 0;
785 if ( ivec>=info->len) return 0;
786
787 #define BRANCH(type_t, convert, is_missing, is_vector_end, out_type_t) { \
788 uint8_t *p = info->vptr; \
789 for (j=0; j<ivec; j++) \
790 { \
791 type_t val = convert(&p[j * sizeof(type_t)]); \
792 if ( is_vector_end ) return 0; \
793 } \
794 type_t val = convert(&p[ivec * sizeof(type_t)]); \
795 if ( is_missing ) return 0; \
796 *((out_type_t*)value) = val; \
797 return 1; \
798 }
799 switch (info->type) {
800 case BCF_BT_INT8: BRANCH(int8_t, le_to_i8, val==bcf_int8_missing, val==bcf_int8_vector_end, int64_t); break;
801 case BCF_BT_INT16: BRANCH(int16_t, le_to_i16, val==bcf_int16_missing, val==bcf_int16_vector_end, int64_t); break;
802 case BCF_BT_INT32: BRANCH(int32_t, le_to_i32, val==bcf_int32_missing, val==bcf_int32_vector_end, int64_t); break;
803 case BCF_BT_FLOAT: BRANCH(float, le_to_float, bcf_float_is_missing(val), bcf_float_is_vector_end(val), double); break;
804 default: fprintf(stderr,"todo: type %d\n", info->type); exit(1); break;
805 }
806 #undef BRANCH
807 return -1; // this shouldn't happen
808 }
809
810 static void filters_set_chrom(filter_t *flt, bcf1_t *line, token_t *tok)
811 {
812 tok->str_value.l = 0;
813 kputs(bcf_seqname(flt->hdr,line), &tok->str_value);
814 tok->nvalues = tok->str_value.l;
815 tok->is_str = 1;
816 }
817
818 static void filters_set_pos(filter_t *flt, bcf1_t *line, token_t *tok)
819 {
820 tok->values[0] = line->pos+1;
821 tok->nvalues = 1;
822 }
823
824 static void filters_set_info_int(filter_t *flt, bcf1_t *line, token_t *tok)
825 {
826 if ( tok->idx==-2 )
827 {
828 tok->nvalues = bcf_get_info_int32(flt->hdr,line,tok->tag,&flt->tmpi,&flt->mtmpi);
829 if ( tok->nvalues<=0 ) tok->nvalues = 0;
830 else
831 {
832 hts_expand(double,tok->nvalues,tok->mvalues,tok->values);
833 int i, j = 0, end = tok->idxs[tok->nidxs-1] < 0 ? tok->nvalues - 1 : tok->nidxs - 1;
834 if ( end >= tok->nvalues ) end = tok->nvalues - 1;
835 for (i=0; i<=end; i++)
836 if ( i>=tok->nidxs || tok->idxs[i] ) tok->values[j++] = flt->tmpi[i];
837 tok->nvalues = j;
838 }
839 }
840 else
841 {
842 int64_t value = 0;
843 if ( bcf_get_info_value(line,tok->hdr_id,tok->idx,&value) <= 0 )
844 tok->nvalues = 0;
845 else
846 {
847 tok->values[0] = value;
848 tok->nvalues = 1;
849 }
850 }
851 }
852
853 static void filters_set_info_float(filter_t *flt, bcf1_t *line, token_t *tok)
854 {
855 if ( tok->idx==-2 )
856 {
857 tok->nvalues = bcf_get_info_float(flt->hdr,line,tok->tag,&flt->tmpf,&flt->mtmpf);
858 if ( tok->nvalues<=0 ) tok->nvalues = 0;
859 else
860 {
861 hts_expand(double,tok->nvalues,tok->mvalues,tok->values);
862 int i, j = 0, end = tok->idxs[tok->nidxs-1] < 0 ? tok->nvalues - 1 : tok->nidxs - 1;
863 if ( end >= tok->nvalues ) end = tok->nvalues - 1;
864 for (i=0; i<=end; i++)
865 if ( i>=tok->nidxs || tok->idxs[i] )
866 {
867 if ( bcf_float_is_missing(flt->tmpf[i]) ) bcf_double_set_missing(tok->values[j]);
868 else tok->values[j] = flt->tmpf[i];
869 j++;
870 }
871 tok->nvalues = j;
872 }
873 }
874 else
875 {
876 double value;
877 if ( bcf_get_info_value(line,tok->hdr_id,tok->idx,&value) <= 0 )
878 tok->nvalues = 0;
879 else
880 {
881 tok->values[0] = value;
882 tok->nvalues = 1;
883 }
884 }
885 }
886
887 static void filters_set_info_string(filter_t *flt, bcf1_t *line, token_t *tok)
888 {
889 int32_t m = tok->str_value.m;
890 int n = bcf_get_info_string(flt->hdr,line,tok->tag,&tok->str_value.s,&m);
891 tok->str_value.m = m;
892 if ( n<0 ) { tok->nvalues = tok->str_value.l = 0; return; }
893
894 if ( tok->idx>=0 )
895 {
896 // get ith field (i=tok->idx)
897 int i = 0;
898 char *ss = tok->str_value.s, *se = tok->str_value.s + n;
899 while ( ss<se && i<tok->idx )
900 {
901 if ( *ss==',' ) i++;
902 ss++;
903 }
904 if ( ss==se || i!=tok->idx ) { tok->nvalues = tok->str_value.l = 0; return; }
905 se = ss;
906 while ( se - tok->str_value.s < n && *se!=',' ) se++;
907 if ( ss==tok->str_value.s ) *se = 0;
908 else
909 {
910 memmove(tok->str_value.s, ss, se-ss);
911 tok->str_value.s[se-ss] = 0;
912 }
913 tok->str_value.l = se - ss;
914 }
915 else if ( tok->idx==-2 && tok->idxs[0]==-1 ) // keep all values, TAG[*]
916 tok->str_value.l = n;
917 else if ( tok->idx==-2 )
918 {
919 flt->tmps.l = 0;
920 ks_resize(&flt->tmps, n);
921 int i, iend = tok->idxs[tok->nidxs-1] < 0 ? n - 1 : tok->nidxs - 1;
922 if ( iend >= n ) iend = n - 1;
923 char *beg = tok->str_value.s, *dst = flt->tmps.s;
924 for (i=0; i<=iend; i++)
925 {
926 char *end = beg;
927 while ( *end && *end!=',' ) end++;
928 if ( i>=tok->nidxs || tok->idxs[i] )
929 {
930 memcpy(dst, beg, end - beg);
931 dst += end - beg;
932 dst[0] = ',';
933 dst++;
934 }
935 beg = end+1;
936 }
937 dst[0] = 0;
938 tok->str_value.l = dst - flt->tmps.s;
939
940 #define SWAP(type_t, a, b) { type_t t = a; a = b; b = t; }
941 SWAP(char *, flt->tmps.s, tok->str_value.s);
942 SWAP(size_t, flt->tmps.m, tok->str_value.m);
943 }
944 tok->nvalues = tok->str_value.l;
945 }
946
947 static void filters_set_info_flag(filter_t *flt, bcf1_t *line, token_t *tok)
948 {
949 int j;
950 for (j=0; j<line->n_info; j++)
951 if ( line->d.info[j].key == tok->hdr_id ) break;
952 tok->values[0] = j==line->n_info ? 0 : 1;
953 tok->nvalues = 1;
954 }
955
956 static void filters_set_format_int(filter_t *flt, bcf1_t *line, token_t *tok)
957 {
958 if ( line->n_sample != tok->nsamples )
959 error("Incorrect number of FORMAT fields at %s:%"PRId64" .. %s, %d vs %d\n", bcf_seqname(flt->hdr,line),(int64_t) line->pos+1,tok->tag,line->n_sample,tok->nsamples);
960
961 int nvals;
962 if ( (nvals=bcf_get_format_int32(flt->hdr,line,tok->tag,&flt->tmpi,&flt->mtmpi))<0 )
963 {
964 tok->nvalues = 0;
965 return;
966 }
967 int i, nsrc1 = nvals / tok->nsamples;
968 tok->nval1 = tok->idx >= 0 ? 1 : (tok->nuidxs ? tok->nuidxs : nsrc1);
969 tok->nvalues = tok->nval1*tok->nsamples;
970 hts_expand(double, tok->nvalues, tok->mvalues, tok->values);
971
972 if ( tok->idx >= 0 ) // scalar or vector index
973 {
974 for (i=0; i<tok->nsamples; i++)
975 {
976 if ( !tok->usmpl[i] ) continue;
977 int32_t *ptr = flt->tmpi + i*nsrc1;
978 if ( tok->idx>=nsrc1 || ptr[tok->idx]==bcf_int32_missing )
979 bcf_double_set_missing(tok->values[i]);
980 else if ( ptr[tok->idx]==bcf_int32_vector_end )
981 bcf_double_set_vector_end(tok->values[i]);
982 else
983 tok->values[i] = ptr[tok->idx];
984 }
985 }
986 else if ( tok->idx==-3 )
987 {
988 if ( filters_cache_genotypes(flt,line)!=0 )
989 {
990 tok->nvalues = 0;
991 return;
992 }
993 for (i=0; i<tok->nsamples; i++)
994 {
995 if ( !tok->usmpl[i] ) continue;
996 int32_t *src = flt->tmpi + i*nsrc1;
997 double *dst = tok->values + i*tok->nval1;
998 int k, j = 0;
999 for (k=0; k<nsrc1; k++) // source values are AD[0..nsrc1]
1000 {
1001 if ( !(flt->cached_GT.mask[i] & (1<<k)) ) continue;
1002 dst[j++] = src[k];
1003 }
1004 if ( !j ) { bcf_double_set_missing(dst[j]); j++; }
1005 for (; j<tok->nval1; j++) bcf_double_set_vector_end(dst[j]);
1006 }
1007 }
1008 else
1009 {
1010 int kend = tok->idxs[tok->nidxs-1] < 0 ? tok->nval1 : tok->nidxs;
1011 for (i=0; i<tok->nsamples; i++)
1012 {
1013 if ( !tok->usmpl[i] ) continue;
1014 int32_t *src = flt->tmpi + i*nsrc1;
1015 double *dst = tok->values + i*tok->nval1;
1016 int k, j = 0;
1017 for (k=0; k<kend; k++)
1018 {
1019 if ( k<tok->nidxs && !tok->idxs[k] ) continue;
1020 if ( src[k]==bcf_int32_missing )
1021 bcf_double_set_missing(dst[j]);
1022 else if ( src[k]==bcf_int32_vector_end )
1023 bcf_double_set_vector_end(dst[j]);
1024 else
1025 dst[j] = src[k];
1026 j++;
1027 }
1028 if ( j==0 )
1029 {
1030 bcf_double_set_missing(dst[j]);
1031 j++;
1032 }
1033 while (j < tok->nval1)
1034 {
1035 bcf_double_set_vector_end(dst[j]);
1036 j++;
1037 }
1038 }
1039 }
1040 }
1041 static void filters_set_format_float(filter_t *flt, bcf1_t *line, token_t *tok)
1042 {
1043 if ( line->n_sample != tok->nsamples )
1044 error("Incorrect number of FORMAT fields at %s:%"PRId64" .. %s, %d vs %d\n", bcf_seqname(flt->hdr,line),(int64_t) line->pos+1,tok->tag,line->n_sample,tok->nsamples);
1045
1046 int nvals;
1047 if ( (nvals=bcf_get_format_float(flt->hdr,line,tok->tag,&flt->tmpf,&flt->mtmpf))<0 )
1048 {
1049 tok->nvalues = 0;
1050 return;
1051 }
1052 int i, nsrc1 = nvals / tok->nsamples;
1053 tok->nval1 = tok->idx >= 0 ? 1 : (tok->nuidxs ? tok->nuidxs : nsrc1);
1054 tok->nvalues = tok->nval1*tok->nsamples;
1055 hts_expand(double, tok->nvalues, tok->mvalues, tok->values);
1056
1057 if ( tok->idx >= 0 ) // scalar or vector index
1058 {
1059 for (i=0; i<tok->nsamples; i++)
1060 {
1061 if ( !tok->usmpl[i] ) continue;
1062 float *ptr = flt->tmpf + i*nsrc1;
1063 if ( tok->idx>=nsrc1 || bcf_float_is_missing(ptr[tok->idx]) )
1064 bcf_double_set_missing(tok->values[i]);
1065 else if ( bcf_float_is_vector_end(ptr[tok->idx]) )
1066 bcf_double_set_vector_end(tok->values[i]);
1067 else
1068 tok->values[i] = ptr[tok->idx];
1069 }
1070 }
1071 else if ( tok->idx==-3 )
1072 {
1073 if ( filters_cache_genotypes(flt,line)!=0 )
1074 {
1075 tok->nvalues = 0;
1076 return;
1077 }
1078 for (i=0; i<tok->nsamples; i++)
1079 {
1080 if ( !tok->usmpl[i] ) continue;
1081 float *src = flt->tmpf + i*nsrc1;
1082 double *dst = tok->values + i*tok->nval1;
1083 int k, j = 0;
1084 for (k=0; k<nsrc1; k++) // source values are AF[0..nsrc1]
1085 {
1086 if ( !(flt->cached_GT.mask[i] & (1<<k)) ) continue;
1087 if ( bcf_float_is_missing(src[k]) )
1088 bcf_double_set_missing(dst[j]);
1089 else if ( bcf_float_is_vector_end(src[k]) )
1090 bcf_double_set_vector_end(dst[j]);
1091 else
1092 dst[j] = src[k];
1093 j++;
1094 }
1095 if ( !j ) { bcf_double_set_missing(dst[j]); j++; }
1096 for (; j<tok->nval1; j++) bcf_double_set_vector_end(dst[j]);
1097 }
1098 }
1099 else
1100 {
1101 int kend = tok->idxs[tok->nidxs-1] < 0 ? tok->nval1 : tok->nidxs;
1102 for (i=0; i<tok->nsamples; i++)
1103 {
1104 if ( !tok->usmpl[i] ) continue;
1105 float *src = flt->tmpf + i*nsrc1;
1106 double *dst = tok->values + i*tok->nval1;
1107 int k, j = 0;
1108 for (k=0; k<kend; k++)
1109 {
1110 if ( k<tok->nidxs && !tok->idxs[k] ) continue;
1111 if ( bcf_float_is_missing(src[k]) )
1112 bcf_double_set_missing(dst[j]);
1113 else if ( bcf_float_is_vector_end(src[k]) )
1114 bcf_double_set_vector_end(dst[j]);
1115 else
1116 dst[j] = src[k];
1117 j++;
1118 }
1119 if ( j==0 )
1120 {
1121 bcf_double_set_missing(dst[j]);
1122 j++;
1123 }
1124 while (j < tok->nval1)
1125 {
1126 bcf_double_set_vector_end(dst[j]);
1127 j++;
1128 }
1129 }
1130 }
1131 }
1132 static void filters_set_format_string(filter_t *flt, bcf1_t *line, token_t *tok)
1133 {
1134 if ( line->n_sample != tok->nsamples )
1135 error("Incorrect number of FORMAT fields at %s:%"PRId64" .. %s, %d vs %d\n", bcf_seqname(flt->hdr,line),(int64_t) line->pos+1,tok->tag,line->n_sample,tok->nsamples);
1136
1137 int i, ndim = tok->str_value.m;
1138 int nstr = bcf_get_format_char(flt->hdr, line, tok->tag, &tok->str_value.s, &ndim);
1139 tok->str_value.m = tok->str_value.l = ndim;
1140 kputc(0,&tok->str_value); // append the nul byte
1141 tok->str_value.l = tok->nvalues = 0;
1142
1143 if ( nstr<0 ) return;
1144
1145 if ( tok->idx==-3 && filters_cache_genotypes(flt,line)!=0 ) return;
1146
1147 tok->nvalues = tok->str_value.l = nstr;
1148 tok->nval1 = nstr / tok->nsamples;
1149 for (i=0; i<tok->nsamples; i++)
1150 {
1151 if ( !tok->usmpl[i] ) continue;
1152 char *src = tok->str_value.s + i*tok->nval1, *dst = src;
1153 int ibeg = 0;
1154 int idx = 0; // idx-th field
1155 while ( ibeg < tok->nval1 )
1156 {
1157 int iend = ibeg;
1158 while ( iend < tok->nval1 && src[iend] && src[iend]!=',' ) iend++;
1159
1160 int keep = 0;
1161 if ( tok->idx >= 0 ) // single index, given explicitly, e.g. AD[:1]
1162 {
1163 if ( tok->idx==idx ) keep = 1;
1164 }
1165 else if ( tok->idx == -3 ) // given by GT index, e.g. AD[:GT]
1166 {
1167 if ( flt->cached_GT.mask[i] & (1<<idx) ) keep = 1;
1168 }
1169 else // given as a list, e.g. AD[:0,3]
1170 {
1171 if ( idx < tok->nidxs )
1172 {
1173 if ( tok->idxs[idx] != 0 ) keep = 1;
1174 }
1175 else if ( tok->idxs[tok->nidxs-1] < 0 )
1176 keep = 1;
1177 }
1178 if ( keep )
1179 {
1180 if ( ibeg!=0 ) memmove(dst, src+ibeg, iend-ibeg+1);
1181 dst += iend - ibeg + 1;
1182 if ( tok->idx>=0 ) break;
1183 }
1184 if ( !src[iend] ) break;
1185 ibeg = iend + 1;
1186 idx++;
1187 }
1188 if ( dst==src ) { dst[0] = '.'; dst+=2; }
1189 if ( dst - src < tok->nval1 ) memset(dst-1, 0, tok->nval1 - (dst - src));
1190 }
1191 }
1192 static void _filters_set_genotype(filter_t *flt, bcf1_t *line, token_t *tok, int type)
1193 {
1194 bcf_fmt_t *fmt = bcf_get_fmt(flt->hdr, line, "GT");
1195 if ( !fmt )
1196 {
1197 tok->nvalues = tok->str_value.l = 0;
1198 return;
1199 }
1200
1201 int i,j, nsmpl = bcf_hdr_nsamples(flt->hdr), nvals1 = type==2 ? 3 : 4;
1202 if ( tok->str_value.m <= nvals1*nsmpl )
1203 {
1204 tok->str_value.m = nvals1*nsmpl + 1;
1205 tok->str_value.s = (char*)realloc(tok->str_value.s, tok->str_value.m);
1206 }
1207
1208 #define BRANCH_INT(type_t, convert, vector_end) \
1209 { \
1210 for (i=0; i<line->n_sample; i++) \
1211 { \
1212 uint8_t *ptr = fmt->p + i*fmt->size; \
1213 int is_het = 0, has_ref = 0, missing = 0, jal = 0; \
1214 for (j=0; j<fmt->n; j++) \
1215 { \
1216 type_t ial = convert(&ptr[j * sizeof(type_t)]); \
1217 if ( ial==vector_end ) break; /* smaller ploidy */ \
1218 if ( bcf_gt_is_missing(ial) ) { missing=1; break; } /* missing allele */ \
1219 if ( bcf_gt_allele(ial)==0 ) has_ref = 1; \
1220 if ( j>0 ) \
1221 { \
1222 if ( bcf_gt_allele(ial)!=bcf_gt_allele(jal) ) is_het = 1; \
1223 } \
1224 jal = ial; \
1225 } \
1226 char *dst = &tok->str_value.s[nvals1*i]; \
1227 if ( type==4 ) \
1228 { \
1229 if ( !j || missing ) dst[0]='m', dst[1]='i', dst[2]='s', dst[3] = 0; /* mis, missing genotype */ \
1230 else if ( !has_ref ) dst[0]='a', dst[1]='l', dst[2]='t', dst[3] = 0; /* alt, no ref, must have alt allele */ \
1231 else if ( !is_het ) dst[0]='r', dst[1]='e', dst[2]='f', dst[3] = 0; /* ref, must be ref-only, no alt alelle */ \
1232 else dst[0]='a', dst[1]='l', dst[2]='t', dst[3] = 0; /* alt, is het, has alt allele */ \
1233 } \
1234 else if ( !j || missing ) dst[0]='.', dst[1]=0; /* ., missing genotype */ \
1235 else if ( type==3 ) \
1236 { \
1237 if ( j==1 ) dst[0]='h', dst[1]='a', dst[2]='p', dst[3] = 0; /* hap, haploid */ \
1238 else if ( !is_het ) dst[0]='h', dst[1]='o', dst[2]='m', dst[3] = 0; /* hom */ \
1239 else dst[0]='h', dst[1]='e', dst[2]='t', dst[3] = 0; /* het */ \
1240 } \
1241 else \
1242 { \
1243 if ( j==1 ) \
1244 { \
1245 if ( has_ref ) dst[0]='r', dst[1]=0; /* r, haploid */ \
1246 else dst[0]='a', dst[1]=0; /* a, haploid */ \
1247 } \
1248 else if ( !is_het ) \
1249 { \
1250 if ( has_ref ) dst[0]='r', dst[1]='r', dst[2] = 0; /* rr */ \
1251 else dst[0]='a', dst[1]='a', dst[2] = 0; /* aa */ \
1252 } \
1253 else \
1254 { \
1255 if ( has_ref ) dst[0]='r', dst[1]='a', dst[2] = 0; /* ra */ \
1256 else dst[0]='a', dst[1]='A', dst[2] = 0; /* aA */ \
1257 } \
1258 } \
1259 } \
1260 }
1261 switch (fmt->type) {
1262 case BCF_BT_INT8: BRANCH_INT(int8_t, le_to_i8, bcf_int8_vector_end); break;
1263 case BCF_BT_INT16: BRANCH_INT(int16_t, le_to_i16, bcf_int16_vector_end); break;
1264 case BCF_BT_INT32: BRANCH_INT(int32_t, le_to_i32, bcf_int32_vector_end); break;
1265 default: error("The GT type is not lineognised: %d at %s:%"PRId64"\n",fmt->type, bcf_seqname(flt->hdr,line),(int64_t) line->pos+1); break;
1266 }
1267 #undef BRANCH_INT
1268 assert( tok->nsamples == nsmpl );
1269 tok->nvalues = tok->str_value.l = nvals1*nsmpl;
1270 tok->str_value.s[tok->str_value.l] = 0;
1271 tok->nval1 = nvals1;
1272 }
1273 static void filters_set_genotype2(filter_t *flt, bcf1_t *line, token_t *tok) { _filters_set_genotype(flt, line, tok, 2); } // rr, ra, aa, aA etc
1274 static void filters_set_genotype3(filter_t *flt, bcf1_t *line, token_t *tok) { _filters_set_genotype(flt, line, tok, 3); } // hap, hom, het
1275 static void filters_set_genotype4(filter_t *flt, bcf1_t *line, token_t *tok) { _filters_set_genotype(flt, line, tok, 4); } // mis, alt, ref
1276
1277 static void filters_set_genotype_string(filter_t *flt, bcf1_t *line, token_t *tok)
1278 {
1279 bcf_fmt_t *fmt = bcf_get_fmt(flt->hdr, line, "GT");
1280 if ( !fmt )
1281 {
1282 tok->nvalues = 0;
1283 return;
1284 }
1285 int i, blen = 4, nsmpl = line->n_sample;
1286
1287 gt_length_too_big:
1288 tok->str_value.l = 0;
1289 for (i=0; i<nsmpl; i++)
1290 {
1291 size_t plen = tok->str_value.l;
1292 bcf_format_gt(fmt, i, &tok->str_value);
1293 kputc_(0, &tok->str_value);
1294 if ( tok->str_value.l - plen > blen )
1295 {
1296 // too many alternate alleles or ploidy is too large, the genotype does not fit
1297 // three characters ("0/0" vs "10/10").
1298 blen *= 2;
1299 goto gt_length_too_big;
1300 }
1301
1302 plen = tok->str_value.l - plen;
1303 while ( plen < blen )
1304 {
1305 kputc_(0, &tok->str_value);
1306 plen++;
1307 }
1308 }
1309 assert( tok->nsamples == nsmpl );
1310 tok->nvalues = tok->str_value.l;
1311 tok->nval1 = blen;
1312 }
1313 static void filters_set_ilen(filter_t *flt, bcf1_t *line, token_t *tok)
1314 {
1315 tok->nvalues = line->n_allele - 1;
1316 hts_expand(double,tok->nvalues,tok->mvalues,tok->values);
1317
1318 int i, rlen = strlen(line->d.allele[0]);
1319 for (i=1; i<line->n_allele; i++)
1320 {
1321 if ( line->d.allele[i][0]=='<' )
1322 {
1323 bcf_double_set_missing(tok->values[i-1]);
1324 continue;
1325 }
1326 int alen = strlen(line->d.allele[i]);
1327 tok->values[i-1] = alen - rlen;
1328 }
1329 }
1330 static void filters_set_ref_string(filter_t *flt, bcf1_t *line, token_t *tok)
1331 {
1332 tok->str_value.l = 0;
1333 kputs(line->d.allele[0], &tok->str_value);
1334 tok->nvalues = tok->str_value.l;
1335 }
1336 static void filters_set_alt_string(filter_t *flt, bcf1_t *line, token_t *tok)
1337 {
1338 tok->str_value.l = 0;
1339 if ( tok->idx>=0 )
1340 {
1341 if ( line->n_allele > tok->idx + 1 )
1342 kputs(line->d.allele[tok->idx + 1], &tok->str_value);
1343 else
1344 kputc('.', &tok->str_value);
1345 }
1346 else if ( tok->idx==-2 )
1347 {
1348 int i, end = tok->nuidxs ? tok->nuidxs : line->n_allele - 1;
1349 if ( end >= line->n_allele - 1 ) end = line->n_allele - 2;
1350 for (i=0; i<=end; i++)
1351 if ( i>=tok->nidxs || tok->idxs[i] )
1352 {
1353 if ( tok->str_value.l ) kputc(',', &tok->str_value);
1354 kputs(line->d.allele[i+1], &tok->str_value);
1355 }
1356 }
1357 else if ( line->n_allele>1 )
1358 {
1359 kputs(line->d.allele[1], &tok->str_value);
1360 int i;
1361 for (i=2; i<line->n_allele; i++)
1362 {
1363 kputc(',', &tok->str_value);
1364 kputs(line->d.allele[i], &tok->str_value);
1365 }
1366 }
1367 else if ( line->n_allele==1 )
1368 kputc('.', &tok->str_value);
1369 tok->nvalues = tok->str_value.l;
1370 }
1371 static void filters_set_nmissing(filter_t *flt, bcf1_t *line, token_t *tok)
1372 {
1373 bcf_unpack(line, BCF_UN_FMT);
1374 if ( !line->n_sample )
1375 {
1376 tok->nvalues = 1;
1377 tok->values[0] = 0;
1378 return;
1379 }
1380
1381 int i,igt = bcf_hdr_id2int(flt->hdr, BCF_DT_ID, "GT");
1382 bcf_fmt_t *fmt = NULL;
1383 for (i=0; i<line->n_fmt; i++)
1384 if ( line->d.fmt[i].id==igt ) { fmt = &line->d.fmt[i]; break; }
1385 if ( !fmt )
1386 {
1387 tok->nvalues = 0;
1388 return;
1389 }
1390
1391 int j,nmissing = 0;
1392 #define BRANCH(type_t, convert, is_vector_end) { \
1393 for (i=0; i<line->n_sample; i++) \
1394 { \
1395 uint8_t *ptr = fmt->p + i*fmt->size; \
1396 for (j=0; j<fmt->n; j++) \
1397 { \
1398 type_t val = convert(&ptr[j * sizeof(type_t)]); \
1399 if ( val==is_vector_end ) break; \
1400 if ( val==bcf_gt_missing ) { nmissing++; break; } \
1401 } \
1402 } \
1403 }
1404 switch (fmt->type) {
1405 case BCF_BT_INT8: BRANCH(int8_t, le_to_i8, bcf_int8_vector_end); break;
1406 case BCF_BT_INT16: BRANCH(int16_t, le_to_i16, bcf_int16_vector_end); break;
1407 case BCF_BT_INT32: BRANCH(int32_t, le_to_i32, bcf_int32_vector_end); break;
1408 default: fprintf(stderr,"todo: type %d\n", fmt->type); exit(1); break;
1409 }
1410 #undef BRANCH
1411 tok->nvalues = 1;
1412 tok->values[0] = tok->tag[0]=='N' ? nmissing : (double)nmissing / line->n_sample;
1413 }
1414 static int func_npass(filter_t *flt, bcf1_t *line, token_t *rtok, token_t **stack, int nstack)
1415 {
1416 if ( nstack==0 ) error("Error parsing the expression\n");
1417 token_t *tok = stack[nstack - 1];
1418 if ( !tok->nsamples ) error("The function %s works with FORMAT fields\n", rtok->tag);
1419 assert(tok->usmpl);
1420
1421 int i, npass = 0;
1422 for (i=0; i<tok->nsamples; i++)
1423 {
1424 if ( !tok->usmpl[i] ) continue;
1425 if ( tok->pass_samples[i] ) npass++;
1426 }
1427 hts_expand(double,1,rtok->mvalues,rtok->values);
1428 rtok->nsamples = 0;
1429 rtok->nvalues = 1;
1430 rtok->values[0] = rtok->tag[0]=='N' ? npass : (line->n_sample ? 1.0*npass/line->n_sample : 0);
1431
1432 return 1;
1433 }
1434 static void filters_set_nalt(filter_t *flt, bcf1_t *line, token_t *tok)
1435 {
1436 tok->nvalues = 1;
1437 tok->values[0] = line->n_allele - 1;
1438 }
1439 static void filters_set_ac(filter_t *flt, bcf1_t *line, token_t *tok)
1440 {
1441 hts_expand(int32_t, line->n_allele, flt->mtmpi, flt->tmpi);
1442 if ( !bcf_calc_ac(flt->hdr, line, flt->tmpi, BCF_UN_INFO|BCF_UN_FMT) )
1443 {
1444 tok->nvalues = 0;
1445 return;
1446 }
1447 int i, an = flt->tmpi[0];
1448 for (i=1; i<line->n_allele; i++) an += flt->tmpi[i];
1449 if ( !an )
1450 {
1451 tok->nvalues = 0;
1452 return;
1453 }
1454 flt->tmpi[0] = an; // for filters_set_[mac|af|maf]
1455 if ( tok->idx>=0 )
1456 {
1457 tok->nvalues = 1;
1458 tok->values[0] = tok->idx+1<line->n_allele ? flt->tmpi[tok->idx+1] : 0;
1459 }
1460 else if ( line->n_allele==1 ) // no ALT
1461 {
1462 tok->nvalues = 1;
1463 tok->values[0] = 0;
1464 }
1465 else
1466 {
1467 hts_expand(double,line->n_allele,tok->mvalues,tok->values);
1468 for (i=1; i<line->n_allele; i++)
1469 tok->values[i-1] = flt->tmpi[i];
1470 tok->nvalues = line->n_allele - 1;
1471 }
1472 }
1473 static void filters_set_an(filter_t *flt, bcf1_t *line, token_t *tok)
1474 {
1475 filters_set_ac(flt,line,tok);
1476 tok->values[0] = tok->nvalues ? flt->tmpi[0] : 0;
1477 tok->nvalues = 1;
1478 }
1479 static void filters_set_mac(filter_t *flt, bcf1_t *line, token_t *tok)
1480 {
1481 filters_set_ac(flt,line,tok);
1482 if ( !tok->nvalues ) return;
1483 int i, an = flt->tmpi[0];
1484 for (i=0; i<tok->nvalues; i++)
1485 if ( tok->values[i] > an*0.5 ) tok->values[i] = an - tok->values[i];
1486 }
1487 static void filters_set_af(filter_t *flt, bcf1_t *line, token_t *tok)
1488 {
1489 filters_set_ac(flt,line,tok);
1490 if ( !tok->nvalues ) return;
1491 int i, an = flt->tmpi[0];
1492 for (i=0; i<tok->nvalues; i++)
1493 tok->values[i] /= (double)an;
1494 }
1495 static void filters_set_maf(filter_t *flt, bcf1_t *line, token_t *tok)
1496 {
1497 filters_set_ac(flt,line,tok);
1498 if ( !tok->nvalues ) return;
1499 int i, an = flt->tmpi[0];
1500 for (i=0; i<tok->nvalues; i++)
1501 {
1502 tok->values[i] /= (double)an;
1503 if ( tok->values[i] > 0.5 ) tok->values[i] = 1 - tok->values[i];
1504 }
1505 }
1506
1507 static int func_max(filter_t *flt, bcf1_t *line, token_t *rtok, token_t **stack, int nstack)
1508 {
1509 token_t *tok = stack[nstack - 1];
1510 rtok->nvalues = 0;
1511 if ( !tok->nvalues ) return 1;
1512 double *ptr, val = -HUGE_VAL;
1513 int i,j, has_value = 0;
1514 if ( tok->nsamples )
1515 {
1516 for (i=0; i<tok->nsamples; i++)
1517 {
1518 if ( !tok->usmpl[i] ) continue;
1519 ptr = tok->values + i*tok->nval1;
1520 for (j=0; j<tok->nval1; j++)
1521 {
1522 if ( bcf_double_is_missing_or_vector_end(ptr[j]) ) continue;
1523 has_value = 1;
1524 if ( val < ptr[j] ) val = ptr[j];
1525 }
1526 }
1527 }
1528 else
1529 {
1530 for (i=0; i<tok->nvalues; i++)
1531 {
1532 if ( bcf_double_is_missing_or_vector_end(tok->values[i]) ) continue;
1533 has_value = 1;
1534 if ( val < tok->values[i] ) val = tok->values[i];
1535 }
1536 }
1537 if ( has_value )
1538 {
1539 rtok->values[0] = val;
1540 rtok->nvalues = has_value;
1541 }
1542 return 1;
1543 }
1544 static int func_smpl_max(filter_t *flt, bcf1_t *line, token_t *rtok, token_t **stack, int nstack)
1545 {
1546 token_t *tok = stack[nstack - 1];
1547 if ( !tok->nsamples ) return func_max(flt,line,rtok,stack,nstack);
1548 rtok->nsamples = tok->nsamples;
1549 rtok->nvalues = tok->nsamples;
1550 rtok->nval1 = 1;
1551 hts_expand(double,rtok->nvalues,rtok->mvalues,rtok->values);
1552 assert(tok->usmpl);
1553 if ( !rtok->usmpl ) rtok->usmpl = (uint8_t*) malloc(tok->nsamples);
1554 memcpy(rtok->usmpl, tok->usmpl, tok->nsamples);
1555 int i, j, has_value;
1556 double val, *ptr;
1557 for (i=0; i<tok->nsamples; i++)
1558 {
1559 if ( !rtok->usmpl[i] ) continue;
1560 val = -HUGE_VAL;
1561 has_value = 0;
1562 ptr = tok->values + i*tok->nval1;
1563 for (j=0; j<tok->nval1; j++)
1564 {
1565 if ( bcf_double_is_missing_or_vector_end(ptr[j]) ) continue;
1566 has_value = 1;
1567 if ( val < ptr[j] ) val = ptr[j];
1568 }
1569 if ( has_value ) rtok->values[i] = val;
1570 else bcf_double_set_missing(rtok->values[i]);
1571 }
1572 return 1;
1573 }
1574 static int func_min(filter_t *flt, bcf1_t *line, token_t *rtok, token_t **stack, int nstack)
1575 {
1576 token_t *tok = stack[nstack - 1];
1577 rtok->nvalues = 0;
1578 if ( !tok->nvalues ) return 1;
1579 double *ptr, val = HUGE_VAL;
1580 int i,j, has_value = 0;
1581 if ( tok->nsamples )
1582 {
1583 for (i=0; i<tok->nsamples; i++)
1584 {
1585 if ( !tok->usmpl[i] ) continue;
1586 ptr = tok->values + i*tok->nval1;
1587 for (j=0; j<tok->nval1; j++)
1588 {
1589 if ( bcf_double_is_missing_or_vector_end(ptr[j]) ) continue;
1590 has_value = 1;
1591 if ( val > ptr[j] ) val = ptr[j];
1592 }
1593 }
1594 }
1595 else
1596 {
1597 for (i=0; i<tok->nvalues; i++)
1598 {
1599 if ( bcf_double_is_missing_or_vector_end(tok->values[i]) ) continue;
1600 has_value = 1;
1601 if ( val > tok->values[i] ) val = tok->values[i];
1602 }
1603 }
1604 if ( has_value )
1605 {
1606 rtok->values[0] = val;
1607 rtok->nvalues = has_value;
1608 }
1609 return 1;
1610 }
1611 static int func_smpl_min(filter_t *flt, bcf1_t *line, token_t *rtok, token_t **stack, int nstack)
1612 {
1613 token_t *tok = stack[nstack - 1];
1614 if ( !tok->nsamples ) return func_min(flt,line,rtok,stack,nstack);
1615 rtok->nsamples = tok->nsamples;
1616 rtok->nvalues = tok->nsamples;
1617 rtok->nval1 = 1;
1618 hts_expand(double,rtok->nvalues,rtok->mvalues,rtok->values);
1619 assert(tok->usmpl);
1620 if ( !rtok->usmpl ) rtok->usmpl = (uint8_t*) malloc(tok->nsamples);
1621 memcpy(rtok->usmpl, tok->usmpl, tok->nsamples);
1622 int i, j, has_value;
1623 double val, *ptr;
1624 for (i=0; i<tok->nsamples; i++)
1625 {
1626 if ( !rtok->usmpl[i] ) continue;
1627 val = HUGE_VAL;
1628 has_value = 0;
1629 ptr = tok->values + i*tok->nval1;
1630 for (j=0; j<tok->nval1; j++)
1631 {
1632 if ( bcf_double_is_missing_or_vector_end(ptr[j]) ) continue;
1633 has_value = 1;
1634 if ( val > ptr[j] ) val = ptr[j];
1635 }
1636 if ( has_value ) rtok->values[i] = val;
1637 else bcf_double_set_missing(rtok->values[i]);
1638 }
1639 return 1;
1640 }
1641 static int func_avg(filter_t *flt, bcf1_t *line, token_t *rtok, token_t **stack, int nstack)
1642 {
1643 token_t *tok = stack[nstack - 1];
1644 rtok->nvalues = 0;
1645 if ( !tok->nvalues ) return 1;
1646 double *ptr, val = 0;
1647 int i,j, n = 0;
1648 if ( tok->nsamples )
1649 {
1650 for (i=0; i<tok->nsamples; i++)
1651 {
1652 if ( !tok->usmpl[i] ) continue;
1653 ptr = tok->values + i*tok->nval1;
1654 for (j=0; j<tok->nval1; j++)
1655 {
1656 if ( bcf_double_is_missing_or_vector_end(ptr[j]) ) continue;
1657 val += ptr[j];
1658 n++;
1659 }
1660 }
1661 }
1662 else
1663 {
1664 for (i=0; i<tok->nvalues; i++)
1665 if ( !bcf_double_is_missing_or_vector_end(tok->values[i]) ) { val += tok->values[i]; n++; }
1666 }
1667 if ( n )
1668 {
1669 rtok->values[0] = val / n;
1670 rtok->nvalues = 1;
1671 }
1672 return 1;
1673 }
1674 static int func_smpl_avg(filter_t *flt, bcf1_t *line, token_t *rtok, token_t **stack, int nstack)
1675 {
1676 token_t *tok = stack[nstack - 1];
1677 if ( !tok->nsamples ) return func_avg(flt,line,rtok,stack,nstack);
1678 rtok->nsamples = tok->nsamples;
1679 rtok->nvalues = tok->nsamples;
1680 rtok->nval1 = 1;
1681 hts_expand(double,rtok->nvalues,rtok->mvalues,rtok->values);
1682 assert(tok->usmpl);
1683 if ( !rtok->usmpl ) rtok->usmpl = (uint8_t*) malloc(tok->nsamples);
1684 memcpy(rtok->usmpl, tok->usmpl, tok->nsamples);
1685 int i, j, n;
1686 double val, *ptr;
1687 for (i=0; i<tok->nsamples; i++)
1688 {
1689 if ( !rtok->usmpl[i] ) continue;
1690 val = 0;
1691 n = 0;
1692 ptr = tok->values + i*tok->nval1;
1693 for (j=0; j<tok->nval1; j++)
1694 {
1695 if ( !bcf_double_is_missing_or_vector_end(ptr[j]) ) { val += ptr[j]; n++; }
1696 }
1697 if ( n ) rtok->values[i] = val / n;
1698 else bcf_double_set_missing(rtok->values[i]);
1699 }
1700 return 1;
1701 }
1702 static int compare_doubles(const void *lhs, const void *rhs)
1703 {
1704 double arg1 = *(const double*) lhs;
1705 double arg2 = *(const double*) rhs;
1706 if (arg1 < arg2) return -1;
1707 if (arg1 > arg2) return 1;
1708 return 0;
1709 }
1710 static int func_median(filter_t *flt, bcf1_t *line, token_t *rtok, token_t **stack, int nstack)
1711 {
1712 token_t *tok = stack[nstack - 1];
1713 rtok->nvalues = 0;
1714 if ( !tok->nvalues ) return 1;
1715 // sweep through all tok->values and while excluding all missing values reuse the very same array
1716 int i,j,k = 0, n = 0;
1717 if ( tok->nsamples )
1718 {
1719 for (i=0; i<tok->nsamples; i++)
1720 {
1721 if ( !tok->usmpl[i] ) { k += tok->nval1; continue; }
1722 for (j=0; j<tok->nval1; k++,j++)
1723 {
1724 if ( bcf_double_is_missing_or_vector_end(tok->values[k]) ) continue;
1725 if ( n < k ) tok->values[n] = tok->values[k];
1726 n++;
1727 }
1728 }
1729 }
1730 else
1731 {
1732 for (i=0; i<tok->nvalues; i++)
1733 {
1734 if ( bcf_double_is_missing_or_vector_end(tok->values[i]) ) continue;
1735 if ( n < i ) tok->values[n] = tok->values[i];
1736 n++;
1737 }
1738 }
1739 if ( !n ) return 1;
1740 if ( n==1 ) rtok->values[0] = tok->values[0];
1741 else
1742 {
1743 qsort(tok->values, n, sizeof(double), compare_doubles);
1744 rtok->values[0] = n % 2 ? tok->values[n/2] : (tok->values[n/2-1] + tok->values[n/2]) * 0.5;
1745 }
1746 rtok->nvalues = 1;
1747 return 1;
1748 }
1749 static int func_smpl_median(filter_t *flt, bcf1_t *line, token_t *rtok, token_t **stack, int nstack)
1750 {
1751 token_t *tok = stack[nstack - 1];
1752 if ( !tok->nsamples ) return func_avg(flt,line,rtok,stack,nstack);
1753 rtok->nsamples = tok->nsamples;
1754 rtok->nvalues = tok->nsamples;
1755 rtok->nval1 = 1;
1756 hts_expand(double,rtok->nvalues,rtok->mvalues,rtok->values);
1757 assert(tok->usmpl);
1758 if ( !rtok->usmpl ) rtok->usmpl = (uint8_t*) malloc(tok->nsamples);
1759 memcpy(rtok->usmpl, tok->usmpl, tok->nsamples);
1760 int i, j, n;
1761 double *ptr;
1762 for (i=0; i<tok->nsamples; i++)
1763 {
1764 if ( !rtok->usmpl[i] ) continue;
1765 n = 0;
1766 ptr = tok->values + i*tok->nval1;
1767 for (j=0; j<tok->nval1; j++)
1768 {
1769 if ( bcf_double_is_missing_or_vector_end(ptr[j]) ) continue;
1770 if ( n < j ) ptr[n] = ptr[j];
1771 n++;
1772 }
1773 if ( n==0 )
1774 bcf_double_set_missing(rtok->values[i]);
1775 else if ( n==1 )
1776 rtok->values[i] = ptr[0];
1777 else
1778 {
1779 qsort(ptr, n, sizeof(double), compare_doubles);
1780 rtok->values[i] = n % 2 ? ptr[n/2] : (ptr[n/2-1] + ptr[n/2]) * 0.5;
1781 }
1782 }
1783 return 1;
1784 }
1785 static int func_stddev(filter_t *flt, bcf1_t *line, token_t *rtok, token_t **stack, int nstack)
1786 {
1787 token_t *tok = stack[nstack - 1];
1788 rtok->nvalues = 0;
1789 if ( !tok->nvalues ) return 1;
1790 // sweep through all tok->values and while excluding all missing values reuse the very same array
1791 int i,j,k = 0, n = 0;
1792 if ( tok->nsamples )
1793 {
1794 for (i=0; i<tok->nsamples; i++)
1795 {
1796 if ( !tok->usmpl[i] ) { k += tok->nval1; continue; }
1797 for (j=0; j<tok->nval1; k++,j++)
1798 {
1799 if ( bcf_double_is_missing_or_vector_end(tok->values[k]) ) continue;
1800 if ( n < k ) tok->values[n] = tok->values[k];
1801 n++;
1802 }
1803 }
1804 }
1805 else
1806 {
1807 for (i=0; i<tok->nvalues; i++)
1808 {
1809 if ( bcf_double_is_missing_or_vector_end(tok->values[i]) ) continue;
1810 if ( n < i ) tok->values[n] = tok->values[i];
1811 n++;
1812 }
1813 }
1814 if ( !n ) return 1;
1815 if ( n==1 ) rtok->values[0] = 0;
1816 else
1817 {
1818 double sdev = 0, avg = 0;
1819 for (i=0; i<n; i++) avg += tok->values[i];
1820 avg /= n;
1821 for (i=0; i<n; i++) sdev += (tok->values[i] - avg) * (tok->values[i] - avg);
1822 rtok->values[0] = sqrt(sdev/n);
1823 }
1824 rtok->nvalues = 1;
1825 return 1;
1826 }
1827 static int func_smpl_stddev(filter_t *flt, bcf1_t *line, token_t *rtok, token_t **stack, int nstack)
1828 {
1829 token_t *tok = stack[nstack - 1];
1830 if ( !tok->nsamples ) return func_avg(flt,line,rtok,stack,nstack);
1831 rtok->nsamples = tok->nsamples;
1832 rtok->nvalues = tok->nsamples;
1833 rtok->nval1 = 1;
1834 hts_expand(double,rtok->nvalues,rtok->mvalues,rtok->values);
1835 assert(tok->usmpl);
1836 if ( !rtok->usmpl ) rtok->usmpl = (uint8_t*) malloc(tok->nsamples);
1837 memcpy(rtok->usmpl, tok->usmpl, tok->nsamples);
1838 int i, j, n;
1839 double *ptr;
1840 for (i=0; i<tok->nsamples; i++)
1841 {
1842 if ( !rtok->usmpl[i] ) continue;
1843 n = 0;
1844 ptr = tok->values + i*tok->nval1;
1845 for (j=0; j<tok->nval1; j++)
1846 {
1847 if ( bcf_double_is_missing_or_vector_end(ptr[j]) ) continue;
1848 if ( n < j ) ptr[n] = ptr[j];
1849 n++;
1850 }
1851 if ( n==0 )
1852 bcf_double_set_missing(rtok->values[i]);
1853 else if ( n==1 )
1854 rtok->values[i] = 0;
1855 else
1856 {
1857 double sdev = 0, avg = 0;
1858 for (j=0; j<n; j++) avg += ptr[j];
1859 avg /= n;
1860 for (j=0; j<n; j++) sdev += (ptr[j] - avg) * (ptr[j] - avg);
1861 rtok->values[i] = sqrt(sdev/n);
1862 }
1863 }
1864 return 1;
1865 }
1866 static int func_sum(filter_t *flt, bcf1_t *line, token_t *rtok, token_t **stack, int nstack)
1867 {
1868 rtok->nvalues = 0;
1869 token_t *tok = stack[nstack - 1];
1870 if ( !tok->nvalues ) return 1;
1871 double *ptr, val = 0;
1872 int i,j, n = 0;
1873 if ( tok->nsamples )
1874 {
1875 for (i=0; i<tok->nsamples; i++)
1876 {
1877 if ( !tok->usmpl[i] ) continue;
1878 ptr = tok->values + i*tok->nval1;
1879 for (j=0; j<tok->nval1; j++)
1880 {
1881 if ( bcf_double_is_missing_or_vector_end(ptr[j]) ) continue;
1882 val += ptr[j];
1883 n++;
1884 }
1885 }
1886 }
1887 else
1888 {
1889 for (i=0; i<tok->nvalues; i++)
1890 if ( !bcf_double_is_missing_or_vector_end(tok->values[i]) ) { val += tok->values[i]; n++; }
1891 }
1892 if ( n )
1893 {
1894 rtok->values[0] = val;
1895 rtok->nvalues = 1;
1896 }
1897 return 1;
1898 }
1899 static int func_smpl_sum(filter_t *flt, bcf1_t *line, token_t *rtok, token_t **stack, int nstack)
1900 {
1901 token_t *tok = stack[nstack - 1];
1902 if ( !tok->nsamples ) return func_avg(flt,line,rtok,stack,nstack);
1903 rtok->nsamples = tok->nsamples;
1904 rtok->nvalues = tok->nsamples;
1905 rtok->nval1 = 1;
1906 hts_expand(double,rtok->nvalues,rtok->mvalues,rtok->values);
1907 assert(tok->usmpl);
1908 if ( !rtok->usmpl ) rtok->usmpl = (uint8_t*) malloc(tok->nsamples);
1909 memcpy(rtok->usmpl, tok->usmpl, tok->nsamples);
1910 int i, j, has_value;
1911 double val, *ptr;
1912 for (i=0; i<tok->nsamples; i++)
1913 {
1914 if ( !rtok->usmpl[i] ) continue;
1915 val = 0;
1916 has_value = 0;
1917 ptr = tok->values + i*tok->nval1;
1918 for (j=0; j<tok->nval1; j++)
1919 {
1920 if ( bcf_double_is_missing_or_vector_end(ptr[j]) ) continue;
1921 has_value = 1;
1922 val += ptr[j];
1923 }
1924 if ( has_value ) rtok->values[i] = val;
1925 else bcf_double_set_missing(rtok->values[i]);
1926 }
1927 return 1;
1928 }
1929 static int func_abs(filter_t *flt, bcf1_t *line, token_t *rtok, token_t **stack, int nstack)
1930 {
1931 token_t *tok = stack[nstack - 1];
1932 if ( tok->is_str ) error("ABS() can be applied only on numeric values\n");
1933 rtok->nsamples = tok->nsamples;
1934 rtok->nvalues = tok->nvalues;
1935 rtok->nval1 = tok->nval1;
1936 hts_expand(double,rtok->nvalues,rtok->mvalues,rtok->values);
1937 if ( tok->usmpl )
1938 {
1939 if ( !rtok->usmpl ) rtok->usmpl = (uint8_t*) malloc(tok->nsamples);
1940 memcpy(rtok->usmpl, tok->usmpl, tok->nsamples);
1941 }
1942 if ( !tok->nvalues ) return 1;
1943 hts_expand(double, rtok->nvalues, rtok->mvalues, rtok->values);
1944 int i,j,k = 0;
1945 if ( tok->usmpl )
1946 {
1947 for (i=0; i<tok->nsamples; i++)
1948 {
1949 if ( !tok->usmpl[i] ) { k+= tok->nval1; continue; }
1950 for (j=0; j<tok->nval1; k++,j++)
1951 {
1952 if ( bcf_double_is_missing_or_vector_end(tok->values[k]) ) bcf_double_set_missing(rtok->values[k]);
1953 else rtok->values[k] = fabs(tok->values[k]);
1954 }
1955 }
1956 }
1957 else
1958 {
1959 for (i=0; i<tok->nvalues; i++)
1960 {
1961 if ( tok->usmpl && !tok->usmpl[i] ) continue;
1962 if ( bcf_double_is_missing(tok->values[i]) ) bcf_double_set_missing(rtok->values[i]);
1963 else if ( !bcf_double_is_vector_end(tok->values[i]) ) rtok->values[i] = fabs(tok->values[i]);
1964 }
1965 }
1966 return 1;
1967 }
1968 static int func_count(filter_t *flt, bcf1_t *line, token_t *rtok, token_t **stack, int nstack)
1969 {
1970 token_t *tok = stack[nstack - 1];
1971 int i,j, cnt = 0;
1972 if ( tok->tag && tok->nsamples )
1973 {
1974 // raw number of values in a FMT tag, e.g. COUNT(FMT/TAG)
1975 if ( tok->is_str ) error("todo: Type=String for COUNT on FORMAT fields?\n");
1976 for (i=0; i<tok->nsamples; i++)
1977 {
1978 if ( !tok->usmpl[i] ) continue;
1979 double *ptr = tok->values + i*tok->nval1;
1980 for (j=0; j<tok->nval1; j++)
1981 if ( !bcf_double_is_missing_or_vector_end(ptr[j]) ) cnt++;
1982 }
1983 }
1984 else if ( tok->nsamples )
1985 {
1986 // number of samples that pass a processed FMT tag
1987 for (i=0; i<tok->nsamples; i++)
1988 if ( tok->pass_samples[i] ) cnt++;
1989 }
1990 else if ( tok->is_str )
1991 {
1992 if ( tok->str_value.l ) cnt = 1;
1993 for (i=0; i<tok->str_value.l; i++) if ( tok->str_value.s[i]==',' ) cnt++;
1994 }
1995 else
1996 cnt = tok->nvalues;
1997
1998 rtok->nvalues = 1;
1999 rtok->values[0] = cnt;
2000 return 1;
2001 }
2002 static int func_strlen(filter_t *flt, bcf1_t *line, token_t *rtok, token_t **stack, int nstack)
2003 {
2004 token_t *tok = stack[nstack - 1];
2005 rtok->nvalues = rtok->str_value.l = 0;
2006 if ( !tok->str_value.l ) return 1;
2007
2008 if ( tok->idx==-2 )
2009 {
2010 int i = 0;
2011 char *ss = tok->str_value.s;
2012 while ( *ss )
2013 {
2014 char *se = ss;
2015 while ( *se && *se!=',' ) se++;
2016 hts_expand(double, i+1, rtok->mvalues, rtok->values);
2017 if ( !*se ) rtok->values[i] = strlen(ss);
2018 else
2019 {
2020 *se = 0;
2021 rtok->values[i] = strlen(ss);
2022 *se = ',';
2023 }
2024 ss = *se ? se + 1 : se;
2025 i++;
2026 }
2027 rtok->nvalues = i;
2028 }
2029 else
2030 {
2031 if ( !tok->str_value.s[1] && tok->str_value.s[0]=='.' )
2032 rtok->values[0] = 0;
2033 else
2034 rtok->values[0] = strlen(tok->str_value.s);
2035 rtok->nvalues = 1;
2036 }
2037 return 1;
2038 }
2039 static int func_binom(filter_t *flt, bcf1_t *line, token_t *rtok, token_t **stack, int nstack)
2040 {
2041 int i, istack = nstack - rtok->nargs;
2042
2043 if ( rtok->nargs!=2 && rtok->nargs!=1 ) error("Error: binom() takes one or two arguments\n");
2044 assert( istack>=0 );
2045
2046 // The expected mean is 0.5. Should we support also prob!=0.5?
2047 //
2048 // double prob = 0.5;
2049 // if ( nstack==3 )
2050 // {
2051 // // three parameters, the first one must be a scalar: binom(0.25,AD[0],AD[1])
2052 // if ( !stack[istack]->is_constant )
2053 // error("The first argument of binom() must be a numeric constant if three parameters are given\n");
2054 // prob = stack[istack]->threshold;
2055 // istack++;
2056 // }
2057 // else if ( nstack==2 && stack[istack]->is_constant )
2058 // {
2059 // // two parameters, the first can be a scalar: binom(0.25,AD) or binom(AD[0],AD[1])
2060 // prob = stack[istack]->threshold;
2061 // istack++;
2062 // }
2063
2064 token_t *tok = stack[istack];
2065 if ( tok->nsamples )
2066 {
2067 // working with a FORMAT tag
2068 rtok->nval1 = 1;
2069 rtok->nvalues = tok->nsamples;
2070 rtok->nsamples = tok->nsamples;
2071 hts_expand(double, rtok->nvalues, rtok->mvalues, rtok->values);
2072 assert(tok->usmpl);
2073 if ( !rtok->usmpl ) rtok->usmpl = (uint8_t*) malloc(tok->nsamples);
2074 memcpy(rtok->usmpl, tok->usmpl, tok->nsamples);
2075
2076 if ( istack+1==nstack )
2077 {
2078 // determine the index from the GT field: binom(AD)
2079 int ngt = bcf_get_genotypes(flt->hdr, line, &flt->tmpi, &flt->mtmpi);
2080 int max_ploidy = ngt/line->n_sample;
2081 if ( ngt <= 0 || max_ploidy < 2 ) // GT not present or not diploid, cannot set
2082 {
2083 for (i=0; i<rtok->nsamples; i++)
2084 if ( rtok->usmpl[i] ) bcf_double_set_missing(rtok->values[i]);
2085 return rtok->nargs;
2086 }
2087 for (i=0; i<rtok->nsamples; i++)
2088 {
2089 if ( !rtok->usmpl[i] ) continue;
2090 int32_t *ptr = flt->tmpi + i*max_ploidy;
2091 if ( bcf_gt_is_missing(ptr[0]) || bcf_gt_is_missing(ptr[1]) || ptr[1]==bcf_int32_vector_end )
2092 {
2093 bcf_double_set_missing(rtok->values[i]);
2094 continue;
2095 }
2096 int idx1 = bcf_gt_allele(ptr[0]);
2097 int idx2 = bcf_gt_allele(ptr[1]);
2098 if ( idx1>=line->n_allele ) error("Incorrect allele index at %s:%"PRId64", sample %s\n", bcf_seqname(flt->hdr,line),(int64_t) line->pos+1,flt->hdr->samples[i]);
2099 if ( idx2>=line->n_allele ) error("Incorrect allele index at %s:%"PRId64", sample %s\n", bcf_seqname(flt->hdr,line),(int64_t) line->pos+1,flt->hdr->samples[i]);
2100 double *vals = tok->values + tok->nval1*i;
2101 if ( bcf_double_is_missing_or_vector_end(vals[idx1]) || bcf_double_is_missing_or_vector_end(vals[idx2]) )
2102 {
2103 bcf_double_set_missing(rtok->values[i]);
2104 continue;
2105 }
2106 rtok->values[i] = calc_binom_two_sided(vals[idx1],vals[idx2],0.5);
2107 if ( rtok->values[i] < 0 )
2108 {
2109 bcf_double_set_missing(rtok->values[i]);
2110 continue;
2111 }
2112 }
2113 }
2114 else
2115 {
2116 // the fields given explicitly: binom(AD[:0],AD[:1])
2117 token_t *tok2 = stack[istack+1];
2118 if ( tok->nval1!=1 || tok2->nval1!=1 )
2119 error("Expected one value per binom() argument, found %d and %d at %s:%"PRId64"\n",tok->nval1,tok2->nval1, bcf_seqname(flt->hdr,line),(int64_t) line->pos+1);
2120 for (i=0; i<rtok->nsamples; i++)
2121 {
2122 if ( !rtok->usmpl[i] ) continue;
2123 double *ptr1 = tok->values + tok->nval1*i;
2124 double *ptr2 = tok2->values + tok2->nval1*i;
2125 if ( bcf_double_is_missing_or_vector_end(ptr1[0]) || bcf_double_is_missing_or_vector_end(ptr2[0]) )
2126 {
2127 bcf_double_set_missing(rtok->values[i]);
2128 continue;
2129 }
2130 rtok->values[i] = calc_binom_two_sided(ptr1[0],ptr2[0],0.5);
2131 if ( rtok->values[i] < 0 )
2132 {
2133 bcf_double_set_missing(rtok->values[i]);
2134 continue;
2135 }
2136 }
2137 }
2138 }
2139 else
2140 {
2141 // working with an INFO tag
2142 rtok->nvalues = 1;
2143 hts_expand(double, rtok->nvalues, rtok->mvalues, rtok->values);
2144
2145 double *ptr1 = NULL, *ptr2 = NULL;
2146 if ( istack+1==nstack )
2147 {
2148 // only one tag, expecting two values: binom(INFO/AD)
2149 if ( tok->nvalues==2 )
2150 {
2151 ptr1 = &tok->values[0];
2152 ptr2 = &tok->values[1];
2153 }
2154 }
2155 else
2156 {
2157 // two tags, expecting one value in each: binom(INFO/AD[0],INFO/AD[1])
2158 token_t *tok2 = stack[istack+1];
2159 if ( tok->nvalues==1 && tok2->nvalues==1 )
2160 {
2161 ptr1 = &tok->values[0];
2162 ptr2 = &tok2->values[0];
2163 }
2164 }
2165 if ( !ptr1 || !ptr2 || bcf_double_is_missing_or_vector_end(ptr1[0]) || bcf_double_is_missing_or_vector_end(ptr2[0]) )
2166 bcf_double_set_missing(rtok->values[0]);
2167 else
2168 {
2169 rtok->values[0] = calc_binom_two_sided(ptr1[0],ptr2[0],0.5);
2170 if ( rtok->values[0] < 0 )
2171 bcf_double_set_missing(rtok->values[0]);
2172 }
2173 }
2174 return rtok->nargs;
2175 }
2176 static int func_phred(filter_t *flt, bcf1_t *line, token_t *rtok, token_t **stack, int nstack)
2177 {
2178 token_t *tok = stack[nstack - 1];
2179 if ( tok->is_str ) error("PHRED() can be applied only on numeric values\n");
2180
2181 rtok->nsamples = tok->nsamples;
2182 rtok->nval1 = tok->nval1;
2183 memcpy(rtok->pass_samples, tok->pass_samples, rtok->nsamples*sizeof(*rtok->pass_samples));
2184 assert(tok->usmpl);
2185 if ( !rtok->usmpl )
2186 {
2187 rtok->usmpl = (uint8_t*) malloc(tok->nsamples*sizeof(*rtok->usmpl));
2188 memcpy(rtok->usmpl, tok->usmpl, tok->nsamples*sizeof(*rtok->usmpl));
2189 }
2190 rtok->nvalues = tok->nvalues;
2191 if ( !tok->nvalues ) return 1;
2192
2193 hts_expand(double, rtok->nvalues, rtok->mvalues, rtok->values);
2194 int i,j,k = 0;
2195 if ( tok->usmpl )
2196 {
2197 for (i=0; i<tok->nsamples; i++)
2198 {
2199 if ( !tok->usmpl[i] ) { k+= tok->nval1; continue; }
2200 for (j=0; j<tok->nval1; k++,j++)
2201 {
2202 if ( bcf_double_is_missing_or_vector_end(tok->values[k]) ) bcf_double_set_missing(rtok->values[k]);
2203 else rtok->values[k] = -4.34294481903*log(tok->values[k]);
2204 }
2205 }
2206 }
2207 else
2208 {
2209 for (i=0; i<tok->nvalues; i++)
2210 {
2211 if ( bcf_double_is_missing_or_vector_end(tok->values[i]) ) bcf_double_set_missing(rtok->values[i]);
2212 else rtok->values[i] = -4.34294481903*log(tok->values[i]);
2213 }
2214 }
2215 return 1;
2216 }
2217 inline static void tok_init_values(token_t *atok, token_t *btok, token_t *rtok)
2218 {
2219 token_t *tok;
2220 if ( (atok->nsamples || btok->nsamples) && (!atok->nsamples || !btok->nsamples) )
2221 tok = atok->nsamples ? atok : btok;
2222 else
2223 tok = atok->nvalues > btok->nvalues ? atok : btok;
2224 rtok->nvalues = tok->nvalues;
2225 rtok->nval1 = tok->nval1;
2226 hts_expand(double, rtok->nvalues, rtok->mvalues, rtok->values);
2227 }
2228 inline static void tok_init_samples(token_t *atok, token_t *btok, token_t *rtok)
2229 {
2230 if ( (atok->nsamples || btok->nsamples) && !rtok->nsamples )
2231 {
2232 rtok->nsamples = atok->nsamples ? atok->nsamples : btok->nsamples;
2233 rtok->usmpl = (uint8_t*) calloc(rtok->nsamples,1);
2234 int i;
2235 for (i=0; i<atok->nsamples; i++) rtok->usmpl[i] |= atok->usmpl[i];
2236 for (i=0; i<btok->nsamples; i++) rtok->usmpl[i] |= btok->usmpl[i];
2237 }
2238 if (rtok->nsamples)
2239 memset(rtok->pass_samples, 0, rtok->nsamples);
2240 }
2241
2242 #define VECTOR_ARITHMETICS(atok,btok,_rtok,AOP,TYPE) \
2243 { \
2244 token_t *rtok = _rtok; \
2245 int i, has_values = 0; \
2246 if ( atok->nvalues && btok->nvalues ) \
2247 { \
2248 tok_init_values(atok, btok, rtok); \
2249 tok_init_samples(atok, btok, rtok); \
2250 if ( !atok->nsamples && !btok->nsamples ) \
2251 { \
2252 if ( atok->nvalues!=btok->nvalues && atok->nvalues!=1 && btok->nvalues!=1 ) \
2253 error("Cannot run numeric operator in -i/-e filtering on vectors of different lengths: %d vs %d\n",atok->nvalues,btok->nvalues); \
2254 int ir,ia = 0, ib = 0; \
2255 for (ir=0; ir<rtok->nvalues; ir++) \
2256 { \
2257 if ( atok->nvalues > 1 ) ia = ir; \
2258 if ( btok->nvalues > 1 ) ib = ir; \
2259 if ( bcf_double_is_missing_or_vector_end(atok->values[ia]) || bcf_double_is_missing_or_vector_end(btok->values[ib]) ) \
2260 { \
2261 bcf_double_set_missing(rtok->values[ir]); \
2262 continue; \
2263 } \
2264 has_values = 1; \
2265 rtok->values[ir] = TYPE atok->values[ia] AOP TYPE btok->values[ib]; \
2266 } \
2267 } \
2268 else if ( atok->nsamples && btok->nsamples ) \
2269 { \
2270 assert( atok->nsamples==btok->nsamples ); \
2271 if ( atok->nval1!=btok->nval1 && atok->nval1!=1 && btok->nval1!=1 ) \
2272 error("Cannot run numeric operator in -i/-e filtering on vectors of different lengths: %d vs %d\n",atok->nval1,btok->nval1); \
2273 for (i=0; i<rtok->nsamples; i++) \
2274 { \
2275 double *rval = rtok->values + i*rtok->nval1; \
2276 double *aval = atok->values + i*atok->nval1; \
2277 double *bval = btok->values + i*btok->nval1; \
2278 int ir,ia = 0, ib = 0; \
2279 for (ir=0; ir<rtok->nval1; ir++) \
2280 { \
2281 if ( atok->nval1 > 1 ) ia = ir; \
2282 if ( btok->nval1 > 1 ) ib = ir; \
2283 if ( bcf_double_is_missing_or_vector_end(aval[ia]) || bcf_double_is_missing_or_vector_end(bval[ib]) ) \
2284 { \
2285 bcf_double_set_missing(rval[ir]); \
2286 continue; \
2287 } \
2288 has_values = 1; \
2289 rval[ir] = TYPE aval[ia] AOP TYPE bval[ib]; \
2290 } \
2291 } \
2292 } \
2293 else if ( atok->nsamples ) \
2294 { \
2295 assert( btok->nvalues==1 ); \
2296 if ( !bcf_double_is_missing_or_vector_end(btok->values[0]) ) \
2297 { \
2298 for (i=0; i<atok->nvalues; i++) \
2299 { \
2300 if ( bcf_double_is_missing_or_vector_end(atok->values[i]) ) \
2301 { \
2302 bcf_double_set_missing(rtok->values[i]); \
2303 continue; \
2304 } \
2305 has_values = 1; \
2306 rtok->values[i] = TYPE atok->values[i] AOP TYPE btok->values[0]; \
2307 } \
2308 } \
2309 } \
2310 else \
2311 { \
2312 assert( atok->nvalues==1 ); \
2313 if ( !bcf_double_is_missing_or_vector_end(atok->values[0]) ) \
2314 { \
2315 for (i=0; i<btok->nvalues; i++) \
2316 { \
2317 if ( bcf_double_is_missing_or_vector_end(btok->values[i]) ) \
2318 { \
2319 bcf_double_set_missing(rtok->values[i]); \
2320 continue; \
2321 } \
2322 has_values = 1; \
2323 rtok->values[i] = TYPE atok->values[0] AOP TYPE btok->values[i]; \
2324 } \
2325 } \
2326 } \
2327 } \
2328 if ( !has_values ) rtok->nvalues = 0; \
2329 }
2330
2331 static int vector_logic_or(filter_t *filter, bcf1_t *line, token_t *rtok, token_t **stack, int nstack)
2332 {
2333 if ( nstack < 2 ) error("Error occurred while processing the filter \"%s\"\n", filter->str);
2334
2335 token_t *atok = stack[nstack-2];
2336 token_t *btok = stack[nstack-1];
2337 tok_init_samples(atok, btok, rtok);
2338
2339 if ( !atok->pass_site && !btok->pass_site ) return 2;
2340
2341 rtok->pass_site = 1;
2342 if ( !atok->nsamples && !btok->nsamples ) return 2;
2343
2344 int i;
2345 if ( rtok->tok_type==TOK_OR_VEC ) // ||, select all samples if one is true
2346 {
2347 if ( (!atok->nsamples && !atok->pass_site) || (!btok->nsamples && !btok->pass_site) )
2348 {
2349 // These two conditions are to ensure the following does not set all samples
2350 // at sites with QUAL<=30:
2351 // QUAL>30 || FMT/GQ>30
2352
2353 token_t *tok = atok->nsamples ? atok : btok;
2354 for (i=0; i<rtok->nsamples; i++)
2355 {
2356 if ( !rtok->usmpl[i] ) continue;
2357 rtok->pass_samples[i] = tok->pass_samples[i];
2358 }
2359 }
2360 else
2361 {
2362 for (i=0; i<rtok->nsamples; i++)
2363 {
2364 if ( !rtok->usmpl[i] ) continue;
2365 rtok->pass_samples[i] = 1;
2366 }
2367 }
2368 return 2;
2369 }
2370
2371 // |, only select samples which are actually true
2372
2373 if ( !atok->nsamples || !btok->nsamples )
2374 {
2375 token_t *tok = atok->nsamples ? atok : btok;
2376 for (i=0; i<rtok->nsamples; i++)
2377 {
2378 if ( !rtok->usmpl[i] ) continue;
2379 rtok->pass_samples[i] = tok->pass_samples[i];
2380 }
2381 return 2;
2382 }
2383
2384 assert( atok->nsamples==btok->nsamples );
2385
2386 for (i=0; i<rtok->nsamples; i++)
2387 {
2388 if ( !rtok->usmpl[i] ) continue;
2389 rtok->pass_samples[i] = atok->pass_samples[i] | btok->pass_samples[i];
2390 }
2391 return 2;
2392 }
2393 static int vector_logic_and(filter_t *filter, bcf1_t *line, token_t *rtok, token_t **stack, int nstack)
2394 {
2395 if ( nstack < 2 ) error("Error occurred while processing the filter \"%s\". (nstack=%d)\n", filter->str,nstack);
2396
2397 token_t *atok = stack[nstack-2];
2398 token_t *btok = stack[nstack-1];
2399 tok_init_samples(atok, btok, rtok);
2400
2401 if ( !atok->pass_site || !btok->pass_site ) return 2;
2402 if ( !atok->nsamples && !btok->nsamples ) { rtok->pass_site = 1; return 2; }
2403
2404 int i;
2405 if ( !atok->nsamples || !btok->nsamples )
2406 {
2407 token_t *tok = atok->nsamples ? atok : btok;
2408 for (i=0; i<rtok->nsamples; i++)
2409 {
2410 if ( !rtok->usmpl[i] ) continue;
2411 rtok->pass_samples[i] = tok->pass_samples[i];
2412 }
2413 rtok->pass_site = 1;
2414 return 2;
2415 }
2416
2417 assert( atok->nsamples==btok->nsamples );
2418 if ( rtok->tok_type==TOK_AND_VEC ) // &&, can be true in different samples
2419 {
2420 for (i=0; i<rtok->nsamples; i++)
2421 {
2422 if ( !rtok->usmpl[i] ) continue;
2423 rtok->pass_samples[i] = atok->pass_samples[i] | btok->pass_samples[i];
2424 }
2425 rtok->pass_site = 1;
2426 }
2427 else // &, must be true within one sample
2428 {
2429 for (i=0; i<rtok->nsamples; i++)
2430 {
2431 if ( !rtok->usmpl[i] ) continue;
2432 rtok->pass_samples[i] = atok->pass_samples[i] & btok->pass_samples[i];
2433 if ( rtok->pass_samples[i] ) rtok->pass_site = 1;
2434 }
2435 }
2436 return 2;
2437 }
2438
2439 // A note about comparisons:
2440 // When setting value by determining index from the genotype, we face the problem
2441 // of how to interpret truncating arrays. Say we have TAG defined as Number=. and
2442 // GT:TAG 1/1:0,1,2 0/0:0
2443 // Then when querying we expect the following expression to evaluate for the second
2444 // sample as
2445 // -i 'TAG[1:1]="."' .. true
2446 // -i 'TAG[1:GT]="."' .. false
2447 // The problem is that the implementation truncates the number of fields, filling
2448 // usually fewer than the original number of per-sample values. This is fixed by
2449 // adding an exception that makes the code aware of this: the GT indexing can be
2450 // recognised by having tok->idx==-3
2451 #define CMP_VECTORS(atok,btok,_rtok,CMP_OP,missing_logic) \
2452 { \
2453 token_t *rtok = _rtok; \
2454 int i, j, k; \
2455 tok_init_samples(atok, btok, rtok); \
2456 if ( !atok->nsamples && !btok->nsamples ) \
2457 { \
2458 if ( !atok->nvalues && !btok->nvalues ) { rtok->pass_site = missing_logic[2]; } \
2459 else if ( !atok->nvalues || !btok->nvalues ) \
2460 { \
2461 token_t *tok = atok->nvalues ? atok : btok; \
2462 for (j=0; j<tok->nvalues; j++) \
2463 { \
2464 if ( bcf_double_is_missing_or_vector_end(tok->values[j]) ) \
2465 { \
2466 if ( missing_logic[2] ) { rtok->pass_site = 1; break; } \
2467 } \
2468 else if ( missing_logic[1] ) { rtok->pass_site = 1; break; } \
2469 } \
2470 } \
2471 else \
2472 { \
2473 for (i=0; i<atok->nvalues; i++) \
2474 { \
2475 int amiss = bcf_double_is_missing_or_vector_end(atok->values[i]) ? 1 : 0; \
2476 for (j=0; j<btok->nvalues; j++) \
2477 { \
2478 int nmiss = amiss + (bcf_double_is_missing_or_vector_end(btok->values[j]) ? 1 : 0); \
2479 if ( nmiss ) \
2480 { \
2481 if ( missing_logic[nmiss] ) { rtok->pass_site = 1; i = atok->nvalues; break; } \
2482 } \
2483 else if ( atok->values[i] > 16777216 || btok->values[j] > 16777216 ) /* Ugly, see #871 */ \
2484 { \
2485 if ( atok->values[i] CMP_OP btok->values[j] ) { rtok->pass_site = 1; i = atok->nvalues; break; } \
2486 } \
2487 else if ( (float)atok->values[i] CMP_OP (float)btok->values[j] ) { rtok->pass_site = 1; i = atok->nvalues; break; } \
2488 } \
2489 } \
2490 } \
2491 } \
2492 else \
2493 { \
2494 if ( !atok->nvalues && !btok->nvalues ) \
2495 { \
2496 if ( missing_logic[2] ) \
2497 { \
2498 for (i=0; i<rtok->nsamples; i++) \
2499 if ( rtok->usmpl[i] ) { rtok->pass_samples[i] = missing_logic[2]; rtok->pass_site = 1; } \
2500 } \
2501 } \
2502 else if ( !atok->nvalues || !btok->nvalues ) \
2503 { \
2504 token_t *tok = atok->nvalues ? atok : btok; \
2505 if ( !tok->nsamples ) \
2506 { \
2507 int miss = 0; \
2508 for (j=0; j<tok->nvalues; j++) \
2509 miss |= bcf_double_is_missing_or_vector_end(tok->values[j]) ? 1 : 0; \
2510 if ( missing_logic[++miss] ) \
2511 { \
2512 for (i=0; i<rtok->nsamples; i++) \
2513 if ( rtok->usmpl[i] ) { rtok->pass_samples[i] = missing_logic[miss]; rtok->pass_site = 1; } \
2514 } \
2515 } \
2516 else \
2517 for (i=0; i<tok->nsamples; i++) \
2518 { \
2519 if ( !rtok->usmpl[i] ) continue; \
2520 double *ptr = tok->values + i*tok->nval1; \
2521 int miss = 0; \
2522 for (j=0; j<tok->nval1; j++) \
2523 miss |= bcf_double_is_missing_or_vector_end(ptr[j]) ? 1 : 0; \
2524 if ( missing_logic[++miss] ) { rtok->pass_samples[i] = missing_logic[miss]; rtok->pass_site = 1; } \
2525 } \
2526 } \
2527 else if ( atok->nsamples && btok->nsamples ) \
2528 { \
2529 if ( atok->nval1!=btok->nval1 ) error("Incompatible number of per-sample values in comparison: %d vs %d\n",atok->nval1,btok->nval1); \
2530 if ( atok->nsamples!=btok->nsamples ) error("Incompatible number samples in comparison: %d vs %d\n",atok->nsamples,btok->nsamples); \
2531 for (i=0; i<atok->nsamples; i++) \
2532 { \
2533 if ( !atok->usmpl[i] || !btok->usmpl[i] ) { rtok->usmpl[i] = 0; continue; } \
2534 double *aptr = atok->values + i*atok->nval1; \
2535 double *bptr = btok->values + i*btok->nval1; \
2536 for (j=0; j<atok->nval1; j++) \
2537 { \
2538 if ( atok->idx==-3 && bcf_double_is_vector_end(aptr[j]) ) break; /* explained above */ \
2539 if ( btok->idx==-3 && bcf_double_is_vector_end(bptr[j]) ) break; /* explained above */ \
2540 int nmiss = bcf_double_is_missing_or_vector_end(aptr[j]) ? 1 : 0; \
2541 if ( nmiss && !missing_logic[0] ) continue; /* any is missing => result is false */ \
2542 nmiss += (bcf_double_is_missing_or_vector_end(bptr[j]) ? 1 : 0); \
2543 if ( nmiss ) \
2544 { \
2545 if ( missing_logic[nmiss] ) { rtok->pass_samples[i] = 1; rtok->pass_site = 1; break; } \
2546 } \
2547 else if ( aptr[j] > 16777216 || bptr[j] > 16777216 ) /* Ugly, see #871 */ \
2548 { \
2549 if ( aptr[j] CMP_OP bptr[j] ) { rtok->pass_samples[i] = 1; rtok->pass_site = 1; break; } \
2550 } \
2551 else if ( (float)aptr[j] CMP_OP (float)bptr[j] ) { rtok->pass_samples[i] = 1; rtok->pass_site = 1; break; } \
2552 } \
2553 } \
2554 } \
2555 else if ( atok->nsamples )\
2556 { \
2557 for (i=0; i<atok->nsamples; i++) \
2558 { \
2559 if ( !rtok->usmpl[i] ) continue; \
2560 double *aptr = atok->values + i*atok->nval1; \
2561 double *bptr = btok->values; \
2562 for (j=0; j<atok->nval1; j++) \
2563 { \
2564 if ( atok->idx==-3 && bcf_double_is_vector_end(aptr[j]) ) break; /* explained above */ \
2565 int miss = bcf_double_is_missing_or_vector_end(aptr[j]) ? 1 : 0; \
2566 if ( miss && !missing_logic[0] ) continue; /* any is missing => result is false */ \
2567 for (k=0; k<btok->nvalues; k++) \
2568 { \
2569 int nmiss = miss + (bcf_double_is_missing_or_vector_end(bptr[k]) ? 1 : 0); \
2570 if ( nmiss ) \
2571 { \
2572 if ( missing_logic[nmiss] ) { rtok->pass_samples[i] = 1; rtok->pass_site = 1; j = atok->nval1; break; } \
2573 } \
2574 else if ( aptr[j] > 16777216 || bptr[k] > 16777216 ) /* Ugly, see #871 */ \
2575 { \
2576 if ( aptr[j] CMP_OP bptr[k] ) { rtok->pass_samples[i] = 1; rtok->pass_site = 1; j = atok->nval1; break; } \
2577 } \
2578 else if ( (float)aptr[j] CMP_OP (float)bptr[k] ) { rtok->pass_samples[i] = 1; rtok->pass_site = 1; j = atok->nval1; break; } \
2579 } \
2580 } \
2581 } \
2582 } \
2583 else /* btok->nsamples */ \
2584 { \
2585 for (i=0; i<btok->nsamples; i++) \
2586 { \
2587 if ( !rtok->usmpl[i] ) continue; \
2588 double *aptr = atok->values; \
2589 double *bptr = btok->values + i*btok->nval1; \
2590 for (j=0; j<btok->nval1; j++) \
2591 { \
2592 if ( atok->idx==-3 && bcf_double_is_vector_end(bptr[j]) ) break; /* explained above */ \
2593 int miss = bcf_double_is_missing_or_vector_end(bptr[j]) ? 1 : 0; \
2594 if ( miss && !missing_logic[0] ) continue; /* any is missing => result is false */ \
2595 for (k=0; k<atok->nvalues; k++) \
2596 { \
2597 int nmiss = miss + (bcf_double_is_missing_or_vector_end(aptr[k]) ? 1 : 0); \
2598 if ( nmiss ) \
2599 { \
2600 if ( missing_logic[nmiss] ) { rtok->pass_samples[i] = 1; rtok->pass_site = 1; j = btok->nval1; break; } \
2601 } \
2602 else if ( bptr[j] > 16777216 || aptr[k] > 16777216 ) /* Ugly, see #871 */ \
2603 { \
2604 if ( aptr[k] CMP_OP bptr[j] ) { rtok->pass_samples[i] = 1; rtok->pass_site = 1; j = btok->nval1; break; } \
2605 } \
2606 else if ( (float)aptr[k] CMP_OP (float)bptr[j] ) { rtok->pass_samples[i] = 1; rtok->pass_site = 1; j = btok->nval1; break; } \
2607 } \
2608 } \
2609 } \
2610 } \
2611 } \
2612 }
2613 static int _regex_vector_strings(regex_t *regex, char *str, size_t len, int logic, int *missing_logic)
2614 {
2615 char *end = str + len;
2616 while ( str < end && *str )
2617 {
2618 char *mid = str;
2619 while ( mid < end && *mid && *mid!=',' ) mid++;
2620 int miss = mid - str == 1 && str[0]=='.' ? 1 : 0;
2621 if ( miss && missing_logic[miss] ) return 1;
2622 char tmp = *mid; *mid = 0;
2623 int match = regexec(regex, str, 0,NULL,0) ? 0 : 1;
2624 *mid = tmp;
2625 if ( logic==TOK_NLIKE ) match = match ? 0 : 1;
2626 if ( match ) return 1;
2627 if ( !*mid ) break;
2628 str = mid + 1;
2629 }
2630 return 0;
2631 }
2632 static inline int _has_missing_string(char *beg)
2633 {
2634 while ( *beg )
2635 {
2636 char *end = beg;
2637 while ( *end && *end!=',' ) end++;
2638 if ( end-beg==1 && beg[0]=='.' ) return 1;
2639 if ( !*end ) break;
2640 beg = end + 1;
2641 }
2642 return 0;
2643 }
2644
2645 // Compare two strings with multiple fields, for example "A,B,.,C"=="X,Y,A".
2646 // Returns 1 if any field matches, otherwise returns 0
2647 static inline int _match_vector_strings(char *abeg, size_t alen, char *bstr, size_t blen, int logic, int *missing_logic)
2648 {
2649 char *aend = abeg + alen;
2650 char *bend = bstr + blen;
2651 while ( abeg < aend && *abeg )
2652 {
2653 char *amid = abeg;
2654 while ( amid < aend && *amid && *amid!=',' ) amid++;
2655 int miss = amid - abeg == 1 && abeg[0]=='.' ? 1 : 0;
2656 char *bbeg = bstr;
2657 while ( bbeg < bend && *bbeg )
2658 {
2659 char *bmid = bbeg;
2660 while ( bmid < bend && *bmid && *bmid!=',' ) bmid++;
2661 int nmiss = miss + (bmid - bbeg == 1 && bbeg[0]=='.' ? 1 : 0);
2662 if ( nmiss )
2663 {
2664 if ( missing_logic[nmiss] ) return 1;
2665 }
2666 else
2667 {
2668 int match = amid-abeg==bmid-bbeg && !strncmp(abeg,bbeg,amid-abeg) ? 1 : 0;
2669 if ( logic==TOK_NE ) match = match==1 ? 0 : 1;
2670 if ( match ) return 1;
2671 }
2672 if ( !*bmid ) break;
2673 bbeg = bmid + 1;
2674 }
2675 if ( !*amid ) break;
2676 abeg = amid + 1;
2677 }
2678 return 0;
2679 }
2680 static void cmp_vector_strings(token_t *atok, token_t *btok, token_t *rtok)
2681 {
2682 tok_init_samples(atok, btok, rtok);
2683
2684 int i, logic = rtok->tok_type; // TOK_EQ, TOK_NE, TOK_LIKE, TOK_NLIKE
2685 regex_t *regex = atok->regex ? atok->regex : (btok->regex ? btok->regex : NULL);
2686
2687 assert( atok->nvalues==atok->str_value.l && btok->nvalues==btok->str_value.l );
2688 assert( !atok->nsamples || !btok->nsamples );
2689 assert( (!regex && (logic==TOK_EQ || logic==TOK_NE)) || (regex && (logic==TOK_LIKE || logic==TOK_NLIKE)) );
2690
2691 int missing_logic[] = {0,0,0};
2692 if ( logic==TOK_EQ || logic==TOK_LIKE ) missing_logic[0] = missing_logic[2] = 1;
2693 else if ( logic==TOK_NE || logic==TOK_NLIKE ) missing_logic[0] = missing_logic[1] = 1;
2694
2695 if ( !atok->nsamples && !btok->nsamples )
2696 {
2697 if ( !atok->nvalues && !btok->nvalues ) { rtok->pass_site = missing_logic[2]; return; }
2698 if ( !atok->nvalues || !btok->nvalues )
2699 {
2700 int miss = _has_missing_string(atok->nvalues ? atok->str_value.s : btok->str_value.s);
2701 if ( missing_logic[miss+1] ) rtok->pass_site = 1;
2702 return;
2703 }
2704 if ( !regex )
2705 rtok->pass_site = _match_vector_strings(atok->str_value.s, atok->str_value.l, btok->str_value.s, btok->str_value.l, logic, missing_logic);
2706 else
2707 {
2708 token_t *tok = atok->regex ? btok : atok;
2709 rtok->pass_site = _regex_vector_strings(regex, tok->str_value.s, tok->str_value.l, logic, missing_logic);
2710 }
2711 return;
2712 }
2713
2714 // The case of (!atok->nsamples || !btok->nsamples)
2715
2716 if ( !atok->nvalues && !btok->nvalues )
2717 {
2718 if ( missing_logic[2] )
2719 {
2720 for (i=0; i<rtok->nsamples; i++)
2721 if ( rtok->usmpl[i] ) { rtok->pass_samples[i] = missing_logic[2]; rtok->pass_site = 1; }
2722 }
2723 return;
2724 }
2725 if ( !atok->nvalues || !btok->nvalues )
2726 {
2727 token_t *tok = atok->nvalues ? atok : btok;
2728 if ( !tok->nsamples )
2729 {
2730 int miss = _has_missing_string(tok->str_value.s);
2731 if ( !missing_logic[miss+1] ) return;
2732 for (i=0; i<rtok->nsamples; i++)
2733 if ( rtok->usmpl[i] ) { rtok->pass_samples[i] = 1; rtok->pass_site = 1; }
2734 }
2735 else
2736 for (i=0; i<tok->nsamples; i++)
2737 {
2738 if ( !rtok->usmpl[i] ) continue;
2739 int miss = _has_missing_string(tok->str_value.s + i*tok->nval1);
2740 if ( missing_logic[miss+1] ) { rtok->pass_samples[i] = 1; rtok->pass_site = 1; }
2741 }
2742 return;
2743 }
2744
2745 // The case of (!atok->nsamples || !btok->nsamples) && (atok->nvalues && btok->nvalues)
2746 token_t *xtok = atok->nsamples ? atok : btok;
2747 token_t *ytok = atok->nsamples ? btok : atok;
2748 assert( regex==ytok->regex );
2749 for (i=0; i<xtok->nsamples; i++)
2750 {
2751 if ( !rtok->usmpl[i] ) continue;
2752 int match;
2753 if ( regex )
2754 match = _regex_vector_strings(regex, xtok->str_value.s + i*xtok->nval1, xtok->nval1, logic, missing_logic);
2755 else
2756 match = _match_vector_strings(xtok->str_value.s + i*xtok->nval1, xtok->nval1, ytok->str_value.s, ytok->str_value.l, logic, missing_logic);
2757 if ( match ) { rtok->pass_samples[i] = 1; rtok->pass_site = 1; }
2758 }
2759 }
2760
2761 static int parse_idxs(char *tag_idx, int **idxs, int *nidxs, int *idx)
2762 {
2763 // TAG[], TAG[*] .. any field; sets idx=-2, idxs[0]=-1
2764 if ( *tag_idx==0 || !strcmp("*", tag_idx) )
2765 {
2766 *idxs = (int*) malloc(sizeof(int));
2767 (*idxs)[0] = -1;
2768 *nidxs = 1;
2769 *idx = -2;
2770 return 0;
2771 }
2772 if ( !strcmp("GT", tag_idx) )
2773 {
2774 *idxs = (int*) malloc(sizeof(int));
2775 (*idxs)[0] = -1;
2776 *nidxs = 1;
2777 *idx = -3;
2778 return 0;
2779 }
2780
2781 // TAG[integer] .. one field; idx positive
2782 char *end, *beg = tag_idx;
2783 *idx = strtol(tag_idx, &end, 10);
2784 if ( *idx >= 0 && *end==0 ) return 0;
2785
2786 // TAG[0,1] or TAG[0-2] or [1-] etc; idx=-2, idxs[...]=0,0,1,1,..
2787 int i, ibeg = -1;
2788 while ( *beg )
2789 {
2790 int num = strtol(beg, &end, 10);
2791 if ( end[0]==',' ) beg = end + 1;
2792 else if ( end[0]==0 ) beg = end;
2793 else if ( end[0]=='-' ) { beg = end + 1; ibeg = num; continue; }
2794 else return -1;
2795 if ( num >= *nidxs )
2796 {
2797 *idxs = (int*) realloc(*idxs, sizeof(int)*(num+1));
2798 memset(*idxs + *nidxs, 0, sizeof(int)*(num - *nidxs + 1));
2799 *nidxs = num + 1;
2800 }
2801 if ( ibeg>=0 )
2802 {
2803 for (i=ibeg; i<=num; i++) (*idxs)[i] = 1;
2804 ibeg = -1;
2805 }
2806 (*idxs)[num] = 1;
2807 }
2808 if ( ibeg >=0 )
2809 {
2810 if ( ibeg >= *nidxs )
2811 {
2812 *idxs = (int*) realloc(*idxs, sizeof(int)*(ibeg+1));
2813 memset(*idxs + *nidxs, 0, sizeof(int)*(ibeg - *nidxs + 1));
2814 *nidxs = ibeg + 1;
2815 }
2816 (*idxs)[ibeg] = -1;
2817 }
2818 *idx = -2;
2819 return 0;
2820 }
2821
2822 static void parse_tag_idx(bcf_hdr_t *hdr, int is_fmt, char *tag, char *tag_idx, token_t *tok) // tag_idx points just after "TAG["
2823 {
2824 int i, len = strlen(tag_idx);
2825 if ( tag_idx[len-1] == ']' ) tag_idx[len-1] = 0;
2826 char *ori = strdup(tag_idx);
2827
2828 assert( !tok->idxs && !tok->usmpl );
2829 int *idxs1 = NULL, nidxs1 = 0, idx1 = 0;
2830 int *idxs2 = NULL, nidxs2 = 0, idx2 = 0;
2831
2832 int set_samples = 0;
2833 char *colon = strrchr(tag_idx, ':');
2834 if ( tag_idx[0]=='@' ) // file list with sample names
2835 {
2836 if ( !is_fmt ) error("Could not parse \"%s\". (Not a FORMAT tag yet a sample list provided.)\n", ori);
2837 char *fname = expand_path(tag_idx+1);
2838 #ifdef _WIN32
2839 if (fname && strlen(fname) > 2 && fname[1] == ':') // Deal with Windows paths, such as 'C:\..'
2840 colon = strrchr(fname+2, ':');
2841 #endif
2842 int nsmpl;
2843 char **list = hts_readlist(fname, 1, &nsmpl);
2844 if ( !list && colon )
2845 {
2846 if ( parse_idxs(colon+1, &idxs2, &nidxs2, &idx2) != 0 ) error("Could not parse the index: %s\n", ori);
2847 tok->idxs = idxs2;
2848 tok->nidxs = nidxs2;
2849 tok->idx = idx2;
2850 colon = strrchr(fname, ':');
2851 *colon = 0;
2852 list = hts_readlist(fname, 1, &nsmpl);
2853 }
2854 if ( !list ) error("Could not read: %s\n", fname);
2855 free(fname);
2856 tok->nsamples = bcf_hdr_nsamples(hdr);
2857 tok->usmpl = (uint8_t*) calloc(tok->nsamples,1);
2858 for (i=0; i<nsmpl; i++)
2859 {
2860 int ismpl = bcf_hdr_id2int(hdr,BCF_DT_SAMPLE,list[i]);
2861 if ( ismpl<0 ) error("No such sample in the VCF: \"%s\"\n", list[i]);
2862 free(list[i]);
2863 tok->usmpl[ismpl] = 1;
2864 }
2865 free(list);
2866 if ( !colon )
2867 {
2868 tok->idxs = (int*) malloc(sizeof(int));
2869 tok->idxs[0] = -1;
2870 tok->nidxs = 1;
2871 tok->idx = -2;
2872 }
2873 }
2874 else if ( colon )
2875 {
2876 if ( !is_fmt ) error("Could not parse the index \"%s\". (Not a FORMAT tag yet sample index implied.)\n", ori);
2877 *colon = 0;
2878 if ( parse_idxs(tag_idx, &idxs1, &nidxs1, &idx1) != 0 ) error("Could not parse the index: %s\n", ori);
2879 if ( parse_idxs(colon+1, &idxs2, &nidxs2, &idx2) != 0 ) error("Could not parse the index: %s\n", ori);
2880 tok->idxs = idxs2;
2881 tok->nidxs = nidxs2;
2882 tok->idx = idx2;
2883 set_samples = 1;
2884 }
2885 else
2886 {
2887 if ( parse_idxs(tag_idx, &idxs1, &nidxs1, &idx1) != 0 ) error("Could not parse the index: %s\n", ori);
2888 if ( is_fmt )
2889 {
2890 if ( nidxs1==1 && idxs1[0]==-1 )
2891 {
2892 tok->idxs = (int*) malloc(sizeof(int));
2893 tok->idxs[0] = -1;
2894 tok->nidxs = 1;
2895 tok->idx = idx1;
2896 }
2897 else if ( bcf_hdr_id2number(hdr,BCF_HL_FMT,tok->hdr_id)!=1 )
2898 error("The FORMAT tag %s can have multiple subfields, run as %s[sample:subfield]\n", tag,tag);
2899 else
2900 tok->idx = 0;
2901 set_samples = 1;
2902 }
2903 else
2904 {
2905 tok->idxs = idxs1;
2906 tok->nidxs = nidxs1;
2907 tok->idx = idx1;
2908 }
2909 }
2910
2911 if ( set_samples )
2912 {
2913 tok->nsamples = bcf_hdr_nsamples(hdr);
2914 tok->usmpl = (uint8_t*) calloc(tok->nsamples,1);
2915 if ( idx1>=0 )
2916 {
2917 if ( idx1 >= bcf_hdr_nsamples(hdr) ) error("The sample index is too large: %s\n", ori);
2918 tok->usmpl[idx1] = 1;
2919 }
2920 else if ( idx1==-2 || idx1==-3 )
2921 {
2922 for (i=0; i<nidxs1; i++)
2923 {
2924 if ( idxs1[i]==0 ) continue;
2925 if ( idxs1[i]==-1 ) break;
2926 if ( i >= bcf_hdr_nsamples(hdr) ) error("The sample index is too large: %s\n", ori);
2927 tok->usmpl[i] = 1;
2928 }
2929 if ( nidxs1 && idxs1[nidxs1-1]==-1 ) // open range, such as "7-"
2930 {
2931 for (; i<tok->nsamples; i++) tok->usmpl[i] = 1;
2932 }
2933 }
2934 else error("todo: %s:%d .. %d\n", __FILE__,__LINE__, idx2);
2935 free(idxs1);
2936 }
2937 free(ori);
2938
2939 if ( tok->nidxs && tok->idxs[tok->nidxs-1]!=-1 )
2940 {
2941 for (i=0; i<tok->nidxs; i++) if ( tok->idxs[i] ) tok->nuidxs++;
2942 }
2943 }
2944 static int max_ac_an_unpack(bcf_hdr_t *hdr)
2945 {
2946 int hdr_id = bcf_hdr_id2int(hdr,BCF_DT_ID,"AC");
2947 if ( hdr_id<0 ) return BCF_UN_FMT;
2948 if ( !bcf_hdr_idinfo_exists(hdr,BCF_HL_INFO,hdr_id) ) return BCF_UN_FMT;
2949
2950 hdr_id = bcf_hdr_id2int(hdr,BCF_DT_ID,"AN");
2951 if ( hdr_id<0 ) return BCF_UN_FMT;
2952 if ( !bcf_hdr_idinfo_exists(hdr,BCF_HL_INFO,hdr_id) ) return BCF_UN_FMT;
2953
2954 return BCF_UN_INFO;
2955 }
2956 static int filters_init1_ext(filter_t *filter, char *str, int len, token_t *tok)
2957 {
2958 tok->hl_type = -1;
2959 tok->ht_type = -1;
2960 tok->tok_type = TOK_VAL;
2961 tok->hdr_id = -1;
2962 tok->pass_site = -1;
2963 tok->idx = 0;
2964 tok->iext = ++filter->n_ext;
2965 filter->ext = realloc(filter->ext,sizeof(*filter->ext)*filter->n_ext);
2966 if ( !strncasecmp(str,"{str}",len) ) { tok->ht_type = BCF_HT_STR; tok->is_str = 1; }
2967 else if ( !strncasecmp(str,"{int}",len) ) tok->ht_type = BCF_HT_INT;
2968 else if ( !strncasecmp(str,"{float}",len) ) tok->ht_type = BCF_HT_REAL;
2969 filter->ext[filter->n_ext-1] = tok->ht_type;
2970 return 0;
2971 }
2972 static int filters_init1(filter_t *filter, char *str, int len, token_t *tok)
2973 {
2974 tok->ht_type = -1;
2975 tok->hl_type = -1;
2976 tok->tok_type = TOK_VAL;
2977 tok->hdr_id = -1;
2978 tok->pass_site = -1;
2979 tok->idx = 0;
2980
2981 // is this a string constant?
2982 if ( str[0]=='"' || str[0]=='\'' )
2983 {
2984 int quote = str[0];
2985 if ( str[len-1] != quote ) error("TODO: [%s]\n", filter->str);
2986 tok->key = (char*) calloc(len-1,sizeof(char));
2987 hts_expand(double,1,tok->mvalues,tok->values);
2988 tok->values[0] = len-2;
2989 memcpy(tok->key,str+1,len-2);
2990 tok->key[len-2] = 0;
2991 tok->is_str = 1;
2992 tok->ht_type = BCF_HT_STR;
2993 tok->nvalues = len-2;
2994 if ( !strcmp(".",tok->key) ) tok->is_missing = 1;
2995 return 0;
2996 }
2997
2998 // is it a file?
2999 if ( str[0]=='@' )
3000 {
3001 tok->tag = (char*) calloc(len+1,sizeof(char));
3002 memcpy(tok->tag,str,len);
3003 tok->tag[len] = 0;
3004 char *fname = expand_path(tok->tag+1);
3005 int i, n;
3006 char **list = hts_readlist(fname, 1, &n);
3007 if ( !list ) error("Could not read: %s\n", fname);
3008 free(fname);
3009 tok->hash = khash_str2int_init();
3010 for (i=0; i<n; i++)
3011 {
3012 char *se = list[i];
3013 while ( *se && !isspace(*se) ) se++;
3014 *se = 0;
3015 if ( !khash_str2int_has_key(tok->hash,list[i]) )
3016 khash_str2int_inc(tok->hash,list[i]);
3017 else
3018 free(list[i]);
3019 }
3020 free(list);
3021 return 0;
3022 }
3023
3024 int is_fmt = -1;
3025 if ( !strncasecmp(str,"FMT/",4) ) { str += 4; len -= 4; is_fmt = 1; }
3026 else if ( !strncasecmp(str,"FORMAT/",7) ) { str += 7; len -= 7; is_fmt = 1; }
3027 else
3028 {
3029 if ( !strncasecmp(str,"INFO/",5) ) { is_fmt = 0; str += 5; len -= 5; }
3030 else if ( !strncasecmp(str,"QUAL",len) || !strncmp(str,"%QUAL",len) /* for backward compatibility */ )
3031 {
3032 tok->setter = filters_set_qual;
3033 tok->tag = strdup("QUAL");
3034 tok->ht_type = BCF_HT_REAL;
3035 filter_add_used_tag(filter,NULL,tok->tag);
3036 return 0;
3037 }
3038 else if ( !strncasecmp(str,"TYPE",len) || !strncmp(str,"%TYPE",len) /* for backward compatibility */ )
3039 {
3040 tok->setter = filters_set_type;
3041 tok->tag = strdup("TYPE");
3042 tok->ht_type = BCF_HT_STR;
3043 return 0;
3044 }
3045 else if ( !strncasecmp(str,"FILTER",len) || !strncmp(str,"%FILTER",len) /* for backward compatibility */ )
3046 {
3047 tok->comparator = filters_cmp_filter;
3048 tok->tag = strdup("FILTER");
3049 filter->max_unpack |= BCF_UN_FLT;
3050 tok->hl_type = BCF_HL_FLT;
3051 tok->ht_type = BCF_HT_STR;
3052 filter_add_used_tag(filter,NULL,tok->tag);
3053 return 0;
3054 }
3055 else if ( !strncasecmp(str,"ID",len) || !strncasecmp(str,"%ID",len) /* for backward compatibility */ )
3056 {
3057 tok->comparator = filters_cmp_id;
3058 tok->tag = strdup("ID");
3059 tok->ht_type = BCF_HT_STR;
3060 filter_add_used_tag(filter,NULL,tok->tag);
3061 return 0;
3062 }
3063 else if ( !strncasecmp(str,"CHROM",len) )
3064 {
3065 tok->setter = &filters_set_chrom;
3066 tok->tag = strdup("CHROM");
3067 tok->ht_type = BCF_HT_STR;
3068 filter_add_used_tag(filter,NULL,tok->tag);
3069 return 0;
3070 }
3071 else if ( !strncasecmp(str,"POS",len) )
3072 {
3073 tok->setter = &filters_set_pos;
3074 tok->tag = strdup("POS");
3075 tok->ht_type = BCF_HT_INT;
3076 filter_add_used_tag(filter,NULL,tok->tag);
3077 return 0;
3078 }
3079 else if ( !strncasecmp(str,"REF",len) )
3080 {
3081 tok->setter = &filters_set_ref_string;
3082 tok->is_str = 1;
3083 tok->tag = strdup("REF");
3084 tok->ht_type = BCF_HT_STR;
3085 filter_add_used_tag(filter,NULL,tok->tag);
3086 return 0;
3087 }
3088 else if ( !strncasecmp(str,"ALT",len) )
3089 {
3090 tok->setter = &filters_set_alt_string;
3091 tok->is_str = 1;
3092 tok->tag = strdup("ALT");
3093 tok->ht_type = BCF_HT_STR;
3094 tok->idxs = (int*) malloc(sizeof(int));
3095 tok->idxs[0] = -1;
3096 tok->nidxs = 1;
3097 tok->idx = -2;
3098 filter_add_used_tag(filter,NULL,tok->tag);
3099 return 0;
3100 }
3101 else if ( !strncasecmp(str,"N_ALT",len) )
3102 {
3103 tok->setter = &filters_set_nalt;
3104 tok->tag = strdup("N_ALT");
3105 tok->ht_type = BCF_HT_INT;
3106 return 0;
3107 }
3108 else if ( !strncasecmp(str,"N_SAMPLES",len) )
3109 {
3110 tok->tok_type = TOK_VAL;
3111 tok->threshold = bcf_hdr_nsamples(filter->hdr);
3112 tok->is_constant = 1;
3113 tok->ht_type = BCF_HT_INT;
3114 return 0;
3115 }
3116 else if ( !strncasecmp(str,"N_MISSING",len) )
3117 {
3118 filter->max_unpack |= BCF_UN_FMT;
3119 tok->setter = &filters_set_nmissing;
3120 tok->tag = strdup("N_MISSING");
3121 tok->ht_type = BCF_HT_INT;
3122 return 0;
3123 }
3124 else if ( !strncasecmp(str,"F_MISSING",len) )
3125 {
3126 filter->max_unpack |= BCF_UN_FMT;
3127 tok->setter = &filters_set_nmissing;
3128 tok->tag = strdup("F_MISSING");
3129 tok->ht_type = BCF_HT_REAL;
3130 return 0;
3131 }
3132 }
3133
3134 // does it have array subscript?
3135 int is_array = 0;
3136 kstring_t tmp = {0,0,0};
3137 kputsn(str, len, &tmp);
3138 if ( tmp.s[tmp.l-1] == ']' )
3139 {
3140 int i;
3141 for (i=0; i<tmp.l; i++)
3142 if ( tmp.s[i]=='[' ) { tmp.s[i] = 0; is_array = i+1; break; }
3143 }
3144 tok->hdr_id = bcf_hdr_id2int(filter->hdr,BCF_DT_ID,tmp.s);
3145 if ( is_fmt==-1 )
3146 {
3147 if ( tok->hdr_id >=0 )
3148 {
3149 int is_info = bcf_hdr_idinfo_exists(filter->hdr,BCF_HL_INFO,tok->hdr_id) ? 1 : 0;
3150 is_fmt = bcf_hdr_idinfo_exists(filter->hdr,BCF_HL_FMT,tok->hdr_id) ? 1 : 0;
3151 if ( is_info && is_fmt )
3152 error("Error: ambiguous filtering expression, both INFO/%s and FORMAT/%s are defined in the VCF header.\n" , tmp.s,tmp.s);
3153 }
3154 if ( is_fmt==-1 ) is_fmt = 0;
3155 }
3156 if ( is_array )
3157 {
3158 parse_tag_idx(filter->hdr, is_fmt, tmp.s, tmp.s+is_array, tok);
3159 if ( tok->idx==-3 && bcf_hdr_id2length(filter->hdr,BCF_HL_FMT,tok->hdr_id)!=BCF_VL_R )
3160 error("Error: GT subscripts can be used only with Number=R tags\n");
3161 }
3162 else if ( is_fmt && !tok->nsamples )
3163 {
3164 int i;
3165 tok->nsamples = bcf_hdr_nsamples(filter->hdr);
3166 tok->usmpl = (uint8_t*) malloc(tok->nsamples);
3167 for (i=0; i<tok->nsamples; i++) tok->usmpl[i] = 1;
3168 }
3169
3170 tok->hl_type = is_fmt ? BCF_HL_FMT : BCF_HL_INFO;
3171 if ( is_fmt ) filter->max_unpack |= BCF_UN_FMT;
3172 if ( tok->hdr_id>=0 )
3173 {
3174 if ( is_fmt && !strcmp("GT",tmp.s) )
3175 {
3176 tok->setter = &filters_set_genotype_string; tok->is_str = 1;
3177 tok->ht_type = BCF_HT_STR;
3178 }
3179 else if ( is_fmt )
3180 {
3181 if ( !bcf_hdr_idinfo_exists(filter->hdr,BCF_HL_FMT,tok->hdr_id) )
3182 error("No such FORMAT field: %s\n", tmp.s);
3183 if ( bcf_hdr_id2number(filter->hdr,BCF_HL_FMT,tok->hdr_id)!=1 && !is_array )
3184 {
3185 tok->idxs = (int*) malloc(sizeof(int));
3186 tok->idxs[0] = -1;
3187 tok->nidxs = 1;
3188 tok->idx = -2;
3189 }
3190 switch ( bcf_hdr_id2type(filter->hdr,BCF_HL_FMT,tok->hdr_id) )
3191 {
3192 case BCF_HT_INT: tok->setter = &filters_set_format_int; tok->ht_type = BCF_HT_INT; break;
3193 case BCF_HT_REAL: tok->setter = &filters_set_format_float; tok->ht_type = BCF_HT_REAL; break;
3194 case BCF_HT_STR: tok->setter = &filters_set_format_string; tok->ht_type = BCF_HT_STR; tok->is_str = 1; break;
3195 default: error("[%s:%d %s] FIXME\n", __FILE__,__LINE__,__FUNCTION__);
3196 }
3197 }
3198 else if ( !bcf_hdr_idinfo_exists(filter->hdr,BCF_HL_INFO,tok->hdr_id) )
3199 error("No such INFO field: %s\n", tmp.s);
3200 else
3201 {
3202 if ( bcf_hdr_id2type(filter->hdr,BCF_HL_INFO,tok->hdr_id) == BCF_HT_FLAG )
3203 {
3204 tok->setter = filters_set_info_flag;
3205 tok->ht_type = BCF_HT_INT;
3206 }
3207 else
3208 {
3209 tok->ht_type = bcf_hdr_id2type(filter->hdr,BCF_HL_INFO,tok->hdr_id);
3210 if ( tok->ht_type == BCF_HT_STR ) tok->is_str = 1;
3211 if ( bcf_hdr_id2number(filter->hdr,BCF_HL_INFO,tok->hdr_id)==1 )
3212 tok->setter = filters_set_info;
3213 else
3214 {
3215 switch ( bcf_hdr_id2type(filter->hdr,BCF_HL_INFO,tok->hdr_id) )
3216 {
3217 case BCF_HT_INT: tok->setter = &filters_set_info_int; break;
3218 case BCF_HT_REAL: tok->setter = &filters_set_info_float; break;
3219 case BCF_HT_STR: tok->setter = &filters_set_info_string; tok->is_str = 1; break;
3220 default: error("[%s:%d %s] FIXME\n", __FILE__,__LINE__,__FUNCTION__);
3221 }
3222 if (!is_array)
3223 {
3224 tok->idx = -2;
3225 tok->idxs = (int*) malloc(sizeof(int));
3226 tok->idxs[0] = -1;
3227 tok->nidxs = 1;
3228 }
3229 }
3230 }
3231 filter->max_unpack |= BCF_UN_INFO;
3232 }
3233 tok->tag = strdup(tmp.s);
3234 if ( tmp.s ) free(tmp.s);
3235 filter_add_used_tag(filter,is_fmt ? "FORMAT/" : "INFO/",tok->tag);
3236 return 0;
3237 }
3238 else if ( !strcasecmp(tmp.s,"ALT") )
3239 {
3240 tok->setter = &filters_set_alt_string;
3241 tok->is_str = 1;
3242 tok->ht_type = BCF_HT_STR;
3243 tok->tag = strdup(tmp.s);
3244 free(tmp.s);
3245 filter_add_used_tag(filter,NULL,tok->tag);
3246 return 0;
3247 }
3248 else if ( !strcasecmp(tmp.s,"AN") )
3249 {
3250 filter->max_unpack |= BCF_UN_FMT;
3251 tok->setter = &filters_set_an;
3252 tok->tag = strdup("AN");
3253 tok->ht_type = BCF_HT_INT;
3254 free(tmp.s);
3255 return 0;
3256 }
3257 else if ( !strcasecmp(tmp.s,"AC") )
3258 {
3259 filter->max_unpack |= BCF_UN_FMT;
3260 tok->setter = &filters_set_ac;
3261 tok->tag = strdup("AC");
3262 tok->ht_type = BCF_HT_INT;
3263 free(tmp.s);
3264 return 0;
3265 }
3266 else if ( !strcasecmp(tmp.s,"MAC") )
3267 {
3268 filter->max_unpack |= max_ac_an_unpack(filter->hdr);
3269 tok->setter = &filters_set_mac;
3270 tok->tag = strdup("MAC");
3271 tok->ht_type = BCF_HT_INT;
3272 free(tmp.s);
3273 return 0;
3274 }
3275 else if ( !strcasecmp(tmp.s,"AF") )
3276 {
3277 filter->max_unpack |= max_ac_an_unpack(filter->hdr);
3278 tok->setter = &filters_set_af;
3279 tok->tag = strdup("AF");
3280 tok->ht_type = BCF_HT_REAL;
3281 free(tmp.s);
3282 return 0;
3283 }
3284 else if ( !strcasecmp(tmp.s,"MAF") )
3285 {
3286 filter->max_unpack |= max_ac_an_unpack(filter->hdr);
3287 tok->setter = &filters_set_maf;
3288 tok->tag = strdup("MAF");
3289 tok->ht_type = BCF_HT_REAL;
3290 free(tmp.s);
3291 return 0;
3292 }
3293 else if ( !strcasecmp(tmp.s,"ILEN") || !strcasecmp(tmp.s,"%ILEN") )
3294 {
3295 filter->max_unpack |= BCF_UN_STR;
3296 tok->setter = &filters_set_ilen;
3297 tok->tag = strdup("ILEN");
3298 tok->ht_type = BCF_HT_INT;
3299 free(tmp.s);
3300 return 0;
3301 }
3302
3303 // is it a value? Here we parse as integer/float separately and use strtof
3304 // rather than strtod, because the more accurate double representation
3305 // would invalidate floating point comparisons like QUAL=59.2, obtained via
3306 // htslib/vcf parser.
3307 // Update: use strtod() and force floats only in comparisons
3308 char *end;
3309 tok->threshold = strtol(tmp.s, &end, 10); // integer?
3310 if ( end - tmp.s != strlen(tmp.s) )
3311 {
3312 errno = 0;
3313 tok->threshold = strtod(tmp.s, &end); // float?
3314 if ( errno!=0 || end!=tmp.s+len )
3315 {
3316 if ( filter->exit_on_error )
3317 error("[%s:%d %s] Error: the tag \"%s\" is not defined in the VCF header\n", __FILE__,__LINE__,__FUNCTION__,tmp.s);
3318 filter->status |= FILTER_ERR_UNKN_TAGS;
3319 filter_add_undef_tag(filter,tmp.s);
3320 }
3321 tok->ht_type = BCF_HT_REAL;
3322 }
3323 else
3324 tok->ht_type = BCF_HT_INT;
3325 tok->is_constant = 1;
3326
3327 if ( tmp.s ) free(tmp.s);
3328 return 0;
3329 }
3330
3331 static void filter_debug_print(token_t *toks, token_t **tok_ptrs, int ntoks)
3332 {
3333 int i;
3334 for (i=0; i<ntoks; i++)
3335 {
3336 token_t *tok = toks ? &toks[i] : tok_ptrs[i];
3337 if ( tok->tok_type==TOK_VAL )
3338 {
3339 if ( tok->key )
3340 fprintf(stderr,"%s", tok->key);
3341 else if ( tok->tag )
3342 fprintf(stderr,"%s", tok->tag);
3343 else
3344 fprintf(stderr,"%e", tok->threshold);
3345 }
3346 else
3347 fprintf(stderr,"%c", TOKEN_STRING[tok->tok_type]);
3348 if ( tok->setter ) fprintf(stderr,"\t[setter %p]", tok->setter);
3349 fprintf(stderr,"\n");
3350 }
3351 }
3352
3353 static void str_to_lower(char *str)
3354 {
3355 while ( *str ) { *str = tolower(*str); str++; }
3356 }
3357 static int perl_exec(filter_t *flt, bcf1_t *line, token_t *rtok, token_t **stack, int nstack)
3358 {
3359 #if ENABLE_PERL_FILTERS
3360
3361 PerlInterpreter *perl = flt->perl;
3362 if ( !perl ) error("Error: perl expression without a perl script name\n");
3363
3364 dSP;
3365 ENTER;
3366 SAVETMPS;
3367
3368 PUSHMARK(SP);
3369 int i,j, istack = nstack - rtok->nargs;
3370 for (i=istack+1; i<nstack; i++)
3371 {
3372 token_t *tok = stack[i];
3373 if ( tok->is_str )
3374 XPUSHs(sv_2mortal(newSVpvn(tok->str_value.s,tok->str_value.l)));
3375 else if ( tok->nvalues==1 )
3376 XPUSHs(sv_2mortal(newSVnv(tok->values[0])));
3377 else if ( tok->nvalues>1 )
3378 {
3379 AV *av = newAV();
3380 for (j=0; j<tok->nvalues; j++) av_push(av, newSVnv(tok->values[j]));
3381 SV *rv = newRV_inc((SV*)av);
3382 XPUSHs(rv);
3383 }
3384 else
3385 {
3386 bcf_double_set_missing(tok->values[0]);
3387 XPUSHs(sv_2mortal(newSVnv(tok->values[0])));
3388 }
3389 }
3390 PUTBACK;
3391
3392 // A possible future todo: provide a means to select samples and indexes,
3393 // expressions like this don't work yet
3394 // perl.filter(FMT/AD)[1:0]
3395
3396 int nret = call_pv(stack[istack]->str_value.s, G_ARRAY);
3397
3398 SPAGAIN;
3399
3400 rtok->nvalues = nret;
3401 hts_expand(double, rtok->nvalues, rtok->mvalues, rtok->values);
3402 for (i=nret; i>0; i--)
3403 {
3404 rtok->values[i-1] = (double) POPn;
3405 if ( isnan(rtok->values[i-1]) ) bcf_double_set_missing(rtok->values[i-1]);
3406 }
3407
3408 PUTBACK;
3409 FREETMPS;
3410 LEAVE;
3411
3412 #else
3413 error("\nPerl filtering requires running `configure --enable-perl-filters` at compile time.\n\n");
3414 #endif
3415 return rtok->nargs;
3416 }
3417 static void perl_init(filter_t *filter, char **str)
3418 {
3419 char *beg = *str;
3420 while ( *beg && isspace(*beg) ) beg++;
3421 if ( !*beg ) return;
3422 if ( strncasecmp("perl:", beg, 5) ) return;
3423 #if ENABLE_PERL_FILTERS
3424 beg += 5;
3425 char *end = beg;
3426 while ( *end && *end!=';' ) end++; // for now not escaping semicolons
3427 *str = end+1;
3428
3429 if ( ++filter_ninit == 1 )
3430 {
3431 // must be executed only once, even for multiple filters; first time here
3432 int argc = 0;
3433 char **argv = NULL;
3434 char **env = NULL;
3435 PERL_SYS_INIT3(&argc, &argv, &env);
3436 }
3437
3438 filter->perl = perl_alloc();
3439 PerlInterpreter *perl = filter->perl;
3440
3441 if ( !perl ) error("perl_alloc failed\n");
3442 perl_construct(perl);
3443
3444 // name of the perl script to run
3445 char *rmme = (char*) calloc(end - beg + 1,1);
3446 memcpy(rmme, beg, end - beg);
3447 char *argv[] = { "", "" };
3448 argv[1] = expand_path(rmme);
3449 free(rmme);
3450
3451 PL_origalen = 1; // don't allow $0 change
3452 int ret = perl_parse(filter->perl, NULL, 2, argv, NULL);
3453 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
3454 if ( ret ) error("Failed to parse: %s\n", argv[1]);
3455 free(argv[1]);
3456
3457 perl_run(perl);
3458 #else
3459 error("\nPerl filtering requires running `configure --enable-perl-filters` at compile time.\n\n");
3460 #endif
3461 }
3462 static void perl_destroy(filter_t *filter)
3463 {
3464 #if ENABLE_PERL_FILTERS
3465 if ( !filter->perl ) return;
3466
3467 PerlInterpreter *perl = filter->perl;
3468 perl_destruct(perl);
3469 perl_free(perl);
3470 if ( --filter_ninit <= 0 )
3471 {
3472 // similarly to PERL_SYS_INIT3, can must be executed only once? todo: test
3473 PERL_SYS_TERM();
3474 }
3475 #endif
3476 }
3477
3478 // A very rudimentary heuristics to determine type, e.g. STR_TAG={} implies {str}.
3479 // Throws an error on anything more complex and asks for an explicit type.
3480 static void determine_ext_types(filter_t *filter, int ntok, token_t *tok)
3481 {
3482 int i;
3483 for (i=0; i<ntok; i++)
3484 {
3485 if ( !tok[i].iext || tok[i].ht_type!=-1 ) continue;
3486 if ( !i || i+1==ntok ) break; // first or last in the RPN
3487 if ( tok[i-1].ht_type==-1 ) break; // previous type not set
3488 // todo: check if the next is an operator
3489 // todo: case when the order is reversed, {}=TAG
3490 tok[i].ht_type = tok[i-1].ht_type;
3491 }
3492 if ( i!=ntok )
3493 error("[%s:%d %s] Error: unable to determine the type, use explicit notation: %s\n",__FILE__,__LINE__,__FUNCTION__,filter->str);
3494 for (i=0; i<ntok; i++)
3495 {
3496 int j = tok[i].iext - 1;
3497 if ( j<0 ) continue;
3498 if ( filter->ext[j]!=-1 && filter->ext[j]!=tok[i].ht_type )
3499 error("[%s:%d %s] FIXME: this should not happen %d vs %d, iext=%d\n",__FILE__,__LINE__,__FUNCTION__,filter->ext[j],tok[i].ht_type,j);
3500 filter->ext[j] = tok[i].ht_type;
3501 if ( tok[i].ht_type==BCF_HT_STR ) tok[i].is_str = 1;
3502 }
3503 }
3504
3505
3506 // Parse filter expression and convert to reverse polish notation. Dijkstra's shunting-yard algorithm
3507 static filter_t *filter_init_(bcf_hdr_t *hdr, const char *str, int exit_on_error)
3508 {
3509 filter_t *filter = (filter_t *) calloc(1,sizeof(filter_t));
3510 filter->str = strdup(str);
3511 filter->hdr = hdr;
3512 filter->max_unpack |= BCF_UN_STR;
3513 filter->exit_on_error = exit_on_error;
3514
3515 int nops = 0, mops = 0; // operators stack
3516 int nout = 0, mout = 0; // filter tokens, RPN
3517 token_t *out = NULL;
3518 token_t *ops = NULL;
3519 char *tmp = filter->str;
3520 perl_init(filter, &tmp);
3521
3522 int last_op = -1;
3523 while ( *tmp )
3524 {
3525 int len, ret;
3526 ret = filters_next_token(&tmp, &len);
3527 if ( ret==-1 ) error("Missing quotes in: %s\n", str);
3528
3529 // fprintf(stderr,"token=[%c] .. [%s] %d\n", TOKEN_STRING[ret], tmp, len);
3530 // int i; for (i=0; i<nops; i++) fprintf(stderr," .%c", TOKEN_STRING[ops[i].tok_type]); fprintf(stderr,"\n");
3531
3532 if ( ret==TOK_LFT ) // left bracket
3533 {
3534 nops++;
3535 hts_expand0(token_t, nops, mops, ops);
3536 ops[nops-1].tok_type = ret;
3537 }
3538 else if ( ret==TOK_RGT ) // right bracket
3539 {
3540 while ( nops>0 && ops[nops-1].tok_type!=TOK_LFT )
3541 {
3542 nout++;
3543 hts_expand0(token_t, nout, mout, out);
3544 out[nout-1] = ops[nops-1];
3545 memset(&ops[nops-1],0,sizeof(token_t));
3546 nops--;
3547 }
3548 if ( nops<=0 ) error("Could not parse: %s\n", str);
3549 memset(&ops[nops-1],0,sizeof(token_t));
3550 nops--;
3551 }
3552 else if ( ret==TOK_EXT ) // external value
3553 {
3554 nout++;
3555 hts_expand0(token_t, nout, mout, out);
3556 filters_init1_ext(filter, tmp, len, &out[nout-1]);
3557 tmp += len;
3558 }
3559 else if ( ret!=TOK_VAL ) // one of the operators
3560 {
3561 // detect unary minus: replace -value with -1*(value)
3562 if ( ret==TOK_SUB && last_op!=TOK_VAL && last_op!=TOK_RGT )
3563 {
3564 nout++;
3565 hts_expand0(token_t, nout, mout, out);
3566 token_t *tok = &out[nout-1];
3567 tok->tok_type = TOK_VAL;
3568 tok->hdr_id = -1;
3569 tok->pass_site = -1;
3570 tok->threshold = -1.0;
3571 tok->is_constant = 1;
3572 ret = TOK_MULT;
3573 }
3574 else if ( ret == -TOK_FUNC )
3575 {
3576 // this is different from TOK_PERLSUB,TOK_BINOM in that the expression inside the
3577 // brackets gets evaluated as normal expression
3578 nops++;
3579 hts_expand0(token_t, nops, mops, ops);
3580 token_t *tok = &ops[nops-1];
3581 tok->tok_type = -ret;
3582 tok->hdr_id = -1;
3583 tok->pass_site = -1;
3584 tok->threshold = -1.0;
3585 if ( !strncasecmp(tmp-len,"N_PASS",6) )
3586 {
3587 filter->max_unpack |= BCF_UN_FMT;
3588 tok->func = func_npass;
3589 tok->tag = strdup("N_PASS");
3590 }
3591 else if ( !strncasecmp(tmp-len,"F_PASS",6) )
3592 {
3593 filter->max_unpack |= BCF_UN_FMT;
3594 tok->func = func_npass;
3595 tok->tag = strdup("F_PASS");
3596 }
3597 else error("The function \"%s\" is not supported\n", tmp-len);
3598 continue;
3599 }
3600 else if ( ret < 0 ) // variable number of arguments: TOK_PERLSUB,TOK_BINOM
3601 {
3602 ret = -ret;
3603
3604 tmp += len;
3605 char *beg = tmp;
3606 kstring_t rmme = {0,0,0};
3607 int i, margs, nargs = 0;
3608
3609 if ( ret == TOK_PERLSUB )
3610 {
3611 while ( *beg && ((isalnum(*beg) && !ispunct(*beg)) || *beg=='_') ) beg++;
3612 if ( *beg!='(' ) error("Could not parse the expression: %s\n", str);
3613
3614 // the subroutine name
3615 kputc('"', &rmme);
3616 kputsn(tmp, beg-tmp, &rmme);
3617 kputc('"', &rmme);
3618 nout++;
3619 hts_expand0(token_t, nout, mout, out);
3620 filters_init1(filter, rmme.s, rmme.l, &out[nout-1]);
3621 nargs++;
3622 }
3623 char *end = beg;
3624 while ( *end && *end!=')' ) end++;
3625 if ( !*end ) error("Could not parse the expression: %s\n", str);
3626
3627 // subroutine arguments
3628 rmme.l = 0;
3629 kputsn(beg+1, end-beg-1, &rmme);
3630 char **rmme_list = hts_readlist(rmme.s, 0, &margs);
3631 for (i=0; i<margs; i++)
3632 {
3633 nargs++;
3634 nout++;
3635 hts_expand0(token_t, nout, mout, out);
3636 filters_init1(filter, rmme_list[i], strlen(rmme_list[i]), &out[nout-1]);
3637 free(rmme_list[i]);
3638 }
3639 free(rmme_list);
3640 free(rmme.s);
3641
3642 nout++;
3643 hts_expand0(token_t, nout, mout, out);
3644 token_t *tok = &out[nout-1];
3645 tok->tok_type = ret;
3646 tok->nargs = nargs;
3647 tok->hdr_id = -1;
3648 tok->pass_site = -1;
3649 tok->threshold = -1.0;
3650
3651 tmp = end + 1;
3652 continue;
3653 }
3654 else
3655 {
3656 while ( nops>0 && op_prec[ret] < op_prec[ops[nops-1].tok_type] )
3657 {
3658 nout++;
3659 hts_expand0(token_t, nout, mout, out);
3660 out[nout-1] = ops[nops-1];
3661 memset(&ops[nops-1],0,sizeof(token_t));
3662 nops--;
3663 }
3664 }
3665 nops++;
3666 hts_expand0(token_t, nops, mops, ops);
3667 ops[nops-1].tok_type = ret;
3668 }
3669 else if ( !len ) // all tokes read or an error
3670 {
3671 if ( *tmp && !isspace(*tmp) ) error("Could not parse the expression: [%s]\n", str);
3672 break; // all tokens read
3673 }
3674 else // TOK_VAL: annotation name or value
3675 {
3676 nout++;
3677 hts_expand0(token_t, nout, mout, out);
3678 if ( tmp[len-1]==',' )
3679 filters_init1(filter, tmp, len-1, &out[nout-1]);
3680 else
3681 filters_init1(filter, tmp, len, &out[nout-1]);
3682 tmp += len;
3683 }
3684 last_op = ret;
3685 }
3686 while ( nops>0 )
3687 {
3688 if ( ops[nops-1].tok_type==TOK_LFT || ops[nops-1].tok_type==TOK_RGT ) error("Could not parse the expression: [%s]\n", filter->str);
3689 nout++;
3690 hts_expand0(token_t, nout, mout, out);
3691 out[nout-1] = ops[nops-1];
3692 memset(&ops[nops-1],0,sizeof(token_t));
3693 nops--;
3694 }
3695
3696 if ( filter->status != FILTER_OK )
3697 {
3698 if ( mops ) free(ops);
3699 filter->filters = out;
3700 filter->nfilters = nout;
3701 return filter;
3702 }
3703
3704 // Determine types of external variables from the context
3705 determine_ext_types(filter,nout,out);
3706
3707 // In the special cases of TYPE and FILTER the BCF header IDs are yet unknown. Walk through the
3708 // list of operators and convert the strings (e.g. "PASS") to BCF ids. The string value token must be
3709 // just before or after the FILTER token and they must be followed with a comparison operator.
3710 // At this point we also initialize regex expressions which, in RPN, must precede the LIKE/NLIKE operator.
3711 // Additionally, treat "." as missing value rather than a string in numeric equalities; that
3712 // @file is only used with ID; etc.
3713 // This code is fragile: improve me.
3714 static int comma_separator_warned = 0;
3715 int i;
3716 for (i=0; i<nout; i++)
3717 {
3718 if ( i+1<nout && (out[i].tok_type==TOK_LT || out[i].tok_type==TOK_BT) && out[i+1].tok_type==TOK_EQ )
3719 error("Error parsing the expression: \"%s\"\n", filter->str);
3720
3721 if ( out[i].hash )
3722 {
3723 int j = out[i+1].tok_type==TOK_VAL ? i+1 : i-1;
3724 if ( out[j].comparator!=filters_cmp_id )
3725 {
3726 if ( out[j].comparator ) error("Error: could not parse the expression with \"@file_name\" syntax (possible todo)\n");
3727 out[j].comparator = filters_cmp_string_hash;
3728 }
3729 }
3730 if ( out[i].tok_type==TOK_OR || out[i].tok_type==TOK_OR_VEC )
3731 out[i].func = vector_logic_or;
3732 if ( out[i].tok_type==TOK_AND || out[i].tok_type==TOK_AND_VEC )
3733 out[i].func = vector_logic_and;
3734 if ( out[i].tok_type==TOK_EQ || out[i].tok_type==TOK_NE )
3735 {
3736 // Look for j="." and k numeric type
3737 int j = i-1, k = i-2;
3738 if ( !out[j].is_str ) { k = i-1, j = i-2; }
3739 if ( out[j].is_str && out[j].key && !strcmp(".",out[j].key) )
3740 {
3741 int set_missing = 0;
3742 if ( out[k].hdr_id>0 )
3743 {
3744 int type = bcf_hdr_id2type(filter->hdr,out[k].hl_type,out[k].hdr_id);
3745 if ( type==BCF_HT_INT ) set_missing = 1;
3746 else if ( type==BCF_HT_REAL ) set_missing = 1;
3747 }
3748 else if ( !strcmp("QUAL",out[k].tag) ) set_missing = 1;
3749 if ( set_missing ) { out[j].is_str = 0; out[j].is_missing = 1; bcf_double_set_missing(out[j].values[0]); }
3750 }
3751 }
3752 if ( out[i].tok_type==TOK_LIKE || out[i].tok_type==TOK_NLIKE )
3753 {
3754 int j = i-1;
3755 if ( !out[j].key )
3756 error("Could not parse the expression, wrong value for regex operator: %s\n", filter->str);
3757 out[j].regex = (regex_t *) malloc(sizeof(regex_t));
3758 int cflags = REG_NOSUB;
3759 int len = strlen(out[j].key);
3760 if ( len>2 && out[j].key[len-1]=='i' && out[j].key[len-2]=='/' && out[j].key[len-3]!='\\' )
3761 {
3762 out[j].key[len-2] = 0;
3763 cflags |= REG_ICASE;
3764 }
3765 if ( regcomp(out[j].regex, out[j].key, cflags) )
3766 error("Could not compile the regex expression \"%s\": %s\n", out[j].key,filter->str);
3767 }
3768 if ( out[i].is_str && out[i].tok_type==TOK_VAL && out[i].key && strchr(out[i].key,',') )
3769 {
3770 int print_note = 0;
3771 if ( out[i+1].tok_type==TOK_EQ || (out[i+1].is_str && out[i+2].tok_type==TOK_EQ) ) print_note = 1;
3772 else if ( out[i+1].tok_type==TOK_NE || (out[i+1].is_str && out[i+2].tok_type==TOK_NE) ) print_note = 1;
3773 if ( print_note && !comma_separator_warned )
3774 {
3775 comma_separator_warned = 1;
3776 fprintf(stderr,
3777 "Warning: comma is interpreted as a separator and OR logic is used in string comparisons.\n"
3778 " (Search the manual for \"Comma in strings\" to learn more.)\n");
3779 }
3780 }
3781 if ( out[i].tok_type!=TOK_VAL ) continue;
3782 if ( !out[i].tag ) continue;
3783 if ( out[i].setter==filters_set_type )
3784 {
3785 if ( i+1==nout || !out[i+1].key )
3786 error("Could not parse the expression: %s\n", filter->str);
3787 int itok, ival;
3788 if ( out[i+1].tok_type==TOK_EQ || out[i+1].tok_type==TOK_NE ) ival = i - 1, itok = i + 1;
3789 else if ( out[i+1].tok_type==TOK_LIKE || out[i+1].tok_type==TOK_NLIKE ) ival = i - 1, itok = i + 1;
3790 else if ( out[i+2].tok_type==TOK_EQ || out[i+2].tok_type==TOK_NE ) itok = i + 2, ival = i + 1;
3791 else if ( out[i+2].tok_type==TOK_LIKE || out[i+2].tok_type==TOK_NLIKE ) itok = i + 2, ival = i + 1;
3792 else error("[%s:%d %s] Could not parse the expression: %s\n", __FILE__,__LINE__,__FUNCTION__, filter->str);
3793 if ( !strcasecmp(out[ival].key,"snp") || !strcasecmp(out[ival].key,"snps") ) { out[ival].threshold = VCF_SNP<<1; out[ival].is_str = 0; }
3794 else if ( !strcasecmp(out[ival].key,"indel") || !strcasecmp(out[ival].key,"indels") ) { out[ival].threshold = VCF_INDEL<<1; out[ival].is_str = 0; }
3795 else if ( !strcasecmp(out[ival].key,"mnp") || !strcasecmp(out[ival].key,"mnps") ) { out[ival].threshold = VCF_MNP<<1; out[ival].is_str = 0; }
3796 else if ( !strcasecmp(out[ival].key,"other") ) { out[ival].threshold = VCF_OTHER<<1; out[ival].is_str = 0; }
3797 else if ( !strcasecmp(out[ival].key,"bnd") ) { out[ival].threshold = VCF_BND<<1; out[ival].is_str = 0; }
3798 else if ( !strcasecmp(out[ival].key,"overlap") ) { out[ival].threshold = VCF_OVERLAP<<1; out[ival].is_str = 0; }
3799 else if ( !strcasecmp(out[ival].key,"ref") ) { out[ival].threshold = 1; out[ival].is_str = 0; }
3800 else error("The type \"%s\" not recognised: %s\n", out[ival].key, filter->str);
3801 out[ival].is_constant = 1;
3802 if ( out[itok].tok_type==TOK_LIKE || out[itok].tok_type==TOK_NLIKE ) out[itok].comparator = filters_cmp_bit_and;
3803 out[ival].tag = out[ival].key; out[ival].key = NULL;
3804 i = itok;
3805 continue;
3806 }
3807 if ( !strcmp(out[i].tag,"GT") )
3808 {
3809 if ( i+1==nout ) error("Could not parse the expression: %s\n", filter->str);
3810 int ival;
3811 if ( out[i+1].tok_type==TOK_EQ || out[i+1].tok_type==TOK_NE ) ival = i - 1;
3812 else if ( out[i+1].tok_type==TOK_LIKE || out[i+1].tok_type==TOK_NLIKE ) ival = i - 1;
3813 else if ( out[i+2].tok_type==TOK_EQ || out[i+2].tok_type==TOK_NE ) ival = i + 1;
3814 else if ( out[i+2].tok_type==TOK_LIKE || out[i+2].tok_type==TOK_NLIKE ) ival = i + 1;
3815 else error("[%s:%d %s] Could not parse the expression: %s\n", __FILE__,__LINE__,__FUNCTION__, filter->str);
3816
3817 if ( !out[ival].key ) error("Comparison between samples is not supported, sorry!\n");
3818
3819 // assign correct setters and unify expressions, eg ar->ra, HOM->hom, etc
3820 if ( !strcasecmp(out[ival].key,"hom") ) { out[i].setter = filters_set_genotype3; str_to_lower(out[ival].key); }
3821 else if ( !strcasecmp(out[ival].key,"het") ) { out[i].setter = filters_set_genotype3; str_to_lower(out[ival].key); }
3822 else if ( !strcasecmp(out[ival].key,"hap") ) { out[i].setter = filters_set_genotype3; str_to_lower(out[ival].key); }
3823 else if ( !strcasecmp(out[ival].key,"mis") ) { out[i].setter = filters_set_genotype4; str_to_lower(out[ival].key); }
3824 else if ( !strcasecmp(out[ival].key,"ref") ) { out[i].setter = filters_set_genotype4; str_to_lower(out[ival].key); }
3825 else if ( !strcasecmp(out[ival].key,"alt") ) { out[i].setter = filters_set_genotype4; str_to_lower(out[ival].key); }
3826 else if ( !strcasecmp(out[ival].key,"rr") ) { out[i].setter = filters_set_genotype2; str_to_lower(out[ival].key); }
3827 else if ( !strcasecmp(out[ival].key,"ra") || !strcasecmp(out[ival].key,"ar") ) { out[i].setter = filters_set_genotype2; out[ival].key[0]='r'; out[ival].key[1]='a'; } // ra
3828 else if ( !strcmp(out[ival].key,"aA") || !strcmp(out[ival].key,"Aa") ) { out[i].setter = filters_set_genotype2; out[ival].key[0]='a'; out[ival].key[1]='A'; } // aA
3829 else if ( !strcasecmp(out[ival].key,"aa") ) { out[i].setter = filters_set_genotype2; out[ival].key[0]='a'; out[ival].key[1]='a'; } // aa
3830 else if ( !strcasecmp(out[ival].key,"a") ) { out[i].setter = filters_set_genotype2; out[ival].key[0]='a'; out[ival].key[1]=0; } // a
3831 else if ( !strcasecmp(out[ival].key,"r") ) { out[i].setter = filters_set_genotype2; out[ival].key[0]='r'; out[ival].key[1]=0; } // r
3832 continue;
3833 }
3834 if ( out[i].hl_type==BCF_HL_FLT )
3835 {
3836 if ( i+1==nout ) error("Could not parse the expression: %s\n", filter->str);
3837 int itok = i, ival;
3838 if ( out[i+1].tok_type==TOK_EQ || out[i+1].tok_type==TOK_NE ) ival = i - 1;
3839 else if ( out[i+1].tok_type==TOK_LIKE ) out[i+1].tok_type = TOK_IN, ival = i - 1;
3840 else if ( out[i+1].tok_type==TOK_NLIKE ) out[i+1].tok_type = TOK_NOT_IN, ival = i - 1;
3841 else if ( out[i+2].tok_type==TOK_EQ || out[i+2].tok_type==TOK_NE ) ival = ++i;
3842 else if ( out[i+2].tok_type==TOK_LIKE ) out[i+2].tok_type = TOK_IN, ival = ++i;
3843 else if ( out[i+2].tok_type==TOK_NLIKE ) out[i+2].tok_type = TOK_NOT_IN, ival = ++i;
3844 else error("[%s:%d %s] Could not parse the expression: %s\n", __FILE__,__LINE__,__FUNCTION__, filter->str);
3845 if ( out[ival].tok_type!=TOK_VAL || !out[ival].key )
3846 error("[%s:%d %s] Could not parse the expression, an unquoted string value perhaps? %s\n", __FILE__,__LINE__,__FUNCTION__, filter->str);
3847 token_t *tok = &out[ival];
3848 char *bp = tok->key;
3849 tok->nvalues = 0;
3850 int has_missing = 0;
3851 while ( *bp )
3852 {
3853 char tmp, *ep = bp;
3854 while ( *ep && *ep!=';' ) ep++;
3855 tmp = *ep;
3856 *ep = 0;
3857 if ( !strcmp(".",bp) ) has_missing = 1;
3858 else
3859 {
3860 tok->nvalues++;
3861 hts_expand(double,tok->nvalues,tok->mvalues,tok->values);
3862 int id = bcf_hdr_id2int(filter->hdr, BCF_DT_ID, bp);
3863 if ( !bcf_hdr_idinfo_exists(filter->hdr,BCF_HL_FLT,id) )
3864 error("The filter \"%s\" not present in the VCF header\n", bp);
3865 tok->values[tok->nvalues-1] = id;
3866 }
3867 *ep = tmp;
3868 if ( !tmp ) break;
3869 bp = ep + 1;
3870 }
3871 if ( has_missing && tok->nvalues ) error("The FILTER expression cannot contain missing value AND filters: \"%s\" (%d)\n",tok->key,tok->nvalues);
3872 out[ival].tag = tok->key;
3873 tok->key = NULL;
3874 out[itok].hdr_id = tok->hdr_id;
3875 continue;
3876 }
3877 }
3878 filter->nsamples = filter->max_unpack&BCF_UN_FMT ? bcf_hdr_nsamples(filter->hdr) : 0;
3879 for (i=0; i<nout; i++)
3880 {
3881 if ( out[i].tok_type==TOK_MAX ) { out[i].func = func_max; out[i].tok_type = TOK_FUNC; }
3882 else if ( out[i].tok_type==TOK_MIN ) { out[i].func = func_min; out[i].tok_type = TOK_FUNC; }
3883 else if ( out[i].tok_type==TOK_AVG ) { out[i].func = func_avg; out[i].tok_type = TOK_FUNC; }
3884 else if ( out[i].tok_type==TOK_MEDIAN ) { out[i].func = func_median; out[i].tok_type = TOK_FUNC; }
3885 else if ( out[i].tok_type==TOK_AVG ) { out[i].func = func_avg; out[i].tok_type = TOK_FUNC; }
3886 else if ( out[i].tok_type==TOK_STDEV ) { out[i].func = func_stddev; out[i].tok_type = TOK_FUNC; }
3887 else if ( out[i].tok_type==TOK_SUM ) { out[i].func = func_sum; out[i].tok_type = TOK_FUNC; }
3888 else if ( out[i].tok_type==TOK_ABS ) { out[i].func = func_abs; out[i].tok_type = TOK_FUNC; }
3889 else if ( out[i].tok_type==TOK_CNT ) { out[i].func = func_count; out[i].tok_type = TOK_FUNC; }
3890 else if ( out[i].tok_type==TOK_LEN ) { out[i].func = func_strlen; out[i].tok_type = TOK_FUNC; }
3891 else if ( out[i].tok_type==TOK_PHRED ) { out[i].func = func_phred; out[i].tok_type = TOK_FUNC; }
3892 else if ( out[i].tok_type==TOK_BINOM ) { out[i].func = func_binom; out[i].tok_type = TOK_FUNC; }
3893 else if ( out[i].tok_type==TOK_PERLSUB ) { out[i].func = perl_exec; out[i].tok_type = TOK_FUNC; }
3894 else if ( out[i].tok_type==TOK_sMAX ) { out[i].func = func_smpl_max; out[i].tok_type = TOK_FUNC; }
3895 else if ( out[i].tok_type==TOK_sMIN ) { out[i].func = func_smpl_min; out[i].tok_type = TOK_FUNC; }
3896 else if ( out[i].tok_type==TOK_sAVG ) { out[i].func = func_smpl_avg; out[i].tok_type = TOK_FUNC; }
3897 else if ( out[i].tok_type==TOK_sMEDIAN ) { out[i].func = func_smpl_median; out[i].tok_type = TOK_FUNC; }
3898 else if ( out[i].tok_type==TOK_sSTDEV ) { out[i].func = func_smpl_stddev; out[i].tok_type = TOK_FUNC; }
3899 else if ( out[i].tok_type==TOK_sSUM ) { out[i].func = func_smpl_sum; out[i].tok_type = TOK_FUNC; }
3900 hts_expand0(double,1,out[i].mvalues,out[i].values);
3901 if ( filter->nsamples )
3902 {
3903 out[i].pass_samples = (uint8_t*)malloc(filter->nsamples);
3904 int j;
3905 for (j=0; j<filter->nsamples; j++) out[i].pass_samples[j] = 0;
3906 }
3907 }
3908
3909 if (0) filter_debug_print(out, NULL, nout);
3910
3911 if ( mops ) free(ops);
3912 filter->filters = out;
3913 filter->nfilters = nout;
3914 filter->flt_stack = (token_t **)malloc(sizeof(token_t*)*nout);
3915 return filter;
3916 }
3917 filter_t *filter_parse(bcf_hdr_t *hdr, const char *str)
3918 {
3919 return filter_init_(hdr, str, 0);
3920 }
3921 filter_t *filter_init(bcf_hdr_t *hdr, const char *str)
3922 {
3923 return filter_init_(hdr, str, 1);
3924 }
3925
3926 void filter_destroy(filter_t *filter)
3927 {
3928 perl_destroy(filter);
3929 int i;
3930 for (i=0; i<filter->nfilters; i++)
3931 {
3932 if ( filter->filters[i].key ) free(filter->filters[i].key);
3933 free(filter->filters[i].str_value.s);
3934 free(filter->filters[i].tag);
3935 free(filter->filters[i].idxs);
3936 free(filter->filters[i].usmpl);
3937 free(filter->filters[i].values);
3938 free(filter->filters[i].pass_samples);
3939 if (filter->filters[i].hash) khash_str2int_destroy_free(filter->filters[i].hash);
3940 if (filter->filters[i].regex)
3941 {
3942 regfree(filter->filters[i].regex);
3943 free(filter->filters[i].regex);
3944 }
3945 }
3946 for (i=0; i<filter->nundef_tag; i++) free(filter->undef_tag[i]);
3947 for (i=0; i<filter->nused_tag; i++) free(filter->used_tag[i]);
3948 free(filter->ext);
3949 free(filter->undef_tag);
3950 free(filter->used_tag);
3951 free(filter->cached_GT.buf);
3952 free(filter->cached_GT.mask);
3953 free(filter->filters);
3954 free(filter->flt_stack);
3955 free(filter->str);
3956 free(filter->tmpi);
3957 free(filter->tmpf);
3958 free(filter->tmps.s);
3959 free(filter);
3960 }
3961
3962 int filter_test_ext(filter_t *filter, bcf1_t *rec, const uint8_t **samples, const void **ext)
3963 {
3964 if ( !filter->n_ext )
3965 return filter_test(filter,rec,samples);
3966
3967 int i;
3968 for (i=0; i<filter->nfilters; i++)
3969 {
3970 token_t *tok = &filter->filters[i];
3971 if ( !tok->iext ) continue;
3972 if ( !ext[tok->iext-1] )
3973 {
3974 tok->is_missing = 1;
3975 tok->nvalues = 0;
3976 if ( filter->ext[tok->iext-1]==BCF_HT_STR ) tok->str_value.l = 0;
3977 continue;
3978 }
3979 tok->is_missing = 0;
3980 tok->nvalues = 1;
3981 if ( filter->ext[tok->iext-1]==BCF_HT_STR )
3982 {
3983 tok->str_value.l = 0;
3984 kputs((const char*)ext[tok->iext-1],&tok->str_value);
3985 tok->nvalues = tok->str_value.l;
3986 }
3987 else if ( filter->ext[tok->iext-1]==BCF_HT_INT ) tok->values[0] = *((const int*)ext[tok->iext-1]);
3988 else if ( filter->ext[tok->iext-1]==BCF_HT_REAL ) tok->values[0] = *((const float*)ext[tok->iext-1]);
3989 }
3990 return filter_test(filter,rec,samples);
3991 }
3992
3993 int filter_test(filter_t *filter, bcf1_t *line, const uint8_t **samples)
3994 {
3995 if ( filter->status != FILTER_OK ) error("Error: the caller did not check the filter status\n");
3996 bcf_unpack(line, filter->max_unpack);
3997
3998 int i, nstack = 0;
3999 for (i=0; i<filter->nfilters; i++)
4000 {
4001 filter->filters[i].pass_site = 0;
4002 if ( filter->filters[i].tok_type == TOK_VAL )
4003 {
4004 if ( filter->filters[i].setter ) // variable, query the VCF line
4005 filter->filters[i].setter(filter, line, &filter->filters[i]);
4006 else if ( filter->filters[i].key ) // string constant
4007 {
4008 filter->filters[i].str_value.l = 0;
4009 kputs(filter->filters[i].key, &filter->filters[i].str_value);
4010 filter->filters[i].nvalues = filter->filters[i].str_value.l;
4011 }
4012 else if ( filter->filters[i].is_constant ) // numeric constant
4013 {
4014 filter->filters[i].values[0] = filter->filters[i].threshold;
4015 filter->filters[i].nvalues = 1;
4016 }
4017 filter->flt_stack[nstack++] = &filter->filters[i];
4018 continue;
4019 }
4020 else if ( filter->filters[i].func )
4021 {
4022 int nargs = filter->filters[i].func(filter, line, &filter->filters[i], filter->flt_stack, nstack);
4023 filter->flt_stack[nstack-nargs] = &filter->filters[i];
4024 if ( --nargs > 0 ) nstack -= nargs;
4025 continue;
4026 }
4027 if ( nstack<2 )
4028 error("Error occurred while processing the filter \"%s\" (1:%d)\n", filter->str,nstack); // too few values left on the stack
4029
4030 int is_str = filter->flt_stack[nstack-1]->is_str + filter->flt_stack[nstack-2]->is_str;
4031
4032 if ( filter->filters[i].tok_type == TOK_ADD )
4033 {
4034 VECTOR_ARITHMETICS(filter->flt_stack[nstack-2],filter->flt_stack[nstack-1],&filter->filters[i],+,(double));
4035 filter->flt_stack[nstack-2] = &filter->filters[i];
4036 nstack--;
4037 continue;
4038 }
4039 else if ( filter->filters[i].tok_type == TOK_SUB )
4040 {
4041 VECTOR_ARITHMETICS(filter->flt_stack[nstack-2],filter->flt_stack[nstack-1],&filter->filters[i],-,(double));
4042 filter->flt_stack[nstack-2] = &filter->filters[i];
4043 nstack--;
4044 continue;
4045 }
4046 else if ( filter->filters[i].tok_type == TOK_MULT )
4047 {
4048 VECTOR_ARITHMETICS(filter->flt_stack[nstack-2],filter->flt_stack[nstack-1],&filter->filters[i],*,(double));
4049 filter->flt_stack[nstack-2] = &filter->filters[i];
4050 nstack--;
4051 continue;
4052 }
4053 else if ( filter->filters[i].tok_type == TOK_DIV )
4054 {
4055 VECTOR_ARITHMETICS(filter->flt_stack[nstack-2],filter->flt_stack[nstack-1],&filter->filters[i],/,(double));
4056 filter->flt_stack[nstack-2] = &filter->filters[i];
4057 nstack--;
4058 continue;
4059 }
4060 else if ( filter->filters[i].tok_type == TOK_MODULO )
4061 {
4062 VECTOR_ARITHMETICS(filter->flt_stack[nstack-2],filter->flt_stack[nstack-1],&filter->filters[i],%,(int));
4063 filter->flt_stack[nstack-2] = &filter->filters[i];
4064 nstack--;
4065 continue;
4066 }
4067
4068 // ideally, these comparators would become func, but this would require more work in init1()
4069 if ( filter->filters[i].comparator )
4070 {
4071 filter->filters[i].comparator(filter->flt_stack[nstack-1],filter->flt_stack[nstack-2],&filter->filters[i],line);
4072 }
4073 else if ( filter->flt_stack[nstack-1]->comparator )
4074 {
4075 filter->flt_stack[nstack-1]->comparator(filter->flt_stack[nstack-1],filter->flt_stack[nstack-2],&filter->filters[i],line);
4076 }
4077 else if ( filter->flt_stack[nstack-2]->comparator )
4078 {
4079 filter->flt_stack[nstack-2]->comparator(filter->flt_stack[nstack-2],filter->flt_stack[nstack-1],&filter->filters[i],line);
4080 }
4081 else if ( is_str==2 )
4082 {
4083 cmp_vector_strings(filter->flt_stack[nstack-2],filter->flt_stack[nstack-1],&filter->filters[i]);
4084 }
4085 else
4086 {
4087 if ( is_str==1 ) error("Error: cannot use arithmetic operators to compare strings and numbers\n");
4088
4089 // Determine what to do with one [1] or both [2] sides missing. The first field [0] gives [1]|[2]
4090 int missing_logic[] = {0,0,0};
4091 if ( filter->filters[i].tok_type == TOK_EQ ) { missing_logic[0] = missing_logic[2] = 1; }
4092 if ( filter->filters[i].tok_type == TOK_NE ) { missing_logic[0] = missing_logic[1] = 1; }
4093
4094 if ( filter->filters[i].tok_type == TOK_EQ )
4095 CMP_VECTORS(filter->flt_stack[nstack-2],filter->flt_stack[nstack-1],&filter->filters[i],==,missing_logic)
4096 else if ( filter->filters[i].tok_type == TOK_NE )
4097 CMP_VECTORS(filter->flt_stack[nstack-2],filter->flt_stack[nstack-1],&filter->filters[i],!=,missing_logic)
4098 else if ( filter->filters[i].tok_type == TOK_LE )
4099 CMP_VECTORS(filter->flt_stack[nstack-2],filter->flt_stack[nstack-1],&filter->filters[i],<=,missing_logic)
4100 else if ( filter->filters[i].tok_type == TOK_LT )
4101 CMP_VECTORS(filter->flt_stack[nstack-2],filter->flt_stack[nstack-1],&filter->filters[i],<,missing_logic)
4102 else if ( filter->filters[i].tok_type == TOK_BT )
4103 CMP_VECTORS(filter->flt_stack[nstack-2],filter->flt_stack[nstack-1],&filter->filters[i],>,missing_logic)
4104 else if ( filter->filters[i].tok_type == TOK_BE )
4105 CMP_VECTORS(filter->flt_stack[nstack-2],filter->flt_stack[nstack-1],&filter->filters[i],>=,missing_logic)
4106 else
4107 error("todo: %s:%d .. type=%d\n", __FILE__,__LINE__,filter->filters[i].tok_type);
4108 }
4109 filter->flt_stack[nstack-2] = &filter->filters[i];
4110 nstack--;
4111 }
4112 if ( nstack>1 ) error("Error occurred while processing the filter \"%s\" (2:%d)\n", filter->str,nstack); // too few values left on the stack
4113 if ( samples )
4114 {
4115 *samples = filter->max_unpack&BCF_UN_FMT ? filter->flt_stack[0]->pass_samples : NULL;
4116 if ( *samples && !filter->flt_stack[0]->nsamples )
4117 {
4118 for (i=0; i<filter->nsamples; i++)
4119 filter->flt_stack[0]->pass_samples[i] = filter->flt_stack[0]->pass_site;
4120 }
4121 }
4122 return filter->flt_stack[0]->pass_site;
4123 }
4124
4125 int filter_max_unpack(filter_t *flt)
4126 {
4127 return flt->max_unpack;
4128 }
4129 const int *filter_ext_types(filter_t *filter, int *n_ext)
4130 {
4131 *n_ext = filter->n_ext;
4132 return filter->ext;
4133 }
4134 const double *filter_get_doubles(filter_t *filter, int *nval, int *nval1)
4135 {
4136 token_t *tok = filter->flt_stack[0];
4137 if ( tok->nvalues )
4138 {
4139 *nval = tok->nvalues;
4140 *nval1 = tok->nval1;
4141 }
4142 else
4143 {
4144 if ( !tok->values ) error("fixme in filter_get_doubles(): %s\n", filter->str);
4145 *nval = 1;
4146 *nval1 = 1;
4147 tok->values[0] = filter->flt_stack[0]->pass_site;
4148 }
4149 return tok->values;
4150 }
4151
4152 void filter_set_samples(filter_t *filter, const uint8_t *samples)
4153 {
4154 int i,j;
4155 for (i=0; i<filter->nfilters; i++)
4156 {
4157 if ( !filter->filters[i].nsamples ) continue;
4158 for (j=0; j<filter->filters[i].nsamples; j++) filter->filters[i].usmpl[j] = samples[j];
4159 }
4160 }
4161
4162 int filter_status(filter_t *filter)
4163 {
4164 return filter->status;
4165 }
4166