File: phase.cpp

package info (click to toggle)
plink 1.07%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,132 kB
  • sloc: cpp: 72,375; makefile: 123; sh: 12
file content (1910 lines) | stat: -rw-r--r-- 43,502 bytes parent folder | download | duplicates (7)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910


//////////////////////////////////////////////////////////////////
//                                                              //
//           PLINK (c) 2005-2009 Shaun Purcell                  //
//                                                              //
// This file is distributed under the GNU General Public        //
// License, Version 2.  Please see the file COPYING for more    //
// details                                                      //
//                                                              //
//////////////////////////////////////////////////////////////////


#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <cmath>
#include <vector>
#include <map>
#include <cassert>

#include "plink.h"
#include "options.h"
#include "helper.h"

#include "genogroup.h"
#include "phase.h"
#include "haplowindow.h"

extern ofstream LOG;
using namespace std;


vector_t HaploPhase::phaseAllHaplotypes(bool display, Perm & perm )
{
  
  vector_t results;


  /////////////////////////////////////////////
  // Set individual to follow in verbose mode?

  if ( par::haplo_plem_follow )
    {
      par::haplo_plem_follow = false;
      for (int i=0; i<P.n; i++)
	{
	  if ( P.sample[i]->fid == par::haplo_plem_follow_fid &&
	       P.sample[i]->iid == par::haplo_plem_follow_iid )
	    {
	      P.printLOG("Following individual [ " 
			 + par::haplo_plem_follow_fid + " " 
			 + par::haplo_plem_follow_iid + " ] in EM\n");
	      par::haplo_plem_follow_ind = i;
	      par::haplo_plem_follow = true;
	    }
	}
    }


  //////////////////////////////
  // Begin phasing (and testing)
	
  int nms = new_map.size();


  for (int l=0; l<nms; l++)
    {

      if (display && ! par::silent)
	{
	  cerr << l+1<< " out of "<< nms 
	       << " haplotypes phased       \r";
	  cerr.flush();
	}

      // Set current haplotype
      current = l;

      // Get number of predictors
      int s = new_pred_locus[l].size();

      // X or haploid markers?
      X = par::chr_sex[new_map[l]->chr];
      haploid = par::chr_haploid[new_map[l]->chr];

      // Same window as previous, unless in weighted 
      // multimarker test mode, in which case do all

      bool same = true;
      if (l==0 || par::weighted_mm)
	same = false;
      else
	{
	  if (new_pred_locus[l].size() != new_pred_locus[l-1].size() )
	    {
	      same = false;
	    }
	  else
	    for (int j=0; j<s; j++)
	      {
		if (new_pred_locus[l][j] != new_pred_locus[l-1][j])
		  {
		    same = false;
		    break;
		  }
	      }
	}


  
      ///////////////////////////////////////////////////////////////
      // Calculate haplotype frequencies and posterior probabilities,
      // if different from previous round

      if (!same)
	{
	  
	  ///////////////////////////////////////////////////
	  // Initialise

	  reset();
	      
	  // Is this a wildcard haplotype?
	  string nm = new_map[l]->name;
	  if (nm.substr(nm.size()-1) == "_")
	    name(new_map[l]->name.substr(0, new_map[l]->name.find("_")));
	  else
	    name(new_map[l]->name);

	  S = new_pred_locus[l];
	  ns = S.size();


	  for (int i=0; i<P.n; i++)
	    {
	      Individual * person = P.sample[i];
	      if (person->founder)
		{
		  if (haploid || (X && person->sex))
		    validN++;
		  else
		    validN+=2;
		}

	      includeIndividuals(i);
	    }

 
	  ////////////////////////////////////////
	  // Verbose recording? (one window only)

	  if ( par::haplo_plem_verbose || par::haplo_plem_follow )
	    VPHASE.open("phased.verbose",ios::out);
	  

	  ///////////////////////////////////////////////////
	  // Define 'windows' within the 'region'

	  int pos = 0;

	  // Number of possible stub haplotypes
	  nsh = (int) pow(2.0, (double) par::haplo_plem_overlap );


	  // Check we have a valid overlap size
	  par::haplo_plem_overlap = par::haplo_plem_original_overlap;
	  if ( par::haplo_plem_window >= ns || 
	      par::haplo_plem_overlap >= par::haplo_plem_window )
	    par::haplo_plem_overlap = 0;


	  while (1)
	    {

	      HaploWindow * window = new HaploWindow( this , & P );


	      //////////////////////////////////
	      // Define SNP span for this window

	      window->start = pos;
	      window->stop = pos + par::haplo_plem_window - 1;
	      
	      if (window->stop >= ns )
		window->stop = ns-1;

	      /////////////////////////////////////////////////////////////////
	      // Enumerate haplotypes/genoGroups/phases and tally
	      // unambiguous

	      window->enumerateHaplotypes(new_pred_locus[l]);

	      window->enumerateGenogroups();

	      set<MultiLocusGenotype*>::iterator im 
		= window->genotypes.begin();

	      while (im != window->genotypes.end() )
		{
		  if (P.sample[ (*im)->reference ]->founder)
		    window->enumeratePhase( (*im)->reference );
		  ++im;
		}

	      window->tallyUnambiguousCounts();

	      ///////////////////////////////
	      // Add the window to the list

	      windows.push_back( window );
	      
	      ///////////////////////////
	      // Reached end of region?

	      if (window->stop == ns-1)
		break;


	      ///////////////////////////////////
	      // Otherwise advance by one window

	      pos += par::haplo_plem_window - par::haplo_plem_overlap;


  	      if (par::haplo_plem_verbose)
  		{
 		  cout << windows.size() << " windows added        \n";
 		  cout << window->stop << " ... " << ns-1 << "\n";
 		}
	      
	    }

  	  if ( par::haplo_plem_verbose )
  	    cout << "\n";

	  // Set number of windows;
	  nw = windows.size();

	  if (par::haplo_plem_verbose)
	    P.printLOG("Constructed "+int2str(nw)+" windows\n");


	  /////////////////////////////////////
	  // Use offspring to reduce ambiguity
	  
	  // To be added in; not yet implemented //
	  //  if (nonfounders)
	  //     for (int i=0; i<P.n; i++) 
	  //       if (P.sample[i]->founder && ambig[i])
	  // 	resolveWithChildren(i)
	  



	  ////////////////////////////////
	  // E-M phasing based on founders
	  
	  // Currently three versions of EM
	  
	  // performAlternEM()     drive chain-of-windows EM
	  // performEM()           individual-window EM
	  // performEM_original()  used for meta-EM	  
	  
	  performAlternEM();


	  //////////////////////////////////
	  // Free window storage

	  for (int w=0; w<nw; w++)
	    delete windows[w];
	  windows.clear();


	  //////////////////////////////////
	  // Prune unlikely regional phases

 	  for (int i=0; i<P.n; i++)
 	    if (P.sample[i]->founder)
 	      prunePhase(i);
	  

	  ////////////////////////////////////////
	  // Fill-in phasing for any non-founders

	  // These functions work at per-individual level, i.e. we do
	  // not use genogroups here


	  if ( nonfounders )
	    {
	      phasemap.clear();
	      phasemap.resize(P.n);

	      if (par::test_hap_TDT || par::proxy_TDT )
		{
		  trans.clear();
		  untrans.clear();
		  trans.resize(nh,0);
		  untrans.resize(nh,0);

		  transmissionX.clear();
		  transmissionX2.clear();
		  transmissionX.resize(nh,0);
		  transmissionX2.resize(nh,0);
		}
		  
	      if (haploid )
		error("Family-based haplotyping only for autosomes and X chromosome");
	      
	      // List all possible non-rare phases
	      //  enumerateAllPhases();

	      for (int i=0; i<P.n; i++)
		if (!P.sample[i]->founder)
		  {
	      
		    // Only phase affecteds, if performing TDT
		    if (par::test_hap_TDT || par::proxy_TDT )
		      if ( !P.sample[i]->aff)
			continue;

		    phaseAndScoreNonfounder(i);

		    prunePhase(i);

		  }
	    }
	  	  

	  if ( par::haplo_plem_verbose 
	       || par::haplo_plem_follow )
	    VPHASE.close();
	  
	  

	  ///////////////////////////////////////////////////////////////
	  //                                                           //
	  // Post-phasing actions                                      //
	  //                                                           //
	  ///////////////////////////////////////////////////////////////


	  ////////////////////////////////
	  // Haplotype frequencies

	  if (par::display_hap_freqs)
	    reportHaplotypeFrequencies();



	  ////////////////////////////////
	  // Haplotype association tests
	  
	  if (par::test_hap_CC ||
	      par::test_hap_GLM ||
	      par::test_hap_TDT ||
	      par::test_hap_QTL )
	    {

	      // Are we testing all haplotypes, or a specified
	      // pre-determined one?

	      if ( !par::phase_hap_all )
		setTestHaplotype(new_pred_allele[l]);
	      
	      // Perform the actual tests: ignore the results for now
	      // (these will be used when we incorporate permutation)
	      
	      vector_t t = performHaplotypeTests(display, perm );
	      for (int i=0; i<t.size(); i++)
		results.push_back( t[i] );
	      
	    }
	  


	  ////////////////////////////////
	  // Haplotype phase probabilities

	  if (par::display_phase_probs)
	    {
	      if (par::display_phase_probs_wide )
		reportPhaseWideFormat();
	      else
		reportPhase();
	    }



	  ////////////////////////////////////////////////////////
	  // Tracking haplotype sharing for a particular pair of
	  // individuals

	  if (par::segment_haplotrack)
	    {
	      trackThisSegment();
	    }
	  
	  // next unique set of SNPs to be phased 
	}
      

      
      // Impute both rare and non-rare
	
      if ( par::impute_tags ) 
	{
	  
	  // If we have specified a particular allele, impute that;
	  // otherwise, impute all above a certain frequency, and 
	  // add to map
	  
	  setTestHaplotype(new_pred_allele[l]);
	  
	  if ( test_hap > -1 ) 
	    imputeThisHaplotype(l);
	  else
	    {
	      for ( test_hap = 0; test_hap < nh; test_hap++ )
		if ( f[test_hap] >= par::min_hf 
		     && f[test_hap] <= par::max_hf )
		  {
		    imputeThisHaplotype(l);
		  }
	    }
	}



      ////////////////////////////////////
      // Next set of SNPs to be phased 
      
    }
  
  if ( par::haplo_plem_verbose )
    cout << "\n";


  return results;

}

