void sjdbInsertJunctions(Parameters * P, Parameters * P1, Genome & genome, SjdbClass & sjdbLoci) { time_t rawtime; if (P->sjdbN>0 && sjdbLoci.chr.size()==0) {//load from the saved genome, only if the loading did not happen already (if sjdb insertion happens at the 1st pass, sjdbLoci will be populated ifstream & sjdbStreamIn = ifstrOpen(P->genomeDir+"/sjdbList.out.tab", ERROR_OUT, "SOLUTION: re-generate the genome in genomeDir=" + P->genomeDir, P); sjdbLoadFromStream(sjdbStreamIn, sjdbLoci); sjdbLoci.priority.resize(sjdbLoci.chr.size(),30); time ( &rawtime ); P->inOut->logMain << timeMonthDayTime(rawtime) << " Loaded database junctions from the generated genome " << P->genomeDir+"/sjdbList.out.tab" <<": "<<sjdbLoci.chr.size()<<" total junctions\n\n"; }; if (P->twoPass.pass2) {//load 1st pass new junctions //sjdbLoci already contains the junctions from before 1st pass ifstream sjdbStreamIn ( P->twoPass.pass1sjFile.c_str() ); if (sjdbStreamIn.fail()) { ostringstream errOut; errOut << "FATAL INPUT error, could not open input file with junctions from the 1st pass="******"\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; sjdbLoadFromStream(sjdbStreamIn, sjdbLoci); sjdbLoci.priority.resize(sjdbLoci.chr.size(),0); time ( &rawtime ); P->inOut->logMain << timeMonthDayTime(rawtime) << " Loaded database junctions from the 1st pass file: " << P->twoPass.pass1sjFile <<": "<<sjdbLoci.chr.size()<<" total junctions\n\n"; } else {//loading junctions from GTF or tab or from the saved genome is only allowed at the 1st pass //at the 2nd pass these are already in the sjdbLoci if (P->sjdbFileChrStartEnd.at(0)!="-") {//load from junction files sjdbLoadFromFiles(P,sjdbLoci); sjdbLoci.priority.resize(sjdbLoci.chr.size(),10); time ( &rawtime ); P->inOut->logMain << timeMonthDayTime(rawtime) << " Loaded database junctions from the sjdbFileChrStartEnd file(s), " << sjdbLoci.chr.size()<<" total junctions\n\n"; }; if (P->sjdbGTFfile!="-") {//load from GTF loadGTF(sjdbLoci, P, P->sjdbInsert.outDir); sjdbLoci.priority.resize(sjdbLoci.chr.size(),20); time ( &rawtime ); P->inOut->logMain << timeMonthDayTime(rawtime) << " Loaded database junctions from the GTF file: " << P->sjdbGTFfile<<": "<<sjdbLoci.chr.size()<<" total junctions\n\n"; }; }; char *Gsj=new char [2*P->sjdbLength*sjdbLoci.chr.size()+1];//array to store junction sequences, will be filled in sjdbPrepare sjdbPrepare (sjdbLoci, P, P->chrStart[P->nChrReal], P->sjdbInsert.outDir, genome.G, Gsj);//P->nGenome - change when replacing junctions time ( &rawtime ); P->inOut->logMain << timeMonthDayTime(rawtime) << " Finished preparing junctions" <<endl; if (P->sjdbN>P->limitSjdbInsertNsj) { ostringstream errOut; errOut << "Fatal LIMIT error: the number of junctions to be inserted on the fly ="<<P->sjdbN<<" is larger than the limitSjdbInsertNsj="<<P->limitSjdbInsertNsj<<"\n"; errOut << "Fatal LIMIT error: the number of junctions to be inserted on the fly ="<<P->sjdbN<<" is larger than the limitSjdbInsertNsj="<<P->limitSjdbInsertNsj<<"\n"; errOut << "SOLUTION: re-run with at least --limitSjdbInsertNsj "<<P->sjdbN<<"\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; //insert junctions into the genome and SA and SAi sjdbBuildIndex (P, P1, Gsj, genome.G, genome.SA, (P->twoPass.pass2 ? genome.SApass2 : genome.SApass1), genome.SAi); delete [] Gsj; //junction sequences have been added to G time ( &rawtime ); P->inOut->logMain << timeMonthDayTime(rawtime) << " ..... finished inserting junctions into genome" <<endl; if (P->sjdbInsert.save=="All") {//save and copy all genome files into sjdbInsert.outDir, except those created above if (P->genomeDir != P->sjdbInsert.outDir) { copyFile(P->genomeDir+"/chrName.txt", P->sjdbInsert.outDir+"/chrName.txt"); copyFile(P->genomeDir+"/chrStart.txt", P->sjdbInsert.outDir+"/chrStart.txt"); copyFile(P->genomeDir+"/chrNameLength.txt", P->sjdbInsert.outDir+"/chrNameLength.txt"); copyFile(P->genomeDir+"/chrLength.txt", P->sjdbInsert.outDir+"/chrLength.txt"); }; genomeParametersWrite(P->sjdbInsert.outDir+("/genomeParameters.txt"), P, ERROR_OUT); ofstream & genomeOut = ofstrOpen(P->sjdbInsert.outDir+"/Genome",ERROR_OUT, P); fstreamWriteBig(genomeOut,genome.G,P->nGenome,P->sjdbInsert.outDir+"/Genome",ERROR_OUT,P); genomeOut.close(); ofstream & saOut = ofstrOpen(P->sjdbInsert.outDir+"/SA",ERROR_OUT, P); fstreamWriteBig(saOut,(char*) genome.SA.charArray, (streamsize) genome.SA.lengthByte, P->sjdbInsert.outDir+"/SA",ERROR_OUT,P); saOut.close(); ofstream & saIndexOut = ofstrOpen(P->sjdbInsert.outDir+"/SAindex",ERROR_OUT, P); fstreamWriteBig(saIndexOut, (char*) &P->genomeSAindexNbases, sizeof(P->genomeSAindexNbases),P->sjdbInsert.outDir+"/SAindex",ERROR_OUT,P); fstreamWriteBig(saIndexOut, (char*) P->genomeSAindexStart, sizeof(P->genomeSAindexStart[0])*(P->genomeSAindexNbases+1),P->sjdbInsert.outDir+"/SAindex",ERROR_OUT,P); fstreamWriteBig(saIndexOut, genome.SAi.charArray, genome.SAi.lengthByte,P->sjdbInsert.outDir+"/SAindex",ERROR_OUT,P); saIndexOut.close(); }; //re-calculate genome-related parameters P->winBinN = P->nGenome/(1LLU << P->winBinNbits)+1; };
void genomeGenerate(Parameters *P) { //check parameters if (P->sjdbOverhang<=0 && (P->sjdbFileChrStartEnd.at(0)!="-" || P->sjdbGTFfile!="-")) { ostringstream errOut; errOut << "EXITING because of FATAL INPUT PARAMETER ERROR: for generating genome with annotations (--sjdbFileChrStartEnd or --sjdbGTFfile options)\n"; errOut << "you need to specify >0 --sjdbOverhang\n"; errOut << "SOLUTION: re-run genome generation specifying non-zero --sjdbOverhang, which ideally should be equal to OneMateLength-1, or could be chosen generically as ~100\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); } if (P->sjdbFileChrStartEnd.at(0)=="-" && P->sjdbGTFfile=="-") { if (P->parArray.at(P->sjdbOverhang_par)->inputLevel>0 && P->sjdbOverhang>0) { ostringstream errOut; errOut << "EXITING because of FATAL INPUT PARAMETER ERROR: when generating genome without annotations (--sjdbFileChrStartEnd or --sjdbGTFfile options)\n"; errOut << "do not specify >0 --sjdbOverhang\n"; errOut << "SOLUTION: re-run genome generation without --sjdbOverhang option\n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; P->sjdbOverhang=0; }; //time time_t rawTime; string timeString; time(&rawTime); P->inOut->logMain << timeMonthDayTime(rawTime) <<" ... Starting to generate Genome files\n" <<flush; *P->inOut->logStdOut << timeMonthDayTime(rawTime) <<" ... Starting to generate Genome files\n" <<flush; //define some parameters from input parameters P->genomeChrBinNbases=1LLU << P->genomeChrBinNbits; //write genome parameters file genomeParametersWrite(P->genomeDir+("/genomeParameters.txt"), P, "ERROR_00102"); char *G=NULL, *G1=NULL; uint nGenomeReal=genomeScanFastaFiles(P,G,false);//first scan the fasta file to find all the sizes P->chrBinFill(); uint L=10000;//maximum length of genome suffix uint nG1alloc=(nGenomeReal + L)*2; G1=new char[nG1alloc]; G=G1+L; memset(G1,GENOME_spacingChar,nG1alloc);//initialize to K-1 all bytes genomeScanFastaFiles(P,G,true); //load the genome sequence uint N = nGenomeReal; P->nGenome=N; uint N2 = N*2; ofstream chrN,chrS,chrL,chrNL; ofstrOpen(P->genomeDir+"/chrName.txt","ERROR_00103", P, chrN); ofstrOpen(P->genomeDir+"/chrStart.txt","ERROR_00103", P, chrS); ofstrOpen(P->genomeDir+"/chrLength.txt","ERROR_00103", P, chrL); ofstrOpen(P->genomeDir+"/chrNameLength.txt","ERROR_00103", P, chrNL); for (uint ii=0;ii<P->nChrReal;ii++) {//output names, starts, lengths chrN<<P->chrName[ii]<<"\n"; chrS<<P->chrStart[ii]<<"\n"; chrL<<P->chrLength.at(ii)<<"\n"; chrNL<<P->chrName[ii]<<"\t"<<P->chrLength.at(ii)<<"\n"; }; chrS<<P->chrStart[P->nChrReal]<<"\n";//size of the genome chrN.close();chrL.close();chrS.close(); chrNL.close(); if (P->limitGenomeGenerateRAM < (nG1alloc+nG1alloc/3)) {//allocate nG1alloc/3 for SA generation ostringstream errOut; errOut <<"EXITING because of FATAL PARAMETER ERROR: limitGenomeGenerateRAM="<< (P->limitGenomeGenerateRAM) <<"is too small for your genome\n"; errOut <<"SOLUTION: please specify limitGenomeGenerateRAM not less than"<< nG1alloc+nG1alloc/3 <<" and make that much RAM available \n"; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; //preparing to generate SA for (uint ii=0;ii<N;ii++) {//- strand G[N2-1-ii]=G[ii]<4 ? 3-G[ii] : G[ii]; }; P->nSA=0; for (uint ii=0;ii<N2;ii+=P->genomeSAsparseD) { if (G[ii]<4) { P->nSA++; }; }; P->GstrandBit = (uint) floor(log(N)/log(2))+1; if (P->GstrandBit<32) P->GstrandBit=32; //TODO: use simple access function for SA P->GstrandMask = ~(1LLU<<P->GstrandBit); PackedArray SA1;//SA without sjdb SA1.defineBits(P->GstrandBit+1,P->nSA); PackedArray SA2;//SA with sjdb, reserve more space if (P->sjdbInsert.yes) {//reserve space for junction insertion SA2.defineBits(P->GstrandBit+1,P->nSA+2*P->limitSjdbInsertNsj*P->sjdbLength);//TODO: this allocation is wasteful, get a better estimate of the number of junctions } else {//same as SA1 SA2.defineBits(P->GstrandBit+1,P->nSA); }; P->nSAbyte=SA2.lengthByte; P->inOut->logMain << "Number of SA indices: "<< P->nSA << "\n"<<flush; //sort SA time ( &rawTime ); P->inOut->logMain << timeMonthDayTime(rawTime) <<" ... starting to sort Suffix Array. This may take a long time...\n" <<flush; *P->inOut->logStdOut << timeMonthDayTime(rawTime) <<" ... starting to sort Suffix Array. This may take a long time...\n" <<flush; // if (false) {//sort SA chunks for (uint ii=0;ii<N;ii++) {//re-fill the array backwards for sorting swap(G[N2-1-ii],G[ii]); }; globalG=G; globalL=L/sizeof(uint); //count the number of indices with 4nt prefix uint indPrefN=1LLU << 16; uint* indPrefCount = new uint [indPrefN]; memset(indPrefCount,0,indPrefN*sizeof(indPrefCount[0])); P->nSA=0; for (uint ii=0;ii<N2;ii+=P->genomeSAsparseD) { if (G[ii]<4) { uint p1=(G[ii]<<12) + (G[ii-1]<<8) + (G[ii-2]<<4) + G[ii-3]; indPrefCount[p1]++; P->nSA++; }; }; uint saChunkSize=(P->limitGenomeGenerateRAM-nG1alloc)/8/P->runThreadN; //number of SA indexes per chunk saChunkSize=saChunkSize*6/10; //allow extra space for qsort //uint saChunkN=((P->nSA/saChunkSize+1)/P->runThreadN+1)*P->runThreadN;//ensure saChunkN is divisible by P->runThreadN //saChunkSize=P->nSA/saChunkN+100000;//final chunk size if (P->runThreadN>1) saChunkSize=min(saChunkSize,P->nSA/(P->runThreadN-1)); uint saChunkN=P->nSA/saChunkSize;//estimate uint* indPrefStart = new uint [saChunkN*2]; //start and stop, *2 just in case uint* indPrefChunkCount = new uint [saChunkN*2]; indPrefStart[0]=0; saChunkN=0;//start counting chunks uint chunkSize1=indPrefCount[0]; for (uint ii=1; ii<indPrefN; ii++) { chunkSize1 += indPrefCount[ii]; if (chunkSize1 > saChunkSize) { saChunkN++; indPrefStart[saChunkN]=ii; indPrefChunkCount[saChunkN-1]=chunkSize1-indPrefCount[ii]; chunkSize1=indPrefCount[ii]; }; }; saChunkN++; indPrefStart[saChunkN]=indPrefN+1; indPrefChunkCount[saChunkN-1]=chunkSize1; P->inOut->logMain << "Number of chunks: " << saChunkN <<"; chunks size limit: " << saChunkSize*8 <<" bytes\n" <<flush; time ( &rawTime ); P->inOut->logMain << timeMonthDayTime(rawTime) <<" ... sorting Suffix Array chunks and saving them to disk...\n" <<flush; *P->inOut->logStdOut << timeMonthDayTime(rawTime) <<" ... sorting Suffix Array chunks and saving them to disk...\n" <<flush; #pragma omp parallel for num_threads(P->runThreadN) ordered schedule(dynamic,1) for (int iChunk=0; iChunk < (int) saChunkN; iChunk++) {//start the chunk cycle: sort each chunk with qsort and write to a file uint* saChunk=new uint [indPrefChunkCount[iChunk]];//allocate local array for each chunk for (uint ii=0,jj=0;ii<N2;ii+=P->genomeSAsparseD) {//fill the chunk with SA indices if (G[ii]<4) { uint p1=(G[ii]<<12) + (G[ii-1]<<8) + (G[ii-2]<<4) + G[ii-3]; if (p1>=indPrefStart[iChunk] && p1<indPrefStart[iChunk+1]) { saChunk[jj]=ii; jj++; }; //TODO: if (jj==indPrefChunkCount[iChunk]) break; }; }; //sort the chunk qsort(saChunk,indPrefChunkCount[iChunk],sizeof(saChunk[0]),funCompareSuffixes); for (uint ii=0;ii<indPrefChunkCount[iChunk];ii++) { saChunk[ii]=N2-1-saChunk[ii]; }; //write files ofstream saChunkFile; string chunkFileName=P->genomeDir+"/SA_"+to_string( (uint) iChunk); ofstrOpen(chunkFileName,"ERROR_00105", P, saChunkFile); fstreamWriteBig(saChunkFile, (char*) saChunk, sizeof(saChunk[0])*indPrefChunkCount[iChunk],chunkFileName,"ERROR_00121",P); saChunkFile.close(); delete [] saChunk; saChunk=NULL; }; time ( &rawTime ); P->inOut->logMain << timeMonthDayTime(rawTime) <<" ... loading chunks from disk, packing SA...\n" <<flush; *P->inOut->logStdOut << timeMonthDayTime(rawTime) <<" ... loading chunks from disk, packing SA...\n" <<flush; //read chunks and pack into full SA1 SA2.allocateArray(); SA1.pointArray(SA2.charArray + SA2.lengthByte-SA1.lengthByte); //SA1 is shifted to have space for junction insertion uint N2bit= 1LLU << P->GstrandBit; uint packedInd=0; #define SA_CHUNK_BLOCK_SIZE 10000000 uint* saIn=new uint[SA_CHUNK_BLOCK_SIZE]; //TODO make adjustable #ifdef genenomeGenerate_SA_textOutput ofstream SAtxtStream ((P->genomeDir + "/SAtxt").c_str()); #endif for (uint iChunk=0;iChunk<saChunkN;iChunk++) {//load files one by one and convert to packed ostringstream saChunkFileNameStream(""); saChunkFileNameStream<< P->genomeDir << "/SA_" << iChunk; ifstream saChunkFile(saChunkFileNameStream.str().c_str()); while (! saChunkFile.eof()) {//read blocks from each file uint chunkBytesN=fstreamReadBig(saChunkFile,(char*) saIn,SA_CHUNK_BLOCK_SIZE*sizeof(saIn[0])); for (uint ii=0;ii<chunkBytesN/sizeof(saIn[0]);ii++) { SA1.writePacked( packedInd+ii, (saIn[ii]<N) ? saIn[ii] : ( (saIn[ii]-N) | N2bit ) ); #ifdef genenomeGenerate_SA_textOutput SAtxtStream << saIn[ii] << "\n"; #endif }; packedInd += chunkBytesN/sizeof(saIn[0]); }; saChunkFile.close(); remove(saChunkFileNameStream.str().c_str());//remove the chunk file }; #ifdef genenomeGenerate_SA_textOutput SAtxtStream.close(); #endif delete [] saIn; if (packedInd != P->nSA ) {// ostringstream errOut; errOut << "EXITING because of FATAL problem while generating the suffix array\n"; errOut << "The number of indices read from chunks = "<<packedInd<<" is not equal to expected nSA="<<P->nSA<<"\n"; errOut << "SOLUTION: try to re-run suffix array generation, if it still does not work, report this problem to the author\n"<<flush; exitWithError(errOut.str(),std::cerr, P->inOut->logMain, EXIT_CODE_INPUT_FILES, *P); }; //DONE with suffix array generation for (uint ii=0;ii<N;ii++) {//return to normal order for future use swap(G[N2-1-ii],G[ii]); }; delete [] indPrefCount; delete [] indPrefStart; delete [] indPrefChunkCount; }; time ( &rawTime ); timeString=asctime(localtime ( &rawTime )); timeString.erase(timeString.end()-1,timeString.end()); P->inOut->logMain << timeMonthDayTime(rawTime) <<" ... Finished generating suffix array\n" <<flush; *P->inOut->logStdOut << timeMonthDayTime(rawTime) <<" ... Finished generating suffix array\n" <<flush; //////////////////////////////////////// // SA index // // PackedArray SAold; // // if (true) // {//testing: load SA from disk // //read chunks and pack into full SA1 // // ifstream oldSAin("./DirTrue/SA"); // oldSAin.seekg (0, ios::end); // P->nSAbyte=(uint) oldSAin.tellg(); // oldSAin.clear(); // oldSAin.seekg (0, ios::beg); // // P->nSA=(P->nSAbyte*8)/(P->GstrandBit+1); // SAold.defineBits(P->GstrandBit+1,P->nSA); // SAold.allocateArray(); // // oldSAin.read(SAold.charArray,SAold.lengthByte); // oldSAin.close(); // // SA1=SAold; // SA2=SAold; // }; PackedArray SAip; genomeSAindex(G,SA1,P,SAip); if (P->sjdbFileChrStartEnd.at(0)!="-" || P->sjdbGTFfile!="-") {//insert junctions SjdbClass sjdbLoci; Genome mainGenome(P); mainGenome.G=G; mainGenome.SA=SA1; mainGenome.SApass1=SA2; mainGenome.SAi=SAip; P->sjdbInsert.outDir=P->genomeDir; P->sjdbN=0;//no junctions are loaded yet P->twoPass.pass2=false; Parameters *P1=new Parameters; *P1=*P; sjdbInsertJunctions(P, P1, mainGenome, sjdbLoci); //write an extra 0 at the end of the array, filling the last bytes that otherwise are not accessible, but will be written to disk //this is - to avoid valgrind complaints. Note that SA2 is allocated with plenty of space to spare. SA2.writePacked(P->nSA,0); }; //write genome to disk time ( &rawTime ); P->inOut->logMain << timeMonthDayTime(rawTime) <<" ... writing Genome to disk ...\n" <<flush; *P->inOut->logStdOut << timeMonthDayTime(rawTime) <<" ... writing Genome to disk ...\n" <<flush; ofstream genomeOut; ofstrOpen(P->genomeDir+"/Genome","ERROR_00104", P, genomeOut); fstreamWriteBig(genomeOut,G,P->nGenome,P->genomeDir+"/Genome","ERROR_00120",P); genomeOut.close(); //write SA time ( &rawTime ); P->inOut->logMain << "SA size in bytes: "<< P->nSAbyte << "\n"<<flush; P->inOut->logMain << timeMonthDayTime(rawTime) <<" ... writing Suffix Array to disk ...\n" <<flush; *P->inOut->logStdOut << timeMonthDayTime(rawTime) <<" ... writing Suffix Array to disk ...\n" <<flush; ofstream SAout; ofstrOpen(P->genomeDir+"/SA","ERROR_00106", P, SAout); fstreamWriteBig(SAout,(char*) SA2.charArray, (streamsize) P->nSAbyte,P->genomeDir+"/SA","ERROR_00122",P); SAout.close(); //write SAi time(&rawTime); P->inOut->logMain << timeMonthDayTime(rawTime) <<" ... writing SAindex to disk\n" <<flush; *P->inOut->logStdOut << timeMonthDayTime(rawTime) <<" ... writing SAindex to disk\n" <<flush; //write SAi to disk ofstream SAiOut; ofstrOpen(P->genomeDir+"/SAindex","ERROR_00107", P, SAiOut); fstreamWriteBig(SAiOut, (char*) &P->genomeSAindexNbases, sizeof(P->genomeSAindexNbases),P->genomeDir+"/SAindex","ERROR_00123",P); fstreamWriteBig(SAiOut, (char*) P->genomeSAindexStart, sizeof(P->genomeSAindexStart[0])*(P->genomeSAindexNbases+1),P->genomeDir+"/SAindex","ERROR_00124",P); fstreamWriteBig(SAiOut, SAip.charArray, SAip.lengthByte,P->genomeDir+"/SAindex","ERROR_00125",P); SAiOut.close(); SA2.deallocateArray(); time(&rawTime); timeString=asctime(localtime ( &rawTime )); timeString.erase(timeString.end()-1,timeString.end()); time(&rawTime); P->inOut->logMain << timeMonthDayTime(rawTime) << " ..... Finished successfully\n" <<flush; *P->inOut->logStdOut << timeMonthDayTime(rawTime) << " ..... Finished successfully\n" <<flush; };