1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
|
/*
* Copyright 2011, Ben Langmead <blangmea@jhsph.edu>
*
* This file is part of Bowtie 2.
*
* Bowtie 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Bowtie 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Bowtie 2. If not, see <http://www.gnu.org/licenses/>.
*/
#include "aligner_cache.h"
#include "aligner_seed.h"
#include "search_globals.h"
#include "bt2_idx.h"
using namespace std;
/**
* Construct a constraint with no edits of any kind allowed.
*/
Constraint Constraint::exact() {
Constraint c;
c.edits = c.mms = c.ins = c.dels = c.penalty = 0;
return c;
}
/**
* Construct a constraint where the only constraint is a total
* penalty constraint.
*/
Constraint Constraint::penaltyBased(int pen) {
Constraint c;
c.penalty = pen;
return c;
}
/**
* Construct a constraint where the only constraint is a total
* penalty constraint related to the length of the read.
*/
Constraint Constraint::penaltyFuncBased(const SimpleFunc& f) {
Constraint c;
c.penFunc = f;
return c;
}
/**
* Construct a constraint where the only constraint is a total
* penalty constraint.
*/
Constraint Constraint::mmBased(int mms) {
Constraint c;
c.mms = mms;
c.edits = c.dels = c.ins = 0;
return c;
}
/**
* Construct a constraint where the only constraint is a total
* penalty constraint.
*/
Constraint Constraint::editBased(int edits) {
Constraint c;
c.edits = edits;
c.dels = c.ins = c.mms = 0;
return c;
}
//
// Some static methods for constructing some standard SeedPolicies
//
/**
* Given a read, depth and orientation, extract a seed data structure
* from the read and fill in the steps & zones arrays. The Seed
* contains the sequence and quality values.
*/
bool
Seed::instantiate(
const Read& read,
const BTDnaString& seq, // seed read sequence
const BTString& qual, // seed quality sequence
const Scoring& pens,
int depth,
int seedoffidx,
int seedtypeidx,
bool fw,
InstantiatedSeed& is) const
{
assert(overall != NULL);
int seedlen = len;
if((int)read.length() < seedlen) {
// Shrink seed length to fit read if necessary
seedlen = (int)read.length();
}
assert_gt(seedlen, 0);
is.steps.resize(seedlen);
is.zones.resize(seedlen);
// Fill in 'steps' and 'zones'
//
// The 'steps' list indicates which read character should be
// incorporated at each step of the search process. Often we will
// simply proceed from one end to the other, in which case the
// 'steps' list is ascending or descending. In some cases (e.g.
// the 2mm case), we might want to switch directions at least once
// during the search, in which case 'steps' will jump in the
// middle. When an element of the 'steps' list is negative, this
// indicates that the next
//
// The 'zones' list indicates which zone constraint is active at
// each step. Each element of the 'zones' list is a pair; the
// first pair element indicates the applicable zone when
// considering either mismatch or delete (ref gap) events, while
// the second pair element indicates the applicable zone when
// considering insertion (read gap) events. When either pair
// element is a negative number, that indicates that we are about
// to leave the zone for good, at which point we may need to
// evaluate whether we have reached the zone's budget.
//
switch(type) {
case SEED_TYPE_EXACT: {
for(int k = 0; k < seedlen; k++) {
is.steps[k] = -(seedlen - k);
// Zone 0 all the way
is.zones[k].first = is.zones[k].second = 0;
}
break;
}
case SEED_TYPE_LEFT_TO_RIGHT: {
for(int k = 0; k < seedlen; k++) {
is.steps[k] = k+1;
// Zone 0 from 0 up to ceil(len/2), then 1
is.zones[k].first = is.zones[k].second = ((k < (seedlen+1)/2) ? 0 : 1);
}
// Zone 1 ends at the RHS
is.zones[seedlen-1].first = is.zones[seedlen-1].second = -1;
break;
}
case SEED_TYPE_RIGHT_TO_LEFT: {
for(int k = 0; k < seedlen; k++) {
is.steps[k] = -(seedlen - k);
// Zone 0 from 0 up to floor(len/2), then 1
is.zones[k].first = ((k < seedlen/2) ? 0 : 1);
// Inserts: Zone 0 from 0 up to ceil(len/2)-1, then 1
is.zones[k].second = ((k < (seedlen+1)/2+1) ? 0 : 1);
}
is.zones[seedlen-1].first = is.zones[seedlen-1].second = -1;
break;
}
case SEED_TYPE_INSIDE_OUT: {
// Zone 0 from ceil(N/4) up to N-floor(N/4)
int step = 0;
for(int k = (seedlen+3)/4; k < seedlen - (seedlen/4); k++) {
is.zones[step].first = is.zones[step].second = 0;
is.steps[step++] = k+1;
}
// Zone 1 from N-floor(N/4) up
for(int k = seedlen - (seedlen/4); k < seedlen; k++) {
is.zones[step].first = is.zones[step].second = 1;
is.steps[step++] = k+1;
}
// No Zone 1 if seedlen is short (like 2)
//assert_eq(1, is.zones[step-1].first);
is.zones[step-1].first = is.zones[step-1].second = -1;
// Zone 2 from ((seedlen+3)/4)-1 down to 0
for(int k = ((seedlen+3)/4)-1; k >= 0; k--) {
is.zones[step].first = is.zones[step].second = 2;
is.steps[step++] = -(k+1);
}
assert_eq(2, is.zones[step-1].first);
is.zones[step-1].first = is.zones[step-1].second = -2;
assert_eq(seedlen, step);
break;
}
default:
throw 1;
}
// Instantiate constraints
for(int i = 0; i < 3; i++) {
is.cons[i] = zones[i];
is.cons[i].instantiate(read.length());
}
is.overall = *overall;
is.overall.instantiate(read.length());
// Take a sweep through the seed sequence. Consider where the Ns
// occur and how zones are laid out. Calculate the maximum number
// of positions we can jump over initially (e.g. with the ftab) and
// perhaps set this function's return value to false, indicating
// that the arrangements of Ns prevents the seed from aligning.
bool streak = true;
is.maxjump = 0;
bool ret = true;
bool ltr = (is.steps[0] > 0); // true -> left-to-right
for(size_t i = 0; i < is.steps.size(); i++) {
assert_neq(0, is.steps[i]);
int off = is.steps[i];
off = abs(off)-1;
Constraint& cons = is.cons[abs(is.zones[i].first)];
int c = seq[off]; assert_range(0, 4, c);
int q = qual[off];
if(ltr != (is.steps[i] > 0) || // changed direction
is.zones[i].first != 0 || // changed zone
is.zones[i].second != 0) // changed zone
{
streak = false;
}
if(c == 4) {
// Induced mismatch
if(cons.canN(q, pens)) {
cons.chargeN(q, pens);
} else {
// Seed disqualified due to arrangement of Ns
return false;
}
}
if(streak) is.maxjump++;
}
is.seedoff = depth;
is.seedoffidx = seedoffidx;
is.fw = fw;
is.s = *this;
return ret;
}
/**
* Return a set consisting of 1 seed encapsulating an exact matching
* strategy.
*/
void
Seed::zeroMmSeeds(int ln, EList<Seed>& pols, Constraint& oall) {
oall.init();
// Seed policy 1: left-to-right search
pols.expand();
pols.back().len = ln;
pols.back().type = SEED_TYPE_EXACT;
pols.back().zones[0] = Constraint::exact();
pols.back().zones[1] = Constraint::exact();
pols.back().zones[2] = Constraint::exact(); // not used
pols.back().overall = &oall;
}
/**
* Return a set of 2 seeds encapsulating a half-and-half 1mm strategy.
*/
void
Seed::oneMmSeeds(int ln, EList<Seed>& pols, Constraint& oall) {
oall.init();
// Seed policy 1: left-to-right search
pols.expand();
pols.back().len = ln;
pols.back().type = SEED_TYPE_LEFT_TO_RIGHT;
pols.back().zones[0] = Constraint::exact();
pols.back().zones[1] = Constraint::mmBased(1);
pols.back().zones[2] = Constraint::exact(); // not used
pols.back().overall = &oall;
// Seed policy 2: right-to-left search
pols.expand();
pols.back().len = ln;
pols.back().type = SEED_TYPE_RIGHT_TO_LEFT;
pols.back().zones[0] = Constraint::exact();
pols.back().zones[1] = Constraint::mmBased(1);
pols.back().zones[1].mmsCeil = 0;
pols.back().zones[2] = Constraint::exact(); // not used
pols.back().overall = &oall;
}
/**
* Return a set of 3 seeds encapsulating search roots for:
*
* 1. Starting from the left-hand side and searching toward the
* right-hand side allowing 2 mismatches in the right half.
* 2. Starting from the right-hand side and searching toward the
* left-hand side allowing 2 mismatches in the left half.
* 3. Starting (effectively) from the center and searching out toward
* both the left and right-hand sides, allowing one mismatch on
* either side.
*
* This is not exhaustive. There are 2 mismatch cases mised; if you
* imagine the seed as divided into four successive quarters A, B, C
* and D, the cases we miss are when mismatches occur in A and C or B
* and D.
*/
void
Seed::twoMmSeeds(int ln, EList<Seed>& pols, Constraint& oall) {
oall.init();
// Seed policy 1: left-to-right search
pols.expand();
pols.back().len = ln;
pols.back().type = SEED_TYPE_LEFT_TO_RIGHT;
pols.back().zones[0] = Constraint::exact();
pols.back().zones[1] = Constraint::mmBased(2);
pols.back().zones[2] = Constraint::exact(); // not used
pols.back().overall = &oall;
// Seed policy 2: right-to-left search
pols.expand();
pols.back().len = ln;
pols.back().type = SEED_TYPE_RIGHT_TO_LEFT;
pols.back().zones[0] = Constraint::exact();
pols.back().zones[1] = Constraint::mmBased(2);
pols.back().zones[1].mmsCeil = 1; // Must have used at least 1 mismatch
pols.back().zones[2] = Constraint::exact(); // not used
pols.back().overall = &oall;
// Seed policy 3: inside-out search
pols.expand();
pols.back().len = ln;
pols.back().type = SEED_TYPE_INSIDE_OUT;
pols.back().zones[0] = Constraint::exact();
pols.back().zones[1] = Constraint::mmBased(1);
pols.back().zones[1].mmsCeil = 0; // Must have used at least 1 mismatch
pols.back().zones[2] = Constraint::mmBased(1);
pols.back().zones[2].mmsCeil = 0; // Must have used at least 1 mismatch
pols.back().overall = &oall;
}
/**
* Types of actions that can be taken by the SeedAligner.
*/
enum {
SA_ACTION_TYPE_RESET = 1,
SA_ACTION_TYPE_SEARCH_SEED, // 2
SA_ACTION_TYPE_FTAB, // 3
SA_ACTION_TYPE_FCHR, // 4
SA_ACTION_TYPE_MATCH, // 5
SA_ACTION_TYPE_EDIT // 6
};
#define MIN(x, y) ((x < y) ? x : y)
/**
* Given a read and a few coordinates that describe a substring of the read (or
* its reverse complement), fill in 'seq' and 'qual' objects with the seed
* sequence and qualities.
*
* The seq field is filled with the sequence as it would align to the Watson
* reference strand. I.e. if fw is false, then the sequence that appears in
* 'seq' is the reverse complement of the raw read substring.
*/
void
SeedAligner::instantiateSeq(
const Read& read, // input read
BTDnaString& seq, // output sequence
BTString& qual, // output qualities
int len, // seed length
int depth, // seed's 0-based offset from 5' end
bool fw) const // seed's orientation
{
// Fill in 'seq' and 'qual'
int seedlen = len;
if((int)read.length() < seedlen) seedlen = (int)read.length();
seq.resize(len);
qual.resize(len);
// If fw is false, we take characters starting at the 3' end of the
// reverse complement of the read.
for(int i = 0; i < len; i++) {
seq.set(read.patFw.windowGetDna(i, fw, read.color, depth, len), i);
qual.set(read.qual.windowGet(i, fw, depth, len), i);
}
}
/**
* We assume that all seeds are the same length.
*
* For each seed, instantiate the seed, retracting if necessary.
*/
pair<int, int> SeedAligner::instantiateSeeds(
const EList<Seed>& seeds, // search seeds
size_t off, // offset into read to start extracting
int per, // interval between seeds
const Read& read, // read to align
const Scoring& pens, // scoring scheme
bool nofw, // don't align forward read
bool norc, // don't align revcomp read
AlignmentCacheIface& cache,// holds some seed hits from previous reads
SeedResults& sr, // holds all the seed hits
SeedSearchMetrics& met) // metrics
{
assert(!seeds.empty());
assert_gt(read.length(), 0);
// Check whether read has too many Ns
offIdx2off_.clear();
int len = seeds[0].len; // assume they're all the same length
#ifndef NDEBUG
for(size_t i = 1; i < seeds.size(); i++) {
assert_eq(len, seeds[i].len);
}
#endif
// Calc # seeds within read interval
int nseeds = 1;
if((int)read.length() - (int)off > len) {
nseeds += ((int)read.length() - (int)off - len) / per;
}
for(int i = 0; i < nseeds; i++) {
offIdx2off_.push_back(per * i + (int)off);
}
pair<int, int> ret;
ret.first = 0; // # seeds that require alignment
ret.second = 0; // # seeds that hit in cache with non-empty results
sr.reset(read, offIdx2off_, nseeds);
assert(sr.repOk(&cache.current(), true)); // require that SeedResult be initialized
// For each seed position
for(int fwi = 0; fwi < 2; fwi++) {
bool fw = (fwi == 0);
if((fw && nofw) || (!fw && norc)) {
// Skip this orientation b/c user specified --nofw or --norc
continue;
}
// For each seed position
for(int i = 0; i < nseeds; i++) {
int depth = i * per + (int)off;
int seedlen = seeds[0].len;
// Extract the seed sequence at this offset
// If fw == true, we extract the characters from i*per to
// i*(per-1) (exclusive). If fw == false,
instantiateSeq(
read,
sr.seqs(fw)[i],
sr.quals(fw)[i],
std::min<int>((int)seedlen, (int)read.length()),
depth,
fw);
QKey qk(sr.seqs(fw)[i] ASSERT_ONLY(, tmpdnastr_));
// For each search strategy
EList<InstantiatedSeed>& iss = sr.instantiatedSeeds(fw, i);
for(int j = 0; j < (int)seeds.size(); j++) {
iss.expand();
assert_eq(seedlen, seeds[j].len);
InstantiatedSeed* is = &iss.back();
if(seeds[j].instantiate(
read,
sr.seqs(fw)[i],
sr.quals(fw)[i],
pens,
depth,
i,
j,
fw,
*is))
{
// Can we fill this seed hit in from the cache?
ret.first++;
} else {
// Seed may fail to instantiate if there are Ns
// that prevent it from matching
met.filteredseed++;
iss.pop_back();
}
}
}
}
return ret;
}
/**
* We assume that all seeds are the same length.
*
* For each seed:
*
* 1. Instantiate all seeds, retracting them if necessary.
* 2. Calculate zone boundaries for each seed
*/
void SeedAligner::searchAllSeeds(
const EList<Seed>& seeds, // search seeds
const Ebwt* ebwtFw, // BWT index
const Ebwt* ebwtBw, // BWT' index
const Read& read, // read to align
const Scoring& pens, // scoring scheme
AlignmentCacheIface& cache, // local cache for seed alignments
SeedResults& sr, // holds all the seed hits
SeedSearchMetrics& met, // metrics
PerReadMetrics& prm) // per-read metrics
{
assert(!seeds.empty());
assert(ebwtFw != NULL);
assert(ebwtFw->isInMemory());
assert(sr.repOk(&cache.current()));
ebwtFw_ = ebwtFw;
ebwtBw_ = ebwtBw;
sc_ = &pens;
read_ = &read;
ca_ = &cache;
bwops_ = bwedits_ = 0;
uint64_t possearches = 0, seedsearches = 0, intrahits = 0, interhits = 0, ooms = 0;
// For each instantiated seed
for(int i = 0; i < (int)sr.numOffs(); i++) {
size_t off = sr.idx2off(i);
for(int fwi = 0; fwi < 2; fwi++) {
bool fw = (fwi == 0);
assert(sr.repOk(&cache.current()));
EList<InstantiatedSeed>& iss = sr.instantiatedSeeds(fw, i);
if(iss.empty()) {
// Cache hit in an across-read cache
continue;
}
QVal qv;
seq_ = &sr.seqs(fw)[i]; // seed sequence
qual_ = &sr.quals(fw)[i]; // seed qualities
off_ = off; // seed offset (from 5')
fw_ = fw; // seed orientation
// Tell the cache that we've started aligning, so the cache can
// expect a series of on-the-fly updates
int ret = cache.beginAlign(*seq_, *qual_, qv);
ASSERT_ONLY(hits_.clear());
if(ret == -1) {
// Out of memory when we tried to add key to map
ooms++;
continue;
}
bool abort = false;
if(ret == 0) {
// Not already in cache
assert(cache.aligning());
possearches++;
for(size_t j = 0; j < iss.size(); j++) {
// Set seq_ and qual_ appropriately, using the seed sequences
// and qualities already installed in SeedResults
assert_eq(fw, iss[j].fw);
assert_eq(i, (int)iss[j].seedoffidx);
s_ = &iss[j];
// Do the search with respect to seq_, qual_ and s_.
if(!searchSeedBi()) {
// Memory exhausted during search
ooms++;
abort = true;
break;
}
seedsearches++;
assert(cache.aligning());
}
if(!abort) {
qv = cache.finishAlign();
}
} else {
// Already in cache
assert_eq(1, ret);
assert(qv.valid());
intrahits++;
}
assert(abort || !cache.aligning());
if(qv.valid()) {
sr.add(
qv, // range of ranges in cache
cache.current(), // cache
i, // seed index (from 5' end)
fw); // whether seed is from forward read
}
}
}
prm.nSdFmops += bwops_;
met.seedsearch += seedsearches;
met.possearch += possearches;
met.intrahit += intrahits;
met.interhit += interhits;
met.ooms += ooms;
met.bwops += bwops_;
met.bweds += bwedits_;
}
bool SeedAligner::sanityPartial(
const Ebwt* ebwtFw, // BWT index
const Ebwt* ebwtBw, // BWT' index
const BTDnaString& seq,
size_t dep,
size_t len,
bool do1mm,
uint32_t topfw,
uint32_t botfw,
uint32_t topbw,
uint32_t botbw)
{
tmpdnastr_.clear();
for(size_t i = dep; i < len; i++) {
tmpdnastr_.append(seq[i]);
}
uint32_t top_fw = 0, bot_fw = 0;
ebwtFw->contains(tmpdnastr_, &top_fw, &bot_fw);
assert_eq(top_fw, topfw);
assert_eq(bot_fw, botfw);
if(do1mm && ebwtBw != NULL) {
tmpdnastr_.reverse();
uint32_t top_bw = 0, bot_bw = 0;
ebwtBw->contains(tmpdnastr_, &top_bw, &bot_bw);
assert_eq(top_bw, topbw);
assert_eq(bot_bw, botbw);
}
return true;
}
/**
* Sweep right-to-left and left-to-right using exact matching. Remember all
* the SA ranges encountered along the way. Report exact matches if there are
* any. Calculate a lower bound on the number of edits in an end-to-end
* alignment.
*/
size_t SeedAligner::exactSweep(
const Ebwt& ebwt, // BWT index
const Read& read, // read to align
const Scoring& sc, // scoring scheme
bool nofw, // don't align forward read
bool norc, // don't align revcomp read
size_t mineMax, // don't care about edit bounds > this
size_t& mineFw, // minimum # edits for forward read
size_t& mineRc, // minimum # edits for revcomp read
bool repex, // report 0mm hits?
SeedResults& hits, // holds all the seed hits (and exact hit)
SeedSearchMetrics& met) // metrics
{
assert_gt(mineMax, 0);
uint32_t top = 0, bot = 0;
SideLocus tloc, bloc;
const size_t len = read.length();
size_t nelt = 0;
for(int fwi = 0; fwi < 2; fwi++) {
bool fw = (fwi == 0);
if( fw && nofw) continue;
if(!fw && norc) continue;
const BTDnaString& seq = fw ? read.patFw : read.patRc;
assert(!seq.empty());
int ftabLen = ebwt.eh().ftabChars();
size_t dep = 0;
size_t nedit = 0;
bool done = false;
while(dep < len && !done) {
top = bot = 0;
size_t left = len - dep;
assert_gt(left, 0);
bool doFtab = ftabLen > 1 && left >= (size_t)ftabLen;
if(doFtab) {
// Does N interfere with use of Ftab?
for(size_t i = 0; i < (size_t)ftabLen; i++) {
int c = seq[len-dep-1-i];
if(c > 3) {
doFtab = false;
break;
}
}
}
if(doFtab) {
// Use ftab
ebwt.ftabLoHi(seq, len - dep - ftabLen, false, top, bot);
dep += (size_t)ftabLen;
} else {
// Use fchr
int c = seq[len-dep-1];
if(c < 4) {
top = ebwt.fchr()[c];
bot = ebwt.fchr()[c+1];
}
dep++;
}
if(bot <= top) {
nedit++;
if(nedit >= mineMax) {
if(fw) { mineFw = nedit; } else { mineRc = nedit; }
break;
}
continue;
}
INIT_LOCS(top, bot, tloc, bloc, ebwt);
// Keep going
while(dep < len) {
int c = seq[len-dep-1];
if(c > 3) {
top = bot = 0;
} else {
if(bloc.valid()) {
bwops_ += 2;
top = ebwt.mapLF(tloc, c);
bot = ebwt.mapLF(bloc, c);
} else {
bwops_++;
top = ebwt.mapLF1(top, tloc, c);
if(top == 0xffffffff) {
top = bot = 0;
} else {
bot = top+1;
}
}
}
if(bot <= top) {
nedit++;
if(nedit >= mineMax) {
if(fw) { mineFw = nedit; } else { mineRc = nedit; }
done = true;
}
break;
}
INIT_LOCS(top, bot, tloc, bloc, ebwt);
dep++;
}
if(done) {
break;
}
if(dep == len) {
// Set the minimum # edits
if(fw) { mineFw = nedit; } else { mineRc = nedit; }
// Done
if(nedit == 0 && bot > top) {
if(repex) {
// This is an exact hit
int64_t score = len * sc.match();
if(fw) {
hits.addExactEeFw(top, bot, NULL, NULL, fw, score);
assert(ebwt.contains(seq, NULL, NULL));
} else {
hits.addExactEeRc(top, bot, NULL, NULL, fw, score);
assert(ebwt.contains(seq, NULL, NULL));
}
}
nelt += (bot - top);
}
break;
}
dep++;
}
}
return nelt;
}
/**
* Search for end-to-end exact hit for read. Return true iff one is found.
*/
bool SeedAligner::oneMmSearch(
const Ebwt* ebwtFw, // BWT index
const Ebwt* ebwtBw, // BWT' index
const Read& read, // read to align
const Scoring& sc, // scoring
int64_t minsc, // minimum score
bool nofw, // don't align forward read
bool norc, // don't align revcomp read
bool local, // 1mm hits must be legal local alignments
bool repex, // report 0mm hits?
bool rep1mm, // report 1mm hits?
SeedResults& hits, // holds all the seed hits (and exact hit)
SeedSearchMetrics& met) // metrics
{
assert(!rep1mm || ebwtBw != NULL);
const size_t len = read.length();
int nceil = sc.nCeil.f<int>((double)len);
size_t ns = read.ns();
if(ns > 1) {
// Can't align this with <= 1 mismatches
return false;
} else if(ns == 1 && !rep1mm) {
// Can't align this with 0 mismatches
return false;
}
assert_geq(len, 2);
assert(!rep1mm || ebwtBw->eh().ftabChars() == ebwtFw->eh().ftabChars());
#ifndef NDEBUG
if(ebwtBw != NULL) {
for(int i = 0; i < 4; i++) {
assert_eq(ebwtBw->fchr()[i], ebwtFw->fchr()[i]);
}
}
#endif
size_t halfFw = len >> 1;
size_t halfBw = len >> 1;
if((len & 1) != 0) {
halfBw++;
}
assert_geq(halfFw, 1);
assert_geq(halfBw, 1);
SideLocus tloc, bloc;
uint32_t t[4], b[4]; // dest BW ranges for BWT
t[0] = t[1] = t[2] = t[3] = 0;
b[0] = b[1] = b[2] = b[3] = 0;
uint32_t tp[4], bp[4]; // dest BW ranges for BWT'
tp[0] = tp[1] = tp[2] = tp[3] = 0;
bp[0] = bp[1] = bp[2] = bp[3] = 0;
uint32_t top = 0, bot = 0, topp = 0, botp = 0;
// Align fw read / rc read
bool results = false;
for(int fwi = 0; fwi < 2; fwi++) {
bool fw = (fwi == 0);
if( fw && nofw) continue;
if(!fw && norc) continue;
// Align going right-to-left, left-to-right
int lim = rep1mm ? 2 : 1;
for(int ebwtfwi = 0; ebwtfwi < lim; ebwtfwi++) {
bool ebwtfw = (ebwtfwi == 0);
const Ebwt* ebwt = (ebwtfw ? ebwtFw : ebwtBw);
const Ebwt* ebwtp = (ebwtfw ? ebwtBw : ebwtFw);
assert(rep1mm || ebwt->fw());
const BTDnaString& seq =
(fw ? (ebwtfw ? read.patFw : read.patFwRev) :
(ebwtfw ? read.patRc : read.patRcRev));
assert(!seq.empty());
const BTString& qual =
(fw ? (ebwtfw ? read.qual : read.qualRev) :
(ebwtfw ? read.qualRev : read.qual));
int ftabLen = ebwt->eh().ftabChars();
size_t nea = ebwtfw ? halfFw : halfBw;
// Check if there's an N in the near portion
bool skip = false;
for(size_t dep = 0; dep < nea; dep++) {
if(seq[len-dep-1] > 3) {
skip = true;
break;
}
}
if(skip) {
continue;
}
size_t dep = 0;
// Align near half
if(ftabLen > 1 && (size_t)ftabLen <= nea) {
// Use ftab to jump partway into near half
bool rev = !ebwtfw;
ebwt->ftabLoHi(seq, len - ftabLen, rev, top, bot);
if(rep1mm) {
ebwtp->ftabLoHi(seq, len - ftabLen, rev, topp, botp);
assert_eq(bot - top, botp - topp);
}
if(bot - top == 0) {
continue;
}
int c = seq[len - ftabLen];
t[c] = top; b[c] = bot;
tp[c] = topp; bp[c] = botp;
dep = ftabLen;
// initialize tloc, bloc??
} else {
// Use fchr to jump in by 1 pos
int c = seq[len-1];
assert_range(0, 3, c);
top = topp = tp[c] = ebwt->fchr()[c];
bot = botp = bp[c] = ebwt->fchr()[c+1];
if(bot - top == 0) {
continue;
}
dep = 1;
// initialize tloc, bloc??
}
INIT_LOCS(top, bot, tloc, bloc, *ebwt);
assert(sanityPartial(ebwt, ebwtp, seq, len-dep, len, rep1mm, top, bot, topp, botp));
bool do_continue = false;
for(; dep < nea; dep++) {
assert_lt(dep, len);
int rdc = seq[len - dep - 1];
tp[0] = tp[1] = tp[2] = tp[3] = topp;
bp[0] = bp[1] = bp[2] = bp[3] = botp;
if(bloc.valid()) {
bwops_++;
t[0] = t[1] = t[2] = t[3] = b[0] = b[1] = b[2] = b[3] = 0;
ebwt->mapBiLFEx(tloc, bloc, t, b, tp, bp);
SANITY_CHECK_4TUP(t, b, tp, bp);
top = t[rdc]; bot = b[rdc];
if(bot <= top) {
do_continue = true;
break;
}
topp = tp[rdc]; botp = bp[rdc];
assert(!rep1mm || bot - top == botp - topp);
} else {
assert_eq(bot, top+1);
assert(!rep1mm || botp == topp+1);
bwops_++;
top = ebwt->mapLF1(top, tloc, rdc);
if(top == 0xffffffff) {
do_continue = true;
break;
}
bot = top + 1;
t[rdc] = top; b[rdc] = bot;
tp[rdc] = topp; bp[rdc] = botp;
assert(!rep1mm || b[rdc] - t[rdc] == bp[rdc] - tp[rdc]);
// topp/botp stay the same
}
INIT_LOCS(top, bot, tloc, bloc, *ebwt);
assert(sanityPartial(ebwt, ebwtp, seq, len - dep - 1, len, rep1mm, top, bot, topp, botp));
}
if(do_continue) {
continue;
}
// Align far half
for(; dep < len; dep++) {
int rdc = seq[len-dep-1];
int quc = qual[len-dep-1];
if(rdc > 3 && nceil == 0) {
break;
}
tp[0] = tp[1] = tp[2] = tp[3] = topp;
bp[0] = bp[1] = bp[2] = bp[3] = botp;
int clo = 0, chi = 3;
bool match = true;
if(bloc.valid()) {
bwops_++;
t[0] = t[1] = t[2] = t[3] = b[0] = b[1] = b[2] = b[3] = 0;
ebwt->mapBiLFEx(tloc, bloc, t, b, tp, bp);
SANITY_CHECK_4TUP(t, b, tp, bp);
match = rdc < 4;
top = t[rdc]; bot = b[rdc];
topp = tp[rdc]; botp = bp[rdc];
} else {
assert_eq(bot, top+1);
assert(!rep1mm || botp == topp+1);
bwops_++;
clo = ebwt->mapLF1(top, tloc);
match = (clo == rdc);
assert_range(-1, 3, clo);
if(clo < 0) {
break; // Hit the $
} else {
t[clo] = top;
b[clo] = bot = top + 1;
}
bp[clo] = botp;
tp[clo] = topp;
assert(!rep1mm || bot - top == botp - topp);
assert(!rep1mm || b[clo] - t[clo] == bp[clo] - tp[clo]);
chi = clo;
}
//assert(sanityPartial(ebwt, ebwtp, seq, len - dep - 1, len, rep1mm, top, bot, topp, botp));
if(rep1mm && (ns == 0 || rdc > 3)) {
for(int j = clo; j <= chi; j++) {
if(j == rdc || b[j] == t[j]) {
// Either matches read or isn't a possibility
continue;
}
// Potential mismatch - next, try
size_t depm = dep + 1;
uint32_t topm = t[j], botm = b[j];
uint32_t topmp = tp[j], botmp = bp[j];
assert_eq(botm - topm, botmp - topmp);
uint32_t tm[4], bm[4]; // dest BW ranges for BWT
tm[0] = t[0]; tm[1] = t[1];
tm[2] = t[2]; tm[3] = t[3];
bm[0] = b[0]; bm[1] = t[1];
bm[2] = b[2]; bm[3] = t[3];
uint32_t tmp[4], bmp[4]; // dest BW ranges for BWT'
tmp[0] = tp[0]; tmp[1] = tp[1];
tmp[2] = tp[2]; tmp[3] = tp[3];
bmp[0] = bp[0]; bmp[1] = tp[1];
bmp[2] = bp[2]; bmp[3] = tp[3];
SideLocus tlocm, blocm;
INIT_LOCS(topm, botm, tlocm, blocm, *ebwt);
for(; depm < len; depm++) {
int rdcm = seq[len - depm - 1];
tmp[0] = tmp[1] = tmp[2] = tmp[3] = topmp;
bmp[0] = bmp[1] = bmp[2] = bmp[3] = botmp;
if(blocm.valid()) {
bwops_++;
tm[0] = tm[1] = tm[2] = tm[3] =
bm[0] = bm[1] = bm[2] = bm[3] = 0;
ebwt->mapBiLFEx(tlocm, blocm, tm, bm, tmp, bmp);
SANITY_CHECK_4TUP(tm, bm, tmp, bmp);
topm = tm[rdcm]; botm = bm[rdcm];
topmp = tmp[rdcm]; botmp = bmp[rdcm];
if(botm <= topm) {
break;
}
} else {
assert_eq(botm, topm+1);
assert_eq(botmp, topmp+1);
bwops_++;
topm = ebwt->mapLF1(topm, tlocm, rdcm);
if(topm == 0xffffffff) {
break;
}
botm = topm + 1;
// topp/botp stay the same
}
INIT_LOCS(topm, botm, tlocm, blocm, *ebwt);
}
if(depm == len) {
// Success; this is a 1MM hit
size_t off5p = dep; // offset from 5' end of read
size_t offstr = dep; // offset into patFw/patRc
if(fw == ebwtfw) {
off5p = len - off5p - 1;
}
if(!ebwtfw) {
offstr = len - offstr - 1;
}
Edit e((uint32_t)off5p, j, rdc, EDIT_TYPE_MM, false);
results = true;
int64_t score = (len - 1) * sc.match();
// In --local mode, need to double-check that
// end-to-end alignment doesn't violate local
// alignment principles. Specifically, it
// shouldn't to or below 0 anywhere in the middle.
int pen = sc.score(rdc, (int)(1 << j), quc - 33);
score += pen;
bool valid = true;
if(local) {
int64_t locscore_fw = 0, locscore_bw = 0;
for(size_t i = 0; i < len; i++) {
if(i == dep) {
if(locscore_fw + pen <= 0) {
valid = false;
break;
}
locscore_fw += pen;
} else {
locscore_fw += sc.match();
}
if(len-i-1 == dep) {
if(locscore_bw + pen <= 0) {
valid = false;
break;
}
locscore_bw += pen;
} else {
locscore_bw += sc.match();
}
}
}
if(valid) {
valid = score >= minsc;
}
if(valid) {
#ifndef NDEBUG
BTDnaString& rf = tmprfdnastr_;
rf.clear();
edits_.clear();
edits_.push_back(e);
if(!fw) Edit::invertPoss(edits_, len);
Edit::toRef(fw ? read.patFw : read.patRc, edits_, rf);
if(!fw) Edit::invertPoss(edits_, len);
assert_eq(len, rf.length());
for(size_t i = 0; i < len; i++) {
assert_lt((int)rf[i], 4);
}
ASSERT_ONLY(uint32_t toptmp = 0);
ASSERT_ONLY(uint32_t bottmp = 0);
assert(ebwtFw->contains(rf, &toptmp, &bottmp));
#endif
uint32_t toprep = ebwtfw ? topm : topmp;
uint32_t botrep = ebwtfw ? botm : botmp;
assert_eq(toprep, toptmp);
assert_eq(botrep, bottmp);
hits.add1mmEe(toprep, botrep, &e, NULL, fw, score);
}
}
}
}
if(bot > top && match) {
assert_lt(rdc, 4);
if(dep == len-1) {
// Success; this is an exact hit
if(ebwtfw && repex) {
if(fw) {
results = true;
int64_t score = len * sc.match();
hits.addExactEeFw(
ebwtfw ? top : topp,
ebwtfw ? bot : botp,
NULL, NULL, fw, score);
assert(ebwtFw->contains(seq, NULL, NULL));
} else {
results = true;
int64_t score = len * sc.match();
hits.addExactEeRc(
ebwtfw ? top : topp,
ebwtfw ? bot : botp,
NULL, NULL, fw, score);
assert(ebwtFw->contains(seq, NULL, NULL));
}
}
break; // End of far loop
} else {
INIT_LOCS(top, bot, tloc, bloc, *ebwt);
assert(sanityPartial(ebwt, ebwtp, seq, len - dep - 1, len, rep1mm, top, bot, topp, botp));
}
} else {
break; // End of far loop
}
} // for(; dep < len; dep++)
} // for(int ebwtfw = 0; ebwtfw < 2; ebwtfw++)
} // for(int fw = 0; fw < 2; fw++)
return results;
}
/**
* Wrapper for initial invcation of searchSeed.
*/
bool
SeedAligner::searchSeedBi() {
return searchSeedBi(
0, 0,
0, 0, 0, 0,
SideLocus(), SideLocus(),
s_->cons[0], s_->cons[1], s_->cons[2], s_->overall,
NULL);
}
/**
* Get tloc, bloc ready for the next step. If the new range is under
* the ceiling.
*/
inline void
SeedAligner::nextLocsBi(
SideLocus& tloc, // top locus
SideLocus& bloc, // bot locus
uint32_t topf, // top in BWT
uint32_t botf, // bot in BWT
uint32_t topb, // top in BWT'
uint32_t botb, // bot in BWT'
int step // step to get ready for
#if 0
, const SABWOffTrack* prevOt, // previous tracker
SABWOffTrack& ot // current tracker
#endif
)
{
assert_gt(botf, 0);
assert(ebwtBw_ == NULL || botb > 0);
assert_geq(step, 0); // next step can't be first one
assert(ebwtBw_ == NULL || botf-topf == botb-topb);
if(step == (int)s_->steps.size()) return; // no more steps!
// Which direction are we going in next?
if(s_->steps[step] > 0) {
// Left to right; use BWT'
if(botb - topb == 1) {
// Already down to 1 row; just init top locus
tloc.initFromRow(topb, ebwtBw_->eh(), ebwtBw_->ebwt());
bloc.invalidate();
} else {
SideLocus::initFromTopBot(
topb, botb, ebwtBw_->eh(), ebwtBw_->ebwt(), tloc, bloc);
assert(bloc.valid());
}
} else {
// Right to left; use BWT
if(botf - topf == 1) {
// Already down to 1 row; just init top locus
tloc.initFromRow(topf, ebwtFw_->eh(), ebwtFw_->ebwt());
bloc.invalidate();
} else {
SideLocus::initFromTopBot(
topf, botf, ebwtFw_->eh(), ebwtFw_->ebwt(), tloc, bloc);
assert(bloc.valid());
}
}
// Check if we should update the tracker with this refinement
#if 0
if(botf-topf <= BW_OFF_TRACK_CEIL) {
if(ot.size() == 0 && prevOt != NULL && prevOt->size() > 0) {
// Inherit state from the predecessor
ot = *prevOt;
}
bool ltr = s_->steps[step-1] > 0;
int adj = abs(s_->steps[step-1])-1;
const Ebwt* ebwt = ltr ? ebwtBw_ : ebwtFw_;
ot.update(
ltr ? topb : topf, // top
ltr ? botb : botf, // bot
adj, // adj (to be subtracted from offset)
ebwt->offs(), // offs array
ebwt->eh().offRate(), // offrate (sample = every 1 << offrate elts)
NULL // dead
);
assert_gt(ot.size(), 0);
}
#endif
assert(botf - topf == 1 || bloc.valid());
assert(botf - topf > 1 || !bloc.valid());
}
/**
* Report a seed hit found by searchSeedBi(), but first try to extend it out in
* either direction as far as possible without hitting any edits. This will
* allow us to prioritize the seed hits better later on. Call reportHit() when
* we're done, which actually adds the hit to the cache. Returns result from
* calling reportHit().
*/
bool
SeedAligner::extendAndReportHit(
uint32_t topf, // top in BWT
uint32_t botf, // bot in BWT
uint32_t topb, // top in BWT'
uint32_t botb, // bot in BWT'
uint16_t len, // length of hit
DoublyLinkedList<Edit> *prevEdit) // previous edit
{
size_t nlex = 0, nrex = 0;
uint32_t t[4], b[4];
uint32_t tp[4], bp[4];
SideLocus tloc, bloc;
if(off_ > 0) {
const Ebwt *ebwt = ebwtFw_;
assert(ebwt != NULL);
// Extend left using forward index
const BTDnaString& seq = fw_ ? read_->patFw : read_->patRc;
// See what we get by extending
uint32_t top = topf, bot = botf;
t[0] = t[1] = t[2] = t[3] = 0;
b[0] = b[1] = b[2] = b[3] = 0;
tp[0] = tp[1] = tp[2] = tp[3] = topb;
bp[0] = bp[1] = bp[2] = bp[3] = botb;
SideLocus tloc, bloc;
INIT_LOCS(top, bot, tloc, bloc, *ebwt);
for(size_t ii = off_; ii > 0; ii--) {
size_t i = ii-1;
// Get char from read
int rdc = seq.get(i);
// See what we get by extending
if(bloc.valid()) {
bwops_++;
t[0] = t[1] = t[2] = t[3] =
b[0] = b[1] = b[2] = b[3] = 0;
ebwt->mapBiLFEx(tloc, bloc, t, b, tp, bp);
SANITY_CHECK_4TUP(t, b, tp, bp);
int nonz = -1;
bool abort = false;
for(int j = 0; j < 4; j++) {
if(b[i] > t[i]) {
if(nonz >= 0) {
abort = true;
break;
}
nonz = j;
top = t[i]; bot = b[i];
}
}
if(abort || nonz != rdc) {
break;
}
} else {
assert_eq(bot, top+1);
bwops_++;
int c = ebwt->mapLF1(top, tloc);
if(c != rdc) {
break;
}
bot = top + 1;
}
if(++nlex == 255) {
break;
}
INIT_LOCS(top, bot, tloc, bloc, *ebwt);
}
}
size_t rdlen = read_->length();
size_t nright = rdlen - off_ - len;
if(nright > 0 && ebwtBw_ != NULL) {
const Ebwt *ebwt = ebwtBw_;
assert(ebwt != NULL);
// Extend right using backward index
const BTDnaString& seq = fw_ ? read_->patFw : read_->patRc;
// See what we get by extending
uint32_t top = topb, bot = botb;
t[0] = t[1] = t[2] = t[3] = 0;
b[0] = b[1] = b[2] = b[3] = 0;
tp[0] = tp[1] = tp[2] = tp[3] = topb;
bp[0] = bp[1] = bp[2] = bp[3] = botb;
INIT_LOCS(top, bot, tloc, bloc, *ebwt);
for(size_t i = off_ + len; i < rdlen; i++) {
// Get char from read
int rdc = seq.get(i);
// See what we get by extending
if(bloc.valid()) {
bwops_++;
t[0] = t[1] = t[2] = t[3] =
b[0] = b[1] = b[2] = b[3] = 0;
ebwt->mapBiLFEx(tloc, bloc, t, b, tp, bp);
SANITY_CHECK_4TUP(t, b, tp, bp);
int nonz = -1;
bool abort = false;
for(int j = 0; j < 4; j++) {
if(b[i] > t[i]) {
if(nonz >= 0) {
abort = true;
break;
}
nonz = j;
top = t[i]; bot = b[i];
}
}
if(abort || nonz != rdc) {
break;
}
} else {
assert_eq(bot, top+1);
bwops_++;
int c = ebwt->mapLF1(top, tloc);
if(c != rdc) {
break;
}
bot = top + 1;
}
if(++nrex == 255) {
break;
}
INIT_LOCS(top, bot, tloc, bloc, *ebwt);
}
}
assert_lt(nlex, rdlen);
assert_leq(nlex, off_);
assert_lt(nrex, rdlen);
return reportHit(topf, botf, topb, botb, len, prevEdit);
}
/**
* Report a seed hit found by searchSeedBi() by adding it to the cache. Return
* false if the hit could not be reported because of, e.g., cache exhaustion.
*/
bool
SeedAligner::reportHit(
uint32_t topf, // top in BWT
uint32_t botf, // bot in BWT
uint32_t topb, // top in BWT'
uint32_t botb, // bot in BWT'
uint16_t len, // length of hit
DoublyLinkedList<Edit> *prevEdit) // previous edit
{
// Add information about the seed hit to AlignmentCache. This
// information eventually makes its way back to the SeedResults
// object when we call finishAlign(...).
BTDnaString& rf = tmprfdnastr_;
rf.clear();
edits_.clear();
if(prevEdit != NULL) {
prevEdit->toList(edits_);
Edit::sort(edits_);
assert(Edit::repOk(edits_, *seq_));
Edit::toRef(*seq_, edits_, rf);
} else {
rf = *seq_;
}
// Sanity check: shouldn't add the same hit twice. If this
// happens, it may be because our zone Constraints are not set up
// properly and erroneously return true from acceptable() when they
// should return false in some cases.
assert_eq(hits_.size(), ca_->curNumRanges());
assert(hits_.insert(rf));
if(!ca_->addOnTheFly(rf, topf, botf, topb, botb)) {
return false;
}
assert_eq(hits_.size(), ca_->curNumRanges());
#ifndef NDEBUG
// Sanity check that the topf/botf and topb/botb ranges really
// correspond to the reference sequence aligned to
{
BTDnaString rfr;
uint32_t tpf, btf, tpb, btb;
tpf = btf = tpb = btb = 0;
assert(ebwtFw_->contains(rf, &tpf, &btf));
if(ebwtBw_ != NULL) {
rfr = rf;
rfr.reverse();
assert(ebwtBw_->contains(rfr, &tpb, &btb));
assert_eq(tpf, topf);
assert_eq(btf, botf);
assert_eq(tpb, topb);
assert_eq(btb, botb);
}
}
#endif
return true;
}
/**
* Given a seed, search. Assumes zone 0 = no backtracking.
*
* Return a list of Seed hits.
* 1. Edits
* 2. Bidirectional BWT range(s) on either end
*/
bool
SeedAligner::searchSeedBi(
int step, // depth into steps_[] array
int depth, // recursion depth
uint32_t topf, // top in BWT
uint32_t botf, // bot in BWT
uint32_t topb, // top in BWT'
uint32_t botb, // bot in BWT'
SideLocus tloc, // locus for top (perhaps unititialized)
SideLocus bloc, // locus for bot (perhaps unititialized)
Constraint c0, // constraints to enforce in seed zone 0
Constraint c1, // constraints to enforce in seed zone 1
Constraint c2, // constraints to enforce in seed zone 2
Constraint overall, // overall constraints to enforce
DoublyLinkedList<Edit> *prevEdit // previous edit
#if 0
, const SABWOffTrack* prevOt // prev off tracker (if tracking started)
#endif
)
{
assert(s_ != NULL);
const InstantiatedSeed& s = *s_;
assert_gt(s.steps.size(), 0);
assert(ebwtBw_ == NULL || ebwtBw_->eh().ftabChars() == ebwtFw_->eh().ftabChars());
#ifndef NDEBUG
for(int i = 0; i < 4; i++) {
assert(ebwtBw_ == NULL || ebwtBw_->fchr()[i] == ebwtFw_->fchr()[i]);
}
#endif
if(step == (int)s.steps.size()) {
// Finished aligning seed
assert(c0.acceptable());
assert(c1.acceptable());
assert(c2.acceptable());
if(!reportHit(topf, botf, topb, botb, seq_->length(), prevEdit)) {
return false; // Memory exhausted
}
return true;
}
#ifndef NDEBUG
if(depth > 0) {
assert(botf - topf == 1 || bloc.valid());
assert(botf - topf > 1 || !bloc.valid());
}
#endif
int off;
uint32_t tp[4], bp[4]; // dest BW ranges for "prime" index
if(step == 0) {
// Just starting
assert(prevEdit == NULL);
assert(!tloc.valid());
assert(!bloc.valid());
off = s.steps[0];
bool ltr = off > 0;
off = abs(off)-1;
// Check whether/how far we can jump using ftab or fchr
int ftabLen = ebwtFw_->eh().ftabChars();
if(ftabLen > 1 && ftabLen <= s.maxjump) {
if(!ltr) {
assert_geq(off+1, ftabLen-1);
off = off - ftabLen + 1;
}
ebwtFw_->ftabLoHi(*seq_, off, false, topf, botf);
#ifdef NDEBUG
if(botf - topf == 0) return true;
#endif
#ifdef NDEBUG
if(ebwtBw_ != NULL) {
topb = ebwtBw_->ftabHi(*seq_, off);
botb = topb + (botf-topf);
}
#else
if(ebwtBw_ != NULL) {
ebwtBw_->ftabLoHi(*seq_, off, false, topb, botb);
assert_eq(botf-topf, botb-topb);
}
if(botf - topf == 0) return true;
#endif
step += ftabLen;
} else if(s.maxjump > 0) {
// Use fchr
int c = (*seq_)[off];
assert_range(0, 3, c);
topf = topb = ebwtFw_->fchr()[c];
botf = botb = ebwtFw_->fchr()[c+1];
if(botf - topf == 0) return true;
step++;
} else {
assert_eq(0, s.maxjump);
topf = topb = 0;
botf = botb = ebwtFw_->fchr()[4];
}
if(step == (int)s.steps.size()) {
// Finished aligning seed
assert(c0.acceptable());
assert(c1.acceptable());
assert(c2.acceptable());
if(!reportHit(topf, botf, topb, botb, seq_->length(), prevEdit)) {
return false; // Memory exhausted
}
return true;
}
nextLocsBi(tloc, bloc, topf, botf, topb, botb, step);
assert(tloc.valid());
} else assert(prevEdit != NULL);
assert(tloc.valid());
assert(botf - topf == 1 || bloc.valid());
assert(botf - topf > 1 || !bloc.valid());
assert_geq(step, 0);
uint32_t t[4], b[4]; // dest BW ranges
Constraint* zones[3] = { &c0, &c1, &c2 };
ASSERT_ONLY(uint32_t lasttot = botf - topf);
for(int i = step; i < (int)s.steps.size(); i++) {
assert_gt(botf, topf);
assert(botf - topf == 1 || bloc.valid());
assert(botf - topf > 1 || !bloc.valid());
assert(ebwtBw_ == NULL || botf-topf == botb-topb);
assert(tloc.valid());
off = s.steps[i];
bool ltr = off > 0;
const Ebwt* ebwt = ltr ? ebwtBw_ : ebwtFw_;
assert(ebwt != NULL);
if(ltr) {
tp[0] = tp[1] = tp[2] = tp[3] = topf;
bp[0] = bp[1] = bp[2] = bp[3] = botf;
} else {
tp[0] = tp[1] = tp[2] = tp[3] = topb;
bp[0] = bp[1] = bp[2] = bp[3] = botb;
}
t[0] = t[1] = t[2] = t[3] = b[0] = b[1] = b[2] = b[3] = 0;
if(bloc.valid()) {
// Range delimited by tloc/bloc has size >1. If size == 1,
// we use a simpler query (see if(!bloc.valid()) blocks below)
bwops_++;
ebwt->mapBiLFEx(tloc, bloc, t, b, tp, bp);
ASSERT_ONLY(uint32_t tot = (b[0]-t[0])+(b[1]-t[1])+(b[2]-t[2])+(b[3]-t[3]));
ASSERT_ONLY(uint32_t totp = (bp[0]-tp[0])+(bp[1]-tp[1])+(bp[2]-tp[2])+(bp[3]-tp[3]));
assert_eq(tot, totp);
assert_leq(tot, lasttot);
ASSERT_ONLY(lasttot = tot);
}
uint32_t *tf = ltr ? tp : t, *tb = ltr ? t : tp;
uint32_t *bf = ltr ? bp : b, *bb = ltr ? b : bp;
off = abs(off)-1;
//
bool leaveZone = s.zones[i].first < 0;
//bool leaveZoneIns = zones_[i].second < 0;
Constraint& cons = *zones[abs(s.zones[i].first)];
Constraint& insCons = *zones[abs(s.zones[i].second)];
int c = (*seq_)[off]; assert_range(0, 4, c);
int q = (*qual_)[off];
// Is it legal for us to advance on characters other than 'c'?
if(!(cons.mustMatch() && !overall.mustMatch()) || c == 4) {
// There may be legal edits
bool bail = false;
if(!bloc.valid()) {
// Range delimited by tloc/bloc has size 1
uint32_t ntop = ltr ? topb : topf;
bwops_++;
int cc = ebwt->mapLF1(ntop, tloc);
assert_range(-1, 3, cc);
if(cc < 0) bail = true;
else { t[cc] = ntop; b[cc] = ntop+1; }
}
if(!bail) {
if((cons.canMismatch(q, *sc_) && overall.canMismatch(q, *sc_)) || c == 4) {
Constraint oldCons = cons, oldOvCons = overall;
SideLocus oldTloc = tloc, oldBloc = bloc;
if(c != 4) {
cons.chargeMismatch(q, *sc_);
overall.chargeMismatch(q, *sc_);
}
// Can leave the zone as-is
if(!leaveZone || (cons.acceptable() && overall.acceptable())) {
for(int j = 0; j < 4; j++) {
if(j == c || b[j] == t[j]) continue;
// Potential mismatch
nextLocsBi(tloc, bloc, tf[j], bf[j], tb[j], bb[j], i+1);
int loff = off;
if(!ltr) loff = (int)(s.steps.size() - loff - 1);
assert(prevEdit == NULL || prevEdit->next == NULL);
Edit edit(off, j, c, EDIT_TYPE_MM, false);
DoublyLinkedList<Edit> editl;
editl.payload = edit;
if(prevEdit != NULL) {
prevEdit->next = &editl;
editl.prev = prevEdit;
}
assert(editl.next == NULL);
bwedits_++;
if(!searchSeedBi(
i+1, // depth into steps_[] array
depth+1, // recursion depth
tf[j], // top in BWT
bf[j], // bot in BWT
tb[j], // top in BWT'
bb[j], // bot in BWT'
tloc, // locus for top (perhaps unititialized)
bloc, // locus for bot (perhaps unititialized)
c0, // constraints to enforce in seed zone 0
c1, // constraints to enforce in seed zone 1
c2, // constraints to enforce in seed zone 2
overall, // overall constraints to enforce
&editl)) // latest edit
{
return false;
}
if(prevEdit != NULL) prevEdit->next = NULL;
}
} else {
// Not enough edits to make this path
// non-redundant with other seeds
}
cons = oldCons;
overall = oldOvCons;
tloc = oldTloc;
bloc = oldBloc;
}
if(cons.canGap() && overall.canGap()) {
throw 1; // TODO
int delEx = 0;
if(cons.canDelete(delEx, *sc_) && overall.canDelete(delEx, *sc_)) {
// Try delete
}
int insEx = 0;
if(insCons.canInsert(insEx, *sc_) && overall.canInsert(insEx, *sc_)) {
// Try insert
}
}
} // if(!bail)
}
if(c == 4) {
return true; // couldn't handle the N
}
if(leaveZone && (!cons.acceptable() || !overall.acceptable())) {
// Not enough edits to make this path non-redundant with
// other seeds
return true;
}
if(!bloc.valid()) {
assert(ebwtBw_ == NULL || bp[c] == tp[c]+1);
// Range delimited by tloc/bloc has size 1
uint32_t top = ltr ? topb : topf;
bwops_++;
t[c] = ebwt->mapLF1(top, tloc, c);
if(t[c] == 0xffffffff) {
return true;
}
assert_geq(t[c], ebwt->fchr()[c]);
assert_lt(t[c], ebwt->fchr()[c+1]);
b[c] = t[c]+1;
assert_gt(b[c], 0);
}
assert(ebwtBw_ == NULL || bf[c]-tf[c] == bb[c]-tb[c]);
assert_leq(bf[c]-tf[c], lasttot);
ASSERT_ONLY(lasttot = bf[c]-tf[c]);
if(b[c] == t[c]) {
return true;
}
topf = tf[c]; botf = bf[c];
topb = tb[c]; botb = bb[c];
if(i+1 == (int)s.steps.size()) {
// Finished aligning seed
assert(c0.acceptable());
assert(c1.acceptable());
assert(c2.acceptable());
if(!reportHit(topf, botf, topb, botb, seq_->length(), prevEdit)) {
return false; // Memory exhausted
}
return true;
}
nextLocsBi(tloc, bloc, tf[c], bf[c], tb[c], bb[c], i+1);
}
return true;
}
#ifdef ALIGNER_SEED_MAIN
#include <getopt.h>
#include <string>
/**
* Parse an int out of optarg and enforce that it be at least 'lower';
* if it is less than 'lower', than output the given error message and
* exit with an error and a usage message.
*/
static int parseInt(const char *errmsg, const char *arg) {
long l;
char *endPtr = NULL;
l = strtol(arg, &endPtr, 10);
if (endPtr != NULL) {
return (int32_t)l;
}
cerr << errmsg << endl;
throw 1;
return -1;
}
enum {
ARG_NOFW = 256,
ARG_NORC,
ARG_MM,
ARG_SHMEM,
ARG_TESTS,
ARG_RANDOM_TESTS,
ARG_SEED
};
static const char *short_opts = "vCt";
static struct option long_opts[] = {
{(char*)"verbose", no_argument, 0, 'v'},
{(char*)"color", no_argument, 0, 'C'},
{(char*)"timing", no_argument, 0, 't'},
{(char*)"nofw", no_argument, 0, ARG_NOFW},
{(char*)"norc", no_argument, 0, ARG_NORC},
{(char*)"mm", no_argument, 0, ARG_MM},
{(char*)"shmem", no_argument, 0, ARG_SHMEM},
{(char*)"tests", no_argument, 0, ARG_TESTS},
{(char*)"random", required_argument, 0, ARG_RANDOM_TESTS},
{(char*)"seed", required_argument, 0, ARG_SEED},
};
static void printUsage(ostream& os) {
os << "Usage: ac [options]* <index> <patterns>" << endl;
os << "Options:" << endl;
os << " --mm memory-mapped mode" << endl;
os << " --shmem shared memory mode" << endl;
os << " --nofw don't align forward-oriented read" << endl;
os << " --norc don't align reverse-complemented read" << endl;
os << " -t/--timing show timing information" << endl;
os << " -C/--color colorspace mode" << endl;
os << " -v/--verbose talkative mode" << endl;
}
bool gNorc = false;
bool gNofw = false;
bool gColor = false;
int gVerbose = 0;
int gGapBarrier = 1;
bool gColorExEnds = true;
int gSnpPhred = 30;
bool gReportOverhangs = true;
extern void aligner_seed_tests();
extern void aligner_random_seed_tests(
int num_tests,
uint32_t qslo,
uint32_t qshi,
bool color,
uint32_t seed);
/**
* A way of feeding simply tests to the seed alignment infrastructure.
*/
int main(int argc, char **argv) {
bool useMm = false;
bool useShmem = false;
bool mmSweep = false;
bool noRefNames = false;
bool sanity = false;
bool timing = false;
int option_index = 0;
int seed = 777;
int next_option;
do {
next_option = getopt_long(
argc, argv, short_opts, long_opts, &option_index);
switch (next_option) {
case 'v': gVerbose = true; break;
case 'C': gColor = true; break;
case 't': timing = true; break;
case ARG_NOFW: gNofw = true; break;
case ARG_NORC: gNorc = true; break;
case ARG_MM: useMm = true; break;
case ARG_SHMEM: useShmem = true; break;
case ARG_SEED: seed = parseInt("", optarg); break;
case ARG_TESTS: {
aligner_seed_tests();
aligner_random_seed_tests(
100, // num references
100, // queries per reference lo
400, // queries per reference hi
false, // true -> generate colorspace reference/reads
18); // pseudo-random seed
return 0;
}
case ARG_RANDOM_TESTS: {
seed = parseInt("", optarg);
aligner_random_seed_tests(
100, // num references
100, // queries per reference lo
400, // queries per reference hi
false, // true -> generate colorspace reference/reads
seed); // pseudo-random seed
return 0;
}
case -1: break;
default: {
cerr << "Unknown option: " << (char)next_option << endl;
printUsage(cerr);
exit(1);
}
}
} while(next_option != -1);
char *reffn;
if(optind >= argc) {
cerr << "No reference; quitting..." << endl;
return 1;
}
reffn = argv[optind++];
if(optind >= argc) {
cerr << "No reads; quitting..." << endl;
return 1;
}
string ebwtBase(reffn);
BitPairReference ref(
ebwtBase, // base path
gColor, // whether we expect it to be colorspace
sanity, // whether to sanity-check reference as it's loaded
NULL, // fasta files to sanity check reference against
NULL, // another way of specifying original sequences
false, // true -> infiles (2 args ago) contains raw seqs
useMm, // use memory mapping to load index?
useShmem, // use shared memory (not memory mapping)
mmSweep, // touch all the pages after memory-mapping the index
gVerbose, // verbose
gVerbose); // verbose but just for startup messages
Timer *t = new Timer(cerr, "Time loading fw index: ", timing);
Ebwt ebwtFw(
ebwtBase,
gColor, // index is colorspace
0, // don't need entireReverse for fw index
true, // index is for the forward direction
-1, // offrate (irrelevant)
useMm, // whether to use memory-mapped files
useShmem, // whether to use shared memory
mmSweep, // sweep memory-mapped files
!noRefNames, // load names?
false, // load SA sample?
true, // load ftab?
true, // load rstarts?
NULL, // reference map, or NULL if none is needed
gVerbose, // whether to be talkative
gVerbose, // talkative during initialization
false, // handle memory exceptions, don't pass them up
sanity);
delete t;
t = new Timer(cerr, "Time loading bw index: ", timing);
Ebwt ebwtBw(
ebwtBase + ".rev",
gColor, // index is colorspace
1, // need entireReverse
false, // index is for the backward direction
-1, // offrate (irrelevant)
useMm, // whether to use memory-mapped files
useShmem, // whether to use shared memory
mmSweep, // sweep memory-mapped files
!noRefNames, // load names?
false, // load SA sample?
true, // load ftab?
false, // load rstarts?
NULL, // reference map, or NULL if none is needed
gVerbose, // whether to be talkative
gVerbose, // talkative during initialization
false, // handle memory exceptions, don't pass them up
sanity);
delete t;
for(int i = optind; i < argc; i++) {
}
}
#endif
|