File: PbwtRecPhaser.java

package info (click to toggle)
beagle 250227-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 9,364 kB
  • sloc: java: 17,684; sh: 55; makefile: 11
file content (343 lines) | stat: -rw-r--r-- 12,307 bytes parent folder | download | duplicates (3)
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
/*
 * 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 phase;

import beagleutil.PbwtUpdater;
import java.util.BitSet;
import java.util.Optional;
import java.util.stream.IntStream;
import vcf.GT;
import vcf.RefGT;

/**
 * <p>Class {@code PbwtRecPhaser} partially phases and imputes genotypes
 * using the Positional Burrows-Wheeler transform.</p>
 *
 * <p>Instances of class {@code PbwtRecPhaser} are not thread-safe.</p>
 *
 * <p>Reference: Richard Durbin. (2014) Efficient haplotype matching and storage
 * using the Positional Burrows-Wheeler Transform (PBWT). Bioinformatics
 * 30(9):1266-72.</p>
 *
 * <p>Reference: Olivier Delaneau, Jean-Francois Zagury, Matthew R Robinson,
 * Jonathan Marchini, Emmanouil Dermitzakis. (2019) Accurate, scalable and
 * integrative haplotype estimation. Nature Communications 10(1):5436.</p>
 *
 * @author Brian L. Browning {@code <browning@uw.edu>}
 */
public class PbwtRecPhaser {

    private final GT targGT;
    private final Optional<RefGT> optRef;
    private final int phasedOverlap;
    private final int nTargHaps;
    private final int nTargSamples;
    private final int nHaps;

    private final int[] a;
    private final int[] invA;
    private final PbwtUpdater pbwt;

    /**
     * Creates a new {@code PbwtPhaser} for the specified data.
     * @param fpd the input data for phasing
     * @throws NullPointerException if {@code fpd == null}
     */
    public PbwtRecPhaser(FixedPhaseData fpd) {
        this.targGT = fpd.stage1TargGT();
        this.optRef = fpd.stage1RefGT();
        this.phasedOverlap = fpd.stage1Overlap();
        this.nTargHaps = targGT.nHaps();
        this.nTargSamples = targGT.nSamples();
        this.nHaps = targGT.nHaps()
                + (optRef.isPresent() ? optRef.get().nHaps() : 0);

        this.a = IntStream.range(0, nHaps).toArray();
        this.invA = IntStream.range(0, nHaps).toArray();
        this.pbwt = new PbwtUpdater(nHaps);
    }

    /**
     * Returns the total number of target and reference haplotypes.
     * @return the total number of target and reference haplotypes
     */
    public int nHaps() {
        return nHaps;
    }

    /**
     * Returns the input target genotypes.
     * @return the input target genotypes
     */
    public GT targGT() {
        return targGT;
    }

