File: whap.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 (1470 lines) | stat: -rw-r--r-- 35,545 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


//////////////////////////////////////////////////////////////////
//                                                              //
//           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 <cmath>
#include <sstream>

#include "whap.h"
#include "helper.h"
#include "plink.h"
#include "options.h"
#include "perm.h"
#include "nlist.h"
#include "phase.h"
#include "model.h"
#include "linear.h"
#include "logistic.h"
#include "stats.h"




//////////////////////////////////////////////////////////////
//
// Conditional Haplotype tests (CHAP models)
//
//   A null and alternate model specified in terms of 
//           haplotypes (potentially grouped)
//           covariates
//           conditioning SNPs
//
//   Only focus on allelic, autosomal main effects right now
//
//
//   SNPs done with --condition {list}
//   Covariates with --covar / --covar-name / --covar-number
//   Haplotypes with --hap-snps
//
//   Covariates are always present under both alternate and null
//   SNPs can be dropped from the alternate (tested)
//   Haplotypes can be dropped (tested) and grouped


// A helper function
void displayHaploGroups(ofstream &, ChapModel &, HaploPhase *);

string ci(double coef, double se)
{
  string c = " (";
  if ( (!par::bt) || par::return_beta )
    {
      c += dbl2str( coef - par::ci_zt * se , 3 ) + "; " ;
      c += dbl2str( coef + par::ci_zt * se , 3 ) + " )" ;
    }
  else
    {
      c += dbl2str( exp( coef - par::ci_zt * se ), 3) + "; " ;
      c += dbl2str( exp( coef + par::ci_zt * se ), 3) + " )" ;
    }
  return c;
}


