]> git.donarmstrong.com Git - mothur.git/blob - summaryqualcommand.cpp
Added summary.qual command. Added fontsize parameter to heatmap.sim and venn commands
[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") { 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                         convert(temp, processors);                      
135                 }
136         }
137         catch(exception& e) {
138                 m->errorOut(e, "SummaryQualCommand", "SummaryQualCommand");
139                 exit(1);
140         }
141 }
142 //***************************************************************************************************************
143 int SummaryQualCommand::execute(){
144         try{
145                 
146                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
147                 
148                 int start = time(NULL);
149                 int numSeqs = 0;
150                 
151                 vector<int> position;
152                 vector<int> averageQ;
153                 vector< vector<int> > scores;
154                                 
155                 if (m->control_pressed) { return 0; }
156                 
157                 if (namefile != "") { nameMap = m->readNames(namefile); }
158                 
159                 vector<unsigned long long> positions; 
160 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
161                 positions = m->divideFile(qualfile, processors);
162                 for (int i = 0; i < (positions.size()-1); i++) {        lines.push_back(linePair(positions[i], positions[(i+1)]));      }
163 #else   
164                 if (processors == 1) {
165                         lines.push_back(linePair(0, 1000)); 
166                 }else {
167                         positions = m->setFilePosFasta(qualfile, numSeqs); 
168                         
169                         //figure out how many sequences you have to process
170                         int numSeqsPerProcessor = numSeqs / processors;
171                         for (int i = 0; i < processors; i++) {
172                                 int startIndex =  i * numSeqsPerProcessor;
173                                 if(i == (processors - 1)){      numSeqsPerProcessor = numSeqs - i * numSeqsPerProcessor;        }
174                                 lines.push_back(linePair(positions[startIndex], numSeqsPerProcessor));
175                         }
176                 }
177 #endif
178                 
179                 
180                 if(processors == 1){ numSeqs = driverCreateSummary(position, averageQ, scores, qualfile, lines[0]);  }
181                 else{  numSeqs = createProcessesCreateSummary(position, averageQ, scores, qualfile);  }
182                 
183                 if (m->control_pressed) {  return 0; }
184                 
185                 //print summary file
186                 string summaryFile = outputDir + m->getRootName(m->getSimpleName(qualfile)) + "qual.summary";
187                 printQual(summaryFile, position, averageQ, scores);
188                 
189                 if (m->control_pressed) {  m->mothurRemove(summaryFile); return 0; }
190                 
191                 //output results to screen
192                 cout.setf(ios::fixed, ios::floatfield); cout.setf(ios::showpoint);
193                 m->mothurOutEndLine();
194                 m->mothurOut("Position\tNumSeqs\tAverageQ"); m->mothurOutEndLine();
195                 for (int i = 0; i < position.size(); i+=100) {
196                         float average = averageQ[i] / (float) position[i];
197                         cout << i << '\t' << position[i] << '\t' << average;
198                         m->mothurOutJustToLog(toString(i) + "\t" + toString(position[i]) + "\t" + toString(average)); m->mothurOutEndLine();
199                 }
200                 
201                 m->mothurOutEndLine();
202                 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to create the summary file for " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
203                 m->mothurOutEndLine();
204                 m->mothurOut("Output File Name: "); m->mothurOutEndLine();
205                 m->mothurOut(summaryFile); m->mothurOutEndLine();       outputNames.push_back(summaryFile); outputTypes["summary"].push_back(summaryFile);
206                 m->mothurOutEndLine();
207                 
208                 return 0;
209         }
210         catch(exception& e) {
211                 m->errorOut(e, "SummaryQualCommand", "execute");
212                 exit(1);
213         }
214 }
215 /**************************************************************************************/
216 int SummaryQualCommand::driverCreateSummary(vector<int>& position, vector<int>& averageQ, vector< vector<int> >& scores, string filename, linePair filePos) {   
217         try {
218                 ifstream in;
219                 m->openInputFile(filename, in);
220                 
221                 in.seekg(filePos.start);
222                 
223                 bool done = false;
224                 int count = 0;
225                 
226                 while (!done) {
227                         
228                         if (m->control_pressed) { in.close(); return 1; }
229                         
230                         QualityScores current(in); m->gobble(in);
231                         
232                         if (current.getName() != "") {
233                                 
234                                 int num = 1;
235                                 if (namefile != "") {
236                                         //make sure this sequence is in the namefile, else error 
237                                         map<string, int>::iterator it = nameMap.find(current.getName());
238                                         
239                                         if (it == nameMap.end()) { m->mothurOut("[ERROR]: " + current.getName() + " is not in your namefile, please correct."); m->mothurOutEndLine(); m->control_pressed = true; }
240                                         else { num = it->second; }
241                                 }
242                                 
243                                 vector<int> thisScores = current.getQualityScores();
244                                 
245                                 //resize to num of positions setting number of seqs with that size to 1
246                                 if (position.size() < thisScores.size()) { position.resize(thisScores.size(), 0); }
247                                 if (averageQ.size() < thisScores.size()) { averageQ.resize(thisScores.size(), 0); }
248                                 if (scores.size() < thisScores.size()) { 
249                                         scores.resize(thisScores.size()); 
250                                         for (int i = 0; i < scores.size(); i++) { scores[i].resize(41, 0); }
251                                 }
252                                 
253                                 //increase counts of number of seqs with this position
254                                 //average is really the total, we will average in execute
255                                 for (int i = 0; i < thisScores.size(); i++) { 
256                                         position[i] += num; 
257                                         averageQ[i] += (thisScores[i] * num); //weighting for namesfile
258                                         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; }
259                                         else { scores[i][thisScores[i]] += num; }  
260                                 }
261                                 
262                                 count += num;
263                         }
264                         
265 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
266                         unsigned long long pos = in.tellg();
267                         if ((pos == -1) || (pos >= filePos.end)) { break; }
268 #else
269                         if (in.eof()) { break; }
270 #endif
271                 }
272                 
273                 in.close();
274                 
275                 return count;
276         }
277         catch(exception& e) {
278                 m->errorOut(e, "SummaryQualCommand", "driverCreateSummary");
279                 exit(1);
280         }
281 }
282 /**************************************************************************************************/
283 int SummaryQualCommand::createProcessesCreateSummary(vector<int>& position, vector<int>& averageQ, vector< vector<int> >& scores, string filename) {
284         try {
285                 int process = 1;
286                 int numSeqs = 0;
287                 processIDS.clear();
288                 
289 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
290                 
291                 //loop through and create all the processes you want
292                 while (process != processors) {
293                         int pid = fork();
294                         
295                         if (pid > 0) {
296                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
297                                 process++;
298                         }else if (pid == 0){
299                                 numSeqs = driverCreateSummary(position, averageQ, scores, qualfile, lines[process]);
300                                 
301                                 //pass numSeqs to parent
302                                 ofstream out;
303                                 string tempFile = qualfile + toString(getpid()) + ".num.temp";
304                                 m->openOutputFile(tempFile, out);
305                                 
306                                 out << numSeqs << endl;
307                                 out << position.size() << endl;
308                                 for (int k = 0; k < position.size(); k++)                       {               out << position[k] << '\t'; }  out << endl;
309                                 for (int k = 0; k < averageQ.size(); k++)                       {               out << averageQ[k] << '\t'; }  out << endl;
310                                 for (int k = 0; k < scores.size(); k++) {               
311                                         for (int j = 0; j < 41; j++) {
312                                                 out << scores[k][j] << '\t'; 
313                                         }
314                                         out << endl;
315                                 }  
316                                 out << endl;
317                                 
318                                 out.close();
319                                 
320                                 exit(0);
321                         }else { 
322                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
323                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
324                                 exit(0);
325                         }
326                 }
327                 
328                 //do your part
329                 numSeqs = driverCreateSummary(position, averageQ, scores, qualfile, lines[0]);
330                 
331                 //force parent to wait until all the processes are done
332                 for (int i=0;i<processIDS.size();i++) { 
333                         int temp = processIDS[i];
334                         wait(&temp);
335                 }
336                 
337                 //parent reads in and combine Filter info
338                 for (int i = 0; i < processIDS.size(); i++) {
339                         string tempFilename = qualfile + toString(processIDS[i]) + ".num.temp";
340                         ifstream in;
341                         m->openInputFile(tempFilename, in);
342                         
343                         int temp, tempNum;
344                         in >> tempNum; m->gobble(in); numSeqs += tempNum;
345                         in >> tempNum; m->gobble(in);
346                         
347                         if (position.size() < tempNum) { position.resize(tempNum, 0); }
348                         if (averageQ.size() < tempNum) { averageQ.resize(tempNum, 0); }
349                         if (scores.size() < tempNum) { 
350                                 scores.resize(tempNum); 
351                                 for (int i = 0; i < scores.size(); i++) { scores[i].resize(41, 0); }
352                         }
353                         
354                         for (int k = 0; k < tempNum; k++)                       {               in >> temp; position[k] += temp;                        }               m->gobble(in);
355                         for (int k = 0; k < tempNum; k++)                       {               in >> temp; averageQ[k] += temp;                }               m->gobble(in);
356                         for (int k = 0; k < tempNum; k++)                       {       
357                                 for (int j = 0; j < 41; j++) {
358                                         in >> temp; scores[k][j] += temp;
359                                         m->gobble(in);
360                                 }       
361                         }
362                         
363                         in.close();
364                         m->mothurRemove(tempFilename);
365                 }
366                 
367 #else
368                 //////////////////////////////////////////////////////////////////////////////////////////////////////
369                 //Windows version shared memory, so be careful when passing variables through the seqSumQualData struct. 
370                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
371                 //Taking advantage of shared memory to allow both threads to add info to vectors.
372                 //////////////////////////////////////////////////////////////////////////////////////////////////////
373                 
374                 vector<seqSumQualData*> pDataArray; 
375                 DWORD   dwThreadIdArray[processors];
376                 HANDLE  hThreadArray[processors]; 
377                 
378                 //Create processor worker threads.
379                 for( int i=0; i<processors; i++ ){
380                         
381                         // Allocate memory for thread data.
382                         seqSumQualData* tempSum = new seqSumQualData(&position, &averageQ, &scores, filename, m, lines[i].start, lines[i].end, namefile, nameMap);
383                         pDataArray.push_back(tempSum);
384                         processIDS.push_back(i);
385                         
386                         //MySeqSumThreadFunction is in header. It must be global or static to work with the threads.
387                         //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
388                         hThreadArray[i] = CreateThread(NULL, 0, MySeqSumQualThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);   
389                 }
390                 
391                 //Wait until all threads have terminated.
392                 WaitForMultipleObjects(processors, hThreadArray, TRUE, INFINITE);
393                 
394                 //Close all thread handles and free memory allocations.
395                 for(int i=0; i < pDataArray.size(); i++){
396                         numSeqs += pDataArray[i]->count;
397                         CloseHandle(hThreadArray[i]);
398                         delete pDataArray[i];
399                 }
400 #endif          
401                 return numSeqs;
402         }
403         catch(exception& e) {
404                 m->errorOut(e, "SummaryQualCommand", "createProcessesCreateSummary");
405                 exit(1);
406         }
407 }
408 /**************************************************************************************************/
409 int SummaryQualCommand::printQual(string sumFile, vector<int>& position, vector<int>& averageQ, vector< vector<int> >& scores) {
410         try {
411                 ofstream out;
412                 m->openOutputFile(sumFile, out);
413                 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
414                 outputNames.push_back(sumFile); outputTypes["summary"].push_back(sumFile);
415                 
416                 //print headings
417                 out << "Position\tnumSeqs\tAverageQ\t";
418                 for (int i = 0; i < 41; i++) { out << "q" << i << '\t'; }
419                 out << endl;
420                 
421                 for (int i = 0; i < position.size(); i++) {
422                         
423                         if (m->control_pressed) { out.close(); return 0; }
424                         
425                         float average = averageQ[i] / (float) position[i];
426                         out << i << '\t' << position[i] << '\t' << average << '\t';
427                         
428                         for (int j = 0; j < 41; j++) {
429                                 out << scores[i][j] << '\t';
430                         }
431                         out << endl;
432                 }
433                 
434                 out.close();
435                 
436                 return 0;
437         }
438         catch(exception& e) {
439                 m->errorOut(e, "SummaryQualCommand", "printQual");
440                 exit(1);
441         }
442 }
443
444 /**************************************************************************************/
445
446