File: mergetaxsummarycommand.cpp

package info (click to toggle)
mothur 1.33.3%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 11,248 kB
  • ctags: 12,231
  • sloc: cpp: 152,046; fortran: 665; makefile: 74; sh: 34
file content (373 lines) | stat: -rw-r--r-- 15,562 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
//
//  mergetaxsummarycommand.cpp
//  Mothur
//
//  Created by Sarah Westcott on 2/13/13.
//  Copyright (c) 2013 Schloss Lab. All rights reserved.
//

#include "mergetaxsummarycommand.h"


//**********************************************************************************************************************
vector<string> MergeTaxSummaryCommand::setParameters(){	
	try {
		CommandParameter pinput("input", "String", "", "", "", "", "","",false,true,true); parameters.push_back(pinput);
		CommandParameter poutput("output", "String", "", "", "", "", "","",false,true,true); parameters.push_back(poutput);
		CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
		CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
		
		vector<string> myArray;
		for (int i = 0; i < parameters.size(); i++) {	myArray.push_back(parameters[i].name);		}
		return myArray;
	}
	catch(exception& e) {
		m->errorOut(e, "MergeTaxSummaryCommand", "setParameters");
		exit(1);
	}
}
//**********************************************************************************************************************
string MergeTaxSummaryCommand::getHelpString(){	
	try {
		string helpString = "";
		helpString += "The merge.taxsummary command takes a list of tax.summary files separated by dashes and merges them into one file."; 
		helpString += "The merge.taxsummary command parameters are input and output."; 
		helpString += "Example merge.taxsummary(input=small.tax.summary-large.tax.summary, output=all.tax.summary).";
		helpString += "Note: No spaces between parameter labels (i.e. output), '=' and parameters (i.e.yourOutputFileName).\n";
		return helpString;
	}
	catch(exception& e) {
		m->errorOut(e, "MergeTaxSummaryCommand", "getHelpString");
		exit(1);
	}
}
//**********************************************************************************************************************
MergeTaxSummaryCommand::MergeTaxSummaryCommand(){	
	try {
		abort = true; calledHelp = true; 
		setParameters();
		vector<string> tempOutNames;
		outputTypes["taxsummary"] = tempOutNames;
	}
	catch(exception& e) {
		m->errorOut(e, "MergeTaxSummaryCommand", "MergeTaxSummaryCommand");
		exit(1);
	}
}
//**********************************************************************************************************************

