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