]> git.donarmstrong.com Git - mothur.git/blob - summaryqualcommand.cpp
fixed bug in windows summary.seqs and summary.qual paralellization. paralellized...
[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
12
13 //**********************************************************************************************************************
14 vector<string> SummaryQualCommand::setParameters(){     
15         try {
16                 CommandParameter pqual("qfile", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pqual);
17                 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
18                 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
19                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
20                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
21                 
22                 vector<string> myArray;
23                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
24                 return myArray;
25         }
26         catch(exception& e) {
27                 m->errorOut(e, "SummaryQualCommand", "setParameters");
28                 exit(1);
29         }
30 }
31 //**********************************************************************************************************************
32 string SummaryQualCommand::getHelpString(){     
33         try {
34                 string helpString = "";
35                 helpString += "The summary.qual command reads a quality file and an optional name file, and summarizes the quality information.\n";
36                 helpString += "The summary.tax command parameters are qfile, name and processors. qfile is required, unless you have a valid current quality file.\n";
37                 helpString += "The name parameter allows you to enter a name file associated with your quality file. \n";
38                 helpString += "The summary.qual command should be in the following format: \n";
39                 helpString += "summary.qual(qfile=yourQualityFile) \n";
40                 helpString += "Note: No spaces between parameter labels (i.e. qfile), '=' and parameters (i.e.yourQualityFile).\n";     
41                 return helpString;
42         }
43         catch(exception& e) {
44                 m->errorOut(e, "SummaryQualCommand", "getHelpString");
45                 exit(1);
46         }
47 }
48
49 //**********************************************************************************************************************
50 SummaryQualCommand::SummaryQualCommand(){       
51         try {
52                 abort = true; calledHelp = true; 
53                 setParameters();
54                 vector<string> tempOutNames;
55                 outputTypes["summary"] = tempOutNames;
56         }
57         catch(exception& e) {
58                 m->errorOut(e, "SummaryQualCommand", "SummaryQualCommand");
59                 exit(1);
60         }
61 }
62 //***************************************************************************************************************
63
64 SummaryQualCommand::SummaryQualCommand(string option)  {
65         try {
66                 abort = false; calledHelp = false;   
67                 
68                 //allow user to run help
69                 if(option == "help") { help(); abort = true; calledHelp = true; }
70                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
71                 
72                 else {
73                         vector<string> myArray = setParameters();
74                         
75                         OptionParser parser(option);
76                         map<string,string> parameters = parser.getParameters();
77                         
78                         ValidParameters validParameter;
79                         map<string,string>::iterator it;
80                         
81                         //check to make sure all parameters are valid for command
82                         for (it = parameters.begin(); it != parameters.end(); it++) { 
83                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
84                         }
85                         
86                         //if the user changes the input directory command factory will send this info to us in the output parameter 
87                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
88                         if (inputDir == "not found"){   inputDir = "";          }
89                         else {
90                                 string path;
91                                 it = parameters.find("qfile");
92                                 //user has given a template file
93                                 if(it != parameters.end()){ 
94                                         path = m->hasPath(it->second);
95                                         //if the user has not given a path then, add inputdir. else leave path alone.
96                                         if (path == "") {       parameters["qfile"] = inputDir + it->second;            }
97                                 }
98                                 
99                                 it = parameters.find("name");
100                                 //user has given a template file
101                                 if(it != parameters.end()){ 
102                                         path = m->hasPath(it->second);
103                                         //if the user has not given a path then, add inputdir. else leave path alone.
104                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
105                                 }
106                         }
107                         
108                         //initialize outputTypes
109                         vector<string> tempOutNames;
110                         outputTypes["summary"] = tempOutNames;
111                         
112                         //check for required parameters
113                         qualfile = validParameter.validFile(parameters, "qfile", true);
114                         if (qualfile == "not open") { qualfile = ""; abort = true; }
115                         else if (qualfile == "not found") {                             
116                                 qualfile = m->getQualFile(); 
117                                 if (qualfile != "") { m->mothurOut("Using " + qualfile + " as input file for the qfile parameter."); m->mothurOutEndLine(); }
118                                 else {  m->mothurOut("You have no current quality file and the qfile parameter is required."); m->mothurOutEndLine(); abort = true; }
119                         }else { m->setQualFile(qualfile); }     
120                         
121                         namefile = validParameter.validFile(parameters, "name", true);
122                         if (namefile == "not open") { namefile = ""; abort = true; }
123                         else if (namefile == "not found") { namefile = "";  }   
124                         else { m->setNameFile(namefile); }
125                         
126                         //if the user changes the output directory command factory will send this info to us in the output parameter 
127                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
128                                 outputDir = ""; 
129                                 outputDir += m->hasPath(qualfile); //if user entered a file with a path then preserve it        
130                         }
131                         
132                         string temp = validParameter.validFile(parameters, "processors", false);        if (temp == "not found"){       temp = m->getProcessors();      }
133                         m->setProcessors(temp);
134                         m->mothurConvert(temp, processors);     
135                         
136                         if (namefile == "") {
137                                 vector<string> files; files.push_back(qualfile);
138                                 parser.getNameFile(files);
139                         }
140                 }
141         }
142         catch(exception& e) {
143                 m->errorOut(e, "SummaryQualCommand", "SummaryQualCommand");
144                 exit(1);
145         }
146 }
147 //***************************************************************************************************************
148 int SummaryQualCommand::execute(){
149         try{
150                 
151                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
152                 
153                 int start = time(NULL);
154                 int numSeqs = 0;
155                 
156                 vector<int> position;
157                 vector<int> averageQ;
158                 vector< vector<int> > scores;
159                                 
160                 if (m->control_pressed) { return 0; }
161                 
162                 if (namefile != "") { nameMap = m->readNames(namefile); }
163                 
164                 vector<unsigned long long> positions; 
165 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
166                 positions = m->divideFile(qualfile, processors);
167                 for (int i = 0; i < (positions.size()-1); i++) {        lines.push_back(linePair(positions[i], positions[(i+1)]));      }
168 #else   
169                 if (processors == 1) {
170                         lines.push_back(linePair(0, 1000)); 
171                 }else {
172                         positions = m->setFilePosFasta(qualfile, numSeqs); 
173                         
174                         //figure out how many sequences you have to process
175                         int numSeqsPerProcessor = numSeqs / processors;
176                         for (int i = 0; i < processors; i++) {
177                                 int startIndex =  i * numSeqsPerProcessor;
178                                 if(i == (processors - 1)){      numSeqsPerProcessor = numSeqs - i * numSeqsPerProcessor;        }
179                                 lines.push_back(linePair(positions[startIndex], numSeqsPerProcessor));
180                         }
181                 }
182 #endif
183                 
184                 
185                 if(processors == 1){ numSeqs = driverCreateSummary(position, averageQ, scores, qualfile, lines[0]);  }
186                 else{  numSeqs = createProcessesCreateSummary(position, averageQ, scores, qualfile);  }
187                 
188                 if (m->control_pressed) {  return 0; }
189                 
190                 //print summary file
191                 string summaryFile = outputDir + m->getRootName(m->getSimpleName(qualfile)) + "qual.summary";
192                 printQual(summaryFile, position, averageQ, scores);
193                 
194                 if (m->control_pressed) {  m->mothurRemove(summaryFile); return 0; }
195                 
196                 //output results to screen
197                 cout.setf(ios::fixed, ios::floatfield); cout.setf(ios::showpoint);
198                 m->mothurOutEndLine();
199                 m->mothurOut("Position\tNumSeqs\tAverageQ"); m->mothurOutEndLine();
200                 for (int i = 0; i < position.size(); i+=100) {
201                         float average = averageQ[i] / (float) position[i];
202                         cout << i << '\t' << position[i] << '\t' << average;
203                         m->mothurOutJustToLog(toString(i) + "\t" + toString(position[i]) + "\t" + toString(average)); m->mothurOutEndLine();
204                 }
205                 
206                 m->mothurOutEndLine();
207                 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to create the summary file for " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
208                 m->mothurOutEndLine();
209                 m->mothurOut("Output File Name: "); m->mothurOutEndLine();
210                 m->mothurOut(summaryFile); m->mothurOutEndLine();       outputNames.push_back(summaryFile); outputTypes["summary"].push_back(summaryFile);
211                 m->mothurOutEndLine();
212                 
213                 return 0;
214         }
215         catch(exception& e) {
216                 m->errorOut(e, "SummaryQualCommand", "execute");
217                 exit(1);
218         }
219 }
220 /**************************************************************************************/
221 int SummaryQualCommand::driverCreateSummary(vector<int>& position, vector<int>& averageQ, vector< vector<int> >& scores, string filename, linePair filePos) {   
222         try {
223                 ifstream in;
224                 m->openInputFile(filename, in);
225                 
226                 in.seekg(filePos.start);
227                 
228                 bool done = false;
229                 int count = 0;
230                 
231                 while (!done) {
232                         
233                         if (m->control_pressed) { in.close(); return 1; }
234                         
235                         QualityScores current(in); m->gobble(in);
236                         
237                         if (current.getName() != "") {
238                                 
239                                 int num = 1;
240                                 if (namefile != "") {
241                                         //make sure this sequence is in the namefile, else error 
242                                         map<string, int>::iterator it = nameMap.find(current.getName());
243                                         
244                                         if (it == nameMap.end()) { m->mothurOut("[ERROR]: " + current.getName() + " is not in your namefile, please correct."); m->mothurOutEndLine(); m->control_pressed = true; }
245                                         else { num = it->second; }
246                                 }
247                                 
248                                 vector<int> thisScores = current.getQualityScores();
249                                 
250                                 //resize to num of positions setting number of seqs with that size to 1
251                                 if (position.size() < thisScores.size()) { position.resize(thisScores.size(), 0); }
252                                 if (averageQ.size() < thisScores.size()) { averageQ.resize(thisScores.size(), 0); }
253                                 if (scores.size() < thisScores.size()) { 
254                                         scores.resize(thisScores.size()); 
255                                         for (int i = 0; i < scores.size(); i++) { scores[i].resize(41, 0); }
256                                 }
257                                 
258                                 //increase counts of number of seqs with this position
259                                 //average is really the total, we will average in execute
260                                 for (int i = 0; i < thisScores.size(); i++) { 
261                                         position[i] += num; 
262                                         averageQ[i] += (thisScores[i] * num); //weighting for namesfile
263                                         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; }
264                                         else { scores[i][thisScores[i]] += num; }  
265                                 }
266                                 
267                                 count += num;
268                         }
269                         
270 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
271                         unsigned long long pos = in.tellg();
272                         if ((pos == -1) || (pos >= filePos.end)) { break; }
273 #else
274                         if (in.eof()) { break; }
275 #endif
276                 }
277                 
278                 in.close();
279                 
280                 return count;
281         }
282         catch(exception& e) {
283                 m->errorOut(e, "SummaryQualCommand", "driverCreateSummary");
284                 exit(1);
285         }
286 }
287 /**************************************************************************************************/
288 int SummaryQualCommand::createProcessesCreateSummary(vector<int>& position, vector<int>& averageQ, vector< vector<int> >& scores, string filename) {
289         try {
290                 int process = 1;
291                 int numSeqs = 0;
292                 processIDS.clear();
293                 
294 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
295                 
296                 //loop through and create all the processes you want
297                 while (process != processors) {
298                         int pid = fork();
299                         
300                         if (pid > 0) {
301                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
302                                 process++;
303                         }else if (pid == 0){
304                                 numSeqs = driverCreateSummary(position, averageQ, scores, qualfile, lines[process]);
305                                 
306                                 //pass numSeqs to parent
307                                 ofstream out;
308                                 string tempFile = qualfile + toString(getpid()) + ".num.temp";
309                                 m->openOutputFile(tempFile, out);
310                                 
311                                 out << numSeqs << endl;
312                                 out << position.size() << endl;
313                                 for (int k = 0; k < position.size(); k++)                       {               out << position[k] << '\t'; }  out << endl;
314                                 for (int k = 0; k < averageQ.size(); k++)                       {               out << averageQ[k] << '\t'; }  out << endl;
315                                 for (int k = 0; k < scores.size(); k++) {               
316                                         for (int j = 0; j < 41; j++) {
317                                                 out << scores[k][j] << '\t'; 
318                                         }
319                                         out << endl;
320                                 }  
321                                 out << endl;
322                                 
323                                 out.close();
324                                 
325                                 exit(0);
326                         }else { 
327                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
328                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
329                                 exit(0);
330                         }
331                 }
332                 
333                 //do your part
334                 numSeqs = driverCreateSummary(position, averageQ, scores, qualfile, lines[0]);
335                 
336                 //force parent to wait until all the processes are done
337                 for (int i=0;i<processIDS.size();i++) { 
338                         int temp = processIDS[i];
339                         wait(&temp);
340                 }
341                 
342                 //parent reads in and combine Filter info
343                 for (int i = 0; i < processIDS.size(); i++) {
344                         string tempFilename = qualfile + toString(processIDS[i]) + ".num.temp";
345                         ifstream in;
346                         m->openInputFile(tempFilename, in);
347                         
348                         int temp, tempNum;
349                         in >> tempNum; m->gobble(in); numSeqs += tempNum;
350                         in >> tempNum; m->gobble(in);
351                         
352                         if (position.size() < tempNum) { position.resize(tempNum, 0); }
353                         if (averageQ.size() < tempNum) { averageQ.resize(tempNum, 0); }
354                         if (scores.size() < tempNum) { 
355                                 scores.resize(tempNum); 
356                                 for (int i = 0; i < scores.size(); i++) { scores[i].resize(41, 0); }
357                         }
358                         
359                         for (int k = 0; k < tempNum; k++)                       {               in >> temp; position[k] += temp;                        }               m->gobble(in);
360                         for (int k = 0; k < tempNum; k++)                       {               in >> temp; averageQ[k] += temp;                }               m->gobble(in);
361                         for (int k = 0; k < tempNum; k++)                       {       
362                                 for (int j = 0; j < 41; j++) {
363                                         in >> temp; scores[k][j] += temp;
364                                         m->gobble(in);
365                                 }       
366                         }
367                         
368                         in.close();
369                         m->mothurRemove(tempFilename);
370                 }
371                 
372 #else
373                 //////////////////////////////////////////////////////////////////////////////////////////////////////
374                 //Windows version shared memory, so be careful when passing variables through the seqSumQualData struct. 
375                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
376                 //Taking advantage of shared memory to pass results vectors.
377                 //////////////////////////////////////////////////////////////////////////////////////////////////////
378                 
379                 vector<seqSumQualData*> pDataArray; 
380                 DWORD   dwThreadIdArray[processors];
381                 HANDLE  hThreadArray[processors]; 
382                 
383                 //Create processor worker threads.
384                 for( int i=0; i<processors; i++ ){
385                         
386                         // Allocate memory for thread data.
387                         seqSumQualData* tempSum = new seqSumQualData(filename, m, lines[i].start, lines[i].end, namefile, nameMap);
388                         pDataArray.push_back(tempSum);
389                         processIDS.push_back(i);
390         
391                         hThreadArray[i] = CreateThread(NULL, 0, MySeqSumQualThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);   
392                 }
393                 
394                 //Wait until all threads have terminated.
395                 WaitForMultipleObjects(processors, hThreadArray, TRUE, INFINITE);
396                 
397                 //Close all thread handles and free memory allocations.
398                 for(int i=0; i < pDataArray.size(); i++){
399                         numSeqs += pDataArray[i]->count;
400             int tempNum = pDataArray[i]->position.size();
401             if (position.size() < tempNum) { position.resize(tempNum, 0); }
402                         if (averageQ.size() < tempNum) { averageQ.resize(tempNum, 0); }
403                         if (scores.size() < tempNum) { 
404                                 scores.resize(tempNum); 
405                                 for (int i = 0; i < scores.size(); i++) { scores[i].resize(41, 0); }
406                         }
407             
408             for (int k = 0; k < tempNum; k++)                   {                position[k]    +=  pDataArray[i]->position[k];         }               
409                         for (int k = 0; k < tempNum; k++)                       {                averageQ[k]    +=  pDataArray[i]->averageQ[k];         }               
410                         for (int k = 0; k < tempNum; k++)                       {       for (int j = 0; j < 41; j++) {  scores[k][j] += pDataArray[i]->scores[k][j];   }        }
411
412                         CloseHandle(hThreadArray[i]);
413                         delete pDataArray[i];
414                 }
415 #endif          
416                 return numSeqs;
417         }
418         catch(exception& e) {
419                 m->errorOut(e, "SummaryQualCommand", "createProcessesCreateSummary");
420                 exit(1);
421         }
422 }
423 /**************************************************************************************************/
424 int SummaryQualCommand::printQual(string sumFile, vector<int>& position, vector<int>& averageQ, vector< vector<int> >& scores) {
425         try {
426                 ofstream out;
427                 m->openOutputFile(sumFile, out);
428                 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
429                 outputNames.push_back(sumFile); outputTypes["summary"].push_back(sumFile);
430                 
431                 //print headings
432                 out << "Position\tnumSeqs\tAverageQ\t";
433                 for (int i = 0; i < 41; i++) { out << "q" << i << '\t'; }
434                 out << endl;
435                 
436                 for (int i = 0; i < position.size(); i++) {
437                         
438                         if (m->control_pressed) { out.close(); return 0; }
439                         
440                         float average = averageQ[i] / (float) position[i];
441                         out << i << '\t' << position[i] << '\t' << average << '\t';
442                         
443                         for (int j = 0; j < 41; j++) {
444                                 out << scores[i][j] << '\t';
445                         }
446                         out << endl;
447                 }
448                 
449                 out.close();
450                 
451                 return 0;
452         }
453         catch(exception& e) {
454                 m->errorOut(e, "SummaryQualCommand", "printQual");
455                 exit(1);
456         }
457 }
458
459 /**************************************************************************************/
460
461