File: ImputedRecBuilder.java

package info (click to toggle)
beagle 220722-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 9,644 kB
  • sloc: java: 17,045; sh: 55; makefile: 11
file content (376 lines) | stat: -rw-r--r-- 13,431 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
/*
 * Copyright (C) 2014-2021 Brian L. Browning
 *
 * This file is part of Beagle
 *
 * Beagle is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Beagle is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package imp;

import blbutil.Const;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.stream.IntStream;
import vcf.Marker;

/**
 * <p>Class {@code ImputeRecBuilder} contains methods for constructing
 * and printing a VCF record in VCF 4.3 format.  The sample data in
 * the output VCF record are in the same order that the data were added
 * with the {@code addSampleData()} method.
 * </p>
 * <p>Instances of class {@code ImputeRecBuilder} are not thread-safe.
 * </p>
 *
 * @author Brian L. Browning {@code <browning@uw.edu>}
 */
public final class ImputedRecBuilder {

    private static final DecimalFormat DF = new DecimalFormat("#.##");
    private static final DecimalFormat DF2 = new DecimalFormat("0.00");
    private static final DecimalFormat DF4 = new DecimalFormat("0.0000");

    private static final String[] DS_VALS = IntStream.range(0, 201)
            .mapToObj(j -> DF.format(j/100.0))
            .toArray(String[]::new);
    private static final String[] R2_VALS = IntStream.range(0, 101)
            .limit(101)
            .mapToObj(i -> (DS_VALS[i].length()!=4 ? DF2.format(i/100.0) : DS_VALS[i]))
            .toArray(String[]::new);

    private static final String[] DEFAULT_HOM_REF_FIELDS = defaultHomRefFields();

    private final Marker marker;
    private final int nAlleles;
    private final int nInputTargHaps;
    private final boolean ap;
    private final boolean gp;
    private final float[] sumAlProbs;
    private final float[] sumAlProbs2;
    private final String[] homRefField;
    private final StringBuilder sampleData;

    private int hapCnt;

    /**
     * Constructs a new {@code ImputedRecBuilder} instance for the specified
     * number of samples.
     *
     * @param marker the marker corresponding to the VCF record
     * @param nInputTargHaps the number of input target haplotypes for haploid
     * and diploid samples
     * @param ap {@code true} if posterior allele probabilities are to be printed
     * @param gp {@code true} if posterior genotype probabilities are to be printed
     * @throws IllegalArgumentException if {@code nInputTargHaps < 1}
     * @throws NullPointerException if {@code marker == null}
     */
    public ImputedRecBuilder(Marker marker, int nInputTargHaps, boolean ap,
            boolean gp) {
        if (nInputTargHaps < 1) {
            throw new IllegalArgumentException(String.valueOf(nInputTargHaps));
        }
        this.marker = marker;
        this.nAlleles = marker.nAlleles();
        this.nInputTargHaps = nInputTargHaps;
        this.ap = ap;
        this.gp = gp;
        this.sumAlProbs = new float[nAlleles];
        this.sumAlProbs2 = new float[nAlleles];
        this.sampleData = new StringBuilder(200 + nInputTargHaps*5);
        this.homRefField = (ap || gp) ? homRefFields(ap, gp)
                : DEFAULT_HOM_REF_FIELDS;
        this.hapCnt = 0;
    }

    /**
     * Returns the marker in the VCF record.
     * @return the marker in the VCF record
     */
    public Marker marker() {
        return marker;
    }

    /**
     * Returns the number of input target haplotypes for haploid
     * and diploid samples.
     * @return the number of input target haplotypes for haploid
     * and diploid samples
     */
    public int nInputTargHaps() {
        return nInputTargHaps;
    }

    /**
     * Returns the number of imputed alleles added by the addSampleData()
     * methods.
     * @return the number of imputed alleles added by the addSampleData()
     * methods
     */
    public int hapCnt() {
        return hapCnt;
    }