void HaploPhase::enumerateHaplotypes(vector<int> & s)
{

  // Make list of haplotypes, and code as +/-
  
  S = s;
  ns = s.size();
  nh = (int)pow((double)2, ns);
  f.resize(nh);
  
  ph_hap1.clear();
  ph_hap2.clear();
  ph_freq.clear();

  // Optionally, for haplotype-based TDT
  if (par::test_hap_TDT || par::proxy_TDT )
    {
      trans.clear();
      untrans.clear();

      trans.resize(nh, 0);
      untrans.resize(nh, 0);
    }

  unsigned int h=0;

  while (h<nh)
    {
      vector<bool> m1;

      unsigned int p=1;
      for (int s=0; s<ns; s++)
	{
	  if (h & p )
	    m1.push_back(false);
	  else
	    m1.push_back(true);
	  p <<= 1;
	}

      // Add to list of haplotypes
      //hap.push_back(m1);

      // Add to HapMap
      //hapmap.insert(make_pair(m1, h));

      // Consider next haplotype
      h++;

    }

  // Product of allele frequencies
  for (int h=0; h<nh; h++)
    {
      f[h] = 1;
      for (int s=0; s<ns; s++)
	{
	  if ( hap[h][s] )
	    f[h] *= P.locus[S[s]]->freq;
	  else
	    f[h] *= ( 1 - P.locus[S[s]]->freq);
	}
    }
}