vector_t Plink::conditionalHaplotypeTest(bool print_results, Perm & perm)
{


  ///////////////////////////////////////////////
  //                                           //
  // Some basic setup first                    //
  //                                           //
  ///////////////////////////////////////////////

  Chap thisCModel(this, haplo);
  
  whap = & thisCModel;

  ChapModel alternateModel;
  ChapModel nullModel;

  
  // Use basic GLM function to fit linear and logistic 
  // models: although, let it know that there will not 
  // be a 'main' SNP 

  par::assoc_glm_without_main_snp = true;


  // Return a single result

  vector_t results(1);


  printLOG("Writing conditional haplotype tests to [ " 
	   + par::output_file_name + ".chap ]\n");

  ofstream CH;
  CH.open((par::output_file_name+".chap").c_str(),ios::out);
  CH.precision(3);
  
  CH << "+++ PLINK conditional haplotype test results +++ \n\n";
  

  ///////////////////////////////////////////////
  //                                           //
  // Phase haplotypes                          //
  //                                           //
  ///////////////////////////////////////////////

  haplo->phaseAllHaplotypes(false,*pperm);

  // Record the number of common haplotypes
  
  int nch = 0;  
  for (int h=0; h < haplo->nh; h++)
    if ( haplo->f[h] >= par::min_hf )
      ++nch;
    
  
  CH << haplo->ns << " SNPs, and " 
     << nch << " common haplotypes ( MHF >= " << par::min_hf << " ) "
     << "from " << haplo->nh << " possible\n\n";

  CH << setw(4) << "CHR" << " "
     << setw(12) << "BP" << " "
     << setw(12) << "SNP" << " "
     << setw(4) << "A1" << " "
     << setw(4) << "A2" << " "
     << setw(10) << "F" << "\n";

  for (int s=0; s< haplo->ns; s++)
    CH << setw(4) << locus[haplo->S[s]]->chr << " "
       << setw(12) << locus[haplo->S[s]]->bp << " "
       << setw(12) << locus[haplo->S[s]]->name << " "
       << setw(4) << locus[haplo->S[s]]->allele1 << " "
       << setw(4) << locus[haplo->S[s]]->allele2 << " "
       << setw(10) << locus[haplo->S[s]]->freq << "\n";
  CH << "\n";

  if ( nch == 0 ) 
    {
      results[0] = 0;
      CH << "Exiting... no common haplotypes to test\n";
      CH.close();
      return results;
    }
  
  
  ///////////////////////////////////////////////
  //                                           //
  // Build models                              //
  //                                           //
  ///////////////////////////////////////////////
 
  whap->setModels(alternateModel, nullModel);
  
  whap->build(alternateModel);

  whap->build(nullModel);



  ///////////////////////////////////////////////
  //                                           //
  // Display models                            //
  //                                           //
  ///////////////////////////////////////////////

  CH << "Haplogrouping: each {set} allowed a unique effect\n";
  CH << "Alternate model\n";
  displayHaploGroups(CH, alternateModel,haplo);

  CH << "Null model\n";
  displayHaploGroups(CH, nullModel,haplo);
  CH << "\n";
  
  if ( ! whap->isNested() )
    error("The null model is not nested in the alternate: please respecify");


  
  ///////////////////////////////////////////////
  //                                           //
  // Fit alternate model                       //
  //                                           //
  ///////////////////////////////////////////////

  whap->current = & alternateModel;
  
  glmAssoc(false,perm);
  
  Model * alternate = model;



  ///////////////////////////////////////////////
  //                                           //
  // Fit null model                            //
  //                                           //
  ///////////////////////////////////////////////

  // Ensure we have the same individuals
  vector<bool> missingInAlternate = alternate->getMissing();
  for (int i=0; i<n; i++)
    sample[i]->missing2 = missingInAlternate[i];

  whap->current = & nullModel;  
  
  glmAssoc(false,perm);
  
  Model * null = model;
  

  ///////////////////////////////////////////////
  //                                           //
  // Fit group-specific models                 //
  //                                           //
  ///////////////////////////////////////////////
  
  // If there is more than 1 group, these models test each group
  // against all others, in both the alternate and null

  vector_t alt_specific_pval;
  bool hasAltSpecifics = alternateModel.group.size() > 2 && par::chap_add_grp_specifics;
  
  if ( hasAltSpecifics ) 
    {

      ////////////////////////////////////////////
      // Create a model with no haplotype effects
  
      ChapModel simpleNullModel = nullModel;
      
      simpleNullModel.group.clear();

      set<int> t;	
      for (int h=0; h< haplo->nh; h++)
	if ( haplo->f[h] >= par::min_hf )
	  t.insert(h);
      simpleNullModel.group.push_back(t);      

      whap->current = & simpleNullModel;  
      glmAssoc(false,perm);
      Model * simplenull = model;

      
      
      ////////////////////////////////////////////
      // Run all haplotype-specific models

      

      for (int h=0; h< haplo->nh; h++)
	{
	  
	  if ( haplo->f[h] < par::min_hf ) 
	    continue;

	  ChapModel simpleAlternateModel = nullModel;
	  
	  simpleAlternateModel.group.clear();
	  simpleAlternateModel.group.resize(1);
	  
	  for (int h2=0; h2< haplo->nh; h2++)
	    {
	      
	      if ( haplo->f[h2] < par::min_hf ) 
		continue;
	      
	      if ( h2 == h )
		{
		  set<int> t;
		  t.insert(h);
		  simpleAlternateModel.group.push_back(t);
		}
	      else
		simpleAlternateModel.group[0].insert(h);	  

	    }
	  
      
	  ////////////////////////////////////////////
	  // Perform test, and model comparison
	  
	  whap->current = & simpleAlternateModel;  
	  glmAssoc(false,perm);
	  Model * simplealternate = model;
	  
	  
	  //////////////////////////
	  // Store test statistic  
	  
	  alt_specific_pval.push_back( modelComparisonPValue(simplealternate, 
							     simplenull) );
	  
	  
	  // Next haplo-group
	}
      
    }

  ///////////////////////////////////////////////
  //                                           //
  // Fit sub-null model                        //
  //                                           //
  ///////////////////////////////////////////////
  
  // If the null model contains >1 group, then 
  // perform the alternate:null comparisons 
  // separately for each sub-group, if the null
  // still contains fewer parameters than the 
  // alternate
  
  vector_t subnull_pval;

  int subnullModels = 0;

  // Worth doing? 
  if ( nullModel.group.size() > 1 && 
       alternateModel.group.size() - nullModel.group.size() > 1 )
    {

      for (int g = 0; g < nullModel.group.size(); g++)
	{
	  // For this null-group, do the haplotypes in the 
	  // alternate belong to >1 group? If so, perform a 
	  // separate test
	  
	  set<int>::iterator ih = nullModel.group[g].begin();
	  set<int> aGroup;
	  
	  while ( ih != nullModel.group[g].end() )
	    {
	      aGroup.insert( alternateModel.haploGroup.find(*ih)->second );	      	      
	      ++ih;
	      
	    }

	  if ( aGroup.size() > 1 ) 
	    {
	      
	      ++subnullModels;
	      
	      // Re-jig a new model, that is basically like the 
	      // alternate, except for this one group.
	      
	      ChapModel subnullModel = alternateModel;
	      
	      // Edit group only (haploGroup will not be used, 
	      // so ignore that for now...)
	      
	      set<int>::iterator ai = aGroup.begin();
	      

	      // Get first group: arbitrarily choose this group to
	      // be the merged-to group

	      int ng = *ai;
	      
	      // All other groups, merge with this first one
	      
	      ++ai;

	      // Iterate over each alternate-model haplogroup to be merged
	      while ( ai != aGroup.end() )
		{

		  // Iterate over all haplotypes in this haplogroup
		  set<int>::iterator s = alternateModel.group[ *ai ].begin();
		  while ( s != alternateModel.group[ *ai ].end() )
		    {
		      subnullModel.group[ ng ].insert( *s ); 
		      ++s;		      
		    }

		  subnullModel.group[ *ai ].clear();
		  ++ai;

		}
	     
	      // Now erase empty groups
	      for (int g=0; g<subnullModel.group.size(); g++)
		{
		  if ( subnullModel.group[g].size() == 0 )
		    {
		      subnullModel.group.erase( subnullModel.group.begin() + g );
		      --g;
		    }
		}

	      whap->current = & subnullModel;  
	      glmAssoc(false,perm);
	      Model * subnull = model;

	      // Store test statistic
	      
	      subnull_pval.push_back( modelComparisonPValue(alternate, subnull) );
	      
	    }
	  else
	    {
	      subnull_pval.push_back(-1);
	    }
	}          

    }



  ///////////////////////////////////////////////
  //                                           //
  // Report model comparisons                  //
  //                                           //
  ///////////////////////////////////////////////


  // Check that both models converged

  if ( ! ( alternate->isValid() && null->isValid() ) )
    error("Could not fit conditional haplotype models:\n   "
	  "collinearity issues from a badly-specified model\n");
      

  vector_t coeff1 = alternate->getCoefs();
  vector_t se1 = alternate->getSE();
  
  vector_t coeff0 = null->getCoefs();
  vector_t se0 = null->getSE();
  
  
  vector<string> label1 = alternate->label;
  vector<string> label0 = null->label;
   
 
  //////////////////////////////////
  // Convert to odds ratios?
  
  vector_t odds1 = coeff1;
  vector_t odds0 = coeff0;
  
  if ( par::bt )
    {
      for (int h=0; h<coeff1.size(); h++)
	odds1[h] = exp(coeff1[h]);
      for (int h=0; h<coeff0.size(); h++)
	odds0[h] = exp(coeff0[h]);
    }


  ////////////////////////////////////////////////////
  // List by groups; first null then alternate groups 

  string clabel_alternate = par::bt ? "OR(A)" : "BETA(A)";
  string clabel_null = par::bt ? "OR(N)" : "BETA(N)";

  string cunder_alternate = par::bt ? "-------" : "---------";
  string cunder_null = par::bt ? "-------" : "---------";
  
  int estimate_size = 12;
  if (par::display_ci) 
    {
      estimate_size += 16;
      cunder_alternate += "----------------";
      cunder_null += "----------------";
    }

  CH << setw( haplo->ns+5 ) << "HAPLO" << "   "
     << setw(10) << "FREQ" << " ";

  CH << setw( estimate_size ) << clabel_alternate << " ";

  if ( hasAltSpecifics )
    CH << setw(12) << "SPEC(A)" << " ";
  
  CH << setw( estimate_size ) << clabel_null << " ";


  if ( subnullModels > 1 )
    CH << setw(12) << "SUBNULL P" << " "; 
  CH << "\n";

  CH << setw( haplo->ns+5 ) << "-------" << "   "
     << setw(10) << "------" << " ";

  CH << setw( estimate_size ) << cunder_alternate << " ";

  if ( hasAltSpecifics )
    CH << setw(12) << "---------" << " ";
  
  CH << setw( estimate_size ) << cunder_null << " ";

  
  if ( subnullModels > 1 )
    CH << setw(12) << "-----------" << " "; 
  CH << "\n";
  
  for ( int g=0; g<nullModel.group.size(); g++ )
    {
      bool printed0 = false;
      for ( int g2=0; g2<alternateModel.group.size(); g2++ )
	{
	  set<int>::iterator ih = alternateModel.group[g2].begin();
	  
	  bool printed = false;
	  while ( ih != alternateModel.group[g2].end() )
	    {
	      
	      // Only display if this haplotype is in the
	      // null group
	      
	      if ( nullModel.group[g].find( *ih ) 
		   == nullModel.group[g].end() )
		{
		  ++ih;
		  continue;
		}
	      

	      CH << setw( haplo->ns+5 ) << haplo->haplotypeName( *ih ) << "   "
		 << setw(10) << haplo->f[ *ih ] << " ";
	      
	      if ( ! printed ) 
		{
		  
		  if ( g2==0 )
		    CH << setw( estimate_size ) << "(-ref-)" << " ";
		  else
		    {
		      int p = alternateModel.haploGroup.find(*ih)->second;
		      if ( realnum( odds1[p] ) ) 
			{
			  string r = dbl2str( odds1[p] , 4 );
			  if ( par::display_ci ) 
			    r += ci( coeff1[p] , se1[ p ]  );
			  CH << setw( estimate_size ) << r << " ";		  
			  
			}
		      else
			{
			  CH << setw( estimate_size ) << "NA" << " ";		  
			}
		    }

		  if ( hasAltSpecifics )
		    CH << setw(12) << alt_specific_pval[ g2 ] << " ";
		  
		  printed = true;
		}
	      else 
		{ 
		  CH << setw( estimate_size ) << "|   " << " ";
		  
		  if ( hasAltSpecifics )
		    CH << setw(12) << " " << " ";
		  
		}
	      
	      ///////////////////////////////
	      // Display corresponding null 
	      
	      if ( ! printed0 ) 
		{		  
		  if ( g==0 )
		    CH << setw( estimate_size ) << "(-ref-)" << " ";
		  else
		    {
		      int p = nullModel.haploGroup.find(*ih)->second;
		      if ( realnum( odds0[p] ) ) 
			{
			  string r = dbl2str( odds0[p] , 4 );
			  if ( par::display_ci ) 
			    r += ci( coeff0[p] , se0[ p ]  );
			  CH << setw( estimate_size ) << r << " ";		  			  
			}
		      else
			CH << setw( estimate_size ) << "NA" << " ";		  
		    }
		}
	      else 
		CH << setw( estimate_size ) << "|   " << " ";
	      
	      ////////////////////////////////
	      // Display corresponding subnull?
	      
	      if ( subnullModels > 1  ) 
		{
		  if ( ! printed0 )
		    {
		      if ( subnull_pval[g] < 0 ) 
			CH << setw(12) << "n/a" << " ";
		      else
			CH << setw(12) << subnull_pval[g] << " ";		  
		    }
		}
	      
	      printed0 = true;
	      
	      
	      CH << "\n";	  
	      ++ih;
	    }
	  
	  // Delimiter alternate groups, unless we 
	  // are also about to delimit a null group
	  
	}
      
      if ( g < nullModel.group.size() - 1 ) 
	CH << "\n";
      
    }
  
  CH << setw( haplo->ns+5 ) << "-------" << "   "
     << setw(10) << "------" << " ";

  
  CH << setw( estimate_size ) << cunder_alternate << " ";
  if ( hasAltSpecifics )
    CH << setw(12) << "---------" << " ";      
  CH << setw( estimate_size ) << cunder_null << " ";
    
  if ( subnullModels > 1 )
    CH << setw(12) << "-----------" << " "; 
  CH << "\n";
  

  /////////////////////////////////////////////////
  //  Display other covariates, conditioning SNPs
  
  // 0=intercept; 1 -> (H-1) haplotype-group coefficients; 
  // then conditioning SNPs; then other covariates

  int p1 = alternateModel.group.size();
  int p0 = nullModel.group.size();
  
  // Only an intercept, then need to add 1
  if ( p1 == 0 ) p1++;
  if ( p0 == 0 ) p0++;


  /////////////////////////////////////////////////////////
  // Conditioning SNPs: will always feature in alternate; 
  // may or may not feature in null
  
  if ( conditioner.size() > 0 )
    {
      CH << "\n";
      
      CH << setw( haplo->ns+5) << "SNPS" << " " 
	 << setw(12) << " " << " "
	 << setw( estimate_size ) << clabel_alternate << " "
	 << setw( estimate_size ) << clabel_null << "\n";
      
      CH << setw( haplo->ns+5) << "-----" << " " 
	 << setw(12) << " " << " "
	 << setw( estimate_size ) << cunder_alternate << " "
	 << setw( estimate_size ) << cunder_null << "\n";

      for (int s=0; s < conditioner.size(); s++)
	{

	  CH << setw( haplo->ns+5 ) << label1[p1] << " " 
	     << setw(12) << " " << " ";
	  if ( realnum( coeff1[ p1 ] ) )
	    {
	      string r = dbl2str( coeff1[ p1 ] , 4 );
	      if ( par::display_ci ) 
		r += ci( coeff1[ p1 ] , se1[ p1 ]  );
	      CH << setw( estimate_size ) << r << " ";		  
			  
	    }
	  else
	    CH << setw( estimate_size ) << "NA" << " ";

	  p1++;

	  if ( nullModel.masked_conditioning_snps[s] ) 
	    {
	      if ( realnum( coeff0[ p0 ] ) )
		{
		  string r = dbl2str( coeff0[ p0 ] , 4 );
		  if ( par::display_ci ) 
		    r += ci( coeff0[ p0 ] , se0[ p0 ]  );
		  CH << setw( estimate_size ) << r << " ";
		}
	      else 
		CH << setw( estimate_size ) << "NA" << "\n";
	      p0++;
	    }
	  else
	    CH << setw( estimate_size ) << "(dropped)" << "\n";
	  
	}

    }



  ///////////////////////////////////////////////////////
  // Other covariates: these will always feature in alternate 
  // and null

  if ( par::clist && par::clist_number > 0 ) 
    {

      CH << "\n";

      CH << setw( haplo->ns+5) << "COVAR" << " " 
	 << setw(12) << " " << " "
	 << setw( estimate_size ) << clabel_alternate << " "
	 << setw( estimate_size ) << clabel_null << "\n";

      CH << setw( haplo->ns+5) << "-----" << " " 
	 << setw(12) << " " << " "
	 << setw( estimate_size ) << cunder_alternate << " "
	 << setw( estimate_size ) << cunder_null << "\n";

      for (int s=0; s<par::clist_number; s++)
	{
	  CH << setw( haplo->ns+5) << label1[p1] << " " 
	     << setw(12) << " " << " ";

	  if ( ! par::display_ci )
	    {
	      CH << setw( estimate_size ) << coeff1[ p1 ] << " "
		 << setw( estimate_size ) << coeff0[ p0 ] << "\n";
	    }
	  else
	    {
	      string r = dbl2str( coeff1[ p1 ] , 4 ) + ci( coeff1[ p1 ] , se1[ p1 ]  );
	      CH << setw( estimate_size ) << r << " ";		  	      
	      r = dbl2str( coeff0[ p0 ] , 4 ) + ci( coeff0[ p0 ] , se0[ p0 ]  );
	      CH << setw( estimate_size ) << r << " ";		  	      
	    }
	  
	  // Advance to next coefficient, 
	  ++p1;
	  ++p0;

	}
    }

  if ( alternate->isSexInModel() )
    {

      // Have we already displayed a header for covariates?
      if ( ! ( par::clist && par::clist_number > 0 ) )
	{
	  CH << "\n";

	  CH << setw( haplo->ns+5) << "COVAR" << " " 
	     << setw(12) << " " << " "
	     << setw( estimate_size ) << clabel_alternate << " "
	     << setw( estimate_size ) << clabel_null << "\n";
	  
	  CH << setw( haplo->ns+5) << "-----" << " " 
	     << setw(12) << " " << " "
	     << setw(estimate_size ) << cunder_alternate << " "
	     << setw(estimate_size ) << cunder_null << "\n";
	}

      CH << setw( haplo->ns+5 ) << label1[p1] << " " 
	 << setw(12) << " " << " ";

      if ( ! par::display_ci )
	{
	  CH << setw(estimate_size) << coeff1[ p1 ] << " "
	     << setw(estimate_size) << coeff0[ p0 ] << "\n";
	}
      else
	{
	  string r = dbl2str( coeff1[ p1 ] , 4 ) + ci( coeff1[ p1 ] , se1[ p1 ]  );
	  CH << setw( estimate_size ) << r << " ";		  	      
	  r = dbl2str( coeff0[ p0 ] , 4 ) + ci( coeff0[ p0 ] , se0[ p0 ]  );
	  CH << setw( estimate_size ) << r << " ";		  	      
	}
      
      ++p1;
      ++p0;
    }
  
   if ( p1 != coeff1.size() || p0 != coeff0.size() )
     error("Internal error in whap.cpp -- p1,p0 do not align");
  
  /////////////////////////////////////////////////
  //  Display overall model comparison statistics


  CH << "\n"
       << "Model comparison test statistics:\n\n";
  
  CH << setw(25) << " " << " "
     << setw(10) << "Alternate" << " " 
     << setw(10) << "Null" << "\n";
  
  if ( par::bt )
    {
      LogisticModel * lalternate = (LogisticModel*)alternate;
      LogisticModel * lnull = (LogisticModel*)null;
      
      CH << setw(25) << "-2LL : " << " " 
	 << setw(10) << lalternate->getLnLk() << " "
	 << setw(10) << lnull->getLnLk() << " "
	 << "\n\n";
      
      if ( lalternate->getNP() - lnull->getNP()  == 0 ) 
	CH << setw(25) << "Likelihood ratio test: "
	   << " ( not a valid comparison: identical models, df = 0 )\n";	   
      else
	{
	  double lrt = lnull->getLnLk() - lalternate->getLnLk();
	  if ( lrt < 0 || !realnum(lrt) ) lrt = 0;
	  int df = lalternate->getNP() - lnull->getNP();
	  double pval = chiprobP( lrt, df);
	  
	  CH << setw(25) << "Likelihood ratio test: "
	     << "chi-square = "
	     << lrt
	     << "\n"
	     << setw(25) << " "
	     << "df = " 
	     << df
	     << "\n"
	     << setw(25) << " "
	     << "p = " ;
	  if ( pval < 0 || ! realnum(pval) ) 
	    CH << "NA";
	  else
	    CH << pval;
	  CH << "\n";
	}
      
    }
  else
    {
      // Quantitative traits

      LinearModel * lalternate = (LinearModel*)alternate;
      LinearModel * lnull = (LinearModel*)null;

      CH << setw(25) << "R-squared : " << " " 
	 << setw(10) << lalternate->calculateRSquared() << " "
	 << setw(10) << lnull->calculateRSquared() << " "
	 << "\n";
      CH << setw(25) << "Adjusted R-squared : " << " " 
	 << setw(10) << lalternate->calculateAdjustedRSquared() << " "
	 << setw(10) << lnull->calculateAdjustedRSquared() << " "
	 << "\n\n";

//       CH << setw(25) << "Mallow's C : " << " " 
// 	 << lalternate->calculateMallowC(lnull) 
// 	 << "\n";
      
      
      double F = lalternate->calculateFTest(lnull);
      
      if ( F < 0 || !realnum(F) ) F = 0;
      
      double pvalue = pF( F, 
			  alternate->getNP() - null->getNP(),
			  alternate->Ysize() - alternate->getNP() - 1 );
      
      string df = int2str(alternate->getNP() - null->getNP())
	+", "+int2str(alternate->Ysize() - alternate->getNP() - 1);

      CH << setw(25) << "F-statistic comparison : "
	 << "F = "
	 << F
	 << "\n"
	 << setw(25) << " "
	 << "df = " 
	 << df
	 << "\n"
	 << setw(25) << " "
	 << "p = ";
      if ( pvalue < 0 || !realnum(pvalue) ) 
	CH << "NA";
      else
	CH << pvalue;
      CH << "\n";
      
    }

  


  ///////////////////////////////////////////////
  //                                           //
  // We're done                                //
  //                                           //
  ///////////////////////////////////////////////


  CH.close();
  
  delete alternate;
  delete null;
  
  return results;
  
}



