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
|
//////////////////////////////////////////////////////////////////
// //
// 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 <assert.h>
#include "plink.h"
#include "options.h"
#include "phase.h"
#include "helper.h"
#include "genogroup.h"
#include "haplowindow.h"
extern ofstream LOG;
using namespace std;
string HaploPhase::haplotypeName(int h)
{
string str;
for (int s=0; s<ns; s++)
{
string a1 = P.locus[S[s]]->allele1;
string a2 = P.locus[S[s]]->allele2;
if ( a1 == "" ) a1 = "X";
if ( a2 == "" ) a2 = "X";
if (h == -1)
str += "-"; // haploid gap
else if (hap[h][s])
str += a1;
else
str += a2;
}
return str;
}
void HaploPhase::imputeAllHaplotypes()
{
///////////////////////////////////////////////
// Impute missing SNPs -- create a new datafile
// Imputation rules:
// Missing predictor allele -> missing haplotype
// P(H|G) < 0.8 (default) -> missing haplotype
// Make space to new, imputed haplotype calls
new_one.resize(P.n);
new_two.resize(P.n);
/////////////////////////////////
// Phase all specified haplotypes
phaseAllHaplotypes(true,*P.pperm);
///////////////////////////
// Write new PED file
P.printLOG("Imputing genotypes with P(H|G) threshold of " + dbl2str( par::hap_post_prob ) + "\n\n");
string filename = par::output_file_name + ".impute.ped";
P.printLOG("Writing imputed ped file to [ " + filename + " ] \n");
ofstream PED(filename.c_str(), ios::out);
PED.clear();
for (int i=0; i<P.n; i++)
{
Individual * person = P.sample[i];
PED << person->fid<< " "<< person->iid<< " "<< person->pat<< " "
<< person->mat<< " "<< person->sexcode<< " ";
if (par::bt)
PED << (int)person->phenotype;
else
PED << person->phenotype;
for (int l=0; l<new_one[i].size(); l++)
{
if ( (!new_one[i][l]) && (!new_two[i][l]))
PED << par::recode_delimit<< actual_map[l]->allele1<< " "
<< actual_map[l]->allele1;
else if ( (!new_one[i][l]) && new_two[i][l])
PED << par::recode_delimit<< actual_map[l]->allele1<< " "
<< actual_map[l]->allele2;
else if (new_one[i][l] && new_two[i][l])
PED << par::recode_delimit<< actual_map[l]->allele2<< " "
<< actual_map[l]->allele2;
else
PED << par::recode_delimit<< par::missing_genotype << " "
<< par::missing_genotype;
}
PED << "\n";
}
PED.close();
//////////////////
// Write new map
filename = par::output_file_name + ".impute.map";
P.printLOG("Writing imputed map file to [ " + filename + " ] \n");
ofstream MAP(filename.c_str(), ios::out);
MAP.clear();
for (int l=0; l < actual_map.size(); l++)
{
MAP << chromosomeName(actual_map[l]->chr) << "\t"
<< actual_map[l]->name<< "\t"
<< actual_map[l]->pos<< "\t"
<< actual_map[l]->bp<< "\n";
}
MAP.close();
}
void HaploPhase::calculateHaplotypeFrequencies()
{
string f = par::output_file_name + ".frq.hap";
if (par::display_hap_freqs)
{
P.printLOG("Writing haplotype frequencies to [ " + f + " ]\n");
HFRQ.open(f.c_str(), ios::out);
HFRQ.precision(4);
HFRQ << setw(10) << "LOCUS"<< " "<< setw(12) << "HAPLOTYPE"<< " "
<< setw(10) << "F"<< "\n";
}
// Phase all SNPs (with frequency flag set, this routine
// will write haplotype frequencies to HFRQ
P.haplo->phaseAllHaplotypes(true,*P.pperm);
if (par::display_hap_freqs)
HFRQ.close();
// So we do not re-write them
par::display_hap_freqs = false;
}
void HaploPhase::imputeThisHaplotype(int l)
{
////////////////////////////////////////////////////
// Impute for all individiuals, if common haplotype
double w = 0;
double c = 0;
if (testHaplotypeFreq() >= par::min_hf &&
testHaplotypeFreq() <= par::max_hf )
{
for (int i=0; i<P.n; i++)
{
bool b1, b2;
// Haplotype-weighting
double t = imputeHaplotypes(i, b1, b2);
if (t>=0)
{
w += t;
c++;
};
// And set new imputed genotypes
new_one[i].push_back(b1);
new_two[i].push_back(b2);
}
/////////////////////////////////////////////
// Add to map of actually imputed haplotypes
Locus * loc = new Locus;
loc->chr = new_map[l]->chr;
loc->name = hname+"_"+haplotypeName(test_hap)+"_";
loc->bp = new_map[l]->bp;
loc->pos = new_map[l]->pos;
loc->allele1 = new_map[l]->allele1;
loc->allele2 = new_map[l]->allele2;
actual_map.push_back( loc );
}
}
/////////////////////////////////////////////
// Legacy function: now redundant
void HaploPhase::enumerateAllPhases()
{
// Note: this function is no longer called
// For individuals w/out parents: make a list of all possible
// phases. Note: currently, we do not use this (i.e. we always
// require father and mother to be 'observed' (i.e. genotyped and
// adequately phased).
// Also note: issue with representing heterozygote haplotypes twice
// in list: previously we did not, but we now change this (seeing as
// it is never used in any case...)
// Also: now we build separate lists for diploid and haploid
// chromosomes, not that we use either.
// Diploid possible phases
if ( !haploid )
{
for (int h1=0; h1<nh; h1++)
for (int h2=0; h2<nh; h2++)
{
double freq = f[h1] * f[h2];
if (h1!=h2)
freq *= 2;
if (freq >= par::hap_min_phase_prob )
{
ph_freq.push_back(freq );
ph_hap1.push_back(h1 );
ph_hap2.push_back(h2 );
}
}
}
// Haploid possible phases
if (haploid || X )
{
for (int h1=0; h1<nh; h1++)
{
double freq = f[h1];
if (freq >= par::hap_min_phase_prob )
{
haploid_ph_freq.push_back(freq );
haploid_ph_hap1.push_back(h1 );
}
}
}
// Original total number of phases
np = ph_hap1.size();
haploid_np = haploid_ph_hap1.size();
}
// Legacy function: now redundant
/////////////////////////////////////////////
//////////////////////////////////////////////////
// Return a list of all possible haplotype names
vector<string> HaploPhase::returnHaplotypes(vector<int> & slist)
{
vector<string> str;
enumerateHaplotypes(slist );
for (int h=0; h<hap.size(); h++)
{
string hstr;
for (int s=0; s<ns; s++)
if (!hap[h][s])
hstr += P.locus[S[s]]->allele1;
else if (P.locus[S[s]]->allele2=="")
hstr += "0";
else
hstr += P.locus[S[s]]->allele2;
str.push_back(hstr);
}
return str;
}
//////////////////////////////////////////////////
// For multi-marker imputation and certain tasks,
// we require a 'test' haplotype
void HaploPhase::setTestHaplotype(string t)
{
// No specified test haplotype?
if ( t == "" )
{
test_hap = -1;
return;
}
// Create match template
vector<bool> tmp(ns, false);
for (int s=0; s<ns; s++)
if (P.locus[S[s]]->allele1 == t.substr(s, 1) )
tmp[s] = true;
// Consider each haplotype
test_hap = -1;
for (int h=0; h<hap.size(); h++)
{
bool match = true;
for (int s=0; s<ns; s++)
{
if (hap[h][s] != tmp[s])
{
match = false;
break;
}
}
if (match)
{
test_hap = h;
break;
}
}
}
void HaploPhase::reportHaplotypeFrequencies()
{
for (int h=0; h<nh; h++)
{
if (f[h] >= par::min_hf)
{
HFRQ << setw(10) << hname << " "<< setw(12) << haplotypeName(h)
<< " "<< setw(10) << f[h]<< "\n";
}
}
}
void HaploPhase::reportPhase()
{
string fn = par::output_file_name+".phase-"+hname;
ofstream PHASE(fn.c_str(), ios::out);
P.printLOG("Writing phased haplotypes for "+ hname + " to [ "+ fn + " ]\n");
PHASE << setw(par::pp_maxfid) << "FID" << " "
<< setw(par::pp_maxiid) << "IID"<< " "
<< setw(4) << "PH"<< " "
<< setw(10) << "HAP1"<< " "
<< setw(10) << "HAP2"<< " "
<< setw(12) << "POSTPROB"<< " "
// << setw(12) << "WEIGHT" << " "
<< setw(6) << "BEST"<< " "<< "\n";
PHASE.precision(4);
for (int i = 0; i < P.n; i++)
{
if (include[i])
{
for (int z = 0; z < hap1[i].size(); z++)
{
PHASE << setw(par::pp_maxfid) << P.sample[i]->fid<< " "
<< setw(par::pp_maxiid) << P.sample[i]->iid<< " "
<< setw(4) << z << " "
<< setw(10) << haplotypeName(hap1[i][z]) << " ";
if (haploid || (X && P.sample[i]->sex))
PHASE << setw(10) << haplotypeName( -1 ) << " ";
else
PHASE << setw(10) << haplotypeName(hap2[i][z]) << " ";
if (ambig[i])
{
PHASE << setw(12) << pp[i][z]<< " ";
int max_z = 0;
for (int z2=0; z2<hap1[i].size(); z2++)
max_z = pp[i][z2] > pp[i][max_z] ? z2 : max_z ;
if (max_z == z)
PHASE << setw(6) << 1<< " "<< " ";
else
PHASE << setw(6) << 0<< " "<< " ";
}
else
PHASE << setw(12) << 1<< " "<< setw(6) << 1<< " "<< " ";
// Genotypes
//for (int s=0; s<ns; s++)
//PHASE << genotype(P, i, S[s]) << " ";
PHASE << "\n";
}
}
// Report also on excluded individuals
// (Should be 0-size phase-set)
else
{
PHASE << setw(par::pp_maxfid) << P.sample[i]->fid << " "
<< setw(par::pp_maxiid) << P.sample[i]->iid << " "
<< setw(4) << "NA" << " "
<< setw(10) << "NA" << " "
<< setw(10) << "NA" << " "
<< setw(12) << "NA" << " "
<< setw(6) << "NA"<< " ";
// genotypes
// for (int s=0; s<ns; s++)
// PHASE << genotype(P, i, S[s]) << " ";
PHASE << "\n";
}
}
PHASE.close();
}
void HaploPhase::reportPhaseWideFormat()
{
string fn = par::output_file_name+".wphase-"+hname;
ofstream PHASE(fn.c_str(), ios::out);
P.printLOG("Writing wide-format phased haplotypes for "+ hname + " to [ "
+ fn + " ]\n");
PHASE << setw(par::pp_maxfid) << "FID"<< " "<< setw(par::pp_maxiid)
<< "IID"<< " ";
for (int h=0; h<nh; h++)
if (f[h] >= par::min_hf)
PHASE << setw(8) << "H_"+haplotypeName(h) << " ";
PHASE << "\n";
PHASE.precision(4);
for (int i = 0; i < P.n; i++)
{
if (include[i])
{
PHASE << setw(par::pp_maxfid) << P.sample[i]->fid<< " "
<< setw(par::pp_maxiid) << P.sample[i]->iid<< " ";
vector_t hcnt(nh, 0);
for (int z = 0; z < hap1[i].size(); z++)
{
if (ambig[i])
{
hcnt[hap1[i][z]] += pp[i][z];
if ( ! (haploid || (X && P.sample[i]->sex)))
hcnt[hap2[i][z]] += pp[i][z];
}
else
{
hcnt[hap1[i][z]] ++;
if ( ! (haploid || (X && P.sample[i]->sex)))
hcnt[hap2[i][z]] ++;
}
}
for (int h=0; h<nh; h++)
if (f[h] >= par::min_hf)
PHASE << setw(8) << hcnt[h]<< " ";
PHASE << "\n";
}
// Report also on excluded individuals
// (Should be 0-size phase-set)
else
{
PHASE << setw(par::pp_maxfid) << P.sample[i]->fid<< " "
<< setw(par::pp_maxiid) << P.sample[i]->iid<< " ";
for (int h=0; h<nh; h++)
if (f[h] >= par::min_hf)
PHASE << setw(8) << "NA"<< " ";
PHASE << "\n";
}
}
PHASE.close();
}
map<int,int> HaploPhase::makeSubHaplotypeSet(boolvec_t & mask)
{
map<int,int> t;
map<boolvec_t,int> shap;
int cnt=0;
for (int h=0; h < nh; h++)
{
boolvec_t sh;
for (int s = 0; s < ns ; s++)
{
if (mask[s])
sh.push_back(hap[h][s]);
}
map<boolvec_t,int>::iterator si = shap.find(sh);
if ( si == shap.end() )
{
shap.insert(make_pair(sh,cnt));
t.insert(make_pair(h,cnt));
++cnt;
}
else
t.insert(make_pair(h, si->second));
}
return t;
}
map<int,int> HaploPhase::makeTestSet(boolvec_t & mask, boolvec_t & allele)
{
map<int,int> tests;
for (int h2=0; h2 < nh; h2++)
{
bool is_A = true;
for (int s = 0; s < ns ; s++)
{
if (mask[s] && hap[h2][s] != allele[s])
is_A = false;
}
if (is_A )
tests.insert(make_pair(h2, 0));
else
tests.insert(make_pair(h2, 1));
}
return tests;
}
string HaploPhase::getSubHaplotypeName(boolvec_t & mask, boolvec_t & allele,
int blank)
{
string str = "";
for (int s=0; s < ns; s++)
{
if (s == blank )
str += " ";
else if (mask[s])
{
if (allele[s])
str += P.locus[ S[s] ]->allele1;
else
str += P.locus[ S[s] ]->allele2;
}
else
str += ".";
}
return str;
}
vector_t HaploPhase::imputeGenotype(int i, int l)
{
// Probability of AA, AB and BB for position 'l'
// (of ns SNPs) for individual 'i'
vector_t g(3);
if (X || haploid )
{
g[0] = g[1] = g[2] = 0;
return g;
error("HaploPhase::imputeGenotypess() not yet set up for X \n");
}
// Not able to be imputed?
if (!include[i])
{
g[0] = g[1] = g[2] = 0;
return g;
}
// Unambiguous imputation?
if (!ambig[i])
{
int h1 = hap1[i][0];
int h2 = hap2[i][0];
bool s1 = hap[h1][l];
bool s2 = hap[h2][l];
if (s1 != s2 )
g[1] = 1;
else if (s1 )
g[0] = 1;
else
g[2] = 1;
return g;
}
// Weighted, ambiguous imputation?
for (int z=0; z<hap1[i].size(); z++)
{
// ?? include?? if (pp[i][max_z] >= par::hap_post_prob)
int h1 = hap1[i][z];
int h2 = hap2[i][z];
bool s1 = hap[h1][l];
bool s2 = hap[h2][l];
if (s1 != s2 )
g[1] += pp[i][z];
else if (s1 )
g[0] += pp[i][z];
else
g[2] += pp[i][z];
} // next possible phase
return g;
}
double HaploPhase::imputeHaplotypes(int i, bool & n1, bool & n2)
{
// if ( X || haploid )
// error("HaploPhase::imputeHaplotypes() not yet set up for X \n");
bool actualX = X && P.sample[i]->sex;
//////////////////////////////////////////////
// Based on P(H|G) impute inferred haplotypes
// for above-threshold individuals
// Not imputed
double w = -1;
if ( ! include[i] )
{
n1 = true;
n2 = false;
return w;
}
// First for individuals of unambiguous phase
if (!ambig[i])
{
if (hap1[i][0] == test_hap)
n1 = false;
else
n1 = true;
if ( actualX || haploid )
{
n2 = n1;
}
else
{
if (hap2[i][0] == test_hap)
n2 = false;
else
n2 = true;
}
// Resolve potential het/missing coding confusion
if (n1 && (!n2))
{
n1 = false;
n2 = true;
}
// Unambiguous weighting (0, 1 or 2 copie of test_hap)
if (!n1)
{
if ( actualX || haploid )
w=1;
else
{
if (!n2)
w = 2;
else
w = 1;
}
}
else
w = 0;
}
else
{
// Second, for ambiguous individuals impute and assign weight
int max_z = 0;
for (int z=0; z<hap1[i].size(); z++)
max_z = pp[i][z] > pp[i][max_z] ? z : max_z ;
// Set missing by default
n1 = true;
n2 = false;
// Consider each phase z
// Above threshold?
if (pp[i][max_z] >= par::hap_post_prob)
{
// Do we match 'test_hap' ( '1' allele )
// or not? ( '2' allele )
if (hap1[i][max_z] == test_hap)
n1 = false;
else
n1 = true;
if ( actualX || haploid )
{
n2 = n1;
}
else
{
if (hap2[i][max_z] == test_hap)
n2 = false;
else
n2 = true;
}
// Resolve potential het/missing coding confusion
if (n1 && (!n2))
{
n1 = false;
n2 = true;
}
// Unambiguous weighting (1 or 2 copies of test_hap)
// We are saying either 0, 1 or 2 copies
// Consider each haplotype
// Number imputed / Actual number
for (int z=0; z<hap1[i].size(); z++)
{
if (hap1[i][z] == test_hap)
w += pp[i][z];
if ( ! ( actualX || haploid ))
{
if (hap2[i][z] == test_hap)
w += pp[i][z];
}
}
w = pp[i][max_z]/ w;
}
}
return w;
}
double HaploPhase::rsq_internal(int s1, int s2)
{
// A convenience function for SNP x SNP r^2
// i.e. here it does not matter which allele
// we consider, so just re-use mask
if (s1 > ns || s2 > ns )
error("Problem in rsq_internal(int,int)");
boolvec_t m1(ns, false);
boolvec_t m2(ns, false);
m1[s1] = true;
m2[s2] = true;
return rsq_internal(m1, m1, m2, m2);
}
double HaploPhase::rsq_internal(boolvec_t & mask1, boolvec_t & alleles1,
boolvec_t & mask2, boolvec_t & alleles2)
{
// Assume f[] has been populated with sensible values
// and hap[][] contains alleles
if (mask1.size() != ns ||mask2.size() != ns ||alleles1.size() != ns
||alleles2.size() != ns )
{
cout << ns << " "
<< mask1.size() << " "
<< mask2.size() << " "
<< alleles1.size() << " "
<< alleles2.size() << "\n";
error("Internal error in Phase::rsq");
}
// ---X-X- mask1
// 0-0 alleles1
// ----X-- mask2
// 1 alleles2
// i.e. find r^2 between 00 haplotype made of SNPs 4 & 6
// from 7 SNP haplotype with allele 1 of SNP 5
// Calculate frequency of first haplotype (fA)
double fA = 0;
double fB = 0;
double fAB = 0, fAb = 0, faB = 0, fab = 0;
for (int h = 0; h < nh; h++)
{
bool is_A = true;
bool is_B = true;
bool is_AB = true;
bool is_Ab = true;
bool is_aB = true;
for (int s = 0; s < ns ; s++)
{
if (mask1[s] && hap[h][s] != alleles1[s])
is_A = false;
if (mask2[s] && hap[h][s] != alleles2[s])
is_B = false;
if ( (mask1[s] && hap[h][s] != alleles1[s])
|| (mask2[s] && hap[h][s] != alleles2[s]))
is_AB = false;
if ( (mask1[s] && hap[h][s] != alleles1[s])
|| (mask2[s] && hap[h][s] == alleles2[s]))
is_Ab = false;
if ( (mask1[s] && hap[h][s] == alleles1[s])
|| (mask2[s] && hap[h][s] != alleles2[s]))
is_aB = false;
}
if (is_A )
fA += f[h];
if (is_B )
fB += f[h];
if (is_AB )
fAB += f[h];
else if (is_aB )
faB += f[h];
else if (is_Ab )
fAb += f[h];
else
fab += f[h];
// Next haplotype
}
double fa = 1 - fA;
double fb = 1 - fB;
// Calculate either r-sq or D'
double D = fAB - fA * fB;
if ( calculateDp )
{
double dmax1 = D > 0 ? fA * fb : fA * fB;
double dmax2 = D > 0 ? fa * fB : fa * fb;
double dmax = dmax1 < dmax2 ? dmax1 : dmax2;
if ( dmax == 0 )
return -1;
return D / dmax;
}
else
{
double denom = fA * fa * fB * fb;
if (denom == 0)
return -1;
return (D*D) / denom;
}
}
double HaploPhase::freq(boolvec_t & mask1, boolvec_t & alleles1)
{
// Assume f[] has been populated with sensible values
// and hap[][] contains alleles
if (mask1.size() != ns ||alleles1.size() != ns )
{
cout << ns << " "
<< mask1.size() << " "
<< alleles1.size() << "\n";
error("Internal error in Phase::freq");
}
// ---X-X- mask1
// 0-0 alleles1
double fA = 0;
for (int h = 0; h < nh; h++)
{
bool is_A = true;
for (int s = 0; s < ns ; s++)
{
if (mask1[s] && hap[h][s] != alleles1[s])
is_A = false;
}
if (is_A )
fA += f[h];
// Next haplotype
}
return fA;
}
double HaploPhase::rsq(int l1, int l2)
{
reset();
new_pred_locus.resize(1);
new_map.resize(1);
vector<int> twoSNPs(2);
twoSNPs[0] = l1;
twoSNPs[1] = l2;
new_pred_locus[0] = twoSNPs;
new_map[0] = P.locus[l1];
bool old_silent = par::silent;
par::silent = true;
new_pred_allele = listPossibleHaplotypes(P, new_pred_locus[0]);
phaseAllHaplotypes(true,*P.pperm);
// hname = locus[l]->name;
par::silent = old_silent;
return rsq_internal(0, 1);
}
double HaploPhase::dprime(int l1, int l2)
{
calculateDp = true;
double dp = rsq(l1,l2);
calculateDp = false;
return fabs(dp);
}
void Plink::calcPairwiseLD()
{
int l1 = getMarkerNumber(*this, par::ld_SNP1);
int l2 = getMarkerNumber(*this, par::ld_SNP2);
if (l1 == l2 )
error("Cannot compute LD with self");
if (l1 == -1)
error("--ld {marker} {marker}: first marker not found");
if (l2 == -1)
error("--ld {marker} {marker}: second marker not found");
printLOG("\nLD information for SNP pair [ "+ par::ld_SNP1 + " "
+ par::ld_SNP2 + " ]\n\n");
printLOG(" R-sq = " + dbl2str_fixed(haplo->rsq(l1, l2) , 3 ) + " ");
printLOG("D' = " + dbl2str_fixed(haplo->dprime(l1, l2) , 3 ) + "\n\n");
printLOG(" Haplotype Frequency Expectation under LE\n");
printLOG(" --------- --------- --------------------\n");
for (int h=0; h < haplo->nh; h++)
{
printLOG(" " + haplo->haplotypeName(h) + " " );
printLOG(dbl2str_fixed( haplo->f[h] ,3) + " ");
double e = 0;
if ( haplo->haplotypeName(h) == locus[l1]->allele2 + locus[l2]->allele2 )
e = (1 - locus[l1]->freq)*(1 - locus[l2]->freq);
else if ( haplo->haplotypeName(h) == locus[l1]->allele1 + locus[l2]->allele2 )
e = ( locus[l1]->freq)*(1 - locus[l2]->freq);
else if ( haplo->haplotypeName(h) == locus[l1]->allele2 + locus[l2]->allele1 )
e = (1 - locus[l1]->freq)*( locus[l2]->freq);
else if ( haplo->haplotypeName(h) == locus[l1]->allele1 + locus[l2]->allele1 )
e = ( locus[l1]->freq)*( locus[l2]->freq);
printLOG(dbl2str_fixed( e ,3 ) + "\n");
}
printLOG("\n");
int ch = 0;
for (int h=0; h < haplo->nh; h++)
if ( haplo->haplotypeName(h) == locus[l1]->allele2 + locus[l2]->allele2 )
ch = h;
// Is D positive or negative?
string s;
if ( haplo->f[ch] > (1 - locus[l1]->freq)*(1 - locus[l2]->freq) )
s = locus[l1]->allele1 + locus[l2]->allele1 + "/" + locus[l1]->allele2 + locus[l2]->allele2;
else
s = locus[l1]->allele1 + locus[l2]->allele2 + "/" + locus[l1]->allele2 + locus[l2]->allele1;
printLOG(" In phase alleles are " + s + "\n");
return;
}
///////////////////////////////////////////////////////////////
// //
// For a particular pair of individuals, track the status //
// of haplotype sharing across the chromosome/region; this //
// is the driver function //
// //
///////////////////////////////////////////////////////////////
void HaploPhase::trackSharedHaplotypes()
{
// Find individual(s) to track
p1 = -1;
p2 = -1;
for (int i=0; i<P.n; i++)
{
if ( P.sample[i]->fid == par::segment_haplotrack_fid1 &&
P.sample[i]->iid == par::segment_haplotrack_iid1 )
{
p1 = i;
}
if ( P.sample[i]->fid == par::segment_haplotrack_fid2 &&
P.sample[i]->iid == par::segment_haplotrack_iid2 )
{
p2 = i;
}
if ( p1 != -1 && p2 != -1 )
break;
}
if ( p1 == -1 || p2 == -1 )
{
error("Problem finding individual(s) indicated in haplo-track option\n");
return;
}
// Set whether looking at homozygosity of shared segments
homozyg = p1 == p2;
Individual * person1 = P.sample[p1];
Individual * person2 = P.sample[p2];
if ( homozyg )
P.printLOG("\nReport for individual [ " + person1->fid + " " + person1->iid + " ]\n");
else
P.printLOG("\nReport for pair [ " + person1->fid + " " + person1->iid
+ ", "+ person2->fid + " " + person2->iid + " ]\n");
string f = par::output_file_name + ".shared";
P.printLOG("Tracking shared haplotypes, writing output to [ " + f + " ]\n");
HFRQ.open(f.c_str(), ios::out);
HFRQ.precision(4);
HFRQ << setw(4) << "CHR" << " "
<< setw(par::pp_maxsnp) << "SNP" << " "
<< "\n";
trackedIBS.resize(P.nl_all);
trackedN.resize(P.nl_all);
////////////////////
// Do all the work
P.haplo->phaseAllHaplotypes(true,*P.pperm);
// Display
for (int l=0; l<P.nl_all; l++)
{
HFRQ << P.locus[l]->name << "\t"
<< P.locus[l]->bp << "\t"
<< trackedIBS[l] << "\t"
<< trackedN[l] << "\t"
<< (double)trackedIBS[l]/(double)trackedN[l] << "\n";
}
if (par::display_hap_freqs)
HFRQ.close();
}
///////////////////////////////////////////////////////////////
// //
// For a particular pair of individuals, track the status //
// of haplotype sharing across the chromosome/region; this //
// function does the actual work
// //
///////////////////////////////////////////////////////////////
void HaploPhase::trackThisSegment()
{
// Are the chromosomes consistent with a shared segment at this position?
// No information? Then exit
if ( ! ( include[p1] && include[p2] ) )
return;
if ( haploid
|| (X && P.sample[p1]->sex)
|| (X && P.sample[p2]->sex) )
error("Cannot use haplo-track options on non-autosomal chromosomes yet");
// Looking within an individual for homozygous segments?
if ( homozyg )
{
double probHomozyg = 0;
for (int z = 0; z < hap1[p1].size(); z++)
{
// Is this region shared...
if ( hap1[p1][z] == hap2[p1][z] )
{
// ...and rare?
if ( f[ hap1[p1][z] ] < 0.02 )
{
if ( ambig[p1] )
probHomozyg += pp[p1][z];
else
probHomozyg = 1;
}
}
}
}
else // ... or looking between individuals for shared segments?
{
double probShared = 0;
int j=0;
for (int z1 = 0; z1 < hap1[p1].size(); z1++)
for (int z2 = 0; z2 < hap1[p2].size(); z2++)
{
// Figure IBS 0, 1 or 2
int a1 = hap1[p1][z1];
int a2 = hap2[p1][z1];
int b1 = hap1[p2][z2];
int b2 = hap2[p2][z2];
double prob = 1;
if ( ambig[p1] )
prob *= pp[p1][z1];
if ( ambig[p2] )
prob *= pp[p2][z2];
if ( a1 > a2 )
{
int tmp = a1;
a1 = a2;
a2 = tmp;
}
if ( b1 > b2 )
{
int tmp = b1;
b1 = b2;
b2 = tmp;
}
// Count up similar, rare haplotypes
int cnt =0 ;
if ( a1 == b1 && f[a1] < .2 )
{
probShared += 0.5 * prob;
cnt++;
}
if ( a2 == b2 && f[a2] < .2 )
{
probShared += 0.5 * prob;
cnt++;
}
// Keep track
for ( int s = 0; s < ns ; s++ )
{
trackedIBS[S[s]] += probShared;
trackedN[S[s]]++;
}
// next pair of haplotypes
}
}
}
///////////////////////////////////////////////////////////////
// //
// Return a set of haplotype number codes given the type of //
// mask + allele template used in the proxy association //
// procedures //
// //
///////////////////////////////////////////////////////////////
set<int> HaploPhase::returnHaplotypeSet(boolvec_t & mask,
boolvec_t & alleles)
{
set<int> hs;
for (int h = 0; h < nh; h++)
{
bool is_A = true;
for (int s = 0; s < ns ; s++)
{
if (mask[s] && hap[h][s] != alleles[s])
is_A = false;
}
if (is_A)
hs.insert(h);
}
return hs;
}
void HaploPhase::calculateEmpiricalVariance(int h)
{
set<int> hs;
hs.insert(h);
calculateEmpiricalVariance(hs);
}
///////////////////////////////////////////////////////////////
// //
// Post-phasing, for a group of haplotypes, return the //
// empirical variance and ratio of this to asymptotic //
// variance for all individuals //
// //
///////////////////////////////////////////////////////////////
void HaploPhase::calculateEmpiricalVariance(set<int> & hs)
{
double frequency = 0;
set<int>::iterator h = hs.begin();
while ( h != hs.end() )
{
frequency += f[*h];
++h;
}
// Do we need to consider this haplotype/set of
// haplotypes?
if( frequency < 0.0000001 )
{
ratio = 0;
empiricalVariance = 0;
return;
}
// Calculate theoretical variance of frequency given binomial
double theoreticalVariance = frequency * ( 1 - frequency );
double weightedVariance = 0;
double dosageSSQ = 0;
double haplotypeCount = 0;
// Calculate empirical variance given imputed haplotype counts:
int ncnt = 0; // for allele count
int dosageCount = 0; // for dosage (individual) count
for( int i = 0; i < P.n; i++ )
{
if ( include[i] )
{
if ( (!X) || !P.sample[i]->sex )
{
if (!ambig[i])
{
if( hs.find( hap1[i][0] ) != hs.end() )
haplotypeCount += 1;
if( hs.find( hap2[i][0] ) != hs.end() )
haplotypeCount += 1;
}
else
for( int z = 0; z < pp[i].size(); z++ )
{
if( hs.find( hap1[i][z] ) != hs.end() )
haplotypeCount += pp[i][z];
if( hs.find( hap2[i][z] ) != hs.end() )
haplotypeCount += pp[i][z];
}
ncnt+=2;
dosageCount++;
}
}
}
double mean = haplotypeCount/(double)ncnt;
double dmean = haplotypeCount/(double)dosageCount;
// Ratio of variance of weighted versus variance of averages
// (i.e. dosage -- this measures information loss, as the deflation
// is only for the dosage))
// Calculate variance: S(x-mean)^2/(n-1)
for( int i = 0; i < P.n; i++ )
{
if ( include[i] )
{
if ( (!X) || !P.sample[i]->sex )
{
double dosage = 0;
if (!ambig[i])
{
if( hs.find( hap1[i][0] ) != hs.end() )
{
weightedVariance += (1-mean) * (1-mean);
dosage++;
}
else
weightedVariance += mean*mean; // (0-mean)^2
if( hs.find( hap2[i][0] ) != hs.end() )
{
weightedVariance += (1-mean) * (1-mean);
dosage++;
}
else
weightedVariance += mean*mean;
dosageSSQ += (dosage-dmean)*(dosage-dmean);
}
else
{
// Variance based on weights
for( int z = 0; z < pp[i].size(); z++ )
{
if( hs.find( hap1[i][z] ) != hs.end() )
{
weightedVariance += pp[i][z] * (1-mean) * (1-mean);
dosage += pp[i][z];
}
else
weightedVariance += pp[i][z] * mean *mean;
if( hs.find( hap2[i][z] ) != hs.end() )
{
weightedVariance += pp[i][z] * (1-mean) * (1-mean);
dosage += pp[i][z];
}
else
weightedVariance += pp[i][z] * mean * mean;
}
dosageSSQ += (dosage-dmean)*(dosage-dmean);
}
}
}
}
// Use N, not N-1 denominator, as we are comparing to the expected
// variance above (i.e. so ratio == 1 in case of complete
// information)
// Update variables in HaploPhase
weightedVariance /= (double)ncnt;
empiricalVariance = dosageSSQ / ((double)dosageCount*2);
ratio = theoreticalVariance > 0 ? empiricalVariance / theoreticalVariance : 0;
}
///////////////////////////////////////////////////////////////
// //
// Verbose display function for phasing routine //
// //
///////////////////////////////////////////////////////////////
void HaploPhase::verboseDisplayWindows(int i, bool use_ref )
{
if ( ! include[i] )
return;
for (int w = startWindow;
w <= finishWindow ; w++)
{
int r = windows[w]->genoGroup[i]->reference;
if ( ! use_ref )
r = i;
HaploWindow * thisWindow = windows[w];
VPHASE << "WINDOW " << w << ": "
<< windows[w]->start << " to "
<< windows[w]->stop
<< " ( " << windows[w]->ns << " SNPs )\n";
for ( int s = 0 ; s < windows[w]->ns ; s++ )
VPHASE << P.locus[ thisWindow->S[s]]->name << " ";
VPHASE << "\n";
// Display real genotypes
VPHASE << setw(w) << " ";
for (int s=0; s< thisWindow->ns; s++)
{
bool s1 = par::SNP_major ?
P.SNP[ thisWindow->S[s] ]->one[i] :
P.sample[i]->one[ thisWindow->S[s] ];
bool s2 = par::SNP_major ?
P.SNP[ thisWindow->S[s] ]->two[i] :
P.sample[i]->two[ thisWindow->S[s] ];
if ( s1 )
{
if ( s2 )
VPHASE << P.locus[ thisWindow->S[s] ]->allele2 ;
else
VPHASE << "-";
}
else
{
if ( s2 )
VPHASE << P.locus[ thisWindow->S[s] ]->allele1 ;
else
VPHASE << P.locus[ thisWindow->S[s] ]->allele1 ;
}
}
VPHASE << " ";
for (int s=0; s< thisWindow->ns; s++)
{
bool s1 = par::SNP_major ?
P.SNP[ thisWindow->S[s] ]->one[i] :
P.sample[i]->one[ thisWindow->S[s] ];
bool s2 = par::SNP_major ?
P.SNP[ thisWindow->S[s] ]->two[i] :
P.sample[i]->two[ thisWindow->S[s] ];
if ( s1 )
{
if ( s2 )
VPHASE << P.locus[ thisWindow->S[s] ]->allele2 ;
else
VPHASE << "-";
}
else
{
if ( s2 )
VPHASE << P.locus[ thisWindow->S[s] ]->allele2 ;
else
VPHASE << P.locus[ thisWindow->S[s] ]->allele1 ;
}
}
VPHASE << "\n";
VPHASE << setw(w) << " ";
for (int s=0; s< thisWindow->ns; s++)
{
bool s1 = par::SNP_major ?
P.SNP[ thisWindow->S[s] ]->one[i] :
P.sample[i]->one[ thisWindow->S[s] ];
bool s2 = par::SNP_major ?
P.SNP[ thisWindow->S[s] ]->two[i] :
P.sample[i]->two[ thisWindow->S[s] ];
if ( s1 )
{
if ( s2 )
VPHASE << P.locus[ thisWindow->S[s] ]->allele2 ;
else
VPHASE << "-";
}
else
{
if ( s2 )
VPHASE << P.locus[ thisWindow->S[s] ]->allele1 ;
else
VPHASE << P.locus[ thisWindow->S[s] ]->allele1 ;
}
}
VPHASE << " ";
for (int s=0; s< thisWindow->ns; s++)
{
bool s1 = par::SNP_major ?
P.SNP[ thisWindow->S[s] ]->one[i] :
P.sample[i]->one[ thisWindow->S[s] ];
bool s2 = par::SNP_major ?
P.SNP[ thisWindow->S[s] ]->two[i] :
P.sample[i]->two[ thisWindow->S[s] ];
if ( s1 )
{
if ( s2 )
VPHASE << P.locus[ thisWindow->S[s] ]->allele2 ;
else
VPHASE << "-";
}
else
{
if ( s2 )
VPHASE << P.locus[ thisWindow->S[s] ]->allele2 ;
else
VPHASE << P.locus[ thisWindow->S[s] ]->allele1 ;
}
}
VPHASE << "\n";
for (int z = 0; z < windows[w]->hap1[r].size(); z++)
{
VPHASE << setw(w) << " "
<< thisWindow->haplotypeName(thisWindow->hap1[r][z])
<< "/"
<< thisWindow->haplotypeName(thisWindow->hap2[r][z])
<< " ";
VPHASE << "( "
<< thisWindow->f[ thisWindow->hap1[r][z] ] << " / "
<< thisWindow->f[ thisWindow->hap2[r][z] ] << " ) ";
if ( thisWindow->hap1[r].size() == 1)
VPHASE << "[1]\n";
else
VPHASE << thisWindow->pp[r][z]<< "\n";
}
}
}
|