void HaploPhase::includeIndividuals(int i)
{

  // Do not look at non-reference individuals in some circumstances

  if ( reference_only && ! P.sample[i]->missing )
    {
      include[i] = false;

      if (P.sample[i]->founder)
	{
	  if (haploid || (X && P.sample[i]->sex))
	    validN--;
	  else
	    validN-=2;
	}
      
      return;
    }
  
  vector<bool> s1(ns);
  vector<bool> s2(ns);

  // Flipping allele-coding for homozygotes
  for (int s=0; s<ns; s++)
    {
      if (par::SNP_major)
	{
	  s1[s] = P.SNP[S[s]]->one[i];
	  s2[s] = P.SNP[S[s]]->two[i];
	}
      else
	{
	  s1[s] = P.sample[i]->one[S[s]];
	  s2[s] = P.sample[i]->two[S[s]];
	}
      
      if (s1[s] == s2[s])
	{
	  s1[s] = !s1[s];
	  s2[s] = !s2[s];
	}

    }


  //////////////////////////////////////////////////////////
  // Count amount of missing genotype data at this position
  
  int nm = 0;
  for (int s=0; s<ns; s++)
    if (s1[s] && !s2[s])
      nm++;

  // But if too much missing genotype data, then 
  // we should not even try to phase this individual
  // for this region; note -- females should always be
  // missing all genotypes for Y, so we don't need to 
  // worry about allowing for a special case here.

  if ( (double)nm/(double)ns >= par::hap_missing_geno )
    {

      include[i] = false;

      if (P.sample[i]->founder)
	{
	  if (haploid || (X && P.sample[i]->sex))
	    validN--;
	  else
	    validN-=2;
	}

      return;
    }

}



