This repository has been archived by the owner on Jun 3, 2021. It is now read-only.
forked from SelfHacked/bcftools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filter.c
3594 lines (3422 loc) · 131 KB
/
filter.c
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* filter.c -- filter expressions.
Copyright (C) 2013-2020 Genome Research Ltd.
Author: Petr Danecek <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#include <ctype.h>
#include <stdlib.h>
#include <strings.h>
#include <assert.h>
#include <errno.h>
#include <math.h>
#include <sys/types.h>
#include <inttypes.h>
#ifndef _WIN32
#include <pwd.h>
#endif
#include <regex.h>
#include <htslib/khash_str2int.h>
#include <htslib/hts_defs.h>
#include <htslib/vcfutils.h>
#include <htslib/kfunc.h>
#include "config.h"
#include "filter.h"
#include "bcftools.h"
#if ENABLE_PERL_FILTERS
# define filter_t perl_filter_t
# include <EXTERN.h>
# include <perl.h>
# undef filter_t
# define my_perl perl
static int filter_ninit = 0;
#endif
#ifndef __FUNCTION__
# define __FUNCTION__ __func__
#endif
typedef struct _token_t
{
// read-only values, same for all VCF lines
int tok_type; // one of the TOK_* keys below
int nargs; // with TOK_PERLSUB the first argument is the name of the subroutine
char *key; // set only for string constants, otherwise NULL
char *tag; // for debugging and printout only, VCF tag name
double threshold; // filtering threshold
int is_constant; // the threshold is set
int hdr_id, tag_type; // BCF header lookup ID and one of BCF_HL_* types
int idx; // 0-based index to VCF vectors,
// -2: list (e.g. [0,1,2] or [1..3] or [1..] or any field[*], which is equivalent to [0..])
int *idxs; // set indexes to 0 to exclude, to 1 to include, and last element negative if unlimited; used by VCF retrievers only
int nidxs, nuidxs; // size of idxs array and the number of elements set to 1
uint8_t *usmpl; // bitmask of used samples as set by idx, set for FORMAT fields, NULL otherwise
int nsamples; // number of samples for format fields, 0 for info and other fields
void (*setter)(filter_t *, bcf1_t *, struct _token_t *);
int (*func)(filter_t *, bcf1_t *, struct _token_t *rtok, struct _token_t **stack, int nstack);
void (*comparator)(struct _token_t *, struct _token_t *, struct _token_t *rtok, bcf1_t *);
void *hash; // test presence of str value in the hash via comparator
regex_t *regex; // precompiled regex for string comparison
// modified on filter evaluation at each VCF line
double *values;
kstring_t str_value;
int is_str, is_missing; // is_missing is set only for constants, variables are controled via nvalues
int pass_site; // -1 not applicable, 0 fails, >0 pass
uint8_t *pass_samples; // status of individual samples
int nvalues, mvalues; // number of used values: n=0 for missing values, n=1 for scalars, for strings n=str_value.l
int nval1; // number of per-sample fields or string length
}
token_t;
struct _filter_t
{
bcf_hdr_t *hdr;
char *str;
int nfilters;
token_t *filters, **flt_stack; // filtering input tokens (in RPN) and evaluation stack
int32_t *tmpi;
float *tmpf;
kstring_t tmps;
int max_unpack, mtmpi, mtmpf, nsamples;
#if ENABLE_PERL_FILTERS
PerlInterpreter *perl;
#endif
};
#define TOK_VAL 0
#define TOK_LFT 1 // (
#define TOK_RGT 2 // )
#define TOK_LE 3 // less or equal
#define TOK_LT 4 // less than
#define TOK_EQ 5 // equal
#define TOK_BT 6 // bigger than
#define TOK_BE 7 // bigger or equal
#define TOK_NE 8 // not equal
#define TOK_OR 9 // |
#define TOK_AND 10 // &
#define TOK_ADD 11 // +
#define TOK_SUB 12 // -
#define TOK_MULT 13 // *
#define TOK_DIV 14 // /
#define TOK_MAX 15
#define TOK_MIN 16
#define TOK_AVG 17
#define TOK_AND_VEC 18 // && (operator applied in samples)
#define TOK_OR_VEC 19 // || (operator applied in samples)
#define TOK_LIKE 20 // ~ regular expression
#define TOK_NLIKE 21 // !~ regular expression
#define TOK_SUM 22
#define TOK_ABS 23
#define TOK_LEN 24
#define TOK_FUNC 25
#define TOK_CNT 26
#define TOK_PERLSUB 27
#define TOK_BINOM 28
#define TOK_PHRED 29
#define TOK_MEDIAN 30
#define TOK_STDEV 31
#define TOK_sMAX 32
#define TOK_sMIN 33
#define TOK_sAVG 34
#define TOK_sMEDIAN 35
#define TOK_sSTDEV 36
#define TOK_sSUM 37
#define TOK_IN 38 // contains, e.g. FILTER~"A"
#define TOK_NOT_IN 39 // does not contain, e.g. FILTER!~"A"
// 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
// ( ) [ < = > ] ! | & + - * / M m a A O ~ ^ S . l f c p b P i s
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 };
#define TOKEN_STRING "x()[<=>]!|&+-*/MmaAO~^S.lfcpis" // this is only for debugging, not maintained diligently
// Return negative values if it is a function with variable number of arguments
static int filters_next_token(char **str, int *len)
{
char *tmp = *str;
while ( *tmp && isspace(*tmp) ) tmp++;
*str = tmp;
*len = 0;
// test for doubles: d.ddde[+-]dd
if ( isdigit(*str[0]) || *str[0]=='.' ) // strtod would eat +/-
{
double HTS_UNUSED v = strtod(*str, &tmp);
if ( *str!=tmp && (!tmp[0] || !isalnum(tmp[0])) )
{
*len = tmp - (*str);
return TOK_VAL;
}
tmp = *str;
}
if ( !strncasecmp(tmp,"SMPL_MAX(",9) ) { (*str) += 8; return TOK_sMAX; }
if ( !strncasecmp(tmp,"SMPL_MIN(",9) ) { (*str) += 8; return TOK_sMIN; }
if ( !strncasecmp(tmp,"SMPL_MEAN(",10) ) { (*str) += 9; return TOK_sAVG; }
if ( !strncasecmp(tmp,"SMPL_MEDIAN(",12) ) { (*str) += 11; return TOK_sMEDIAN; }
if ( !strncasecmp(tmp,"SMPL_AVG(",9) ) { (*str) += 8; return TOK_sAVG; }
if ( !strncasecmp(tmp,"SMPL_STDEV(",11) ) { (*str) += 10; return TOK_sSTDEV; }
if ( !strncasecmp(tmp,"SMPL_SUM(",9) ) { (*str) += 8; return TOK_sSUM; }
if ( !strncasecmp(tmp,"sMAX(",5) ) { (*str) += 4; return TOK_sMAX; }
if ( !strncasecmp(tmp,"sMIN(",5) ) { (*str) += 4; return TOK_sMIN; }
if ( !strncasecmp(tmp,"sMEAN(",6) ) { (*str) += 5; return TOK_sAVG; }
if ( !strncasecmp(tmp,"sMEDIAN(",8) ) { (*str) += 7; return TOK_sMEDIAN; }
if ( !strncasecmp(tmp,"sAVG(",5) ) { (*str) += 4; return TOK_sAVG; }
if ( !strncasecmp(tmp,"sSTDEV(",7) ) { (*str) += 6; return TOK_sSTDEV; }
if ( !strncasecmp(tmp,"sSUM(",5) ) { (*str) += 4; return TOK_sSUM; }
if ( !strncasecmp(tmp,"MAX(",4) ) { (*str) += 3; return TOK_MAX; }
if ( !strncasecmp(tmp,"MIN(",4) ) { (*str) += 3; return TOK_MIN; }
if ( !strncasecmp(tmp,"MEAN(",5) ) { (*str) += 4; return TOK_AVG; }
if ( !strncasecmp(tmp,"MEDIAN(",7) ) { (*str) += 6; return TOK_MEDIAN; }
if ( !strncasecmp(tmp,"AVG(",4) ) { (*str) += 3; return TOK_AVG; }
if ( !strncasecmp(tmp,"STDEV(",6) ) { (*str) += 5; return TOK_STDEV; }
if ( !strncasecmp(tmp,"SUM(",4) ) { (*str) += 3; return TOK_SUM; }
if ( !strncasecmp(tmp,"ABS(",4) ) { (*str) += 3; return TOK_ABS; }
if ( !strncasecmp(tmp,"COUNT(",4) ) { (*str) += 5; return TOK_CNT; }
if ( !strncasecmp(tmp,"STRLEN(",7) ) { (*str) += 6; return TOK_LEN; }
if ( !strncasecmp(tmp,"BINOM(",6) ) { (*str) += 5; return -TOK_BINOM; }
if ( !strncasecmp(tmp,"PHRED(",6) ) { (*str) += 5; return TOK_PHRED; }
if ( !strncasecmp(tmp,"%MAX(",5) ) { (*str) += 4; return TOK_MAX; } // for backward compatibility
if ( !strncasecmp(tmp,"%MIN(",5) ) { (*str) += 4; return TOK_MIN; } // for backward compatibility
if ( !strncasecmp(tmp,"%AVG(",5) ) { (*str) += 4; return TOK_AVG; } // for backward compatibility
if ( !strncasecmp(tmp,"%SUM(",5) ) { (*str) += 4; return TOK_SUM; } // for backward compatibility
if ( !strncasecmp(tmp,"INFO/",5) ) tmp += 5;
if ( !strncasecmp(tmp,"FORMAT/",7) ) tmp += 7;
if ( !strncasecmp(tmp,"FMT/",4) ) tmp += 4;
if ( !strncasecmp(tmp,"PERL.",5) ) { (*str) += 5; return -TOK_PERLSUB; }
if ( !strncasecmp(tmp,"N_PASS(",7) ) { *len = 6; (*str) += 6; return -TOK_FUNC; }
if ( !strncasecmp(tmp,"F_PASS(",7) ) { *len = 6; (*str) += 6; return -TOK_FUNC; }
if ( !strncasecmp(tmp,"%ILEN",5) ) { *len = 5; return TOK_VAL; } // to be able to distinguish between INFO/ILEN and on-the-fly ILEN
if ( tmp[0]=='@' ) // file name
{
while ( *tmp && !isspace(*tmp) && *tmp!='=' && *tmp!='!' ) tmp++;
*len = tmp - (*str);
return TOK_VAL;
}
int square_brackets = 0;
while ( tmp[0] )
{
if ( !square_brackets )
{
if ( tmp[0]=='"' ) break;
if ( tmp[0]=='\'' ) break;
if ( isspace(tmp[0]) ) break;
if ( tmp[0]=='<' ) break;
if ( tmp[0]=='>' ) break;
if ( tmp[0]=='=' ) break;
if ( tmp[0]=='!' ) break;
if ( tmp[0]=='&' ) break;
if ( tmp[0]=='|' ) break;
if ( tmp[0]=='(' ) break;
if ( tmp[0]==')' ) break;
if ( tmp[0]=='+' ) break;
if ( tmp[0]=='*' ) break;
if ( tmp[0]=='-' ) break;
if ( tmp[0]=='/' ) break;
if ( tmp[0]=='~' ) break;
}
if ( tmp[0]==']' ) { if (square_brackets) tmp++; break; }
if ( tmp[0]=='[' ) square_brackets++;
tmp++;
}
if ( tmp > *str )
{
*len = tmp - (*str);
return TOK_VAL;
}
if ( tmp[0]=='"' || tmp[0]=='\'' )
{
int quote = tmp[0];
tmp++;
while ( *tmp && tmp[0]!=quote ) tmp++;
if ( !*tmp ) return -1; // missing quotes
*len = tmp - (*str) + 1;
return TOK_VAL;
}
if ( tmp[0]=='!' )
{
if ( tmp[1]=='=' ) { (*str) += 2; return TOK_NE; }
if ( tmp[1]=='~' ) { (*str) += 2; return TOK_NLIKE; }
}
if ( tmp[0]=='<' )
{
if ( tmp[1]=='=' ) { (*str) += 2; return TOK_LE; }
(*str) += 1; return TOK_LT;
}
if ( tmp[0]=='>' )
{
if ( tmp[1]=='=' ) { (*str) += 2; return TOK_BE; }
(*str) += 1; return TOK_BT;
}
if ( tmp[0]=='=' )
{
if ( tmp[1]=='=' ) { (*str) += 2; return TOK_EQ; }
(*str) += 1; return TOK_EQ;
}
if ( tmp[0]=='(' ) { (*str) += 1; return TOK_LFT; }
if ( tmp[0]==')' ) { (*str) += 1; return TOK_RGT; }
if ( tmp[0]=='&' && tmp[1]=='&' ) { (*str) += 2; return TOK_AND_VEC; }
if ( tmp[0]=='|' && tmp[1]=='|' ) { (*str) += 2; return TOK_OR_VEC; }
if ( tmp[0]=='&' ) { (*str) += 1; return TOK_AND; }
if ( tmp[0]=='|' ) { (*str) += 1; return TOK_OR; }
if ( tmp[0]=='+' ) { (*str) += 1; return TOK_ADD; }
if ( tmp[0]=='-' ) { (*str) += 1; return TOK_SUB; }
if ( tmp[0]=='*' ) { (*str) += 1; return TOK_MULT; }
if ( tmp[0]=='/' ) { (*str) += 1; return TOK_DIV; }
if ( tmp[0]=='~' ) { (*str) += 1; return TOK_LIKE; }
*len = tmp - (*str);
return TOK_VAL;
}
/*
Simple path expansion, expands ~/, ~user, $var. The result must be freed by the caller.
Based on jkb's staden code with some adjustments.
https://sourceforge.net/p/staden/code/HEAD/tree/staden/trunk/src/Misc/getfile.c#l123
*/
char *expand_path(char *path)
{
kstring_t str = {0,0,0};
if ( path[0] == '~' )
{
if ( !path[1] || path[1] == '/' )
{
#ifdef _WIN32
kputs(getenv("HOMEDRIVE"), &str);
kputs(getenv("HOMEPATH"), &str);
#else
// ~ or ~/path
kputs(getenv("HOME"), &str);
if ( path[1] ) kputs(path+1, &str);
#endif
}
#ifndef _WIN32
else
{
// user name: ~pd3/path
char *end = path;
while ( *end && *end!='/' ) end++;
kputsn(path+1, end-path-1, &str);
struct passwd *pwentry = getpwnam(str.s);
str.l = 0;
if ( !pwentry ) kputsn(path, end-path, &str);
else kputs(pwentry->pw_dir, &str);
kputs(end, &str);
}
#endif
return ks_release(&str);
}
if ( path[0] == '$' )
{
char *var = getenv(path+1);
if ( var ) {
kputs(var, &str);
return ks_release(&str);
}
}
return strdup(path);
}
static void filters_set_qual(filter_t *flt, bcf1_t *line, token_t *tok)
{
float *ptr = &line->qual;
if ( bcf_float_is_missing(*ptr) )
bcf_double_set_missing(tok->values[0]);
else
tok->values[0] = (double)line->qual;
tok->nvalues = 1;
}
static void filters_set_type(filter_t *flt, bcf1_t *line, token_t *tok)
{
tok->values[0] = bcf_get_variant_types(line);
if ( !tok->values[0] ) tok->values[0] = 1; // mistake in htslib: VCF_* should start with 1
else tok->values[0] = ((int)tok->values[0]) << 1;
tok->nvalues = 1;
}
static void filters_set_info(filter_t *flt, bcf1_t *line, token_t *tok)
{
assert( tok->hdr_id >=0 );
int i;
for (i=0; i<line->n_info; i++)
if ( line->d.info[i].key == tok->hdr_id ) break;
if ( i==line->n_info )
tok->nvalues = tok->str_value.l = 0;
else if ( line->d.info[i].type==BCF_BT_CHAR )
{
int n = line->d.info[i].len;
if ( n >= tok->str_value.m )
{
tok->str_value.m = n + 1;
tok->str_value.s = (char*) realloc(tok->str_value.s, tok->str_value.m);
if ( !tok->str_value.s ) error("Failed to alloc %d bytes\n", (int)tok->str_value.m);
}
memcpy(tok->str_value.s, line->d.info[i].vptr, n);
tok->str_value.s[n] = 0;
tok->nvalues = tok->str_value.l = n;
}
else if ( line->d.info[i].type==BCF_BT_FLOAT )
{
if ( bcf_float_is_missing(line->d.info[i].v1.f) ) tok->nvalues = 0;
else
{
tok->values[0] = line->d.info[i].v1.f;
tok->nvalues = 1;
}
tok->str_value.l = 0;
}
else
{
tok->str_value.l = 0;
if ( line->d.info[i].type==BCF_BT_INT8 && line->d.info[i].v1.i==bcf_int8_missing ) tok->nvalues = 0;
else if ( line->d.info[i].type==BCF_BT_INT16 && line->d.info[i].v1.i==bcf_int16_missing ) tok->nvalues = 0;
else if ( line->d.info[i].type==BCF_BT_INT32 && line->d.info[i].v1.i==bcf_int32_missing ) tok->nvalues = 0;
else
{
tok->values[0] = line->d.info[i].v1.i;
tok->nvalues = 1;
}
}
}
static void filters_cmp_bit_and(token_t *atok, token_t *btok, token_t *rtok, bcf1_t *line)
{
int a = (int)(atok->nvalues?atok->values[0]:atok->threshold);
int b = (int)(btok->nvalues?btok->values[0]:btok->threshold);
if ( rtok->tok_type==TOK_LIKE )
rtok->pass_site = a&b ? 1 : 0;
else
rtok->pass_site = a&b ? 0 : 1;
}
static void filters_cmp_filter(token_t *atok, token_t *btok, token_t *rtok, bcf1_t *line)
{
int i;
if ( rtok->tok_type==TOK_NOT_IN )
{
if ( !line->d.n_flt )
{
if ( atok->hdr_id==-1 ) return; // missing value
rtok->pass_site = 1;
return; // no filter present, eval to true
}
for (i=0; i<line->d.n_flt; i++)
if ( atok->hdr_id==line->d.flt[i] ) return;
rtok->pass_site = 1;
return;
}
else if ( rtok->tok_type==TOK_IN )
{
if ( !line->d.n_flt )
{
if ( atok->hdr_id==-1 ) { rtok->pass_site = 1; return; }
return; // no filter present, eval to false
}
for (i=0; i<line->d.n_flt; i++)
if ( atok->hdr_id==line->d.flt[i] ) { rtok->pass_site = 1; return; }
return;
}
else if ( rtok->tok_type==TOK_NE ) // exact match
{
if ( !line->d.n_flt )
{
if ( atok->hdr_id==-1 ) return; // missing value
rtok->pass_site = 1;
return; // no filter present, eval to true
}
if ( line->d.n_flt==1 && atok->hdr_id==line->d.flt[0] ) return; // exact match, fail iff a single matching value is present
rtok->pass_site = 1;
return;
}
else if ( rtok->tok_type==TOK_EQ ) // exact match, pass iff a single matching value is present
{
if ( !line->d.n_flt )
{
if ( atok->hdr_id==-1 ) { rtok->pass_site = 1; return; }
return; // no filter present, eval to false
}
if ( line->d.n_flt==1 && atok->hdr_id==line->d.flt[0] ) rtok->pass_site = 1;
return;
}
else
error("Only ==, !=, ~, and !~ operators are supported for FILTER\n");
return;
}
static void filters_cmp_id(token_t *atok, token_t *btok, token_t *rtok, bcf1_t *line)
{
// multiple IDs not supported yet (easy to add though)
if ( rtok->tok_type!=TOK_EQ && rtok->tok_type!=TOK_NE )
error("Only == and != operators are supported for ID\n");
if ( btok->hash )
{
token_t *tmp = atok; atok = btok; btok = tmp;
}
if ( atok->hash )
{
int ret = khash_str2int_has_key(atok->hash, line->d.id);
if ( rtok->tok_type==TOK_NE ) ret = ret ? 0 : 1;
rtok->pass_site = ret;
return;
}
if ( !btok->str_value.l ) error("Error occurred while evaluating the expression\n");
if ( rtok->tok_type==TOK_EQ )
rtok->pass_site = strcmp(btok->str_value.s,line->d.id) ? 0 : 1;
else
rtok->pass_site = strcmp(btok->str_value.s,line->d.id) ? 1 : 0;
}
/**
* bcf_get_info_value() - get single INFO value, int64_t or double
* @line: BCF line
* @info_id: tag ID, as returned by bcf_hdr_id2int
* @ivec: 0-based index to retrieve, -1 when single value is expected
* @vptr: pointer to memory location of sufficient size to accomodate
* info_id's type
*
* The returned value is -1 if tag is not present, 0 if present but
* values is missing or ivec is out of range, and 1 on success.
*/
static int bcf_get_info_value(bcf1_t *line, int info_id, int ivec, void *value)
{
int j;
for (j=0; j<line->n_info; j++)
if ( line->d.info[j].key == info_id ) break;
if ( j==line->n_info ) return -1;
bcf_info_t *info = &line->d.info[j];
if ( info->len == 1 )
{
if ( info->type==BCF_BT_FLOAT ) *((double*)value) = info->v1.f;
else if ( info->type==BCF_BT_INT8 || info->type==BCF_BT_INT16 || info->type==BCF_BT_INT32 ) *((int64_t*)value) = info->v1.i;
return 1;
}
if ( ivec<0 ) ivec = 0;
#define BRANCH(type_t, is_missing, is_vector_end, out_type_t) { \
type_t *p = (type_t *) info->vptr; \
for (j=0; j<ivec && j<info->len; j++) \
{ \
if ( is_vector_end ) return 0; \
} \
if ( is_missing ) return 0; \
*((out_type_t*)value) = p[j]; \
return 1; \
}
switch (info->type) {
case BCF_BT_INT8: BRANCH(int8_t, p[j]==bcf_int8_missing, p[j]==bcf_int8_vector_end, int64_t); break;
case BCF_BT_INT16: BRANCH(int16_t, p[j]==bcf_int16_missing, p[j]==bcf_int16_vector_end, int64_t); break;
case BCF_BT_INT32: BRANCH(int32_t, p[j]==bcf_int32_missing, p[j]==bcf_int32_vector_end, int64_t); break;
case BCF_BT_FLOAT: BRANCH(float, bcf_float_is_missing(p[j]), bcf_float_is_vector_end(p[j]), double); break;
default: fprintf(stderr,"todo: type %d\n", info->type); exit(1); break;
}
#undef BRANCH
return -1; // this shouldn't happen
}
static void filters_set_chrom(filter_t *flt, bcf1_t *line, token_t *tok)
{
tok->str_value.l = 0;
kputs(bcf_seqname(flt->hdr,line), &tok->str_value);
tok->nvalues = tok->str_value.l;
tok->is_str = 1;
}
static void filters_set_pos(filter_t *flt, bcf1_t *line, token_t *tok)
{
tok->values[0] = line->pos+1;
tok->nvalues = 1;
}
static void filters_set_info_int(filter_t *flt, bcf1_t *line, token_t *tok)
{
if ( tok->idx==-2 )
{
tok->nvalues = bcf_get_info_int32(flt->hdr,line,tok->tag,&flt->tmpi,&flt->mtmpi);
if ( tok->nvalues<=0 ) tok->nvalues = 0;
else
{
hts_expand(double,tok->nvalues,tok->mvalues,tok->values);
int i, j = 0, end = tok->idxs[tok->nidxs-1] < 0 ? tok->nvalues - 1 : tok->nidxs - 1;
if ( end >= tok->nvalues ) end = tok->nvalues - 1;
for (i=0; i<=end; i++)
if ( i>=tok->nidxs || tok->idxs[i] ) tok->values[j++] = flt->tmpi[i];
tok->nvalues = j;
}
}
else
{
int64_t value = 0;
if ( bcf_get_info_value(line,tok->hdr_id,tok->idx,&value) <= 0 )
tok->nvalues = 0;
else
{
tok->values[0] = value;
tok->nvalues = 1;
}
}
}
static void filters_set_info_float(filter_t *flt, bcf1_t *line, token_t *tok)
{
if ( tok->idx==-2 )
{
tok->nvalues = bcf_get_info_float(flt->hdr,line,tok->tag,&flt->tmpf,&flt->mtmpf);
if ( tok->nvalues<=0 ) tok->nvalues = 0;
else
{
hts_expand(double,tok->nvalues,tok->mvalues,tok->values);
int i, j = 0, end = tok->idxs[tok->nidxs-1] < 0 ? tok->nvalues - 1 : tok->nidxs - 1;
if ( end >= tok->nvalues ) end = tok->nvalues - 1;
for (i=0; i<=end; i++)
if ( i>=tok->nidxs || tok->idxs[i] )
{
if ( bcf_float_is_missing(flt->tmpf[i]) ) bcf_double_set_missing(tok->values[j]);
else tok->values[j] = flt->tmpf[i];
j++;
}
tok->nvalues = j;
}
}
else
{
double value;
if ( bcf_get_info_value(line,tok->hdr_id,tok->idx,&value) <= 0 )
tok->nvalues = 0;
else
{
tok->values[0] = value;
tok->nvalues = 1;
}
}
}
static void filters_set_info_string(filter_t *flt, bcf1_t *line, token_t *tok)
{
int32_t m = tok->str_value.m;
int n = bcf_get_info_string(flt->hdr,line,tok->tag,&tok->str_value.s,&m);
tok->str_value.m = m;
if ( n<0 ) { tok->nvalues = tok->str_value.l = 0; return; }
if ( tok->idx>=0 )
{
// get ith field (i=tok->idx)
int i = 0;
char *ss = tok->str_value.s, *se = tok->str_value.s + n;
while ( ss<se && i<tok->idx )
{
if ( *ss==',' ) i++;
ss++;
}
if ( ss==se || i!=tok->idx ) { tok->nvalues = tok->str_value.l = 0; return; }
se = ss;
while ( se - tok->str_value.s < n && *se!=',' ) se++;
if ( ss==tok->str_value.s ) *se = 0;
else
{
memmove(tok->str_value.s, ss, se-ss);
tok->str_value.s[se-ss] = 0;
}
tok->str_value.l = se - ss;
}
else if ( tok->idx==-2 && tok->idxs[0]==-1 ) // keep all values, TAG[*]
tok->str_value.l = n;
else if ( tok->idx==-2 )
{
flt->tmps.l = 0;
ks_resize(&flt->tmps, n);
int i, iend = tok->idxs[tok->nidxs-1] < 0 ? n - 1 : tok->nidxs - 1;
if ( iend >= n ) iend = n - 1;
char *beg = tok->str_value.s, *dst = flt->tmps.s;
for (i=0; i<=iend; i++)
{
char *end = beg;
while ( *end && *end!=',' ) end++;
if ( i>=tok->nidxs || tok->idxs[i] )
{
memcpy(dst, beg, end - beg);
dst += end - beg;
dst[0] = ',';
dst++;
}
beg = end+1;
}
dst[0] = 0;
tok->str_value.l = dst - flt->tmps.s;
#define SWAP(type_t, a, b) { type_t t = a; a = b; b = t; }
SWAP(char *, flt->tmps.s, tok->str_value.s);
SWAP(size_t, flt->tmps.m, tok->str_value.m);
}
tok->nvalues = tok->str_value.l;
}
static void filters_set_info_flag(filter_t *flt, bcf1_t *line, token_t *tok)
{
int j;
for (j=0; j<line->n_info; j++)
if ( line->d.info[j].key == tok->hdr_id ) break;
tok->values[0] = j==line->n_info ? 0 : 1;
tok->nvalues = 1;
}
static void filters_set_format_int(filter_t *flt, bcf1_t *line, token_t *tok)
{
if ( line->n_sample != tok->nsamples )
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);
int nvals;
if ( (nvals=bcf_get_format_int32(flt->hdr,line,tok->tag,&flt->tmpi,&flt->mtmpi))<0 )
{
tok->nvalues = 0;
return;
}
int i, nsrc1 = nvals / tok->nsamples;
tok->nval1 = tok->idx >= 0 ? 1 : (tok->nuidxs ? tok->nuidxs : nsrc1);
tok->nvalues = tok->nval1*tok->nsamples;
hts_expand(double, tok->nvalues, tok->mvalues, tok->values);
if ( tok->idx >= 0 ) // scalar or vector index
{
for (i=0; i<tok->nsamples; i++)
{
if ( !tok->usmpl[i] ) continue;
int32_t *ptr = flt->tmpi + i*nsrc1;
if ( tok->idx>=nsrc1 || ptr[tok->idx]==bcf_int32_missing )
bcf_double_set_missing(tok->values[i]);
else if ( ptr[tok->idx]==bcf_int32_vector_end )
bcf_double_set_vector_end(tok->values[i]);
else
tok->values[i] = ptr[tok->idx];
}
}
else
{
int kend = tok->idxs[tok->nidxs-1] < 0 ? tok->nval1 : tok->nidxs;
for (i=0; i<tok->nsamples; i++)
{
if ( !tok->usmpl[i] ) continue;
int32_t *src = flt->tmpi + i*nsrc1;
double *dst = tok->values + i*tok->nval1;
int k, j = 0;
for (k=0; k<kend; k++)
{
if ( k<tok->nidxs && !tok->idxs[k] ) continue;
if ( src[k]==bcf_int32_missing )
bcf_double_set_missing(dst[j]);
else if ( src[k]==bcf_int32_vector_end )
bcf_double_set_vector_end(dst[j]);
else
dst[j] = src[k];
j++;
}
if ( j==0 )
{
bcf_double_set_missing(dst[j]);
j++;
}
while (j < tok->nval1)
{
bcf_double_set_vector_end(dst[j]);
j++;
}
}
}
}
static void filters_set_format_float(filter_t *flt, bcf1_t *line, token_t *tok)
{
if ( line->n_sample != tok->nsamples )
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);
int nvals;
if ( (nvals=bcf_get_format_float(flt->hdr,line,tok->tag,&flt->tmpf,&flt->mtmpf))<0 )
{
tok->nvalues = 0;
return;
}
int i, nsrc1 = nvals / tok->nsamples;
tok->nval1 = tok->idx >= 0 ? 1 : (tok->nuidxs ? tok->nuidxs : nsrc1);
tok->nvalues = tok->nval1*tok->nsamples;
hts_expand(double, tok->nvalues, tok->mvalues, tok->values);
if ( tok->idx >= 0 ) // scalar or vector index
{
for (i=0; i<tok->nsamples; i++)
{
if ( !tok->usmpl[i] ) continue;
float *ptr = flt->tmpf + i*nsrc1;
if ( tok->idx>=nsrc1 || bcf_float_is_missing(ptr[tok->idx]) )
bcf_double_set_missing(tok->values[i]);
else if ( bcf_float_is_vector_end(ptr[tok->idx]) )
bcf_double_set_vector_end(tok->values[i]);
else
tok->values[i] = ptr[tok->idx];
}
}
else
{
int kend = tok->idxs[tok->nidxs-1] < 0 ? tok->nval1 : tok->nidxs;
for (i=0; i<tok->nsamples; i++)
{
if ( !tok->usmpl[i] ) continue;
float *src = flt->tmpf + i*nsrc1;
double *dst = tok->values + i*tok->nval1;
int k, j = 0;
for (k=0; k<kend; k++)
{
if ( k<tok->nidxs && !tok->idxs[k] ) continue;
if ( bcf_float_is_missing(src[k]) )
bcf_double_set_missing(dst[j]);
else if ( bcf_float_is_vector_end(src[k]) )
bcf_double_set_vector_end(dst[j]);
else
dst[j] = src[k];
j++;
}
if ( j==0 )
{
bcf_double_set_missing(dst[j]);
j++;
}
while (j < tok->nval1)
{
bcf_double_set_vector_end(dst[j]);
j++;
}
}
}
}
static void filters_set_format_string(filter_t *flt, bcf1_t *line, token_t *tok)
{
if ( line->n_sample != tok->nsamples )
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);
int i, ndim = tok->str_value.m;
int nstr = bcf_get_format_char(flt->hdr, line, tok->tag, &tok->str_value.s, &ndim);
tok->str_value.m = ndim;
tok->str_value.l = tok->nvalues = 0;
if ( nstr<0 ) return;
tok->nvalues = tok->str_value.l = nstr;
tok->nval1 = nstr / tok->nsamples;
for (i=0; i<tok->nsamples; i++)
{
if ( !tok->usmpl[i] ) continue;
char *src = tok->str_value.s + i*tok->nval1, *dst = src;
int ibeg = 0, idx = 0;
while ( ibeg < tok->nval1 )
{
int iend = ibeg;
while ( iend < tok->nval1 && src[iend] && src[iend]!=',' ) iend++;
int keep = 0;
if ( tok->idx >= 0 )
{
if ( tok->idx==idx ) keep = 1;
}
else if ( idx < tok->nidxs )
{
if ( tok->idxs[idx] != 0 ) keep = 1;
}
else if ( tok->idxs[tok->nidxs-1] < 0 )
keep = 1;
if ( keep )
{
if ( ibeg!=0 ) memmove(dst, src+ibeg, iend-ibeg+1);
dst += iend - ibeg + 1;
if ( tok->idx>=0 ) break;
}
if ( !src[iend] ) break;
ibeg = iend + 1;
idx++;
}
if ( dst==src ) { dst[0] = '.'; dst+=2; }
if ( dst - src < tok->nval1 ) memset(dst-1, 0, tok->nval1 - (dst - src));
}
}
static void _filters_set_genotype(filter_t *flt, bcf1_t *line, token_t *tok, int type)
{
bcf_fmt_t *fmt = bcf_get_fmt(flt->hdr, line, "GT");
if ( !fmt )
{
tok->nvalues = tok->str_value.l = 0;
return;
}
int i,j, nsmpl = bcf_hdr_nsamples(flt->hdr), nvals1 = type==2 ? 3 : 4;
if ( tok->str_value.m <= nvals1*nsmpl )
{
tok->str_value.m = nvals1*nsmpl + 1;
tok->str_value.s = (char*)realloc(tok->str_value.s, tok->str_value.m);
}
#define BRANCH_INT(type_t,vector_end) \
{ \
for (i=0; i<line->n_sample; i++) \
{ \
type_t *ptr = (type_t*) (fmt->p + i*fmt->size); \
int is_het = 0, has_ref = 0, missing = 0; \
for (j=0; j<fmt->n; j++) \
{ \
if ( ptr[j]==vector_end ) break; /* smaller ploidy */ \
if ( bcf_gt_is_missing(ptr[j]) ) { missing=1; break; } /* missing allele */ \
int ial = ptr[j]; \
if ( bcf_gt_allele(ial)==0 ) has_ref = 1; \
if ( j>0 ) \
{ \
int jal = ptr[j-1]; \
if ( bcf_gt_allele(ial)!=bcf_gt_allele(jal) ) is_het = 1; \
} \
} \
char *dst = &tok->str_value.s[nvals1*i]; \
if ( type==4 ) \
{ \
if ( !j || missing ) dst[0]='m', dst[1]='i', dst[2]='s', dst[3] = 0; /* mis, missing genotype */ \
else if ( !has_ref ) dst[0]='a', dst[1]='l', dst[2]='t', dst[3] = 0; /* alt, no ref, must have alt allele */ \
else if ( !is_het ) dst[0]='r', dst[1]='e', dst[2]='f', dst[3] = 0; /* ref, must be ref-only, no alt alelle */ \
else dst[0]='a', dst[1]='l', dst[2]='t', dst[3] = 0; /* alt, is het, has alt allele */ \
} \
else if ( !j || missing ) dst[0]='.', dst[1]=0; /* ., missing genotype */ \
else if ( type==3 ) \
{ \
if ( j==1 ) dst[0]='h', dst[1]='a', dst[2]='p', dst[3] = 0; /* hap, haploid */ \
else if ( !is_het ) dst[0]='h', dst[1]='o', dst[2]='m', dst[3] = 0; /* hom */ \
else dst[0]='h', dst[1]='e', dst[2]='t', dst[3] = 0; /* het */ \
} \
else \
{ \
if ( j==1 ) \
{ \
if ( has_ref ) dst[0]='r', dst[1]=0; /* r, haploid */ \
else dst[0]='a', dst[1]=0; /* a, haploid */ \
} \
else if ( !is_het ) \
{ \
if ( has_ref ) dst[0]='r', dst[1]='r', dst[2] = 0; /* rr */ \
else dst[0]='a', dst[1]='a', dst[2] = 0; /* aa */ \
} \
else \
{ \
if ( has_ref ) dst[0]='r', dst[1]='a', dst[2] = 0; /* ra */ \
else dst[0]='a', dst[1]='A', dst[2] = 0; /* aA */ \
} \
} \
} \
}
switch (fmt->type) {
case BCF_BT_INT8: BRANCH_INT(int8_t, bcf_int8_vector_end); break;
case BCF_BT_INT16: BRANCH_INT(int16_t, bcf_int16_vector_end); break;
case BCF_BT_INT32: BRANCH_INT(int32_t, bcf_int32_vector_end); break;
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;
}
#undef BRANCH_INT
assert( tok->nsamples == nsmpl );
tok->nvalues = tok->str_value.l = nvals1*nsmpl;
tok->str_value.s[tok->str_value.l] = 0;
tok->nval1 = nvals1;
}
static void filters_set_genotype2(filter_t *flt, bcf1_t *line, token_t *tok) { _filters_set_genotype(flt, line, tok, 2); }
static void filters_set_genotype3(filter_t *flt, bcf1_t *line, token_t *tok) { _filters_set_genotype(flt, line, tok, 3); }
static void filters_set_genotype4(filter_t *flt, bcf1_t *line, token_t *tok) { _filters_set_genotype(flt, line, tok, 4); }
static void filters_set_genotype_string(filter_t *flt, bcf1_t *line, token_t *tok)
{
bcf_fmt_t *fmt = bcf_get_fmt(flt->hdr, line, "GT");
if ( !fmt )
{
tok->nvalues = 0;
return;
}
int i, blen = 4, nsmpl = line->n_sample;
gt_length_too_big:
tok->str_value.l = 0;
for (i=0; i<nsmpl; i++)
{
size_t plen = tok->str_value.l;
bcf_format_gt(fmt, i, &tok->str_value);
kputc_(0, &tok->str_value);
if ( tok->str_value.l - plen > blen )
{
// too many alternate alleles or ploidy is too large, the genotype does not fit
// three characters ("0/0" vs "10/10").
blen *= 2;
goto gt_length_too_big;
}
plen = tok->str_value.l - plen;
while ( plen < blen )
{
kputc_(0, &tok->str_value);
plen++;
}
}
assert( tok->nsamples == nsmpl );
tok->nvalues = tok->str_value.l;
tok->nval1 = blen;
}
static void filters_set_ilen(filter_t *flt, bcf1_t *line, token_t *tok)
{
tok->nvalues = line->n_allele - 1;
hts_expand(double,tok->nvalues,tok->mvalues,tok->values);
int i, rlen = strlen(line->d.allele[0]);
for (i=1; i<line->n_allele; i++)
{
int alen = strlen(line->d.allele[i]);
if ( rlen==alen ) bcf_double_set_missing(tok->values[i-1]);
else tok->values[i-1] = alen - rlen;