    /**
     * Copies input target and reference alleles for the marker {@code nextMkr}
     * to the {@code alleles} array and partially phases and imputes the alleles.
     * When the method returns, the {@code alleles} array will contain the
     * partially phased and imputed genotypes at {@code nextMkr}, the
     * {@code true}  elements of the {@code missing} array will identify
     * target samples whose genotype  at marker {@code nextMkr} is missing
     * before partial phasing and imputation, and the {@code true} elements
     * of the {@code unphHet} array will identify samples with a non-missing,
     * unphased heteroygote genotype at marker {@code nextMkr} that remain
     * unphased after partial phasing and imputation.
     *
     * @param currentMkr the marker index corresponding to the specified
     * phased alleles or {@code -1} if the the alleles array does not contain
     * phased alleles
     * @param alleles phased alleles at marker {@code currentMkr} that
     * will be overwritten with partially phased genotypes at marker
     * {@code nextMkr}
     * @param nextMkr the marker whose partially phased genotypes will be
     * stored in the specified {@code alleles} array
     * @param missing an array whose {@code true} elements identify samples
     * with missing genotype at marker {@code nextMkr} before partial
     * phasing and imputation
     * @param unphHet an array whose {@code true} elements identify samples
     * with non-missing, unphased heterozygote genotype at marker
     * {@code nextMkr} that remain unphased after partial phasing
     * @return the CDF for the allele counts at marker {@code nextMkr}
     *
     * @throws IndexOutOfBoundsException if
     * {@code currentMkr < -1 || currentMkr >= this.targGT().nMarkers()}
     * @throws IndexOutOfBoundsException if
     * {@code nextMkr < 0 || nextMkr >= this.targGT().nMarkers()}
     * @throws IndexOutOfBoundsException if
     * {@code (0 <= currentMkr && currentMkr < this.targGT().nMarkers())} and
     * there exists {@code h} such that {@code (0 <= h && h < alleles.length)}
     * and {@code (alleles[h] < 0
     *          || alleles[h] >= this.targGT.marker(currentMkr).nAlleles())}
     * @throws IndexOutOfBoundsException if
     * {@code alleles.length != this.nHaps()}
     * @throws IndexOutOfBoundsException if
     * {@code missing.length != this.nTargGT().nSamples()}
     * @throws IndexOutOfBoundsException if
     * {@code unphHet.length != this.targGT().nSamples()}
     * @throws NullPointerException if any array is {@code null}
     */
    public int[] phase(int currentMkr, int[] alleles, int nextMkr,
            boolean[] missing, boolean[] unphHet) {
        checkArrays(alleles, missing, unphHet);
        if (currentMkr != -1) {
            pbwt.update(alleles, targGT.marker(currentMkr).nAlleles(), a);
        }
        int[] alCnts = setAlleles(nextMkr, alleles, unphHet, missing);
        if (nextMkr>=phasedOverlap) {
            phase(alleles, unphHet);
        }
        return alCnts;
    }

    private void checkArrays(int[] alleles, boolean[] missing, boolean[] unphHet) {
        if (alleles.length != nHaps) {
            throw new IllegalArgumentException(String.valueOf(alleles.length));
        }
        if (missing.length != nTargSamples) {
            throw new IllegalArgumentException(String.valueOf(missing.length));
        }
        if (unphHet.length != nTargSamples) {
            throw new IllegalArgumentException(String.valueOf(unphHet.length));
        }
    }

    private void phase(int[] alleles, boolean[] unphHet) {
        setInvA(a);
        int threshold = 2;
        boolean changeMade = true;
        while (threshold>0 || changeMade==true) {
            changeMade = false;
            for (int s=0; s<nTargSamples; ++s) {
                if (unphHet[s]) {
                    changeMade |= phase(s, threshold, alleles, unphHet, a);
                }
                else {
                    int h1 = s<<1;
                    int h2 = h1 | 0b1;
                    if (alleles[h1] == -1) {
                        alleles[h1] = impute(alleles, unphHet, a, invA[h1]);
                        changeMade |= (alleles[h1]>=0);
                    }
                    if (alleles[h2] == -1) {
                        alleles[h2] = impute(alleles, unphHet, a, invA[h2]);
                        changeMade |= (alleles[h2]>=0);
                    }
                }
            }
            if (changeMade==false) {
                --threshold;
            }
        }
    }

    private boolean phase(int s, int threshold, int[] alleles,
            boolean[] unphHet, int[] a) {
        int h1 = s<<1;
        int h2 = h1 | 0b1;
        int a1 = alleles[h1];
        int a2 = alleles[h2];
        assert a1>=0 && a2>=0 && a1!=a2;
        int cnt1 = phaseCnt(a, alleles, unphHet, invA[h1], a1, a2);
        int cnt2 = phaseCnt(a, alleles, unphHet, invA[h2], a2, a1);
        int cnt = cnt1 + cnt2;
        if (cnt>=threshold) {
            unphHet[s] = false;
            return true;
        }
        if (cnt <= -threshold) {
            alleles[h1] = a2;
            alleles[h2] = a1;
            unphHet[s] = false;
            return true;
        }
        return false;
    }

