File: gvcfz.c.pysam.c

package info (click to toggle)
python-pysam 0.15.4%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 27,992 kB
  • sloc: ansic: 140,738; python: 7,881; sh: 265; makefile: 223; perl: 41
file content (380 lines) | stat: -rw-r--r-- 14,324 bytes parent folder | download
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
#include "bcftools.pysam.h"

/* 
    Copyright (C) 2017 Genome Research Ltd.

    Author: Petr Danecek <pd3@sanger.ac.uk>

    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.
*/
/*
    Compress gVCF file by resizing gVCF blocks according to specified criteria.
*/

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <getopt.h>
#include <stdarg.h>
#include <unistd.h>
#include <stdint.h>
#include <errno.h>
#include <ctype.h>
#include <inttypes.h>
#include <sys/stat.h>
#include <htslib/vcf.h>
#include <htslib/vcfutils.h>
#include <htslib/synced_bcf_reader.h>
#include "bcftools.h"
#include "filter.h"

#define FLT_INCLUDE 1
#define FLT_EXCLUDE 2

#define GQ_KEY_NONE NULL
#define GQ_KEY_GQ   "GQ"
#define GQ_KEY_RGQ  "RGQ"

typedef struct
{
    int32_t end, min_dp, gq, pl[3], grp;
    char *gq_key;
    bcf1_t *rec;
}
block_t;
typedef struct
{
    char *expr;     // expression
    int flt_id;     // filter id, -1 for PASS
    filter_t *flt;  // filter
}
grp_t;
typedef struct
{
    filter_t *filter;
    char *filter_str;
    int filter_logic;
    block_t gvcf;
    htsFile *fh_out;
    int ngrp;
    grp_t *grp;
    char *group_by;
    int argc, region_is_file, target_is_file, output_type, trim_alts;
    int32_t *tmpi, mtmpi, mean_min_dp_reported;
    char **argv, *region, *target, *fname, *output_fname, *keep_tags;
    bcf_hdr_t *hdr_in, *hdr_out;
    bcf_srs_t *sr;
}
args_t;

const char *about(void)
{
    return "Compress gVCF file by resizing gVCF blocks according to specified criteria.\n";
}

static const char *usage_text(void)
{
    return 
        "\n"
        "About: Compress gVCF file by resizing gVCF blocks according to specified criteria.\n"
        "\n"
        "Usage: bcftools +gvcfz [Options]\n"
        "Plugin options:\n"
        "   -a, --trim-alt-alleles          trim alternate alleles not seen in the genotypes\n"
        "   -e, --exclude <expr>            exclude sites for which the expression is true\n"
        "   -i, --include <expr>            include sites for which the expression is true\n"
        "   -g, --group-by EXPR             group gVCF blocks according to the expression\n"
        "   -o, --output FILE               write gVCF output to the FILE\n"
        "   -O, --output-type b|u|z|v       b: compressed BCF, u: uncompressed BCF, z: compressed VCF, v: uncompressed VCF [v]\n"
        "Examples:\n"
        "   # Compress blocks by GQ and DP. Multiple blocks separated by a semicolon can be defined\n"
        "   bcftools +gvcfz input.bcf -g'PASS:GQ>60 & DP<20; PASS:GQ>40 & DP<15; Flt1:QG>20; Flt2:-'\n"
        "\n"
        "   # Compress all non-reference sites into a single block, remove unused alternate alleles\n"
        "   bcftools +gvcfz input.bcf -a -g'PASS:GT!=\"alt\"'\n"
        "\n";
}

