File: WindowWriter.java

package info (click to toggle)
beagle 241217-3
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 9,712 kB
  • sloc: java: 17,684; sh: 55; makefile: 11
file content (273 lines) | stat: -rw-r--r-- 10,385 bytes parent folder | download | duplicates (2)
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
/*
 * 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 main;

import blbutil.BGZIPOutputStream;
import blbutil.Utilities;
import imp.ImpData;
import imp.ImputedVcfWriter;
import imp.StateProbs;
import ints.IntList;
import ints.UnsignedByteArray;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.stream.IntStream;
import phase.Stage2Haps;
import vcf.GT;
import vcf.GTRec;
import vcf.Samples;
import vcf.VcfWriter;

/**
 * <p>Class {@code WindowWriter} writes VCF and IBD output data.
 * </p>
 * <p>Instances of class {@code WindowWriter} are not thread-safe.
 * </p>
 *
 * @author Brian L. Browning {@code <browning@uw.edu>}
 */
public class WindowWriter implements Closeable {

    private final Samples samples;
    private final String outPrefix;
    private final File vcfOutFile;

    /**
     * Constructs a new {@code WindowWriter} object.
     * @param par the analysis parameters
     * @param samples the sample whose data will be printed
     *
     * @throws IllegalArgumentException if {@code outPrefix.length() == 0}
     * @throws NullPointerException if
     * {@code par == null || samples == null}
     */
    public WindowWriter(Par par, Samples samples) {
        if (samples==null) {
            throw new NullPointerException("samples==null");
        }
        this.outPrefix = par.out();
        this.vcfOutFile = new File(outPrefix + ".vcf.gz");
        this.samples = samples;

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (PrintWriter vcfOut=new PrintWriter(
                new BGZIPOutputStream(baos, false))) {
            boolean ds = true;
            boolean ap = par.ap();
            boolean gp = par.gp();
            boolean gl = false;
            VcfWriter.writeMetaLines(samples.ids(), Main.PROGRAM,
                    ds, ap, gp, gl, vcfOut);
        }
        try {
            try (FileOutputStream fos=new FileOutputStream(vcfOutFile)) {
                fos.write(baos.toByteArray());
            }
        } catch (IOException e) {
            fileOutputError(vcfOutFile, e);
        }
    }

    /**
     * Returns the output file prefix.
     * @return the output file prefix
     */
    public String outPrefix() {
        return outPrefix;
    }

    /**
     * Returns the samples whose data is written by {@code this}.
     * @return the samples whose data is written by {@code this}
     */
    public Samples samples() {
        return samples;
    }

    /**
     * Prints the data in {@code alProbs} for markers
     * with index between {@code refStart} (inclusive) and
     * {@code refEnd} (exclusive) to the output
     * VCF file: {@code this.outPrefix() + ".vcf.gz"}.
     *
     * @param impData the input data for genotype imputation
     * @param stateProbs the imputed state probabilities
     * @param start the starting reference marker index (inclusive)
     * @param end the ending reference marker index (exclusive)
     *
     * @throws IllegalArgumentException if
     * {@code stateProbs.size() != impData.nTargHaps()}
     * @throws IndexOutOfBoundsException if
     * {@code start < 0 || end > impData.refGT().nMarkers()}
     * @throws NullPointerException if {@code impData==null || stateProbs==null}
     * @throws NullPointerException if any element of {@code stateProbs} is
     * {@code null}
     */
    public void printImputed(ImpData impData, int start, int end,
            AtomicReferenceArray<StateProbs> stateProbs) {
        checkInterval(start, end, impData.refGT().nMarkers());
        if (stateProbs.length() != impData.nTargHaps()) {
            throw new IllegalArgumentException("inconsistent data:");
        }
        UnsignedByteArray[] output = IntStream.range(0, impData.nClusters())
                .parallel()
                .mapToObj(c -> toByteArray(impData, start, end, stateProbs, c))
                .toArray(UnsignedByteArray[]::new);
        append(output, vcfOutFile);
    }

    private static UnsignedByteArray toByteArray(ImpData impData,
            int refStart, int refEnd,
            AtomicReferenceArray<StateProbs> stateProbs, int m) {
        ImputedVcfWriter ivw = new ImputedVcfWriter(impData, refStart, refEnd, m);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (PrintWriter out = new PrintWriter(
                new BGZIPOutputStream(baos, false))) {
            ivw.appendRecords(stateProbs, out);
        }
        return new UnsignedByteArray(baos);
    }

