]> git.donarmstrong.com Git - mothur.git/commitdiff
added subsample and consensus parameters to unifrac.unweighted command
authorSarah Westcott <mothur.westcott@gmail.com>
Mon, 16 Apr 2012 16:23:59 +0000 (12:23 -0400)
committerSarah Westcott <mothur.westcott@gmail.com>
Mon, 16 Apr 2012 16:23:59 +0000 (12:23 -0400)
unifracunweightedcommand.cpp
unifracunweightedcommand.h
unifracweightedcommand.h

index de8cb5637fe64a5a63e88852a26935512ff53806..dbdee2ad942db51860cb0a7f403662a895def1bf 100644 (file)
@@ -9,6 +9,8 @@
 
 #include "unifracunweightedcommand.h"
 #include "treereader.h"
+#include "subsample.h"
+#include "consensus.h"
 
 //**********************************************************************************************************************
 vector<string> UnifracUnweightedCommand::setParameters(){      
@@ -21,7 +23,9 @@ vector<string> UnifracUnweightedCommand::setParameters(){
                CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
                CommandParameter prandom("random", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(prandom);
                CommandParameter pdistance("distance", "Multiple", "column-lt-square", "column", "", "", "",false,false); parameters.push_back(pdistance);
-               CommandParameter proot("root", "Boolean", "F", "", "", "", "",false,false); parameters.push_back(proot);
+        CommandParameter psubsample("subsample", "String", "", "", "", "", "",false,false); parameters.push_back(psubsample);
+        CommandParameter pconsensus("consensus", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(pconsensus);
+        CommandParameter proot("root", "Boolean", "F", "", "", "", "",false,false); parameters.push_back(proot);
                CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
                CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
                
@@ -46,6 +50,8 @@ string UnifracUnweightedCommand::getHelpString(){
                helpString += "The root parameter allows you to include the entire root in your calculations. The default is false, meaning stop at the root for this comparision instead of the root of the entire tree.\n";
                helpString += "The processors parameter allows you to specify the number of processors to use. The default is 1.\n";
                helpString += "The unifrac.unweighted command should be in the following format: unifrac.unweighted(groups=yourGroups, iters=yourIters).\n";
+        helpString += "The subsample parameter allows you to enter the size pergroup of the sample or you can set subsample=T and mothur will use the size of your smallest group. The subsample parameter may only be used with a group file.\n";
+        helpString += "The consensus parameter allows you to indicate you would like trees built from distance matrices created with the results of the subsampling, as well as a consensus tree built from these trees. Default=F.\n";
                helpString += "Example unifrac.unweighted(groups=A-B-C, iters=500).\n";
                helpString += "The default value for groups is all the groups in your groupfile, and iters is 1000.\n";
                helpString += "The unifrac.unweighted command output two files: .unweighted and .uwsummary their descriptions are in the manual.\n";
@@ -67,6 +73,7 @@ UnifracUnweightedCommand::UnifracUnweightedCommand(){
                outputTypes["uwsummary"] = tempOutNames;
                outputTypes["phylip"] = tempOutNames;
                outputTypes["column"] = tempOutNames;
+        outputTypes["tree"] = tempOutNames;
        }
        catch(exception& e) {
                m->errorOut(e, "UnifracUnweightedCommand", "UnifracUnweightedCommand");
@@ -103,6 +110,7 @@ UnifracUnweightedCommand::UnifracUnweightedCommand(string option)  {
                        outputTypes["uwsummary"] = tempOutNames;
                        outputTypes["phylip"] = tempOutNames;
                        outputTypes["column"] = tempOutNames;
+            outputTypes["tree"] = tempOutNames;
                        
                        //if the user changes the input directory command factory will send this info to us in the output parameter 
                        string inputDir = validParameter.validFile(parameters, "inputdir", false);              
@@ -154,7 +162,7 @@ UnifracUnweightedCommand::UnifracUnweightedCommand(string option)  {
                        else if (namefile == "not found") { namefile = ""; }
                        else { m->setNameFile(namefile); }
                        
-                       outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = ""; }
+                       outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = m->hasPath(treefile);       }
                        
                        //check for optional parameter and set defaults
                        // ...at some point should added some additional type checking...
@@ -185,6 +193,24 @@ UnifracUnweightedCommand::UnifracUnweightedCommand(string option)  {
                        m->setProcessors(temp);
                        m->mothurConvert(temp, processors); 
                        
+            temp = validParameter.validFile(parameters, "subsample", false);           if (temp == "not found") { temp = "F"; }
+                       if (m->isNumeric1(temp)) { m->mothurConvert(temp, subsampleSize); subsample = true; }
+            else {  
+                if (m->isTrue(temp)) { subsample = true; subsampleSize = -1; }  //we will set it to smallest group later 
+                else { subsample = false; }
+            }
+                       
+            if (!subsample) { subsampleIters = 0;   }
+            else { subsampleIters = iters;          }
+            
+            temp = validParameter.validFile(parameters, "consensus", false);                                   if (temp == "not found") { temp = "F"; }
+                       consensus = m->isTrue(temp);
+            
+                       if (subsample && random) {  m->mothurOut("[ERROR]: random must be false, if subsample=t.\n"); abort=true;  } 
+                       if (subsample && (groupfile == "")) {  m->mothurOut("[ERROR]: if subsample=t, a group file must be provided.\n"); abort=true;  } 
+            if (subsample && (!phylip)) { phylip=true; outputForm = "lt"; }
+            if (consensus && (!subsample)) { m->mothurOut("[ERROR]: you cannot use consensus without subsample.\n"); abort=true; }
+
                        if (!random) {  iters = 0;  } //turn off random calcs
                        
                        //if user selects distance = true and no groups it won't calc the pairwise
@@ -218,7 +244,7 @@ int UnifracUnweightedCommand::execute() {
                TreeReader* reader = new TreeReader(treefile, groupfile, namefile);
         T = reader->getTrees();
         tmap = T[0]->getTreeMap();
-        map<string, string> nameMap = reader->getNameMap();
+        map<string, string> nameMap = reader->getNames();
         delete reader; 
         
                sumFile = outputDir + m->getSimpleName(treefile) + ".uwsummary";
@@ -229,20 +255,46 @@ int UnifracUnweightedCommand::execute() {
                Groups = m->getGroups();
                vector<string> namesGroups = tmap->getNamesOfGroups();
                util.setGroups(Groups, namesGroups, allGroups, numGroups, "unweighted");        //sets the groups the user wants to analyze
-               util.getCombos(groupComb, Groups, numComp);
-               m->setGroups(Groups);
-       
-               if (numGroups == 1) { numComp++; groupComb.push_back(allGroups); }
                
                Unweighted unweighted(includeRoot);
                
                int start = time(NULL);
-               
-               userData.resize(numComp,0);  //data[0] = unweightedscore 
-               randomData.resize(numComp,0); //data[0] = unweightedscore
-               //create new tree with same num nodes and leaves as users
-               
+        
+        //set or check size
+        if (subsample) {
+            //user has not set size, set size = smallest samples size
+            if (subsampleSize == -1) { 
+                vector<string> temp; temp.push_back(Groups[0]);
+                subsampleSize = (tmap->getNamesSeqs(temp)).size(); //num in first group
+                for (int i = 1; i < Groups.size(); i++) {
+                    temp.clear(); temp.push_back(Groups[i]);
+                    int thisSize = (tmap->getNamesSeqs(temp)).size();
+                    if (thisSize < subsampleSize) {    subsampleSize = thisSize;       }
+                }
+                m->mothurOut("\nSetting subsample size to " + toString(subsampleSize) + ".\n\n");
+            }else { //eliminate any too small groups
+                vector<string> newGroups = Groups;
+                Groups.clear();
+                for (int i = 0; i < newGroups.size(); i++) {
+                    vector<string> thisGroup; thisGroup.push_back(newGroups[i]);
+                    vector<string> thisGroupsSeqs = tmap->getNamesSeqs(thisGroup);
+                    int thisSize = thisGroupsSeqs.size();
+                    
+                    if (thisSize >= subsampleSize) {    Groups.push_back(newGroups[i]);        }
+                    else {  m->mothurOut("You have selected a size that is larger than "+newGroups[i]+" number of sequences, removing "+newGroups[i]+".\n"); }
+                } 
+                m->setGroups(Groups);
+            }
+        }
+               
+        util.getCombos(groupComb, Groups, numComp);
+               m->setGroups(Groups);
+        
+               if (numGroups == 1) { numComp++; groupComb.push_back(allGroups); }
+        
                if (numComp < processors) { processors = numComp;  }
+        
+        if (consensus && (numComp < 2)) { m->mothurOut("consensus can only be used with numComparisions greater than 1, setting consensus=f.\n"); consensus=false; }
                
                outSum << "Tree#" << '\t' << "Groups" << '\t'  <<  "UWScore" <<'\t';
                m->mothurOut("Tree#\tGroups\tUWScore\t");
@@ -251,13 +303,7 @@ int UnifracUnweightedCommand::execute() {
         
                //get pscores for users trees
                for (int i = 0; i < T.size(); i++) {
-                       if (m->control_pressed) { 
-                               delete tmap;
-                               for (int i = 0; i < T.size(); i++) { delete T[i]; }
-                               outSum.close();
-                               for (int i = 0; i < outputNames.size(); i++) {  m->mothurRemove(outputNames[i]);  }
-                               return 0; 
-                       }
+                       if (m->control_pressed) { delete tmap; for (int i = 0; i < T.size(); i++) { delete T[i]; }outSum.close(); for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]);  } return 0; }
                        
                        counter = 0;
                        
@@ -273,11 +319,12 @@ int UnifracUnweightedCommand::execute() {
                        rCumul.resize(numComp);  
                        utreeScores.resize(numComp);  
                        UWScoreSig.resize(numComp); 
+            
+            vector<double> userData; userData.resize(numComp,0);  //weighted score info for user tree. data[0] = weightedscore AB, data[1] = weightedscore AC...
 
                        userData = unweighted.getValues(T[i], processors, outputDir);  //userData[0] = unweightedscore
                
-                       if (m->control_pressed) { delete tmap; 
-                               for (int i = 0; i < T.size(); i++) { delete T[i]; }if (random) { delete output;  } outSum.close();  for (int i = 0; i < outputNames.size(); i++) {      m->mothurRemove(outputNames[i]);  }return 0; }
+                       if (m->control_pressed) { delete tmap; for (int i = 0; i < T.size(); i++) { delete T[i]; }if (random) { delete output;  } outSum.close();  for (int i = 0; i < outputNames.size(); i++) {       m->mothurRemove(outputNames[i]);  }return 0; }
                        
                        //output scores for each combination
                        for(int k = 0; k < numComp; k++) {
@@ -286,56 +333,47 @@ int UnifracUnweightedCommand::execute() {
                                
                                //add users score to validscores
                                validScores[userData[k]] = userData[k];
+                
+                if (!random) { UWScoreSig[k].push_back(0.0);   }
                        }
-               
-                       //get unweighted scores for random trees - if random is false iters = 0
-                       for (int j = 0; j < iters; j++) {
-               
-                               //we need a different getValues because when we swap the labels we only want to swap those in each pairwise comparison
-                               randomData = unweighted.getValues(T[i], "", "", processors, outputDir);
-                               
-                               if (m->control_pressed) { delete tmap; 
-                                       for (int i = 0; i < T.size(); i++) { delete T[i]; }if (random) { delete output;  } outSum.close(); for (int i = 0; i < outputNames.size(); i++) {       m->mothurRemove(outputNames[i]);  } return 0; }
-                       
-                               for(int k = 0; k < numComp; k++) {      
-                                       //add trees unweighted score to map of scores
-                                       map<float,float>::iterator it = rscoreFreq[k].find(randomData[k]);
-                                       if (it != rscoreFreq[k].end()) {//already have that score
-                                               rscoreFreq[k][randomData[k]]++;
-                                       }else{//first time we have seen this score
-                                               rscoreFreq[k][randomData[k]] = 1;
-                                       }
-                               
-                                       //add randoms score to validscores
-                                       validScores[randomData[k]] = randomData[k];
-                               }
-                               
-                               //report progress
-//                             m->mothurOut("Iter: " + toString(j+1)); m->mothurOutEndLine();  
-                       }
-       
-                       for(int a = 0; a < numComp; a++) {
-                               float rcumul = 1.0000;
-                               
-                               if (random) {
-                                       //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
-                                       for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) { 
-                                               //make rscoreFreq map and rCumul
-                                               map<float,float>::iterator it2 = rscoreFreq[a].find(it->first);
-                                               rCumul[a][it->first] = rcumul;
-                                               //get percentage of random trees with that info
-                                               if (it2 != rscoreFreq[a].end()) {  rscoreFreq[a][it->first] /= iters; rcumul-= it2->second;  }
-                                               else { rscoreFreq[a][it->first] = 0.0000; } //no random trees with that score
-                                       }
-                                       UWScoreSig[a].push_back(rCumul[a][userData[a]]);
-                               }else           {       UWScoreSig[a].push_back(0.0);                                           }
-       
-                       }
-                       
-                       if (m->control_pressed) { delete tmap; 
-                               for (int i = 0; i < T.size(); i++) { delete T[i]; }if (random) { delete output;  } outSum.close(); for (int i = 0; i < outputNames.size(); i++) {       m->mothurRemove(outputNames[i]);  } return 0;  }
+            
+            if (random) {  runRandomCalcs(T[i], userData);  }
                        
-                       //print output files
+                       if (m->control_pressed) { delete tmap; for (int i = 0; i < T.size(); i++) { delete T[i]; }if (random) { delete output;  } outSum.close(); for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]);  } return 0;  }
+            
+            //subsample loop
+            vector< vector<double> > calcDistsTotals;  //each iter, each groupCombos dists. this will be used to make .dist files
+            for (int thisIter = 0; thisIter < subsampleIters; thisIter++) { //subsampleIters=0, if subsample=f.
+                
+                if (m->control_pressed) { break; }
+                
+                //copy to preserve old one - would do this in subsample but memory cleanup becomes messy.
+                TreeMap* newTmap = new TreeMap();
+                newTmap->getCopy(*tmap);
+                
+                SubSample sample;
+                Tree* subSampleTree = sample.getSample(T[i], newTmap, nameMap, subsampleSize);
+                
+                //call new weighted function
+                vector<double> iterData; iterData.resize(numComp,0);
+                Unweighted thisUnweighted(includeRoot);
+                iterData = thisUnweighted.getValues(subSampleTree, processors, outputDir); //userData[0] = weightedscore
+                
+                //save data to make ave dist, std dist
+                calcDistsTotals.push_back(iterData);
+                
+                delete newTmap;
+                delete subSampleTree;
+                
+                if((thisIter+1) % 100 == 0){   m->mothurOut(toString(thisIter+1)); m->mothurOutEndLine();              }
+            }
+            
+            if (m->control_pressed) { delete tmap; for (int i = 0; i < T.size(); i++) { delete T[i]; }if (random) { delete output;  } outSum.close(); for (int i = 0; i < outputNames.size(); i++) {   m->mothurRemove(outputNames[i]);  } return 0;  }
+
+            if (subsample) {  getAverageSTDMatrices(calcDistsTotals, i); }
+            if (consensus) {  getConsensusTrees(calcDistsTotals, i);  }
+            
+            //print output files
                        printUWSummaryFile(i);
                        if (random)  {  printUnweightedFile();  delete output;  }
                        if (phylip) {   createPhylipFile(i);            }
@@ -382,6 +420,273 @@ int UnifracUnweightedCommand::execute() {
                exit(1);
        }
 }
+/**************************************************************************************************/
+int UnifracUnweightedCommand::getAverageSTDMatrices(vector< vector<double> >& dists, int treeNum) {
+       try {
+        //we need to find the average distance and standard deviation for each groups distance
+        
+        //finds sum
+        vector<double> averages; averages.resize(numComp, 0); 
+        for (int thisIter = 0; thisIter < subsampleIters; thisIter++) {
+            for (int i = 0; i < dists[thisIter].size(); i++) {  
+                averages[i] += dists[thisIter][i];
+            }
+        }
+        
+        //finds average.
+        for (int i = 0; i < averages.size(); i++) {  averages[i] /= (float) subsampleIters; }
+        
+        //find standard deviation
+        vector<double> stdDev; stdDev.resize(numComp, 0);
+        
+        for (int thisIter = 0; thisIter < iters; thisIter++) { //compute the difference of each dist from the mean, and square the result of each
+            for (int j = 0; j < dists[thisIter].size(); j++) {
+                stdDev[j] += ((dists[thisIter][j] - averages[j]) * (dists[thisIter][j] - averages[j]));
+            }
+        }
+        for (int i = 0; i < stdDev.size(); i++) {  
+            stdDev[i] /= (float) subsampleIters; 
+            stdDev[i] = sqrt(stdDev[i]);
+        }
+        
+        //make matrix with scores in it
+        vector< vector<double> > avedists;     avedists.resize(m->getNumGroups());
+        for (int i = 0; i < m->getNumGroups(); i++) {
+            avedists[i].resize(m->getNumGroups(), 0.0);
+        }
+        
+        //make matrix with scores in it
+        vector< vector<double> > stddists;     stddists.resize(m->getNumGroups());
+        for (int i = 0; i < m->getNumGroups(); i++) {
+            stddists[i].resize(m->getNumGroups(), 0.0);
+        }
+        
+        //flip it so you can print it
+        int count = 0;
+        for (int r=0; r<m->getNumGroups(); r++) { 
+            for (int l = 0; l < r; l++) {
+                avedists[r][l] = averages[count];
+                avedists[l][r] = averages[count];
+                stddists[r][l] = stdDev[count];
+                stddists[l][r] = stdDev[count];
+                count++;
+            }
+        }
+        
+        string aveFileName = outputDir + m->getSimpleName(treefile)  + toString(treeNum+1) + ".unweighted.ave.dist";
+        outputNames.push_back(aveFileName); outputTypes["phylip"].push_back(aveFileName); 
+        
+        ofstream out;
+        m->openOutputFile(aveFileName, out);
+        
+        string stdFileName = outputDir + m->getSimpleName(treefile)  + toString(treeNum+1) + ".unweighted.std.dist";
+        outputNames.push_back(stdFileName); outputTypes["phylip"].push_back(stdFileName); 
+        
+        ofstream outStd;
+        m->openOutputFile(stdFileName, outStd);
+        
+        if ((outputForm == "lt") || (outputForm == "square")) {
+            //output numSeqs
+            out << m->getNumGroups() << endl;
+            outStd << m->getNumGroups() << endl;
+        }
+        
+        //output to file
+        for (int r=0; r<m->getNumGroups(); r++) { 
+            //output name
+            string name = (m->getGroups())[r];
+            if (name.length() < 10) { //pad with spaces to make compatible
+                while (name.length() < 10) {  name += " ";  }
+            }
+            
+            if (outputForm == "lt") {
+                out << name << '\t';
+                outStd << name << '\t';
+                
+                //output distances
+                for (int l = 0; l < r; l++) {  out  << avedists[r][l] << '\t';  outStd  << stddists[r][l] << '\t';}
+                out << endl;  outStd << endl;
+            }else if (outputForm == "square") {
+                out << name << '\t';
+                outStd << name << '\t';
+                
+                //output distances
+                for (int l = 0; l < m->getNumGroups(); l++) {  out  << avedists[r][l] << '\t'; outStd  << stddists[r][l] << '\t'; }
+                out << endl; outStd << endl;
+            }else{
+                //output distances
+                for (int l = 0; l < r; l++) {  
+                    string otherName = (m->getGroups())[l];
+                    if (otherName.length() < 10) { //pad with spaces to make compatible
+                        while (otherName.length() < 10) {  otherName += " ";  }
+                    }
+                    
+                    out  << name << '\t' << otherName << avedists[r][l] << endl;  
+                    outStd  << name << '\t' << otherName << stddists[r][l] << endl; 
+                }
+            }
+        }
+        out.close();
+        outStd.close();
+        
+        return 0;
+    }
+       catch(exception& e) {
+               m->errorOut(e, "UnifracUnweightedCommand", "getAverageSTDMatrices");
+               exit(1);
+       }
+}
+
+/**************************************************************************************************/
+int UnifracUnweightedCommand::getConsensusTrees(vector< vector<double> >& dists, int treeNum) {
+       try {
+        
+        //used in tree constructor 
+        m->runParse = false;
+        
+        //create treemap class from groupmap for tree class to use
+        TreeMap newTmap;
+        newTmap.makeSim(m->getGroups());
+        
+        //clear  old tree names if any
+        m->Treenames.clear();
+        
+        //fills globaldatas tree names
+        m->Treenames = m->getGroups();
+        
+        vector<Tree*> newTrees = buildTrees(dists, treeNum, newTmap); //also creates .all.tre file containing the trees created
+        
+        if (m->control_pressed) { return 0; }
+        
+        Consensus con;
+        Tree* conTree = con.getTree(newTrees);
+        
+        //create a new filename
+        string conFile = outputDir + m->getRootName(m->getSimpleName(treefile)) + toString(treeNum+1) + ".unweighted.cons.tre";                                
+        outputNames.push_back(conFile); outputTypes["tree"].push_back(conFile); 
+        ofstream outTree;
+        m->openOutputFile(conFile, outTree);
+        
+        if (conTree != NULL) { conTree->print(outTree, "boot"); delete conTree; }
+        outTree.close();
+        
+        return 0;
+        
+    }
+       catch(exception& e) {
+               m->errorOut(e, "UnifracUnweightedCommand", "getConsensusTrees");
+               exit(1);
+       }
+}
+/**************************************************************************************************/
+
+vector<Tree*> UnifracUnweightedCommand::buildTrees(vector< vector<double> >& dists, int treeNum, TreeMap& mytmap) {
+       try {
+        
+        vector<Tree*> trees;
+        
+        //create a new filename
+        string outputFile = outputDir + m->getRootName(m->getSimpleName(treefile)) + toString(treeNum+1) + ".unweighted.all.tre";                              
+        outputNames.push_back(outputFile); outputTypes["tree"].push_back(outputFile); 
+        
+        ofstream outAll;
+        m->openOutputFile(outputFile, outAll);
+        
+        
+        for (int i = 0; i < dists.size(); i++) { //dists[0] are the dists for the first subsampled tree.
+            
+            if (m->control_pressed) { break; }
+            
+            //make matrix with scores in it
+            vector< vector<double> > sims;     sims.resize(m->getNumGroups());
+            for (int j = 0; j < m->getNumGroups(); j++) {
+                sims[j].resize(m->getNumGroups(), 0.0);
+            }
+            
+            int count = 0;
+                       for (int r=0; r<m->getNumGroups(); r++) { 
+                               for (int l = 0; l < r; l++) {
+                    double sim = -(dists[i][count]-1.0);
+                                       sims[r][l] = sim;
+                                       sims[l][r] = sim;
+                                       count++;
+                               }
+                       }
+            
+            //create tree
+            Tree* tempTree = new Tree(&mytmap, sims);
+            map<string, string> empty;
+            tempTree->assembleTree(empty);
+            
+            trees.push_back(tempTree);
+            
+            //print tree
+            tempTree->print(outAll);
+        }
+        
+        outAll.close();
+        
+        if (m->control_pressed) {  for (int i = 0; i < trees.size(); i++) {  delete trees[i]; trees[i] = NULL; } m->mothurRemove(outputFile); }
+        
+        return trees;
+    }
+       catch(exception& e) {
+               m->errorOut(e, "UnifracUnweightedCommand", "buildTrees");
+               exit(1);
+       }
+}
+/**************************************************************************************************/
+
+int UnifracUnweightedCommand::runRandomCalcs(Tree* thisTree, vector<double> usersScores) {
+       try {
+        vector<double> randomData; randomData.resize(numComp,0); //weighted score info for random trees. data[0] = weightedscore AB, data[1] = weightedscore AC...
+        
+        Unweighted unweighted(includeRoot);
+        
+        //get unweighted scores for random trees - if random is false iters = 0
+        for (int j = 0; j < iters; j++) {
+            
+            //we need a different getValues because when we swap the labels we only want to swap those in each pairwise comparison
+            randomData = unweighted.getValues(thisTree, "", "", processors, outputDir);
+            
+            if (m->control_pressed) { return 0; }
+                       
+            for(int k = 0; k < numComp; k++) { 
+                //add trees unweighted score to map of scores
+                map<float,float>::iterator it = rscoreFreq[k].find(randomData[k]);
+                if (it != rscoreFreq[k].end()) {//already have that score
+                    rscoreFreq[k][randomData[k]]++;
+                }else{//first time we have seen this score
+                    rscoreFreq[k][randomData[k]] = 1;
+                }
+                               
+                //add randoms score to validscores
+                validScores[randomData[k]] = randomData[k];
+            }
+        }
+        
+        for(int a = 0; a < numComp; a++) {
+            float rcumul = 1.0000;
+    
+            //this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
+            for (map<float,float>::iterator it = validScores.begin(); it != validScores.end(); it++) { 
+                //make rscoreFreq map and rCumul
+                map<float,float>::iterator it2 = rscoreFreq[a].find(it->first);
+                rCumul[a][it->first] = rcumul;
+                //get percentage of random trees with that info
+                if (it2 != rscoreFreq[a].end()) {  rscoreFreq[a][it->first] /= iters; rcumul-= it2->second;  }
+                else { rscoreFreq[a][it->first] = 0.0000; } //no random trees with that score
+            }
+            UWScoreSig[a].push_back(rCumul[a][usersScores[a]]);
+        }
+        
+        return 0;
+       }
+       catch(exception& e) {
+               m->errorOut(e, "UnifracUnweightedCommand", "runRandomCalcs");
+               exit(1);
+       }
+}
 /***********************************************************/
 void UnifracUnweightedCommand::printUnweightedFile() {
        try {
index 8b243964fe4c427768a7c8076f58daf975caa99f..fd39ae43852bee7ad970d77035fa839c50f62422 100644 (file)
@@ -41,25 +41,27 @@ class UnifracUnweightedCommand : public Command {
                TreeMap* tmap;
                string sumFile, allGroups;
                vector<string> groupComb; // AB. AC, BC...
-               int iters, numGroups, numComp, counter, processors, numUniquesInName;
-               EstOutput userData;                     //unweighted score info for user tree
-               EstOutput randomData;           //unweighted score info for random trees
+               int iters, numGroups, numComp, counter, processors, subsampleSize, subsampleIters;
                vector< vector<float> > utreeScores; //scores for users trees for each comb.
                vector< vector<float> > UWScoreSig;  //tree score signifigance when compared to random trees - percentage of random trees with that score or higher.
                map<float, float>  validScores;  //map contains scores from random
                vector< map<float, float> > rscoreFreq;  //map <unweighted score, number of random trees with that score.> -vector entry for each combination.
                vector< map<float, float> > rCumul;  //map <unweighted score, cumulative percentage of number of random trees with that score or higher.> -vector entry for each combination.
                
-               bool abort, phylip, random, includeRoot;
+               bool abort, phylip, random, includeRoot, consensus, subsample;
                string groups, itersString, outputDir, outputForm, treefile, groupfile, namefile;
                vector<string> Groups, outputNames; //holds groups to be used
 
                ofstream outSum, out;
                ifstream inFile;
                
+        int runRandomCalcs(Tree*, vector<double>);
                void printUWSummaryFile(int);
                void printUnweightedFile();
                void createPhylipFile(int);
+        vector<Tree*> buildTrees(vector< vector<double> >&, int, TreeMap&);
+        int getConsensusTrees(vector< vector<double> >&, int);
+        int getAverageSTDMatrices(vector< vector<double> >&, int);
                
 };
 
index ddbdc8548dad7e0545d75f8e98cd92fdb76a3419..9deb065b21da66b0bd83ef50d6d7d457e750025a 100644 (file)
@@ -59,7 +59,7 @@ class UnifracWeightedCommand : public Command {
                bool abort, phylip, random, includeRoot, subsample, consensus;
                string groups, itersString, outputForm, treefile, groupfile, namefile;
                vector<string> Groups, outputNames; //holds groups to be used
-               int processors, numUniquesInName, subsampleSize, subsampleIters;
+               int processors, subsampleSize, subsampleIters;
                ofstream outSum;
                map<string, string> nameMap;