static void init_groups(args_t *args)
{
    args->hdr_out = bcf_hdr_dup(args->hdr_in);
    bcf_hdr_printf(args->hdr_out, "##INFO=<ID=END,Number=1,Type=Integer,Description=\"Stop position of the interval\">");

    // avoid nested double quotes in FILTER description
    char *hdr_str = strdup(args->group_by);
    char *tmp = hdr_str;
    while (*tmp)
    {
        if ( *tmp=='"' ) *tmp = '\'';
        tmp++;
    }

    char *rmme_str = strdup(args->group_by), *beg = rmme_str;
    while ( *beg )
    {
        while ( *beg && isspace(*beg) ) beg++;
        if ( !beg ) break;
        char *end = beg;
        while ( *end && *end!=':' ) end++;
        if ( *end!=':' ) error("Could not parse the expression: \"%s\"\n", args->group_by);
        *end = 0;
        char *flt = beg;
        beg = ++end;
        while ( *end && *end!=';' ) end++;
        char tmp = *end; *end = 0;
        if ( strcmp(flt,"PASS") ) 
        {
            bcf_hdr_printf(args->hdr_out, "##FILTER=<ID=%s,Description=\"%s\">", flt, hdr_str);
            if (bcf_hdr_sync(args->hdr_out) < 0)
                error_errno("[%s] Failed to update header", __func__);
        }
        args->ngrp++;
        args->grp = (grp_t*) realloc(args->grp,sizeof(grp_t)*args->ngrp);
        grp_t *grp = args->grp + args->ngrp - 1;
        grp->expr = strdup(beg);
        grp->flt_id = bcf_hdr_id2int(args->hdr_out, BCF_DT_ID, flt);
        if ( !bcf_hdr_idinfo_exists(args->hdr_out, BCF_HL_FLT, grp->flt_id) ) error("Could not initialize the filter \"%s\"\n", flt);
        if ( !strcmp(flt,"PASS") ) grp->flt_id = -1;

        // remove trailing spaces
        beg = grp->expr + strlen(grp->expr); while ( beg >= grp->expr && isspace(*beg) ) { *beg = 0; beg--; }
        beg = grp->expr; while ( *beg && isspace(*beg) ) beg++;

        grp->flt = strcmp("-",beg) ? filter_init(args->hdr_in, grp->expr) : NULL;

        if ( !tmp ) break;
        beg = end + 1;
    }
    free(rmme_str);
    free(hdr_str);
}

static void destroy_data(args_t *args)
{
    int i;
    for (i=0; i<args->ngrp; i++)
    {
        if ( args->grp[i].flt ) filter_destroy(args->grp[i].flt);
        free(args->grp[i].expr);
    }
    free(args->grp);

    if ( args->filter ) filter_destroy(args->filter);
    if ( hts_close(args->fh_out)!=0 ) error("failed to close %s\n", args->output_fname);

    bcf_sr_destroy(args->sr);
    if ( args->hdr_out ) bcf_hdr_destroy(args->hdr_out);
    if ( args->gvcf.rec ) bcf_destroy(args->gvcf.rec);
    free(args->tmpi);
    free(args);
}