    /**
     * Scales the specified probabilities for each allele to each sum to 1.0,
     * and adds the sample data to the VCF record.  The contract
     * for this method is undefined if any element of the specified arrays is
     * not a finite non-negative number.
     * @param a1 the allele probabilities for the first allele
     * @param a2 the allele probabilities for the second allele
     * @throws IndexOutOfBoundsException if
     * {@code a1.length < this.marker().nAlleles()}
     * @throws IndexOutOfBoundsException if
     * {@code a2.length < this.marker().nAlleles()}
     * @throws NullPointerException if {@code a1 == null || a2 == null}
     */
    public void addSampleData(float[] a1, float[] a2) {
        hapCnt+=2;
        if (a1[0]==1.0f && a2[0]==1.0f && a1.length < DEFAULT_HOM_REF_FIELDS.length) {
            sampleData.append(homRefField[a1.length]);
        }
        else {
            scale(a1);
            scale(a2);
            sampleData.append(Const.tab);
            sampleData.append(maxIndex(a1));
            sampleData.append(Const.phasedSep);
            sampleData.append(maxIndex(a2));
            for (int a=1; a<nAlleles; ++a) {
                float dose = a1[a] + a2[a];
                float dose2 = a1[a]*a1[a] + a2[a]*a2[a];
                sumAlProbs[a] += dose;
                sumAlProbs2[a] += dose2;
                sampleData.append( (a==1) ? Const.colon : Const.comma );
                sampleData.append(DS_VALS[(int) Math.rint(100*dose)]);
            }
            if (ap) {
                for (int a=1; a<nAlleles; ++a) {
                    sampleData.append( (a==1) ? Const.colon : Const.comma );
                    sampleData.append(DS_VALS[(int) Math.rint(100*a1[a])]);
                }
                for (int a=1; a<nAlleles; ++a) {
                    sampleData.append( (a==1) ? Const.colon : Const.comma );
                    sampleData.append(DS_VALS[(int) Math.rint(100*a2[a])]);
                }
            }
            if (gp) {
                for (int i2=0; i2<nAlleles; ++i2) {
                    for (int i1=0; i1<=i2; ++i1) {
                        float prob = a1[i1]*a2[i2];
                        if (i1!=i2) {
                            prob += a1[i2]*a2[i1];
                        }
                        sampleData.append( (i2==0) ? Const.colon : Const.comma );
                        sampleData.append(DS_VALS[(int) Math.rint(100*prob)]);
                    }
                }
            }
        }
    }

    /**
     * Scales the specified probabilities for each allele to each sum to 1.0,
     * and adds the sample data to the VCF record.  The contract
     * for this method is undefined if any element of the specified arrays is
     * not a finite non-negative number.
     * @param a1 the allele probabilities
     * @throws IndexOutOfBoundsException if
     * {@code a1.length < this.marker().nAlleles()}
     * @throws IndexOutOfBoundsException if
     * {@code a2.length < this.marker().nAlleles()}
     * @throws NullPointerException if {@code a1 == null || a2 == null}
     */
    public void addSampleData(float[] a1) {
        ++hapCnt;
        scale(a1);
        sampleData.append(Const.tab);
        sampleData.append(maxIndex(a1));
        for (int a=1; a<nAlleles; ++a) {
            float dose = a1[a];
            float dose2 = a1[a]*a1[a];
            sumAlProbs[a] += dose;
            sumAlProbs2[a] += dose2;
            sampleData.append( (a==1) ? Const.colon : Const.comma );
            sampleData.append(DS_VALS[(int) Math.rint(100*dose)]);
        }
        if (ap) {
            for (int a=1; a<nAlleles; ++a) {
                sampleData.append( (a==1) ? Const.colon : Const.comma );
                sampleData.append(DS_VALS[(int) Math.rint(100*a1[a])]);
            }
        }
    }

    private static void scale(float[] fa) {
        float sum = 0f;
        for (float f : fa) {
            sum += f;
        }
        for (int j=0; j<fa.length; ++j) {
            fa[j] /= sum;
        }
    }

    private static int maxIndex(float[] fa) {
        int maxIndex=0;
        for (int j=1; j<fa.length; ++j) {
            if (fa[j] > fa[maxIndex]) {
                maxIndex = j;
            }
        }
        return maxIndex;
    }

