2 * summaryqualcommand.cpp
5 * Created by westcott on 11/28/11.
6 * Copyright 2011 Schloss Lab. All rights reserved.
10 #include "summaryqualcommand.h"
11 #include "counttable.h"
13 //**********************************************************************************************************************
14 vector<string> SummaryQualCommand::setParameters(){
16 CommandParameter pqual("qfile", "InputTypes", "", "", "none", "none", "none","summary",false,true,true); parameters.push_back(pqual);
17 CommandParameter pname("name", "InputTypes", "", "", "namecount", "none", "none","",false,false,true); parameters.push_back(pname);
18 CommandParameter pcount("count", "InputTypes", "", "", "namecount", "none", "none","",false,false,true); parameters.push_back(pcount);
19 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "","",false,false,true); parameters.push_back(pprocessors);
20 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
21 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
23 vector<string> myArray;
24 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
28 m->errorOut(e, "SummaryQualCommand", "setParameters");
32 //**********************************************************************************************************************
33 string SummaryQualCommand::getHelpString(){
35 string helpString = "";
36 helpString += "The summary.qual command reads a quality file and an optional name or count file, and summarizes the quality information.\n";
37 helpString += "The summary.tax command parameters are qfile, name, count and processors. qfile is required, unless you have a valid current quality file.\n";
38 helpString += "The name parameter allows you to enter a name file associated with your quality file. \n";
39 helpString += "The count parameter allows you to enter a count file associated with your quality file. \n";
40 helpString += "The summary.qual command should be in the following format: \n";
41 helpString += "summary.qual(qfile=yourQualityFile) \n";
42 helpString += "Note: No spaces between parameter labels (i.e. qfile), '=' and parameters (i.e.yourQualityFile).\n";
46 m->errorOut(e, "SummaryQualCommand", "getHelpString");
50 //**********************************************************************************************************************
51 string SummaryQualCommand::getOutputPattern(string type) {
55 if (type == "summary") { pattern = "[filename],qual.summary"; }
56 else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true; }
61 m->errorOut(e, "SummaryQualCommand", "getOutputPattern");
65 //**********************************************************************************************************************
66 SummaryQualCommand::SummaryQualCommand(){
68 abort = true; calledHelp = true;
70 vector<string> tempOutNames;
71 outputTypes["summary"] = tempOutNames;
74 m->errorOut(e, "SummaryQualCommand", "SummaryQualCommand");
78 //***************************************************************************************************************
80 SummaryQualCommand::SummaryQualCommand(string option) {
82 abort = false; calledHelp = false;
84 //allow user to run help
85 if(option == "help") { help(); abort = true; calledHelp = true; }
86 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
89 vector<string> myArray = setParameters();
91 OptionParser parser(option);
92 map<string,string> parameters = parser.getParameters();
94 ValidParameters validParameter;
95 map<string,string>::iterator it;
97 //check to make sure all parameters are valid for command
98 for (it = parameters.begin(); it != parameters.end(); it++) {
99 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
102 //if the user changes the input directory command factory will send this info to us in the output parameter
103 string inputDir = validParameter.validFile(parameters, "inputdir", false);
104 if (inputDir == "not found"){ inputDir = ""; }
107 it = parameters.find("qfile");
108 //user has given a template file
109 if(it != parameters.end()){
110 path = m->hasPath(it->second);
111 //if the user has not given a path then, add inputdir. else leave path alone.
112 if (path == "") { parameters["qfile"] = inputDir + it->second; }
115 it = parameters.find("name");
116 //user has given a template file
117 if(it != parameters.end()){
118 path = m->hasPath(it->second);
119 //if the user has not given a path then, add inputdir. else leave path alone.
120 if (path == "") { parameters["name"] = inputDir + it->second; }
123 it = parameters.find("count");
124 //user has given a template file
125 if(it != parameters.end()){
126 path = m->hasPath(it->second);
127 //if the user has not given a path then, add inputdir. else leave path alone.
128 if (path == "") { parameters["count"] = inputDir + it->second; }
132 //initialize outputTypes
133 vector<string> tempOutNames;
134 outputTypes["summary"] = tempOutNames;
136 //check for required parameters
137 qualfile = validParameter.validFile(parameters, "qfile", true);
138 if (qualfile == "not open") { qualfile = ""; abort = true; }
139 else if (qualfile == "not found") {
140 qualfile = m->getQualFile();
141 if (qualfile != "") { m->mothurOut("Using " + qualfile + " as input file for the qfile parameter."); m->mothurOutEndLine(); }
142 else { m->mothurOut("You have no current quality file and the qfile parameter is required."); m->mothurOutEndLine(); abort = true; }
143 }else { m->setQualFile(qualfile); }
145 namefile = validParameter.validFile(parameters, "name", true);
146 if (namefile == "not open") { namefile = ""; abort = true; }
147 else if (namefile == "not found") { namefile = ""; }
148 else { m->setNameFile(namefile); }
150 countfile = validParameter.validFile(parameters, "count", true);
151 if (countfile == "not open") { abort = true; countfile = ""; }
152 else if (countfile == "not found") { countfile = ""; }
153 else { m->setCountTableFile(countfile); }
155 if ((countfile != "") && (namefile != "")) { m->mothurOut("You must enter ONLY ONE of the following: count or name."); m->mothurOutEndLine(); abort = true; }
157 //if the user changes the output directory command factory will send this info to us in the output parameter
158 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
160 outputDir += m->hasPath(qualfile); //if user entered a file with a path then preserve it
163 string temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
164 m->setProcessors(temp);
165 m->mothurConvert(temp, processors);
168 if (countfile == "") {
169 if (namefile == "") {
170 vector<string> files; files.push_back(qualfile);
171 parser.getNameFile(files);
176 catch(exception& e) {
177 m->errorOut(e, "SummaryQualCommand", "SummaryQualCommand");
181 //***************************************************************************************************************
182 int SummaryQualCommand::execute(){
185 if (abort == true) { if (calledHelp) { return 0; } return 2; }
187 int start = time(NULL);
190 vector<int> position;
191 vector<int> averageQ;
192 vector< vector<int> > scores;
194 if (m->control_pressed) { return 0; }
196 if (namefile != "") { nameMap = m->readNames(namefile); }
197 else if (countfile != "") {
199 ct.readTable(countfile, false, false);
200 nameMap = ct.getNameMap();
203 vector<unsigned long long> positions;
204 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
205 positions = m->divideFile(qualfile, processors);
206 for (int i = 0; i < (positions.size()-1); i++) { lines.push_back(linePair(positions[i], positions[(i+1)])); }
208 if (processors == 1) {
209 lines.push_back(linePair(0, 1000));
211 positions = m->setFilePosFasta(qualfile, numSeqs);
212 if (positions.size() < processors) { processors = positions.size(); }
214 //figure out how many sequences you have to process
215 int numSeqsPerProcessor = numSeqs / processors;
216 for (int i = 0; i < processors; i++) {
217 int startIndex = i * numSeqsPerProcessor;
218 if(i == (processors - 1)){ numSeqsPerProcessor = numSeqs - i * numSeqsPerProcessor; }
219 lines.push_back(linePair(positions[startIndex], numSeqsPerProcessor));
225 if(processors == 1){ numSeqs = driverCreateSummary(position, averageQ, scores, qualfile, lines[0]); }
226 else{ numSeqs = createProcessesCreateSummary(position, averageQ, scores, qualfile); }
228 if (m->control_pressed) { return 0; }
231 map<string, string> variables;
232 variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(qualfile));
233 string summaryFile = getOutputFileName("summary",variables);
234 printQual(summaryFile, position, averageQ, scores);
236 if (m->control_pressed) { m->mothurRemove(summaryFile); return 0; }
238 //output results to screen
239 cout.setf(ios::fixed, ios::floatfield); cout.setf(ios::showpoint);
240 m->mothurOutEndLine();
241 m->mothurOut("Position\tNumSeqs\tAverageQ"); m->mothurOutEndLine();
242 for (int i = 0; i < position.size(); i+=100) {
243 float average = averageQ[i] / (float) position[i];
244 cout << i << '\t' << position[i] << '\t' << average;
245 m->mothurOutJustToLog(toString(i) + "\t" + toString(position[i]) + "\t" + toString(average)); m->mothurOutEndLine();
248 m->mothurOutEndLine();
249 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to create the summary file for " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
250 m->mothurOutEndLine();
251 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
252 m->mothurOut(summaryFile); m->mothurOutEndLine(); outputNames.push_back(summaryFile); outputTypes["summary"].push_back(summaryFile);
253 m->mothurOutEndLine();
257 catch(exception& e) {
258 m->errorOut(e, "SummaryQualCommand", "execute");
262 /**************************************************************************************/
263 int SummaryQualCommand::driverCreateSummary(vector<int>& position, vector<int>& averageQ, vector< vector<int> >& scores, string filename, linePair filePos) {
266 m->openInputFile(filename, in);
268 in.seekg(filePos.start);
275 if (m->control_pressed) { in.close(); return 1; }
277 QualityScores current(in); m->gobble(in);
279 if (current.getName() != "") {
282 if ((namefile != "") || (countfile != "")) {
283 //make sure this sequence is in the namefile, else error
284 map<string, int>::iterator it = nameMap.find(current.getName());
286 if (it == nameMap.end()) { m->mothurOut("[ERROR]: " + current.getName() + " is not in your namefile, please correct."); m->mothurOutEndLine(); m->control_pressed = true; }
287 else { num = it->second; }
290 vector<int> thisScores = current.getQualityScores();
292 //resize to num of positions setting number of seqs with that size to 1
293 if (position.size() < thisScores.size()) { position.resize(thisScores.size(), 0); }
294 if (averageQ.size() < thisScores.size()) { averageQ.resize(thisScores.size(), 0); }
295 if (scores.size() < thisScores.size()) {
296 scores.resize(thisScores.size());
297 for (int i = 0; i < scores.size(); i++) { scores[i].resize(41, 0); }
300 //increase counts of number of seqs with this position
301 //average is really the total, we will average in execute
302 for (int i = 0; i < thisScores.size(); i++) {
304 averageQ[i] += (thisScores[i] * num); //weighting for namesfile
305 if (thisScores[i] > 40) { m->mothurOut("[ERROR]: " + current.getName() + " has a quality scores of " + toString(thisScores[i]) + ", expecting values to be less than 40."); m->mothurOutEndLine(); m->control_pressed = true; }
306 else { scores[i][thisScores[i]] += num; }
312 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
313 unsigned long long pos = in.tellg();
314 if ((pos == -1) || (pos >= filePos.end)) { break; }
316 if (in.eof()) { break; }
324 catch(exception& e) {
325 m->errorOut(e, "SummaryQualCommand", "driverCreateSummary");
329 /**************************************************************************************************/
330 int SummaryQualCommand::createProcessesCreateSummary(vector<int>& position, vector<int>& averageQ, vector< vector<int> >& scores, string filename) {
336 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
338 //loop through and create all the processes you want
339 while (process != processors) {
343 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
346 numSeqs = driverCreateSummary(position, averageQ, scores, qualfile, lines[process]);
348 //pass numSeqs to parent
350 string tempFile = qualfile + toString(getpid()) + ".num.temp";
351 m->openOutputFile(tempFile, out);
353 out << numSeqs << endl;
354 out << position.size() << endl;
355 for (int k = 0; k < position.size(); k++) { out << position[k] << '\t'; } out << endl;
356 for (int k = 0; k < averageQ.size(); k++) { out << averageQ[k] << '\t'; } out << endl;
357 for (int k = 0; k < scores.size(); k++) {
358 for (int j = 0; j < 41; j++) {
359 out << scores[k][j] << '\t';
369 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
370 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
376 numSeqs = driverCreateSummary(position, averageQ, scores, qualfile, lines[0]);
378 //force parent to wait until all the processes are done
379 for (int i=0;i<processIDS.size();i++) {
380 int temp = processIDS[i];
384 //parent reads in and combine Filter info
385 for (int i = 0; i < processIDS.size(); i++) {
386 string tempFilename = qualfile + toString(processIDS[i]) + ".num.temp";
388 m->openInputFile(tempFilename, in);
391 in >> tempNum; m->gobble(in); numSeqs += tempNum;
392 in >> tempNum; m->gobble(in);
394 if (position.size() < tempNum) { position.resize(tempNum, 0); }
395 if (averageQ.size() < tempNum) { averageQ.resize(tempNum, 0); }
396 if (scores.size() < tempNum) {
397 scores.resize(tempNum);
398 for (int i = 0; i < scores.size(); i++) { scores[i].resize(41, 0); }
401 for (int k = 0; k < tempNum; k++) { in >> temp; position[k] += temp; } m->gobble(in);
402 for (int k = 0; k < tempNum; k++) { in >> temp; averageQ[k] += temp; } m->gobble(in);
403 for (int k = 0; k < tempNum; k++) {
404 for (int j = 0; j < 41; j++) {
405 in >> temp; scores[k][j] += temp;
411 m->mothurRemove(tempFilename);
415 //////////////////////////////////////////////////////////////////////////////////////////////////////
416 //Windows version shared memory, so be careful when passing variables through the seqSumQualData struct.
417 //Above fork() will clone, so memory is separate, but that's not the case with windows,
418 //Taking advantage of shared memory to pass results vectors.
419 //////////////////////////////////////////////////////////////////////////////////////////////////////
421 vector<seqSumQualData*> pDataArray;
422 DWORD dwThreadIdArray[processors];
423 HANDLE hThreadArray[processors];
425 bool hasNameMap = false;
426 if ((namefile !="") || (countfile != "")) { hasNameMap = true; }
428 //Create processor worker threads.
429 for( int i=0; i<processors; i++ ){
431 // Allocate memory for thread data.
432 seqSumQualData* tempSum = new seqSumQualData(filename, m, lines[i].start, lines[i].end, hasNameMap, nameMap);
433 pDataArray.push_back(tempSum);
434 processIDS.push_back(i);
436 hThreadArray[i] = CreateThread(NULL, 0, MySeqSumQualThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);
439 //Wait until all threads have terminated.
440 WaitForMultipleObjects(processors, hThreadArray, TRUE, INFINITE);
442 //Close all thread handles and free memory allocations.
443 for(int i=0; i < pDataArray.size(); i++){
444 numSeqs += pDataArray[i]->numSeqs;
445 if (pDataArray[i]->count != pDataArray[i]->end) {
446 m->mothurOut("[ERROR]: process " + toString(i) + " only processed " + toString(pDataArray[i]->count) + " of " + toString(pDataArray[i]->end) + " sequences assigned to it, quitting. \n"); m->control_pressed = true;
448 int tempNum = pDataArray[i]->position.size();
449 if (position.size() < tempNum) { position.resize(tempNum, 0); }
450 if (averageQ.size() < tempNum) { averageQ.resize(tempNum, 0); }
451 if (scores.size() < tempNum) {
452 scores.resize(tempNum);
453 for (int i = 0; i < scores.size(); i++) { scores[i].resize(41, 0); }
456 for (int k = 0; k < tempNum; k++) { position[k] += pDataArray[i]->position[k]; }
457 for (int k = 0; k < tempNum; k++) { averageQ[k] += pDataArray[i]->averageQ[k]; }
458 for (int k = 0; k < tempNum; k++) { for (int j = 0; j < 41; j++) { scores[k][j] += pDataArray[i]->scores[k][j]; } }
460 CloseHandle(hThreadArray[i]);
461 delete pDataArray[i];
466 catch(exception& e) {
467 m->errorOut(e, "SummaryQualCommand", "createProcessesCreateSummary");
471 /**************************************************************************************************/
472 int SummaryQualCommand::printQual(string sumFile, vector<int>& position, vector<int>& averageQ, vector< vector<int> >& scores) {
475 m->openOutputFile(sumFile, out);
476 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
477 outputNames.push_back(sumFile); outputTypes["summary"].push_back(sumFile);
480 out << "Position\tnumSeqs\tAverageQ\t";
481 for (int i = 0; i < 41; i++) { out << "q" << i << '\t'; }
484 for (int i = 0; i < position.size(); i++) {
486 if (m->control_pressed) { out.close(); return 0; }
488 double average = averageQ[i] / (float) position[i];
489 out << i << '\t' << position[i] << '\t' << average << '\t';
491 for (int j = 0; j < 41; j++) {
492 out << scores[i][j] << '\t';
501 catch(exception& e) {
502 m->errorOut(e, "SummaryQualCommand", "printQual");
507 /**************************************************************************************/