void Chap::determineTestType()
{  
  // REDUNDANT 
}


void Chap::build(ChapModel & model)
{
  
  bool isNull = (&model) == null;
  
  // Either:
  //  1) Grouping for alternate and/or null
  //  2) Specific SNPs for alternate and/or null
  //  3) Sole-variant framing
  //  4) Independent effects
  //  5) Haplotype-specific


  model.group.clear();

  bool useDefault = false;
  
  string modelDescription = isNull ? 
    par::chap_model0 : par::chap_model1;
	  

  if ( par::chap_specified_groups )
    {
      
      // Make comma as hash group-delimiter code
      modelDescription = searchAndReplace(modelDescription,","," # ");
      
      // Expand haplotype equality statements
      modelDescription = searchAndReplace(modelDescription,"="," ");
      
      // Tokenize
      vector<string> tok;
      string buf; 
      stringstream ss(modelDescription);
      while (ss >> buf)
	tok.push_back(buf);
      
      
      // Check the same haplotype isn't specified more than once
      set<string> hapin;
      for (int h=0; h<tok.size(); h++)
	{
	  if ( tok[h] == "#" )
	    continue;
	  if ( hapin.find( tok[h] ) != hapin.end() )
	    {
	      if ( ! par::silent )
		cout << "\n";
	      error("Symbol " + tok[h] + " appears more than once in haplotype list");
	    }
	  hapin.insert(tok[h]);
	}

      // We have a list of haplotypes which need 
      // parsing; allow for wildcards
      
      // * = all haplotypes in one group
      // % = all haplotypes in own group
      // # = group delimiter
      
      // Check: cannot have both * and %
      bool groupAll = false;
      bool ungroupAll = false;
      
      for (int i=0; i<tok.size(); i++)
	{
	  if ( tok[i] == "*" )
	    groupAll = true;
	  else if ( tok[i] == "%" )
	    ungroupAll = true;
	}
      
      if ( groupAll && ungroupAll ) 
	error("Cannot specify * and % on same haplotype model");
      
      if ( isNull && ! ungroupAll ) 
	groupAll = true;
      
      if ( (!isNull) && ! groupAll ) 
	ungroupAll = true;
      
      if ( groupAll || ungroupAll ) 
	{
	  
	  set<int> toAdd;
	  
	  for ( int h=0; h < H->nh; h++ )
	    {
	      // Is this haplotype already explicitly listed?
	      
	      string hname = H->haplotypeName( h );
	      bool listed = false;
	      
	      for (int i=0; i< tok.size(); i++)
		{
		  if ( tok[i] == hname ) 
		    {
		      listed = true;
		      break;
		    }
		}
	      
	      if ( ! listed ) toAdd.insert(h);
	      
	    }
	  
	  // Is there anything to add?
	  if ( toAdd.size() > 0 ) 
	    {
	      if ( groupAll ) 
		tok.push_back("#");
	      set<int>::iterator ih = toAdd.begin();
	      while ( ih != toAdd.end() )
		{
		  if ( ungroupAll ) 
		    tok.push_back("#");
		  tok.push_back( H->haplotypeName(*ih) );
		  ++ih;
		}
	    }
	}
      
      
      /////////////////////////////////////////////
      // Now work out the wild-card expanded list
      set<int> t;
      for ( int i = 0 ; i < tok.size() ; i++ ) 
	{
	  if ( tok[i] == "#" ) 
	    {
	      if ( t.size() > 0 ) 
		model.group.push_back( t );
	      t.clear();
	    }
	  else if ( tok[i] == "*" || tok[i] == "%" ) 
	    continue;
	  else
	    {
	      // find haplotype code the long way...
	      for (int h=0; h< H->nh; h++)
		{
		  if ( H->f[h] < par::min_hf ) 
		    continue;
		  
		  if ( tok[i] == H->haplotypeName(h) )
		    t.insert(h);
		}
	    }	      
	}
      
      if ( t.size() > 0 ) 
	model.group.push_back(t);
      
    }
  else if ( par::chap_specified_snps )
    {
      
      // Assume that modelDescription contains a list of SNPs
      
      map<string,int> mapping;
      for (int l=0; l<P->nl_all; l++)
	mapping.insert(make_pair( P->locus[l]->name,l));
      
      NList nl(P->nl_all);
      vector<int> snplist = nl.deparseStringList(modelDescription,&mapping);
      
      if (snplist.size() == 0 )
	useDefault = true;
      
      setSNPList(snplist, model);
      
    }
  else if ( par::chap_sole_variant && isNull )
    {
      
      // This could be a list of SNPs, or a list of haplotypes
      // If SNPs, in NList form (i.e. allowing for 
      // If haplotypes, just in common delimited form
      
      // Under the alternate, we do not do anything here (i.e. thus the
      // condition above, which means the default alternate coding 
      // will be used)
      
      // We may also have specified, with "--control-alleles", that only 
      // a subset of the implied groupings are constrained under the null
      
      modelDescription = par::chap_entity;
      
      // We need to determine whether haplotypes or SNPs specified
      
      map<string,int> mapping;
      for (int s=0; s<H->ns; s++)
	mapping.insert(make_pair( P->locus[H->S[s]]->name,s));
      for (int h=0; h<H->nh; h++)
	mapping.insert(make_pair( H->haplotypeName(h),H->ns + h));
      
      if ( mapping.size() != H->ns + H->nh ) 
	error("Problem, as some SNPs and haplotypes appear not to have unique names");

      NList nl(H->ns + H->nh);
      vector<int> lst = nl.deparseStringList(modelDescription,&mapping);
      
      if (lst.size() == 0 )
	useDefault = true;
      
      bool isSNP = false;
      bool isHAP = false;
      for (int i=0; i< lst.size(); i++)
	if ( lst[i] >= H->ns ) isHAP = true;
	else if ( lst[i] < H->ns ) isSNP = true;
      
      if ( isSNP && isHAP ) 
	error("Cannot specify both SNPs and hapltoypes for --chap-control");

      if ( isHAP && par::chap_sole_variant_specific_alleles ) 
	error("Can only specify --control-alleles when SNPs are listed for --control");
      
      if ( isSNP ) 
	{
	  // Convert to locus 0..nl_all coding
	  for (int i=0; i<lst.size(); i++)
	    lst[i] = H->S[lst[i]]; 
	  
	  setSNPList(lst, model);
	}
      else
	{
	  // For any haplotype found, make so that it has it's 
	  // own group

	  model.group.clear();
	  model.group.resize(1); // main null group

	  for (int h=0; h< H->nh; h++)
	    {
	      if ( H->f[h] < par::min_hf ) 
		continue;
	      
	      bool found = false;
	      
	      for (int i=0; i<lst.size(); i++)
		if ( lst[i] - H->ns == h )
		  {
		    set<int> t;
		    t.insert(h);
		    model.group.push_back(t);
		    found = true;
		  }
	      if ( ! found ) 
		model.group[0].insert(h);
	      
	    }
	}
    }
  else if ( par::chap_independent_effect && isNull )
    {

      // Set SNPs for all *except* the one(s) specified, under the null

      modelDescription = par::chap_entity;

      map<string,int> mapping;
      for (int s=0; s<H->ns; s++)
	mapping.insert(make_pair( P->locus[H->S[s]]->name,s));	  
	

      // Use NList to return negative complement of SNPs listed

      NList nl(H->ns,false);
      vector<int> snplist = nl.deparseStringList(modelDescription,&mapping);
      
      if (snplist.size() == 0 )
	useDefault = true;
      
      // Convert to locus 0..nl_all coding
      for (int i=0; i<snplist.size(); i++)
	snplist[i] = H->S[snplist[i]]; 
      
      setSNPList(snplist, model);
      
    }
  else if ( par::chap_haplotype_specific && ! isNull ) 
    {
      
      // Set a single haplotype under the alternative

      modelDescription = par::chap_entity;

      map<string,int> mapping;
      for (int h=0; h<H->nh; h++)
	mapping.insert(make_pair( H->haplotypeName(h),h));
      
      NList nl(H->nh);
      vector<int> lst = nl.deparseStringList(modelDescription,&mapping);
      
      if (lst.size() == 0 )
	useDefault = true;
      
      model.group.clear();
      model.group.resize(1); // main null group
      
      for (int h=0; h< H->nh; h++)
	{
	  
	  if ( H->f[h] < par::min_hf ) 
	    continue;
	  
	  bool found = false;
	  
	  for (int i=0; i<lst.size(); i++)
	    {
	      if ( lst[i] == h )
		{
		  set<int> t;
		  t.insert(h);
		  model.group.push_back(t);
		  found = true;
		}
	      if ( ! found ) 
		model.group[0].insert(h);
	    }
	  
	}
      
    }
  else
    {
      // If nothing else done by now...
      useDefault = true;
    }
  
  
  /////////////////////////////////////////////////
  // Use defaults? Default null model is all 
  // haplotypes in one group. 
  
  if ( useDefault )
    {
      
      model.group.clear();
      
      if ( isNull )
	{      
	  set<int> t;	
	  for (int h=0; h< H->nh; h++)
	    if ( H->f[h] >= par::min_hf )
	      t.insert(h);
	  model.group.push_back(t);      
	}
      else
	{
	  for (int h=0; h< H->nh; h++)
	    if ( H->f[h] >= par::min_hf )
	      {
		set<int> t;	
		t.insert(h);
		model.group.push_back(t);
	      }      
	}
    }

  

  ////////////////////////////////////////////////////
  // Also make haploGroup's also -- might not need these?

  model.haploGroup.clear();

  for (int g=0; g< model.group.size(); g++)
    {
      set<int>::iterator ih = model.group[g].begin();
      while ( ih != model.group[g].end() )
	{
	  
	  // cout << H->haplotypeName(*ih) << " " << g << "\n";

	  model.haploGroup.insert(make_pair( *ih, g));
	  
	  ++ih;
	}
    }

  
  /////////////////////////////////////////////
  // What about dropping conditioning SNPs?

  // By default, include all conditioning SNPs
  
  model.masked_conditioning_snps.clear();
  model.masked_conditioning_snps.resize(P->conditioner.size(),true);
      
  // *Unless* this is the null, and we have requested that some be
  // dropped

  if ( isNull && par::chap_drop_snps )
    {      
     
      // List of conditioning SNPs
      
      if ( P->conditioner.size() == 0 ) 
	error("No conditioning SNPs in the analysis:\n   cannot test " 
	      + par::chap_drop_snps_list );
      
      map<string,int> mapping;
      for (int c=0; c < P->conditioner.size(); c++)
	mapping.insert(make_pair( P->locus[P->conditioner[c]]->name,c));
      
      // List of SNPs to drop:
      
      NList nl( P->conditioner.size() );
      vector<int> lst = nl.deparseStringList(par::chap_drop_snps_list,&mapping);
      
      for (int l=0; l<lst.size(); l++)
	{
	  model.masked_conditioning_snps[l] = false;
	}
    }


}