void HaploPhase::performAlternEM()
{
  

  // Working variables for convergence for first 
  // pass meta-EM (chain of EMs)

  int iter = 0;
  bool converged;
  int num_converged = 0 ;

  // Start multiple EM runs, one per window, allowing each to update
  // the adjoining window's EM state

  startWindow = 0; 
  finishWindow = nw-1;

  bool verboseOutputInFirstRound = true;

  if ( par::haplo_plem_follow && verboseOutputInFirstRound ) 
    {
      VPHASE << "\n\nFOLLOWED INDIVIDUAL " << par::haplo_plem_follow_ind << "\n";
      VPHASE << " PRIOR TO START OF ANY EM\n";
      verboseDisplayWindows(par::haplo_plem_follow_ind);
    }
  
  
  do
    {

      if ( par::haplo_plem_verbose && verboseOutputInFirstRound )
	VPHASE << "OUTER LOOP ITERATION " << iter << "\n\n";
      
      // Iterate forward through windows
      int w = 0;

      while (w < nw )
	{

// 	  if ( ! par::silent ) 
// 	    {	      
// 	      cout << num_converged << " converged windows at iteration " 
// 		   << iter << " forwards chain, window " << w << "      \r";
// 	      cout.flush();
// 	    }

	  if ( par::haplo_plem_verbose && verboseOutputInFirstRound )
	    VPHASE << "\n\nFORWARD WINDOW " << w << "\n";
	  
	  HaploWindow * currentWindow = windows[w];
	  
	  if ( par::haplo_plem_follow && verboseOutputInFirstRound ) 
	    {
	      VPHASE << "\n\nFOLLOWED INDIVIDUAL " << par::haplo_plem_follow_ind << "\n";
	      VPHASE << "  FORWARD LOOP, WINDOW " << w << " PRIOR TO ADJUSTMENT \n";
	      verboseDisplayWindows(par::haplo_plem_follow_ind);
	    }

	  ///////////////////////////////////////////////////
	  // Only adjust freq if this window isn't converged

	  if ( !currentWindow->converged )
	    {
	      
	      if ( par::haplo_plem_verbose && verboseOutputInFirstRound )
		VPHASE << "WINDOW NOT YET CONVERGED\n";

	      
	      ///////////////////////////////////////////////////
	      // Only pass freq information once after convergence
	      

	      if ( false && w > 0 && !windows[w-1]->right_passed )
		{

		  if ( par::haplo_plem_verbose && verboseOutputInFirstRound )
		    VPHASE << "ADJUSTING FREQUENCIES BASED ON PREVIOUS WINDOW " << w-1 << "\n";

		  HaploWindow * previousWindow = windows[w-1];

		  // Populate stub frequencies for both windows

		  vector_t currentStub = currentWindow->leftStubFrequency();
		  vector_t previousStub = previousWindow->rightStubFrequency();

		  if ( par::haplo_plem_verbose )
		    {
		      for (int z=0; z<currentStub.size(); z++)
			{
			  VPHASE << "STUB " << z << "\t"
				 << currentStub[z] << " " 
				 << previousStub[z] << "\n";
			}		   
		    }
		  
		  vector_t of = currentWindow->f;
		  
		  // Adjust haplotype frequencies

		  for (int h = 0; h < currentWindow->nh; h++)
		    {
		      int stub = currentWindow->leftStub[h];
		      
		      if ( abs( previousStub[ stub ] - currentStub[ stub ] ) > 0.02 )
			{
			  double nf;
			  if (currentStub[ stub ] == 0)
			    nf = 0;
			  else
			    nf = currentWindow->f[h] * ( previousStub[ stub ] / currentStub[ stub ] );
			  
			  currentWindow->f[h] = ( currentWindow->f[h] + nf ) * 0.5; 
			}
		    }
		  

	      if ( par::haplo_plem_follow && verboseOutputInFirstRound ) 
		{
		  VPHASE << "FOLLOWED INDIVIDUAL " << par::haplo_plem_follow_ind << "\n";
		  VPHASE << "  FORWARD LOOP, WINDOW " << w << " POST ADJUSTMENT \n";
		  verboseDisplayWindows(par::haplo_plem_follow_ind);
		}

	      
	      if ( par::haplo_plem_verbose )
		{
		  
		  VPHASE << "OLD, ADJUSTED FREQS\n";
		  
		  for (int h = 0; h < currentWindow->nh; h++)
		    { 
		      if ( of[h] > 0.001 || currentWindow->f[h] > 0.001 ) 
			VPHASE << "ORIGINAL HAP " << currentWindow->haplotypeName(h) 
			       << "\t"
			       << currentWindow->leftStub[h] << " " 
			       << of[h] << "\t"
			       << currentWindow->f[h] << "\n";
		    }
		  VPHASE << "\n";
		}
	      
	      
	      // Once window has converged pass freq and keep track
	      if (previousWindow->converged)
		{
		  previousWindow->right_passed = true;
		  
		  if ( par::haplo_plem_verbose )
		    VPHASE << "\nPREVIOUS WINDOW CONVERGED AND PASSED ON: NOW FIXED\n";
		}
		}
	      
	      if ( par::haplo_plem_verbose )
		VPHASE << "\nENTERING INNER EM FOR THIS WINDOW\n";
	      
	      // Do some more EM iterations
	      currentWindow->performEM();

	      if ( par::haplo_plem_follow && verboseOutputInFirstRound ) 
		{
		  VPHASE << "FOLLOWED INDIVIDUAL " << par::haplo_plem_follow_ind << "\n";
		  VPHASE << "  FORWARD LOOP, WINDOW " << w << " POST EM PHASING \n";
		  verboseDisplayWindows(par::haplo_plem_follow_ind);
		}


	      if ( par::haplo_plem_verbose )
		VPHASE << "\nENTERING PRUNING FOR THIS WINDOW\n";
	      
	      // Get rid of unlikely phases 
	      currentWindow->pruneGenogroups();

	      if ( par::haplo_plem_follow && verboseOutputInFirstRound ) 
		{
		  VPHASE << "FOLLOWED INDIVIDUAL " << par::haplo_plem_follow_ind << "\n";
		  VPHASE << "  FORWARD LOOP, WINDOW " << w << " POST EM PRUNING \n";
		  verboseDisplayWindows(par::haplo_plem_follow_ind);
		}

	      
	      if ( par::haplo_plem_verbose )
		VPHASE << "\nDONE WITH WINDOW " << w << " IN FORWARDS LOOP\n";

	    }
	  

	  // Next window
	  ++w;
	}



      //////////////////////
      // Now move backwards

      w = windows.size() - 1;

      while (w >= 0)
	{

	  if ( par::haplo_plem_verbose ) 
 	    cout << num_converged << " converged windows at iteration " 
		 << iter << " backwards chain, window " << w << "      \r";
	  

	  if ( par::haplo_plem_verbose && verboseOutputInFirstRound )
	    VPHASE << "\n\nBACKWARD WINDOW " << w << "\n";

	  HaploWindow * currentWindow = windows[w];

	  if ( par::haplo_plem_follow && verboseOutputInFirstRound ) 
	    {
	      VPHASE << "\n\nFOLLOWED INDIVIDUAL " << par::haplo_plem_follow_ind << "\n";
	      VPHASE << "  BACKWARDS LOOP, WINDOW " << w << " PRIOR ADJUSTMENT \n";
	      verboseDisplayWindows(par::haplo_plem_follow_ind);
	    }


	  // Only adjust freq if window isn't converged
	  
	  if ( !currentWindow->converged)
	    {

	      if ( false && w+1< windows.size() && !windows[w+1]->left_passed)

		{
		  if ( par::haplo_plem_verbose && verboseOutputInFirstRound )
		    VPHASE << "ADJUSTING FREQUENCIES BASED ON PREVIOUS WINDOW " << w+1 << "\n";

		  HaploWindow * previousWindow = windows[w+1];

		  // Populate stub frequencies for both windows

		  vector_t currentStub = currentWindow->rightStubFrequency();
		  vector_t previousStub = previousWindow->leftStubFrequency();

		  vector_t of = currentWindow->f;

		  // Adjust haplotype frequencies

		  for (int h = 0; h < currentWindow->nh; h++)
		    {
		      int stub = currentWindow->rightStub[h];

		      if ( abs( previousStub[ stub ] - currentStub[ stub ] ) > 0.02 )
			{
			  double nf;
			  if (currentStub[ stub ] == 0)
			    nf = 0;
			  else
			    nf = currentWindow->f[h] * ( previousStub[ stub ] / currentStub[ stub ] );
			  currentWindow->f[h] = ( currentWindow->f[h] + nf ) * 0.5; 
			}
		    }

		  if ( par::haplo_plem_verbose )
		    {

		      VPHASE << "OLD, ADJUSTED FREQS\n";

		      for (int h = 0; h < currentWindow->nh; h++)
			{ 
			  if ( of[h] > 0.001 || currentWindow->f[h] > 0.001 ) 
			    VPHASE << "ORIGINAL HAP " << currentWindow->haplotypeName(h) 
				   << "\t"
				   << currentWindow->leftStub[h] << " " 
				   << of[h] << "\t"
				   << currentWindow->f[h] << "\n";
			}
		      VPHASE << "\n";
		    }

		  
		  // Once window has converged pass freq and keep
		  // track
		  
		  if (previousWindow->converged)
		    previousWindow->left_passed = true;

		}

	      if ( par::haplo_plem_follow && verboseOutputInFirstRound ) 
		{
		  VPHASE << "FOLLOWED INDIVIDUAL " << par::haplo_plem_follow_ind << "\n";
		  VPHASE << "  BACKWARDS LOOP, WINDOW " << w << " POST ADJUSTMENT \n";
		  verboseDisplayWindows(par::haplo_plem_follow_ind);
		}



	      // Do some more EM iterations
	      currentWindow->performEM();


	      if ( par::haplo_plem_follow && verboseOutputInFirstRound ) 
		{
		  VPHASE << "FOLLOWED INDIVIDUAL " << par::haplo_plem_follow_ind << "\n";
		  VPHASE << "  BACKWARDS LOOP, WINDOW " << w << " POST EM PHASING \n";
		  verboseDisplayWindows(par::haplo_plem_follow_ind);
		}

	      
	      // Get rid of unlikely phases 

	      currentWindow->pruneGenogroups();

	      if ( par::haplo_plem_follow && verboseOutputInFirstRound ) 
		{
		  VPHASE << "FOLLOWED INDIVIDUAL " << par::haplo_plem_follow_ind << "\n";
		  VPHASE << "  BACKWARDS LOOP, WINDOW " << w << " POST EM PRUNING \n";
		  verboseDisplayWindows(par::haplo_plem_follow_ind);
		}



	    }

	  // Next window
	  --w;
	}

      converged = true;
      num_converged = 0;
      for (int w = 0; w < nw; w++)
	if ( !windows[w]->converged)
	  converged = false;
	else
	  ++num_converged;
      
      // Next regional iteration
      iter++;

    } while ( !converged );

  
  if ( par::debug ) 
    cout << "Chain of EMs has convered, now putting together...                \n";
  
  if (par::haplo_plem_verbose)
    P.printLOG("Chain of E-Ms converged\n");


  ////////////////////////////////////////////////
  // Finished chain of window-EMs; now perform 
  // the meta-EM (to stitch windows together), 
  // if needed
  ////////////////////////////////////////////////


  //////////////////////////////////
  // Expand genoGroups

//   if ( ! par::silent ) 
//     cout << "Expanding genogroups...\n";

  for (int w = 0; w < nw; w++)
    {

      // A more intense pruning now at the end 

      windows[w]->pruneGenogroups( par::haplo_plem_meta_prune_phase );
      
      // before we expand out...
      windows[w]->expandGenogroups();
    }


  
  
  ////////////////////////////////////////////////////////////
  // If only a single window, just swap in the relevant variables from
  // the window
  
   if ( nw == 1 )
     {

       if ( par::meta_large_phase ) 
	 {
	   mainImputation();
	   return;
	 }

       HaploWindow * thisWindow = windows[0];
      
       f = thisWindow->f;
       hap = thisWindow->hap;
       hapmapb = thisWindow->hapmap;
       nh = thisWindow->nh;
       S = thisWindow->S;
       ns = thisWindow->ns;
       
       if ( par::test_hap_TDT )
 	{
 	  trans.clear();
 	  untrans.clear();
 	  trans.resize(nh,0);
 	  untrans.resize(nh,0);
 	}
      
       pp.resize(P.n);
       hap1.resize(P.n);
       hap2.resize(P.n);

       for (int i = 0; i < P.n; i++)
	 {	  
	   if ( include[i] ) 
	     {
	       pp[i] = thisWindow->pp[i];
	       hap1[i] = thisWindow->hap1[i];
	       hap2[i] = thisWindow->hap2[i];
	       
	       if ( hap1[i].size() == 1 )
		 ambig[i] = false;
	       else 
		 ambig[i] = true;
	       
	       if ( hap1[i].size() == 0 )
		 {
		   include[i] = false;
		 }
	       else 
		 include[i] = true;
	     }
 	}
      
       // Now we are done
       return;
      
     }
  
  
  
  ////////////////////////////////////////////////////////////
  // Combine haplotypes and define initial variables (f, pp)

  
  int waplotypeSize = par::haplo_plem_meta_window > nw ? 
    nw :
    par::haplo_plem_meta_window;
  
  if (par::haplo_plem_verbose)
    P.printLOG("Window size is " + int2str( waplotypeSize ) + " in meta-EM\n");

  startWindow = 0;
  finishWindow = startWindow + waplotypeSize - 1;
  
  if ( finishWindow >= nw ) 
    finishWindow = nw-1;

  actual_nw = finishWindow - startWindow + 1;


  if ( par::haplo_plem_follow ) 
    {
      VPHASE << "\n\n--------------\nENTERING NOW META-EM STAGE\n\n";
      if ( par::meta_large_phase ) 
	VPHASE << " ** IN IMPUTE MODE ** \n";
      else
	VPHASE << " ** IN HAPLOTYING MODE ** \n";
    }


  ////////////////////////////////////////////////////////
  // Double up phase possibilities for all windows beyond
  // the first
  
  for (int w=1; w<nw; w++)
    {
      for (int i=0; i<P.n; i++)
	{

	  if ( ! include[i] ) 
	    continue;
	  
	  if ( ! P.sample[i]->founder ) 
	    continue;
	  
	  HaploWindow * currentWindow = windows[w];
	  
	  if ( ! currentWindow->ambig[i] )
	    {
	      if ( currentWindow->hap1[i][0] != currentWindow->hap2[i][0] )
		{
		  currentWindow->hap1[i].push_back( currentWindow->hap2[i][0] );
		  currentWindow->hap2[i].push_back( currentWindow->hap1[i][0] );
		}	      
	      currentWindow->ambig[i] = true;
	      currentWindow->pp[i].resize(2,0.5);
	    }
	  else
	    {
	      int o = currentWindow->pp[i].size();
	      
	      for ( int z=0; z<o; z++)
		{
		  if ( currentWindow->hap1[i][z] != currentWindow->hap2[i][z] )
		    {
		      currentWindow->hap1[i].push_back( currentWindow->hap2[i][z] );
		      currentWindow->hap2[i].push_back( currentWindow->hap1[i][z] );
		      currentWindow->pp[i][z] /= 2;
		      currentWindow->pp[i].push_back( currentWindow->pp[i][z] );
		    }	      
		}
	    }
	}
    }

  

  //////////////////////////////////
  // Some temporary descriptions 

  long int cnt_phase = 0;
  long int cnt_hap  = 0;
  long int cnt_ambig = 0;
  for (int w = 0; w < nw; w++)
    {
      for (int i = 0; i < P.n; i++) 
	if ( include[i] && P.sample[i]->founder )
	  {
	    cnt_phase += windows[w]->hap1[i].size(); 
	    if ( windows[w]->pp[i].size() > 0 )
	      cnt_ambig++;
	  }
      cnt_hap += windows[w]->f.size();
    }

  // Average number of phases per person per window = 
  
  double avg_phase_depth = (double)cnt_phase / ( (double)P.n * (double)nw ) ;

  if (par::haplo_plem_verbose)
    {
      stringstream s2;
      s2 << "In " << nw << " windows, "
	 << cnt_phase << " total phases and " << cnt_hap << " haplotypes\n";
      s2 << "Of these, " << cnt_ambig << " individual/windows still need resolving\n";
      s2 << "Average phase depth = " << avg_phase_depth << "\n";  
      
      P.printLOG(s2.str());
    }


  ////////////////////////////////
  // Begin main loop for meta-EM

  bool completed = false;

  // For imputation mode, we might want to scan the windows multiple
  // times

  bool forwards_mode = true;
  int meta_iter = 0;
  int num_meta_iter = 1;

  while ( 1 ) 
    {
      

      /////////////////////////////////
      // Enumerate possible waplotypes

      for (int i = 0; i < P.n; i++)
	{
	  
	  // Always try to phase as much as possible when 
	  // in imputation mode
	  
	  if ( par::meta_large_phase ) 
	    include[i] = true;

	  if ( include[i] )
	    {

	      enumeratePhasedWindows(i);
	      
	      if ( hap1[i].size() > 1 )
		pp[i].resize(hap1[i].size());
	      else
		pp[i].resize(0);
	     	      
	      if ( par::haplo_plem_follow && par::haplo_plem_follow_ind == i )
		{
		  VPHASE << "AFTER ENUMERATED_PHASED DUMP, WINDOWS " << startWindow 
			 << " to " << finishWindow << "\n";
		  verboseDisplayWindows(i,false);
		  VPHASE << "\n\n";
		  
		}
	    }
	}
      

      // Generate starting values for haplotypes -- for now use a
      // uniform distribution
      
      if ( nh != hapmap.size() )
	error("weirdness...\n");
      
      if (par::haplo_plem_verbose)
	P.printLOG("Considering "+int2str(nh)
		   + " waplotypes in second-stage EM, "
		   + int2str(startWindow)
		   +" to "+int2str(finishWindow)+"\n");
      
      if ( par::haplo_plem_verbose )
	VPHASE << "ENTERING PLEM WITH " << nh << " WAPLOTYPES\n";
      
      // Set up haplotype space for HaploPhase
      
      f.resize( hapmap.size() );
      for (int h=0; h<nh; h++)
	f[h] = 1/(double)nh;
      

      // (Remove these in final version, until end?) Make overall
      // haplotype codes, etc

      S.clear();
      for(int w= startWindow; w <= finishWindow; w++)
        {
          HaploWindow * currentWindow = windows[w];
          int start = par::haplo_plem_overlap;
          if (w==startWindow) start = 0;
          for (int s = start; s < currentWindow->ns; s++)
            S.push_back( currentWindow->S[s] );
        }
      
      ns = S.size();

      if ( par::test_hap_TDT )
	{
	  trans.clear();
	  untrans.clear();
	  trans.resize(nh,0);
	  untrans.resize(nh,0);
	}
      
      
      
      if ( par::haplo_plem_follow ) 
	{

	  VPHASE << "inclusion status = " << include[ par::haplo_plem_follow_ind ] << "\n";

	  VPHASE << "HAPLOPHASE PRE_MERGING STATUS \n";
	  
	  for (int z=0; z<hap1[par::haplo_plem_follow_ind].size(); z++)
	    {
	      VPHASE << haplotypeName(hap1[par::haplo_plem_follow_ind][z]) << " / " 
		     << haplotypeName(hap2[par::haplo_plem_follow_ind][z]) << "\n";
	    }
	  
	  VPHASE << "\n\n";
	}
      

      //////////////////////////////////////////////////
      // Invoke basic EM algorithm on subset of windows 
      
//       if ( ! par::silent ) 
// 	{
// 	  cout << "Performing meta-EM on windows " << startWindow 
// 	       << " to " << finishWindow << " of " << nw << "         \r";
// 	  cout.flush();
// 	}
    
      performEM_original();
      

      if ( par::haplo_plem_verbose ) 
	{
	  
	  VPHASE << "Post meta-EM frequencies\n";
	  for (int h=0; h<nh; h++)
	    VPHASE << h << "\t" 
		   << f[h] << "\t"
		   << haplotypeName(h) << "\n";
	  
          VPHASE << "Post meta-EM frequencies of common haplotypes (1 MAF)\n";
          for (int h=0; h<nh; h++)
            if ( f[h] >= 0.01 ) 
	      VPHASE << h << "\t"
		     << f[h] << "\t"
		     << haplotypeName(h) << "\n";
	  
	  VPHASE << "Post meta-EM phase frequencies\n";
	  for (int i=0; i<P.n; i++)
	    {
	      for (int z=0; z<hap1[i].size(); z++)
		{
		  VPHASE << i << "\t"
			 << haplotypeName(hap1[i][z]) << " / " 
			 << haplotypeName(hap2[i][z]) << "\t";
		  if ( pp[i].size() == 0 ) 
		    VPHASE << "F" << ambig[i] << "\n";
		  else
		    VPHASE << pp[i][z] << " " << ambig[i] << "\n";
		}
	    }
	  VPHASE << "\n";
	}
      

      
      if ( par::haplo_plem_follow ) 
	{
	  VPHASE << "HAPLOPHASE MERGING RESULTS \n";
	  for (int z=0; z<hap1[par::haplo_plem_follow_ind].size(); z++)
	    {
	      if ( pp[par::haplo_plem_follow_ind].size() == 0 || 
		   pp[par::haplo_plem_follow_ind][z] > 0.01 )
		{
		  VPHASE << haplotypeName(hap1[par::haplo_plem_follow_ind][z]) << " / " 
			 << haplotypeName(hap2[par::haplo_plem_follow_ind][z]) << "\t";
		  VPHASE << "(freqs = " << f[hap1[par::haplo_plem_follow_ind][z]] << " / "
			 << f[hap2[par::haplo_plem_follow_ind][z]] << " )\t";		  
		  if ( pp[par::haplo_plem_follow_ind].size() == 0 ) 
		    VPHASE << "F" << ambig[par::haplo_plem_follow_ind] << "\n";
		  else
		    VPHASE << pp[par::haplo_plem_follow_ind][z] << " " 
			   << ambig[par::haplo_plem_follow_ind] << "\n";
		}
	    }
	  VPHASE << "\n\n";
	}
  


      ///////////////////////////////////////////////////////////////////
      // Given new results in phase, copy these back into the original
      // windows, applying appropriate pruning of phases
      

      if ( par::meta_large_phase ) 
	{
	  updateForImputation();
	}
      

      // In imputation mode, we mnight want to re-prune the windows
      // several times
      
      if ( par::meta_large_phase )
	{
	  
	  if ( finishWindow == nw-1 && forwards_mode ) 
	    {
	      if ( ++meta_iter == num_meta_iter )
		completed = true;
	      else
		forwards_mode = false;
	    }
	  
	  if ( startWindow == 0 && ! forwards_mode ) 
	    {
	      if ( ++meta_iter == num_meta_iter )
		completed = true;
	      else
		forwards_mode = true;
	    }
      
	}


      // In haplotyping mode, we only do a single run through
      // the windows

      if ( ! par::meta_large_phase ) 
	{
	  if ( finishWindow == nw-1 )
	    completed = true;
	}

      /////////////////////////////////////////////////////////////////
      // Have we finished? In this case, generate imputed solution, or
      // copy final solution into HaploPhase (if not already there?)
      
      if ( completed )
	{
	  
// 	  if ( !par::silent ) 
// 	    cout << "Finished meta-EM: creating the final solution...        \n";

	  ////////////////////////////////////////////////////////////
	  // Copy back SNPs for HaploPhase -- we shouldn't need to do
	  // this -- we only ever swapped things for debug purposes,
	  // therefore we can remove above and this change...
	  
	  
	  ////////////////////////////////////
	  // Imputation, or haplotyping mode?
	  
	  if ( par::meta_large_phase ) 
	    {

	      S.clear();
	      for( int w= 0; w < nw; w++)
		{
		  HaploWindow * currentWindow = windows[w];
		  int start = par::haplo_plem_overlap;
		  if (w==0) start = 0;
		  for (int s = start; s < currentWindow->ns; s++)
		    S.push_back( currentWindow->S[s] );
		}
	      
	      ns = S.size();
	      
	      mainImputation();
	    }
	  

	  /////////////////////////////////////////////////////////////
	  // Finish up haplotyping (copy frequencies, phases, etc back
	  // into HaploPhase)

	  if ( ! par::meta_large_phase )
	    {
	      
	      // The things we need / should check are all okay are:
	      
	      // f = thisWindow->f;
	      // hap = thisWindow->hap;
	      // nh = thisWindow->nh;
	      // S = thisWindow->S;
	      // ns = thisWindow->ns;
	      
	      // pp[i]
	      // hap1[i]
	      // hap2[i]
	      // ambig[i]
	      // include[i]
	      
	      ////////////////////////
	      // Some final things...
	      
	      if ( par::test_hap_TDT )
		{
		  trans.clear();
		  untrans.clear();
		  trans.resize(nh,0);
		  untrans.resize(nh,0);
		}
	      
	    }


	  //////////////////////////////////
	  // Some temporary descriptions 
	  
	  long int cnt_phase = 0;
	  long int cnt_hap  = 0;
	  long int cnt_ambig = 0;

	  for (int w = 0; w < nw; w++)
	    {
	      for (int i = 0; i < P.n; i++) 
		if ( include[i] && P.sample[i]->founder )
		  {
		    cnt_phase += windows[w]->hap1[i].size(); 
		    if ( windows[w]->pp[i].size() > 0 )
		      cnt_ambig++;
		  }
	      cnt_hap += windows[w]->f.size();
	    }
	  
	  if (par::haplo_plem_verbose)
	    {
	      stringstream s2;	  
	      s2 << "After meta-EM, in " << nw << " windows, "
		 << cnt_phase << " total phases and " << cnt_hap << " haplotypes\n";
	      s2 << "Of these, " << cnt_ambig << " individual/windows still need resolving\n";
	      P.printLOG(s2.str());
	    }
	  
	  ////////////////////
	  // And now finish

	  break;

	}

      
      //////////////////////////////////////////////////////////////////
      // Alternatively, in haplotyping mode, we want to keep track of
      // all non-rare haplotypes and accumulate

      //////////////////////////////////////////////////////////////
      // If haplotyping (estimating haplotype frequencies) as opposed
      // to imputation, then we use an alternate strategy: we copy
      // HaploPhase results back into last window in this set, and
      // shift window forwards (copying only common haplotypes
      // (default=?) and phases (default=10%) )
      
      if ( ! par::meta_large_phase ) 
	{
      
	  HaploWindow * thisWindow = windows[ finishWindow ];
	  
	  thisWindow->f.clear();
	  thisWindow->hap.clear();
	  thisWindow->nh = 0;

	  
	  /////////////////////////////////
	  // Save only non-rare haplotypes
	  
	  map<int,int> keptHaplotypes;
	  keptHaplotypes.clear();
	  int new_h = 0;
	  
	  for (int h=0; h<nh; h++)
	    {
	      if ( f[h] > par::haplo_plem_meta_prune_haplotype ) 
		{
		  thisWindow->f.push_back(f[h]);
		  thisWindow->hap.push_back(hap[h]);
		  thisWindow->nh++;
		  keptHaplotypes.insert( make_pair(h,new_h++) );
		}
	    }
	  
	  
	  /////////////////////////////////////////////////////////////////
	  // Update list of SNPs this HaploWindow now points to (handling
	  // any possible overlap)
	  
	  vector<int> tmp;
	  
	  for(int w = startWindow; w <= finishWindow; w++ )
	    {	  
	      HaploWindow * currentWindow = windows[w];
	      int start = par::haplo_plem_overlap;
	      if (w==startWindow) start = 0;
	      for (int s = start; s < currentWindow->ns; s++)
		tmp.push_back( currentWindow->S[s] );
	    }
	  
	  thisWindow->S = tmp;
	  
	  if ( hap[0].size() > 0 )
	    thisWindow->ns = hap[0].size();
	  else
	    thisWindow->ns = 0;
	  

	  ////////////////////////////////////////////////////
	  // For this new window, set the stub codes for each 
	  // new haplotype
	  
	  thisWindow->setStubCodes();
	  

	  /////////////////////////////////////////////////////////
	  // Copy per-person information (phases and probabilities)
	  
	  for (int i = 0; i < P.n; i++)
	    {
	      
	      thisWindow->pp[i].clear();
	      thisWindow->hap1[i].clear();
	      thisWindow->hap2[i].clear();
	      
	      if ( pp[i].size() == 0 ) 
		{
		  
		  thisWindow->pp[i] = pp[i];
		  if ( hap1[i].size() == 1 ) 
		    {
		      map<int,int>::iterator k1 = keptHaplotypes.find( hap1[i][0] );
		      map<int,int>::iterator k2 = keptHaplotypes.find( hap2[i][0] );
		      
		      if ( k1 != keptHaplotypes.end() 
			   &&
			   k2 != keptHaplotypes.end() )
			{
			  thisWindow->hap1[i].push_back( k1->second );
			  thisWindow->hap2[i].push_back( k2->second );      
			}
		    }
		  
		}
	      else
		{
		  for ( int z = 0 ; z < pp[i].size() ; z++ )
		    {
		      if (pp[i][z] > par::haplo_plem_meta_prune_phase )
			{
			  
			  map<int,int>::iterator k1 = keptHaplotypes.find( hap1[i][z] );
			  map<int,int>::iterator k2 = keptHaplotypes.find( hap2[i][z] );
			  
			  if ( k1 != keptHaplotypes.end() 
			       &&
			       k2 != keptHaplotypes.end() )
			    {
			      
			      thisWindow->pp[i].push_back(pp[i][z]);
			      thisWindow->hap1[i].push_back(k1->second);
			      thisWindow->hap2[i].push_back(k2->second);				      
			      
			    }
			}
		      
		    }
		  
		  // No need to rescale these, as we do not use posterior
		  // probs (or haplotype freqs) at this stage in any case
		  // yet -- but otherwise, we will want to adjust to sum
		  // to 1 if we edit out rare phases, or set ambig codes,
		  // etc
		  		  
		}	      
	    } // Next individual     
	  
	}



      if ( par::haplo_plem_follow ) 
	{
	  VPHASE << "POST WINDOW STITCHING... " 
		 << startWindow << " to " 
		 << finishWindow << "\n";
	  verboseDisplayWindows(par::haplo_plem_follow_ind,false);
	  VPHASE << "\n--------------------------------------\n";
	}
	
      
      /////////////////////////////////////////
      // Reset key variables in HaploPhase
      
      nh = 0;
      hap.clear();
      hapi.clear();
      f.clear();
      hapmap.clear();
      
      
      
      /////////////////////////////////////////
      // Advance to next set of windows       
      
      // Imputation?
      
      if ( par::meta_large_phase )
	{
	  if ( forwards_mode )
	    {  
	      ++startWindow;
	      ++finishWindow;
	    }
	  else
	    {
	      --startWindow;
	      --finishWindow;
	    }
	}

      
      // or haplotyping?

      else
	{
	  startWindow = finishWindow;
	  finishWindow = startWindow + waplotypeSize - 1;
	  if ( finishWindow >= nw ) 
	    finishWindow = nw-1;
	  actual_nw = finishWindow - startWindow + 1;
	}
      
    
    } // loop while not finished
  


  //////////////////////////////////
  // End of alternate EM algorithm

  return;
  
}




