File: mergefilecommand.cpp

package info (click to toggle)
mothur 1.48.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 13,692 kB
  • sloc: cpp: 161,866; makefile: 122; sh: 31
file content (264 lines) | stat: -rwxr-xr-x 13,056 bytes parent folder | download | duplicates (2)
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
/*
 *  mergefilecommand.cpp
 *  Mothur
 *
 *  Created by Pat Schloss on 6/14/09.
 *  Copyright 2009 Patrick D. Schloss. All rights reserved.
 *
 */

#include "mergefilecommand.h"

//**********************************************************************************************************************
vector<string> MergeFileCommand::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 pseed("seed", "Number", "", "0", "", "", "","",false,false); parameters.push_back(pseed);
        CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
		CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
        CommandParameter ptaxonomy("taxonomy", "", "", "", "none", "none", "none","",false,true,true); parameters.push_back(ptaxonomy);
        CommandParameter pfasta("fasta", "", "", "", "none", "none", "none","taxonomy",false,true,true); parameters.push_back(pfasta);
        CommandParameter pname("name", "InputTypes", "", "", "NameCount", "none", "none","",false,false,true); parameters.push_back(pname);
        CommandParameter pcount("count", "InputTypes", "", "", "NameCount-CountGroup", "none", "none","",false,false,true); parameters.push_back(pcount);
        
        abort = false; calledHelp = false;   appendMode = true;
        
        vector<string> tempOutNames;
        outputTypes["merge"] = tempOutNames;
        outputTypes["fasta"] = tempOutNames;

		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, "MergeFileCommand", "setParameters");
		exit(1);
	}
}
//**********************************************************************************************************************
string MergeFileCommand::getHelpString(){	
	try {
		string helpString = "";
        helpString += "The merge.file command takes a list of files separated by dashes and appends them into one file. Altternatively, the merge file command can combine the data of several files. For example, you can combine a fasta, taxonomy and name or count field to achieve outputs like: GQY1XT001C44N8 3677 Bacteria;Bacteroidetes;Bacteroidia;Bacteroidales;Porphyromonadaceae;Porphyromonadaceae_unclassified; C-G--T-T--GA-A-A-C-T-G-G--CG-T-T-C--T-T-G-A-G-T-G-G-GC-GA-G-A-A-G-T-A--TG-C-GG-A-ATG-C-G-T-G-GT-GT-A-G-CGGT-G-AAA--...";
		helpString += "The merge.file command parameters are input and output or fasta, taxonomy, name and count.";
		helpString += "Example merge.file(input=small.fasta-large.fasta, output=all.fasta).";
        helpString += "Example merge.file(fasta=final.fasta, name=final.names, taxonomy=final.taxonomy).";
		return helpString;
	}
	catch(exception& e) {
		m->errorOut(e, "MergeFileCommand", "getHelpString");
		exit(1);
	}
}
//**********************************************************************************************************************
string MergeFileCommand::getOutputPattern(string type) {
    try {
        string pattern = "";
        
        if (type == "fasta") {  pattern = "[filename],merged,[extension]"; }
        else if (type == "merge") { pattern = ""; }
        else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->setControl_pressed(true);  }
        
        return pattern;
    }
    catch(exception& e) {
        m->errorOut(e, "MergeFileCommand", "getOutputPattern");
        exit(1);
    }
}
//**********************************************************************************************************************
MergeFileCommand::MergeFileCommand(string option) : Command()  {
	try {
 		if(option == "help") { help(); abort = true; calledHelp = true; }
        else if(option == "citation") { citation(); abort = true; calledHelp = true;}
        else if(option == "category") {  abort = true; calledHelp = true;  }
		else {
			OptionParser parser(option, setParameters());
			map<string,string> parameters = parser.getParameters();
			
			ValidParameters validParameter;

            string inputDir = validParameter.validPath(parameters, "inputdir");
            if (inputDir == "not found"){    inputDir = "";        }
            
			string fileList = validParameter.validPath(parameters, "input");
            if(fileList == "not found") { appendMode = false; fileList = "";  }
			else{ 	util.splitAtDash(fileList, fileNames);	}
            
            outputFileName = validParameter.validPath(parameters, "output");
            if (outputFileName == "not found") { appendMode = false; outputFileName = "";   }

            fastafile = validParameter.validFile(parameters, "fasta");
            if (fastafile == "not open") { fastafile = ""; abort = true; }
            else if (fastafile == "not found") {  fastafile = "";  }
            else { current->setFastaFile(fastafile); appendMode = false; }
            
            namefile = validParameter.validFile(parameters, "name");
            if (namefile == "not open") { namefile = ""; abort = true; }
            else if (namefile == "not found") {  namefile = "";  }
            else { current->setNameFile(namefile); appendMode = false; }
            
            taxfile = validParameter.validFile(parameters, "taxonomy");
            if (taxfile == "not open") { taxfile = ""; abort = true; }
            else if (taxfile == "not found") {  taxfile = "";  }
            else { current->setTaxonomyFile(taxfile); appendMode = false; }
            
            countfile = validParameter.validFile(parameters, "count");
            if (countfile == "not open") { countfile = ""; abort = true; }
            else if (countfile == "not found") { countfile = "";  }	
            else { current->setCountFile(countfile); appendMode = false; }
            
            if (!appendMode) { //if you are not appending, fasta is required as well as at least one of taxonomy, name or count
                if (fastafile == "") { //look for current
                    fastafile = current->getFastaFile();
                    if (fastafile != "") {  m->mothurOut("Using " + fastafile + " as input file for the fasta parameter.\n");  }
                    else { 	m->mothurOut("[ERROR]: You have no current fastafile and the fasta parameter is required.\n"); abort = true; }
                }
                
                if ((namefile == "") && (countfile == "") && (taxfile == "")) {
                    taxfile = current->getTaxonomyFile();
                    if (taxfile != "") {  m->mothurOut("Using " + taxfile + " as input file for the taxonomy parameter.\n");  }
                    else {
                        countfile = current->getCountFile();
                        if (countfile != "") {  m->mothurOut("Using " + countfile + " as input file for the count parameter.\n");  }
                        else {
                            namefile = current->getNameFile();
                            if (namefile != "") {  m->mothurOut("Using " + namefile + " as input file for the name parameter.\n");  }
                            else { m->mothurOut("[ERROR]: You have no current taxonomy, name or count files. At least one is required. \n"); abort = true; }
                        }
                    }
                }
                
                if ((namefile != "") && (countfile != "")) {
                    m->mothurOut("[ERROR]: you may only use one of the following: name or count.\n"); abort = true;
                }
            }else {
                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\n"); abort=true; }
                else{
                    for(int i=0;i<numInputFiles;i++){
                        string path = util.hasPath(fileNames[i]);
                        if (inputDir != "") {
                            //if the user has not given a path then, add inputdir. else leave path alone.
                            if (path == "") { fileNames[i] = inputDir + fileNames[i]; }
                        }
                        
                        if (util.checkLocations(fileNames[i], current->getLocations())) { }
                        else { fileNames.erase(fileNames.begin()+i); i--; } //erase from file list
                        
                        path = util.hasPath(fileNames[i]);
                        if (path != "") { if (outputdir == "") { outputdir = path; } }
                    }
                    if (outputdir != "") { outputFileName = outputdir + util.getSimpleName(outputFileName);  }
                }
            }
			
        }
			
	}
	catch(exception& e) {
		m->errorOut(e, "MergeFileCommand", "MergeFileCommand");
		exit(1);
	}
}
//**********************************************************************************************************************