void Chap::setModels(ChapModel & a, ChapModel & n)
{
  alternate = &a;
  null = &n;
}

bool Chap::isNested()
{

  // If two haplotypes have the same grouping in the alternate, they
  // must also have the same in the null
  
  for (int h1 = 0; h1 < H->nh-1 ; h1++)
    for (int h2 = h1+1; h2 < H->nh; h2++)
      {
	if ( alternate->haplotypesInSameGroup(h1,h2) )
	  if ( ! null->haplotypesInSameGroup(h1,h2) )
	    return false;
      }
  return true;
}


bool ChapModel::haplotypesInSameGroup(int h1, int h2)
{
  map<int,int>::iterator i1 = haploGroup.find(h1);
  map<int,int>::iterator i2 = haploGroup.find(h2);
  
  if ( i1 == haploGroup.end() ||
       i2 == haploGroup.end() )
    return true;

  if ( i1 == haploGroup.end() ||
       i2 == haploGroup.end() )
    error("Internal problem in ChapModel...");

  return ( i1->second == i2->second );
  
}


void Chap::setSNPList(vector<int> & snplist, ChapModel & model)
{

  boolvec_t snpmask(H->ns,false);
  for (int l=0;l<snplist.size(); l++)
    for ( int s=0; s < H->ns; s++)
      if ( H->S[s] == snplist[l] )
	snpmask[s] = true;		      
  
  map<int,int> subhaplotypes = H->makeSubHaplotypeSet(snpmask);
  
  model.group.clear();
  int cnt=0;
  map<int,int> added;
  for (int h = 0; h < H->nh; h++)
    {	      
      if ( H->f[h] >= par::min_hf )
	{		  
	  int g = subhaplotypes.find(h)->second;
	  map<int,int>::iterator gi = added.find(g);
	  if ( gi == added.end() )
	    {
	      added.insert(make_pair(g,cnt));
	      cnt++;
	      set<int> t;
	      t.insert(h);
	      model.group.push_back(t);
	    }
	  else
	    model.group[ added.find(g)->second ].insert(h);
	}
    }
}


void displayHaploGroups(ofstream & CH, ChapModel & m, HaploPhase * haplo)
{
  bool closeThenEnd = false;
  int cnt = 0;
  CH << "   ";
  for (int h=0; h < m.group.size(); h++)
    {

      CH << "{ ";
      set<int>::iterator ih = m.group[h].begin();

      int cnt2 = m.group[h].size();
      while ( ih != m.group[h].end() )
	{
	  if ( cnt>0 && cnt2 < m.group[h].size() ) 
	    CH << ", ";
	  CH << haplo->haplotypeName( *ih );
  
	  ++cnt;
	  --cnt2;

	  if ( cnt * haplo->ns > 40 ) 
	    {

	      if ( cnt2 == 0) 
		closeThenEnd = true;
	      else
		{
		  CH << "\n     ";
		  cnt = 0;
		}
	    }
  
	  ++ih;
	}
      // Close group      
      CH << " }  ";

      if ( closeThenEnd )
	{
	  CH << "\n   ";
	  closeThenEnd = false;
	  cnt=0;
	}
    }
  CH << "\n";

}