vector_t HaploPhase::performHaplotypeTests(bool display, Perm & perm)
{
  
  vector_t statistic;
  
  if ( par::test_hap_GLM )
    {                
      return P.glmHaplotypeTest(display,perm);
    }

  // Weighted multimarker test (test a single Haplotype)
  
  if ( par::weighted_mm )
    {

      if (par::test_hap_CC)
	haplotypicWeightedCC();
      else if (par::test_hap_TDT)
	haplotypicWeightedTDT();

      return statistic;
    }

  // Standard haplotype tests

  if ( !par::phase_hap_all )
    {

      map<int,int> tests;

      // Of the specific, prespecified haplotype? 
      // Test only the specific haplotype

      if (f[test_hap] >= par::min_hf)
	{
	  
	  for (int h2=0; h2 < nh; h2++)
	    {
	      if (f[h2] >= par::min_hf)
		{
		  if (test_hap==h2)
		    tests.insert(make_pair(h2, 0));
		  else
		    tests.insert(make_pair(h2, 1));
		}
	    }
	  
	  if (par::test_hap_CC)
	    haplotypicCC(tests, 2, true);
	  else if (par::test_hap_QTL)
	    haplotypicQTL(tests, 2, true);
	  else if (par::test_hap_TDT)
	    haplotypicTDT(tests, 2, true);
	
	}

    }
  else
    {
      // Perform an omnibus test and all haplotype-specific
      // tests, if the --hap-all flag has been set

      // Omnibus test

      // tests[0] = 0
      // tests[1] = 1
      // tests[2] = 2
      // ...
      // tests[h] = h

      map<int,int> tests;
      int nch=0;
      for (int h=0; h < nh; h++)
	if (f[h] >= par::min_hf)
	  {
	    tests.insert(make_pair(h, nch++));
	  }
      
      if (nch>2)
	{
	  if (par::test_hap_CC)
	    haplotypicCC(tests, nch, true);
	  else if (par::test_hap_QTL)
	    haplotypicQTL(tests, nch, true);
	  else if (par::test_hap_TDT)
	    haplotypicTDT(tests, nch, true);
	}
      
      
      // Haplotype-specific test

      // tests[0] = 0
      // tests[1] = 1,2,...,h

      // tests[0] = 1
      // tests[1] = 0,2,3,...,h

      // etc

      for (int h=0; h < nh; h++)
	{
	  
	  if (f[h] >= par::min_hf)
	    {
	      tests.clear();

	      for (int h2=0; h2 < nh; h2++)
		{
		  if (f[h2] >= par::min_hf)
		    {
		      if (h==h2)
			{
			  tests.insert(make_pair(h2, 0));
			}
		      else
			tests.insert(make_pair(h2, 1));
		    }
		}
	      
	      if (par::test_hap_CC)
		haplotypicCC(tests, 2, true);
	      else if (par::test_hap_QTL)
		haplotypicQTL(tests, 2, true);
	      else if (par::test_hap_TDT)
		haplotypicTDT(tests, 2, true);
	      
	    }
	}

    } // end of --hap-all routine


  // Dummy return vector (for now)
  return statistic;

}

