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
|
#include "ReadsMapping.h"
#include "MappingResult.h"
const int MISQUERYCHECKPOINT = 100000;
int parallelMappingLongReads(vector<string>& readSetsList,\
CGenome_Index_TableQ& indexTable, MappingOpts P)
{
P.clearOutputFileName(readSetsList.size() > 1);
indexTable.bExcludeAmbiguous = P.bExcludeAmbiguousReads;
//__OPENMP_FOR_PARALLEL__(#pragma)
int i;
#ifdef _OPENMP
int numberOfCPUs = omp_get_num_procs();
LOG_INFO("\nInfo %d: %d CPUs detected. %s.\n",\
INFO_LOG, numberOfCPUs, BLANK_LINE);
#pragma omp parallel for
#endif
for (i = 0; i < (int)readSetsList.size(); i++) {
CReadsMapping mapping(P);
const char* readSetName = (readSetsList.at(i)).c_str();
if (checkFileExist(readSetName)) {
CLongReadsSet longReadSet(readSetName, P.readsFileFormat, P.readLength,\
P.allowedNumOfNinRead, P.truncatedReadPrefix);
if (P.bIgnoreQS) {
longReadSet.ignoreQScores();
}
TIME_INFO(mapping.mapLongReads(longReadSet, indexTable), "Mapping takes");
}
}
return(0);
}
// Given a read set list and the index table, this function maps reads in parallel
int parallelMapping(vector<string>& readSetsList, \
CGenome_Index_TableQ& indexTable, MappingOpts P)
{
P.clearOutputFileName(readSetsList.size() > 1);
//__OPENMP_FOR_PARALLEL__(#pragma)
int i;
#ifdef _OPENMP
int numberOfCPUs = omp_get_num_procs();
LOG_INFO("\nInfo %d: %d CPUs detected. %s.\n",\
INFO_LOG, numberOfCPUs, BLANK_LINE);
#pragma omp parallel for
#endif
for (i = 0; i < (int)readSetsList.size(); i++) {
CReadInBitsSet readSet
(readSetsList.at(i).c_str(), \
P.readsFileFormat, P.truncatedReadPrefix,\
indexTable.uiRead_Length, P.allowedNumOfNinRead);
if (P.bIgnoreQS) {
readSet.ignoreQScores();
}
CReadsMapping mapping(P);
TIME_INFO(mapping.mapReads(readSet, indexTable), "Mapping completed");
}
return(0);
}
CReadsMapping::CReadsMapping(void)
{
this->initialization();
}
CReadsMapping::CReadsMapping(MappingOpts P)
{
this->initialization();
this->opt= P;
this->iMultiMappedLocationThreshold = P.maxAlignPerRead;
alignmentsQ[0].iMaxCapacity = P.maxAlignPerRead + 1; // store one more record
alignmentsQ[1].iMaxCapacity = P.maxAlignPerRead + 1; // So the load can be used to judge if overflow
if (P.bGetAllAlignments) {
// WARNING if index indexTable.bExcludeAmbiguous will have some error
alignmentsQ[0].setQueue_All_Best_OneFlag('A');
alignmentsQ[1].setQueue_All_Best_OneFlag('A');
}
if (P.outputFormat[0] != '\0') {
if (strcmp(P.outputFormat, "SAM") == 0 ||
strcmp(P.outputFormat, "sam") == 0 ) {
this->cOutputFormat = 's';
} else if (strcmp(P.outputFormat, "MAPPING") == 0 ||
strcmp(P.outputFormat, "mapping") == 0 ) {
this->cOutputFormat = 'm';
} else if (strcmp(P.outputFormat, "FASTQ") == 0 ||
strcmp(P.outputFormat, "fastq") == 0 ) {
this->cOutputFormat = 'F';
this->opt.bPrintFirstAlignmentOnly = true;
} else {
LOG_INFO("Info %d: Specified output format %s is not recognizable.\n", WARNING_LOG, P.outputFormat);
}
}
// check if the director exist, if not, create one
if (P.outputDir[0] != '\0') {
if (dirExist(P.outputDir) || createdir(P.outputDir) == 0) {
#ifdef WIN32
sprintf(this->opt.outputDir, "%s\\", P.outputDir);
#else
sprintf(this->opt.outputDir, "%s/", P.outputDir);
#endif
} else {
LOG_INFO("Info %d: Can't create dir %s.\n", WARNING_LOG, P.outputDir);
this->opt.outputDir[0] = '\0';
}
}
}
CReadsMapping::~CReadsMapping(void)
{
delete AlignResult;
delete MissReads;
}
void CReadsMapping::initialization(void)
{
this->AlignResult = NULL;
this->AmbiguousReads = NULL;
this->MissReads = NULL;
this->BadReads = NULL;
this->cOutputFormat = 'm';
}
int CReadsMapping::mapReadsSets(const char* ReadsSetsList, CGenome_Index_TableQ& table, bool bDiscardReadsWN)
{
// Counter for coverage is not initialize
this->initializeStatsCounter();
char readsFile[FILENAME_MAX];
ifstream readsFileList(ReadsSetsList);
while (GetNextFilenameFromListFile(readsFileList, readsFile)) {
CReadInBitsSet readSet(readsFile, this->opt.readsFileFormat,\
this->opt.truncatedReadPrefix,\
table.uiRead_Length, bDiscardReadsWN);
this->mapReads(readSet, table);
}
return(0);
}
int CReadsMapping::mapReads(CReadInBitsSet& readSet, const CGenome_Index_TableQ& table)
{
if (wrongIndex(readSet, table)) return(0);
unsigned qsShift = table.bMapReadInColors ? Phred_SCALE_QUAL_SHIFT : SolexaScoreEncodingShift;
getReadsFileFormat(readSet.InputFile, opt.readsFileFormat);
string seedStr = seedSymbol(table.chosenSeedId);
unsigned int uiReadLength = readSet.uiRead_Length;
printf("Mapping %s (%u-bp reads) with %s seed.%s\n", \
readSet.InputFile, uiReadLength, seedStr.c_str(), BLANK_LINE);
// if there are multiple gene in first chromosome.
// bool bPrintGeneName = (table.pgenomeNT->paChromosomes[0]->geneVec.table.size() >= 0);
this->initializeStatsCounter();
if (this->setUpIO4Aligment(readSet.InputFile, table) != 0) {
LOG_INFO("\nInfo %d: Fail to setup I/O files.", ERROR_LOG);
return(1);
}
readSet.setBadReadOutputFile(this->BadReads);
CAlignmentsQ& aQue = this->alignmentsQ[0];
while (readSet.get_next_capacity_reads(BUFFERED_READS_SIZE, opt.readtag_delimiter) != 0) {
vector<CReadInBits>::iterator it = readSet.pReadsSet->begin();
for (int i = 0; it != readSet.pReadsSet->end(); i++, it++) {
this->printCheckPointInfo(i);
readSet.get_read_id(i, aQue.tag);
aQue.read = *it;
aQue.qualityScores = readSet.getQScoresPtr(i);
bool map2forwardStrand = !opt.bMap2ReverseStrandOnly;
bool map2reverseStrand = !opt.bMap2ForwardStrandOnly;
if (table.bMapReadInColors) {
if(map2forwardStrand) {
bool clearQ;
table.queryReadColors(*it, aQue, clearQ = true, true);
}
if(map2reverseStrand) {
bool clearQ = this->opt.bMap2ReverseStrandOnly ? true : false;
table.queryReadColors(*it, aQue, clearQ, false);
}
} else {
bool clearQ;
if(map2forwardStrand) {
table.queryReadBases(*it, aQue, clearQ = true, true);
}
if(map2reverseStrand) {
clearQ = opt.bMap2ReverseStrandOnly ? true : false;
table.queryReadBases(*it, aQue, clearQ, false);
}
}
// statistics and output
if (aQue.load > 0) {
bookKeepMapping(aQue);
bool bPrintAlignment = this->printAlignmentOrNot(aQue, this->opt.bExcludeAmbiguousReads, this->opt.bPrintAmbiguousReadsOnly);
if (bPrintAlignment) {
this->dealMappedRead(table, aQue);
}
} else if (this->opt.bPrintUnMappedReads) {
char qs[MAX_READ_LENGTH];
qs[0] = '\0';
if (readSet.pQualScores != NULL) {
const char* qsPtr = readSet.pQualScores->qScores((unsigned int)i);
trQScores(table.uiRead_Length, qsShift, qsPtr, qs);
}
dealMissedRead(table.bMapReadInColors, aQue.tag, aQue.read, qs);
}
}
iReadCounter += (unsigned int)readSet.pReadsSet->size();
}
this->tearDownIO4Aligment();
this->iBadReadCounter = readSet.uiNo_of_Bad_Reads;
this->printMappingStats(cout, readSet.InputFile, opt.subDiffThreshold);
return(0);
}
// Map a single long read in two CReadInBits format
int CReadsMapping::queryALongReadInBase(CReadInBits& r1stHalf, CReadInBits& r2ndHalf, const CGenome_Index_TableQ& table, CAlignmentsQ& aQue) const
{
// TODO: The reads should be query and "Check" immediately before que.
// In this way, "short cut and filter can be applied right away. Should be changed
/*
table.queryReadBases(r1stHalf, aQue, true, true);
table.queryReadBases(r1stHalf, aQue, false, false);
table.extendAlignment(aQue, r2ndHalf);
aQue.filterAlignments(this->opt.subDiffThreshold, this->opt.bGetAllAlignments);
*/
const bool bOddReadLength = this->opt.bOddReadLengthAndLongRead;
const bool bAmbiguousOnly = this->opt.bPrintAmbiguousReadsOnly;
const bool bShortCutAE = this->opt.bExcludeAmbiguousReads && aQue.qAllInThreshold() && !bAmbiguousOnly;
const bool bShortCutE = this->opt.bExcludeAmbiguousReads && !bAmbiguousOnly;
const bool bShortCutB = !this->opt.bExcludeAmbiguousReads && !aQue.qAllInThreshold() && !bAmbiguousOnly;
const bool bMap2ForwardStrand = ! this->opt.bMap2ReverseStrandOnly;
const bool bMap2ReverseStrand = ! this->opt.bMap2ForwardStrandOnly;
if(bMap2ForwardStrand) {
bool clearQ;
table.queryLongReadBases(r1stHalf, r2ndHalf, bOddReadLength, aQue, 1, clearQ = true, true);
if (aQue.load > 1) {
if (bShortCutAE || (bShortCutE && aQue.MinDiff == 0)) {
return (aQue.load);
}
}
if (!(bShortCutB && aQue.MinDiff == 0)) {
table.queryLongReadBases(r1stHalf, r2ndHalf, bOddReadLength, aQue, 2, clearQ = false, true);
if (aQue.load > 1) {
if (bShortCutAE || (bShortCutE && aQue.MinDiff == 0)) {
return (aQue.load);
}
}
}
}
if(bMap2ReverseStrand) {
bool clearQ = this->opt.bMap2ReverseStrandOnly ? true : false;
table.queryLongReadBases(r1stHalf, r2ndHalf, bOddReadLength, aQue, 1, clearQ, false);
if (aQue.load > 1) {
if (bShortCutAE || (bShortCutE && aQue.MinDiff == 0)) {
return (aQue.load);
}
}
if (!(bShortCutB && aQue.MinDiff == 0)) {
table.queryLongReadBases(r1stHalf, r2ndHalf, bOddReadLength, aQue, 2, clearQ = false, false);
}
}
return(aQue.load);
}
int CReadsMapping::queryALongReadInColors(CReadInBits& r1stHalf, CReadInBits& r2ndHalf, const CGenome_Index_TableQ& table, CAlignmentsQ& aQue) const
{
LOG_INFO("\nInfo %d: Currently PerM doesn't support mapping SOLiD reads longer than 64 base pairs.\n",\
ERROR_LOG);
const bool bOddReadLength = this->opt.bOddReadLengthAndLongRead;
const bool bAmbiguousOnly = this->opt.bPrintAmbiguousReadsOnly;
const bool bShortCutAE = this->opt.bExcludeAmbiguousReads && aQue.qAllInThreshold() && !bAmbiguousOnly;
const bool bShortCutE = this->opt.bExcludeAmbiguousReads && !bAmbiguousOnly;
const bool bShortCutB = !this->opt.bExcludeAmbiguousReads && !aQue.qAllInThreshold() && !bAmbiguousOnly;
const bool bMap2ForwardStrand = ! this->opt.bMap2ReverseStrandOnly;
const bool bMap2ReverseStrand = ! this->opt.bMap2ForwardStrandOnly;
if(bMap2ForwardStrand) {
bool clearQ;
table.queryLongReadColors(r1stHalf, r2ndHalf, bOddReadLength, aQue, 1, clearQ = true, true);
if (aQue.load > 1) {
if (bShortCutAE || (bShortCutE && aQue.MinDiff == 0)) {
return (aQue.load);
}
}
if ( !(bShortCutB && aQue.MinDiff == 0)) {
table.queryLongReadColors(r1stHalf, r2ndHalf, bOddReadLength, aQue, 2, clearQ = false, true);
if (aQue.load > 1) {
if (bShortCutAE || (bShortCutE && aQue.MinDiff == 0)) {
return (aQue.load);
}
}
}
}
if(bMap2ReverseStrand) {
bool clearQ = this->opt.bMap2ReverseStrandOnly ? true : false;
table.queryLongReadColors(r1stHalf, r2ndHalf, bOddReadLength, aQue, 1, clearQ, false);
if (aQue.load > 1) {
if (bShortCutAE || (bShortCutE && aQue.MinDiff == 0)) {
return (aQue.load);
}
}
if ( !(bShortCutB && aQue.MinDiff == 0)) {
table.queryLongReadColors(r1stHalf, r2ndHalf, bOddReadLength, aQue, 2, clearQ = false, false);
}
}
return(aQue.load);
}
int CReadsMapping::printLogFile(const char* inputFile)
{
ofstream logFile(opt.logFileN, ofstream::app);
if (logFile.good()) {
this->printCommand(logFile, opt.fullCommand);
this->printMappingStats(logFile, inputFile, opt.subDiffThreshold);
this->printCommand(cout, opt.fullCommand);
this->printMappingStats(cout, inputFile, opt.subDiffThreshold);
} else {
this->printCommand(cout, opt.fullCommand);
this->printMappingStats(cout, inputFile, opt.subDiffThreshold);
}
logFile.close();
return(0);
}
// To map reads longer than MAX_READ_LENGTH, locate alignments using first half and check the mismatches in the second half
int CReadsMapping::mapLongReads(CLongReadsSet& longReadSet, const CGenome_Index_TableQ& table)
{
unsigned int uiReadLength = this->opt.readLength;
CAlignmentsQ& aQue = this->alignmentsQ[0];
CReadInBitsSet& readSet1stHalf = *(longReadSet.F_Reads);
CReadInBitsSet& readSet2ndHalf = *(longReadSet.R_Reads);
const char* readSetName = readSet1stHalf.InputFile;
// Flag that set the alignment is ambiguous or not
getReadsFileFormat(readSetName, opt.readsFileFormat);
string seedStr = seedSymbol(table.chosenSeedId);
printf("Mapping %s (%u-bp reads) with %s seed.\n", \
readSetName, uiReadLength, seedStr.c_str());
this->initializeStatsCounter();
if (this->setUpIO4Aligment(readSetName, table) != 0) {
LOG_INFO("\nInfo %d: Fail to setup I/O files.", ERROR_LOG);
return(1);
}
longReadSet.setBadReadOutputFile(this->BadReads);
// alignmentsQ[0].setQueue_All_Best_OneFlag('A');
const bool bMapReadInColors = table.bMapReadInColors;
while (longReadSet.get_next_capacity_long_reads() > 0) {
int bufferedReadNo = this->checkPairedReadSetSize(readSet1stHalf, readSet2ndHalf);
vector<CReadInBits>::iterator it1, it2;
it1 = readSet1stHalf.pReadsSet->begin();
it2 = readSet2ndHalf.pReadsSet->begin();
for (int i = 0; i < bufferedReadNo; i++, it1++, it2++) {
this->printCheckPointInfo(i);
CMappingResult m;
if (bMapReadInColors) {
this->getLongColorReadInfo(readSet1stHalf, readSet2ndHalf, i, *it1, *it2, m);
this->queryALongReadInColors(*it1, *it2, table, aQue);
return(-1);
} else {
this->getLongBaseReadInfo(readSet1stHalf, readSet2ndHalf, i, *it1, *it2, m);
this->queryALongReadInBase(*it1, *it2, table, aQue);
}
// statistics and output
if (aQue.load > 0) {
bookKeepMapping(aQue);
bool bPrintAlignment = this->printAlignmentOrNot(aQue, this->opt.bExcludeAmbiguousReads, this->opt.bPrintAmbiguousReadsOnly);
if (bPrintAlignment) {
this->dealMappedLongRead(table, aQue, m);
}
} else if (this->opt.bPrintUnMappedReads) {
dealMissedRead(m);
}
}
this->iReadCounter += bufferedReadNo;
}
this->tearDownIO4Aligment();
this->iBadReadCounter = longReadSet.uiNo_of_Bad_Reads;
this->printLogFile(readSetName);
return(0);
}
int CReadsMapping::dealMissedRead(bool bMapReadInColors, const char* readName, CReadInBits r, const char* qs)
{
this->printRead(this->MissReads, bMapReadInColors, readName, r, qs);
return(this->iMissReadCounter++);
}
int CReadsMapping::dealAmbiguousRead(bool bMapReadInColors, const char* readName, CReadInBits r, const char* qs)
{
this->printRead(this->AmbiguousReads, bMapReadInColors, readName, r, qs);
return(this->iReadsMapped2tooManyLocations);
}
inline void CReadsMapping::printRead(FileOutputBuffer* FileBuf, bool bMapReadInColors, const char* readName, CReadInBits r, const char* qs)
{
char caRead[MAX_READ_LENGTH + 1];
if (bMapReadInColors) {
decodeColorReadWithPrimer(caRead, r);
} else {
r.decode(caRead);
}
if (qs == NULL || qs[0] == '\0') {
sprintf(FileBuf->caBufp, ">%s\n%s\n", readName, caRead);
} else {
sprintf(FileBuf->caBufp, "@%s\n%s\n+\n%s\n", readName, caRead, qs);
}
FileBuf->UpdateSize();
}
inline void CReadsMapping::printRead(FileOutputBuffer* FileBuf, CMappingResult& m)
{
const char* readSeqOrColors;
if (m.caRead[0] != '\0') {
readSeqOrColors = m.caRead;
} else {
readSeqOrColors = m.TAG;
}
if (m.QScores[0] == '\0') {
sprintf(FileBuf->caBufp, ">%s\n%s\n", m.QNAME, readSeqOrColors);
FileBuf->UpdateSize();
} else {
sprintf(FileBuf->caBufp, "@%s\n%s\n+\n%s\n", m.QNAME, readSeqOrColors, m.QScores);
FileBuf->UpdateSize();
}
}
int CReadsMapping::dealMissedRead(CMappingResult& m)
{
printRead(this->MissReads, m);
return(this->iMissReadCounter++);
}
int CReadsMapping::dealAmbiguousRead(CMappingResult& m)
{
printRead(this->AmbiguousReads, m);
return(this->iReadsMapped2tooManyLocations);
}
unsigned int CReadsMapping::checkPairedReadSetSize\
(CReadInBitsSet& firstHalfSet, CReadInBitsSet& SecondHalfSet)
{
unsigned int size1 = (unsigned int)firstHalfSet.pReadsSet->size();
unsigned int size2 = (unsigned int)SecondHalfSet.pReadsSet->size();
if (size1 == size2) {
return(size1);
} else {
LOG_INFO("Info %d: Not every read has the second half\n", WARNING_LOG);
return(min(size1, size2));
}
}
void printSingleEndReads(char format, unsigned int uiReadLength);
// This function print out alignments for each read and the corresponding information.
int CReadsMapping::dealMappedRead(const CGenome_Index_TableQ& table, CAlignmentsQ& aQue)
{
bool samFormat = (this->cOutputFormat == 's');
CMappingResult m(aQue, opt.readLength);
if (!table.bMapReadInColors) {
// TODO: get read
getReadQscores4Solexa(aQue, m, samFormat);
}
if (this->opt.bPrintAlignments) {
if (aQue.load < aQue.iMaxCapacity || this->opt.bPrintAmbiguousReadsOnly) {
for (unsigned int i = 0; i < aQue.load && i < aQue.iMaxCapacity; i++) {
getSingleMappingInfo(table, aQue, i, m, samFormat);
this->printSingleEndReads(m);
if (this->opt.bPrintFirstAlignmentOnly) {
break;
}
}
}
if (aQue.load >= aQue.iMaxCapacity) {
// If a read is mapped to over threshold place, don't print it
this->iReadsMapped2tooManyLocations++;
if (this->opt.bPrintAmbigReadsSeparately) {
this->dealAmbiguousRead(table.bMapReadInColors,aQue.tag, aQue.read, aQue.qualityScores);
/* The alternative ambiguous print will not include the adapter
const bool IF_COLOR2BASE = false;
const int FIRST_INDEX = 0;
getSingleMappingInfo(table, aQue, FIRST_INDEX, m, IF_COLOR2BASE);
this->dealAmbiguousRead(m);
*/
} else if (this->opt.bPrintAmbigReadsInOneLine) {
getSingleMappingInfo(table, aQue, 0, m, samFormat);
this->printSingleEndReads(m);
}
}
}
return(aQue.load);
}
int CReadsMapping::dealMappedLongRead\
(const CGenome_Index_TableQ& table, CAlignmentsQ& aQue, CMappingResult& m)
{
bool samFormat = (this->cOutputFormat == 's');
if (aQue.load < aQue.iMaxCapacity || this->opt.bPrintAmbiguousReadsOnly) {
if (this->opt.bPrintAlignments) {
for (unsigned int i = 0; i < aQue.load && i < aQue.iMaxCapacity; i++) {
// get and store all the output info in CMappingResult
getLongMappingInfo(table, aQue, samFormat, i, m); // TODO make change for SOLiD long read
this->printSingleEndReads(m);
if (this->opt.bPrintFirstAlignmentOnly) {
break;
}
}
}
}
if (aQue.load >= aQue.iMaxCapacity) {
// If a read is mapped to over threshold place, don't print it
this->iReadsMapped2tooManyLocations++;
if (this->opt.bPrintAmbigReadsSeparately) {
this->dealAmbiguousRead(m);
} else if (this->opt.bPrintAmbigReadsInOneLine) {
getLongMappingInfo(table, aQue, samFormat, 0, m);
this->printSingleEndReads(m);
}
}
return(aQue.load);
}
int CReadsMapping::printSingleEndReads(CMappingResult& m)
{
string dummyStr = "";
int map_score = 0;
switch (this->cOutputFormat) {
case 's':
printAMappingInSam(this->AlignResult, m);
break;
case 'F':
printAMappingInFastq(this->AlignResult, m);
break;
case 'g':
printAMappingInGff(this->AlignResult, m, map_score, dummyStr);
break;
default:
printAMappingInPerM(this->AlignResult, m, this->opt.bPrintNM);
break;
}
return(0);
}
/*
int CReadsMapping::printMappingsInBEDformat(FileOutputBuffer &OBuf, char* caKmer,
CMapOfSingleRead& mapPatternsSet, unsigned int ReadID)
{
const unsigned int SUB_LEVEL = 4;
const char* RGB[SUB_LEVEL];
RGB[0] = "0,0,0";
RGB[1] = "0,0,255";
RGB[2] = "0,255,0";
RGB[3] = "255,0,0";
unsigned int readLength = this->uiKmer_Length;
for(int i = 0; i < mapPatternsSet.size; i++)
{ // For each kind of pattern
set<CSingleMapping,Comp>* pSet = &(mapPatternsSet.mappingsSets[i]);
set<CSingleMapping,Comp>::iterator j;
// Print each occurrence of a same pattern
for(j = pSet->begin(); j != pSet->end(); j++) {
unsigned int chrom = j->chrId;
unsigned int chromStart = j->chrLocusId;
unsigned int chromEnd = chromStart + readLength;
int name = ReadID;
int score = 1;
if( score > 0) {
char strand = j->bReverse ? '-' : '+';
unsigned int subNum = diNtStrWildCardComp(mapPatternsSet.caPattern[i], caKmer, readLength);
const char* subRGB = (subNum > (SUB_LEVEL - 1)) ? RGB[subNum] : RGB[SUB_LEVEL - 1] ;
sprintf(OBuf.caBufp,"chr%u %u %u read%d %d %c %d %d %s %d %d 0\n",
chrom, chromStart, chromEnd, name, score, strand, chromStart, chromEnd,
subRGB, subNum, readLength);
OBuf.UpdateSize();
} else {
// bad read;
}
}
// delete each set if it has been report
mapPatternsSet.mappingsSets[i].clear();
}
return(mapPatternsSet.size);
} */
// This private function returns a string as the prefix of the output file name for mapping
string getOutputFileNamePrefix(const char* dir, const CGenome_Index_TableQ& table, MappingOpts& opt)
{
// The prefix contains 4 parts: (0) dir (1) ref file (2) ambiguous flag (3) mismatch threshold
char outputPrefixStr[MAX_PATH];
char excludeAmbiguous = opt.bExcludeAmbiguousReads ? 'E' : 'B';
if (opt.bGetAllAlignments) excludeAmbiguous = 'A';
sprintf(outputPrefixStr, "%s%s_%c_%u_%d",\
dir, table.caRefName, excludeAmbiguous, table.chosenSeedId, opt.subDiffThreshold);
return(string(outputPrefixStr));
}
bool isGalaxyOutputPath(const char* fileName)
{
return(hasTheExtName(fileName, ".dat"));
}
bool isSupportedExtName(const char* fileN)
{
if (hasTheExtName(fileN, ".fasta") ||
hasTheExtName(fileN, ".fastq") ||
hasTheExtName(fileN, ".fq") ||
hasTheExtName(fileN, ".csfq") ||
hasTheExtName(fileN, ".csfastq") ||
hasTheExtName(fileN, ".csfasta") ||
hasTheExtName(fileN, ".dat") ||
hasTheExtName(fileN, ".txt")) {
return(true);
}
return(false);
}
string rmSupportedExtName(const char* fileN)
{
char newFileN[FILENAME_MAX];
strcpy(newFileN, fileN);
if (isSupportedExtName(fileN)) {
for (int i = (int)strlen(newFileN); i > 0; i--) {
if (newFileN[i] == '.') {
newFileN[i] = '\0';
return(string(newFileN));
}
}
}
return(string(fileN));
}
// generate the unmapped FileN, if the original one is not null
void getAmbiguousFileN(char* ambiguousFileN, const char* readFileN, const char* readFormat,\
const char* refN, bool bQual = false)
{
string refNStr = rmSupportedExtName(refN);
string readFileNStr = rmSupportedExtName(readFileN);
if (strcmp(ambiguousFileN, "") == 0) { // make sure the readFormat is valid
if (strcmp(readFormat, "csfasta") == 0) {
if (bQual) {
sprintf(ambiguousFileN, "%s_ambig_%s.%s", readFileNStr.c_str(), refNStr.c_str(), "fastq");
} else {
sprintf(ambiguousFileN, "%s_ambig_%s", readFileNStr.c_str(), refNStr.c_str()); // Not sure csfasta or not
}
} else {
if (readFormat[0] == '\0') {
sprintf(ambiguousFileN, "%s_ambig_%s", readFileNStr.c_str(), refNStr.c_str());
} else {
sprintf(ambiguousFileN, "%s_ambig_%s.%s", readFileNStr.c_str(), refNStr.c_str(), readFormat);
}
}
}
}
// generate the unmapped FileN, if the original one is not null
void getUnmappedFileN(char* unmappedFileN, const char* readFileN, const char* readFormat,\
const char* refN, bool bQual = false)
{
string refNStr = rmSupportedExtName(refN);
string readFileNStr = rmSupportedExtName(readFileN);
if (strcmp(unmappedFileN, "") == 0) { // make sure the readFormat is valid
if (strcmp(readFormat, "csfasta") == 0) {
if (bQual) {
sprintf(unmappedFileN, "%s_miss_%s.%s", readFileNStr.c_str(), refNStr.c_str(), "fastq");
} else {
sprintf(unmappedFileN, "%s_miss_%s", readFileNStr.c_str(), refNStr.c_str()); // Not sure csfasta or not
}
} else {
if (readFormat[0] == '\0') {
sprintf(unmappedFileN, "%s_miss_%s", readFileNStr.c_str(), refNStr.c_str());
} else {
sprintf(unmappedFileN, "%s_miss_%s.%s", readFileNStr.c_str(), refNStr.c_str(), readFormat);
}
}
}
}
// generate the unmapped FileN, if the original one is not null
void getBadReadsFileN(char* badFileN, const char* readFileN, const char* readFormat,\
const char* refN, bool bQual = false)
{
string refNStr = rmSupportedExtName(refN);
string readFileNStr = rmSupportedExtName(readFileN);
if (strcmp(badFileN, "") == 0) { // make sure the readFormat is valid
if (strcmp(readFormat, "csfasta") == 0) {
if (bQual) {
sprintf(badFileN, "%s_bad.%s", readFileNStr.c_str(), "fastq");
} else {
sprintf(badFileN, "%s_bad", readFileNStr.c_str()); // Not sure csfasta or not
}
} else {
if (readFormat[0] == '\0') {
sprintf(badFileN, "%s_bad", readFileNStr.c_str());
} else {
sprintf(badFileN, "%s_bad.%s", readFileNStr.c_str(), readFormat);
}
}
}
}
string CReadsMapping::getMappingFileN(const char* caReadsSetName, const CGenome_Index_TableQ& table)
{
if (this->cOutputFormat == 'm') {
strcpy(opt.outputFormat, "mapping");
} else if (this->cOutputFormat == 's') {
strcpy(opt.outputFormat, "sam");
} else if (this->cOutputFormat == 'F') {
strcpy(opt.outputFormat, "fastq");
}
char outputPath[MAX_LINE];
if (this->opt.outputFileN[0] == '\0') { // No output file has been set
string outFileNPrefix = getOutputFileNamePrefix(this->opt.outputDir, table, opt);
string fileNameOfReadSet = getBasename(caReadsSetName);
const char* extN = opt.outputFormat;
if (string(extN) == "sam" || string(extN) == "mapping" || string(extN) == "fastq") {
sprintf(outputPath, "%s_%s.%s", outFileNPrefix.c_str(), fileNameOfReadSet.c_str(), extN);
} else {
if (extN[0] != '0') {
char msg[MAX_LINE];
sprintf(msg, "The specified output format %s is unrecognizable.\n", extN);
cout << msg;
// LOG_INFO("%s", WARNING_LOG, msg);
}
sprintf(outputPath, "%s_%s", outFileNPrefix.c_str(), fileNameOfReadSet.c_str());
}
} else {
sprintf(outputPath, "%s%s", this->opt.outputDir, this->opt.outputFileN);
}
return(string(outputPath));
}
int CReadsMapping::setUpIO4Aligment(const char* caReadsSetName, const CGenome_Index_TableQ& table)
{
if (this->opt.bGetAllAlignments) {
// Find all alignments with in threshold, instead of queuing
// only all best(with the fewest mismatches) alignments as default.
alignmentsQ[0].setQueue_All_Best_OneFlag('A');
alignmentsQ[1].setQueue_All_Best_OneFlag('A');
}
char outputPath[MAX_PATH];
strcpy(outputPath, this->getMappingFileN(caReadsSetName, table).c_str());
// (1)Initialize the I/O for output the alignments
if (this->opt.bPrintAlignments) {
if (this->AlignResult == NULL) {
ofstream* AlignResultFile = new ofstream(outputPath);
this->AlignResult =
new FileOutputBuffer(ALIGNMENT_RESULT_FILE_BUFFER_SIZE, AlignResultFile);
if (this->AlignResult == NULL) {
ERR;//check new FileOutputBuffer
return(1);
} else if (this->cOutputFormat == 's') {
if (this->opt.bPrintSamHeader) {
string RG = getSamRG(caReadsSetName, table.bMapReadInColors);
vector<CGene> refs = table.pgenomeNT->getRefNamesLengths();
string commandLineStr = this->opt.fullCommand;
printSamHeader(AlignResult, refs, RG.c_str(), commandLineStr.c_str());
}
}
}
}
// (2)Initialize the I/O for output the up-mapped reads.
if (this->opt.bPrintUnMappedReads) {
// Make sure opt.readsFileFormat has been set
const char* refN = table.pgenomeNT->refName;
getUnmappedFileN(opt.unmappedFileN, caReadsSetName, opt.readsFileFormat, refN);
/* // This line force the output to be the right ext name (fasta, csfasta or fastq)
if (!isGalaxyOutputPath(opt.unmappedFileN)) {
string extName = string(".").append(string(opt.readsFileFormat));
chExtName(opt.unmappedFileN, extName.c_str());
}*/
if (this->MissReads == NULL) {
ofstream* MissReadsFile = new ofstream(opt.unmappedFileN);
this->MissReads =
new FileOutputBuffer(ALIGNMENT_RESULT_FILE_BUFFER_SIZE, MissReadsFile);
if (this->MissReads == NULL) {
ERR; // check new FileOutputBuffer
return(1);
}
}
}
// (3) Initialize the I/O for output the ambiguous reads over the threshold
if (this->opt.bPrintAmbigReadsSeparately) {
// Make sure opt.readsFileFormat has been set
const char* refN = table.pgenomeNT->refName;
getAmbiguousFileN(opt.ambiguousReadFileN, caReadsSetName, opt.readsFileFormat, refN);
if (this->AmbiguousReads == NULL) {
ofstream* ambiguousReadsFile = new ofstream(opt.ambiguousReadFileN);
this->AmbiguousReads =
new FileOutputBuffer(ALIGNMENT_RESULT_FILE_BUFFER_SIZE, ambiguousReadsFile);
if (this->AmbiguousReads == NULL) {
ERR; // check new FileOutputBuffer
return(1);
}
}
}
// (4) Initialize the I/O for output the bad reads or reads shorter than expected
if (this->opt.bPrintBadReads) {
// Make sure opt.readsFileFormat has been set
const char* refN = table.pgenomeNT->refName;
getBadReadsFileN(opt.badReadFileN, caReadsSetName, opt.readsFileFormat, refN);
if (this->BadReads == NULL) {
ofstream* badReadsFile = new ofstream(opt.badReadFileN);
this->BadReads =
new FileOutputBuffer(ALIGNMENT_RESULT_FILE_BUFFER_SIZE, badReadsFile);
if (this->BadReads == NULL) {
ERR; // check new FileOutputBuffer
return(1);
}
}
}
return(0);
}
int CReadsMapping::tearDownIO4Aligment(void)
{
// close file, which has been opened before
if (this->opt.bPrintAlignments) {
// this->AlignResult->removeEndBlankLine();
delete this->AlignResult;
this->AlignResult = NULL;
}
if (this->opt.bPrintUnMappedReads) {
// this->MissReads->removeEndBlankLine();
delete this->MissReads;
this->MissReads = NULL;
}
if (this->opt.bPrintAmbigReadsSeparately) {
delete this->AmbiguousReads;
this->AmbiguousReads = NULL;
}
if (this->opt.bPrintBadReads) {
delete this->BadReads;
this->BadReads = NULL;
}
return(0);
}
void getSingleMappingSeq4Solexa(const CGenome_Index_TableQ& table, CMappingResult& m, bool noRef)
{
if (noRef) { // sam format doesn't need to know reference sequence
m.caRef[0] = '\0';
} else {
const unsigned int readLength = (unsigned int)strlen(m.caRead);
// (1) Get ref in bits
CReadInBits ref = table.pgenomeNTInBits->getSubstringInBits(m.uiGlobalMappedPos, readLength);
if (m.strand == '-') {
ref = reverseCompliment(readLength, ref);
}
// (2) Get ref seq
ref.decode(m.caRef);
}
}
void getQscores4Solexa(CAlignmentsQ& aQue, CMappingResult& m, bool samFormat)
{
if (aQue.qualityScores == NULL) {
m.mismatchScore = (int)m.uiDiff;
m.QScores[0] = '\0';
} else { // If quality score are available, get quality score
m.mismatchScore = alignmentScore(m.caRead, m.caRef, m.uiReadLength, aQue.qualityScores);
trQScores(m.uiReadLength, SolexaScoreEncodingShift, aQue.qualityScores, m.QScores);
if (samFormat) {
m.getReverseReadandQual();
}
}
}
void getReadQscores4Solexa(CAlignmentsQ& aQue, CMappingResult& m, bool samFormat)
{
aQue.read.decode(m.caRead);
getQscores4Solexa(aQue, m, samFormat);
}
inline CReadInBits getSingleMappingRef4SOLiD(const CGenome_Index_TableQ& table, CAlignmentsQ& aQue, CMappingResult& m, bool samFormat)
{
const unsigned int readlength = table.uiRead_Length;
// (1) Get ref in bits
CReadInBits ref = table.pgenomeNTInBits->getSubstringInBits(m.uiGlobalMappedPos, readlength);
if (m.strand == '-') {
ref = reverseCompliment(readlength, ref);
}
// (2) Get ref in color
CReadInBits colorsInRef = bases2Colors(ref);
m.SNPtype = returnSNPtype(aQue.read, colorsInRef);
// (3) Get ref in sequence
if(!samFormat) {
decodeColors(m.caRef, colorsInRef); // Show the reference for validation purpose
}
return(colorsInRef);
}
inline void getQualityScore4SOLiD(unsigned int readlength, CReadInBits &colorsInRef, CAlignmentsQ& aQue, CMappingResult& m, bool samFormat)
{
if (samFormat) { // correctRead
if (aQue.qualityScores == NULL) {
char dummyScore = (char)(20);
fillDummyQScores(readlength, dummyScore + Phred_SCALE_QUAL_SHIFT, m.QScores);
} else {
trQScores(readlength, Phred_SCALE_QUAL_SHIFT, aQue.qualityScores, m.QScores);
}
sprintf(m.TAG, "%s\tCS:Z:%s\tCQ:Z:%s", m.TAG, m.caRead, m.QScores);
//sprintf(m.TAG, "%s\tX1:Z:%s\tCS:Z:%s\tCQ:Z:%s", m.TAG, m.caRef, m.caRead, m.QScores);
correctAndDecodeRead(aQue.read, colorsInRef, samFormat, m.caRead, m.QScores);
if (m.strand == '-')
m.getReverseReadandQual();
} else {
if (aQue.qualityScores == NULL) {
m.mismatchScore = (int)m.uiDiff;
m.QScores[0] = '\0';
m.rawScores[0] = '\0';
} else {
m.mismatchScore = alignmentScore(m.caRead, m.caRef,\
readlength, aQue.qualityScores);
printCommaSepScoresStr(readlength, aQue.qualityScores, m.QScores);
}
}
}
void getSingleMappingSeqAndQ4SOLiD\
(const CGenome_Index_TableQ& table, CAlignmentsQ& aQue, CMappingResult& m, bool samFormat)
{
/*
const unsigned int readlength = table.uiRead_Length;
// (1) Get ref in bits
CReadInBits ref = table.pgenomeNTInBits->getSubstringInBits(m.uiGlobalMappedPos, readlength);
if (m.strand == '-') {
ref = reverseCompliment(readlength, ref);
}
// (2) Get ref (and read) in Seq
decodeColors(m.caRead, aQue.read);
CReadInBits colorsInRef = bases2Colors(ref);
*/
const unsigned int readlength = table.uiRead_Length;
// (1) Get read in Seq
decodeColors(m.caRead, aQue.read);
// (2) Get ref in Seq
CReadInBits colorsInRef = getSingleMappingRef4SOLiD(table, aQue, m, samFormat);
// (3) Get nucleotide and quality sequence
getQualityScore4SOLiD(readlength, colorsInRef, aQue, m, samFormat);
/*
if (samFormat) { // correctRead
if (aQue.qualityScores == NULL) {
char dummyScore = (char)(20);
fillDummyQScores(readlength, dummyScore + Phred_SCALE_QUAL_SHIFT, m.QScores);
} else {
trQScores(readlength, Phred_SCALE_QUAL_SHIFT, aQue.qualityScores, m.QScores);
}
sprintf(m.TAG, "%s\tCS:Z:%s\tCQ:Z:%s", m.TAG, m.caRead, m.QScores);
//sprintf(m.TAG, "%s\tX1:Z:%s\tCS:Z:%s\tCQ:Z:%s", m.TAG, m.caRef, m.caRead, m.QScores);
correctAndDecodeRead(aQue.read, colorsInRef, samFormat, m.caRead, m.QScores);
if (m.strand == '-')
m.getReverseReadandQual();
} else {
decodeColors(m.caRef, colorsInRef); // Show the reference for validation purpose
m.SNPtype = returnSNPtype(aQue.read, colorsInRef);
if (aQue.qualityScores == NULL) {
m.mismatchScore = (int)m.uiDiff;
m.QScores[0] = '\0';
m.rawScores[0] = '\0';
} else {
m.mismatchScore = alignmentScore(m.caRead, m.caRef,\
readlength, aQue.qualityScores);
printCommaSepScoresStr(readlength, aQue.qualityScores, m.QScores);
}
}*/
}
unsigned int getNoOfDiff(const char* str1, const char* str2, unsigned int readLength)
{
unsigned int noOfDiff = 0;
for (unsigned int i = 0; i < readLength; i++) {
if (str1[i] != str2[i]) {
noOfDiff ++;
}
}
return(noOfDiff);
}
// For one read to one location,
void getSingleMappingInfo(const CGenome_Index_TableQ& table, CAlignmentsQ& aQue,\
unsigned int mappingId, CMappingResult& m, bool samFormat)
{
getSingleMappingIndex(*(table.pgenomeNT), aQue, mappingId, m);
if (samFormat) { // must set after the strand flag is set
m.setSingleEndSamFields();
} // must set before the color seq and QUAL is set
if (table.bMapReadInColors) {
getSingleMappingSeqAndQ4SOLiD(table, aQue, m, samFormat);
} else {
getSingleMappingSeq4Solexa(table, m, samFormat);
}
if (aQue.qAllInThreshold() && !samFormat) {
int noMisMatch = getNoOfDiff(m.caRead, m.caRef, m.uiReadLength);
/* if(m.uiDiff != noMisMatch) {
ERR;
}*/
m.uiDiff = noMisMatch;
}
if (table.pbaRepeatRepresentativeFlag->b(aQue.aiHitIndex[mappingId])) {
m.MultipleMappedNo++;
}
}
void getLongMappingInfo(const CGenome_Index_TableQ& table, CAlignmentsQ& aQue, bool samFormat,\
unsigned int mappingId, CMappingResult& m)
{
// (1) Get index
getSingleMappingIndex(*(table.pgenomeNT), aQue, mappingId, m);
if (samFormat) {
m.setSingleEndSamFields();
} else {
// (2) Get Ref Sequence
getLongRefSeq(table, m, samFormat);
// (3) Get mismatch score
if (m.QScores[0] == '\0') {
m.mismatchScore = (int)m.uiDiff;
} else { // If quality score are available, get quality score
m.mismatchScore = alignmentScore(m.caRead, m.caRef, m.uiReadLength, m.rawScores);
}
if (m.strand == '-') {
reverseComplementKmer(m.caRef);
}
}
}
bool wrongIndex(const CReadInBitsSet& readSet, const CGenome_Index_TableQ& table)
{
if (readSet.uiRead_Length != table.uiRead_Length) {
LOG_INFO("Info %d: The index is not for read length %d, is for %d.\n",\
readSet.uiRead_Length, table.uiRead_Length, ERROR_LOG);
return(true);
}
bool bColorRead = (readSet.cFileType == 'Q' || readSet.cFileType == 'S');
if ( bColorRead != table.bMapReadInColors) {
if (bColorRead) {
LOG_INFO("Info %d: The index is not for color read.\n", ERROR_LOG);
} else {
LOG_INFO("Info %d: The index is for color read.\n", ERROR_LOG);
}
return(true);
}
return(false);
}
|