    /**
     * Prints the VCF record to the specified {@code PrintWriter}.
     * The INFO field of the VCF record will include the DR2 (dose r2) and
     * AF (ALT allele frequency) subfields.
     * @param isImputed {@code true} if the INFO field of the VCF record will
     * have an IMP flag and {@code false} otherwise
      *@param out the {@code PrintWriter} to which the VCF record will be
     * printed
     * @throws IllegalStateException if
     * {@code this.hapCnt() != this.nInputTargHaps()}
     * @throws NullPointerException if {@code out == null}
     */
    public void printRec(PrintWriter out, boolean isImputed) {
        if (hapCnt != nInputTargHaps) {
            throw new IllegalStateException("inconsistent data");
        }
        printMarkerFields(marker, out);
        out.print(Const.tab);
        out.print(Const.MISSING_DATA_CHAR);             // QUAL
        out.print(Const.tab);
        out.print("PASS");                              // FILTER
        out.print(Const.tab);
        printInfoField(out, isImputed);                 // INFO
        out.print(Const.tab);
        out.print("GT:DS");                             // FORMAT
        if (ap) {
            out.print(":AP1:AP2");
        }
        if (gp) {
            out.print(":GP");
        }
        out.println(sampleData);
    }

    private static void printMarkerFields(Marker marker, PrintWriter out) {
        out.print(marker.chrom());
        out.print(Const.tab);
        out.print(marker.pos());
        int nIds = marker.nIds();
        if (nIds==0) {
            out.print(Const.tab);
            out.print(Const.MISSING_DATA_CHAR);
        }
        else {
            for (int j=0; j<nIds; ++j) {
                out.print(j==0 ? Const.tab : Const.semicolon);
                out.print(marker.id(j));
            }
        }
        int nAlleles = marker.nAlleles();
        if (nAlleles==1) {
            out.print(Const.tab);
            out.print(marker.allele(0));
            out.print(Const.tab);
            out.print(Const.MISSING_DATA_CHAR);
        }
        else {
            for (int j=0; j<nAlleles; ++j) {
                out.print(j<2 ? Const.tab : Const.comma);
                out.print(marker.allele(j));
            }
        }
    }

    private void printInfoField(PrintWriter out, boolean isImputed) {
        if (nAlleles==1) {
            if (isImputed) {
                out.print("IMP");
            }
        }
        else {
            for (int a=1; a<nAlleles; ++a) {
                out.print( (a==1) ? "DR2=" : Const.comma);
                out.print(R2_VALS[(int) Math.rint(100*r2(a))]);
            }
            for (int a=1; a<nAlleles; ++a) {
                out.print( (a==1) ? ";AF=" : Const.comma);
                out.print(DF4.format(sumAlProbs[a]/nInputTargHaps));
            }
            if (marker.end()!=-1) {
                out.print(";END=");
                out.print(marker.end());
            }
            if (isImputed) {
                out.print(";IMP");
            }
        }
    }

    private float r2(int allele) {
        float sum = sumAlProbs[allele];
        if (sum==0f) {
            return 0f;
        }
        else {
            float sum2 = sumAlProbs2[allele];
            float meanTerm = sum*sum/(nInputTargHaps);
            float num = (sum2 - meanTerm);
            float den = (sum - meanTerm);
            return num <= 0 ? 0f : num/den;
        }
    }

    private static String[] defaultHomRefFields() {
        String[] sa = new String[5];
        sa[1] = Const.tab + "0|0";
        sa[2] = Const.tab + "0|0:0";
        for (int j=3; j<sa.length; ++j) {
            sa[j] = sa[j-1] + ",0";
        }
        return sa;
    }

    private static String[] homRefFields(boolean ap, boolean gp) {
        String[] homRefField = new String[DEFAULT_HOM_REF_FIELDS.length];
        for (int nAl=1; nAl<homRefField.length; ++nAl) {
            StringBuilder sb = new StringBuilder(DEFAULT_HOM_REF_FIELDS[nAl]);
            if (ap) {
                for (int a=1; a<nAl; ++a) {
                    sb.append( (a==1) ? Const.colon : Const.comma );
                    sb.append(DS_VALS[0]);
                }
                for (int a=1; a<nAl; ++a) {
                    sb.append( (a==1) ? Const.colon : Const.comma );
                    sb.append(DS_VALS[0]);
                }
            }
            if (gp) {
                sb.append(Const.colon);
                sb.append(DS_VALS[100]);
                for (int i2=1; i2<nAl; ++i2) {
                    for (int i1=0; i1<=i2; ++i1) {
                        sb.append(Const.comma);
                        sb.append(DS_VALS[0]);
                    }
                }
            }
            homRefField[nAl] = sb.toString();
        }
        return homRefField;
    }
}