forked from richarddurbin/pbwt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pbwtImpute.c
1702 lines (1525 loc) · 66.4 KB
/
pbwtImpute.c
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* File: pbwtImpute.c
* Author: Richard Durbin ([email protected])
* Copyright (C) Genome Research Limited, 2013-
*-------------------------------------------------------------------
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*-------------------------------------------------------------------
* Description: phasing and imputation functions in pbwt package,
plus utilities to intentionally corrupt data
* Exported functions:
* HISTORY:
* Last edited: Apr 28 16:33 2017 (rd)
* * Sep 22 23:10 2014 (rd): move to 64 bit arrays
* Created: Thu Apr 4 12:02:56 2013 (rd)
*-------------------------------------------------------------------
*/
#include "pbwt.h"
static void genotypeComparePbwt (PBWT *p, PBWT *q) ; /* forward declaration */
/************************* IMPUTATION AND PHASING *************************/
#include <math.h>
static double fBound[] = {0.1, 0.2, 0.3, 0.5, 0.7, 1, 2, 3, 5, 7, 10, 20, 30, 50, 70, 90, 100.01} ;
void imputeExplore (PBWT *p, int test)
{
int i, j, k, M = p->M, N = p->N, ff ;
uchar *y ;
double xbar, ybar, tot, r2 ;
double f ;
typedef struct {
long n00, n01 ; /* neither neighbour is 1, truth is 0 or 1 */
long n10a, n10b, n11a, n11b ;/* one neighbour is 1; a if d is lower for the 0 neighbour */
long n20, n21 ; /* both neighbours are 1 */
double fsum ;
} TestStat ;
TestStat *testStat = mycalloc (17, TestStat), *t ;
typedef long Counts[4] ;
Array dHist = arrayCreate (1000, Counts) ;
Counts cSimple, cCond0, cCond1 ;
int *n0 = myalloc (M, int), *n1 = myalloc (M, int) ;
uchar *x = myalloc (M, uchar) ;
static long c0[17][5], c1[17][5] ;
pbwtBuildReverse (p) ;
PbwtCursor *u = pbwtCursorCreate (p, TRUE, TRUE) ;
PbwtCursor *uz = pbwtCursorCreate (p, FALSE, FALSE) ;
for (i = 0 ; i < 4 ; ++i) cSimple[i] = cCond0[i] = cCond1[i] = 0 ;
for (k = 0 ; k < N ; ++k)
{ pbwtCursorReadBackwards (uz) ;
if (isCheck)
{ for (i = 0 ; i < M ; ++i)
x[u->a[i]] = u->y[i] ;
for (i = 0 ; i < M ; ++i)
if (x[uz->a[i]] != uz->y[i])
fprintf (logFile, "forward-backward mismatch at k %d i %d\n", k, i) ;
}
if (k > 0.2*N && k < 0.8*N) /* ignore ends */
{ f = (M - u->c) / (double)M ; for (ff = 0 ; f*100 > fBound[ff] ; ++ff) ;
t = &testStat[ff] ;
t->fsum += f ;
memset (n0, 0, M*sizeof(int)) ; memset (n1, 0, M*sizeof(int)) ;
for (i = 1 ; i < M-1 ; ++i)
{ if (u->y[i-1] && u->y[i+1])
if (u->y[i]) ++t->n21 ; else ++t->n20 ;
else if (!u->y[i-1] && !u->y[i+1])
if (u->y[i]) ++t->n01 ; else ++t->n00 ;
else if ((!u->y[i-1] && u->d[i] < u->d[i+1]) ||
(!u->y[i+1] && u->d[i+1] < u->d[i]))
if (u->y[i]) ++t->n11a ; else ++t->n10a ;
else
if (u->y[i]) ++t->n11b ; else ++t->n10b ;
++(array(dHist, u->d[i]/100, Counts)[u->y[i-1] + 2*u->y[i]]) ;
++cSimple[u->y[i-1] + 2*u->y[i]] ;
if (u->y[i+1])
++cCond1[u->y[i-1] + 2*u->y[i]] ;
else
++cCond0[u->y[i-1] + 2*u->y[i]] ;
n0[u->a[i]] += 2 - (u->y[i-1] + u->y[i+1]) ;
n1[u->a[i]] += u->y[i-1] + u->y[i+1] ;
n0[uz->a[i]] += 2 - (uz->y[i-1] + uz->y[i+1]) ;
n1[uz->a[i]] += uz->y[i-1] + uz->y[i+1] ;
x[u->a[i]] = u->y[i] ;
}
for (i = 0 ; i < M ; ++i)
if (n0[i] + n1[i] == 4) /* it wasn't at the end either forwards or backwards */
{ if (x[i]) ++c1[ff][n1[i]] ; else ++c0[ff][n1[i]] ; }
}
pbwtCursorForwardsReadAD (u, k) ;
}
if (test == 1)
for (j = 0 ; j < 17 ; ++j)
{ t = &testStat[j] ;
tot = t->n00 + t->n01 + t->n10a + t->n11a + t->n10b + t->n11b + t->n20 + t->n21 ;
printf ("%-5.1f\t%-7.3f\t00,01\t%ld\t%ld\t10a,11a\t%ld\t%ld\t10b,11b\t%ld\t%ld\t20,21\t%ld\t%ld",
fBound[j], tot ? ((double)testStat[j].fsum) / tot : 0.0,
t->n00, t->n01, t->n10a, t->n11a, t->n10b, t->n11b, t->n20, t->n21) ;
if (tot)
{ xbar = (t->n10b + t->n11b + t->n20 + t->n21)/tot ;
ybar = (t->n01 + t->n11a + t->n11b + t->n21)/tot ;
r2 = ((t->n21 + t->n11b)/tot - xbar*ybar)/sqrt((xbar - xbar*xbar)*(ybar - ybar*ybar)) ;
printf ("\tx,y,r2\t%.4f\t%.4f\t%.4f\n", xbar, ybar, r2) ;
}
else
putchar ('\n') ;
}
else if (test == 2)
for (j = 0 ; j < arrayMax(dHist) ; ++j)
{ long *c ; c = arr(dHist, j, Counts) ;
printf ("%d\t%ld\t%ld\t%ld\t%ld", j, c[0], c[1], c[2], c[3]) ;
if (c[0] + c[2]) printf ("\t%.3f", c[0]/(double)(c[0]+c[2])) ; else printf ("\t0") ;
if (c[1] + c[3]) printf ("\t%.3f", c[3]/(double)(c[1]+c[3])) ; else printf ("\t0") ;
putchar ('\n') ;
}
else if (test == 3)
{ printf ("%.3f %.3f\t", cSimple[0]/(double)(cSimple[0]+cSimple[2]), cSimple[3]/(double)(cSimple[1]+cSimple[3])) ;
printf ("%.3f %.3f\t", cCond0[0]/(double)(cCond0[0]+cCond0[2]), cCond0[3]/(double)(cCond0[1]+cCond0[3])) ;
printf ("%.3f %.3f\n", cCond1[0]/(double)(cCond1[0]+cCond1[2]), cCond1[3]/(double)(cCond1[1]+cCond1[3])) ;
}
else if (test == 4)
for (j = 0 ; j < 17 ; ++j)
{ printf ("%-5.1f", fBound[j]) ;
tot = 0 ;
for (i = 0 ; i < 5 ; ++i) { tot += c0[j][i] + c1[j][i] ; }
printf ("\t%-7.3f", tot ? ((double) testStat[j].fsum) / tot : 0.0) ;
xbar = 0 ; r2 = 0 ;
for (i = 0 ; i < 5 ; ++i)
{ long sum = c0[j][i] + c1[j][i] ;
printf ("\t%ld ", sum) ;
if (sum) printf (" %.3f", c1[j][i]/(double)sum) ; else printf (" 00000") ;
xbar += c1[j][i] ;
if (i == 3 || i == 4) r2 += c1[j][i] ; if (i ==2) r2 += 0.5*c1[j][i] ;
tot += sum ;
}
ybar = c0[j][4] + c1[j][4] + c0[j][3] + c1[j][3] + 0.5*(c0[j][2] + c1[j][2]) ;
if (tot)
{ xbar /= tot ;
ybar /= tot ;
r2 = (r2/tot - xbar*ybar)/sqrt((xbar - xbar*xbar)*(ybar - ybar*ybar)) ;
printf ("\tx,y,r2\t%.4f\t%.4f\t%.4f\n", xbar, ybar, r2) ;
}
else
putchar ('\n') ;
}
pbwtCursorDestroy (u) ;
pbwtCursorDestroy (uz) ;
}
/****************** phasing ****************/
static void phaseCompare (PBWT *p, PBWT *q)
{
int i, k ;
int M = p->M, N = p->N ;
PbwtCursor *up = pbwtCursorCreate (p, TRUE, TRUE) ;
PbwtCursor *uq = pbwtCursorCreate (q, TRUE, TRUE) ;
int *xp = myalloc (M, int), *xq = myalloc (M, int) ;
int *isFirst = myalloc (M, int), *isFlipped = myalloc (M, int) ;
int *lastFlip = mycalloc (M, int), *kHet = mycalloc (M, int) ;
int nSwitch = 0, nHet = 0, nSwitch1 = 0, nSwitch5 = 0 ;
double mFac = 2.0/M ;
int *nSwitchSample = mycalloc (M, int), *nSwitchSite = mycalloc (N, int) ;
if (p->M != q->M || p->N != q->N) die ("size incompatibility in phaseCompare") ;
if (p->M %2) die ("phaseCompare requires that M %d is even", M) ;
memset (isFirst, 1, M*sizeof(int)) ; /* I know this is not 1 - anything non-zero will do */
for (k = 0 ; k < N ; k++)
{ for (i = 0 ; i < M ; ++i)
{ xp[up->a[i]] = up->y[i] ;
xq[uq->a[i]] = uq->y[i] ;
}
for (i = 0 ; i < M ; i += 2)
{ if (xp[i] + xp[i+1] == 1)
{ ++nHet ; ++kHet[i] ;
if (isFirst[i])
{ isFirst[i] = 0 ;
isFlipped[i] = (xp[i] == xq[i+1]) ? 1 : 0 ;
}
else if (xp[i] != xq[i+isFlipped[i]])
{ ++nSwitch ; ++nSwitchSample[i/2] ; ++nSwitchSite[k] ;
if (kHet[i] - lastFlip[i] > 1) ++nSwitch1 ;
if (kHet[i] - lastFlip[i] > 5) ++nSwitch5 ;
isFlipped[i] = 1 - isFlipped[i] ;
lastFlip[i] = kHet[i] ;
}
}
if (isCheck && (xp[i]+xp[i+1] != xq[i]+xq[i+1]))
{ fprintf (logFile, "phaseCompare mismatch k %d sequence %d\np", k, i) ;
uchar **pHaps = pbwtHaplotypes(p), **qHaps = pbwtHaplotypes(q) ;
int kk ;
for (kk = 0 ; kk < 40 ; ++kk)
fprintf (logFile, " %d", pHaps[i][kk] + pHaps[i+1][kk]) ;
fprintf (logFile, "\nq") ;
for (kk = 0 ; kk < 40 ; ++kk)
fprintf (logFile, " %d", qHaps[i][kk] + qHaps[i+1][kk]) ;
fprintf (logFile, "\n") ;
die ("phaseCompare mismatch: k %d, i %d, xp %d|%d, xq %d|%d",
k, i, xp[i], xp[i+1], xq[i], xq[i+1]) ;
}
}
pbwtCursorForwardsRead (up) ;
pbwtCursorForwardsRead (uq) ;
}
fprintf (logFile, "%.1f switches per sample, %.3f per het, %.1f nSwitch1, %.1f nSwitch5\n",
mFac*nSwitch, nSwitch/(double)nHet, mFac*nSwitch1, mFac*nSwitch5) ;
if (isStats)
{ for (i = 0 ; i < M/2 ; ++i)
{ printf ("SAMPLE-SWITCH\t%d\t%d", i, nSwitchSample[i]) ;
if (p->samples)
printf ("\t%s", sampleName(sample (p, 2*i))) ;
putchar ('\n') ;
}
for (k = 0 ; k < N ; ++k)
{ printf ("SITE-SWITCH\t%d\t%d", k, nSwitchSite[k]) ;
if (p->sites)
{ Site *s = arrp(p->sites,k,Site) ;
printf ("\t%s\t%d\t%s", p->chrom, s->x, dictName(variationDict, s->varD)) ;
}
putchar ('\n') ;
}
}
pbwtCursorDestroy (up) ; pbwtCursorDestroy (uq) ;
free (xp) ; free (xq) ; free (isFirst) ; free (isFlipped) ;
free (nSwitchSample) ; free (nSwitchSite) ;
}
/****************************************************************/
static double *scoreBit ;
static double *logisticCache ;
static void phaseInit (int N)
{ int i ;
double z ;
scoreBit = myalloc (N+1, double) ;
for (i = 0 ; i <= N ; ++i) scoreBit[i] = log (i + 1.0) ; /* 1 is simple version */
logisticCache = myalloc (100000, double) ;
for (i = 0 ; i < 100000 ; ++i)
{ z = exp (-i * 0.0001) ; logisticCache[i] = 1.0 / (1.0 + z) ; }
}
static inline double score0 (PbwtCursor *u, double *xp, int i)
{
double s = 0.0 ;
int ubi = u->b[i] ;
if (ubi > 0) s += xp[u->a[ubi-1]] ;
if (ubi < u->M-1) s += xp[u->a[ubi+1]] ;
return s ;
}
static inline double score1 (PbwtCursor *u, double *xp, int i, int k)
{
double s = 0 ;
int ubi = u->b[i] ;
if (ubi > 0) s += xp[u->a[ubi-1]] * scoreBit[(k+1)-u->d[ubi]] ;
if (ubi < u->M-1) s += xp[u->a[ubi+1]] * scoreBit[(k+1)-u->d[ubi+1]] ;
return s ;
}
static inline double logistic (double x)
{ int i = x * 10000 ;
if (i < -99999) return 1.0 - logisticCache[99999] ;
else if (i < 0) return 1.0 - logisticCache[-i] ;
else if (i < 100000) return logisticCache[i] ;
else return logisticCache[99999] ;
}
/******* phase() is phaseOld() rewritten with new API and method 3 only ******/
PBWT *phaseSweep (PBWT *p, PBWT *ref, BOOL isStart, PBWT *r, int nSparse)
{
int i, j, k, kk, kr = 0 ;
int M = p->M, N = p->N ;
if (ref && p->M > ref->M) die ("phaseSweep requires ref->M >= p->M") ;
/* initialisation */
PbwtCursor *up = pbwtCursorCreate (p, TRUE, isStart) ;
PBWT *q = pbwtCreate (M, N) ; /* new pbwt */
PbwtCursor *ur, *uref ;
if (ref) uref = pbwtCursorCreate (ref, TRUE, isStart) ;
if (r)
{ ur = pbwtCursorCreate (r, TRUE, FALSE) ;
memcpy (ur->b, r->aRend, M*sizeof(int)) ; /* recover stored locations */
// for (i = 0 ; i < M ; ++i) ur->b[ur->a[i]] = i ; /* store inverse a in b */
memcpy (q->aFstart, r->aFend, M*sizeof(int)) ; /* prime uq with final ur */
}
PbwtCursor *uq = pbwtCursorCreate (q, TRUE, TRUE) ;
for (i = 0 ; i < M ; ++i) uq->b[uq->a[i]] = i ; /* store inverse a in b */
PbwtCursor **uqq = myalloc (nSparse, PbwtCursor*) ;
for (kk = 0 ; kk < nSparse ; ++kk)
{ uqq[kk] = pbwtNakedCursorCreate (M, 0) ;
for (i = 0 ; i < M ; ++i) uqq[kk]->b[uqq[kk]->a[i]] = i ;
}
/* now loop through p phasing into q */
uchar *x = myalloc (M, uchar) ; /* actual haplotypes in original order, from p */
double *xp = myalloc(M, double) ; /* 2*p(x=1)-1, so 1 if x=1, -1 if x=0, 0 if unknown */
for (k = 0 ; k < N ; k++)
{ if (!isStart) pbwtCursorReadBackwards (up) ;
for (i = 0 ; i < M ; ++i) x[up->a[i]] = up->y[i] ; /* build x from up->y */
if (isStart) pbwtCursorForwardsRead (up) ;
for (i = 0 ; i < M ; ++i) xp[i] = x[i] ? 1.0 : -1.0 ;
int n2 = 0 ;
for (i = 0 ; i < M ; i += 2) /* go through x in pairs */
if (x[i] != x[i+1]) { ++n2 ; xp[i] = xp[i+1] = 0.0 ; } /* a het */
double s, thresh = ref ? 0.5 : 2*(nSparse + (r?2:1)) + 0.5 ;
while (n2 && thresh > 1.0)
{ int n2Old = n2 ; n2 = 0 ;
for (i = 0 ; i < M ; i += 2) /* loop over genotype pairs in original order */
if (!xp[i]) /* a het to phase */
{ s = score0 (uq, xp, i) - score0 (uq, xp, i+1) ;
if (r) s += score0 (ur, xp,i) - score0 (ur, xp, i+1) ;
for (kk = 0 ; kk < nSparse ; ++kk)
s += score0 (uqq[kk], xp, i) - score0 (uqq[kk], xp, i+1) ;
if (s > thresh) { xp[i] = 1 ; xp[i+1] = -1 ; }
else if (s < -thresh) { xp[i] = -1 ; xp[i+1] = 1 ; }
else ++n2 ;
}
if (n2 == n2Old) { thresh -= 1.0 ; n2Old = M+1 ; }
}
if (n2) /* some unresolved values - phase using length, forwards only for now */
for (i = 0 ; i < M ; i += 2)
if (!xp[i])
{ s = score1 (uq, xp, i, k) - score1 (uq, xp, i+1, k) ;
for (kk = 0 ; kk < nSparse ; ++kk)
s += score1 (uqq[kk], xp, i, k/nSparse) - score1 (uqq[kk], xp, i+1, k/nSparse) ;
if (s > 0) { xp[i] = 1 ; xp[i+1] = -1 ; }
else { xp[i] = -1 ; xp[i+1] = 1 ; }
}
for (i = 0 ; i < M ; ++i) x[i] = (xp[i] > 0.0) ? 1 : 0 ;
for (i = 0 ; i < M ; ++i) uq->y[i] = x[uq->a[i]] ;
pbwtCursorWriteForwardsAD (uq, k) ;
for (i = 0 ; i < M ; ++i) uq->b[uq->a[i]] = i ;
kk = k % nSparse ; /* which of the sparse pbwts to update this time */
for (i = 0 ; i < M ; ++i) uqq[kk]->y[i] = x[uqq[kk]->a[i]] ;
pbwtCursorForwardsAD (uqq[kk], k/nSparse) ;
for (i = 0 ; i < M ; ++i) uqq[kk]->b[uqq[kk]->a[i]] = i ;
if (r)
{ pbwtCursorReadBackwards (ur) ;
for (i = 0 ; i < M ; ++i) ur->b[ur->a[i]] = i ;
}
}
pbwtCursorToAFend (uq, q) ;
/* cache uq->b in aRend so we can retrieve from reverse on forwards pass */
q->aRend = myalloc (q->M, int) ;
for (i = 0 ; i < q->M ; ++i) q->aRend[i] = uq->b[i] ;
/* clean up memory allocated */
free (x) ; free (xp) ;
pbwtCursorDestroy (up) ; pbwtCursorDestroy (uq) ; if (r) pbwtCursorDestroy (ur) ;
for (kk = 0 ; kk < nSparse ; ++kk) pbwtCursorDestroy (uqq[kk]) ; free (uqq) ;
return q ;
}
PBWT *phase (PBWT *p, int nSparse) /* return rephased p */
{
if (p->M % 2) die ("phase requires that M = %d is even", p->M) ;
if (nSparse < 2) nSparse = 2 ;
phaseInit (p->N) ; /* sets up some lookup tables */
if (!p->aFend) pbwtBuildReverse (p) ; /* needed for old PBWT format data */
PBWT *r = phaseSweep (p, 0, FALSE, 0, 2) ; /* always reverse sweep wth nSparse 2 */
if (isCheck) /* flip p->zz round into p->yz and compare to r */
{ Array yzStore = p->yz ; p->yz = p->zz ;
int *aFstartStore = p->aFstart ; p->aFstart = p->aRstart ;
fprintf (logFile, "After reverse pass: ") ; phaseCompare (p, r) ;
p->yz = yzStore ; p->aFstart = aFstartStore ;
}
PBWT *q = phaseSweep (p, 0, TRUE, r, nSparse) ;
/* compare new phasing to original and report switch rates */
fprintf (logFile, "After forward pass: ") ; phaseCompare (p, q) ;
pbwtDestroy (p) ;
return q ;
}
/******* reference phase using same strategy as phase **********/
PBWT *referencePhase0 (PBWT *p, PBWT *pRef)
{
int nSparse = 2 ;
phaseInit (pRef->N) ;
if (!pRef->aFend) pbwtBuildReverse (pRef) ; /* needed for oldPBWT format data */
PBWT *r = phaseSweep (p, pRef, FALSE, 0, 2) ; /* always reverse with nSparse 2 */
if (isCheck) /* flip p->zz round into p->yz and compare to r */
{ if (!p->zz) pbwtBuildReverse (p) ;
Array yzStore = p->yz ; p->yz = p->zz ;
int *aFstartStore = p->aFstart ; p->aFstart = p->aRstart ;
fprintf (logFile, "After reverse pass: ") ; phaseCompare (p, r) ;
p->yz = yzStore ; p->aFstart = aFstartStore ;
}
PBWT *q = phaseSweep (p, pRef, TRUE, r, nSparse) ;
return q ;
}
/******* phase a new pbwt against the existing one as a reference *******/
typedef struct { int jRef ; int start ; int end ; } MatchSegment ;
/* matches are semi-open [start,end) so length is end-start */
static Array *maxMatch = 0 ; /* of MatchSegment */
static void reportMatch (int iq, int jRef, int start, int end)
{
MatchSegment *ms = arrayp (maxMatch[iq], arrayMax(maxMatch[iq]), MatchSegment) ;
ms->jRef = jRef ; ms->start = start ; ms->end = end ;
}
/**************** referencePhase4 *************************************************/
/* This one keeps track for each position j in the reference pbwt of the (normalised)
probability of generating the data given that the phasing so far sorts at position j,
and also of the other haplotype sort position given that phasing. We keep backtrack
pointers for each j, and prune them back so that only ones connected to the current
values at k are kept live.
As currently implemented this calculates the full likelihood, but gives the most likely
path contributing to that. We could adapt it to full Viterbi, or sampling mode.
*/
/* within this, try different ways to keep the score and extend */
#define EXTEND4
/******** type declarations ********/
typedef unsigned int TraceBackIndex ; /* index into traceBackHeap */
/* #define TRACEBACK_DEBUG */
typedef struct
{ TraceBackIndex back : 28 ; /* index into traceBackHeap for cell at previous het site */
unsigned int value : 1 ; /* 0 or 1 */
unsigned int count : 3 ; /* how many cells at next het site point back to this: 0,1 or 2 */
#ifdef TRACEBACK_DEBUG
int j, k ;
#endif
} TraceBackCell ; /* pack this so it fits into a 4-byte word */
typedef struct {
int j1 ; /* the pair index of j0, which is the index of the cell */
TraceBackIndex back ;
float s ;
#ifdef EXTEND0
float sBest ;
#endif
#ifdef EXTEND1
int dplus0, dminus0, dmax0, dplus1, dminus1, dmax1 ;
#endif
#ifdef EXTEND2
int j0min, j0max, j1min, j1max ;
#endif
#if defined(EXTEND3) || defined(EXTEND4)
int dplus0, dminus0, dplus1, dminus1 ;
#endif
} PhaseCell ;
/********** first the package to manage trace back space efficiently **********/
static Array traceBackHeap = 0 ; /* of TraceBackCell */
static Array traceBackFreeStack = 0 ; /* of TraceBackIndex */
#define traceBackCell(tb) arrp(traceBackHeap, (tb), TraceBackCell)
TraceBackIndex traceBackCreate (TraceBackIndex back, unsigned int value, int j, int k)
{ TraceBackIndex tb ;
TraceBackCell *tc ;
if (!isCheck && arrayMax (traceBackFreeStack))
{ tb = arr (traceBackFreeStack, --arrayMax(traceBackFreeStack), TraceBackIndex) ;
tc = arrp (traceBackHeap, tb, TraceBackCell) ;
}
else
{ tb = arrayMax(traceBackHeap) ;
tc = arrayp (traceBackHeap, tb, TraceBackCell) ;
}
tc->back = back ; tc->value = value ; tc->count = 1 ;
#ifdef TRACEBACK_DEBUG
tc->j = j ; tc->k = k ;
#endif
/* if (isCheck) printf ("traceBackCreate %d at k %d j %d back %d value %d\n", tb, k, j, back, value) ; */
return tb ;
}
inline static void traceBackPrune (TraceBackIndex tb, int k, int j)
{ TraceBackCell *tc = traceBackCell(tb) ;
while (tb && --tc->count == 0) /* i.e. that was the last active link for that cell */
{ array(traceBackFreeStack, arrayMax(traceBackFreeStack), int) = tb ;
/* if (isCheck) printf ("traceBackDestroy %d at k %d j %d\n", tb, k, j) ; */
tb = tc->back ;
tc = traceBackCell(tb) ;
}
}
void traceBackInitialise (void)
{ traceBackHeap = arrayReCreate (traceBackHeap, 4096, TraceBackCell) ;
traceBackFreeStack = arrayReCreate (traceBackFreeStack, 2048, TraceBackIndex) ;
traceBackCreate (0, 0, 0, 0) ; /* make empty first element, so that later back == 0 only at end*/
}
#ifdef TRACEBACK_DEBUG
void traceBackReport (TraceBackIndex tb)
{ while (tb)
{ TraceBackCell *tc = traceBackCell(tb) ;
printf (" %dk%dj%d", tc->value, tc->k, tc->j) ;
tb = tc->back ;
}
}
void traceBackCheck (int jq, int k, PhaseCell *pc, int M) /* beware - very costly */
{
int j ;
int* zCount = mycalloc (arrayMax(traceBackHeap), int) ;
for (j = 0 ; j < arrayMax(traceBackHeap) ; ++j)
{ TraceBackCell *tc = traceBackCell(j) ;
if (tc->count) ++zCount[tc->back] ;
}
for (j = 0 ; j <= M ; ++j) if (pc[j].s) ++zCount[pc[j].back] ;
for (j = 1 ; j < arrayMax(traceBackHeap) ; ++j)
if (zCount[j] && traceBackCell(j)->count != zCount[j])
{ warn ("bad count jq %d, k %d, j %d, zCount[j] %d, traceBackCell(j)->count %d",
jq, k, j, zCount[j], traceBackCell(j)->count) ;
int jj ;
for (jj = 0 ; jj <= M ; ++jj)
if (pc[jj].s && pc[jj].back == j) warn (" back[%d] == %d", jj, j) ;
for (jj = 0 ; jj < arrayMax(traceBackHeap) ; ++jj)
{ TraceBackCell *tc = traceBackCell(jj) ;
if (tc->count && tc->back == j)
warn (" tc[%d]->back %d, tc[%d]->count %d", jj, j, jj, tc->count) ;
}
}
free (zCount) ;
}
#endif // TRACEBACK_DEBUG
/********** next the calculation of how likely to extend from j with value x **********/
#ifdef EXTEND0
/* first version tries to consider all copying haplotypes with weights proportional to shared length */
/* we pre-calculate contributions from above and below in extendPrepare(), caching in extendScore0/1 */
static char *extendMethodText = "EXTEND0" ;
static long *extendScore0 = 0, *extendScore1 = 0 ;
static int extendScoreSize = 0 ;
static Array extendStack = 0 ;
typedef struct {
int d ;
int n0, n1 ; /* number of y[j] == 0/1 so far with this effective dd */
int sum0, sum1 ; /* sum of dd*n up to this element */
} ExtendStruct ;
static ExtendStruct *extendUpdate (int dd, int x)
{
int i, n0 = 0, n1 = 0 ; /* n0 and n1 are # 0s,1s with d > dd */
ExtendStruct *ex ;
if (isCheck && dd < 0) die ("dd %d < 0 in extendUpdate", dd) ;
/* find highest place in stack less than or equal to dd */
for (i = arrayMax(extendStack) ; i-- ; )
{ ex = arrp(extendStack, i, ExtendStruct) ;
if (dd >= ex->d) break ;
n0 += ex->n0 ; n1 += ex->n1 ;
}
arrayMax(extendStack) = i+1 ;
if (dd > ex->d) /* make a new exStack element */
{ ex = arrayp(extendStack, i+1, ExtendStruct) ;
ex->d = dd ; ex->n0 = n0 ; ex->n1 = n1 ;
ex->sum0 = ex[-1].sum0 + dd*n0 ; ex->sum1 = ex[-1].sum1 + dd*n1 ;
}
else /* add these things from longer dd to current element */
{ ex->n0 += n0 ; ex->sum0 += dd*n0 ; ex->n1 += n1 ; ex->sum1 += dd*n1 ; }
/* now add the current element on */
if (x) { ++ex->n1 ; ex->sum1 += dd ; } else { ++ex->n0 ; ex->sum0 += dd ; }
return ex ;
}
static void extendPrepare (PbwtCursor *u, int k)
{
int j ;
ExtendStruct *ex ;
if (extendScoreSize != u->M)
{ if (extendScore0) { free (extendScore0) ; free (extendScore1) ; }
extendScore0 = mycalloc (u->M+1, long) ; extendScore1 = mycalloc (u->M+1, long) ;
extendScoreSize = u->M ;
}
/* first run through samples j == 1..M and add scores from top to j */
extendStack = arrayReCreate (extendStack, 512, ExtendStruct) ;
ex = arrayp (extendStack, 0, ExtendStruct) ;
ex->d = 0 ; ex->n0 = 0 ; ex->n1 = 0 ; ex->sum0 = 1 ; ex->sum1 = 1 ;
extendScore0[0] = 0 ; extendScore1[0] = 0 ;
for (j = 0 ; j++ < u->M ; )
{ extendScore0[j] = ex->sum0 ; extendScore1[j] = ex->sum1 ;
int bit = (j < u->M || u->d[j-1] > u->d[j]) ? u->d[j-1] : u->d[j] ;
if (u->y[j-1]) extendScore1[j] += bit ; else extendScore0[j] += bit ;
if (j < u->M) ex = extendUpdate (k - u->d[j], u->y[j-1]) ;
}
/* then reverse j == M-1..0 and add on scores from bottom to j */
extendStack = arrayReCreate (extendStack, 512, ExtendStruct) ;
ex = arrayp (extendStack, 0, ExtendStruct) ;
ex->d = 0 ; ex->n0 = 0 ; ex->n1 = 0 ; ex->sum0 = 1 ; ex->sum1 = 1 ;
for (j = u->M ; j-- > 0 ; )
{ extendScore0[j] += ex->sum0 ; extendScore1[j] += ex->sum1 ;
int bit = (j || u->d[j+1] > u->d[j]) ? u->d[j+1] : u->d[j] ;
if (u->y[j]) extendScore1[j] += bit ; else extendScore0[j] += bit ;
if (j) ex = extendUpdate (k - u->d[j], u->y[j]) ;
}
}
/* To be correct I should calculate the upper score up until but not including the
preceding j-1, and the lower score back until but not including the succeeding j,
because I don't know here the match lengths to the flanking j-1,j. I can know them
during the dynamic programming, because I know the backtrace. But this means
calculating and storing the dplus, dminus values induced by the backtrace, which adds
considerable complexity. Above I assume that they are the greater of d[j] and d[j-1]
(for j-1) and d[j] and d[j+1] (for j), which is a lower bound, taking care not to
query out of bounds at the top and bottom.
*/
static inline double extendScore (int j, int x)
{
double p = extendScore1[j] / (double) (extendScore0[j] + extendScore1[j]) ;
return (x ? p : 1-p) ;
}
static int phaseExtend (int x0, int x1, PbwtCursor *uRef, int j0,
PhaseCell *pcOld, PhaseCell *pcNew, int k)
/* returns the number of new back pointers created */
/* change at XXX for sampling or YYY for Viterbi */
/* this code uses extend structure above via extendScore, but did not perform well */
/* so replace with new phaseExtend() below, I hope */
{
PhaseCell *old = &pcOld[j0] ;
PhaseCell *new = &pcNew[pbwtCursorMap (uRef, x0, j0)] ;
int j1New = pbwtCursorMap (uRef, x1, old->j1) ;
double sBit = old->s * extendScore (j0, x0) * extendScore (old->j1, x1) ;
if (isCheck && k == 51 && (j0 == 1389 || pbwtCursorMap(uRef,x0,j0) == 1370))
printf ("at k %d extend j0 %d j1 %d s %.3g with x %d %d to j0New %d j1New %d sbit %.3g\n",
k, j0, old->j1, old->s, x0, x1, pbwtCursorMap (uRef, x0, j0), j1New, sBit) ;
if (!new->s) /* this is the first j to map here */
{ new->s = sBit ; new->sBest = sBit ;
new->j1 = j1New ;
new->back = (x0 == x1) ? old->back : traceBackCreate (old->back, x0, j0, k) ;
return 1 ;
}
/* XXX for sampling calculate chance to pick this j rather than
previous here */
if (sBit > new->sBest) /* this is better than previous j that mapped here */
{ new->s = sBit ; /* YYY originally +=, for Viterbi change to = */
new->sBest = sBit ;
new->j1 = j1New ;
if (traceBackCell(new->back)->back == old->back) /* be careful - edge case! */
{ traceBackCell(new->back)->value = x0 ; return 0 ; }
else
{ traceBackPrune (new->back, k, j0) ;
new->back = (x0 == x1) ? old->back : traceBackCreate (old->back, x0, j0, k) ;
return 1 ;
}
}
/* new->s += sBit ; /* include if not Viterbi */
return 0 ;
}
#endif // EXTEND0
#ifdef EXTEND1 /* alternate version minimises number of recombinations */
/* in this version pc->s is -1 minus the number of recombinations */
static char *extendMethodText = "EXTEND1" ;
static void extendPrepare (PbwtCursor *u, int k) {}
static inline int phaseExtend (int x0, int x1, PbwtCursor *uRef, int j0,
PhaseCell *pcOld, PhaseCell *pcNew, int k)
/* returns the number of new back pointers created */
{
PhaseCell *old = &pcOld[j0] ;
int j0New = pbwtCursorMap (uRef, x0, j0) ;
PhaseCell *new = &pcNew[j0New] ;
if (new->s && new->s > old->s) return 0 ; /* quick check whether this is possible */
PhaseCell temp ;
temp.s = old->s ;
temp.dplus0 = pbwtCursorMapDplus (uRef, x0, j0, old->dplus0) ;
temp.dminus0 = pbwtCursorMapDminus (uRef, x0, j0, old->dminus0) ;
if (temp.dplus0 > old->dmax0 && temp.dminus0 > old->dmax0) /* need a recombination */
{ --temp.s ; temp.dmax0 = k ; } else temp.dmax0 = old->dmax0 ;
temp.j1 = pbwtCursorMap (uRef, x1, old->j1) ;
temp.dplus1 = pbwtCursorMapDplus (uRef, x1, old->j1, old->dplus1) ;
temp.dminus1 = pbwtCursorMapDminus (uRef, x1, old->j1, old->dminus1) ;
if (temp.dplus1 > old->dmax1 && temp.dminus1 > old->dmax1) /* need a recombination */
{ --temp.s ; temp.dmax1 = k ; } else temp.dmax1 = old->dmax1 ;
if (!new->s) /* this is the first j0 to map here */
{ *new = temp ;
new->back = (x0 == x1) ? old->back : traceBackCreate (old->back, x0, j0, k) ;
return 1 ;
}
else if (temp.s > new->s) /* this is better than previous j that mapped here */
{ TraceBackIndex oldNewBack = new->back ;
*new = temp ; /* originally +=, for Viterbi change to = */
if (traceBackCell(oldNewBack)->back == old->back) /* be careful - edge case! */
{ new->back = oldNewBack ; traceBackCell(new->back)->value = x0 ; return 0 ; }
else
{ traceBackPrune (oldNewBack, k, j0) ;
new->back = (x0 == x1) ? old->back : traceBackCreate (old->back, x0, j0, k) ;
return 1 ;
}
}
else
return 0 ;
}
#endif // EXTEND1
#ifdef EXTEND2 /* alternate version of EXTEND1 that minimises number of recombinations */
/* in this version we track the prefix interval (jmin,jmax) for matches to j0, j1 */
static char *extendMethodText = "EXTEND2" ;
static void extendPrepare (PbwtCursor *u, int k) {}
static inline int phaseExtend (int x0, int x1, PbwtCursor *uRef, int j0,
PhaseCell *pcOld, PhaseCell *pcNew, int k)
/* returns the number of new back pointers created */
{
PhaseCell *old = &pcOld[j0] ;
int j0New = pbwtCursorMap (uRef, x0, j0) ;
PhaseCell *new = &pcNew[j0New] ;
if (new->s && new->s > old->s) return 0 ; /* quick check whether this is possible */
PhaseCell temp ;
temp.s = old->s ;
temp.j0min = pbwtCursorMap (uRef, x0, old->j0min) ;
temp.j0max = pbwtCursorMap (uRef, x0, old->j0max) ;
if (temp.j0min == temp.j0max) /* need a recombination */
{ --temp.s ; temp.j0min = x0 ? uRef->c-1 : 0 ; temp.j0max = x0 ? uRef->M : uRef->c ; }
temp.j1 = pbwtCursorMap (uRef, x1, old->j1) ;
temp.j1min = pbwtCursorMap (uRef, x1, old->j1min) ;
temp.j1max = pbwtCursorMap (uRef, x1, old->j1max) ;
if (temp.j1min == temp.j1max) /* need a recombination */
{ --temp.s ; temp.j1min = x1 ? uRef->c-1 : 0 ; temp.j1max = x1 ? uRef->M : uRef->c ; }
if (!new->s) /* this is the first j0 to map here */
{ *new = temp ;
new->back = (x0 == x1) ? old->back : traceBackCreate (old->back, x0, j0, k) ;
return 1 ;
}
else if (temp.s > new->s) /* this is better than previous j that mapped here */
{ TraceBackIndex oldNewBack = new->back ;
*new = temp ; /* originally +=, for Viterbi change to = */
if (traceBackCell(oldNewBack)->back == old->back) /* be careful - edge case! */
{ new->back = oldNewBack ; traceBackCell(new->back)->value = x0 ; return 0 ; }
else
{ traceBackPrune (oldNewBack, k, j0) ;
new->back = (x0 == x1) ? old->back : traceBackCreate (old->back, x0, j0, k) ;
return 1 ;
}
}
else
return 0 ;
}
#endif // EXTEND2
#ifdef EXTEND3 /* like EXTEND1,2 but maximises sum of lengths of maximal matches*/
/* in this version pc->s is 1 + sum of lengths of maximal matches */
static char *extendMethodText = "EXTEND3" ;
static void extendPrepare (PbwtCursor *u, int k) {}
static inline int phaseExtend (int x0, int x1, PbwtCursor *uRef, int j0,
PhaseCell *pcOld, PhaseCell *pcNew, int k)
/* returns the number of new back pointers created */
{
PhaseCell *old = &pcOld[j0] ;
int j0New = pbwtCursorMap (uRef, x0, j0) ;
PhaseCell *new = &pcNew[j0New] ;
PhaseCell temp ; /* build the potential new in this */
temp.s = old->s ;
temp.dplus0 = pbwtCursorMapDplus (uRef, x0, j0, old->dplus0) ;
temp.dminus0 = pbwtCursorMapDminus (uRef, x0, j0, old->dminus0) ;
int j ;
if (old->dplus0 < old->dminus0 && old->dplus0 < temp.dplus0)
for (j = j0 ; j < uRef->M ; )
{ temp.s += (k - old->dplus0) ;
if (uRef->d[++j] > old->dplus0) break ;
}
else if (old->dminus0 < old->dplus0 && old->dminus0 < temp.dminus0)
for (j = j0 ; j < uRef->M ; )
{ temp.s += (k - old->dminus0) ;
if (uRef->d[--j] > old->dminus0) break ;
}
temp.j1 = pbwtCursorMap (uRef, x1, old->j1) ;
temp.dplus1 = pbwtCursorMapDplus (uRef, x1, old->j1, old->dplus1) ;
temp.dminus1 = pbwtCursorMapDminus (uRef, x1, old->j1, old->dminus1) ;
if (old->dplus1 < old->dminus1 && old->dplus1 < temp.dplus1)
for (j = j0 ; j < uRef->M ; )
{ temp.s += (k - old->dplus1) ;
if (uRef->d[++j] > old->dplus1) break ;
}
else if (old->dminus1 < old->dplus1 && old->dminus1 < temp.dminus1)
for (j = j0 ; j < uRef->M ; )
{ temp.s += (k - old->dminus1) ;
if (uRef->d[--j] > old->dminus1) break ;
}
if (!new->s) /* this is the first j0 to map here */
{ *new = temp ;
new->back = (x0 == x1) ? old->back : traceBackCreate (old->back, x0, j0, k) ;
return 1 ;
}
else if (temp.s > new->s) /* this is better than previous j that mapped here */
{ TraceBackIndex oldNewBack = new->back ;
*new = temp ; /* originally +=, for Viterbi change to = */
if (traceBackCell(oldNewBack)->back == old->back) /* be careful - edge case! */
{ new->back = oldNewBack ; traceBackCell(new->back)->value = x0 ; return 0 ; }
else
{ traceBackPrune (oldNewBack, k, j0) ;
new->back = (x0 == x1) ? old->back : traceBackCreate (old->back, x0, j0, k) ;
return 1 ;
}
}
else
return 0 ;
}
#endif // EXTEND3
#ifdef EXTEND4 /* based on diff from neighbours based on -log generative model */
/* in this version pc->s is -1 - sum of lengths of mismatched neighbours */
static char *extendMethodText = "EXTEND4" ;
static void extendPrepare (PbwtCursor *u, int k) {}
static inline int phaseExtend (int x0, int x1, PbwtCursor *uRef, int j0,
PhaseCell *pcOld, PhaseCell *pcNew, int k)
/* returns the number of new back pointers created */
{
PhaseCell *old = &pcOld[j0] ;
int j0New = pbwtCursorMap (uRef, x0, j0) ;
PhaseCell *new = &pcNew[j0New] ;
PhaseCell temp ; /* build the potential new in this */
temp.s = old->s ;
temp.dplus0 = pbwtCursorMapDplus (uRef, x0, j0, old->dplus0) ;
temp.dminus0 = pbwtCursorMapDminus (uRef, x0, j0, old->dminus0) ;
float dS = 0 ;
if (j0)
{ if (x0 == uRef->y[j0-1]) dS += (k-old->dminus0) ; else dS -= (k-old->dminus0) ; }
if (j0 < uRef->M)
{ if (x0 == uRef->y[j0]) dS += (k-old->dplus0) ; else dS -= (k-old->dplus0) ; }
if (dS < 0) temp.s += dS ;
temp.j1 = pbwtCursorMap (uRef, x1, old->j1) ;
temp.dplus1 = pbwtCursorMapDplus (uRef, x1, old->j1, old->dplus1) ;
temp.dminus1 = pbwtCursorMapDminus (uRef, x1, old->j1, old->dminus1) ;
dS = 0 ;
if (old->j1)
{ if (x1 == uRef->y[old->j1-1]) dS += (k-old->dminus1) ; else dS -= (k-old->dminus1) ; }
if (old->j1 < uRef->M)
{ if (x1 == uRef->y[old->j1]) dS += (k-old->dplus1) ; else dS -= (k-old->dplus1) ; }
if (dS < 0) temp.s += dS ;
if (!new->s) /* this is the first j0 to map here */
{ *new = temp ;
new->back = (x0 == x1) ? old->back : traceBackCreate (old->back, x0, j0, k) ;
return 1 ;
}
else if (temp.s > new->s) /* this is better than previous j that mapped here */
{ TraceBackIndex oldNewBack = new->back ;
*new = temp ; /* originally +=, for Viterbi change to = */
if (traceBackCell(oldNewBack)->back == old->back) /* be careful - edge case! */
{ new->back = oldNewBack ; traceBackCell(new->back)->value = x0 ; return 0 ; }
else
{ traceBackPrune (oldNewBack, k, j0) ;
new->back = (x0 == x1) ? old->back : traceBackCreate (old->back, x0, j0, k) ;
return 1 ;
}
}
else
return 0 ;
}
#endif // EXTEND4
/********** finally the main function ********/
static PBWT *referencePhase4 (PBWT *pOld, PBWT *pRef)
{
fprintf (logFile, "Reference phase with extension method %s\n", extendMethodText) ;
int i, j, jq, k ;
PbwtCursor *uOld = pbwtCursorCreate (pOld, TRUE, TRUE) ;
uchar *xOld = myalloc (pOld->M, uchar) ;
PbwtCursor *uRef = pbwtCursorCreate (pRef, TRUE, TRUE) ;
traceBackInitialise() ;
PhaseCell **pcOld = myalloc (pOld->M, PhaseCell*) ;
PhaseCell **pcNew = myalloc (pOld->M, PhaseCell*) ;
for (jq = 0 ; jq < pOld->M ; jq += 2)
{ pcOld[jq] = mycalloc (pRef->M+1, PhaseCell) ;
pcOld[jq][0].back = 0 ;
#if defined(EXTEND0) || defined(EXTEND3)
pcOld[jq][0].s = 1.0 ;
#endif
#if defined(EXTEND1) || defined(EXTEND2) || defined(EXTEND4)
pcOld[jq][0].s = -1.0 ;
#endif
pcNew[jq] = myalloc (pRef->M+1, PhaseCell) ;
}
/* some declarations for checks */
int *checkLiveSum = mycalloc (pOld->M, int) ;
double *checkLikeSum = mycalloc (pOld->M, double) ;
int *checkHets = mycalloc (pOld->M, int) ;
/* here is the main loop through the sites */
for (k = 0 ; k < pOld->N ; ++k)
{ for (j = 0 ; j < pOld->M ; ++j) xOld[uOld->a[j]] = uOld->y[j] ;
#ifdef QUERY0_IS_REF0
if (isCheck)
{ PhaseCell *pc ; TraceBackCell *tc ;
int a0, a1 ;
for (j = 0 ; j < pRef->M ; ++j)
{ if (uRef->a[j] == 0) a0 = j ;
if (uRef->a[j] == 1) a1 = j ;
}
PhaseCell *pc0 = &pcOld[0][a0], *pc1 = &pcOld[0][a1] ;
printf ("at k %4d x0 %d x1 %d", k, xOld[0], xOld[1]) ;
printf ("\n 0 j %4d s %10.3g", a0, pc0->s) ; traceBackReport (pc0->back) ;
printf ("\n 1 j %4d s %10.3g", a1, pc1->s) ; traceBackReport (pc1->back) ;
for (j = 0, pc = pcOld[0] ; j < pRef->M ; ++j, ++pc)
if (pc->s > pc0->s && pc->s > pc1->s)
{ printf ("\n j %4d s %10.3g", j, pc->s) ; traceBackReport (pc->back) ;
die ("done") ;
}
putchar ('\n') ;
}
#endif
if (isCheck && !(k % 100))
{ printf ("check k %d", k) ; int nS = 0 ; PhaseCell *pc ;
for (j = 0, pc = pcOld[0] ; j < pRef->M ; ++j, ++pc) if (pc->s) ++nS ;
printf (" nS %d\n", nS) ;
}
extendPrepare (uRef, k) ;
pbwtCursorCalculateU (uRef) ; /* before pbwtCursorMap()s in phaseExtend() */
/* update each query sample in turn */
for (jq = 0 ; jq < pOld->M ; jq +=2)
{ bzero (pcNew[jq], (pRef->M+1)*sizeof(PhaseCell)) ; /* clear pcNew */
int x0 = xOld[jq], x1 = xOld[jq+1] ;
if (x0 != x1) checkHets[jq]++ ;
for (j = 0 ; j <= pRef->M ; ++j)
if (pcOld[jq][j].s)
{ int countBack ;
if (x0 == x1)
countBack = phaseExtend (x0, x1, uRef, j, pcOld[jq], pcNew[jq], k) ;
else
countBack = phaseExtend (x0, x1, uRef, j, pcOld[jq], pcNew[jq], k) +
phaseExtend (x1, x0, uRef, j, pcOld[jq], pcNew[jq], k) ;
/* now resolve traceback counts on pcOld[jq][j].back */
if (countBack == 0)
traceBackPrune (pcOld[jq][j].back, k, j) ;
else if (countBack == 2 && pcOld[jq][j].back) /* don't increment tb cell 0 */
traceBackCell(pcOld[jq][j].back)->count++ ;
/* else leave count at default of 1 */
++checkLiveSum[jq] ;
}
/* now update pcOld from pcNew to be ready for next column */
double sum = 0 ; for (j = 0 ; j <= pRef->M ; ++j) sum += pcNew[jq][j].s ;
if (!sum) die ("sum is 0 at k %d jq %d", k, jq) ;
checkLikeSum[jq] += log (sum) ;
for (j = 0 ; j <= pRef->M ; ++j)
{ pcOld[jq][j] = pcNew[jq][j] ;
#ifdef EXTEND0
if (!isCheck) pcOld[jq][j].s /= sum ; /* normalise */
#endif
}
}
#ifdef TRACEBACK_DEBUG
if (isCheck) traceBackCheck (jq, k, pcOld[0], pRef->M) ; /* check traceback counters */
printf ("%d%d %d", xOld[0], xOld[1], uRef->y[0]) ;
for (j = 1 ; j <= pRef->M ; ++j) printf (" %d", uRef->y[j]) ; putchar ('\n') ;
for (j = 0 ; j <= pRef->M ; ++j) printf (" %6.1f", pcOld[0][j].s) ; putchar ('\n') ;
for (j = 0 ; j <= pRef->M ; ++j) printf (" %6d", pcOld[0][j].j1) ; putchar ('\n') ;
#endif