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
|
/*
Copyright (C) 2006-2008 Keio University
(Kris Popendorf) <comp@bio.keio.ac.jp> (2006)
This file is part of Murasaki.
Murasaki 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.
Murasaki 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 Murasaki. If not, see <http://www.gnu.org/licenses/>.
*/
///////////////
// murasaki - multiple genome global alignment program
// by Kris Popendorf (krisp@dna.bio.keio.ac.jp)
/////////////
// murasaki.cc
// main program control and such
//////////
#include <iostream>
#include <fstream>
#include <vector>
#include <assert.h>
#include <iterator>
#include <unistd.h>
#include <limits.h>
#include <math.h>
#include "murasaki.h"
#include "timing.h"
#include "dinkymath.h"
#include "sequence.h"
#include "msethash.h"
#include "ecohash.h"
#include "openhash.h"
#include "murasaki_mpi.h"
#include "arrayhash.h"
#include "mingw32compat.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <boost/regex.hpp> //screw "sscanf" =P
#include <boost/lexical_cast.hpp>
#include <boost/filesystem/operations.hpp>
#include <algorithm> //for random_shuffle
#ifdef __FreeBSD__
#include <sys/types.h>
#include <sys/resource.h>
#include <sys/sysctl.h>
#include <sys/vmmeter.h>
#endif
#ifdef __APPLE__
#include <mach/mach_init.h>
#include <mach/host_info.h>
#include <mach/mach_host.h>
#endif
#ifdef __MINGW32__
#include <windef.h>
#include <winbase.h>
#include <windows.h>
#endif
#ifdef MURASAKI_MPI
#include "mpi.h"
#endif
using namespace std;
int seq_count=0;
Hash *mfh; //multi-fasta-hash
vector<Sequence*> seqs;
word usedBuckets=0,usedPats=0,worstPat=0;
UsedMap *anchors;
RepeatMap *repeats=0;
string version_string(PROGRAMVERSION);
string pattern_src;//the pattern hunter default 18long
int patLength;
BitSequence* globalPat;
char nodename[81];
int debugbits=-22;
SystemInfo sysinfo;
Options opt; //runtime option manager
ProgressTicker ticker(100);
int verbose=0; //ubersneaky debug switch
word longestSeq=0;
word totalSeqLength=0;
word totalHashLength=0;
word totalKeysUsed=0,totalSeedsSeen=0;
word *dfCount=0;
word totalAnchoredLocs=0;
ofstream *entropy_fh=0,*anchorProgress_fh=0;
int main (int argc,char **argv){
MurasakiRuntime *murasakiRunner=0;
murasakiRunner=new MurasakiRuntime(argc,argv);
cout << "Murasaki finished!"<<endl;
delete murasakiRunner; //for some reason calling delete explicitly makes everything happier.
return 0; //if we make it here, yay.
}
MurasakiRuntime::MurasakiRuntime(int argc,char ** argv) : cleaned(false) {
//all this class wrapping just for the sake of not making this try { } block not cover 1000 lines
try{
init(argc,argv);
prep();
work();
success();
}
catch(MurasakiAbortException &e){//used when user actually requests an abort (eg. when running --version)
cleanup(e.status());
exit(e.status());
}
catch(exception &e){
cerr << "Encountered exception: "<< e.what()<<endl;
cerr << "Bailing..."<<endl;
try {
cleanup(99);
} catch(exception &e){
cerr << "Caught an exception during cleanup. Ouch. "<<e.what()<<endl;
throw(e);
}
#ifdef MURASAKI_MPI
if(mpi_capable)
throw(e); //OpenMPI has it's own exception handlers that kick in and provide backtraces, so just throw it again (which might also help cleanup any loose ends)
#endif
exit(99);
}
}
void MurasakiRuntime::init(int argc,char **argv){
#ifdef MURASAKI_MPI
gethostname(nodename, 80);
assert(cout << "MPI> Init "<<nodename<<" pid: "<<getpid()<<endl);
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &mpi_id);
MPI_Comm_size(MPI_COMM_WORLD, &mpi_procs);
mpi_capable = true;
// set tag for printing
sprintf(mpi_tag,"<%d>",mpi_id);
if(mpi_procs<2){
if(opt.verbose)
cerr << "MPI>MPI is useless (and in fact impossible) with fewer than 2 processes. Disabling."<<endl;
mpi_capable=false;
}else{
cout << "MPI>murasaki/MPI rank " << mpi_id << "/"<<mpi_procs<<": running on " << nodename << " pid: "<<getpid()<<endl;
}
//setup message types
mpi_types_init();
// synchronize random seed
MPI_Bcast((void*)&opt.rand_seed, sizeof(int), MPI_CHAR, 0, MPI_COMM_WORLD);
#endif
initConstants();
//option procesing
opt.preInit(); //attempt to guess some defaults now that MPI is up
opt.commandline_opts(argc,argv);
// opt.dumpCommandline(opt.prefix+".cmdline"); //not implemented yet
#ifdef MURASAKI_MPI
// redirection
if(opt.mpi_outputRedirect){
stdoe=0; // stdout & err
if(mpi_id != 0){ // only process #0 uses the console
snprintf(stdoename, 100, "murasaki-mpiout-%d", mpi_id);
stdoe = open(stdoename, O_WRONLY|O_CREAT|O_TRUNC, 0644);
dup2(stdoe, 1);
dup2(stdoe, 2);
}else{
strcpy(stdoename,"");
}
}
#endif
//grab remaining args
if(optind<argc && !pattern_src.empty()){
for(int i=optind;i<argc;i++){
args.push_back(string(argv[i]));
}
}else{
if(optind>=argc)
cout << "Error: Need at least one input sequence."<<endl;
else
if(pattern_src.empty())
cout << "Error: Need to specify a pattern (see -p option)."<<endl;
cout << program_help(); exit(1);
}
//generate pattern from pattern_src if necessary
convertPattern(pattern_src);
#ifdef MURASAKI_MPI
//this might not be necessary if std's random number generator obeys srand, but, just in case.
if(mpi_capable)
MPI_Bcast(const_cast<char*>(pattern_src.data()),pattern_src.size(),MPI_CHAR,0,MPI_COMM_WORLD); //everybody use 0's pattern
#endif
writeOut(opt.pat_record,pattern_src);
//solidfy parameters
seq_count=args.size();
if(seq_count==1)
opt.hashOnly=true; //can't anchor with only 1 sequence.
opt.solidify();
if(opt.anchorProgressCheck)
anchorProgress_fh=new ofstream(opt.anchorProgress_record.c_str());
ofstream opf(opt.options_record.c_str());
opf << opt;
opf << platformInfo();
opf.close();
cout << opt;
#ifdef MURASAKI_MPI
//solidfy mpi data
if(mpi_capable)
mpi_init();
#endif
}
void MurasakiRuntime::prep(){
writeOut(opt.status_record,"Loading sequences...",true);
//load sequences
ofstream outf(opt.seq_record.c_str());
seqLoadStart.reset();
for(int i=0;i<seq_count;i++){
outf << args[i] << endl;
seqs.push_back(new Sequence(args[i]));
cout << "Seq "<<seqs[i]->name<<" loaded. "<<humanMemory(seqs[i]->length())<<endl;
longestSeq=max<word>(longestSeq,seqs[i]->length());
totalSeqLength+=seqs[i]->length();
totalHashLength+=((opt.skipRev || opt.skipFwd) ? seqs[i]->fwd->getCounted():seqs[i]->fwd->getCounted()*2)/opt.hashSkip;
}
set_seqtable(seqs); // prepare for hashing: can we skip this process in future version?
Timer seqLoadStop;
outf.close();
cout << "Sequence loading took: "<<elapsed(seqLoadStart,seqLoadStop)<<endl;
#ifdef MURASAKI_MPI
if(mpi_capable && opt.mpi_fileDistro) mpi_syncSeqCounts();
#endif
finishGlobalFrequencies();
//ready pattern(s) and hash
pat=new BitSequence(pattern_src);
cout << "Pat: "<<pat->length()<<" bases long with weight "<<pat->hashLength()<<endl;
cout << *pat <<endl;
int hashLength=pat->hashLength();
patLength=pat->length();
globalPat=pat;
double idealHash=pow((double)4.,(double)(hashLength));
hash_max=intpow(2,max_hash_bits);
int hashBits=min<int>(max_hash_bits,hashLength*2);
bool memoryFitting=false;
#ifdef MURASAKI_MPI
if(mpi_capable){
mpi_initJobs();
if(opt.auto_hashbits){
int oldHashBits=hashBits;
int storageHosts=mpi_hostLeader_byName.size();
while((storageHosts>>=1)>0) //every time we double the number of hosts we're on, we double hash table size
hashBits++;
if(hashBits>hashLength*2)
hashBits=hashLength*2;
if(oldHashBits!=hashBits)
cout << "Using "<<hashBits<<" hashbits instead of "<<oldHashBits<<" because we have "<<mpi_hostnames.size()<<" hosts available."<<endl;
opt.auto_hashbits=false; //this is the extent to which we can automate this for MPI for now...
}
}
#endif
if(opt.getOptSource("hashtype")!=OPT_SRC_MANUAL){
if(totalHashLength/(seq_count) < intpow(2,hashBits)/3){
cout << "Auto> Input sequence is short, so using OpenHash."<<endl;
opt.hashPref=OpenHash_t;
}
}
if(opt.getOptSource("quickhash")!=OPT_SRC_MANUAL){
int target=(opt.hashPref==OpenHash_t ? 0:3);
if(opt.quick_hash!=target){
cout << "Auto> Switching hash function to "<<target<<" to accommodate "<<opt.hashPref_s()<<endl;
opt.quick_hash=target;
}
}
Timer hashFuncCreate;
writeOut(opt.status_record,"Computing hash parameters...\n",true);
cout << "Computing hash parameters...\n";
INITHASHSETTINGS:
initHashParams(hashBits,pat);
//report size info after the fact...
unsigned long linearHashCost=1;
unsigned long linearAnchorCost=1;
unsigned long bucketPrepCost=1;
unsigned long hashBlockSize=1;
switch(opt.hashPref){
//this could be a template...but meh....
#define GETMEMORYSTATS(hashtype) linearHashCost=hashtype::linear_cost(totalHashLength); \
linearAnchorCost=sizeof(AnchorSet)*totalSeqLength/pattern_src.length()*seq_count; \
bucketPrepCost=hashtype::bucket_prep_cost(hash_size); \
hashBlockSize=hashtype::bucket_prep_cost(1);
case ArrayHash_t: GETMEMORYSTATS(ArrayHash);
break;
case MSetHash_t: GETMEMORYSTATS(MSetHash);
break;
case EcoHash_t: GETMEMORYSTATS(EcoHash);
break;
case OpenHash_t: GETMEMORYSTATS(OpenHash);
break;
default: break;
}
//need to come up with these values
//basicmemory is the memory required just to start the hash table
word basicMemory=bucketPrepCost;
word bestCaseMemory=basicMemory+linearHashCost;
word avgCaseMemory=basicMemory+linearHashCost+linearAnchorCost;
bool memoryFits=!opt.auto_hashbits || bestCaseMemory/1024<opt.targetMemory;
if(!memoryFitting || memoryFits){
cout << "Would take minimum "<< humanMemory(idealHash*hashBlockSize) <<" to make perfect hash."<<endl
<< "Hashing "<<humanMemory(totalHashLength)<<" of sequence requires: "<<endl
<< " ~ linear (in seq length) hashing cost of "<<humanMemory(linearHashCost)<<endl
<< " ~ linear (in seq length) expected anchor cost of "<<humanMemory(linearAnchorCost)<<endl;
}
cout << "Initial hash table uses: " << humanMemory(basicMemory) << " ("<<hashBits<<" bits, "<<hash_size<<" entries)"<< endl;
cout << "Expected memory usage (without anchors): "<<humanMemory(bestCaseMemory)<<endl;
if(avgCaseMemory/1024<opt.targetMemory && !memoryFits && hashBits>1){
if(!memoryFitting)
cout << " ### This is more memory than is available in your system." << endl
<< " ## Murasaki will try reducing the number of hashbits used..." << endl
<< " # (You can override this behaviour by specifying --hasbits manually)"<<endl;
else
cout << "# Reducing hashbits again..."<<endl;
memoryFitting=true;
hashBits--;
goto INITHASHSETTINGS;
}
cout << "Expected memory usage (with anchors): "<<humanMemory(avgCaseMemory)<<endl;
#ifdef MURASAKI_MPI
if(mpi_capable){
//now that we know the specifics of the hash,
//finish figuring out the details of what each node is working on
//figure out how much hash goes to each node
mpi_storeShare.resize(mpi_procs,0);
mpi_storeOwn.resize(mpi_procs,pair<word,word>(0,0));
mpi_totalStorage=0;
for(int i=0;i<mpi_procs;i++)
if(mpi_jobs[i]==JOB_STORAGE){
mpi_totalStorage+=mpi_worldMemory[i];
}
int last=-1;
word prevStop=-1;
for(int i=0;i<mpi_procs;i++){
if(mpi_jobs[i]==JOB_STORAGE){
mpi_storeShare[i]=(opt.mpi_memoryBalance ? ((double)mpi_worldMemory[i])/((double)mpi_totalStorage):
(double)1.0/mpi_jobCount[JOB_STORAGE]);
word size=(word)(hash_size*mpi_storeShare[i]);
word start=prevStop+1,stop=start+size-1;
mpi_storeBrk[start]=i;
mpi_storeBrkStop[stop+1]=i;
mpi_storeOwn[i]=pair<word,word>(start,stop);
prevStop=stop;
last=i;
}
}
assert(last!=-1);
mpi_storeOwn[last].second=hash_size-1;
mpi_storeBrkStop[hash_size+1]=last;
mpi_total_hash_size=hash_size;
//my own personal hash settings:
if(mpi_jobs[mpi_id]==JOB_STORAGE){
mpi_myStoreOffset=mpi_storeOwn[mpi_id].first;
hash_size=mpi_storeOwn[mpi_id].second-mpi_storeOwn[mpi_id].first+1;
}
//split up hashing work (if we had some cpu information about each node maybe
//we could split it by speed, but for now, split evenly)
word hashChunkSize=globalCounted/(word)mpi_jobCount[JOB_HASHER];
mpi_hashShare.resize(mpi_procs,0);
mpi_hashOwn.resize(mpi_procs,pair<word,word>(0,0));
last=-1;
int hasher=0;
for(int i=0;i<mpi_procs;i++){
if(mpi_jobs[i]==JOB_HASHER){
word start=hashChunkSize*(word)hasher;
mpi_hashShare[i]=1.0/(double)mpi_jobCount[JOB_HASHER];
mpi_hashBrk[start]=i;
mpi_hashOwn[i]=pair<word,word>(start,start+hashChunkSize);
last=i;
hasher++;
}
}
assert(last!=-1);
mpi_hashOwn[last].second=globalCounted-1;
//display a nice summary of what's going on on each node and why
cout << "MPI>Node summary:"<<endl;
for(int i=0;i<mpi_procs;i++){
cout << "MPI> node "<<i<< (mpi_id==i ? "*":" ") << " ("<<mpi_hostnames[i]<<"): Mem:"<<humanMemory(mpi_worldMemory[i]*1024)
<< " Job: "<<MPI_jobNames[mpi_jobs[i]]<<"#"<<mpi_worldId2jobId[i];
switch(mpi_jobs[i]){
case JOB_HASHER: cout << " " << mpi_hashShare[i]*100 <<"% (from "<<mpi_hashOwn[i].first<<")"<<endl;break;
case JOB_STORAGE: cout << " " << mpi_storeShare[i]*100 <<"% (from "<<mpi_storeOwn[i].first<<")"<<endl;break;
default: cout << endl;break;
}
}
if(mpi_jobs[mpi_id]==JOB_STORAGE and !opt.mpi_distMerge)
cout << "My merge and assembly: node "<<mpi_assemblerIds[mpi_id]<<endl;
cout << "MPI>Total world memory: "<<humanMemory(mpi_totalMemory*1024)<<endl;
cout << "MPI>Total world storage: "<<humanMemory(mpi_totalStorage*1024)<<" ("<<((double)mpi_totalStorage/(double)mpi_totalMemory*100)<<"%)"<<endl;
}
#endif
#ifdef MURASAKI_MPI
if(mpi_capable){
if(linearHashCost/1024>mpi_totalStorage){
cout << "**** Warning: Using this hash method, it's physically impossible"<<endl
<< "**** to hash this amount of data into available ram."<<endl;
if(opt.hashPref!=EcoHash_t)
cout << "****--------> Consider using EcoHash."<<endl;
else
cout << "****--------> Consider using more nodes/memory."<<endl;
}
if(avgCaseMemory/1024>mpi_totalStorage){
cout << "****>>>>>> Impending Disaster <<<<<<****" << endl
<< "****>> Murasaki "
<< (bestCaseMemory/1024>mpi_totalStorage ? "_will_":"may")
<<" consume more memory than you have available to MPI.\n"
<< "****>> Consider changing hash settings (like using fewer hashbits).\n";
}
}else{
#endif
//obligatory warnings about memory usage
if(linearHashCost/1024>sysinfo.totalMemory){
cout << "**** Warning: Using this hash method, it's physically impossible"<<endl
<< "**** to hash this amount of data into your computer's"<<endl
<< "**** total ram."<<endl;
if(opt.hashPref!=EcoHash_t)
cout << "****--------> Consider using EcoHash or MPI across multiple nodes."<<endl;
else
cout << "****--------> Consider using MPI across multiple nodes."<<endl;
}
if(avgCaseMemory/1024>sysinfo.freeMemory)
cout << "**** Warning: This is more memory you have free on your system.\n"
<< "**** You may encounter massive slowdowns if murasaki\n"
<< "**** gets swapped to disk.\n"
<< "****--------> Consider changing hash settings.\n";
if(avgCaseMemory/1024>sysinfo.totalMemory)
cout << "****>>>>>> Impending Disaster <<<<<<****" << endl
<< "****>> Murasaki "<<
(bestCaseMemory/1024>sysinfo.totalMemory ? "_will_":"may")
<<" consume more memory than you have in your system.\n"
<< "****>> Consider changing hash settings.\n";
if(avgCaseMemory/1024>opt.targetMemory && avgCaseMemory/1024<=sysinfo.totalMemory){
cout << "** Warning: This is more memory than "<<(opt.userSetMemory ? "specified.":"recommended.")<<endl
<< "** You may run Murasaki with a higher --memory option to avoid"<<endl
<< "** this warning";
if(avgCaseMemory*100/sysinfo.totalMemory>90)
cout << " (however you may run out of memory!)";
cout << "."<<endl;
}
#ifdef MURASAKI_MPI
}
#endif
Timer hashCreate;
cout << "Hash parameters computed in "<<elapsed(hashFuncCreate,hashCreate)<<endl;
#ifdef MURASAKI_MPI
if(!mpi_capable || mpi_jobs[mpi_id]==JOB_STORAGE){ //only if we're doing storage
//repeat the memory check
switch(opt.hashPref){
case ArrayHash_t: GETMEMORYSTATS(ArrayHash);
break;
case MSetHash_t: GETMEMORYSTATS(MSetHash);
break;
case EcoHash_t: GETMEMORYSTATS(EcoHash);
break;
case OpenHash_t: GETMEMORYSTATS(OpenHash);
break;
default: break;
}
#endif
//suitable hashBits selected, so lets make one.
writeOut(opt.status_record,"Creating storage structures...\n",true);
cout << "Creating storage structures: "<<hash_size<<" entries in "<<humanMemory(bucketPrepCost)<<" space."<<endl;
switch(opt.hashPref){
case ArrayHash_t: mfh=new ArrayHash(pat);break;
case MSetHash_t: mfh=new MSetHash(pat);break;
case EcoHash_t: mfh=new EcoHash(pat);break;
case OpenHash_t: mfh=new OpenHash(pat);break;
default: cout << "That hash ("<<opt.hashPref_s()<<") isn't supported."<<endl
<< "Using EcoHash instead."<<endl;
mfh=new EcoHash(pat);break;
}
Timer storageCreated;
cout << "Storage structures created in: "<<elapsed(hashCreate,storageCreated)<<endl;
#ifdef MURASAKI_MPI
}
if(mpi_id==mpi_finalAssembler || (opt.mpi_distCollect && mpi_jobs[mpi_id]==JOB_HASHER)){
anchors=new UsedMap();
if(opt.mergeFilter && opt.repeatMap)
repeats=new RepeatMap();
cout << "Anchor structures created."<<endl;
}
if(mpi_id==0){ //only 1 process needs to do this...
#endif
//archive region list
if(opt.dumpRegions){
cout << "Dumping region list..."<<endl;
ofstream regionsOf(opt.region_record.c_str());
outputRegions(regionsOf);
regionsOf.close();
}
#ifdef MURASAKI_MPI
}
#endif
//end of prep work
}
void MurasakiRuntime::work(){
#ifdef MURASAKI_MPI
if(!mpi_capable){
#endif
anchors=new UsedMap(); //in single cpu land, of course we have anchors
Timer hashStart;
//hash the monkey! all but the first of the monkies...
for(unsigned i=0;i<seqs.size();i++){
// try hashCache
if(opt.hashCache){
mfh->clear();
string cachename=hashCacheName(seqs[i]->name, pat);
ifstream cachef;
cachef.open(cachename.c_str(), ios::binary);
if (cachef){
cachef.close();
cout << "cache hit, so skipping to hash " << seqs[i]->name << "." << endl;
continue;
}
}
// Hash
if(!opt.skipFwd){
cout << "\nHashing "+seqs[i]->name+" forwards\n";
writeOut(opt.status_record,"Hashing "+seqs[i]->name+" forwards\n",true);
hashSeq(seqs[i]->fwd,pat,1,seqs[i]);
}
if(!opt.skipRev){
cout << "\nHashing "+seqs[i]->name+" backwards\n";
writeOut(opt.status_record,"Hashing "+seqs[i]->name+" backwards\n",true);
hashSeq(seqs[i]->rev,pat,-1,seqs[i]);
}
// Save hashCache
if(opt.hashCache){
string cachename=hashCacheName(seqs[i]->name, pat);
ofstream cachef;
cout << endl <<"Saving hash as: " << cachename << endl;
cachef.open(cachename.c_str(), ios::trunc|ios::out|ios::binary);
if(!cachef){ throw MurasakiException(string("can't write ")+cachename); }
mfh->dump(cachef);
cachef.close();
}
// assert(mfh->sanityCheck());
// load from cache
if(opt.hashCache){
mfh->clear();
for(unsigned i=(opt.histogram ? 0:1);i<seqs.size();i++){
string cachename=hashCacheName(seqs[i]->name, pat);
ifstream cachef;
cout << "Loading hash from: " << cachename << endl;
cachef.open(cachename.c_str(), ios::binary);
if(!cachef){ throw MurasakiException(string("can't load ")+cachename); }
mfh->load(cachef);
cachef.close();
}
}
}
Timer hashStop;
cout << "\nInitial hashing took: "<<elapsed(hashStart,hashStop)<<endl;
#ifdef MURASAKI_MPI
} //end of "if(!mpi_capable)" under MPI
#endif
#ifdef MURASAKI_MPI
if (mpi_capable){
MPI_Barrier(MPI_COMM_WORLD);
writeOut(opt.status_record,"Starting unique MPI jobs...\n",true);
Timer mpiJobsStart;
switch(mpi_jobs[mpi_id]){
case JOB_HASHER: if(!opt.mpi_noCake)
mpi_hasher_client_mode(pat);
cout << "Waiting for storage nodes to finish..."<<endl;
//phase 1 complete
MPI_Barrier(MPI_COMM_WORLD);
if(opt.hashOnly) //skip extraction
break;
if(opt.mpi_distCollect){
mpi_merge_client_mode();
//now we have to figure out who sends to who
for(int mergePass=0;(1<<mergePass)<((int)mpi_hasherIds.size());mergePass++){
bool sending=(mpi_myJobRank & (1<<mergePass));
int partner=sending ? (mpi_myJobRank - (1<<(mergePass))):(mpi_myJobRank+(1<<(mergePass)));
cout << "Hasher: "<<mpi_myJobRank<<" on pass "<<mergePass<<" running as a "<<(sending ? "sender":"receiver")<<" with "<<partner<<endl;
if(sending){ //sender
mpi_anchorMergeClient(partner);
cout << "Waiting for other hashers to finish merging..."<<endl;
goto DistMergeDone; //only send once
}else{ //receiver
if(partner>=(int)mpi_hasherIds.size()){
cout << " (sender "<<partner<<" doesn't exist. Skipping this round.)"<<endl;
continue; //will still be active next round
}
vector<int> senders(1,partner); //for now we only use 1 sender
mpi_anchorMergeServer(senders);
}
}
DistMergeDone: ;
}else{
if(mpi_id==mpi_finalAssembler){
mpi_merge_client_mode();
}
}
break;
case JOB_STORAGE:
if(!opt.mpi_noCake)
mpi_storage_client_mode();
else
mpi_hashAndStore_client_mode(pat);
//phase 1 complete
MPI_Barrier(MPI_COMM_WORLD);
if(opt.hashOnly) //skip extraction
break;
mpi_extract_client_mode(pat);
break;
default: cerr << "Please place the device on the ground and assume the party submission position. A Keio Science representative will arrive shortly to escort you to the party."<<endl;break;
}
MPI_Barrier(MPI_COMM_WORLD);
Timer mpiJobsDone;
cout << "Total wall clock time on all calculations: "<<elapsed(mpiJobsStart,mpiJobsDone)<<endl;
if(mpi_id==mpi_finalAssembler){ //my job to write the output
if(!opt.hashOnly){
cout << "Writing anchors...";cout.flush();
writeAnchors(opt.anchor_record);
if(repeats && opt.mergeFilter){
cout << "Writing "<<repeats->size()<<" repeats...";cout.flush();
writeRepeats(opt.repeat_record);
}
if(opt.histogram)
mpi_write_histogram();
cout << endl;
}
}
cout << "Counter tallies:"<<endl;
cout << "node\thash\tstore\tloc\text\tmerge\tasend\tarecv\twork"<<endl;
//accumulate all the little counters
for(int i=0;i<mpi_procs;i++){
MPI_Bcast(&mpi_hashCount[i],1,MPI_LONG,i,MPI_COMM_WORLD);
MPI_Bcast(&mpi_storeCount[i],1,MPI_LONG,i,MPI_COMM_WORLD);
MPI_Bcast(&mpi_extractLocCount[i],1,MPI_LONG,i,MPI_COMM_WORLD);
MPI_Bcast(&mpi_extractCount[i],1,MPI_LONG,i,MPI_COMM_WORLD);
MPI_Bcast(&mpi_mergeCount[i],1,MPI_LONG,i,MPI_COMM_WORLD);
MPI_Bcast(&mpi_workTime[i],1,MPI_DOUBLE,i,MPI_COMM_WORLD);
MPI_Bcast(&mpi_anchorSendCount[i],1,MPI_LONG,i,MPI_COMM_WORLD);
MPI_Bcast(&mpi_anchorRecvCount[i],1,MPI_LONG,i,MPI_COMM_WORLD);
}
word anchorCount;
if(mpi_id==mpi_finalAssembler){
anchorCount=anchors->count();
}
MPI_Bcast(&anchorCount,1,MPI_UNSIGNED_LONG,mpi_finalAssembler,MPI_COMM_WORLD);
//print them in one go (otherwise mpi tends to block on the endl buffer flushes)
for(int i=0;i<mpi_procs;i++){
cout << i
<< "\t" << mpi_hashCount[i]
<< "\t" << mpi_storeCount[i]
<< "\t" << mpi_extractLocCount[i]
<< "\t" << mpi_extractCount[i]
<< "\t" << mpi_mergeCount[i]
<< "\t" << mpi_anchorSendCount[i]
<< "\t" << mpi_anchorRecvCount[i]
<< "\t" << humanTime(mpi_workTime[i])
<< endl;
}
cout << "*"
<< "\t" << sum<long>(mpi_hashCount)
<< "\t" << sum<long>(mpi_storeCount)
<< "\t" << sum<long>(mpi_extractLocCount)
<< "\t" << sum<long>(mpi_extractCount)
<< "\t" << sum<long>(mpi_mergeCount)
<< "\t" << sum<long>(mpi_anchorSendCount)
<< "\t" << sum<long>(mpi_anchorRecvCount)
<< "\t" << humanTime(sum<double>(mpi_workTime))
<< endl;
cout << "Total anchors: "<<anchorCount<<endl;
cout << "MPI work finished."<<endl;
}else{
#endif //do it the non-mpi way
//midway init of anchor-related structures. weee
if(opt.mergeFilter && opt.repeatMap)
repeats=new RepeatMap();
Timer matchStart, matchStop;
if(!opt.hashOnly){
extractAndMatch(pat);
matchStop.reset();
cout << "Total anchors: "<<anchors->count()<<endl;
cout << "Anchor extraction + merge time: "<<elapsed(matchStart,matchStop)<<endl;
}
cout << "Total processing time: "<<elapsed(seqLoadStart,matchStop)<<endl;
Timer outputWrite;
if(opt.histogram){
cout << "Writing histogram data...";cout.flush();
writeHisto(opt.hashHisto_record,opt.hashDetailed_record);
cout << endl;
}
if(!opt.hashOnly){
cout << "Writing anchors...";cout.flush();
writeAnchors(opt.anchor_record);
cout << endl;
}
if(opt.measureHashCollisions){
cout << "Generating hash collision/seed histogram..."<<endl;
map<size_t,size_t> collisionSizeHistogram;
map<size_t,size_t> seedHistogram;
generateCollisionHistogram(collisionSizeHistogram,seedHistogram);
writeMap(collisionSizeHistogram,opt.prefix+".collisions.histogram","hash collision histogram");
writeMap(seedHistogram,opt.prefix+".seed.histogram","seed count histogram");
}
#ifdef HASHPROFILE
cout << "Writing hash table performance data..."<<endl;
mfh->writePerformanceData(opt.prefix+".hash.performance");
#endif
if(!opt.hashOnly || opt.measureHashCollisions){
double optimal=((double)totalSeedsSeen)/((double)hash_size)*100.0;
optimal=min<double>(optimal,100.0);
double usage=((double)totalKeysUsed)/((double)hash_size)*100.0;
cout << "Total seeds used in anchors: "<<totalSeedsSeen<<endl;
cout <<"Hash performance:"<<endl
<< " Keys used: "<<totalKeysUsed<<" out of "<<hash_size<<" possible ("
<<fstring(usage)<<"%)."<<endl
<<" Used keyspace is "<<fstring(usage)<<"% = "
<<fstring(usage/optimal*100.)<<"% of magic *optimal "
<<fstring(optimal)<<"%"<<endl;
if(totalKeysUsed)
cout << " Average pigeons per pigeon hole: "<<((double)totalSeedsSeen)/((double)totalKeysUsed)<<endl;
}
if(repeats){
cout << "Writing "<<repeats->size()<<" repeats...";cout.flush();
writeRepeats(opt.repeat_record);
}
Timer totalDone;
cout << "Output writing finished in: "<<elapsed(matchStop,totalDone)<<endl;
cout << "Total time: "<<elapsed(seqLoadStart,totalDone)<<endl;
writeOut(opt.status_record,"Done!\n",true);
#ifdef MURASAKI_MPI
} //trailing } from the if(mpi_capable){starting mpi jobs...}else{
#endif
}
void writeAnchors(string anchor_record){
ofstream of(anchor_record.c_str());
anchors->writeOut(of);
of.close();
ofstream ancDetails((anchor_record+".details").c_str());
if(opt.bitscore){
ofstream ancBitscore((anchor_record+".bitscore").c_str());
anchors->saveDetails(ancDetails,ancBitscore);
ancBitscore.close();
}else{
anchors->saveDetails(ancDetails,cerr);
}
ancDetails.close();
if(opt.tfidf){
ofstream of((anchor_record+".stats.tfidf").c_str());
anchors->writeTfidf(of);
}
if(!opt.gappedAnchors){
ofstream of((anchor_record+".stats.ungappedscore").c_str());
anchors->writeScores(of);
}
}
void writeRepeats(string record){
ofstream of(record.c_str());
repeats->writeOut(of);
}
void writeHisto(string hashHisto_record,string details){
ofstream histo(hashHisto_record.c_str());
if(opt.histogram)
mfh->writeHistogram(histo);
histo.close();
if(opt.histogram>=3){
cout << "Writing detailed histogram...";cout.flush();
ofstream histo(details.c_str());
mfh->writeDetailedHistogram(histo);
histo.close();
}
}
void hashSeq(BitSequence *bitseq,BitSequence *pat,int sign,Sequence *s){
ticker.reset(bitseq->length()-1);
for(SeqPosPairArray::iterator region=bitseq->matchRegions.begin();
region!=bitseq->matchRegions.end();region++){
//cout << "Valid region is "<<region->first<<" to "<<region->second<< " - patlen" << pat->length() << endl;
SeqPos stop=region->second-pat->length()+2;
SeqPos start=region->first+1;
Window win(bitseq,region->first,pat);
word hash; //don't need to init this
int progress;
// cout << "Hasing region from "<<start<<" to "<<stop<<endl;
for(SeqPos p=start;p<=stop;p+=opt.hashSkip){
hash=win.hash();
// assert(cout << "Hashing "<<s->name<<"."<<(sign>0 ? "fwd":"rev")<<":"<<p<<"->"<<wordToString(hash)<<endl);
// assert(cout << "At "<<p<<" "<<hash<<" hash= " << wordToString(hash)<<endl);
Location here(s,p*sign);
if(!mfh->emptyAt(hash)){
if(opt.hashfilter){
if(mfh->sizeAt(hash)>(unsigned)opt.hashfilter)
goto NextHash;
}
if(opt.seedfilter){
if(mfh->sizeAt(hash,here)>(unsigned)opt.seedfilter)
goto NextHash;
}
}
mfh->add(hash,here);
NextHash:
if((progress=ticker.tick(p-1))>=0){
hashStatusCheck(progress,p);
}
// assert(mfh->sanityCheck(hash));
if(opt.hashSkip>1)
win.slide(opt.hashSkip*2);
else
win.slide();
}
}
}
void extractAndMatch(BitSequence *pat){
cout << "Extracting anchors from hash-space."<<endl;
Timer extractStart;
ticker.reset(hash_size);
word &base=activeHash;
for(base=0;base<(word)hash_size;base++,ticker.tick()){
// cout << "Checking "<<base<<endl;
if(mfh->emptyAt(base))
continue;
totalKeysUsed++;
// cout << "Got bits! ("<<mfh->sizeAt(base)<<" bits!)"<<endl;
list<LocList> fulllist;
mfh->getMatchingSets(base,fulllist);
for(list<LocList>::iterator seti=fulllist.begin();seti!=fulllist.end();++seti){
totalSeedsSeen++;
LocList& loclist=*seti;
bool gotAllSeqs=true;
word combinations=1;
int skips=opt.rifts;
for(unsigned i=0;i<loclist.size();i++){
size_t size=loclist[i].size();
if(size){
combinations*=size;
}else{
if(skips>0)
skips--;
else{
gotAllSeqs=false;
}
}
}
if(gotAllSeqs){
if(opt.mergeFilter && combinations>opt.mergeFilter){
if(repeats){
repeats->add(loclist);
}
goto ExtractLocDone;
}
list<Location> start;
procLocs(loclist,start,opt.rifts,0);
}
ExtractLocDone:
;
}
}
cout << endl; //for ticker
Timer extractDone;
cout << "Anchor extraction completed in: "<<elapsed(extractStart,extractDone)<<endl;
}
bool sanityCheck(Location &l){
if(!l.seq())return false;
if(l.pos>l.seq()->length())return false;
if(l.pos<-l.seq()->length())return false;
return true;
}
bool isFullLocList(const LocList &locList){
word skips=opt.rifts;
for(unsigned i=0;i<locList.size();i++)
if(locList[i].empty()){
if(skips>0)
skips--;
else
return false;
}
return true;
}
void procLocs(LocList &locList,list<Location> &use,int skipsLeft,int level){
if(level<seq_count){
if(locList[level].empty() && skipsLeft>0 ){
list<Location> temp(use);
temp.push_back(Location(SeqIdx(0),SeqPos(0)));
procLocs(locList,temp,skipsLeft-1,level+1);
}else{
for(list<Location>::iterator i=locList[level].begin();
i!=locList[level].end();
i++){
list<Location> temp(use);
assert(sanityCheck(*i));
temp.push_back(*i);
procLocs(locList,temp,skipsLeft,level+1);
}
}
return;
}
//got a full package!
IntervalSet s;
while(!use.empty()){
// assert(cout << " -> add "<<use.front()<< " hash: "<<
// wordToString(Window(use.front(),Hash::hashpat).hash(),debugbits) << endl);
s.add(use.front(),patLength);
use.pop_front();
}
bool revZero=false;
int firstReal=0;
while(isZero(s.spaces[firstReal])){
firstReal++;
assert(firstReal<seq_count);
}
if(s.spaces[firstReal].start<0){ //firstReal is forced to be fwd only to prevent double matches
// cout << "Inverting "<<s<<" into ";
s.invert();
// cout << s<<endl;
revZero=true;
}
// cout << "Matched: "<<s << endl;
if(opt.skip1to1){
vector<UsedInt>::iterator i(s.spaces.begin());
while(!(*i).start){
++i;
assert(i!=s.spaces.end());
}
SeqPos ref=(*i).start;
for(i++;i!=s.spaces.end();i++)
if((*i).start && (*i).start!=ref)
goto HAS_OTHERS;
//finished without finding a non-self reference
return; //abort
HAS_OTHERS:; //safe ^^
}
//s ready!
// cout << "inserting.."<<endl;
anchors->insert(s); //check alreadyExists/merge/add whatever. do what you need to do
}
void generateCollisionHistogram(map<size_t,size_t> &collisionSizeHistogram,map<size_t,size_t> &seedHistogram){
ticker.reset(hash_size);
for(word idx=0;idx<hash_size;idx++,ticker.tick()){
if(mfh->emptyAt(idx)){
collisionSizeHistogram[0]++;
continue;
}else{
list<LocList> fulllist;
mfh->getMatchingSets(idx,fulllist);
collisionSizeHistogram[fulllist.size()]++;
if(opt.hashOnly){//we're collecting stats inplace of normal extract func
totalKeysUsed++;
totalSeedsSeen+=fulllist.size();
}
for(list<LocList>::iterator li=fulllist.begin();li!=fulllist.end();++li){
size_t freq=0;
for(LocList::iterator si=li->begin();si!=li->end();++si)
freq+=si->size();
seedHistogram[freq]++;
}
}
}
ticker.done();
}
string platformInfo(){
char buf[1024];
sprintf(buf,"Platform information:\nWordsize: %u bits\n\
sizeof(word): %u bytes\n\
%s\n\
",WORDSIZE,(unsigned)sizeof(word),
sysinfo.toString().c_str());
return string(buf);
}
string program_version(){
list<string> features;
#ifndef NDEBUG
features.push_back("DEBUG");
#endif
#ifdef MURASAKI_MPI
features.push_back("MPI");
#endif
#ifdef LARGESEQ_SUPPORT
features.push_back("LARGESEQ");
#endif
#ifdef USE_SHM_MMAP
features.push_back("MMAP");
#endif
#ifdef USE_SHM_SYSV
features.push_back("SYSV");
#endif
#ifdef USE_LIBCRYPTOPP
features.push_back("CRYPTOPP");
#endif
#ifdef SVNREVISION
features.push_back("SVN=" QUOTEME(SVNREVISION));
#endif
#ifdef HGREVISION
features.push_back("HG=" QUOTEME(HGREVISION));
#endif
string featurestring;
if(!features.empty())
featurestring=string(" (")+ (joinStrings(features,string(", "))) + string(")");
return "Murasaki version "+version_string+featurestring+"\n";
}
#ifdef __FreeBSD__
int getsysctl(char* name){
int mib[4];
size_t len = 4;
int size;
sysctlnametomib(name, mib, &len);
if (sysctl(mib, 4, &size, &len, NULL, 0) != -1)
return size;
return 0;
}
#endif
SystemInfo::SystemInfo()
: wordsize(WORDSIZE),
totalMemory(0),freeMemory(0),swapTotal(0),
unit(1024)
{
//platform specific mojo.
// for Linux:
#ifdef __linux__
using namespace boost;
ifstream meminfo("/proc/meminfo");
const boost::regex memline("(\\w+):\\s+(\\d+)\\s(\\w+)");
boost::smatch results;
string line;
while(getline(meminfo,line)){
if(regex_search(line,results,memline)){
if(results[1]=="MemTotal")
totalMemory=lexical_cast<long>(results[2]);
else if(results[1]=="MemFree")
freeMemory+=lexical_cast<long>(results[2]);
else if(results[1]=="Buffers")
freeMemory+=lexical_cast<long>(results[2]);
else if(results[1]=="Cached")
freeMemory+=lexical_cast<long>(results[2]);
else if(results[1]=="SwapTotal")
swapTotal=lexical_cast<long>(results[2]);
}
}
if(totalMemory>swapTotal) //good clue that memTotal is comprised of physical+swap, but sadly we don't have any other clues! =(
totalMemory-=swapTotal; //don't count swap. we only want physical memory in total (a bit of a lie, I know)
#endif
// for FreeBSD
#ifdef __FreeBSD__
int pagesize = getpagesize()/unit;
unsigned int pa, pi, pw, pc, pf;
pa = getsysctl("vm.stats.vm.v_active_count");
pi = getsysctl("vm.stats.vm.v_inactive_count");
pw = getsysctl("vm.stats.vm.v_wire_count");
pc = getsysctl("vm.stats.vm.v_cache_count");
pf = getsysctl("vm.stats.vm.v_free_count");
totalMemory = (pa + pi + pw + pc + pf) * pagesize;
freeMemory = (pc + pf) * pagesize;
#endif
// for MacOS X
#ifdef __APPLE__
vm_statistics_data_t page_info;
host_basic_info maxmem_info;
vm_size_t pagesize;
mach_msg_type_number_t count;
kern_return_t kret;
unsigned int pf;
pagesize = 0;
kret = host_page_size (mach_host_self(), &pagesize);
count = HOST_VM_INFO_COUNT;
kret = host_statistics (mach_host_self(), HOST_VM_INFO,
(host_info_t)&page_info, &count);
if (kret == KERN_SUCCESS){
pf = page_info.free_count*pagesize;
freeMemory = pf / unit;
}
count = HOST_BASIC_INFO_COUNT;
kret = host_info (mach_host_self(), HOST_BASIC_INFO, (host_info_t)&maxmem_info, &count);
if (kret == KERN_SUCCESS){
totalMemory = maxmem_info.max_mem / unit;
}
#endif
// for Windoze
#ifdef __MINGW32__
MEMORYSTATUSEX msex = { sizeof(MEMORYSTATUSEX) };
GlobalMemoryStatusEx( &msex );
freeMemory = (unsigned long)(msex.ullAvailPhys/unit);
totalMemory = (unsigned long)(msex.ullTotalPhys/unit);
#endif
}
string SystemInfo::toString() const{
char buf[1024];
sprintf(buf,"Total Memory: %s\n\
Available Memory: %s (%.2f%%)\n",
humanMemory(totalMemory*unit).c_str(),
humanMemory(freeMemory*unit).c_str(),
((double)freeMemory/(double)totalMemory*100.0));
return string(buf);
}
ostream& operator<<(ostream& of,const SystemInfo& a){
return of << a.toString();
}
ostream& outputRegions(ostream &of){
for(unsigned i=0;i<seqs.size();i++){
BitSequence *a=seqs[i]->fwd;
start: of << "Seq "<<i<<" "<< (seqs[i]->name)<<" strand "<<(a==seqs[i]->fwd ? "fwd":"rev")<<endl;
for(unsigned j=0;j<a->matchRegions.size();j++)
of << " Region from: "<<a->matchRegions[j].first
<<" to "<<a->matchRegions[j].second<<endl;
if(a==seqs[i]->fwd){
a=seqs[i]->rev;
goto start;
}
}
return of;
}
void hashStatusCheck(int tick,SeqPos pos){
#ifdef NDEBUG
return; //this function is really slow actually. rely on tee instead
#endif
ofstream of(opt.hashStatus_record.c_str());
of << "Done "<<tick<<"%"<<" ("<<pos<<")"<<endl;
of << "Anchors: "<<anchors->count()<<endl;
// of << SystemInfo();
}
//for calling from gdb
void verboseOn(){
verbose=1;
}
void verboseOff(){
verbose=0;
}
bool convertPattern(string &pat){
using namespace boost;
const regex patternRe("\\W?(\\d+)\\D(\\d+)\\W?");
smatch results;
if(!regex_match(pat,results,patternRe)){
if(!regex_match(pat,results,regex("[01]+")))
throw MurasakiException("Invalid pattern: "+pat);
return false;
}
//make a random pattern
int weight=lexical_cast<int>(results[1]),length=lexical_cast<int>(results[2]);
if(weight>length)
throw MurasakiException("Pattern weight must be less than or equal to pattern length");
if(weight<1)
throw MurasakiException("Can't use patterns with weight <1");
switch(length){//degenerate cases
case 2:pat="11";return true;
case 1:pat="1";return true;
}
string randomStr;
randomStr.reserve(length-2);
for(int i=0;i<length-2;i++)
randomStr+=(i<weight-2 ? "1":"0");
random_shuffle(randomStr.begin(),randomStr.end());
pat="1"+randomStr+"1";
return true;
}
MurasakiRuntime::~MurasakiRuntime(){
cleanup();
}
void MurasakiRuntime::success(){
//yay! successful run. cleanup any lose boring/annoying files
using namespace boost::filesystem;
if(!opt.leaveRecords){
if(exists(opt.status_record))
remove(opt.status_record);
#ifdef MURASAKI_MPI
if(mpi_capable){
if(stdoe && exists(stdoename) && !opt.mpi_keepstdoe)
remove(stdoename);
}
#endif
}
}
void MurasakiRuntime::cleanup(int disaster){
if(cleaned)
return;
cleaned=true;
if(anchorProgress_fh){
cerr << "Cleaning up file handles..."<<endl;
if(anchorProgress_fh)
delete anchorProgress_fh;
}
if(opt.use_shm_sysv && !seqs.empty()){
cerr << "Dettaching sysv IPC shared memory regions."<<endl;
for(vector<Sequence*>::iterator i=seqs.begin();i!=seqs.end();i++)
delete *i;
seqs.clear();
}
#ifdef MURASAKI_MPI
if(mpi_capable){
cerr << "Terminating MPI"<<endl;
close(stdoe);
// writeOut(opt.status_record,"MPI client mode: terminated.\n",true);
if(disaster)
MPI_Abort(MPI_COMM_WORLD,disaster);
else
MPI_Finalize();
}
#endif
}
|