int MergeFileCommand::execute(){
	try {
		if (abort) { if (calledHelp) { return 0; }  return 2;	}
		
        if (appendMode) {
            util.mothurRemove(outputFileName);
            for(int i=0;i<numInputFiles;i++){  util.appendFiles(fileNames[i], outputFileName);  }
            outputNames.push_back(outputFileName); outputTypes["merge"].push_back(outputFileName);
        }else { outputFileName = mergeFileData(); }
		
        if (m->getControl_pressed()) {  util.mothurRemove(outputFileName); return 0;  }
        
        //set taxonomy file as new current taxonomyfile
        string currentName = "";
        itTypes = outputTypes.find("fasta");
        if (itTypes != outputTypes.end()) { if ((itTypes->second).size() != 0) { currentName = (itTypes->second)[0]; current->setFastaFile(currentName); } }

        
		m->mothurOut("\nOutput File Names: \n"); 
		m->mothurOut(outputFileName); m->mothurOutEndLine();
		m->mothurOutEndLine();

		return 0;
	}
	catch(exception& e) {
		m->errorOut(e, "MergeFileCommand", "execute");
		exit(1);
	}
}
//**********************************************************************************************************************

string MergeFileCommand::mergeFileData(){
    try {
        string thisOutputDir = outputdir;
        if (outputdir == "") {  thisOutputDir += util.hasPath(fastafile);  }
        map<string, string> variables;
        variables["[filename]"] = thisOutputDir + util.getRootName(util.getSimpleName(fastafile));
        variables["[extension]"] = util.getExtension(fastafile);
        outputFileName = getOutputFileName("fasta", variables);
        ofstream out;
        util.openOutputFile(outputFileName, out);
        
        //extract seq counts from name or count file
        map<string, int> nameMap; map<string, int>::iterator itCount;
        bool useNameMap = true;
        if (countfile != "") {
            CountTable ct; ct.readTable(countfile, false, false);
            nameMap = ct.getNameMap();
        }else if (namefile != "") {
            nameMap = util.readNames(namefile);
        }else { useNameMap = false;  }
        
        map<string, string> taxMap; map<string, string>::iterator itTax;
        bool useTax = false;
        if (taxfile != "") {  util.readTax(taxfile, taxMap, false);  useTax = true;  }
        
        ifstream in; util.openInputFile(fastafile, in);

        while(!in.eof()){
            
            if (m->getControl_pressed()) { break; }
            
            Sequence currSeq(in); gobble(in);
            
            string comment = " ";
            
            if (useNameMap) {
                itCount = nameMap.find(currSeq.getName());
                if (itCount != nameMap.end()) {
                    comment += toString(itCount->second) + " ";
                    nameMap.erase(itCount);
                }else { m->mothurOut("[ERROR]: Missing count data for " + currSeq.getName() + ", please correct.\n"); m->setControl_pressed(true); }
            }
            
            
            if (useTax) {
                itTax = taxMap.find(currSeq.getName());
                if (itTax != taxMap.end()) {
                    comment += itTax->second;
                    taxMap.erase(itTax);
                }else { m->mothurOut("[ERROR]: Missing taxonomy for " + currSeq.getName() + ", please correct.\n"); m->setControl_pressed(true); }
            }
            
            currSeq.setComment(comment);
            currSeq.printSequence(out);
        }
        in.close(); out.close();
        
        return outputFileName;
    }
    catch(exception& e) {
        m->errorOut(e, "MergeFileCommand", "mergeFileData");
        exit(1);
    }
}
//**********************************************************************************************************************