    /**
     * Appends the data in phased genotypes for the specified markers
     * to the output VCF file: {@code this.outPrefix() + ".vcf.gz"}.
     *
     * @param phasedTarg the estimated target haplotypes
     * @param start the starting marker index (inclusive)
     * @param end the ending marker index (exclusive)
     * @throws IllegalArgumentException if {@code phasedTarg.isPhased() == false}
     * @throws IndexOutOfBoundsException if
     * {@code start < 0 || end > phasedTarg.nMarkers() || start > end}
     * @throws NullPointerException if {@code phasedTarg == null}
     */
    public void printPhased(GT phasedTarg, int start, int end) {
        checkInterval(start, end, phasedTarg.nMarkers());
        long t0 = System.nanoTime();
        int blockSize = 50000;
        int stepSize = 100;
        int[] blockEnds = ends(start, end, blockSize);
        for (int j=1; j<blockEnds.length; ++j) {
            int[] stepEnds = ends(blockEnds[j-1], blockEnds[j], stepSize);
            UnsignedByteArray[] output = IntStream.range(1, stepEnds.length)
                    .parallel()
                    .mapToObj(i -> toByteArray(phasedTarg, stepEnds[i-1], stepEnds[i]))
                    .toArray(UnsignedByteArray[]::new);
            append(output, vcfOutFile);
        }
        long t1 = System.nanoTime();
        System.out.println("WindWriter tot: " + Utilities.elapsedNanos(t1-t0));
    }

    public void printPhased(Stage2Haps stage2Haps, int start, int end) {
        GT targGT = stage2Haps.fpd().targGT();
        checkInterval(start, end, targGT.nMarkers());
        long t0 = System.nanoTime();
        int blockSize = 20000;
        int stepSize = 50;
        int[] blockEnds = ends(start, end, blockSize);
        for (int j=1; j<blockEnds.length; ++j) {
            int blockStart = blockEnds[j-1];
            int blockEnd = blockEnds[j];
            GTRec[] recBlock = stage2Haps.toGTRecs(blockStart, blockEnd);
            int[] stepEnds = ends(blockStart, blockEnd, stepSize);
            UnsignedByteArray[] output = IntStream.range(1, stepEnds.length)
                    .parallel()
                    .mapToObj(i -> toByteArray(samples, Arrays.copyOfRange(recBlock,
                            (stepEnds[i-1]-blockStart), (stepEnds[i]-blockStart))))
                    .toArray(UnsignedByteArray[]::new);
            append(output, vcfOutFile);
        }
        long t1 = System.nanoTime();
        System.out.println("WindWriter tot: " + Utilities.elapsedNanos(t1-t0));
    }

    private static void checkInterval(int start, int end, int nMarkers) {
        if (start<0 || end>nMarkers || end<start) {
            throw new IllegalArgumentException("start=" + start + " end=" + end
                    + " nMarkers=" + nMarkers);
        }
    }

    private static int[] ends(int start, int end, int step) {
        IntList starts = new IntList(2 + ((end - start) / step));
        for (int m=start; m<end; m+=step) {
            starts.add(m);
        }
        starts.add(end);
        return starts.toArray();
    }

    private static UnsignedByteArray toByteArray(GT phasedTarg, int start, int end) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (PrintWriter vcfOut=new PrintWriter(
                new BGZIPOutputStream(baos, false))) {
            VcfWriter.appendRecords(phasedTarg, start, end, vcfOut);
        }
        return new UnsignedByteArray(baos);
    }

    private static UnsignedByteArray toByteArray(Samples samples, GTRec[] phasedRecs) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (PrintWriter vcfOut=new PrintWriter(
                new BGZIPOutputStream(baos, false))) {
            VcfWriter.appendRecords(samples, phasedRecs, vcfOut);
        }
        return new UnsignedByteArray(baos);
    }

    private static void append(UnsignedByteArray[] output, File outFile)  {
        boolean append = true;
        try {
            try (OutputStream fos = new BufferedOutputStream(
                    new FileOutputStream(outFile, append))) {
                for (UnsignedByteArray uba : output) {
                    uba.write(fos);
                }
            }
        } catch (IOException e) {
            fileOutputError(outFile, e);
        }
    }

    @Override
    public void close() {
        boolean append = true;
        try {
            try (FileOutputStream fos = new FileOutputStream(vcfOutFile, append);
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    BGZIPOutputStream bgzip = new BGZIPOutputStream(bos, true)) {
                // write empty BGZIP block to bgzip by closing bgzip
            }
        } catch (IOException e) {
            Utilities.exit(e, "Error closing file: " + vcfOutFile);
        }
    }

    private static void fileOutputError(File file, Exception e) {
        Utilities.exit(e, "Error writing to file: " + file);
    }
}