File: RefIt.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 (304 lines) | stat: -rw-r--r-- 10,655 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
/*
 * 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 vcf;

import blbutil.BlockLineReader;
import blbutil.FileIt;
import blbutil.Filter;
import blbutil.SampleFileIt;
import bref.SeqCoder3;
import java.io.File;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.function.Function;

/**
 * <p>Class {@code RefIt} represents  an iterator whose {@code next()}
 * method returns an object storing data from a VCF record with
 * phased, non-missing genotypes.
 * </p>
 * <p>Instances of class {@code RefIt} are not thread-safe.
 * </p>
 * <p>Methods of this class will terminate the Java Virtual Machine with
 * an error message if an I/O error or file format error is detected.
 * </p>
 *
 * @author Brian L. Browning {@code <browning@uw.edu>}
 */
public class RefIt implements SampleFileIt<RefGTRec> {

    /**
     * The default number of {@code GTRec} objects that are
     * stored in a buffer.
     */
    private static final int DEFAULT_BUFFER_SIZE = 1<<10;

    private final VcfHeader vcfHeader;
    private final Function<String, RefGTRec> mapper;
    private final Filter<Marker> markerFilter;

    private final BlockLineReader reader;
    private final List<RefGTRec> lowFreqBuffer;
    private final Deque<RefGTRec> recBuffer;
    private final SeqCoder3 seqCoder;
    private final int maxSeqCodedAlleles;
    private final int maxSeqCodingMajorCnt;

    private int lastChrom = -1;

    /**
     * Create and returns a new {@code RefIt} instance from the specified
     * iterator.
     * @param it an iterator that returns lines of a VCF file
     * @return a new {@code RefIt} instance
     * @throws IllegalArgumentException if a format error is detected in a
     * line of a VCF file returned by {@code it}
     * @throws NullPointerException if {@code it == null}
     */
    public static RefIt create(FileIt<String> it) {
        return RefIt.create(it, Filter.acceptAllFilter(),
                Filter.acceptAllFilter(), DEFAULT_BUFFER_SIZE);
    }

    /**
     * Create and returns a new {@code RefIt} instance from the specified
     * objects.
     * @param it an iterator that returns lines of a VCF file
     * @param sampleFilter a sample filter or {@code null}
     * @param markerFilter a marker filter or {@code null}
     * @return a new {@code RefIt} instance
     * @throws IllegalArgumentException if a format error is detected in a
     * line of a VCF file returned by {@code it}
     * @throws IllegalArgumentException if {@code bufferSize < 1}
     * @throws NullPointerException if {@code it == null}
     */
    public static RefIt create(FileIt<String> it, Filter<String> sampleFilter,
            Filter<Marker> markerFilter) {
        return new RefIt(it, sampleFilter, markerFilter, DEFAULT_BUFFER_SIZE);
    }

    /**
     * Create and returns a new {@code RefIt} instance from the specified
     * objects.
     * @param it an iterator that returns lines of a VCF file
     * @param sampleFilter a sample filter or {@code null}
     * @param markerFilter a marker filter or {@code null}
     * @param bufferSize the number of VCF records stored in a buffer
     * @return a new {@code RefIt} instance
     * @throws IllegalArgumentException if a format error is detected in a
     * line of a VCF file returned by {@code it}
     * @throws IllegalArgumentException if {@code bufferSize < 1}
     * @throws NullPointerException if {@code it == null}
     */
    public static RefIt create(FileIt<String> it, Filter<String> sampleFilter,
            Filter<Marker> markerFilter, int bufferSize) {
        return new RefIt(it, sampleFilter, markerFilter, bufferSize);
    }

    private RefIt(FileIt<String> it, Filter<String> sampleFilter,
            Filter<Marker> markerFilter, int blockSize) {
        if (blockSize < 1) {
            throw new IllegalArgumentException(String.valueOf(blockSize));
        }
        if (markerFilter==null) {
            markerFilter = Filter.acceptAllFilter();
        }
        String src = it.file()==null ? "stdin" : it.file().getName();
        String[] head = VcfIt.head(src, it);
        String[] nonDataLines = Arrays.copyOf(head, head.length-1);
        String firstDataLine = head[head.length-1];
        boolean[] isDiploid = VcfHeader.isDiploid(firstDataLine);
        this.vcfHeader = new VcfHeader(src, nonDataLines, isDiploid, sampleFilter);
        this.mapper = (String s) -> {
            return RefGTRec.alleleCodedInstance(new VcfRecGTParser(vcfHeader, s));
        } ;
        this.markerFilter = markerFilter;
        this.seqCoder = new SeqCoder3(vcfHeader.samples());
        this.maxSeqCodedAlleles = Math.min(seqCoder.maxNSeq(), SeqCoder3.MAX_NALLELES);
        this.maxSeqCodingMajorCnt = maxSeqCodingMajorCnt(vcfHeader.samples());

        this.lowFreqBuffer = new ArrayList<>();
        this.recBuffer = new ArrayDeque<>(blockSize);

        int nBlocks = 1;
        this.reader = BlockLineReader.create(it, blockSize, nBlocks);
        fillRecBuffer(firstDataLine);
    }

