File: PbwtPhaser.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 (256 lines) | stat: -rw-r--r-- 9,710 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
/*
 * 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 blbutil.DoubleArray;
import blbutil.Utilities;
import ints.IntList;
import ints.WrappedIntArray;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.stream.IntStream;
import vcf.GT;

/**
 * <p>Class {@code PbwtPhaser} phases input genotype data and imputes
 * missing alleles using the Positional Burrows-Wheeler Transform (PBWT)</p>
 *
 * <p>Instances of class {@code PbwtPhaser} 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 PbwtPhaser {

    private final int start;
    private final int end;
    private final FwdPbwtPhaser fwdPbwt;

    private PbwtPhaser(FixedPhaseData fpd, int start, int end, long seed) {
        if (start<0 || end>fpd.targGT().nMarkers() || start>=end) {
            throw new IllegalArgumentException(String.valueOf(start));
        }
        this.start = start;
        this.end = end;
        this.fwdPbwt = new FwdPbwtPhaser(fpd, start, end, seed);
    }

    /**
     * Returns an initial phasing for first-stage markers in the target samples.
     * @param fpd the input data for phasing
     * @param seed seed for random number generation
     * @return an initial genotype phasing for the first-stage markers in the
     * target samples
     * @throws NullPointerException if {@code fpd == null}
     */
    public static AtomicReferenceArray<SamplePhase> initPhase(FixedPhaseData fpd,
            long seed) {
        PbwtPhaser[] ppa = pbwtPhasers(fpd, seed);
        int nSamples = fpd.stage1TargGT().nSamples();
        int nThreads = fpd.par().nthreads();
        int maxStepSize = 128;
        int stepSize = Math.min((nSamples + nThreads - 1)/nThreads, maxStepSize);
        int nSteps = (nSamples + (stepSize-1)) / stepSize;
        AtomicReferenceArray<SamplePhase> phase = new AtomicReferenceArray<>(nSamples);
        IntStream.range(0, nSteps)
                .parallel()
                .boxed()
                .forEach(step -> setSamplePhase(fpd, ppa, phase, step, stepSize));
        return phase;
    }

    private static void setSamplePhase(FixedPhaseData fpd, PbwtPhaser[] ppa,
            AtomicReferenceArray<SamplePhase> phase, int step, int stepSize) {
        GT gt = fpd.stage1TargGT();
        int sStart = step*stepSize;
        int sEnd = Math.min(sStart + stepSize, gt.nSamples());
        Indices[] indices = indices(fpd, sStart, sEnd);

        int overlapEnd = 0;
        int[][] haps = new int[(sEnd-sStart)<<1][gt.nMarkers()];
        ppa[0].copyHaps(haps, indices, overlapEnd, sStart, sEnd);
        for (int j=1; j<ppa.length; ++j) {
            overlapEnd = ppa[j-1].end;
            ppa[j].copyHaps(haps, indices, overlapEnd, sStart, sEnd);
        }

        for (int s=sStart; s<sEnd; ++s) {
            int ss = s - sStart;
            int hh1 = ss<<1;
            int hh2 = hh1 | 0b1;
            phase.set(s, new SamplePhase(s, gt.markers(), fpd.stage1Map().genPos(),
                haps[hh1], haps[hh2], indices[ss].hetIndices, indices[ss].missIndices));
        }
    }

    private void copyHaps(int[][] haps, Indices[] indices, int overlapEnd,
            int sStart, int sEnd) {
        int copyStart = (this.start + overlapEnd)>>>1;
        int[][] alignedHaps = haps.clone();
        if (this.start>0) {
            for (int s=sStart; s<sEnd; ++s) {
                int ss = s - sStart;
                int hh1 = ss<<1;
                int hh2 = hh1 | 0b1;
                int alignHet = alignmentHet(indices[ss].hetIndices,
                        start, copyStart, overlapEnd);
                if (alignHet>=0 && switchHapLabels(s, haps[hh1], haps[hh2], alignHet)) {
                    alignedHaps[hh1] = haps[hh2];
                    alignedHaps[hh2] = haps[hh1];
                }
            }
        }
        for (int m=copyStart; m<end; ++m) {
            for (int s=sStart; s<sEnd; ++s) {
                int h1 = s<<1;
                int h2 = h1 | 0b1;
                int hh1 = (s - sStart)<<1;
                int hh2 = hh1 | 0b1;
                alignedHaps[hh1][m] = fwdPbwt.allele(m, h1);
                alignedHaps[hh2][m] = fwdPbwt.allele(m, h2);
            }
        }
    }

    /* Returns -1 if no alignment het exists */
    private static int alignmentHet(WrappedIntArray hetList, int start,
            int copyStart, int overlapEnd) {
        if (hetList.size()==0) {
            return -1;
        }
        int index = insPt(hetList, copyStart);
        if (index==hetList.size() || (hetList.get(index)>=overlapEnd && index>0)) {
            index -= 1;
        }
        int het = hetList.get(index);
        return (start<=het && het<overlapEnd) ? het : -1;
    }

    private boolean switchHapLabels(int sample, int[] hap1, int[] hap2, int alignHet) {
        int h1 = sample<<1;
        int h2 = h1 | 0b1;
        int a1 = hap1[alignHet];
        int a2 = hap2[alignHet];
        int b1 = fwdPbwt.allele(alignHet, h1);
        int b2 = fwdPbwt.allele(alignHet, h2);
        return a1==b2 && a2==b1;
    }

    private static int insPt(WrappedIntArray list, int value) {
        int index = list.binarySearch(value);
        return (index<0) ? -index-1 : index;
    }

    private static PbwtPhaser[] pbwtPhasers(FixedPhaseData fpd, long seed) {
        int[][] windows = hiFreqWindows(fpd);
        return IntStream.range(0, windows.length)
                .parallel()
                .mapToObj(j -> new PbwtPhaser(fpd, windows[j][0], windows[j][1],
                        seed + j))
                .toArray(PbwtPhaser[]::new);
    }

    private static int[][] hiFreqWindows(FixedPhaseData fpd) {
        DoubleArray genPos = fpd.stage1Map().genPos();
        int nMarkers = genPos.size();
        int nThreads = fpd.par().nthreads();
        double totalCM = genPos.get(genPos.size()-1) - genPos.get(0);
        double overlapCM = 0.5;
        double advanceCM = Math.max(4*overlapCM, (totalCM/nThreads));
        List<int[]> windowList = new ArrayList<>(nThreads);
        int from = 0;
        int to = to(genPos, genPos.get(from) + advanceCM);
        while (to<nMarkers) {
            windowList.add(new int[] {from, to});
            from = from(genPos, genPos.get(to) - overlapCM);
            to = to(genPos, genPos.get(to) + advanceCM);
        }
        assert to==nMarkers;
        windowList.add(new int[] {from, to});
        return windowList.toArray(new int[0][]);
    }

    private static int from(DoubleArray genPos, double pos) {
        int insPt = genPos.binarySearch(pos);
        return insPt<0 ? -insPt-1 : insPt;
    }

    private static int to(DoubleArray genPos, double pos) {
        int insPt = genPos.binarySearch(pos);
        return insPt<0 ? -insPt-1 : (insPt+1);  //insPt>=0 implies insPt<genpPos.size()
    }

    private static Indices[] indices(FixedPhaseData fpd, int sStart, int sEnd) {
        GT gt = fpd.stage1TargGT();
        int overlap = fpd.stage1Overlap();
        int nMarkers = gt.nMarkers();
        int len = sEnd - sStart;
        IntList[] missIndices = intLists(len);
        IntList[] hetIndices = intLists(len);
        boolean[] notFirstHet = new boolean[len];
        for (int m=0; m<nMarkers; ++m) {
            for (int s=sStart; s<sEnd; ++s) {
                int ss = s-sStart;
                int hap1 = s << 1;
                int a1 = gt.allele(m, hap1);
                int a2 = gt.allele(m, hap1 | 0b1);
                if (a1<0 || a2<0) {
                    missIndices[ss].add(m);
                }
                else if (a1!=a2) {
                    if (m>=overlap && notFirstHet[ss]) {
                        hetIndices[ss].add(m);
                    }
                    else {
                        notFirstHet[ss] = true;
                    }
                }
            }
        }
        return IntStream.range(0, len)
                .mapToObj(j -> new Indices(missIndices[j], hetIndices[j]))
                .toArray(Indices[]::new);

    }

    private static IntList[] intLists(int length) {
        return IntStream.range(0, length)
                .parallel()
                .mapToObj(j -> new IntList())
                .toArray(IntList[]::new);
    }

    private static class Indices {
        public final WrappedIntArray missIndices;
        public final WrappedIntArray hetIndices;

        public Indices(IntList missIndices, IntList hetIndices) {
            this.missIndices = new WrappedIntArray(missIndices);
            this.hetIndices = new WrappedIntArray(hetIndices);
        }
    }
}