static void flush_block(args_t *args, bcf1_t *rec)
{
    block_t *gvcf = &args->gvcf;
    if ( gvcf->grp < 0 ) return;
    if ( rec && gvcf->end - 1 >= rec->pos ) gvcf->end = rec->pos; // NB: end is 1-based, rec->pos is 0-based

    if ( gvcf->rec->pos+1 < gvcf->end && bcf_update_info_int32(args->hdr_out,gvcf->rec,"END",&gvcf->end,1) != 0 )
        error("Could not update INFO/END at %s:%"PRId64"\n", bcf_seqname(args->hdr_out,gvcf->rec),(int64_t) gvcf->rec->pos+1);
    if ( bcf_update_format_int32(args->hdr_out,gvcf->rec,"DP",&gvcf->min_dp,1) != 0 )
        error("Could not update FORMAT/DP at %s:%"PRId64"\n", bcf_seqname(args->hdr_out,gvcf->rec),(int64_t) gvcf->rec->pos+1);
    if ( gvcf->gq_key )
    {
        if ( bcf_update_format_int32(args->hdr_out,gvcf->rec,gvcf->gq_key,&gvcf->gq,1) != 0 )
            error("Could not update FORMAT/%s at %s:%"PRId64"\n", gvcf->gq_key, bcf_seqname(args->hdr_out,gvcf->rec),(int64_t) gvcf->rec->pos+1);
    }
    if ( gvcf->pl[0] >=0 )
    {
        if ( bcf_update_format_int32(args->hdr_out,gvcf->rec,"PL",&gvcf->pl,3) != 0 )
            error("Could not update FORMAT/PL at %s:%"PRId64"\n", bcf_seqname(args->hdr_out,gvcf->rec),(int64_t) gvcf->rec->pos+1);
    }
    if ( gvcf->grp < args->ngrp && args->grp[gvcf->grp].flt_id >= 0 ) 
        bcf_add_filter(args->hdr_out, gvcf->rec, args->grp[gvcf->grp].flt_id);

    if ( bcf_write(args->fh_out, args->hdr_out, gvcf->rec)!=0 ) error("Failed to write the header\n");

    gvcf->grp = -1;
}
static void process_gvcf(args_t *args)
{
    bcf1_t *rec = bcf_sr_get_line(args->sr,0);

    if ( args->filter )
    {
        int pass = filter_test(args->filter, rec, NULL);
        if ( args->filter_logic & FLT_EXCLUDE ) pass = pass ? 0 : 1;
        if ( !pass ) return;
    }

    if ( rec->n_allele > 2 || (rec->n_allele == 2 && strcmp("<NON_REF>",rec->d.allele[1]) && strcmp("<*>",rec->d.allele[1])) )
    {
        if ( args->trim_alts )
        {
            bcf_unpack(rec, BCF_UN_ALL);
            if ( bcf_trim_alleles(args->hdr_in, rec)<0 )
                error("Error: Could not trim alleles at %s:%"PRId64"\n", bcf_seqname(args->hdr_in, rec),(int64_t)  rec->pos+1);

            // trim the ref allele if necessary
            if ( rec->d.allele[0][1] )
            {
                rec->d.allele[0][1] = 0;
                bcf_update_alleles(args->hdr_in, rec, (const char**)rec->d.allele, 1);
            }

        }
        if ( rec->n_allele > 2 || (rec->n_allele == 2 && strcmp("<NON_REF>",rec->d.allele[1]) && strcmp("<*>",rec->d.allele[1])) )
        {
            // not a gvcf block
            flush_block(args, rec);
            if ( bcf_write(args->fh_out, args->hdr_out, rec)!=0 ) error("Failed to write\n");
            return;
        }
    }

    int ret = bcf_get_info_int32(args->hdr_in,rec,"END",&args->tmpi,&args->mtmpi);
    int32_t end = ret==1 ? args->tmpi[0] : rec->pos + 1;

    char *gq_key = GQ_KEY_GQ;
    ret = bcf_get_format_int32(args->hdr_in,rec,gq_key,&args->tmpi,&args->mtmpi);
    if ( ret!=1 )
    {
        gq_key = GQ_KEY_RGQ;
        if ( ret<1 ) ret = bcf_get_format_int32(args->hdr_in,rec,gq_key,&args->tmpi,&args->mtmpi);
        if ( ret!=1 ) gq_key = GQ_KEY_NONE;
    }
    int32_t gq = ret==1 ? args->tmpi[0] : 0;

    int32_t min_dp = 0;
    if ( bcf_get_format_int32(args->hdr_in,rec,"MIN_DP",&args->tmpi,&args->mtmpi)==1 )
        min_dp = args->tmpi[0];
    else if ( bcf_get_format_int32(args->hdr_in,rec,"DP",&args->tmpi,&args->mtmpi)==1 )
        min_dp = args->tmpi[0];
    else
        error("Expected one FORMAT/MIN_DP or FORMAT/DP value at %s:%"PRId64"\n", bcf_seqname(args->hdr_in,rec),(int64_t) rec->pos+1);

    int32_t pl[3] = {-1,-1,-1};
    ret = bcf_get_format_int32(args->hdr_in,rec,"PL",&args->tmpi,&args->mtmpi);
    if ( ret>3 ) error("Expected three FORMAT/PL values at %s:%"PRId64"\n", bcf_seqname(args->hdr_in,rec),(int64_t) rec->pos+1);
    else if ( ret==3 )
    {
        pl[0] = args->tmpi[0];
        pl[1] = args->tmpi[1];
        pl[2] = args->tmpi[2];
    }

    int i;
    for (i=0; i<args->ngrp; i++)
        if ( !args->grp[i].flt || filter_test(args->grp[i].flt, rec, NULL)==1 ) break;

    if ( args->gvcf.grp != i ) flush_block(args, rec);      // new block
    if ( args->gvcf.grp >= 0 && args->gvcf.rec->rid != rec->rid ) flush_block(args, NULL);  // new chromosome

    if ( args->gvcf.grp >= 0 ) // extend an existing block
    {
        if ( args->gvcf.end < end ) args->gvcf.end = end;
        if ( args->gvcf.gq_key!=GQ_KEY_NONE && gq_key!=GQ_KEY_NONE && args->gvcf.gq > gq ) args->gvcf.gq = gq;
        if ( args->gvcf.min_dp > min_dp ) args->gvcf.min_dp = min_dp;
        if ( args->gvcf.pl[0] > pl[0] ) args->gvcf.pl[0] = pl[0];
        if ( args->gvcf.pl[1] > pl[1] ) args->gvcf.pl[1] = pl[1];
        if ( args->gvcf.pl[2] > pl[2] ) args->gvcf.pl[2] = pl[2];
        return;
    }

    // start a new block
    args->gvcf.rec = bcf_copy(args->gvcf.rec, rec);
    args->gvcf.grp = i;
    args->gvcf.min_dp   = min_dp;
    args->gvcf.end      = end;
    args->gvcf.pl[0]    = pl[0];
    args->gvcf.pl[1]    = pl[1];
    args->gvcf.pl[2]    = pl[2];
    args->gvcf.gq_key   = gq_key;
    if ( gq_key!=GQ_KEY_NONE ) args->gvcf.gq = gq;
}

