]> git.donarmstrong.com Git - mothur.git/blobdiff - pintail.cpp
changes while testing
[mothur.git] / pintail.cpp
index 6ccccde7f1d73154faee33a1003e13633217e0d6..b9f2434d19d4cc842bfac1dce4f6de5a0d1b742d 100644 (file)
 
 #include "pintail.h"
 #include "ignoregaps.h"
+#include "eachgapdist.h"
 
+//********************************************************************************************************************
+//sorts lowest to highest
+inline bool compareQuanMembers(quanMember left, quanMember right){
+       return (left.score < right.score);      
+} 
 //***************************************************************************************************************
 
-Pintail::Pintail(string name) {
+Pintail::Pintail(string filename, string temp, bool f, int p, string mask, string cons, string q, int win, int inc, string o) : Chimera() { 
        try {
-               fastafile = name;
+       
+               fastafile = filename; 
+               templateFileName = temp; templateSeqs = readSeqs(temp);
+               filter = f;
+               processors = p;
+               setMask(mask);
+               consfile = cons;
+               quanfile = q;
+               window = win;
+               increment = inc; 
+               outputDir = o; 
+               
+               distcalculator = new eachGapDist();
+               decalc = new DeCalculator();
+               
+               doPrep();
        }
        catch(exception& e) {
-               errorOut(e, "Pintail", "Pintail");
+               m->errorOut(e, "Pintail", "Pintail");
                exit(1);
        }
+
 }
 //***************************************************************************************************************
 
 Pintail::~Pintail() {
-       try {
-               for (int i = 0; i < querySeqs.size(); i++)              {  delete querySeqs[i];         }
-               for (int i = 0; i < templateSeqs.size(); i++)   {  delete templateSeqs[i];      }
-       }
-       catch(exception& e) {
-               errorOut(e, "Pintail", "~Pintail");
-               exit(1);
-       }
-}      
-//***************************************************************************************************************
-void Pintail::print(ostream& out) {
        try {
                
-               for (itCoef = DE.begin(); itCoef != DE.end(); itCoef++) {
-               
-                       out << itCoef->first->getName() << '\t' << itCoef->second << endl;
-                       out << "Observed\t";
-                       
-                       itObsDist = obsDistance.find(itCoef->first);
-                       for (int i = 0; i < itObsDist->second.size(); i++) {  out << itObsDist->second[i] << '\t';  }
-                       out << endl;
-                       
-                       out << "Expected\t";
-                       
-                       itExpDist = expectedDistance.find(itCoef->first);
-                       for (int i = 0; i < itExpDist->second.size(); i++) {  out << itExpDist->second[i] << '\t';  }
-                       out << endl;
-                       
-               }
-
+               delete distcalculator;
+               delete decalc; 
        }
        catch(exception& e) {
-               errorOut(e, "Pintail", "print");
+               m->errorOut(e, "Pintail", "~Pintail");
                exit(1);
        }
 }
-
 //***************************************************************************************************************
-void Pintail::getChimeras() {
+int Pintail::doPrep() {
        try {
                
-               distCalculator = new ignoreGaps();
-               
-               //read in query sequences and subject sequences
-               mothurOut("Reading sequences and template file... "); cout.flush();
-               querySeqs = readSeqs(fastafile);
-               templateSeqs = readSeqs(templateFile);
-               mothurOut("Done."); mothurOutEndLine();
-               
-               int numSeqs = querySeqs.size();
-               
-               //if window is set to default
-               if (window == 0) {  if (querySeqs[0]->getAligned().length() > 800) {  setWindow(200); }
-                                                       else{  setWindow((querySeqs[0]->getAligned().length() / 4)); }  } 
-       
-               //calculate number of iters
-               iters = (querySeqs[0]->getAligned().length() - window + 1) / increment;
-               
-               int linesPerProcess = processors / numSeqs;
-               
-               //find breakup of sequences for all times we will Parallelize
-               if (processors == 1) {   lines.push_back(new linePair(0, numSeqs));  }
-               else {
-                       //fill line pairs
-                       for (int i = 0; i < (processors-1); i++) {                      
-                               lines.push_back(new linePair((i*linesPerProcess), ((i*linesPerProcess) + linesPerProcess)));
+               mergedFilterString = "";
+               windowSizesTemplate.resize(templateSeqs.size(), window);
+               quantiles.resize(100);  //one for every percent mismatch
+               quantilesMembers.resize(100);  //one for every percent mismatch
+               
+               //if the user does not enter a mask then you want to keep all the spots in the alignment
+               if (seqMask.length() == 0)      {       decalc->setAlignmentLength(templateSeqs[0]->getAligned().length());     }
+               else                                            {       decalc->setAlignmentLength(seqMask.length());                                           }
+               
+               decalc->setMask(seqMask);
+               
+       #ifdef USE_MPI
+               //do nothing
+       #else
+               #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
+                       //find breakup of templatefile for quantiles
+                       if (processors == 1) {   templateLines.push_back(new linePair(0, templateSeqs.size()));  }
+                       else { 
+                               for (int i = 0; i < processors; i++) {
+                                       templateLines.push_back(new linePair());
+                                       templateLines[i]->start = int (sqrt(float(i)/float(processors)) * templateSeqs.size());
+                                       templateLines[i]->end = int (sqrt(float(i+1)/float(processors)) * templateSeqs.size());
+                               }
                        }
-                       //this is necessary to get remainder of processors / numSeqs so you don't miss any lines at the end
-                       int i = processors - 1;
-                       lines.push_back(new linePair((i*linesPerProcess), numSeqs));
-               }
-               
-               //map query sequences to their most similiar sequences in the template - Parallelized
-               mothurOut("Finding closest sequence in template to each sequence... "); cout.flush();
-               if (processors == 1) {   findPairs(lines[0]->start, lines[0]->end);  } 
-               else {          createProcessesPairs();         }
-               mothurOut("Done."); mothurOutEndLine();
-       //      itBest = bestfit.begin();
-       //      itBest++; itBest++;
-//cout << itBest->first->getName() << '\t' << itBest->second->getName()        << endl;        
-               //find Oqs for each sequence - the observed distance in each window - Parallelized
-               mothurOut("Calculating observed percentage differences for each sequence... "); cout.flush();
-               if (processors == 1) {   calcObserved(lines[0]->start, lines[0]->end);  } 
-               else {          createProcessesObserved();              }
-               mothurOut("Done."); mothurOutEndLine();
-               
-               //find P
-               mothurOut("Calculating expected percentage differences for each sequence... "); cout.flush();
-               vector<float> probabilityProfile = calcFreq(templateSeqs);
+               #else
+                       templateLines.push_back(new linePair(0, templateSeqs.size()));
+               #endif
+       #endif
+               
+               m->mothurOut("Getting conservation... "); cout.flush();
+               if (consfile == "") { 
+                       m->mothurOut("Calculating probability of conservation for your template sequences.  This can take a while...  I will output the frequency of the highest base in each position to a .freq file so that you can input them using the conservation parameter next time you run this command.  Providing the .freq file will improve speed.    "); cout.flush();
+                       probabilityProfile = decalc->calcFreq(templateSeqs, templateFileName); 
+                       if (m->control_pressed) {  return 0;  }
+                       m->mothurOut("Done."); m->mothurOutEndLine();
+               }else                           {   probabilityProfile = readFreq();    m->mothurOut("Done.");            }
+               m->mothurOutEndLine();
                
                //make P into Q
-               for (int i = 0; i < probabilityProfile.size(); i++)  {  probabilityProfile[i] = 1 - probabilityProfile[i];      }
-//cout << "after p into Q" << endl;            
-               //find Qav
-               averageProbability = findQav(probabilityProfile);
-//cout << "after Qav" << endl;         
-               //find Coefficient - maps a sequence to its coefficient
-               seqCoef = getCoef(averageProbability);
-//cout << "after coef" << endl;                
-               //find Eqs for each sequence - the expected distance in each window - Parallelized
-               if (processors == 1) {   calcExpected(lines[0]->start, lines[0]->end);  } 
-               else {          createProcessesExpected();              }
-               mothurOut("Done."); mothurOutEndLine();
-               
-               //find deviation - Parallelized
-               mothurOut("Finding deviation from expected... "); cout.flush();
-               if (processors == 1) {   calcDE(lines[0]->start, lines[0]->end);  } 
-               else {          createProcessesDE();            }
-               mothurOut("Done."); mothurOutEndLine();
+               for (int i = 0; i < probabilityProfile.size(); i++)  { probabilityProfile[i] = 1 - probabilityProfile[i];  }  //
                
+               bool reRead = false;
+               //create filter if needed for later
+               if (filter) {
+                                               
+                       //read in all query seqs
+                       vector<Sequence*> tempQuerySeqs = readSeqs(fastafile);
                                
-               //free memory
-               for (int i = 0; i < lines.size(); i++)                  {       delete lines[i];                }
-               delete distCalculator;  
-
-       }
-       catch(exception& e) {
-               errorOut(e, "Pintail", "getChimeras");
-               exit(1);
-       }
-}
-
-//***************************************************************************************************************
-
-vector<Sequence*> Pintail::readSeqs(string file) {
-       try {
+                       vector<Sequence*> temp;
+                       //merge query seqs and template seqs
+                       temp = templateSeqs;
+                       for (int i = 0; i < tempQuerySeqs.size(); i++) {  temp.push_back(tempQuerySeqs[i]);  }
        
-               ifstream in;
-               openInputFile(file, in);
-               vector<Sequence*> container;
-               
-               //read in seqs and store in vector
-               while(!in.eof()){
-                       Sequence* current = new Sequence(in);
-                       
-                       if (current->getAligned() == "") { current->setAligned(current->getUnaligned()); }
+                       if (seqMask != "") {
+                           reRead = true;
+                               //mask templates
+                               for (int i = 0; i < temp.size(); i++) {
+                                       if (m->control_pressed) {  
+                                               for (int i = 0; i < tempQuerySeqs.size(); i++) { delete tempQuerySeqs[i];  }
+                                               return 0; 
+                                       }
+                                       decalc->runMask(temp[i]);
+                               }
+                       }
+
+                       mergedFilterString = createFilter(temp, 0.5);
                        
-                       container.push_back(current);
+                       if (m->control_pressed) {  
+                               for (int i = 0; i < tempQuerySeqs.size(); i++) { delete tempQuerySeqs[i];  }
+                               return 0; 
+                       }
                        
-                       gobble(in);
+                       //reread template seqs
+                       for (int i = 0; i < tempQuerySeqs.size(); i++) { delete tempQuerySeqs[i];  }
                }
                
-               in.close();
-               return container;
                
-       }
-       catch(exception& e) {
-               errorOut(e, "Pintail", "readSeqs");
-               exit(1);
-       }
-}
-
-//***************************************************************************************************************
-//calculate the distances from each query sequence to all sequences in the template to find the closest sequence
-void Pintail::findPairs(int start, int end) {
-       try {
-               
-               for(int i = start; i < end; i++){
+               //quantiles are used to determine whether the de values found indicate a chimera
+               //if you have to calculate them, its time intensive because you are finding the de and deviation values for each 
+               //combination of sequences in the template
+               if (quanfile != "") {  
+                       quantiles = readQuantiles(); 
+               }else {
+                       if ((!filter) && (seqMask != "")) { //if you didn't filter but you want to mask. if you filtered then you did mask first above.
+                               reRead = true;
+                               //mask templates
+                               for (int i = 0; i < templateSeqs.size(); i++) {
+                                       if (m->control_pressed) {  return 0;  }
+                                       decalc->runMask(templateSeqs[i]);
+                               }
+                       }
+                       
+                       if (filter) { 
+                               reRead = true;
+                               for (int i = 0; i < templateSeqs.size(); i++) {
+                                       if (m->control_pressed) {  return 0;  }
+                                       runFilter(templateSeqs[i]);
+                               }
+                       }
+                       
+                       m->mothurOut("Calculating quantiles for your template.  This can take a while...  I will output the quantiles to a .quan file that you can input them using the quantiles parameter next time you run this command.  Providing the .quan file will dramatically improve speed.    "); cout.flush();
+                       if (processors == 1) { 
+                               quantilesMembers = decalc->getQuantiles(templateSeqs, windowSizesTemplate, window, probabilityProfile, increment, 0, templateSeqs.size());
+                       }else {         createProcessesQuan();          }
                
-                       float smallest = 10000.0;
-                       Sequence query = *(querySeqs[i]);
+                       if (m->control_pressed) {  return 0;  }
+                       
+                       string noOutliers, outliers;
+                       
+                       if ((!filter) && (seqMask == "")) {
+                               noOutliers = m->getRootName(m->getSimpleName(templateFileName)) + "pintail.quan";
+                       }else if ((!filter) && (seqMask != "")) { 
+                               noOutliers =m->getRootName(m->getSimpleName(templateFileName)) + "pintail.masked.quan";
+                       }else if ((filter) && (seqMask != "")) { 
+                               noOutliers = m->getRootName(m->getSimpleName(templateFileName)) + "pintail.filtered." + m->getSimpleName(m->getRootName(fastafile)) + "masked.quan";
+                       }else if ((filter) && (seqMask == "")) { 
+                               noOutliers = m->getRootName(m->getSimpleName(templateFileName)) + "pintail.filtered." + m->getSimpleName(m->getRootName(fastafile)) + "quan";
+                       }
+
+                       decalc->removeObviousOutliers(quantilesMembers, templateSeqs.size());
+                       
+                       if (m->control_pressed) {  return 0;  }
                
-                       for(int j = 0; j < templateSeqs.size(); j++){
+                       string outputString = "#" + m->getVersion() + "\n";
+                       
+                       //adjust quantiles
+                       for (int i = 0; i < quantilesMembers.size(); i++) {
+                               vector<float> temp;
                                
-                               Sequence temp = *(templateSeqs[j]);
+                               if (quantilesMembers[i].size() == 0) {
+                                       //in case this is not a distance found in your template files
+                                       for (int g = 0; g < 6; g++) {
+                                               temp.push_back(0.0);
+                                       }
+                               }else{
+                                       
+                                       sort(quantilesMembers[i].begin(), quantilesMembers[i].end());
+                                       
+                                       //save 10%
+                                       temp.push_back(quantilesMembers[i][int(quantilesMembers[i].size() * 0.10)]);
+                                       //save 25%
+                                       temp.push_back(quantilesMembers[i][int(quantilesMembers[i].size() * 0.25)]);
+                                       //save 50%
+                                       temp.push_back(quantilesMembers[i][int(quantilesMembers[i].size() * 0.5)]);
+                                       //save 75%
+                                       temp.push_back(quantilesMembers[i][int(quantilesMembers[i].size() * 0.75)]);
+                                       //save 95%
+                                       temp.push_back(quantilesMembers[i][int(quantilesMembers[i].size() * 0.95)]);
+                                       //save 99%
+                                       temp.push_back(quantilesMembers[i][int(quantilesMembers[i].size() * 0.99)]);
+                                       
+                               }
                                
-                               distCalculator->calcDist(query, temp);
-                               float dist = distCalculator->getDist();
+                               //output quan value
+                               outputString += toString(i+1) + "\t";                           
+                               for (int u = 0; u < temp.size(); u++) {   outputString += toString(temp[u]) + "\t"; }
+                               outputString += "\n";
                                
-                               if (dist < smallest) { 
+                               quantiles[i] = temp;
                                
-                                       bestfit[querySeqs[i]] = templateSeqs[j];
-                                       smallest = dist;
-                               }
                        }
+                       
+                       printQuanFile(noOutliers, outputString);
+                       
+                       //free memory
+                       quantilesMembers.clear();
+                       
+                       m->mothurOut("Done."); m->mothurOutEndLine();
+               }
+               
+               if (reRead) {
+                       for (int i = 0; i < templateSeqs.size(); i++) { delete templateSeqs[i];  }
+                       templateSeqs.clear();
+                       templateSeqs = readSeqs(templateFileName);
                }
+
+               
+               //free memory
+               for (int i = 0; i < templateLines.size(); i++) { delete templateLines[i];  }
+               
+               return 0;
                
        }
        catch(exception& e) {
-               errorOut(e, "Pintail", "findPairs");
+               m->errorOut(e, "Pintail", "doPrep");
                exit(1);
        }
 }
 //***************************************************************************************************************
-void Pintail::calcObserved(int start, int end) {
+Sequence Pintail::print(ostream& out, ostream& outAcc) {
        try {
-
-               for(int i = start; i < end; i++){
                
-                       itBest = bestfit.find(querySeqs[i]);
-                       Sequence* query;
-                       Sequence* subject;
-                       
-                       if (itBest != bestfit.end()) {
-                               query = itBest->first;
-                               subject = itBest->second;
-                       }else{ mothurOut("Error in calcObserved"); mothurOutEndLine(); }
-                       
-                       vector<Sequence*> queryFragment;
-                       vector<Sequence*> subjectFragment;
-                       
-                       int startpoint = 0; 
-                       for (int m = 0; m < iters; m++) {
-                               string seqFrag = query->getAligned().substr(startpoint, window);
-                               Sequence* temp = new Sequence(query->getName(), seqFrag);
-                               queryFragment.push_back(temp);
-                               
-                               string seqFragsub = subject->getAligned().substr(startpoint, window);
-                               Sequence* tempsub = new Sequence(subject->getName(), seqFragsub);
-                               subjectFragment.push_back(tempsub);
-                               
-                               startpoint += increment;
-                       }
-                       
-                       
-                       for(int j = 0; j < iters; j++){
-                       
-                               distCalculator->calcDist(*(queryFragment[j]), *(subjectFragment[j]));
-                               float dist = distCalculator->getDist();
-                               
-                               //convert to similiarity
-                               //dist = 1 - dist;
-                               
-                               //save oi
-                               obsDistance[query].push_back(dist);
+               int index = ceil(deviation);
+               
+               //is your DE value higher than the 95%
+               string chimera;
+               if (index != 0) {  //if index is 0 then its an exact match to a template seq
+                       if (quantiles[index][4] == 0.0) {
+                               chimera = "Your template does not include sequences that provide quantile values at distance " + toString(index);
+                       }else {
+                               if (DE > quantiles[index][4])           {       chimera = "Yes";        }
+                               else                                                            {       chimera = "No";         }
                        }
+               }else{ chimera = "No";          }
                
-                       //free memory
-                       for (int i = 0; i < queryFragment.size(); i++)  {  delete queryFragment[i];             }
-                       for (int i = 0; i < subjectFragment.size(); i++) {  delete subjectFragment[i];  }
+               out << querySeq->getName() << '\t' << "div: " << deviation << "\tstDev: " << DE << "\tchimera flag: " << chimera << endl;
+               if (chimera == "Yes") {
+                       m->mothurOut(querySeq->getName() + "\tdiv: " + toString(deviation) + "\tstDev: " + toString(DE) + "\tchimera flag: " + chimera); m->mothurOutEndLine();
+                       outAcc << querySeq->getName() << endl;
                }
+               out << "Observed\t";
+               
+               for (int j = 0; j < obsDistance.size(); j++) {  out << obsDistance[j] << '\t';  }
+               out << endl;
+               
+               out << "Expected\t";
+               
+               for (int m = 0; m < expectedDistance.size(); m++) {  out << expectedDistance[m] << '\t';  }
+               out << endl;
+               
+               return *querySeq;
                
        }
        catch(exception& e) {
-               errorOut(e, "Pintail", "calcObserved");
+               m->errorOut(e, "Pintail", "print");
                exit(1);
        }
 }
-
+#ifdef USE_MPI
 //***************************************************************************************************************
-void Pintail::calcExpected(int start, int end) {
+Sequence Pintail::print(MPI_File& out, MPI_File& outAcc) {
        try {
                
-       
-               //for each sequence
-               for(int i = start; i < end; i++){
-                       
-                       itCoef = seqCoef.find(querySeqs[i]);
-                       float coef = itCoef->second;
-                       
-                       //for each window
-                       vector<float> queryExpected;
-                       for (int m = 0; m < iters; m++) {               
-                               float expected = averageProbability[m] * coef;
-                               queryExpected.push_back(expected);              
+               string outputString = "";
+               int index = ceil(deviation);
+               
+               //is your DE value higher than the 95%
+               string chimera;
+               if (index != 0) {  //if index is 0 then its an exact match to a template seq
+                       if (quantiles[index][4] == 0.0) {
+                               chimera = "Your template does not include sequences that provide quantile values at distance " + toString(index);
+                       }else {
+                               if (DE > quantiles[index][4])           {       chimera = "Yes";        }
+                               else                                                            {       chimera = "No";         }
                        }
-                       
-                       expectedDistance[querySeqs[i]] = queryExpected;
-                       
+               }else{ chimera = "No";          }
+
+               outputString += querySeq->getName() + "\tdiv: " + toString(deviation) + "\tstDev: " + toString(DE) + "\tchimera flag: " + chimera + "\n";
+               if (chimera == "Yes") {
+                       cout << querySeq->getName() << "\tdiv: " << toString(deviation) << "\tstDev: " << toString(DE) << "\tchimera flag: " << chimera << endl;
+                       string outAccString = querySeq->getName() + "\n";
+                       
+                       MPI_Status statusAcc;
+                       int length = outAccString.length();
+                       char* buf = new char[length];
+                       memcpy(buf, outAccString.c_str(), length);
+                               
+                       MPI_File_write_shared(outAcc, buf, length, MPI_CHAR, &statusAcc);
+                       delete buf;
+
+                       return *querySeq;
                }
+               outputString += "Observed\t";
+               
+               for (int j = 0; j < obsDistance.size(); j++) {  outputString += toString(obsDistance[j]) + "\t";  }
+               outputString += "\n";
+               
+               outputString += "Expected\t";
+               
+               for (int m = 0; m < expectedDistance.size(); m++) {  outputString += toString(expectedDistance[m]) + "\t";  }
+               outputString += "\n";
+               
+               MPI_Status status;
+               int length = outputString.length();
+               char* buf2 = new char[length];
+               memcpy(buf2, outputString.c_str(), length);
                                
+               MPI_File_write_shared(out, buf2, length, MPI_CHAR, &status);
+               delete buf2;
+               
+               return *querySeq;
        }
        catch(exception& e) {
-               errorOut(e, "Pintail", "calcExpected");
+               m->errorOut(e, "Pintail", "print");
                exit(1);
        }
 }
+#endif
 //***************************************************************************************************************
-void Pintail::calcDE(int start, int end) {
+int Pintail::getChimeras(Sequence* query) {
        try {
-               
-       
-               //for each sequence
-               for(int i = start; i < end; i++){
-                       
-                       itObsDist = obsDistance.find(querySeqs[i]);
-                       vector<float> obs = itObsDist->second;
-                       
-                       itExpDist = expectedDistance.find(querySeqs[i]);
-                       vector<float> exp = itExpDist->second;
-                       
-                       //for each window
-                       float sum = 0.0;  //sum = sum from 1 to m of (oi-ei)^2
-                       for (int m = 0; m < iters; m++) {               sum += ((obs[m] - exp[m]) * (obs[m] - exp[m]));         }
-                       
-                       float de = sqrt((sum / (iters - 1)));
-                       
-                       DE[querySeqs[i]] = de;
+               querySeq = query;
+               trimmed.clear();
+               windowSizes = window;
+                                                       
+               //find pairs has to be done before a mask
+               bestfit = findPairs(query);
+               
+               if (m->control_pressed) {  return 0; } 
+               
+               //if they mask  
+               if (seqMask != "") {
+                       decalc->runMask(query);
+                       decalc->runMask(bestfit);
+               }
+
+               if (filter) { //must be done after a mask
+                       runFilter(query);
+                       runFilter(bestfit);
                }
+               
                                
+               //trim seq
+               decalc->trimSeqs(query, bestfit, trimmed);  
+               
+               //find windows
+               it = trimmed.begin();
+               windowsForeachQuery = decalc->findWindows(query, it->first, it->second, windowSizes, increment);
+
+               //find observed distance
+               obsDistance = decalc->calcObserved(query, bestfit, windowsForeachQuery, windowSizes);
+               
+               if (m->control_pressed) {  return 0; } 
+                               
+               Qav = decalc->findQav(windowsForeachQuery, windowSizes, probabilityProfile);
+               
+               if (m->control_pressed) {  return 0; } 
+
+               //find alpha                    
+               seqCoef = decalc->getCoef(obsDistance, Qav);
+               
+               //calculating expected distance
+               expectedDistance = decalc->calcExpected(Qav, seqCoef);
+               
+               if (m->control_pressed) {  return 0; } 
+               
+               //finding de
+               DE = decalc->calcDE(obsDistance, expectedDistance);
+               
+               if (m->control_pressed) {  return 0; } 
+               
+               //find distance between query and closest match
+               it = trimmed.begin();
+               deviation = decalc->calcDist(query, bestfit, it->first, it->second); 
+               
+               delete bestfit;
+                                                                       
+               return 0;
        }
        catch(exception& e) {
-               errorOut(e, "Pintail", "calcDE");
+               m->errorOut(e, "Pintail", "getChimeras");
                exit(1);
        }
 }
 
 //***************************************************************************************************************
 
-vector<float> Pintail::calcFreq(vector<Sequence*> seqs) {
+vector<float> Pintail::readFreq() {
        try {
+               //read in probabilities and store in vector
+               int pos; float num; 
 
                vector<float> prob;
+               set<int> h = decalc->getPos();  //positions of bases in masking sequence
                
-               //at each position in the sequence
-               for (int i = 0; i < seqs[0]->getAligned().length(); i++) {
+       #ifdef USE_MPI
                
-                       vector<int> freq;   freq.resize(4,0);
-                       
-                       //find the frequency of each nucleotide
-                       for (int j = 0; j < seqs.size(); j++) {
-                               
-                               char value = seqs[j]->getAligned()[i];
+               MPI_File inMPI;
+               MPI_Offset size;
+               MPI_Status status;
+
+               //char* inFileName = new char[consfile.length()];
+               //memcpy(inFileName, consfile.c_str(), consfile.length());
+               
+               char inFileName[1024];
+               strcpy(inFileName, consfile.c_str());
+
+               MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);  
+               MPI_File_get_size(inMPI, &size);
+               //delete inFileName;
+
+               char* buffer = new char[size];
+               MPI_File_read(inMPI, buffer, size, MPI_CHAR, &status);
+
+               string tempBuf = buffer;
+               delete buffer;
+
+               if (tempBuf.length() > size) { tempBuf = tempBuf.substr(0, size);  }
+               istringstream iss (tempBuf,istringstream::in);
+               
+               //read version
+               string line = m->getline(iss); m->gobble(iss);
+               
+               while(!iss.eof()) {
+                       iss >> pos >> num;
+       
+                       if (h.count(pos) > 0) {
+                               float Pi;
+                               Pi =  (num - 0.25) / 0.75; 
                        
-                               if(toupper(value) == 'A')                                                                       {       freq[0]++;      }
-                               else if(toupper(value) == 'T' || toupper(value) == 'U')         {       freq[1]++;      }
-                               else if(toupper(value) == 'G')                                                          {       freq[2]++;      }
-                               else if(toupper(value) == 'C')                                                          {       freq[3]++;      }
+                               //cannot have probability less than 0.
+                               if (Pi < 0) { Pi = 0.0; }
+
+                               //do you want this spot
+                               prob.push_back(Pi);  
                        }
                        
-                       //find base with highest frequency
-                       int highest = 0;
-                       for (int m = 0; m < freq.size(); m++) {    if (freq[m] > highest) {  highest = freq[m];  }              }
-                               
-                       float highFreq = highest / (float) seqs.size(); 
-                       float Pi;
-                       //if this is not a gap column
-                       if (highFreq != 0) { Pi =  (highFreq - 0.25) / 0.75;  }
-                       else { Pi = 0; }
-                       
-                       prob.push_back(Pi);
-                       
+                       m->gobble(iss);
                }
+       
+               MPI_File_close(&inMPI);
                
-               return prob;
-                               
-       }
-       catch(exception& e) {
-               errorOut(e, "Pintail", "calcFreq");
-               exit(1);
-       }
-}
-//***************************************************************************************************************
-vector<float> Pintail::findQav(vector<float> prob) {
-       try {
-               vector<float> averages;
+       #else   
+
+               ifstream in;
+               m->openInputFile(consfile, in);
                
-               //for each window find average
-               int startpoint = 0;
-               for (int m = 0; m < iters; m++) {
+               //read version
+               string line = m->getline(in); m->gobble(in);
+                               
+               while(!in.eof()){
                        
-                       float average = 0.0;
-                       for (int i = startpoint; i < (startpoint+window); i++) {   average += prob[i];  }
+                       in >> pos >> num;
                        
-                       average = average / window;
+                       if (h.count(pos) > 0) {
+                               float Pi;
+                               Pi =  (num - 0.25) / 0.75; 
                        
-                       //save this windows average
-                       averages.push_back(average);
-               
-                       startpoint += increment;
+                               //cannot have probability less than 0.
+                               if (Pi < 0) { Pi = 0.0; }
+
+                               //do you want this spot
+                               prob.push_back(Pi);  
+                       }
+                       
+                       m->gobble(in);
                }
+               in.close();
+               
+       #endif
+       
+               return prob;
                
-               return averages;
        }
        catch(exception& e) {
-               errorOut(e, "Pintail", "findQav");
+               m->errorOut(e, "Pintail", "readFreq");
                exit(1);
        }
 }
+
 //***************************************************************************************************************
-map<Sequence*, float> Pintail::getCoef(vector<float> prob) {
+//calculate the distances from each query sequence to all sequences in the template to find the closest sequence
+Sequence* Pintail::findPairs(Sequence* q) {
        try {
-               map<Sequence*, float> coefs;
-               
-               //find average prob
-               float probAverage = 0.0;
-               for (int i = 0; i < prob.size(); i++) {   probAverage += prob[i];       }
-               probAverage = probAverage / (float) prob.size();
                
-               //find a coef for each sequence
-               map<Sequence*, vector<float> >::iterator it;
-               for (it = obsDistance.begin(); it != obsDistance.end(); it++) {
-                       
-                       vector<float> temp = it->second;
-                       Sequence* tempSeq = it->first;
-                       
-                       //find observed average 
-                       float obsAverage = 0.0;
-                       for (int i = 0; i < temp.size(); i++) {   obsAverage += temp[i];        }
-                       obsAverage = obsAverage / (float) temp.size();
-                       
-                       float coef = obsAverage / probAverage;
-                       
-                       //save this sequences coefficient
-                       coefs[tempSeq] = coef;
-               }
+               Sequence* seqsMatches;  
                
-                                               
-               return coefs;
+               seqsMatches = decalc->findClosest(q, templateSeqs);
+               return seqsMatches;
+       
        }
        catch(exception& e) {
-               errorOut(e, "Pintail", "getCoef");
+               m->errorOut(e, "Pintail", "findPairs");
                exit(1);
        }
 }
-
-/**************************************************************************************************/
-
-void Pintail::createProcessesPairs() {
+//**************************************************************************************************
+void Pintail::createProcessesQuan() {
        try {
-#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
-               int process = 0;
+#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
+               int process = 1;
                vector<int> processIDS;
-               
+                               
                //loop through and create all the processes you want
                while (process != processors) {
                        int pid = fork();
@@ -446,142 +541,235 @@ void Pintail::createProcessesPairs() {
                                processIDS.push_back(pid);  
                                process++;
                        }else if (pid == 0){
-                               findPairs(lines[process]->start, lines[process]->end);
+                               
+                               quantilesMembers = decalc->getQuantiles(templateSeqs, windowSizesTemplate, window, probabilityProfile, increment, templateLines[process]->start, templateLines[process]->end);
+                               
+                               //write out data to file so parent can read it
+                               ofstream out;
+                               string s = toString(getpid()) + ".temp";
+                               m->openOutputFile(s, out);
+                                                               
+                               //output observed distances
+                               for (int i = 0; i < quantilesMembers.size(); i++) {
+                                       out << quantilesMembers[i].size() << '\t';
+                                       for (int j = 0; j < quantilesMembers[i].size(); j++) {
+                                               out << quantilesMembers[i][j] << '\t';
+                                       }
+                                       out << endl;
+                               }
+                               
+                               out.close();
+                               
+                               exit(0);
+                       }else { 
+                               m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
+                               for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
                                exit(0);
-                       }else { mothurOut("unable to spawn the necessary processes."); mothurOutEndLine(); exit(0); }
+                       }
                }
                
+               //parent does its part
+               quantilesMembers = decalc->getQuantiles(templateSeqs, windowSizesTemplate, window, probabilityProfile, increment, templateLines[0]->start, templateLines[0]->end);
+               
                //force parent to wait until all the processes are done
-               for (int i=0;i<processors;i++) { 
+               for (int i=0;i<(processors-1);i++) { 
                        int temp = processIDS[i];
                        wait(&temp);
                }
-               
-#else
-               findPairs(lines[0]->start, lines[0]->end);
 
-#endif         
-       }
-       catch(exception& e) {
-               errorOut(e, "Pintail", "createProcessesPairs");
-               exit(1);
-       }
-}
+               //get data created by processes
+               for (int i=0;i<(processors-1);i++) { 
+                       ifstream in;
+                       string s = toString(processIDS[i]) + ".temp";
+                       m->openInputFile(s, in);
+                       
+                       vector< vector<float> > quan; 
+                       quan.resize(100);
+                       
+                       //get quantiles
+                       for (int h = 0; h < quan.size(); h++) {
+                               int num;
+                               in >> num; 
+                               
+                               m->gobble(in);
 
-/**************************************************************************************************/
+                               vector<float> q;  float w; 
+                               for (int j = 0; j < num; j++) {
+                                       in >> w;
+                                       q.push_back(w);
+                               }
 
-void Pintail::createProcessesObserved() {
-       try {
-#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
-               int process = 0;
-               vector<int> processIDS;
-               
-               //loop through and create all the processes you want
-               while (process != processors) {
-                       int pid = fork();
+                               quan[h] = q;
+                               m->gobble(in);
+                       }
                        
-                       if (pid > 0) {
-                               processIDS.push_back(pid);  
-                               process++;
-                       }else if (pid == 0){
-                               calcObserved(lines[process]->start, lines[process]->end);
-                               exit(0);
-                       }else { mothurOut("unable to spawn the necessary processes."); mothurOutEndLine(); exit(0); }
-               }
-               
-               //force parent to wait until all the processes are done
-               for (int i=0;i<processors;i++) { 
-                       int temp = processIDS[i];
-                       wait(&temp);
+       
+                       //save quan in quantiles
+                       for (int j = 0; j < quan.size(); j++) {
+                               //put all values of q[i] into quan[i]
+                               for (int l = 0; l < quan[j].size(); l++) {  quantilesMembers[j].push_back(quan[j][l]);   }
+                               //quantilesMembers[j].insert(quantilesMembers[j].begin(), quan[j].begin(), quan[j].end());
+                       }
+                                       
+                       in.close();
+                       m->mothurRemove(s);
                }
-               
-#else
-               calcObserved(lines[0]->start, lines[0]->end);
 
+#else
+               quantilesMembers = decalc->getQuantiles(templateSeqs, windowSizesTemplate, window, probabilityProfile, increment, 0, templateSeqs.size());
 #endif         
        }
        catch(exception& e) {
-               errorOut(e, "Pintail", "createProcessesObserved");
+               m->errorOut(e, "Pintail", "createProcessesQuan");
                exit(1);
        }
 }
-
 //***************************************************************************************************************
-
-void Pintail::createProcessesExpected() {
+vector< vector<float> > Pintail::readQuantiles() {
        try {
-#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
-               int process = 0;
-               vector<int> processIDS;
+               int num; 
+               float ten, twentyfive, fifty, seventyfive, ninetyfive, ninetynine; 
                
-               //loop through and create all the processes you want
-               while (process != processors) {
-                       int pid = fork();
+               vector< vector<float> > quan;
+               vector <float> temp; temp.resize(6, 0);
+               
+               //to fill 0
+               quan.push_back(temp); 
+
+       #ifdef USE_MPI
+               
+               MPI_File inMPI;
+               MPI_Offset size;
+               MPI_Status status;
+               
+               //char* inFileName = new char[quanfile.length()];
+               //memcpy(inFileName, quanfile.c_str(), quanfile.length());
+               
+               char inFileName[1024];
+               strcpy(inFileName, quanfile.c_str());
+
+               MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);  
+               MPI_File_get_size(inMPI, &size);
+               //delete inFileName;
+
+
+               char* buffer = new char[size];
+               MPI_File_read(inMPI, buffer, size, MPI_CHAR, &status);
+
+               string tempBuf = buffer;
+               if (tempBuf.length() > size) { tempBuf = tempBuf.substr(0, size);  }
+               istringstream iss (tempBuf,istringstream::in);
+               delete buffer;
+               
+               //read version
+               string line = m->getline(iss); m->gobble(iss);
+               
+               while(!iss.eof()) {
+                       iss >> num >> ten >> twentyfive >> fifty >> seventyfive >> ninetyfive >> ninetynine; 
                        
-                       if (pid > 0) {
-                               processIDS.push_back(pid);  
-                               process++;
-                       }else if (pid == 0){
-                               calcExpected(lines[process]->start, lines[process]->end);
-                               exit(0);
-                       }else { mothurOut("unable to spawn the necessary processes."); mothurOutEndLine(); exit(0); }
+                       temp.clear();
+                       
+                       temp.push_back(ten); 
+                       temp.push_back(twentyfive);
+                       temp.push_back(fifty);
+                       temp.push_back(seventyfive);
+                       temp.push_back(ninetyfive);
+                       temp.push_back(ninetynine);
+                       
+                       quan.push_back(temp);  
+                       
+                       m->gobble(iss);
                }
+       
+               MPI_File_close(&inMPI);
                
-               //force parent to wait until all the processes are done
-               for (int i=0;i<processors;i++) { 
-                       int temp = processIDS[i];
-                       wait(&temp);
+       #else   
+
+               ifstream in;
+               m->openInputFile(quanfile, in);
+               
+               //read version
+               string line = m->getline(in); m->gobble(in);
+                       
+               while(!in.eof()){
+                       
+                       in >> num >> ten >> twentyfive >> fifty >> seventyfive >> ninetyfive >> ninetynine; 
+                       
+                       temp.clear();
+                       
+                       temp.push_back(ten); 
+                       temp.push_back(twentyfive);
+                       temp.push_back(fifty);
+                       temp.push_back(seventyfive);
+                       temp.push_back(ninetyfive);
+                       temp.push_back(ninetynine);
+                       
+                       quan.push_back(temp);  
+       
+                       m->gobble(in);
                }
+               in.close();
+       #endif
+       
+               return quan;
                
-#else
-               calcExpected(lines[0]->start, lines[0]->end);
-
-#endif         
        }
        catch(exception& e) {
-               errorOut(e, "Pintail", "createProcessesExpected");
+               m->errorOut(e, "Pintail", "readQuantiles");
                exit(1);
        }
 }
+//***************************************************************************************************************/
 
-/**************************************************************************************************/
-
-void Pintail::createProcessesDE() {
+void Pintail::printQuanFile(string file, string outputString) {
        try {
-#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
-               int process = 0;
-               vector<int> processIDS;
+       
+               #ifdef USE_MPI
                
-               //loop through and create all the processes you want
-               while (process != processors) {
-                       int pid = fork();
+                       MPI_File outQuan;
+                       MPI_Status status;
                        
-                       if (pid > 0) {
-                               processIDS.push_back(pid);  
-                               process++;
-                       }else if (pid == 0){
-                               calcDE(lines[process]->start, lines[process]->end);
-                               exit(0);
-                       }else { mothurOut("unable to spawn the necessary processes."); mothurOutEndLine(); exit(0); }
-               }
-               
-               //force parent to wait until all the processes are done
-               for (int i=0;i<processors;i++) { 
-                       int temp = processIDS[i];
-                       wait(&temp);
-               }
-               
-#else
-               calcDE(lines[0]->start, lines[0]->end);
+                       int pid;
+                       MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
 
-#endif         
+                       int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
+
+                       //char* FileName = new char[file.length()];
+                       //memcpy(FileName, file.c_str(), file.length());
+                       
+                       char FileName[1024];
+                       strcpy(FileName, file.c_str());
+                       
+                       if (pid == 0) {
+                               MPI_File_open(MPI_COMM_SELF, FileName, outMode, MPI_INFO_NULL, &outQuan);  //comm, filename, mode, info, filepointer
+                               
+                               int length = outputString.length();
+                               char* buf = new char[length];
+                               memcpy(buf, outputString.c_str(), length);
+                                       
+                               MPI_File_write(outQuan, buf, length, MPI_CHAR, &status);
+                               delete buf;
+
+                               MPI_File_close(&outQuan);
+                       }
+
+                       //delete FileName;
+               #else
+                       ofstream outQuan;
+                       m->openOutputFile(file, outQuan);
+                       
+                       outQuan << outputString;
+                       
+                       outQuan.close();
+               #endif
        }
        catch(exception& e) {
-               errorOut(e, "Pintail", "createProcessesDE");
+               m->errorOut(e, "Pintail", "printQuanFile");
                exit(1);
        }
 }
 
-//***************************************************************************************************************
+//***************************************************************************************************************/
+