    private int maxSeqCodingMajorCnt(Samples samples) {
        int nHaps = samples.size() << 1;
        return (int) Math.floor(nHaps*SeqCoder3.COMPRESS_FREQ_THRESHOLD - 1);
    }

    private void fillRecBuffer() {
        fillRecBuffer(null);
    }

    private void fillRecBuffer(String firstDataLine) {
        assert recBuffer.isEmpty();
        while (recBuffer.isEmpty()) {
            String[] lines = reader.next();
            if (firstDataLine!=null) {
                lines = combine(firstDataLine, lines);
                firstDataLine = null;
            }
            if (lines==BlockLineReader.SENTINAL) {
                flushCompressedRecords();
                return;
            }
            else {
                RefGTRec[] recs = parseLines(lines);
                for (int j=0; j<recs.length; ++j) {
                    RefGTRec rec = recs[j];
                    int chrom = rec.marker().chromIndex();
                    if (lastChrom == -1) {
                        lastChrom = chrom;
                    }
                    if (chrom!=lastChrom || lowFreqBuffer.size()==Integer.MAX_VALUE) {
                        flushCompressedRecords();
                        lastChrom = chrom;
                    }
                    if (applySeqCoding(rec)==false) {
                        lowFreqBuffer.add(rec);
                    }
                    else {
                        boolean success = seqCoder.add(rec);
                        if (success == false) {
                            flushCompressedRecords();
                            success = seqCoder.add(rec);
                            assert success;
                        }
                        lowFreqBuffer.add(null);
                    }
                }
            }
        }
    }

    private String[] combine(String firstDataLine, String[] lines) {
        String[] modLines = new String[lines.length + 1];
        modLines[0] = firstDataLine;
        System.arraycopy(lines, 0, modLines, 1, lines.length);
        return modLines;
    }

    private RefGTRec[] parseLines(String[] lines) {
        return Arrays.stream(lines)
                .parallel()
                .map(mapper)
                .filter(e -> markerFilter.accept(e.marker()))
                .toArray(RefGTRec[]::new);
    }

    private void flushCompressedRecords() {
        List<RefGTRec> list = seqCoder.getCompressedList();
        int index = 0;
        for (int j=0, n=lowFreqBuffer.size(); j<n; ++j) {
            GTRec ve = lowFreqBuffer.get(j);
            if (ve==null) {
                lowFreqBuffer.set(j, list.get(index++));
            }
        }
        recBuffer.addAll(lowFreqBuffer);
        lowFreqBuffer.clear();
    }

    @Override
    public void close() {
        reader.close();
        recBuffer.clear();
        lowFreqBuffer.clear();
    }

    /**
     * Returns {@code true} if the iteration has more elements, and returns
     * {@code false} otherwise.
     * @return {@code true} if the iteration has more elements
     */
    @Override
    public boolean hasNext() {
        return !recBuffer.isEmpty();
    }

    /**
     * Returns the next element in the iteration.
     * @return the next element in the iteration
     * @throws NoSuchElementException if the iteration has no more elements
     */
    @Override
    public RefGTRec next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        RefGTRec first = recBuffer.removeFirst();
        if (recBuffer.isEmpty()) {
            fillRecBuffer();
        }
        return first;
    }

    /**
     * The {@code remove} method is not supported by this iterator.
     * @throws UnsupportedOperationException if this method is invoked
     */
    @Override
    public void remove() {
        throw new UnsupportedOperationException(this.getClass().toString());
    }

    @Override
    public File file() {
        return reader.file();
    }

    @Override
    public Samples samples() {
        return vcfHeader.samples();
    }

    @Override
    public String toString() {
        File file = reader.file();
        StringBuilder sb = new StringBuilder(80);
        sb.append(this.getClass().toString());
        sb.append(" : ");
        sb.append(file==null ? "stdin" : file.toString());
        return sb.toString();
    }

    private boolean applySeqCoding(RefGTRec rec) {
        assert rec.isAlleleCoded();
        if (rec.marker().nAlleles() > maxSeqCodedAlleles) {
            return false;
        }
        int nHaps = rec.size();
        int majAllele = rec.majorAllele();
        int majCnt = nHaps;
        for (int a=0, n=rec.marker().nAlleles(); a<n; ++a) {
            if (a!=majAllele) {
                majCnt -= rec.alleleCount(a);
            }
        }
        return majCnt<=maxSeqCodingMajorCnt;
    }
}