]> git.donarmstrong.com Git - mothur.git/blobdiff - unifracweightedcommand.cpp
added subsample and consensus parameters to unifrac.weighted command
[mothur.git] / unifracweightedcommand.cpp
index b3a54c929ace3221fe3ba736a3b5fad7f87818f9..e596db230ee24d80597cfa903a49ed9ee6a7f25b 100644 (file)
@@ -8,6 +8,8 @@
  */
 
 #include "unifracweightedcommand.h"
+#include "consensus.h"
+#include "subsample.h"
 
 //**********************************************************************************************************************
 vector<string> UnifracWeightedCommand::setParameters(){        
@@ -18,7 +20,9 @@ vector<string> UnifracWeightedCommand::setParameters(){
                CommandParameter pgroups("groups", "String", "", "", "", "", "",false,false); parameters.push_back(pgroups);
                CommandParameter piters("iters", "Number", "", "1000", "", "", "",false,false); parameters.push_back(piters);
                CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
-               CommandParameter prandom("random", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(prandom);
+        CommandParameter psubsample("subsample", "String", "", "", "", "", "",false,false); parameters.push_back(psubsample);
+        CommandParameter pconsensus("consensus", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(pconsensus);
+        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 pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
@@ -37,14 +41,16 @@ vector<string> UnifracWeightedCommand::setParameters(){
 string UnifracWeightedCommand::getHelpString(){        
        try {
                string helpString = "";
-               helpString += "The unifrac.weighted command parameters are tree, group, name, groups, iters, distance, processors, root and random.  tree parameter is required unless you have valid current tree file.\n";
+               helpString += "The unifrac.weighted command parameters are tree, group, name, groups, iters, distance, processors, root, subsample, consensus and random.  tree parameter is required unless you have valid current tree file.\n";
                helpString += "The groups parameter allows you to specify which of the groups in your groupfile you would like analyzed.  You must enter at least 2 valid groups.\n";
                helpString += "The group names are separated by dashes.  The iters parameter allows you to specify how many random trees you would like compared to your tree.\n";
                helpString += "The distance parameter allows you to create a distance file from the results. The default is false.\n";
                helpString += "The random parameter allows you to shut off the comparison to random trees. The default is false, meaning don't compare your trees with randomly generated trees.\n";
                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.weighted command should be in the following format: unifrac.weighted(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, as well as a consensus tree built from these trees. Default=F.\n";
+        helpString += "The unifrac.weighted command should be in the following format: unifrac.weighted(groups=yourGroups, iters=yourIters).\n";
                helpString += "Example unifrac.weighted(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.weighted command output two files: .weighted and .wsummary their descriptions are in the manual.\n";
@@ -66,6 +72,7 @@ UnifracWeightedCommand::UnifracWeightedCommand(){
                outputTypes["wsummary"] = tempOutNames;
                outputTypes["phylip"] = tempOutNames;
                outputTypes["column"] = tempOutNames;
+        outputTypes["tree"] = tempOutNames;
        }
        catch(exception& e) {
                m->errorOut(e, "UnifracWeightedCommand", "UnifracWeightedCommand");
@@ -102,6 +109,7 @@ UnifracWeightedCommand::UnifracWeightedCommand(string option) {
                        outputTypes["wsummary"] = 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);              
@@ -159,7 +167,7 @@ UnifracWeightedCommand::UnifracWeightedCommand(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
@@ -190,9 +198,25 @@ UnifracWeightedCommand::UnifracWeightedCommand(string option) {
                        temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = m->getProcessors();      }
                        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 (!random) {  iters = 0;  } //turn off random calcs
-                       
+            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 (namefile == "") {
                                vector<string> files; files.push_back(treefile);
                                parser.getNameFile(files);
@@ -214,7 +238,389 @@ int UnifracWeightedCommand::execute() {
                
                m->setTreeFile(treefile);
                
-               if (groupfile != "") {
+        readTrees();  if (m->control_pressed) {  delete tmap; for (int i = 0; i < T.size(); i++) { delete T[i]; } return 0; }
+                               
+               sumFile = outputDir + m->getSimpleName(treefile) + ".wsummary";
+               m->openOutputFile(sumFile, outSum);
+               outputNames.push_back(sumFile);  outputTypes["wsummary"].push_back(sumFile);
+               
+        SharedUtil util;
+               string s; //to make work with setgroups
+               Groups = m->getGroups();
+               vector<string> nameGroups = tmap->getNamesOfGroups();
+               util.setGroups(Groups, nameGroups, s, numGroups, "weighted");   //sets the groups the user wants to analyze
+               m->setGroups(Groups);
+               
+        if (m->control_pressed) {  delete tmap; for (int i = 0; i < T.size(); i++) { delete T[i]; } return 0; }
+        
+               Weighted weighted(tmap, includeRoot);
+                       
+               int start = time(NULL);
+            
+        //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);
+            }
+        }
+        
+        //here in case some groups are removed by subsample
+        util.getCombos(groupComb, Groups, numComp);
+        
+        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; }
+        
+        //get weighted scores 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; }
+            
+            counter = 0;
+            rScores.resize(numComp);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
+            uScores.resize(numComp);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
+            
+            vector<double> userData; userData.resize(numComp,0);  //weighted score info for user tree. data[0] = weightedscore AB, data[1] = weightedscore AC...
+            vector<double> randomData; randomData.resize(numComp,0); //weighted score info for random trees. data[0] = weightedscore AB, data[1] = weightedscore AC...
+            
+            if (random) {  
+                output = new ColumnFile(outputDir + m->getSimpleName(treefile)  + toString(i+1) + ".weighted", itersString);  
+                outputNames.push_back(outputDir + m->getSimpleName(treefile)  + toString(i+1) + ".weighted");
+                outputTypes["weighted"].push_back(outputDir + m->getSimpleName(treefile)  + toString(i+1) + ".weighted");
+            } 
+            
+            userData = weighted.getValues(T[i], processors, outputDir); //userData[0] = weightedscore
+            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; }
+            
+            //save users score
+            for (int s=0; s<numComp; s++) {
+                //add users score to vector of user scores
+                uScores[s].push_back(userData[s]);
+                //save users tree score for summary file
+                utreeScores.push_back(userData[s]);
+            }
+            
+            if (random) {  runRandomCalcs(T[i], userData); }
+            
+            //clear data
+            rScores.clear();
+            uScores.clear();
+            validScores.clear();
+            
+            //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 tree needs it and 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);
+                Weighted thisWeighted(newTmap, includeRoot);
+                iterData = thisWeighted.getValues(subSampleTree, processors, outputDir); //userData[0] = weightedscore
+                
+                //save data to make ave dist, std dist
+                calcDistsTotals.push_back(iterData);
+                
+                delete newTmap;
+                delete subSampleTree;
+            }
+            
+            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);  }
+        }
+        
+               
+               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 (phylip) {  createPhylipFile();             }
+    
+               printWSummaryFile();
+               
+               //clear out users groups
+               m->clearGroups();
+               delete tmap; 
+               for (int i = 0; i < T.size(); i++) { delete T[i]; }
+               
+               if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]);  } return 0; }
+               
+               m->mothurOut("It took " + toString(time(NULL) - start) + " secs to run unifrac.weighted."); m->mothurOutEndLine();
+               
+               //set phylip file as new current phylipfile
+               string current = "";
+               itTypes = outputTypes.find("phylip");
+               if (itTypes != outputTypes.end()) {
+                       if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setPhylipFile(current); }
+               }
+               
+               //set column file as new current columnfile
+               itTypes = outputTypes.find("column");
+               if (itTypes != outputTypes.end()) {
+                       if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setColumnFile(current); }
+               }
+               
+               m->mothurOutEndLine();
+               m->mothurOut("Output File Names: "); m->mothurOutEndLine();
+               for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
+               m->mothurOutEndLine();
+               
+               return 0;
+               
+       }
+       catch(exception& e) {
+               m->errorOut(e, "UnifracWeightedCommand", "execute");
+               exit(1);
+       }
+}
+/**************************************************************************************************/
+int UnifracWeightedCommand::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) + ".weighted.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) + ".weighted.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, "UnifracWeightedCommand", "getAverageSTDMatrices");
+               exit(1);
+       }
+}
+
+/**************************************************************************************************/
+int UnifracWeightedCommand::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 = new TreeMap();
+        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) { delete newTmap; return 0; }
+        
+        Consensus con;
+        Tree* conTree = con.getTree(newTrees, newTmap);
+        
+        //create a new filename
+        string conFile = outputDir + m->getRootName(m->getSimpleName(treefile)) + toString(treeNum+1) + ".weighted.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();
+        delete newTmap;
+        
+        return 0;
+
+    }
+       catch(exception& e) {
+               m->errorOut(e, "UnifracWeightedCommand", "getConsensusTrees");
+               exit(1);
+       }
+}
+/**************************************************************************************************/
+
+vector<Tree*> UnifracWeightedCommand::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) + ".weighted.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);
+            tempTree->assembleTree();
+            
+            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, "UnifracWeightedCommand", "buildTrees");
+               exit(1);
+       }
+}
+/**************************************************************************************************/
+
+int UnifracWeightedCommand::readTrees() {
+       try {
+        
+        if (groupfile != "") {
                        //read in group map info.
                        tmap = new TreeMap(groupfile);
                        tmap->readMap();
@@ -275,183 +681,91 @@ int UnifracWeightedCommand::execute() {
                                }
                        }
                }
-               
-               sumFile = outputDir + m->getSimpleName(treefile) + ".wsummary";
-               m->openOutputFile(sumFile, outSum);
-               outputNames.push_back(sumFile);  outputTypes["wsummary"].push_back(sumFile);
-                       
-               util = new SharedUtil();
-               string s; //to make work with setgroups
-               Groups = m->getGroups();
-               vector<string> nameGroups = tmap->getNamesOfGroups();
-               util->setGroups(Groups, nameGroups, s, numGroups, "weighted");  //sets the groups the user wants to analyze
-               util->getCombos(groupComb, Groups, numComp);
-               m->setGroups(Groups);
-               delete util;
-               
-               weighted = new Weighted(tmap, includeRoot);
-                       
-               int start = time(NULL);
-               
-               //get weighted for users tree
-               userData.resize(numComp,0);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
-               randomData.resize(numComp,0); //data[0] = weightedscore AB, data[1] = weightedscore AC...
-               
-               if (numComp < processors) { processors = numComp; }
-                               
-               //get weighted scores for users trees
-               for (int i = 0; i < T.size(); i++) {
-                       
-                       if (m->control_pressed) { delete tmap; delete weighted;
-                               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;
-                       rScores.resize(numComp);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
-                       uScores.resize(numComp);  //data[0] = weightedscore AB, data[1] = weightedscore AC...
-                       
-                       if (random) {  
-                               output = new ColumnFile(outputDir + m->getSimpleName(treefile)  + toString(i+1) + ".weighted", itersString);  
-                               outputNames.push_back(outputDir + m->getSimpleName(treefile)  + toString(i+1) + ".weighted");
-                               outputTypes["weighted"].push_back(outputDir + m->getSimpleName(treefile)  + toString(i+1) + ".weighted");
-                       } 
-
-                       userData = weighted->getValues(T[i], processors, outputDir);  //userData[0] = weightedscore
-                       
-                       if (m->control_pressed) { delete tmap; delete weighted;
-                               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; }
-                       
-                       //save users score
-                       for (int s=0; s<numComp; s++) {
-                               //add users score to vector of user scores
-                               uScores[s].push_back(userData[s]);
-                               
-                               //save users tree score for summary file
-                               utreeScores.push_back(userData[s]);
-                       }
-                       
-                       if (random) { 
-                       
-                               //calculate number of comparisons i.e. with groups A,B,C = AB, AC, BC = 3;
-                               vector< vector<string> > namesOfGroupCombos;
-                               for (int a=0; a<numGroups; a++) { 
-                                       for (int l = 0; l < a; l++) {   
-                                               vector<string> groups; groups.push_back((m->getGroups())[a]); groups.push_back((m->getGroups())[l]);
-                                               namesOfGroupCombos.push_back(groups);
-                                       }
-                               }
-                               
-                               lines.clear();
-                               
-                               #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
-                                       if(processors != 1){
-                                               int numPairs = namesOfGroupCombos.size();
-                                               int numPairsPerProcessor = numPairs / processors;
-                                       
-                                               for (int i = 0; i < processors; i++) {
-                                                       int startPos = i * numPairsPerProcessor;
-                                                       if(i == processors - 1){
-                                                               numPairsPerProcessor = numPairs - i * numPairsPerProcessor;
-                                                       }
-                                                       lines.push_back(linePair(startPos, numPairsPerProcessor));
-                                               }
-                                       }
-                               #endif
 
-                               
-                               //get scores for random trees
-                               for (int j = 0; j < iters; j++) {
-                               
-                                       #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
-                                               if(processors == 1){
-                                                       driver(T[i],  namesOfGroupCombos, 0, namesOfGroupCombos.size(),  rScores);
-                                               }else{
-                                                       createProcesses(T[i],  namesOfGroupCombos, rScores);
-                                               }
-                                       #else
-                                               driver(T[i], namesOfGroupCombos, 0, namesOfGroupCombos.size(), rScores);
-                                       #endif
-                                       
-                                       if (m->control_pressed) { delete tmap; delete weighted;
-                                               for (int i = 0; i < T.size(); i++) { delete T[i]; } delete output; outSum.close(); for (int i = 0; i < outputNames.size(); i++) {       m->mothurRemove(outputNames[i]);  } return 0; }
-                                       
-                                       //report progress
-//                                     m->mothurOut("Iter: " + toString(j+1)); m->mothurOutEndLine();          
-                               }
-                               lines.clear();
-                       
-                               //find the signifigance of the score for summary file
-                               for (int f = 0; f < numComp; f++) {
-                                       //sort random scores
-                                       sort(rScores[f].begin(), rScores[f].end());
-                                       
-                                       //the index of the score higher than yours is returned 
-                                       //so if you have 1000 random trees the index returned is 100 
-                                       //then there are 900 trees with a score greater then you. 
-                                       //giving you a signifigance of 0.900
-                                       int index = findIndex(userData[f], f);    if (index == -1) { m->mothurOut("error in UnifracWeightedCommand"); m->mothurOutEndLine(); exit(1); } //error code
-                                       
-                                       //the signifigance is the number of trees with the users score or higher 
-                                       WScoreSig.push_back((iters-index)/(float)iters);
-                               }
-                               
-                               //out << "Tree# " << i << endl;
-                               calculateFreqsCumuls();
-                               printWeightedFile();
-                               
-                               delete output;
-                       
-                       }
-                       
-                       //clear data
-                       rScores.clear();
-                       uScores.clear();
-                       validScores.clear();
-               }
-               
-               
-               if (m->control_pressed) { delete tmap; delete weighted;
-                       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;  }
-               
-               printWSummaryFile();
-               
-               if (phylip) {   createPhylipFile();             }
-
-               //clear out users groups
-               m->clearGroups();
-               delete tmap; delete weighted;
-               for (int i = 0; i < T.size(); i++) { delete T[i]; }
-               
-               
-               if (m->control_pressed) { 
-                       for (int i = 0; i < outputNames.size(); i++) {  m->mothurRemove(outputNames[i]);  }
-                       return 0; 
-               }
-               
-               m->mothurOut("It took " + toString(time(NULL) - start) + " secs to run unifrac.weighted."); m->mothurOutEndLine();
-               
-               //set phylip file as new current phylipfile
-               string current = "";
-               itTypes = outputTypes.find("phylip");
-               if (itTypes != outputTypes.end()) {
-                       if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setPhylipFile(current); }
-               }
-               
-               //set column file as new current columnfile
-               itTypes = outputTypes.find("column");
-               if (itTypes != outputTypes.end()) {
-                       if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setColumnFile(current); }
-               }
-               
-               m->mothurOutEndLine();
-               m->mothurOut("Output File Names: "); m->mothurOutEndLine();
-               for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
-               m->mothurOutEndLine();
-               
-               return 0;
-               
+        return 0;
+    }
+       catch(exception& e) {
+               m->errorOut(e, "UnifracWeightedCommand", "readTrees");
+               exit(1);
        }