void HaploPhase::prunePhase(int i)
{

  // Prune regional phases (HaploPhase)

  if ( (!include[i]) ||(!ambig[i]))
    return;


  double psum = 0;

  vector<double> new_pp(0);
  vector<int> new_h1(0);
  vector<int> new_h2(0);
  
  for (int z=0; z < hap1[i].size(); z++)
    {
      if (pp[i][z] >= par::hap_min_phase_prob)
	{
	  new_pp.push_back(pp[i][z]);
	  psum += pp[i][z];
	  new_h1.push_back(hap1[i][z]);
	  new_h2.push_back(hap2[i][z]);
	}
    }

  // Normalise?
  if (pp[i].size() > new_pp.size() )
    {
      for (int z=0; z < new_pp.size(); z++)
	new_pp[z] /= psum;
    }
  
  // Update
  pp[i] = new_pp;
  hap1[i] = new_h1;
  hap2[i] = new_h2;

}

set<int> HaploPhase::makeSetFromMap(map<int,int> & h)
{

  // Wrapper function for dosage that takes a set<int>
  // Extract indicated haplotypes (coded 0)

  set<int> tests;
  
  map<int,int>::iterator ih = h.begin();
  while ( ih != h.end() )
    {
      if ( ih->second == 0 ) 
	tests.insert( ih->first );
      ++ih;
    }

  return tests;
}


double HaploPhase::dosage(int i, set<int> & h)
{

  // Assume i and h are valid

  double d = 0;
  
  if ( ambig[i] )
    {

      vector_t & posterior = pp[i];
      vector<int> & h1 = hap1[i];
      vector<int> & h2 = hap2[i];

      for (int z = 0; z < h1.size(); z++)
	{
	  if ( h.find( h1[z] ) != h.end() ) 
	    d += posterior[z];
	  if ( ! (haploid || (X && P.sample[i]->sex)))
	    if ( h.find( h2[z] ) != h.end() ) 
	      d += posterior[z];
	}
    }
  else
    {
      if ( h.find( hap1[i][0] ) != h.end() ) 
	++d;
      if ( ! (haploid || (X && P.sample[i]->sex)))
	if ( h.find( hap2[i][0] ) != h.end() )  
	  ++d;
    }
    
  return d;

}