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
|
// Author: Mark Chaisson
#pragma once
#include "BlasrUtils.hpp"
template <typename T_Sequence, typename T_RefSequence, typename T_SuffixArray,
typename T_TupleCountTable>
void MapRead(T_Sequence &read, T_Sequence &readRC, T_RefSequence &genome, T_SuffixArray &sarray,
BWT &bwt, SeqBoundaryFtr<FASTQSequence> &seqBoundary, T_TupleCountTable &ct,
SequenceIndexDatabase<FASTQSequence> &seqdb, MappingParameters ¶ms,
MappingMetrics &metrics, std::vector<T_AlignmentCandidate *> &alignmentPtrs,
MappingBuffers &mappingBuffers, MappingIPC *mapData, MappingSemaphores &semaphores)
{
bool matchFound;
WeightedIntervalSet topIntervals(params.nCandidates);
int numKeysMatched = 0, rcNumKeysMatched = 0;
(void)(numKeysMatched);
(void)(rcNumKeysMatched);
int expand = params.minExpand;
metrics.clocks.total.Tick();
int forwardNumBasesMatched = 0, reverseNumBasesMatched = 0;
do {
matchFound = false;
mappingBuffers.matchPosList.clear();
mappingBuffers.rcMatchPosList.clear();
alignmentPtrs.clear();
topIntervals.clear();
params.anchorParameters.expand = expand;
metrics.clocks.mapToGenome.Tick();
if (params.useSuffixArray) {
params.anchorParameters.lcpBoundsOutPtr = mapData->lcpBoundsOutPtr;
numKeysMatched = MapReadToGenome(genome, sarray, read, params.lookupTableLength,
mappingBuffers.matchPosList, params.anchorParameters);
//
// Only print values for the read in forward direction (and only
// the first read).
//
mapData->lcpBoundsOutPtr = NULL;
if (!params.forwardOnly) {
rcNumKeysMatched =
MapReadToGenome(genome, sarray, readRC, params.lookupTableLength,
mappingBuffers.rcMatchPosList, params.anchorParameters);
}
} else if (params.useBwt) {
numKeysMatched = MapReadToGenome(bwt, read, read.SubreadStart(), read.SubreadEnd(),
mappingBuffers.matchPosList, params.anchorParameters,
forwardNumBasesMatched);
if (!params.forwardOnly) {
rcNumKeysMatched = MapReadToGenome(
bwt, readRC, readRC.SubreadStart(), readRC.SubreadEnd(),
mappingBuffers.rcMatchPosList, params.anchorParameters, reverseNumBasesMatched);
}
}
//
// Look to see if only the anchors are printed.
if (params.anchorFileName != "") {
size_t i;
if (params.nProc > 1) {
#ifdef __APPLE__
sem_wait(semaphores.writer);
#else
sem_wait(&semaphores.writer);
#endif
}
*mapData->anchorFilePtr << read.title << std::endl;
for (i = 0; i < mappingBuffers.matchPosList.size(); i++) {
*mapData->anchorFilePtr << mappingBuffers.matchPosList[i] << std::endl;
}
*mapData->anchorFilePtr << readRC.title << " (RC) " << std::endl;
for (i = 0; i < mappingBuffers.rcMatchPosList.size(); i++) {
*mapData->anchorFilePtr << mappingBuffers.rcMatchPosList[i] << std::endl;
}
if (params.nProc > 1) {
#ifdef __APPLE__
sem_post(semaphores.writer);
#else
sem_post(&semaphores.writer);
#endif
}
}
metrics.totalAnchors +=
mappingBuffers.matchPosList.size() + mappingBuffers.rcMatchPosList.size();
metrics.clocks.mapToGenome.Tock();
metrics.clocks.sortMatchPosList.Tick();
SortMatchPosList(mappingBuffers.matchPosList);
SortMatchPosList(mappingBuffers.rcMatchPosList);
metrics.clocks.sortMatchPosList.Tock();
PValueWeightor lisPValue(read, genome, ct.tm, &ct);
MultiplicityPValueWeightor lisPValueByWeight(genome);
LISSumOfLogPWeightor<T_GenomeSequence, std::vector<ChainedMatchPos> > lisPValueByLogSum(
genome);
LISSizeWeightor<std::vector<ChainedMatchPos> > lisWeightFn;
IntervalSearchParameters intervalSearchParameters;
intervalSearchParameters.globalChainType = params.globalChainType;
intervalSearchParameters.advanceHalf = params.advanceHalf;
intervalSearchParameters.warp = params.warp;
intervalSearchParameters.fastMaxInterval = params.fastMaxInterval;
intervalSearchParameters.aggressiveIntervalCut = params.aggressiveIntervalCut;
intervalSearchParameters.verbosity = params.verbosity;
//
// If specified, only align a band from the anchors.
//
DNALength squareRefLength = read.length * 1.25 + params.limsAlign;
if (params.limsAlign != 0) {
size_t fi;
for (fi = 0; fi < mappingBuffers.matchPosList.size(); fi++) {
if (mappingBuffers.matchPosList[fi].t >= squareRefLength) {
break;
}
}
if (fi < mappingBuffers.matchPosList.size()) {
mappingBuffers.matchPosList.resize(fi);
}
}
metrics.clocks.findMaxIncreasingInterval.Tick();
//
// For now say that something that has a 50% chance of happening
// by chance is too high of a p value. This is probably many times
// the size.
//
intervalSearchParameters.maxPValue = log(0.5);
intervalSearchParameters.aboveCategoryPValue = -300;
VarianceAccumulator<float> accumPValue;
VarianceAccumulator<float> accumWeight;
VarianceAccumulator<float> accumNBases;
mappingBuffers.clusterList.Clear();
mappingBuffers.revStrandClusterList.Clear();
//
// Remove anchors that are fully encompassed by longer ones. This
// speeds up limstemplate a lot.
//
RemoveOverlappingAnchors(mappingBuffers.matchPosList);
RemoveOverlappingAnchors(mappingBuffers.rcMatchPosList);
if (params.pValueType == 0) {
if (params.printDotPlots) {
std::ofstream dotPlotOut;
std::string dotPlotName = std::string(read.title) + ".anchors";
CrucialOpen(dotPlotName, dotPlotOut, std::ios::out);
for (size_t mp = 0; mp < mappingBuffers.matchPosList.size(); mp++) {
dotPlotOut << mappingBuffers.matchPosList[mp].q << " "
<< mappingBuffers.matchPosList[mp].t << " "
<< mappingBuffers.matchPosList[mp].l << " " << std::endl;
}
dotPlotOut.close();
}
/*
This is an optimization that is being tested out that places a grid over the
area where there are anchors, and then finds an increasing maximally weighted
path through the grid. The weight of a cell in the grid is the sum of the
number of anchors in it. All other anchors are to be removed. This will likely
only work for LIMSTemplate sequences, or other sequences with little structural
variation.
FindBand(mappingBuffers.matchPosList,
refCopy, read, 100);
*/
FindMaxIncreasingInterval(
Forward, mappingBuffers.matchPosList,
// allow for indels to stretch out the mapping of the read.
(DNALength)((read.SubreadLength()) * (1 + params.indelRate)), params.nCandidates,
seqBoundary,
lisPValue, //lisPValue2,
lisWeightFn, topIntervals, genome, read, intervalSearchParameters,
&mappingBuffers.globalChainEndpointBuffer, mappingBuffers.clusterList, accumPValue,
accumWeight, accumNBases);
// Uncomment when the version of the weight functor needs the sequence.
mappingBuffers.clusterList.ResetCoordinates();
FindMaxIncreasingInterval(
Reverse, mappingBuffers.rcMatchPosList,
(DNALength)((read.SubreadLength()) * (1 + params.indelRate)), params.nCandidates,
seqBoundary,
lisPValue, //lisPValue2
lisWeightFn, topIntervals, genome, readRC, intervalSearchParameters,
&mappingBuffers.globalChainEndpointBuffer, mappingBuffers.revStrandClusterList,
accumPValue, accumWeight, accumNBases);
} else if (params.pValueType == 1) {
FindMaxIncreasingInterval(
Forward, mappingBuffers.matchPosList,
// allow for indels to stretch out the mapping of the read.
(DNALength)((read.SubreadLength()) * (1 + params.indelRate)), params.nCandidates,
seqBoundary,
lisPValueByWeight, // different from pvaltype == 2 and 0
lisWeightFn, topIntervals, genome, read, intervalSearchParameters,
&mappingBuffers.globalChainEndpointBuffer, mappingBuffers.clusterList, accumPValue,
accumWeight, accumNBases);
mappingBuffers.clusterList.ResetCoordinates();
FindMaxIncreasingInterval(
Reverse, mappingBuffers.rcMatchPosList,
(DNALength)((read.SubreadLength()) * (1 + params.indelRate)), params.nCandidates,
seqBoundary,
lisPValueByWeight, // different from pvaltype == 2 and 0
lisWeightFn, topIntervals, genome, readRC, intervalSearchParameters,
&mappingBuffers.globalChainEndpointBuffer, mappingBuffers.revStrandClusterList,
accumPValue, accumWeight, accumNBases);
} else if (params.pValueType == 2) {
FindMaxIncreasingInterval(
Forward, mappingBuffers.matchPosList,
// allow for indels to stretch out the mapping of the read.
(DNALength)((read.SubreadLength()) * (1 + params.indelRate)), params.nCandidates,
seqBoundary,
lisPValueByLogSum, // different from pvaltype == 1 and 0
lisWeightFn, topIntervals, genome, read, intervalSearchParameters,
&mappingBuffers.globalChainEndpointBuffer, mappingBuffers.clusterList, accumPValue,
accumWeight, accumNBases);
mappingBuffers.clusterList.ResetCoordinates();
FindMaxIncreasingInterval(
Reverse, mappingBuffers.rcMatchPosList,
(DNALength)((read.SubreadLength()) * (1 + params.indelRate)), params.nCandidates,
seqBoundary,
lisPValueByLogSum, // different from pvaltype == 1 and 0
lisWeightFn, topIntervals, genome, readRC, intervalSearchParameters,
&mappingBuffers.globalChainEndpointBuffer, mappingBuffers.revStrandClusterList,
accumPValue, accumWeight, accumNBases);
}
mappingBuffers.clusterList.numBases.insert(
mappingBuffers.clusterList.numBases.end(),
mappingBuffers.revStrandClusterList.numBases.begin(),
mappingBuffers.revStrandClusterList.numBases.end());
mappingBuffers.clusterList.numAnchors.insert(
mappingBuffers.clusterList.numAnchors.end(),
mappingBuffers.revStrandClusterList.numAnchors.begin(),
mappingBuffers.revStrandClusterList.numAnchors.end());
metrics.clocks.findMaxIncreasingInterval.Tock();
//
// Print verbose output.
//
WeightedIntervalSet::iterator topIntIt, topIntEnd;
topIntEnd = topIntervals.end();
if (params.verbosity > 0) {
int topintind = 0;
std::cout << "Top " << topIntervals.size() << " Intervals" << std::endl;
for (topIntIt = topIntervals.begin(); topIntIt != topIntEnd; ++topIntIt) {
std::cout << "top interval " << topintind << ", " << (*topIntIt) << std::endl;
if (params.verbosity > 2) {
for (size_t m = 0; m < (*topIntIt).matches.size(); m++) {
std::cout << " (" << (*topIntIt).matches[m].q << ", "
<< (*topIntIt).matches[m].t << ", " << (*topIntIt).matches[m].l
<< ") ";
}
std::cout << std::endl;
}
++topintind;
}
}
//
// Allocate candidate alignments on the stack. Each interval is aligned.
//
alignmentPtrs.resize(topIntervals.size());
UInt i;
for (i = 0; i < alignmentPtrs.size(); i++) {
alignmentPtrs[i] = new T_AlignmentCandidate;
}
metrics.clocks.alignIntervals.Tick();
AlignIntervals(genome, read, readRC, topIntervals, SMRTDistanceMatrix, params.indel,
params.indel, params.sdpTupleSize, params.useSeqDB, seqdb, alignmentPtrs,
params, mappingBuffers, params.startRead);
/* std::cout << read.title << std::endl;
for (i = 0; i < alignmentPtrs.size(); i++) {
std::cout << alignmentPtrs[i]->clusterScore << " " << alignmentPtrs[i]->score << std::endl;
}
*/
StoreRankingStats(alignmentPtrs, accumPValue, accumWeight);
std::sort(alignmentPtrs.begin(), alignmentPtrs.end(), SortAlignmentPointersByScore());
metrics.clocks.alignIntervals.Tock();
//
// Evalutate the matches that are found for 'good enough'.
//
matchFound = CheckForSufficientMatch(read, alignmentPtrs, params);
//
// When no proper alignments are found, the loop will resume.
// Delete all alignments because they are bad.
//
if (expand < params.maxExpand and matchFound == false) {
DeleteAlignments(alignmentPtrs, 0);
}
//
// Record some metrics that show how long this took to run per base.
//
if (alignmentPtrs.size() > 0) {
metrics.RecordNumAlignedBases(read.length);
metrics.RecordNumCells(alignmentPtrs[0]->nCells);
}
if (matchFound == true) {
metrics.totalAnchorsForMappedReads +=
mappingBuffers.matchPosList.size() + mappingBuffers.rcMatchPosList.size();
}
++expand;
} while (expand <= params.maxExpand and matchFound == false);
metrics.clocks.total.Tock();
UInt i;
int totalCells = 0;
for (i = 0; i < alignmentPtrs.size(); i++) {
totalCells += alignmentPtrs[i]->nCells;
}
metrics.clocks.AddCells(totalCells);
int totalBases = 0;
for (i = 0; i < alignmentPtrs.size(); i++) {
totalBases += alignmentPtrs[i]->qLength;
}
metrics.clocks.AddBases(totalBases);
//
// Some of the alignments are to spurious regions. Delete the
// references that have too small of a score.
//
int effectiveReadLength = 0;
for (i = 0; i < read.length; i++) {
if (read.seq[i] != 'N') effectiveReadLength++;
}
if (params.sdpFilterType == 0) {
RemoveLowQualityAlignments(read, alignmentPtrs, params);
} else if (params.sdpFilterType == 1) {
RemoveLowQualitySDPAlignments(effectiveReadLength, alignmentPtrs, params);
}
//
// Now remove overlapping alignments.
//
std::vector<T_Sequence *> bothQueryStrands;
bothQueryStrands.resize(2);
bothQueryStrands[Forward] = &read;
bothQueryStrands[Reverse] = &readRC;
//
// Possibly use banded dynamic programming to refine the columns
// of an alignment and the alignment score.
//
if (params.refineAlignments) {
RefineAlignments(bothQueryStrands, genome, alignmentPtrs, params, mappingBuffers);
RemoveLowQualityAlignments(read, alignmentPtrs, params);
RemoveOverlappingAlignments(alignmentPtrs, params);
}
//
// Look to see if the number of anchors found for this read match
// what is expected given the expected distribution of number of
// anchors.
//
if (alignmentPtrs.size() > 0) {
size_t clusterIndex;
//
// Compute some stats on the read. For now this is fixed but will
// be updated on the fly soon.
//
float meanAnchorBasesPerRead, sdAnchorBasesPerRead;
float meanAnchorsPerRead, sdAnchorsPerRead;
int lookupValue;
//
// If a very short anchor size was used, or very long min match
// size there may be no precomputed distributions for it.
// Handle this by bounding the min match by the smallest and
// largest values for which there are precomputed statistics.
int boundedMinWordMatchLength = std::min(
std::max(params.minMatchLength, PacBio::AnchorDistributionTable::anchorMinKValues[0]),
PacBio::AnchorDistributionTable::anchorMinKValues[1]);
//
// Do a similar bounding for match length and accuracy.
//
int boundedMatchLength =
std::min(std::max((int)alignmentPtrs[0]->qAlignedSeq.length,
PacBio::AnchorDistributionTable::anchorReadLengths[0]),
PacBio::AnchorDistributionTable::anchorReadLengths[1]);
int boundedPctSimilarity =
std::min(std::max((int)alignmentPtrs[0]->pctSimilarity,
PacBio::AnchorDistributionTable::anchorReadAccuracies[0]),
PacBio::AnchorDistributionTable::anchorReadAccuracies[1]);
lookupValue = LookupAnchorDistribution(
boundedMatchLength, boundedMinWordMatchLength, boundedPctSimilarity, meanAnchorsPerRead,
sdAnchorsPerRead, meanAnchorBasesPerRead, sdAnchorBasesPerRead);
float minExpAnchors = meanAnchorsPerRead - sdAnchorsPerRead;
//
// The number of standard deviations is just trial and error.
float minExpAnchorBases = meanAnchorBasesPerRead - 2 * sdAnchorBasesPerRead;
if (lookupValue < 0 or minExpAnchorBases < 0) {
minExpAnchorBases = 0;
}
int numSignificantClusters = 0;
int totalSignificantClusterSize = 0;
int maxClusterSize = 0;
int numAlnAnchorBases, numAlnAnchors;
alignmentPtrs[0]->ComputeNumAnchors(boundedMinWordMatchLength, numAlnAnchors,
numAlnAnchorBases);
int totalAnchorBases = 0;
if (numAlnAnchorBases > meanAnchorBasesPerRead + sdAnchorBasesPerRead) {
numSignificantClusters = 1;
} else {
if (alignmentPtrs[0]->score < params.maxScore) {
for (clusterIndex = 0; clusterIndex < mappingBuffers.clusterList.numBases.size();
clusterIndex++) {
if (mappingBuffers.clusterList.numBases[clusterIndex] > maxClusterSize) {
maxClusterSize = mappingBuffers.clusterList.numBases[clusterIndex];
}
}
int scaledExpectedClusterSize =
maxClusterSize / ((float)numAlnAnchorBases) * minExpAnchorBases;
for (clusterIndex = 0; clusterIndex < mappingBuffers.clusterList.numBases.size();
clusterIndex++) {
if (mappingBuffers.clusterList.numBases[clusterIndex] >=
scaledExpectedClusterSize) {
// std::cout << mappingBuffers.clusterList.numBases[clusterIndex] << " " << scaledExpectedClusterSize << " " << meanAnchorBasesPerRead << " " << sdAnchorBasesPerRead << std::endl;
++numSignificantClusters;
totalSignificantClusterSize += meanAnchorBasesPerRead;
}
//
// The following output block is useful in debugging mapqv
// calculation. It should be uncommented and examined when
// mapqvs do not look correct.
//
totalAnchorBases += mappingBuffers.clusterList.numBases[clusterIndex];
}
}
if (lookupValue == 0) {
alignmentPtrs[0]->ComputeNumAnchors(params.minMatchLength, numAlnAnchors,
numAlnAnchorBases);
}
}
for (i = 0; i < alignmentPtrs.size(); i++) {
alignmentPtrs[i]->numSignificantClusters = numSignificantClusters;
}
if (mapData->clusterFilePtr != NULL and topIntervals.size() > 0 and
alignmentPtrs.size() > 0) {
WeightedIntervalSet::iterator intvIt = topIntervals.begin();
if (params.nProc > 1) {
#ifdef __APPLE__
sem_wait(semaphores.hitCluster);
#else
sem_wait(&semaphores.hitCluster);
#endif
}
*mapData->clusterFilePtr
<< (*intvIt).size << " " << (*intvIt).pValue << " " << (*intvIt).nAnchors << " "
<< read.length << " " << alignmentPtrs[0]->score << " "
<< alignmentPtrs[0]->pctSimilarity << " "
<< " " << minExpAnchors << " " << alignmentPtrs[0]->qAlignedSeq.length << std::endl;
if (params.nProc > 1) {
#ifdef __APPLE__
sem_post(semaphores.hitCluster);
#else
sem_post(&semaphores.hitCluster);
#endif
}
}
}
//
// Assign the query name and strand for each alignment.
//
for (i = 0; i < alignmentPtrs.size(); i++) {
T_AlignmentCandidate *aref = alignmentPtrs[i];
if (aref->tStrand == 0) {
aref->qName = read.GetName();
} else {
aref->qName = readRC.GetName();
}
}
AssignRefContigLocations(alignmentPtrs, seqdb, genome);
}
template <typename T_Sequence>
void MapRead(T_Sequence &read, T_Sequence &readRC,
std::vector<T_AlignmentCandidate *> &alignmentPtrs, MappingBuffers &mappingBuffers,
MappingIPC *mapData, MappingSemaphores &semaphores)
{
DNASuffixArray sarray;
TupleCountTable<T_GenomeSequence, DNATuple> ct;
SequenceIndexDatabase<FASTQSequence> seqdb;
T_GenomeSequence genome;
BWT *bwtPtr = mapData->bwtPtr;
mapData->ShallowCopySuffixArray(sarray);
mapData->ShallowCopyReferenceSequence(genome);
mapData->ShallowCopySequenceIndexDatabase(seqdb);
mapData->ShallowCopyTupleCountTable(ct);
SeqBoundaryFtr<FASTQSequence> seqBoundary(&seqdb);
return MapRead(read, readRC,
genome, // possibly multi fasta file read into one sequence
sarray, *bwtPtr, // The suffix array, and the bwt-fm index structures
seqBoundary, // Boundaries of contigs in the
// genome, alignments do not span
// the ends of boundaries.
ct, // Count table to use word frequencies in the genome to weight matches.
seqdb, // Information about the names of
// chromosomes in the genome, and
// where their sequences are in the genome.
mapData->params, // A huge list of parameters for
// mapping, only compile/command
// line values set.
mapData->metrics, // Keep track of time/ hit counts,
// etc.. Not fully developed, but
// should be.
alignmentPtrs, // Where the results are stored.
mappingBuffers, // A class of buffers for structurs
// like dyanmic programming
// matrices, match lists, etc., that are not
// reallocated between calls to
// MapRead. They are cleared though.
mapData, // Some values that are shared
// across threads.
semaphores);
}
template <typename T_TargetSequence, typename T_QuerySequence, typename TDBSequence>
void AlignIntervals(T_TargetSequence &genome, T_QuerySequence &read, T_QuerySequence &rcRead,
WeightedIntervalSet &weightedIntervals, int mutationCostMatrix[][5], int ins,
int del, int sdpTupleSize, int useSeqDB,
SequenceIndexDatabase<TDBSequence> &seqDB,
std::vector<T_AlignmentCandidate *> &alignments, MappingParameters ¶ms,
MappingBuffers &mappingBuffers, int procId)
{
(void)(mutationCostMatrix);
(void)(ins);
(void)(del);
(void)(procId);
std::vector<T_QuerySequence *> forrev;
forrev.resize(2);
forrev[Forward] = &read;
forrev[Reverse] = &rcRead;
//
// Use an edit distance scoring function instead of IDS. Although
// the IDS should be more accurate, it is more slow, and it is more
// important at this stage to have faster alignments than accurate,
// since all alignments are rerun using GuidedAlignment later on.
//
DistanceMatrixScoreFunction<DNASequence, FASTQSequence> distScoreFn(
SMRTDistanceMatrix, params.insertion, params.deletion);
DistanceMatrixScoreFunction<DNASequence, FASTQSequence> distScoreFn2(SMRTDistanceMatrix, ins,
ins);
//
// Assume there is at least one interval.
//
if (weightedIntervals.size() == 0) return;
WeightedIntervalSet::iterator intvIt = weightedIntervals.begin();
int alignmentIndex = 0;
do {
T_AlignmentCandidate *alignment = alignments[alignmentIndex];
alignment->clusterWeight = (*intvIt).size; // totalAnchorSize == size
alignment->clusterScore = (*intvIt).pValue;
//
// Advance references. Intervals are stored in reverse order, so
// go backwards in the list, and alignments are in forward order.
// That should probably be changed.
//
++alignmentIndex;
//
// Try aligning the read to the genome.
//
DNALength matchIntervalStart, matchIntervalEnd;
matchIntervalStart = (*intvIt).start;
matchIntervalEnd = (*intvIt).end;
bool readOverlapsContigStart = false;
bool readOverlapsContigEnd = false;
int startOverlappedContigIndex = 0;
int endOverlappedContigIndex = 0;
(void)(readOverlapsContigStart);
(void)(readOverlapsContigEnd);
(void)(startOverlappedContigIndex);
(void)(endOverlappedContigIndex);
if (params.verbosity > 0) {
std::cout << "aligning interval: "
<< "read_length=" << read.length << "; interval=" << (*intvIt)
<< "; max_insertion_rate=" << params.approximateMaxInsertionRate << std::endl;
}
assert(matchIntervalEnd >= matchIntervalStart);
//
// If using a sequence database, check to make sure that the
// boundaries of the sequence windows do not overlap with
// the boundaries of the reads. If the beginning is before
// the boundary, move the beginning up to the start of the read.
// If the end is past the end boundary of the read, similarly move
// the window boundary to the end of the read boundary.
int seqDBIndex = 0;
//
// Stretch the alignment interval so that it is close to where
// the read actually starts.
//
DNALength subreadStart = read.SubreadStart();
DNALength subreadEnd = read.SubreadEnd();
if ((*intvIt).GetStrandIndex() == Reverse) {
subreadEnd = read.MakeRCCoordinate(read.SubreadStart()) + 1;
subreadStart = read.MakeRCCoordinate(read.SubreadEnd() - 1);
}
DNALength lengthBeforeFirstMatch =
((*intvIt).qStart - subreadStart) * params.approximateMaxInsertionRate;
DNALength lengthAfterLastMatch =
(subreadEnd - (*intvIt).qEnd) * params.approximateMaxInsertionRate;
if (matchIntervalStart < lengthBeforeFirstMatch or params.doGlobalAlignment) {
matchIntervalStart = 0;
} else {
matchIntervalStart -= lengthBeforeFirstMatch;
}
if (genome.length < matchIntervalEnd + lengthAfterLastMatch or params.doGlobalAlignment) {
matchIntervalEnd = genome.length;
} else {
matchIntervalEnd += lengthAfterLastMatch;
}
DNALength intervalContigStartPos, intervalContigEndPos;
if (useSeqDB) {
//
// The sequence db index is the one where the actual match is
// contained. The matchIntervalStart might be before the sequence
// index boundary due to the extrapolation of alignment start by
// insertion rate. If this is the case, bump up the
// matchIntervalStart to be at the beginning of the boundary.
// Modify bounds similarly for the matchIntervalEnd and the end
// of a boundary.
//
seqDBIndex = seqDB.SearchForIndex((*intvIt).start);
intervalContigStartPos = seqDB.seqStartPos[seqDBIndex];
if (intervalContigStartPos > matchIntervalStart) {
matchIntervalStart = intervalContigStartPos;
}
intervalContigEndPos = seqDB.seqStartPos[seqDBIndex + 1] - 1;
if (intervalContigEndPos < matchIntervalEnd) {
matchIntervalEnd = intervalContigEndPos;
}
alignment->tName = seqDB.GetSpaceDelimitedName(seqDBIndex);
alignment->tLength = intervalContigEndPos - intervalContigStartPos;
//
// When there are multiple sequences in the database, store the
// index of this sequence. This lets one compare the contigs
// that reads are mapped to, for instance.
//
alignment->tIndex = seqDBIndex;
} else {
alignment->tLength = genome.length;
alignment->tName = genome.GetName();
intervalContigStartPos = 0;
intervalContigEndPos = genome.length;
//
// When there are multiple sequences in the database, store the
// index of this sequence. This lets one compare the contigs
// that reads are mapped to, for instance.
//
}
alignment->qName = read.title;
//
// Look to see if a read overhangs the beginning of a contig.
//
if (params.verbosity > 2) {
std::cout << "Check for prefix/suffix overlap on interval: " << (*intvIt).qStart
<< " ?> " << (*intvIt).start - intervalContigStartPos << std::endl;
}
if ((*intvIt).qStart > (*intvIt).start - intervalContigStartPos) {
readOverlapsContigStart = true;
startOverlappedContigIndex = seqDBIndex;
}
//
// Look to see if the read overhangs the end of a contig.
//
if (params.verbosity > 2) {
std::cout << "Check for suffix/prefix overlap on interval, read overhang: "
<< read.length - (*intvIt).qEnd << " ?> " << matchIntervalEnd - (*intvIt).end
<< std::endl;
}
if (read.length - (*intvIt).qEnd > matchIntervalEnd - (*intvIt).end) {
if (params.verbosity > 2) {
std::cout << "read overlaps genome end." << std::endl;
}
readOverlapsContigEnd = true;
endOverlappedContigIndex = seqDBIndex;
}
int alignScore;
alignScore = 0;
alignment->tAlignedSeqPos = matchIntervalStart;
alignment->tAlignedSeqLength = matchIntervalEnd - matchIntervalStart;
if ((*intvIt).GetStrandIndex() == Forward) {
alignment->tAlignedSeq.Copy(genome, alignment->tAlignedSeqPos,
alignment->tAlignedSeqLength);
alignment->tStrand = Forward;
} else {
if (not params.placeGapConsistently) {
DNALength rcAlignedSeqPos = genome.MakeRCCoordinate(
alignment->tAlignedSeqPos + alignment->tAlignedSeqLength - 1);
genome.CopyAsRC(alignment->tAlignedSeq, rcAlignedSeqPos,
alignment->tAlignedSeqLength);
// Map forward coordinates into reverse complement.
intervalContigStartPos = genome.MakeRCCoordinate(intervalContigStartPos) + 1;
intervalContigEndPos = genome.MakeRCCoordinate(intervalContigEndPos - 1);
std::swap(intervalContigStartPos, intervalContigEndPos);
alignment->tAlignedSeqPos = rcAlignedSeqPos;
alignment->tStrand = Reverse;
} else {
// To place gaps consistently for both forward/reverse strand alignments,
// reference genome is ALWAYS ALIGNED in FORWARD direction, rc query instead.
alignment->tAlignedSeq.Copy(genome, alignment->tAlignedSeqPos,
alignment->tAlignedSeqLength);
alignment->tStrand = Forward;
alignment->qStrand = Reverse;
}
}
// Configure the part of the query that is aligned. The entire
// query should always be aligned.
const auto ConfigureQuery = [&alignment](T_QuerySequence &inputRead) {
alignment->qAlignedSeqPos = 0;
alignment->qAlignedSeq.ReferenceSubstring(inputRead);
alignment->qAlignedSeqLength = alignment->qAlignedSeq.length;
alignment->qLength = inputRead.length;
};
assert(read.length == rcRead.length);
ConfigureQuery(alignment->qStrand == Forward ? read : rcRead);
if (params.verbosity > 1) {
std::cout << "aligning read, qstrand is " << alignment->qStrand << ", tstrand is "
<< alignment->tStrand << std::endl;
static_cast<DNASequence *>(&(alignment->qAlignedSeq))->PrintSeq(std::cout);
std::cout << std::endl << "aligning reference" << std::endl;
static_cast<DNASequence *>(&(alignment->tAlignedSeq))->PrintSeq(std::cout);
std::cout << std::endl;
}
//
// The type of alignment that is performed depends on the mode
// blasr is running in. If it is running in normal mode, local
// aligment is performed and guided by SDP alignment. When
// running in overlap mode, the alignments are forced to the ends
// of reads.
//
int intervalSize = 0;
//
// Check to see if the matches to the genome are sufficiently
// dense to allow them to be used instead of having to redo
// sdp alignment.
//
// First count how much of the read matches the genome exactly.
for (size_t m = 0; m < intvIt->matches.size(); m++) {
intervalSize += intvIt->matches[m].l;
}
int subreadLength = forrev[(*intvIt).GetStrandIndex()]->SubreadEnd() -
forrev[(*intvIt).GetStrandIndex()]->SubreadStart();
if ((1.0 * intervalSize) / subreadLength < params.sdpBypassThreshold and
!params.emulateNucmer) {
//
// Not enough of the read maps to the genome, need to use
// sdp alignment to define the regions of the read that map.
//
if (params.refineBetweenAnchorsOnly) {
// rbao && placeGapConsistently can not be set together
assert(not params.placeGapConsistently);
//
// Run SDP alignment only between the genomic anchors,
// including the genomic anchors as part of the alignment.
//
size_t m;
std::vector<ChainedMatchPos> *matches;
std::vector<ChainedMatchPos> rcMatches;
Alignment anchorsOnly;
DNASequence tAlignedSeq;
FASTQSequence qAlignedSeq;
//
// The strand bookkeeping is a bit confusing, so hopefully
// this will set things straight.
//
// If the alignment is forward strand, the coordinates of the
// blocks are relative to the forward read, starting at 0, not
// the subread start.
// If the alignment is reverse strand, the coordinates of the
// blocks are relative to the reverse strand, starting at the
// position of the subread on the reverse strand.
//
// The coordinates of the blocks in the genome are always
// relative to the forward strand on the genome, starting at
// 0.
//
//
// The first step to refining between anchors only is to make
// the anchors relative to the tAlignedSeq.
matches = (std::vector<ChainedMatchPos> *)&(*intvIt).matches;
tAlignedSeq = alignment->tAlignedSeq;
qAlignedSeq = alignment->qAlignedSeq;
if (alignment->tStrand == 0) {
for (m = 0; m < matches->size(); m++) {
(*matches)[m].t -= alignment->tAlignedSeqPos;
(*matches)[m].q -= alignment->qAlignedSeqPos;
}
} else {
//
// Flip the entire alignment if it is on the reverse strand.
DNALength rcAlignedSeqPos = genome.MakeRCCoordinate(
alignment->tAlignedSeqPos + alignment->tAlignedSeqLength - 1);
for (m = 0; m < matches->size(); m++) {
(*matches)[m].t -= rcAlignedSeqPos;
(*matches)[m].q -= alignment->qAlignedSeqPos;
}
alignment->tAlignedSeq.CopyAsRC(tAlignedSeq);
rcMatches.resize((*intvIt).matches.size());
//
// Make the reverse complement of the match list.
//
// 1. Reverse complement the coordinates.
for (m = 0; m < (*intvIt).matches.size(); m++) {
int revCompIndex = rcMatches.size() - m - 1;
rcMatches[revCompIndex].q = read.MakeRCCoordinate(
(*intvIt).matches[m].q + (*intvIt).matches[m].l - 1);
rcMatches[revCompIndex].t = tAlignedSeq.MakeRCCoordinate(
(*intvIt).matches[m].t + (*intvIt).matches[m].l - 1);
rcMatches[revCompIndex].l = (*intvIt).matches[m].l;
}
matches = &rcMatches;
}
/*
Uncomment to get a dot plot
std::ofstream matchFile;
matchFile.open("matches.txt");
matchFile << "q t l " << std::endl;
for (m = 0; matches->size() > 0 and m < matches->size() - 1; m++) {
matchFile << (*matches)[m].q << " " << (*matches)[m].t << " " << (*matches)[m].l << std::endl;
}
*/
DNASequence tSubSeq;
FASTQSequence qSubSeq;
for (m = 0; matches->size() > 0 and m < matches->size() - 1; m++) {
Block block;
block.qPos = (*matches)[m].q;
block.tPos = (*matches)[m].t;
block.length = (*matches)[m].l;
//
// Find the lengths of the gaps between anchors.
//
int tGap, qGap;
tGap = (*matches)[m + 1].t - ((*matches)[m].t + (*matches)[m].l);
qGap = (*matches)[m + 1].q - ((*matches)[m].q + (*matches)[m].l);
if (tGap > 0 and qGap > 0) {
DNALength tPos, qPos;
tPos = block.tPos + block.length;
qPos = block.qPos + block.length;
tSubSeq.ReferenceSubstring(tAlignedSeq, tPos, tGap);
qSubSeq.ReferenceSubstring(alignment->qAlignedSeq, qPos, qGap);
Alignment alignmentInGap;
/*
The following code is experimental code for trying to do
something like affine gap alignment in long gaps. It
would eventually be used in cDNA alignment to align
between exons, but for now is being tested here by using
it to align when there is a big gap between anchors.
*/
if (params.separateGaps == true and qSubSeq.length > 0 and
tSubSeq.length > 0 and
((1.0 * qSubSeq.length) / tSubSeq.length < 0.25)) {
OneGapAlign(qSubSeq, tSubSeq, distScoreFn, mappingBuffers,
alignmentInGap);
} else {
/*
This is the 'normal/default' way to align between
gaps. It is more well tested than OneGapAlign.
*/
SDPAlign(qSubSeq, tSubSeq, distScoreFn, params.sdpTupleSize,
params.sdpIns, params.sdpDel, params.indelRate * 2,
alignmentInGap, mappingBuffers, Global,
params.detailedSDPAlignment, params.extendFrontAlignment,
params.recurseOver, params.fastSDP);
}
//
// Now, splice the fragment alignment into the current
// alignment.
//
if (alignmentInGap.blocks.size() > 0) {
size_t b;
//
// Configure this block to be relative to the beginning
// of the aligned substring.
//
for (b = 0; b < alignmentInGap.size(); b++) {
alignmentInGap.blocks[b].tPos += tPos + alignmentInGap.tPos;
alignmentInGap.blocks[b].qPos += qPos + alignmentInGap.qPos;
assert(alignmentInGap.blocks[b].tPos <
alignment->tAlignedSeq.length);
assert(alignmentInGap.blocks[b].qPos <
alignment->qAlignedSeq.length);
}
}
// Add the original block
alignment->blocks.push_back(block);
anchorsOnly.blocks.push_back(block);
// Add the blocks for the refined alignment
alignment->blocks.insert(alignment->blocks.end(),
alignmentInGap.blocks.begin(),
alignmentInGap.blocks.end());
}
}
// Add the last block
m = (*matches).size() - 1;
Block block;
block.qPos = (*matches)[m].q;
block.tPos = (*matches)[m].t;
assert(block.tPos <= alignment->tAlignedSeq.length);
assert(block.qPos <= alignment->qAlignedSeq.length);
block.length = (*matches)[m].l;
alignment->blocks.push_back(block);
anchorsOnly.blocks.push_back(block);
//
// By convention, blocks start at 0, and the
// alignment->tPos,qPos give the start of the alignment.
// Modify the block positions so that they are offset by 0.
alignment->tPos = alignment->blocks[0].tPos;
alignment->qPos = alignment->blocks[0].qPos;
size_t b;
size_t blocksSize = alignment->blocks.size();
for (b = 0; b < blocksSize; b++) {
assert(alignment->tPos <= alignment->blocks[b].tPos);
assert(alignment->qPos <= alignment->blocks[b].qPos);
alignment->blocks[b].tPos -= alignment->tPos;
alignment->blocks[b].qPos -= alignment->qPos;
}
for (b = 0; b < anchorsOnly.blocks.size(); b++) {
anchorsOnly.blocks[b].tPos -= alignment->tPos;
anchorsOnly.blocks[b].qPos -= alignment->qPos;
}
anchorsOnly.tPos = alignment->tPos;
anchorsOnly.qPos = alignment->qPos;
ComputeAlignmentStats(*alignment, alignment->qAlignedSeq.seq,
alignment->tAlignedSeq.seq, distScoreFn);
tAlignedSeq.Free();
qAlignedSeq.Free();
tSubSeq.Free();
qSubSeq.Free();
} else {
alignScore =
SDPAlign(alignment->qAlignedSeq, alignment->tAlignedSeq, distScoreFn,
sdpTupleSize, params.sdpIns, params.sdpDel, params.indelRate * 3,
*alignment, mappingBuffers, Local, params.detailedSDPAlignment,
params.extendFrontAlignment, params.recurseOver, params.fastSDP);
ComputeAlignmentStats(*alignment, alignment->qAlignedSeq.seq,
alignment->tAlignedSeq.seq, distScoreFn);
}
} else {
//
// The anchors used to anchor the sequence are sufficient to extend the alignment.
//
size_t m;
for (m = 0; m < (*intvIt).matches.size(); m++) {
Block block;
block.qPos = (*intvIt).matches[m].q - alignment->qAlignedSeqPos;
block.tPos = (*intvIt).matches[m].t - alignment->tAlignedSeqPos;
block.length = (*intvIt).matches[m].l;
alignment->blocks.push_back(block);
}
}
//
// The anchors/sdp alignments may leave portions of the read
// unaligned at the beginning and end. If the parameters
// specify extending alignments, try and align extra bases at
// the beginning and end of alignments.
if (params.extendAlignments) {
// extend && placeGapConsistently can not be set together
assert(not params.placeGapConsistently);
//
// Modify the alignment so that the start and end of the
// alignment strings are at the alignment boundaries.
//
// Since the query sequence is pointing at a subsequence of the
// read (and is always in the forward direction), just reference
// a new portion of the read.
alignment->qAlignedSeqPos = alignment->qAlignedSeqPos + alignment->qPos;
alignment->qAlignedSeqLength = alignment->QEnd();
alignment->qAlignedSeq.ReferenceSubstring(read, alignment->qAlignedSeqPos,
alignment->qAlignedSeqLength);
alignment->qPos = 0;
//
// Since the target sequence may be on the forward or reverse
// strand, a copy of the subsequence is made, and the original
// sequence free'd.
//
DNASequence tSubseq;
alignment->tAlignedSeqPos = alignment->tAlignedSeqPos + alignment->tPos;
alignment->tAlignedSeqLength = alignment->TEnd();
tSubseq.Copy(alignment->tAlignedSeq, alignment->tPos, alignment->tAlignedSeqLength);
alignment->tPos = 0;
alignment->tAlignedSeq.Free();
alignment->tAlignedSeq.TakeOwnership(tSubseq);
DNALength maximumExtendLength = 500;
if (alignment->blocks.size() > 0) {
int lastAlignedBlock = alignment->blocks.size() - 1;
DNALength lastAlignedQPos = alignment->blocks[lastAlignedBlock].QEnd() +
alignment->qPos + alignment->qAlignedSeqPos;
DNALength lastAlignedTPos = alignment->blocks[lastAlignedBlock].TEnd() +
alignment->tPos + alignment->tAlignedSeqPos;
T_AlignmentCandidate extendedAlignmentForward, extendedAlignmentReverse;
int forwardScore, reverseScore;
SMRTSequence readSuffix;
DNALength readSuffixLength;
DNASequence genomeSuffix;
DNALength genomeSuffixLength;
SMRTSequence readPrefix;
DNALength readPrefixLength;
DNASequence genomePrefix;
DNALength genomePrefixLength;
//
// Align the entire end of the read if it is short enough.
//
readSuffixLength = std::min(read.length - lastAlignedQPos, maximumExtendLength);
if (readSuffixLength > 0) {
readSuffix.ReferenceSubstring(read, lastAlignedQPos, readSuffixLength);
} else {
readSuffix.length = 0;
}
//
// Align The entire end of the genome up to the maximum extend length;
//
genomeSuffixLength =
std::min(intervalContigEndPos - lastAlignedTPos, maximumExtendLength);
if (genomeSuffixLength > 0) {
if (alignment->tStrand == Forward) {
genomeSuffix.Copy(genome, lastAlignedTPos, genomeSuffixLength);
} else {
static_cast<DNASequence *>(&genome)->CopyAsRC(genomeSuffix, lastAlignedTPos,
genomeSuffixLength);
}
} else {
genomeSuffix.length = 0;
}
forwardScore = 0;
if (readSuffix.length > 0 and genomeSuffix.length > 0) {
forwardScore = ExtendAlignmentForward(
readSuffix, 0, genomeSuffix, 0, params.extendBandSize,
// Reuse buffers to speed up alignment
mappingBuffers.scoreMat, mappingBuffers.pathMat,
// Do the alignment in the forward direction.
extendedAlignmentForward, distScoreFn,
1, // don't bother attempting
// to extend the alignment
// if one of the sequences
// is less than 1 base long
params.maxExtendDropoff);
}
if (forwardScore < 0) {
//
// The extended alignment considers the whole genome, but
// should be modified to be starting at the end of where
// the original alignment left off.
//
if (params.verbosity > 0) {
std::cout << "forward extended an alignment of score " << alignment->score
<< " with score " << forwardScore << " by "
<< extendedAlignmentForward.blocks.size() << " blocks and length "
<< extendedAlignmentForward
.blocks[extendedAlignmentForward.blocks.size() - 1]
.qPos
<< std::endl;
}
extendedAlignmentForward.tAlignedSeqPos = lastAlignedTPos;
extendedAlignmentForward.qAlignedSeqPos = lastAlignedQPos;
genomeSuffix.length =
extendedAlignmentForward.tPos + extendedAlignmentForward.TEnd();
alignment->tAlignedSeq.Append(genomeSuffix);
alignment->qAlignedSeq.length +=
extendedAlignmentForward.qPos + extendedAlignmentForward.QEnd();
assert(alignment->qAlignedSeq.length <= read.length);
alignment->AppendAlignment(extendedAlignmentForward);
}
DNALength firstAlignedQPos = alignment->qPos + alignment->qAlignedSeqPos;
DNALength firstAlignedTPos = alignment->tPos + alignment->tAlignedSeqPos;
readPrefixLength = std::min(firstAlignedQPos, maximumExtendLength);
if (readPrefixLength > 0) {
readPrefix.ReferenceSubstring(read, firstAlignedQPos - readPrefixLength,
readPrefixLength);
} else {
readPrefix.length = 0;
}
genomePrefixLength =
std::min(firstAlignedTPos - intervalContigStartPos, maximumExtendLength);
if (genomePrefixLength > 0) {
if (alignment->tStrand == 0) {
genomePrefix.Copy(genome, firstAlignedTPos - genomePrefixLength,
genomePrefixLength);
} else {
static_cast<DNASequence *>(&genome)->MakeRC(
genomePrefix, firstAlignedTPos - genomePrefixLength,
genomePrefixLength);
}
}
reverseScore = 0;
if (readPrefix.length > 0 and genomePrefix.length > 0) {
reverseScore = ExtendAlignmentReverse(
readPrefix, readPrefix.length - 1, genomePrefix, genomePrefixLength - 1,
params.extendBandSize, //k
mappingBuffers.scoreMat, mappingBuffers.pathMat, extendedAlignmentReverse,
distScoreFn,
1, // don't bother attempting
// to extend the alignment
// if one of the sequences
// is less than 1 base long
params.maxExtendDropoff);
}
if (reverseScore < 0) {
//
// Make alignment->tPos relative to the beginning of the
// extended alignment so that when it is appended, the
// coordinates match correctly.
if (params.verbosity > 0) {
std::cout << "reverse extended an alignment of score " << alignment->score
<< " with score " << reverseScore << " by "
<< extendedAlignmentReverse.blocks.size() << " blocks and length "
<< extendedAlignmentReverse
.blocks[extendedAlignmentReverse.blocks.size() - 1]
.qPos
<< std::endl;
}
extendedAlignmentReverse.tAlignedSeqPos = firstAlignedTPos - genomePrefixLength;
extendedAlignmentReverse.qAlignedSeqPos = firstAlignedQPos - readPrefixLength;
extendedAlignmentReverse.AppendAlignment(*alignment);
genomePrefix.Append(alignment->tAlignedSeq,
genomePrefix.length - alignment->tPos);
alignment->tAlignedSeq.Free();
alignment->tAlignedSeq.TakeOwnership(genomePrefix);
alignment->blocks = extendedAlignmentReverse.blocks;
alignment->tAlignedSeqPos = extendedAlignmentReverse.tAlignedSeqPos;
alignment->tPos = extendedAlignmentReverse.tPos;
alignment->qAlignedSeqPos = extendedAlignmentReverse.qAlignedSeqPos;
alignment->qAlignedSeq.length =
readPrefix.length + alignment->qAlignedSeq.length;
alignment->qPos = extendedAlignmentReverse.qPos;
alignment->qAlignedSeq.seq = readPrefix.seq;
//
// Make sure the two ways of accounting for aligned sequence
// length are in sync. This needs to go.
//
if (alignment->blocks.size() > 0) {
alignment->qAlignedSeqLength = alignment->qAlignedSeq.length;
alignment->tAlignedSeqLength = alignment->tAlignedSeq.length;
} else {
alignment->qAlignedSeqLength = alignment->qAlignedSeq.length = 0;
alignment->tAlignedSeqLength = alignment->tAlignedSeq.length = 0;
}
} // end of if (reverseScore < 0 )
readSuffix.Free();
readPrefix.Free();
genomePrefix.Free();
genomeSuffix.Free();
}
tSubseq.Free();
}
if (params.verbosity > 0) {
std::cout << "interval align score: " << alignScore << std::endl;
StickPrintAlignment(*alignment, (DNASequence &)alignment->qAlignedSeq,
(DNASequence &)alignment->tAlignedSeq, std::cout, 0,
alignment->tAlignedSeqPos);
}
ComputeAlignmentStats(*alignment, alignment->qAlignedSeq.seq, alignment->tAlignedSeq.seq,
distScoreFn2);
//SMRTDistanceMatrix, ins, del );
intvIt++;
} while (intvIt != weightedIntervals.end());
}
template <typename T_RefSequence, typename T_Sequence>
void PairwiseLocalAlign(T_Sequence &qSeq, T_RefSequence &tSeq, int k, MappingParameters ¶ms,
T_AlignmentCandidate &alignment, MappingBuffers &mappingBuffers,
AlignmentType alignType)
{
//
// Perform a pairwise alignment between qSeq and tSeq, but choose
// the pairwise alignment method based on the parameters. The
// options for pairwise alignment are:
// - Affine KBanded alignment: usually used for sequences with no
// quality information.
// - KBanded alignment: For sequences with quality information.
// Gaps are scored with quality values.
//
QualityValueScoreFunction<DNASequence, FASTQSequence> scoreFn;
scoreFn.del = params.indel;
scoreFn.ins = params.indel;
DistanceMatrixScoreFunction<DNASequence, FASTASequence> distScoreFn2(
SMRTDistanceMatrix, params.indel, params.indel);
IDSScoreFunction<DNASequence, FASTQSequence> idsScoreFn;
idsScoreFn.ins = params.insertion;
idsScoreFn.del = params.deletion;
idsScoreFn.substitutionPrior = params.substitutionPrior;
idsScoreFn.globalDeletionPrior = params.globalDeletionPrior;
idsScoreFn.InitializeScoreMatrix(SMRTDistanceMatrix);
int kbandScore;
int qvAwareScore;
if (params.ignoreQualities || qSeq.qual.Empty() || !ReadHasMeaningfulQualityValues(qSeq)) {
kbandScore = AffineKBandAlign(
qSeq, tSeq, SMRTDistanceMatrix, params.indel + 2,
params.indel - 3, // homopolymer insertion open and extend
params.indel + 2, params.indel - 1, // any insertion open and extend
params.indel, // deletion
k * 1.2, mappingBuffers.scoreMat, mappingBuffers.pathMat, mappingBuffers.hpInsScoreMat,
mappingBuffers.hpInsPathMat, mappingBuffers.insScoreMat, mappingBuffers.insPathMat,
alignment, Global);
alignment.score = kbandScore;
if (params.verbosity >= 2) {
std::cout << "align score: " << kbandScore << std::endl;
}
} else {
if (qSeq.insertionQV.Empty() == false) {
qvAwareScore = KBandAlign(qSeq, tSeq, SMRTDistanceMatrix,
params.indel + 2, // ins
params.indel + 2, // del
k, mappingBuffers.scoreMat, mappingBuffers.pathMat, alignment,
idsScoreFn, alignType);
if (params.verbosity >= 2) {
std::cout << "ids score fn score: " << qvAwareScore << std::endl;
}
} else {
qvAwareScore = KBandAlign(qSeq, tSeq, SMRTDistanceMatrix,
params.indel + 2, // ins
params.indel + 2, // del
k, mappingBuffers.scoreMat, mappingBuffers.pathMat, alignment,
scoreFn, alignType);
if (params.verbosity >= 2) {
std::cout << "qv score fn score: " << qvAwareScore << std::endl;
}
}
alignment.sumQVScore = qvAwareScore;
alignment.score = qvAwareScore;
alignment.probScore = 0;
}
// Compute stats and assign a default alignment score using an edit distance.
ComputeAlignmentStats(alignment, qSeq.seq, tSeq.seq, distScoreFn2);
if (params.scoreType == 1) {
alignment.score = alignment.sumQVScore;
}
}
// Extend target aligned sequence of the input alignement to both ends
// by flankSize bases. Update alignment->tAlignedSeqPos,
// alignment->tAlignedSeqLength and alignment->tAlignedSeq.
void FlankTAlignedSeq(T_AlignmentCandidate *alignment, SequenceIndexDatabase<FASTQSequence> &seqdb,
DNASequence &genome, int flankSize)
{
assert(alignment != NULL and alignment->tIsSubstring);
UInt forwardTPos, newTAlignedSeqPos, newTAlignedSeqLen;
// New aligned start position relative to this chromosome, with
// the same direction as alignment->tStrand.
newTAlignedSeqPos =
UInt((alignment->tAlignedSeqPos > UInt(flankSize)) ? (alignment->tAlignedSeqPos - flankSize)
: 0);
newTAlignedSeqLen =
std::min(alignment->tAlignedSeqPos + alignment->tAlignedSeqLength + flankSize,
alignment->tLength) -
newTAlignedSeqPos;
if (alignment->tStrand == 0) {
forwardTPos = newTAlignedSeqPos;
} else {
forwardTPos = alignment->tLength - newTAlignedSeqPos - 1;
}
// Find where this chromosome is in the genome.
int seqIndex = seqdb.GetIndexOfSeqName(alignment->tName);
assert(seqIndex != -1);
UInt newGenomePos = seqdb.ChromosomePositionToGenome(seqIndex, forwardTPos);
if (alignment->tIsSubstring == false) {
alignment->tAlignedSeq.Free();
}
alignment->tAlignedSeqPos = newTAlignedSeqPos;
alignment->tAlignedSeqLength = newTAlignedSeqLen;
if (alignment->tStrand == 0) {
alignment->tAlignedSeq.ReferenceSubstring(genome, newGenomePos, newTAlignedSeqLen);
} else {
// Copy and then reverse complement.
genome.MakeRC(alignment->tAlignedSeq, newGenomePos + 1 - alignment->tAlignedSeqLength,
alignment->tAlignedSeqLength);
alignment->tIsSubstring = false;
}
}
// Align a subread of a SMRT sequence to target sequence of an alignment.
// Input:
// subread - a subread of a SMRT sequence.
// unrolledRead - the full SMRT sequence.
// alignment - an alignment.
// passDirection - whether or not the subread has the
// same direction as query of the alignment.
// 0 = true, 1 = false.
// subreadInterval - [start, end) interval of the subread in the
// SMRT read.
// subreadIndex - index of the subread in allReadAlignments.
// params - mapping paramters.
// Output:
// allReadAlignments - where the sequence and alignments of the
// subread are saved.
// threadOut - an out stream for debugging the current thread.
void AlignSubreadToAlignmentTarget(ReadAlignments &allReadAlignments, SMRTSequence &subread,
SMRTSequence &unrolledRead, T_AlignmentCandidate *alignment,
int passDirection, ReadInterval &subreadInterval,
int subreadIndex, MappingParameters ¶ms,
MappingBuffers &mappingBuffers, std::ostream &threadOut)
{
assert(passDirection == 0 or passDirection == 1);
//
// Determine where in the genome the subread has mapped.
//
DNASequence alignedForwardRefSequence, alignedReverseRefSequence;
if (alignment->tStrand == 0) {
// This needs to be changed -- copy copies RHS into LHS,
// CopyAsRC copies LHS into RHS
alignedForwardRefSequence.Copy(alignment->tAlignedSeq);
alignment->tAlignedSeq.CopyAsRC(alignedReverseRefSequence);
} else {
alignment->tAlignedSeq.CopyAsRC(alignedForwardRefSequence);
alignedReverseRefSequence.Copy(alignment->tAlignedSeq);
}
IDSScoreFunction<DNASequence, FASTQSequence> idsScoreFn;
idsScoreFn.ins = params.insertion;
idsScoreFn.del = params.deletion;
idsScoreFn.InitializeScoreMatrix(SMRTDistanceMatrix);
idsScoreFn.globalDeletionPrior = params.globalDeletionPrior;
idsScoreFn.substitutionPrior = params.substitutionPrior;
DistanceMatrixScoreFunction<DNASequence, FASTQSequence> distScoreFn2(
SMRTDistanceMatrix, params.indel, params.indel);
//
// Determine the strand to align the subread to.
//
T_AlignmentCandidate exploded;
bool sameAlignmentPassDirection =
((alignment->tStrand == alignment->qStrand) ? (passDirection == 0) : (passDirection == 1));
bool computeProbIsFalse = false;
// Config aligned query read and aligned target read;
SMRTSequence rcsubread;
subread.MakeRC(rcsubread);
SMRTSequence &alignedRead = subread;
DNASequence &alignedRefSequence =
(sameAlignmentPassDirection ? alignedForwardRefSequence : alignedReverseRefSequence);
if (params.placeGapConsistently and !sameAlignmentPassDirection) {
alignedRead = rcsubread;
alignedRefSequence = alignedForwardRefSequence;
}
//
// In the original code, parameters: bandSize=10, alignType=Global,
// sdpTupleSize=4 (instead of 12, Local and 6) were used when
// alignment & pass have different directions.
//
int explodedScore =
GuidedAlign(alignedRead, alignedRefSequence, idsScoreFn, 12, params.sdpIns, params.sdpDel,
params.indelRate, mappingBuffers, exploded, Local, computeProbIsFalse, 6);
if (params.verbosity >= 3) {
threadOut << "zmw " << unrolledRead.zmwData.holeNumber << ", subreadIndex " << subreadIndex
<< ", passDirection " << passDirection << ", subreadInterval ["
<< subreadInterval.start << ", " << subreadInterval.end << ")" << std::endl
<< "Exploded score " << explodedScore << std::endl
<< "StickPrintAlignment subread-reference alignment which has"
<< " the " << (sameAlignmentPassDirection ? "same" : "different")
<< " direction as the ccs-reference (or the "
<< "longestSubread-reference) alignment. " << std::endl
<< "subread: " << std::endl;
static_cast<DNASequence *>(&alignedRead)->PrintSeq(threadOut);
threadOut << std::endl;
threadOut << "alignedRefSeq: " << std::endl;
static_cast<DNASequence *>(&alignedRefSequence)->PrintSeq(threadOut);
StickPrintAlignment(exploded, (DNASequence &)alignedRead, (DNASequence &)alignedRefSequence,
threadOut, exploded.qAlignedSeqPos, exploded.tAlignedSeqPos);
}
if (exploded.blocks.size() > 0) {
DistanceMatrixScoreFunction<DNASequence, FASTQSequence> distScoreFn(
SMRTDistanceMatrix, params.indel, params.indel);
ComputeAlignmentStats(exploded, alignedRead.seq, alignedRefSequence.seq, distScoreFn2);
if (exploded.score <= params.maxScore) {
//
// The coordinates of the alignment should be
// relative to the reference sequence (the specified chromosome,
// not the whole genome).
//
const DNALength q0 = subreadInterval.start;
const DNALength q1 = unrolledRead.length - subreadInterval.end;
const DNALength t0 = alignment->tAlignedSeqPos;
const DNALength t1 =
alignment->tLength - alignment->tAlignedSeqPos - alignment->tAlignedSeqLength;
const auto ConfigureExploded = [&exploded](const int qStrand, const int tStrand,
const DNALength qasp, const DNALength tasp) {
exploded.qStrand = qStrand;
exploded.tStrand = tStrand;
exploded.tAlignedSeqPos = tasp;
exploded.qAlignedSeqPos = qasp;
};
// Illustrative table below.
// a - alignment, e - exploded alignment
// q - query, t - target, s - strand,
// apos - AlignedSeqPos, asl - AlignedSeqLength,
// P - passDirection, 0=subread has the same direction as the template read
// S - sameAlignmentPassDirection, true/y=subread has the same direction as target
// pgc - place gap consistently,
// F - Forward, R - Reverse, n - false, y - true
// q0 = subreadInterval.start, q1 = a.qLength - a.qtasp - a.qasl
// t0 = a.tapos, t1 = a.tLength - a.tasp - a.tasl
// +----------------------------------------------------------+
// | pgc | P | S | a.qs | a.ts | e.qs | e.ts | e.qasp |e.tasp |
// +----------------------------------------------------------+
// | n | 0 | y | F | F | F | F | q0 | t0 |
// | n | 1 | n | F | F | F | R | q0 | t1 |
// | n | 0 | n | F | R | F | R | q0 | t0 |
// | n | 1 | y | F | R | F | F | q0 | t1 |
// +----------------------------------------------------------+
// | y | 0 | y | F | F | F | F | q0 | t0 |
// | y | 1 | n | F | F | R | F | q1 | t0 |
// | y | 0 | n | R | F | R | F | q1 | t0 |
// | y | 1 | y | R | F | F | F | q0 | t0 |
// +----------------------------------------------------------+
const int eqs = (!params.placeGapConsistently || sameAlignmentPassDirection)
? (Forward)
: (Reverse);
const int ets =
(params.placeGapConsistently || sameAlignmentPassDirection) ? (Forward) : (Reverse);
const DNALength eqasp =
(!params.placeGapConsistently || sameAlignmentPassDirection) ? (q0) : (q1);
const DNALength etasp =
(params.placeGapConsistently || passDirection == 0) ? (t0) : (t1);
ConfigureExploded(eqs, ets, eqasp, etasp);
exploded.qLength = unrolledRead.length;
exploded.tLength = alignment->tLength;
exploded.qAlignedSeqLength = subreadInterval.end - subreadInterval.start;
exploded.tAlignedSeqLength = alignment->tAlignedSeqLength;
exploded.qAlignedSeq.ReferenceSubstring(alignedRead);
exploded.tAlignedSeq.Copy(alignedRefSequence);
exploded.mapQV = alignment->mapQV;
exploded.tName = alignment->tName;
exploded.tIndex = alignment->tIndex;
std::stringstream namestrm;
namestrm << "/" << subreadInterval.start << "_" << subreadInterval.end;
exploded.qName = std::string(unrolledRead.title) + namestrm.str();
//
// Don't call AssignRefContigLocation as the coordinates
// of the alignment is already relative to the chromosome coordiantes.
//
// Save this alignment for printing later.
//
T_AlignmentCandidate *alignmentPtr = new T_AlignmentCandidate;
// Refine concordant alignments
if (params.refineConcordantAlignments) {
std::vector<SMRTSequence *> vquery;
vquery.push_back(&unrolledRead);
SMRTSequence rcUnrolledRead;
unrolledRead.MakeRC(rcUnrolledRead);
vquery.push_back(&rcUnrolledRead);
RefineAlignment(vquery, alignedRefSequence, exploded, params, mappingBuffers);
}
*alignmentPtr = exploded;
//
// Check if need to be filtered
// For now filtering only in concordant mode
// Later add filtration in other modes
//
if (allReadAlignments.alignMode == ZmwSubreads) {
if (params.filterCriteria.Satisfy(alignmentPtr)) {
if (params.verbosity > 3) {
std::cerr << " Filters passed. Adding slave alignment in concordant mode"
<< std::endl;
}
allReadAlignments.AddAlignmentForSeq(subreadIndex, alignmentPtr);
} else {
// delete alignment immediately
if (params.verbosity > 3) {
std::cerr << " Filters failed. Delete alignment immediately" << std::endl;
}
delete alignmentPtr;
}
}
// for all modes except ZmwSubreads no filtering for now
else {
allReadAlignments.AddAlignmentForSeq(subreadIndex, alignmentPtr);
}
} // End of exploded score <= maxScore.
if (params.verbosity >= 3) {
threadOut << "exploded score: " << exploded.score << std::endl
<< "exploded alignment: " << std::endl;
exploded.Print(threadOut);
threadOut << std::endl;
}
} // End of exploded.blocks.size() > 0.
}
|