+}
+/**************************************************************************************************/
+
+int UnifracWeightedCommand::runRandomCalcs(Tree* thisTree, vector<double> usersScores) {
+       try {
+        
+        //calculate number of comparisons i.e. with groups A,B,C = AB, AC, BC = 3;
+        vector< vector<string> > namesOfGroupCombos;
+        for (int a=0; a<numGroups; a++) { 
+            for (int l = 0; l < a; l++) {      
+                vector<string> groups; groups.push_back((m->getGroups())[a]); groups.push_back((m->getGroups())[l]);
+                namesOfGroupCombos.push_back(groups);
+            }
+        }
+        
+        lines.clear();
+        
+#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
+        if(processors != 1){
+            int numPairs = namesOfGroupCombos.size();
+            int numPairsPerProcessor = numPairs / processors;
+            
+            for (int i = 0; i < processors; i++) {
+                int startPos = i * numPairsPerProcessor;
+                if(i == processors - 1){
+                    numPairsPerProcessor = numPairs - i * numPairsPerProcessor;
+                }
+                lines.push_back(linePair(startPos, numPairsPerProcessor));
+            }
+        }
+#endif
+        
+        
+        //get scores for random trees
+        for (int j = 0; j < iters; j++) {
+            
+#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
+            if(processors == 1){
+                driver(thisTree,  namesOfGroupCombos, 0, namesOfGroupCombos.size(),  rScores);
+            }else{
+                createProcesses(thisTree,  namesOfGroupCombos, rScores);
+            }
+#else
+            driver(T[i], namesOfGroupCombos, 0, namesOfGroupCombos.size(), rScores);
+#endif
+            
+            if (m->control_pressed) { delete tmap;  for (int i = 0; i < T.size(); i++) { delete T[i]; } delete output; outSum.close(); for (int i = 0; i < outputNames.size(); i++) {  m->mothurRemove(outputNames[i]);  } return 0; }
+            
+            //report progress
+            //                                 m->mothurOut("Iter: " + toString(j+1)); m->mothurOutEndLine();          
+        }
+        lines.clear();
+        
+        //find the signifigance of the score for summary file
+        for (int f = 0; f < numComp; f++) {
+            //sort random scores
+            sort(rScores[f].begin(), rScores[f].end());
+            
+            //the index of the score higher than yours is returned 
+            //so if you have 1000 random trees the index returned is 100 
+            //then there are 900 trees with a score greater then you. 
+            //giving you a signifigance of 0.900
+            int index = findIndex(usersScores[f], f);    if (index == -1) { m->mothurOut("error in UnifracWeightedCommand"); m->mothurOutEndLine(); exit(1); } //error code
+            
+            //the signifigance is the number of trees with the users score or higher 
+            WScoreSig.push_back((iters-index)/(float)iters);
+        }
+        
+        //out << "Tree# " << i << endl;
+        calculateFreqsCumuls();
+        printWeightedFile();
+        
+        delete output;
+        
+        return 0;
+    }
        catch(exception& e) {
-               m->errorOut(e, "UnifracWeightedCommand", "execute");
+               m->errorOut(e, "UnifracWeightedCommand", "runRandomCalcs");
                exit(1);
        }
 }