int run(int argc, char **argv)
{
    args_t *args = (args_t*) calloc(1,sizeof(args_t));
    args->argc   = argc; args->argv = argv;
    args->output_type  = FT_VCF;
    args->output_fname = "-";
    static struct option loptions[] =
    {
        {"trim-alt-alleles",required_argument,0,'a'},
        {"include",required_argument,0,'i'},
        {"exclude",required_argument,0,'e'},
        {"group-by",required_argument,NULL,'g'},
        {"stats",required_argument,NULL,'s'},
        {"output",required_argument,NULL,'o'},
        {"output-type",required_argument,NULL,'O'},
        {NULL,0,NULL,0}
    };
    int c;
    while ((c = getopt_long(argc, argv, "vr:R:t:T:o:O:g:i:e:a",loptions,NULL)) >= 0)
    {
        switch (c) 
        {
            case 'a': args->trim_alts = 1; break;
            case 'e': args->filter_str = optarg; args->filter_logic |= FLT_EXCLUDE; break;
            case 'i': args->filter_str = optarg; args->filter_logic |= FLT_INCLUDE; break;
            case 'g': args->group_by = optarg; break;
            case 'o': args->output_fname = optarg; break;
            case 'O':
                      switch (optarg[0]) {
                          case 'b': args->output_type = FT_BCF_GZ; break;
                          case 'u': args->output_type = FT_BCF; break;
                          case 'z': args->output_type = FT_VCF_GZ; break;
                          case 'v': args->output_type = FT_VCF; break;
                          default: error("The output type \"%s\" not recognised\n", optarg);
                      }
                      break;
            case 'h':
            case '?':
            default: error("%s", usage_text()); break;
        }
    }
    if ( optind==argc )
    {
        if ( !isatty(fileno((FILE *)stdin)) ) args->fname = "-";  // reading from stdin
        else { error("%s", usage_text()); }
    }
    else if ( optind+1!=argc ) error("%s", usage_text());
    else args->fname = argv[optind];

    if ( !args->group_by ) error("Missing the -g option\n");

    args->gvcf.rec = bcf_init();
    args->gvcf.grp = -1;            // the block is inactive
    args->sr = bcf_sr_init();
    if ( !bcf_sr_add_reader(args->sr,args->fname) ) error("Error: %s\n", bcf_sr_strerror(args->sr->errnum));
    args->hdr_in = bcf_sr_get_header(args->sr,0);
    if ( args->filter_str )
        args->filter = filter_init(args->hdr_in, args->filter_str);
    init_groups(args);
    args->fh_out = hts_open(args->output_fname,hts_bcf_wmode(args->output_type));
    if ( bcf_hdr_write(args->fh_out, args->hdr_out)!=0 ) error("Failed to write the header\n");
    while ( bcf_sr_next_line(args->sr) ) process_gvcf(args);
    flush_block(args, NULL);

    destroy_data(args);
    return 0;
}