]> git.donarmstrong.com Git - mothur.git/blob - summaryqualcommand.cpp
fixes while testing 1.33.0
[mothur.git] / summaryqualcommand.cpp
1 /*
2  *  summaryqualcommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 11/28/11.
6  *  Copyright 2011 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "summaryqualcommand.h"
11 #include "counttable.h"
12
13 //**********************************************************************************************************************
14 vector<string> SummaryQualCommand::setParameters(){     
15         try {
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);
22                 
23                 vector<string> myArray;
24                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
25                 return myArray;
26         }
27         catch(exception& e) {
28                 m->errorOut(e, "SummaryQualCommand", "setParameters");
29                 exit(1);
30         }
31 }
32 //**********************************************************************************************************************
33 string SummaryQualCommand::getHelpString(){     
34         try {
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";     
43                 return helpString;
44         }
45         catch(exception& e) {
46                 m->errorOut(e, "SummaryQualCommand", "getHelpString");
47                 exit(1);
48         }
49 }
50 //**********************************************************************************************************************
51 string SummaryQualCommand::getOutputPattern(string type) {
52     try {
53         string pattern = "";
54         
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;  }
57         
58         return pattern;
59     }
60     catch(exception& e) {
61         m->errorOut(e, "SummaryQualCommand", "getOutputPattern");
62         exit(1);
63     }
64 }
65 //**********************************************************************************************************************
66 SummaryQualCommand::SummaryQualCommand(){       
67         try {
68                 abort = true; calledHelp = true; 
69                 setParameters();
70                 vector<string> tempOutNames;
71                 outputTypes["summary"] = tempOutNames;
72         }
73         catch(exception& e) {
74                 m->errorOut(e, "SummaryQualCommand", "SummaryQualCommand");
75                 exit(1);
76         }
77 }
78 //***************************************************************************************************************
79
80 SummaryQualCommand::SummaryQualCommand(string option)  {
81         try {
82                 abort = false; calledHelp = false;   
83                 
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;}
87                 
88                 else {
89                         vector<string> myArray = setParameters();
90                         
91                         OptionParser parser(option);
92                         map<string,string> parameters = parser.getParameters();
93                         
94                         ValidParameters validParameter;
95                         map<string,string>::iterator it;
96                         
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;  }
100                         }
101                         
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 = "";          }
105                         else {
106                                 string path;
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;            }
113                                 }
114                                 
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;             }
121                                 }
122                 
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;            }
129                                 }
130                         }
131                         
132                         //initialize outputTypes
133                         vector<string> tempOutNames;
134                         outputTypes["summary"] = tempOutNames;
135                         
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); }     
144                         
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); }
149             
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); }
154                         
155             if ((countfile != "") && (namefile != "")) { m->mothurOut("You must enter ONLY ONE of the following: count or name."); m->mothurOutEndLine(); abort = true; }
156                         
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"){  
159                                 outputDir = ""; 
160                                 outputDir += m->hasPath(qualfile); //if user entered a file with a path then preserve it        
161                         }
162                         
163                         string temp = validParameter.validFile(parameters, "processors", false);        if (temp == "not found"){       temp = m->getProcessors();      }
164                         m->setProcessors(temp);
165                         m->mothurConvert(temp, processors);     
166                         
167             
168                         if (countfile == "") {
169                 if (namefile == "") {
170                     vector<string> files; files.push_back(qualfile);
171                     parser.getNameFile(files);
172                 }
173             }
174                 }
175         }
176         catch(exception& e) {
177                 m->errorOut(e, "SummaryQualCommand", "SummaryQualCommand");
178                 exit(1);
179         }
180 }
181 //***************************************************************************************************************
182 int SummaryQualCommand::execute(){
183         try{
184                 
185                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
186                 
187                 int start = time(NULL);
188                 int numSeqs = 0;
189                 
190                 vector<int> position;
191                 vector<int> averageQ;
192                 vector< vector<int> > scores;
193                                 
194                 if (m->control_pressed) { return 0; }
195                 
196                 if (namefile != "") { nameMap = m->readNames(namefile); }
197                 else if (countfile != "") {
198             CountTable ct;
199             ct.readTable(countfile, false, false);
200             nameMap = ct.getNameMap();
201         }
202         
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)]));      }
207 #else   
208                 if (processors == 1) {
209                         lines.push_back(linePair(0, 1000)); 
210                 }else {
211                         positions = m->setFilePosFasta(qualfile, numSeqs); 
212             if (positions.size() < processors) { processors = positions.size(); }
213                         
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));
220                         }
221                 }
222 #endif
223                 
224                 
225                 if(processors == 1){ numSeqs = driverCreateSummary(position, averageQ, scores, qualfile, lines[0]);  }
226                 else{  numSeqs = createProcessesCreateSummary(position, averageQ, scores, qualfile);  }
227                 
228                 if (m->control_pressed) {  return 0; }
229                 
230                 //print summary file
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);
235                 
236                 if (m->control_pressed) {  m->mothurRemove(summaryFile); return 0; }
237                 
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();
246                 }
247                 
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();
254                 
255                 return 0;
256         }
257         catch(exception& e) {
258                 m->errorOut(e, "SummaryQualCommand", "execute");
259                 exit(1);
260         }
261 }
262 /**************************************************************************************/
263 int SummaryQualCommand::driverCreateSummary(vector<int>& position, vector<int>& averageQ, vector< vector<int> >& scores, string filename, linePair filePos) {   
264         try {
265                 ifstream in;
266                 m->openInputFile(filename, in);
267                 
268                 in.seekg(filePos.start);
269                 
270                 bool done = false;
271                 int count = 0;
272                 
273                 while (!done) {
274                         
275                         if (m->control_pressed) { in.close(); return 1; }
276                         
277                         QualityScores current(in); m->gobble(in);
278                         
279                         if (current.getName() != "") {
280                                 
281                                 int num = 1;
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());
285                                         
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; }
288                                 }
289                                 
290                                 vector<int> thisScores = current.getQualityScores();
291                                 
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); }
298                                 }
299                                 
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++) { 
303                                         position[i] += num; 
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; }  
307                                 }
308                                 
309                                 count += num;
310                         }
311                         
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; }
315 #else
316                         if (in.eof()) { break; }
317 #endif
318                 }
319                 
320                 in.close();
321                 
322                 return count;
323         }
324         catch(exception& e) {
325                 m->errorOut(e, "SummaryQualCommand", "driverCreateSummary");
326                 exit(1);
327         }
328 }
329 /**************************************************************************************************/
330 int SummaryQualCommand::createProcessesCreateSummary(vector<int>& position, vector<int>& averageQ, vector< vector<int> >& scores, string filename) {
331         try {
332                 int process = 1;
333                 int numSeqs = 0;
334                 processIDS.clear();
335                 
336 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
337                 
338                 //loop through and create all the processes you want
339                 while (process != processors) {
340                         int pid = fork();
341                         
342                         if (pid > 0) {
343                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
344                                 process++;
345                         }else if (pid == 0){
346                                 numSeqs = driverCreateSummary(position, averageQ, scores, qualfile, lines[process]);
347                                 
348                                 //pass numSeqs to parent
349                                 ofstream out;
350                                 string tempFile = qualfile + toString(getpid()) + ".num.temp";
351                                 m->openOutputFile(tempFile, out);
352                                 
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'; 
360                                         }
361                                         out << endl;
362                                 }  
363                                 out << endl;
364                                 
365                                 out.close();
366                                 
367                                 exit(0);
368                         }else { 
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); }
371                                 exit(0);
372                         }
373                 }
374                 
375                 //do your part
376                 numSeqs = driverCreateSummary(position, averageQ, scores, qualfile, lines[0]);
377                 
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];
381                         wait(&temp);
382                 }
383                 
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";
387                         ifstream in;
388                         m->openInputFile(tempFilename, in);
389                         
390                         int temp, tempNum;
391                         in >> tempNum; m->gobble(in); numSeqs += tempNum;
392                         in >> tempNum; m->gobble(in);
393                         
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); }
399                         }
400                         
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;
406                                         m->gobble(in);
407                                 }       
408                         }
409                         
410                         in.close();
411                         m->mothurRemove(tempFilename);
412                 }
413                 
414 #else
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                 //////////////////////////////////////////////////////////////////////////////////////////////////////
420                 
421                 vector<seqSumQualData*> pDataArray; 
422                 DWORD   dwThreadIdArray[processors];
423                 HANDLE  hThreadArray[processors]; 
424                 
425         bool hasNameMap = false;
426         if ((namefile !="") || (countfile != "")) { hasNameMap = true; }
427         
428                 //Create processor worker threads.
429                 for( int i=0; i<processors; i++ ){
430                         
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);
435         
436                         hThreadArray[i] = CreateThread(NULL, 0, MySeqSumQualThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);   
437                 }
438                 
439                 //Wait until all threads have terminated.
440                 WaitForMultipleObjects(processors, hThreadArray, TRUE, INFINITE);
441                 
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; 
447             }
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); }
454                         }
455             
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];   }        }
459
460                         CloseHandle(hThreadArray[i]);
461                         delete pDataArray[i];
462                 }
463 #endif          
464                 return numSeqs;
465         }
466         catch(exception& e) {
467                 m->errorOut(e, "SummaryQualCommand", "createProcessesCreateSummary");
468                 exit(1);
469         }
470 }
471 /**************************************************************************************************/
472 int SummaryQualCommand::printQual(string sumFile, vector<int>& position, vector<int>& averageQ, vector< vector<int> >& scores) {
473         try {
474                 ofstream out;
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);
478                 
479                 //print headings
480                 out << "Position\tnumSeqs\tAverageQ\t";
481                 for (int i = 0; i < 41; i++) { out << "q" << i << '\t'; }
482                 out << endl;
483                 
484                 for (int i = 0; i < position.size(); i++) {
485                         
486                         if (m->control_pressed) { out.close(); return 0; }
487                         
488                         double average = averageQ[i] / (float) position[i];
489                         out << i << '\t' << position[i] << '\t' << average << '\t';
490                         
491                         for (int j = 0; j < 41; j++) {
492                                 out << scores[i][j] << '\t';
493                         }
494                         out << endl;
495                 }
496                 
497                 out.close();
498                 
499                 return 0;
500         }
501         catch(exception& e) {
502                 m->errorOut(e, "SummaryQualCommand", "printQual");
503                 exit(1);
504         }
505 }
506
507 /**************************************************************************************/
508
509