    private int phaseCnt(int[] a, int[] alleles, boolean[] unphasedHet,
            int ai, int a1, int a2) {
        int phaseCnt = 0;
        if (ai>0) {
            int h = a[ai-1];
            int s = h>>1;
            if (s>=unphasedHet.length || unphasedHet[s]==false) {
                phaseCnt += phaseCnt(alleles[h], a1, a2);
            }
        }
        if ((ai+1)<alleles.length) {
            int h = a[ai+1];
            int s = h>>1;
            if (s>=unphasedHet.length || unphasedHet[s]==false) {
                phaseCnt += phaseCnt(alleles[h], a1, a2);
            }
        }
        return phaseCnt;
    }

    private static int phaseCnt(int adjacentAllele, int a1, int a2) {
        if (adjacentAllele==a1) {
            return 1;
        }
        if (adjacentAllele==a2) {
            return -1;
        }
        return 0;
    }

    private int impute(int[] inputAlleles, boolean[] unphasedHet, int[] a,
            int ai) {
        int prev = -1;
        int next = -1;
        if (ai>0) {
            int h = a[ai-1];
            int s = h>>1;
            if (s>=unphasedHet.length || unphasedHet[s]==false) {
                prev = inputAlleles[h];
            }
        }
        if ((ai+1)<a.length) {
            int h = a[ai+1];
            int s = h>>1;
            if (s>=unphasedHet.length || unphasedHet[s]==false) {
                next = inputAlleles[h];
            }
        }
        if (prev>=0 && (prev==next || next<0)) {
            return prev;
        }
        else if (prev<0 && next>=0) {
            return next;
        }
        return -1;
    }

    private void setInvA(int[] a) {
        for (int j=0; j<a.length; ++j) {
            invA[a[j]] = j;
        }
    }

    private int[] setAlleles(int m, int[] inputAlleles, boolean[] unphHet,
            boolean[] missing) {
        int[] alCnts = new int[targGT.marker(m).nAlleles()];
        setTargAlleles(m, inputAlleles, unphHet, missing, alCnts);
        if (optRef.isPresent()) {
            setRefAlleles(m, inputAlleles, alCnts);
        }
        // convert allele counts to CDF
        for (int j=1; j<alCnts.length; ++j) {
            alCnts[j] += alCnts[j-1];
        }
        return alCnts;
    }

    private void setTargAlleles(int m, int[] inputAlleles, boolean[] unphHet,
            boolean[] missing, int[] alCnts) {
        for (int s=0; s<nTargSamples; ++s) {
            int h1 = s<<1;
            int h2 = h1 | 0b1;
            int a1 = targGT.allele(m, h1);
            int a2 = targGT.allele(m, h2);
            inputAlleles[h1] = a1;
            inputAlleles[h2] = a2;
            unphHet[s] = (m>=phasedOverlap && (a1>=0 && a2>=0 && a1!=a2));
            missing[s] = a1<0 || a2<0;
            if (a1>=0) {
                ++alCnts[a1];
            }
            if (a2>=0) {
                ++alCnts[a2];
            }
        }
    }

    private void setRefAlleles(int m, int[] inputAlleles, int[] alCnts) {
        assert optRef.isPresent();
        RefGT refGT = optRef.get();
        int refHap = 0;
        for (int h1=nTargHaps; h1<nHaps; h1+=2) {
            int h2 = h1 | 0b1;
            int a1 = refGT.allele(m, refHap++);
            int a2 = refGT.allele(m, refHap++);
            inputAlleles[h1] = a1;
            inputAlleles[h2] = a2;
            ++alCnts[a1];
            ++alCnts[a2];
        }
    }

    /**
     * Returns an array of bit sets.
     * @param nBitSets the size of the returned array
     * @param initBitSetCapacity the initial capacity of each bit set in
     * the returned array
     * @return an array of bit sets
     * @throws NegativeArraySizeException if {
     * {@code nBitSets < 0 || initBitSetCapacity < 0}
     */
    public static BitSet[] bitSets(int nBitSets, int initBitSetCapacity) {
        if (nBitSets<0) {
            throw new IllegalArgumentException(String.valueOf(nBitSets));
        }
        return IntStream.range(0, nBitSets)
                .mapToObj(j -> new BitSet(initBitSetCapacity))
                .toArray(BitSet[]::new);
    }
}