Source code

Download source archive ↓

upstream-dependencies/bcftools/plugins/fixploidy.c

1/* 
2    Copyright (C) 2014, 2018 Genome Research Ltd.
3
4    Author: Petr Danecek <pd3@sanger.ac.uk>
5
6    Permission is hereby granted, free of charge, to any person obtaining a copy
7    of this software and associated documentation files (the "Software"), to deal
8    in the Software without restriction, including without limitation the rights
9    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10    copies of the Software, and to permit persons to whom the Software is
11    furnished to do so, subject to the following conditions:
12    
13    The above copyright notice and this permission notice shall be included in
14    all copies or substantial portions of the Software.
15    
16    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22    THE SOFTWARE.
23*/
24
25#include <stdio.h>
26#include <stdlib.h>
27#include <strings.h>
28#include <assert.h>
29#include <getopt.h>
30#include <stdarg.h>
31#include <ctype.h>
32#include <htslib/vcf.h>
33#include <htslib/kseq.h>
34#include "bcftools.h"
35#include "ploidy.h"
36
37static bcf_hdr_t *in_hdr = NULL, *out_hdr = NULL;
38static int *sample2sex = NULL;
39static int n_sample = 0, nsex = 0, *sex2ploidy = NULL;
40static int32_t ngt_arr = 0, *gt_arr = NULL, *gt_arr2 = NULL, ngt_arr2 = 0;
41static ploidy_t *ploidy = NULL;
42static int force_ploidy = -1;
43
44const char *about(void)
45{
46    return "Fix ploidy.\n";
47}
48
49const char *usage(void)
50{
51    return 
52        "\n"
53        "About: Fix ploidy\n"
54        "Usage: bcftools +fixploidy [General Options] -- [Plugin Options]\n"
55        "Options:\n"
56        "   run \"bcftools plugin\" for a list of common options\n"
57        "\n"
58        "Plugin options:\n"
59        "   -d, --default-ploidy <int>  default ploidy for regions unlisted in -p [2]\n"
60        "   -f, --force-ploidy <int>    ignore -p, set the same ploidy for all genotypes\n"
61        "   -p, --ploidy <file>         space/tab-delimited list of CHROM,FROM,TO,SEX,PLOIDY\n"
62        "   -s, --sex <file>            list of samples, \"NAME SEX\"\n"
63        "   -t, --tags <list>           VCF tags to fix [GT]\n"
64        "\n"
65        "Example:\n"
66        "   # Default ploidy, if -p not given. Unlisted regions have ploidy 2\n"
67        "   X 1 60000 M 1\n"
68        "   X 2699521 154931043 M 1\n"
69        "   Y 1 59373566 M 1\n"
70        "   Y 1 59373566 F 0\n"
71        "   MT 1 16569 M 1\n"
72        "   MT 1 16569 F 1\n"
73        "   \n"
74        "   # Example of -s file, sex of unlisted samples is \"F\"\n"
75        "   sampleName1 M\n"
76        "   \n"
77        "   bcftools +fixploidy in.vcf -- -s samples.txt\n"
78        "\n";
79}
80
81void set_samples(char *fname, bcf_hdr_t *hdr, ploidy_t *ploidy, int *sample2sex)
82{
83    kstring_t tmp = {0,0,0};
84
85    htsFile *fp = hts_open(fname, "r");
86    if ( !fp ) error("Could not read: %s\n", fname);
87    while ( hts_getline(fp, KS_SEP_LINE, &tmp) > 0 )
88    {
89        char *ss = tmp.s;
90        while ( *ss && isspace(*ss) ) ss++;
91        if ( !*ss ) error("Could not parse: %s\n", tmp.s);
92        if ( *ss=='#' ) continue;
93        char *se = ss;
94        while ( *se && !isspace(*se) ) se++;
95        char x = *se; *se = 0;
96
97        int ismpl = bcf_hdr_id2int(hdr, BCF_DT_SAMPLE, ss);
98        if ( ismpl < 0 ) { fprintf(stderr,"Warning: No such sample in the VCF: %s\n",ss); continue; }
99
100        *se = x;
101        ss = se+1;
102        while ( *ss && isspace(*ss) ) ss++;
103        if ( !*ss )  error("Could not parse: %s\n", tmp.s);
104        se = ss;
105        while ( *se && !isspace(*se) ) se++;
106        if ( se==ss ) error("Could not parse: %s\n", tmp.s);
107
108        sample2sex[ismpl] = ploidy_add_sex(ploidy, ss);
109    }
110    if ( hts_close(fp) ) error("Close failed: %s\n", fname);
111    free(tmp.s);
112}
113
114int init(int argc, char **argv, bcf_hdr_t *in, bcf_hdr_t *out)
115{
116    int c, default_ploidy = 2;
117    char *tags_str = "GT";
118    char *ploidy_fname = NULL, *sex_fname = NULL;
119
120    static struct option loptions[] =
121    {
122        {"default-ploidy",1,0,'d'},
123        {"force-ploidy",1,0,'f'},
124        {"ploidy",1,0,'p'},
125        {"sex",1,0,'s'},
126        {"tags",1,0,'t'},
127        {0,0,0,0}
128    };
129    char *tmp;
130    while ((c = getopt_long(argc, argv, "?ht:s:p:d:f:",loptions,NULL)) >= 0)
131    {
132        switch (c) 
133        {
134            case 'd': 
135                default_ploidy = strtod(optarg,&tmp);
136                if ( *tmp ) error("Could not parse: -d %s\n", optarg);
137                break;
138            case 'f': 
139                force_ploidy = strtod(optarg,&tmp);
140                if ( *tmp ) error("Could not parse: -f %s\n", optarg);
141                break;
142            case 'p': ploidy_fname = optarg; break;
143            case 's': sex_fname = optarg; break;
144            case 't': tags_str = optarg; break;
145            case 'h':
146            case '?':
147            default: error("%s", usage()); break;
148        }
149    }
150    if ( strcasecmp("GT",tags_str) ) error("Only -t GT is currently supported, sorry\n");
151
152    n_sample   = bcf_hdr_nsamples(in);
153    sample2sex = (int*) calloc(n_sample,sizeof(int));
154    in_hdr     = in;
155    out_hdr    = out;
156
157    if ( ploidy_fname )
158        ploidy = ploidy_init(ploidy_fname, default_ploidy);
159    else if ( force_ploidy==-1 )
160    {
161        ploidy = ploidy_init_string(
162                "X 1 60000 M 1\n"
163                "X 2699521 154931043 M 1\n"
164                "Y 1 59373566 M 1\n"
165                "Y 1 59373566 F 0\n"
166                "MT 1 16569 M 1\n"
167                "MT 1 16569 F 1\n", 2);
168    }
169    if ( force_ploidy==-1 )
170    {
171        if ( !ploidy ) return -1;
172
173        // add default sex in case it was not included
174        int i, dflt_sex_id = ploidy_add_sex(ploidy, "F");
175        for (i=0; i<n_sample; i++) sample2sex[i] = dflt_sex_id; // by default all are F
176        if ( sex_fname ) set_samples(sex_fname, in, ploidy, sample2sex);
177        nsex = ploidy_nsex(ploidy);
178        sex2ploidy = (int*) malloc(sizeof(int)*nsex);
179    }
180
181    return 0;
182}
183
184
185bcf1_t *process(bcf1_t *rec)
186{
187    int i,j, max_ploidy;
188
189    int ngts = bcf_get_genotypes(in_hdr, rec, &gt_arr, &ngt_arr);
190    if ( ngts<0 )
191        return rec;     // GT field not present
192
193    if ( ngts % n_sample )
194        error("Error at %s:%"PRId64": wrong number of GT fields\n",bcf_seqname(in_hdr,rec),(int64_t) rec->pos+1);
195
196    if ( force_ploidy==-1 )
197        ploidy_query(ploidy, (char*)bcf_seqname(in_hdr,rec), rec->pos, sex2ploidy,NULL,&max_ploidy);
198    else
199        max_ploidy = force_ploidy;
200
201    ngts /= n_sample;
202    if ( ngts < max_ploidy )
203    {
204        hts_expand(int32_t,max_ploidy*n_sample,ngt_arr2,gt_arr2);
205        for (i=0; i<n_sample; i++)
206        {
207            int ploidy = force_ploidy!=-1 ? force_ploidy : sex2ploidy[ sample2sex[i] ];
208            int32_t *src = &gt_arr[i*ngts];
209            int32_t *dst = &gt_arr2[i*max_ploidy];
210            j = 0;
211            if ( !ploidy ) { dst[j] = bcf_gt_missing; j++; }
212            else
213                while ( j<ngts && j<ploidy && src[j]!=bcf_int32_vector_end ) { dst[j] = src[j]; j++; }
214            assert( j );
215            while ( j<ploidy ) { dst[j] = dst[j-1]; j++; } // expand "." to "./." and "0" to "0/0"
216            while ( j<max_ploidy ) { dst[j] = bcf_int32_vector_end; j++; }
217        }
218        if ( bcf_update_genotypes(out_hdr,rec,gt_arr2,n_sample*max_ploidy) )
219            error("Could not update GT field at %s:%"PRId64"\n", bcf_seqname(in_hdr,rec),(int64_t) rec->pos+1);
220    }
221    else if ( ngts!=1 || max_ploidy!=1 )
222    {
223        for (i=0; i<n_sample; i++)
224        {
225            int ploidy = force_ploidy!=-1 ? force_ploidy : sex2ploidy[ sample2sex[i] ];
226            int32_t *gts = &gt_arr[i*ngts];
227            j = 0;
228            if ( !ploidy ) { gts[j] = bcf_gt_missing; j++; }
229            else 
230                while ( j<ngts && j<ploidy && gts[j]!=bcf_int32_vector_end ) j++;
231            assert( j );
232            while ( j<ploidy ) { gts[j] = gts[j-1]; j++; } // expand "." to "./." and "0" to "0/0"
233            while ( j<ngts ) { gts[j] = bcf_int32_vector_end; j++; }
234        }
235        if ( bcf_update_genotypes(out_hdr,rec,gt_arr,n_sample*ngts) )
236            error("Could not update GT field at %s:%"PRId64"\n", bcf_seqname(in_hdr,rec),(int64_t) rec->pos+1);
237    }
238    return rec;
239}
240
241
242void destroy(void)
243{
244    free(gt_arr);
245    free(gt_arr2);
246    free(sample2sex);
247    free(sex2ploidy);
248    if ( ploidy ) ploidy_destroy(ploidy);
249}
250
251