@@ -524,7 +838,9 @@ int UnifracWeightedCommand::createProcesses(Tree* t, vector< vector<string> > na
 int UnifracWeightedCommand::driver(Tree* t, vector< vector<string> > namesOfGroupCombos, int start, int num, vector< vector<double> >& scores) { 
  try {
                Tree* randT = new Tree(tmap);
-
+     
+        Weighted weighted(tmap, includeRoot);
+     
                for (int h = start; h < (start+num); h++) {
        
                        if (m->control_pressed) { return 0; }
@@ -542,7 +858,7 @@ int UnifracWeightedCommand::driver(Tree* t, vector< vector<string> > namesOfGrou
                        if (m->control_pressed) { delete randT;  return 0;  }
 
                        //get wscore of random tree
-                       EstOutput randomData = weighted->getValues(randT, groupA, groupB);
+                       EstOutput randomData = weighted.getValues(randT, groupA, groupB);
                
                        if (m->control_pressed) { delete randT;  return 0;  }
                                                                                
@@ -789,7 +1105,7 @@ int UnifracWeightedCommand::readNamesFile() {
                                m->splitAtComma(second, dupNames);
                                
                                for (int i = 0; i < dupNames.size(); i++) {     
-                                       nameMap[dupNames[i]] = dupNames[i]
+                                       nameMap[dupNames[i]] = first
                                        if ((groupfile == "") && (i != 0)) { tmap->addSeq(dupNames[i], "Group1"); } 
                                }
                        }else {  m->mothurOut(first + " has already been seen in namefile, disregarding names file."); m->mothurOutEndLine(); in.close(); m->names.clear(); namefile = ""; return 1; }