2 * summaryqualcommand.cpp
5 * Created by westcott on 11/28/11.
6 * Copyright 2011 Schloss Lab. All rights reserved.
10 #include "summaryqualcommand.h"
13 //**********************************************************************************************************************
14 vector<string> SummaryQualCommand::setParameters(){
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);
22 vector<string> myArray;
23 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
27 m->errorOut(e, "SummaryQualCommand", "setParameters");
31 //**********************************************************************************************************************
32 string SummaryQualCommand::getHelpString(){
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";
44 m->errorOut(e, "SummaryQualCommand", "getHelpString");
48 //**********************************************************************************************************************
49 string SummaryQualCommand::getOutputFileNameTag(string type, string inputName=""){
51 string outputFileName = "";
52 map<string, vector<string> >::iterator it;
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"); }
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; }
61 return outputFileName;
64 m->errorOut(e, "SummaryQualCommand", "getOutputFileNameTag");
68 //**********************************************************************************************************************
69 SummaryQualCommand::SummaryQualCommand(){
71 abort = true; calledHelp = true;
73 vector<string> tempOutNames;
74 outputTypes["summary"] = tempOutNames;
77 m->errorOut(e, "SummaryQualCommand", "SummaryQualCommand");
81 //***************************************************************************************************************
83 SummaryQualCommand::SummaryQualCommand(string option) {
85 abort = false; calledHelp = false;
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;}
92 vector<string> myArray = setParameters();
94 OptionParser parser(option);
95 map<string,string> parameters = parser.getParameters();
97 ValidParameters validParameter;
98 map<string,string>::iterator it;
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; }
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 = ""; }
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; }
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; }
127 //initialize outputTypes
128 vector<string> tempOutNames;
129 outputTypes["summary"] = tempOutNames;
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); }
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); }
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"){
148 outputDir += m->hasPath(qualfile); //if user entered a file with a path then preserve it
151 string temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
152 m->setProcessors(temp);
153 m->mothurConvert(temp, processors);
155 if (namefile == "") {
156 vector<string> files; files.push_back(qualfile);
157 parser.getNameFile(files);
161 catch(exception& e) {
162 m->errorOut(e, "SummaryQualCommand", "SummaryQualCommand");
166 //***************************************************************************************************************
167 int SummaryQualCommand::execute(){
170 if (abort == true) { if (calledHelp) { return 0; } return 2; }
172 int start = time(NULL);
175 vector<int> position;
176 vector<int> averageQ;
177 vector< vector<int> > scores;
179 if (m->control_pressed) { return 0; }
181 if (namefile != "") { nameMap = m->readNames(namefile); }
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)])); }
188 if (processors == 1) {
189 lines.push_back(linePair(0, 1000));
191 positions = m->setFilePosFasta(qualfile, numSeqs);
192 if (positions.size() < processors) { processors = positions.size(); }
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));
205 if(processors == 1){ numSeqs = driverCreateSummary(position, averageQ, scores, qualfile, lines[0]); }
206 else{ numSeqs = createProcessesCreateSummary(position, averageQ, scores, qualfile); }
208 if (m->control_pressed) { return 0; }
211 string summaryFile = outputDir + m->getRootName(m->getSimpleName(qualfile)) + getOutputFileNameTag("summary");
212 printQual(summaryFile, position, averageQ, scores);
214 if (m->control_pressed) { m->mothurRemove(summaryFile); return 0; }
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();
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();
235 catch(exception& e) {
236 m->errorOut(e, "SummaryQualCommand", "execute");
240 /**************************************************************************************/
241 int SummaryQualCommand::driverCreateSummary(vector<int>& position, vector<int>& averageQ, vector< vector<int> >& scores, string filename, linePair filePos) {
244 m->openInputFile(filename, in);
246 in.seekg(filePos.start);
253 if (m->control_pressed) { in.close(); return 1; }
255 QualityScores current(in); m->gobble(in);
257 if (current.getName() != "") {
260 if (namefile != "") {
261 //make sure this sequence is in the namefile, else error
262 map<string, int>::iterator it = nameMap.find(current.getName());
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; }
268 vector<int> thisScores = current.getQualityScores();
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); }
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++) {
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; }
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; }
294 if (in.eof()) { break; }
302 catch(exception& e) {
303 m->errorOut(e, "SummaryQualCommand", "driverCreateSummary");
307 /**************************************************************************************************/
308 int SummaryQualCommand::createProcessesCreateSummary(vector<int>& position, vector<int>& averageQ, vector< vector<int> >& scores, string filename) {
314 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
316 //loop through and create all the processes you want
317 while (process != processors) {
321 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
324 numSeqs = driverCreateSummary(position, averageQ, scores, qualfile, lines[process]);
326 //pass numSeqs to parent
328 string tempFile = qualfile + toString(getpid()) + ".num.temp";
329 m->openOutputFile(tempFile, out);
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';
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); }
354 numSeqs = driverCreateSummary(position, averageQ, scores, qualfile, lines[0]);
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];
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";
366 m->openInputFile(tempFilename, in);
369 in >> tempNum; m->gobble(in); numSeqs += tempNum;
370 in >> tempNum; m->gobble(in);
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); }
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;
389 m->mothurRemove(tempFilename);
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 //////////////////////////////////////////////////////////////////////////////////////////////////////
399 vector<seqSumQualData*> pDataArray;
400 DWORD dwThreadIdArray[processors];
401 HANDLE hThreadArray[processors];
403 //Create processor worker threads.
404 for( int i=0; i<processors; i++ ){
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);
411 hThreadArray[i] = CreateThread(NULL, 0, MySeqSumQualThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);
414 //Wait until all threads have terminated.
415 WaitForMultipleObjects(processors, hThreadArray, TRUE, INFINITE);
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); }
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]; } }
432 CloseHandle(hThreadArray[i]);
433 delete pDataArray[i];
438 catch(exception& e) {
439 m->errorOut(e, "SummaryQualCommand", "createProcessesCreateSummary");
443 /**************************************************************************************************/
444 int SummaryQualCommand::printQual(string sumFile, vector<int>& position, vector<int>& averageQ, vector< vector<int> >& scores) {
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);
452 out << "Position\tnumSeqs\tAverageQ\t";
453 for (int i = 0; i < 41; i++) { out << "q" << i << '\t'; }
456 for (int i = 0; i < position.size(); i++) {
458 if (m->control_pressed) { out.close(); return 0; }
460 float average = averageQ[i] / (float) position[i];
461 out << i << '\t' << position[i] << '\t' << average << '\t';
463 for (int j = 0; j < 41; j++) {
464 out << scores[i][j] << '\t';
473 catch(exception& e) {
474 m->errorOut(e, "SummaryQualCommand", "printQual");
479 /**************************************************************************************/