MergeTaxSummaryCommand::MergeTaxSummaryCommand(string option)  {
	try {
		abort = false; calledHelp = false;   
		
		if(option == "help") { help();  abort = true; calledHelp = true;    }
		else if(option == "citation") { citation(); abort = true; calledHelp = true;   }
		else {
			vector<string> myArray = setParameters();
			
			OptionParser parser(option);
			map<string,string> parameters = parser.getParameters();
			
			ValidParameters validParameter;
			
			//check to make sure all parameters are valid for command
			for (map<string,string>::iterator it = parameters.begin(); it != parameters.end(); it++) { 
				if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
			}
			
			//initialize outputTypes
			vector<string> tempOutNames;
			outputTypes["taxsummary"] = 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);		
			if (inputDir == "not found"){	inputDir = "";		}
			
			string fileList = validParameter.validFile(parameters, "input", false);			
			if(fileList == "not found") { m->mothurOut("you must enter two or more file names"); m->mothurOutEndLine();  abort=true;  }
			else{ 	m->splitAtDash(fileList, fileNames);	}
			
			//if the user changes the output directory command factory will send this info to us in the output parameter 
			string outputDir = validParameter.validFile(parameters, "outputdir", false);		if (outputDir == "not found")	{	outputDir = "";		}
			
			
			numInputFiles = fileNames.size();
			ifstream testFile;
			if(numInputFiles == 0){
				m->mothurOut("you must enter two or more file names and you entered " + toString(fileNames.size()) +  " file names"); m->mothurOutEndLine();
				abort=true;  
			}
			else{
				for(int i=0;i<numInputFiles;i++){
					if (inputDir != "") {
                        string path = m->hasPath(fileNames[i]);
                        //if the user has not given a path then, add inputdir. else leave path alone.
                        if (path == "") {	fileNames[i] = inputDir + fileNames[i];		}
                    }
                    
                    int ableToOpen;
                    ifstream in;
                    ableToOpen = m->openInputFile(fileNames[i], in, "noerror");
                    in.close();	
                    
                    //if you can't open it, try default location
                    if (ableToOpen == 1) {
                        if (m->getDefaultPath() != "") { //default path is set
                            string tryPath = m->getDefaultPath() + m->getSimpleName(fileNames[i]);
                            m->mothurOut("Unable to open " + fileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
                            ifstream in2;
                            ableToOpen = m->openInputFile(tryPath, in2, "noerror");
                            in2.close();
                            fileNames[i] = tryPath;
                        }
                    }
                    
                    //if you can't open it, try output location
                    if (ableToOpen == 1) {
                        if (m->getOutputDir() != "") { //default path is set
                            string tryPath = m->getOutputDir() + m->getSimpleName(fileNames[i]);
                            m->mothurOut("Unable to open " + fileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
                            ifstream in2;
                            ableToOpen = m->openInputFile(tryPath, in2, "noerror");
                            in2.close();
                            fileNames[i] = tryPath;
                        }
                    }
                    
                    
                    
                    if (ableToOpen == 1) { 
                        m->mothurOut("Unable to open " + fileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
                        //erase from file list
                        fileNames.erase(fileNames.begin()+i);
                        i--;
                    }
				}
			}   
			
			outputFileName = validParameter.validFile(parameters, "output", false);			
			if (outputFileName == "not found") { m->mothurOut("you must enter an output file name"); m->mothurOutEndLine();  abort=true;  }
			else if (outputDir != "") { outputFileName = outputDir + m->getSimpleName(outputFileName);   }
            
		}
        
	}
	catch(exception& e) {
		m->errorOut(e, "MergeTaxSummaryCommand", "MergeTaxSummaryCommand");
		exit(1);
	}
}
//**********************************************************************************************************************

int MergeTaxSummaryCommand::execute(){
	try {
		if (abort == true) { if (calledHelp) { return 0; }  return 2;	}
		
        outputFileName = m->getFullPathName(outputFileName);
		m->mothurRemove(outputFileName);
        
        vector<rawTaxNode> tree;
        tree.push_back(rawTaxNode("Root"));
		tree[0].rank = "0";
        bool hasGroups = true;
        set<string> groups;
       
        for (int i = 0; i < fileNames.size(); i++) {
            
            ifstream in;
            m->openInputFile(fileNames[i], in);
            string temp = m->getline(in);
            vector<string> headers = m->splitWhiteSpace(temp);
            
            vector<string> thisFilesGroups;
            if (headers.size() == 5) { hasGroups = false; }
            else {  for (int j = 5; j < headers.size(); j++) { groups.insert(headers[j]); thisFilesGroups.push_back(headers[j]); } }
            
            int level, daugterLevels, total;
            string rankId, tax; 
            map<int, int> levelToCurrentNode;
            levelToCurrentNode[0] = 0;
            while (!in.eof()) {
                
                if (m->control_pressed) {   return 0;  }
                
                in >> level >> rankId >> tax >> daugterLevels >> total; m->gobble(in);
                map<string, int> groupCounts;
                if (thisFilesGroups.size() != 0) {  
                    for (int j = 0; j < thisFilesGroups.size(); j++) {  
                        int tempNum; in >> tempNum; m->gobble(in);
                        groupCounts[thisFilesGroups[j]] = tempNum; 
                    } 
                }
                
                if (level == 0) {}
                else { 
                    map<int, int>::iterator itParent = levelToCurrentNode.find(level-1);
                    int parent = 0;
                    if (itParent == levelToCurrentNode.end()) { m->mothurOut("[ERROR]: situation I didnt expect.\n"); }
                    else { parent = itParent->second; }
                    
                    levelToCurrentNode[level] = addTaxToTree(tree, level, parent, tax, total, groupCounts);
                } 
            }
            in.close();
        }
        
        if (!hasGroups && (groups.size() != 0)) { groups.clear();  m->mothurOut("[WARNING]: not all files contain group breakdown, ignoring group counts.\n");  }
        
        ofstream out;
        m->openOutputFile(outputFileName, out);
        print(out, tree, groups);
        		
		if (m->control_pressed) {  m->mothurRemove(outputFileName); return 0;  }
		
		m->mothurOutEndLine();
		m->mothurOut("Output File Names: "); m->mothurOutEndLine();
		m->mothurOut(outputFileName); m->mothurOutEndLine();	outputNames.push_back(outputFileName); outputTypes["taxsummary"].push_back(outputFileName);
		m->mothurOutEndLine();
        
		return 0;
	}
	catch(exception& e) {
		m->errorOut(e, "MergeTaxSummaryCommand", "execute");
		exit(1);
	}
}
/**************************************************************************************************/

int MergeTaxSummaryCommand::addTaxToTree(vector<rawTaxNode>& tree, int level, int currentNode, string taxon, int total, map<string, int> groups){
	try {
		map<string, int>::iterator childPointer;
		
        childPointer = tree[currentNode].children.find(taxon);
        int nodeToIncrement = 0;
			
        if(childPointer != tree[currentNode].children.end()){	//if the node already exists, increment counts
            nodeToIncrement = childPointer->second;
            tree[nodeToIncrement].total += total;
            
            for (map<string, int>::iterator itGroups = groups.begin(); itGroups != groups.end(); itGroups++) {
                map<string, int>::iterator it = tree[nodeToIncrement].groupCount.find(itGroups->first);
                if (it == tree[nodeToIncrement].groupCount.end()) { tree[nodeToIncrement].groupCount[itGroups->first] = itGroups->second; }
                else {   it->second += itGroups->second;  }
            }
        }
        else{											//otherwise, create it
            tree.push_back(rawTaxNode(taxon));
            tree[currentNode].children[taxon] = tree.size()-1;
            tree[tree.size()-1].parent = currentNode;
            nodeToIncrement = tree.size()-1;
            tree[nodeToIncrement].total = total;
            tree[nodeToIncrement].level = level;
            for (map<string, int>::iterator itGroups = groups.begin(); itGroups != groups.end(); itGroups++) {
                 tree[nodeToIncrement].groupCount[itGroups->first] = itGroups->second; 
            }
        }
        
 		return nodeToIncrement;
	}
	catch(exception& e) {
		m->errorOut(e, "MergeTaxSummaryCommand", "addSeqToTree");
		exit(1);
	}
}
/**************************************************************************************************/

int MergeTaxSummaryCommand::assignRank(int index, vector<rawTaxNode>& tree){
	try {
		map<string,int>::iterator it;
		int counter = 1;
		
		for(it=tree[index].children.begin();it!=tree[index].children.end();it++){
            if (m->control_pressed) { return 0; }
			tree[it->second].rank = tree[index].rank + '.' + toString(counter);
			counter++;
            
			assignRank(it->second, tree);
		}
        
        return 0;
	}
	catch(exception& e) {
		m->errorOut(e, "MergeTaxSummaryCommand", "assignRank");
		exit(1);
	}
}
/**************************************************************************************************/

int MergeTaxSummaryCommand::print(ofstream& out, vector<rawTaxNode>& tree, set<string> groups){
	try {
		
		assignRank(0, tree); 
        vector<string> mGroups;
		//print labels
		out << "taxlevel\t rankID\t taxon\t daughterlevels\t total\t";
		for (set<string>::iterator it = groups.begin(); it != groups.end(); it++) { out << (*it) << '\t'; }		
		out << endl;
        
        for (set<string>::iterator it2 = groups.begin(); it2 != groups.end(); it2++) {  tree[0].groupCount[*it2] = 0;  }
            
        map<string,int>::iterator it;
		for(it=tree[0].children.begin();it!=tree[0].children.end();it++){   
            tree[0].total += tree[it->second].total;
			for (set<string>::iterator it2 = groups.begin(); it2 != groups.end(); it2++) { 
                map<string, int>:: iterator itGroups = tree[it->second].groupCount.find(*it2);
                if (itGroups != tree[it->second].groupCount.end()) { 
                    tree[0].groupCount[*it2] += itGroups->second;
                }
            }
		}

		
		//print root
		out << tree[0].level << "\t" << tree[0].rank << "\t" << tree[0].name << "\t" << tree[0].children.size() << "\t" << tree[0].total << "\t";
		
        for (set<string>::iterator it = groups.begin(); it != groups.end(); it++) { 
            map<string, int>:: iterator itGroups = tree[0].groupCount.find(*it);
            int num = 0;
            if (itGroups != tree[0].groupCount.end()) { num = itGroups->second; }
            out << num << '\t';
        }
        out << endl;
		
		//print rest
		print(0, out, tree, groups);
        
        return 0;
		
	}
	catch(exception& e) {
		m->errorOut(e, "MergeTaxSummaryCommand", "print");
		exit(1);
	}
}
/**************************************************************************************************/
int MergeTaxSummaryCommand::print(int i, ofstream& out, vector<rawTaxNode>& tree, set<string> groups){
	try {
		map<string,int>::iterator it;
		for(it=tree[i].children.begin();it!=tree[i].children.end();it++){
			
            //print root
            out << tree[it->second].level << "\t" << tree[it->second].rank << "\t" << tree[it->second].name << "\t" << tree[it->second].children.size() << "\t" << tree[it->second].total << "\t";
            
            for (set<string>::iterator it2 = groups.begin(); it2 != groups.end(); it2++) { 
                map<string, int>:: iterator itGroups = tree[it->second].groupCount.find(*it2);
                int num = 0;
                if (itGroups != tree[it->second].groupCount.end()) { num = itGroups->second; }
                out << num << '\t';
            }
            out << endl;

			print(it->second, out, tree, groups);
		}
        
        return 0;
	}
	catch(exception& e) {
		m->errorOut(e, "MergeTaxSummaryCommand", "print");
		exit(1);
	}
}
//**********************************************************************************************************************