File: SeqCoder3.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 (328 lines) | stat: -rw-r--r-- 11,641 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
/*
 * 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 bref;

import ints.IntArray;
import ints.IntList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import vcf.Marker;
import vcf.RefGTRec;
import vcf.Samples;
import vcf.SeqCodedRefGTRec;

/**
 * <p>Class {@code SeqCoder3} compresses a sequence of allele-coded
 * {@code RefGTRec} objects.  The class is designed for use with bref v3 format.
 * Compression is performed by storing the list of distinct allele sequences
 * and the allele sequence carried by each haplotype.
 * </p>
 * <p>Class {@code SeqCoder3} is not thread-safe.
 * </p>
 *
 * @author Brian L. Browning {@code <browning@uw.edu>}
 */
public class SeqCoder3 {

    /**
     * The maximum number of alleles are that permitted in order
     * for the {@code add()} method to return {@code true}
     */
    public static final int MAX_NALLELES = 255;

    /**
     * The major allele frequency threshold for allele coding.
     * Sequence coding should only be applied if the major allele frequency
     * less than or equal to this threshold.
     */
    public static final float COMPRESS_FREQ_THRESHOLD = 0.995f;

    private final Samples samples;
    private final int maxNSeq;
    private final List<RefGTRec> recs;
    private final int[] hap2Seq;
    private final IntList seq2Cnt;  // for processiing allele-coded markers
    private final List<IntList> seq2AlleleMap;

    /**
     * Constructs a new {@code SeqCoder3} for the specified samples.
     * @param samples the list of samples whose data will be compressed
     * @throws NullPointerException if {@code samples == null}
     */
    public SeqCoder3(Samples samples) {
        this(samples, defaultMaxNSeq(samples.size()));
    }

    /**
     * Constructs a new {@code SeqCoder3} for the specified samples.
     * @param samples the list of samples whose data will be compressed
     * @param maxNSeq the maximum number of distinct allele sequences
     * permitted if the {@code add()} method returns {@code true}
     * @throws NullPointerException if {@code samples == null}
     * @throws IllegalArgumentException
     * {@code maxNSeq < 0 || maxNSeq >= Chracter.MAX_VALUE}
     */
    public SeqCoder3(Samples samples, int maxNSeq) {
        if (maxNSeq < 0 || maxNSeq >= Character.MAX_VALUE) {
            throw new IllegalArgumentException(String.valueOf(maxNSeq));
        }
        this.samples = samples;
        this.maxNSeq = maxNSeq;
        this.recs = new ArrayList<>(100);
        this.hap2Seq = new int[2*samples.size()];
        this.seq2Cnt = new IntList(3*maxNSeq/2 + 1);
        this.seq2AlleleMap = new ArrayList<>(maxNSeq + 1);
        initialize();
    }

    /**
     * Returns the default maximum number of sequences for the specified
     * number of samples.  The default value is equal to
     * {@code (int) Math.min((long) Math.pow(2, 2*Math.log10(size) + 1),
 Character.MAX_VALUE)}
     * @param nSamples the number of samples
     * @return the default maximum number of sequences for the specified
     * number of samples
     * @throws IllegalArgumentException if {@code size < 1}
     */
    public static int defaultMaxNSeq(int nSamples) {
        if (nSamples < 1) {
            throw new IllegalArgumentException(String.valueOf(nSamples));
        }
        if (nSamples==1) {
            return 3;
        }
        else {
            double exponent = 2*Math.log10(nSamples) + 1;
            long maxNSeq = (long) Math.floor(Math.pow(2.0, exponent));
            if (maxNSeq > Character.MAX_VALUE) {
                return Character.MAX_VALUE;
            }
            else {
                return (int) maxNSeq;
            }
        }
    }

    /**
     * Returns the list of samples whose phased genotype data will be compressed.
     * @return the list of samples whose phased genotype data will be compressed
     */
    public Samples samples() {
        return samples;
    }

    /**
     * Returns the number of compressed {@code RefGTRec} objects.
     * @return the number of compressed {@code RefGTRec} objects
     */
    public int nRecs() {
        return recs.size();
    }

    /**
     * Returns the maximum number of distinct allele sequences.
     * @return the maximum number of distinct allele sequences
     */
    public int maxNSeq() {
        return maxNSeq;
    }

    /**
     * Attempts to add the specified {@code RefGTRec} object to the list of
     * compressed {@code RefGTRec} objects, and returns {@code true}
     * if the {@code RefGTRec} object was added.
     *
     * @param rec reference genotypes for a marker
     * @return {@code true} if the specified {@code RefGTRec} object was
     * added to the list of compressed markers
     *
     * @throws IllegalArgumentException if
     * {@code em.samples().equals(this.samples()) == false}
     * @throws IllegalArgumentException if
     * {@code rec.isAlleleCoded() == false}
     * @throws NullPointerException if {@code rec == null}
     */
    public boolean add(RefGTRec rec) {
        if (rec.samples().equals(samples)==false) {
            throw new IllegalArgumentException("inconsistent samples");
        }
        if (rec.isAlleleCoded()==false) {
            throw new IllegalArgumentException(rec.getClass().toString());
        }
        boolean success = setAlleleMap(rec);
        if (success) {
            recs.add(rec);
            int majorAllele = rec.majorAllele();
            for (int a=0, n=rec.marker().nAlleles(); a<n; ++a) {
                if (a!=majorAllele) {
                    int nCopies = rec.alleleCount(a);
                    for (int c=0; c<nCopies; ++c) {
                        int h = rec.hapIndex(a, c);
                        int oldSeq = hap2Seq[h];
                        IntList list = seq2AlleleMap.get(oldSeq);
                        int index=0;
                        while (index<list.size() && list.get(index)!=a) {
                            index+=2;
                        }
                        int newSeq = list.get(index+1);
                        if (newSeq != oldSeq) {
                            while (newSeq >= seq2Cnt.size()) {
                                seq2Cnt.add(0);
                            }
                            hap2Seq[h] = newSeq;
                            seq2Cnt.decrementAndGet(oldSeq);
                            seq2Cnt.incrementAndGet(newSeq);
                        }
                    }
                }
            }
        }
        assert seq2Cnt.size()==seq2AlleleMap.size();
        return success;
    }

    private void clearAlleleMap() {
        for (int j=0, n=seq2AlleleMap.size(); j<n; ++j) {
            seq2AlleleMap.get(j).clear();
        }
    }

    private boolean setAlleleMap(RefGTRec rec) {
        assert seq2Cnt.size()==seq2AlleleMap.size();
        int nStartSeq = seq2Cnt.size();
        int[] seq2NonMajorCnt = new int[nStartSeq];
        clearAlleleMap();
        int nAlleles = rec.marker().nAlleles();
        int majorAllele = rec.majorAllele();
        for (int a=0; a<nAlleles; ++a) {
            if (a!=majorAllele) {
                int nCopies = rec.alleleCount(a);
                for (int c=0; c<nCopies; ++c) {
                    int h = rec.hapIndex(a, c);
                    int seq = hap2Seq[h];
                    ++seq2NonMajorCnt[seq];
                    IntList list = seq2AlleleMap.get(seq);
                    if (list.isEmpty()) {
                        list.add(a);
                        list.add(seq);
                    }
                    else {
                        int index=0;
                        while (index<list.size() && list.get(index)!=a) {
                            index+=2;
                        }
                        if (index==list.size()) {
                            list.add(a);
                            list.add(seq2AlleleMap.size());
                            seq2AlleleMap.add(new IntList(4));
                        }
                    }
                }
            }
        }
        addMajorAllele(seq2NonMajorCnt, majorAllele);
        if (seq2AlleleMap.size() >= maxNSeq) {
            seq2AlleleMap.subList(nStartSeq, seq2AlleleMap.size()).clear();
            return false;
        }
        else {
            return true;
        }
    }

    private void addMajorAllele(int[] seq2NonMajorCnt, int majorAllele) {
        for (int s=0; s<seq2NonMajorCnt.length; ++s) {
            if (seq2NonMajorCnt[s] < seq2Cnt.get(s)) {
                IntList list = seq2AlleleMap.get(s);
                if (list.isEmpty()) {
                    list.add(majorAllele);
                    list.add(s);
                }
                else {
                    // assign major allele the existing sequence index
                    list.add(list.get(0));
                    assert list.get(1)==s;
                    list.add(seq2AlleleMap.size());
                    list.set(0, majorAllele);
                    seq2AlleleMap.add(new IntList(4));
                }
            }
        }
    }

    /**
     * Returns and clears the stored list of compressed {@code RefGTRec}
     * objects.
     *
     * @return the list of compressed {@code RefGTRec} objects
     */
    public List<RefGTRec> getCompressedList() {
        if (recs.isEmpty()) {
            return Collections.emptyList();
        }
        List<RefGTRec> list = new ArrayList<>(recs.size());
        int[] seq2Hap = seq2Hap();  // can this be created when adding records?
        IntArray hap2seq =  IntArray.packedCreate(hap2Seq, seq2Hap.length);
        for (int j=0, n=recs.size(); j<n; ++j) {
            RefGTRec rec = recs.get(j);
            Marker m = rec.marker();
            IntArray seq2allele = seq2Allele(rec, seq2Hap);
            list.add(new SeqCodedRefGTRec(m, samples, hap2seq, seq2allele));
        }
        initialize();
        return list;
    }

    private int[] seq2Hap() {
        int[] seqToHap = new int[seq2AlleleMap.size()];
        Arrays.fill(seqToHap, -1);
        for (int h=0; h<hap2Seq.length; ++h) {
            int seq = hap2Seq[h];
            if (seqToHap[seq] == -1) {
                seqToHap[seq] = h;
            }
        }
        return seqToHap;
    }

    private IntArray seq2Allele(RefGTRec rec, int[] seq2Hap) {
        int[] seq2Allele = new int[seq2Hap.length];
        for (int j=0; j<seq2Allele.length; ++j) {
            seq2Allele[j] = rec.get(seq2Hap[j]);
        }
        return IntArray.packedCreate(seq2Allele, rec.marker().nAlleles());
    }

    /**
     * Clears the list of compressed {@code RefGTRec} objects.
     */
    private void initialize() {
        recs.clear();
        seq2Cnt.clear();
        seq2AlleleMap.clear();

        // initialize with empty sequence (seq index is 0)
        Arrays.fill(hap2Seq, 0);
        seq2Cnt.add(hap2Seq.length);
        seq2AlleleMap.add(new IntList(4));
    }
}