]> git.donarmstrong.com Git - mothur.git/blob - sensspeccommand.cpp
added citation function to commands
[mothur.git] / sensspeccommand.cpp
1 /*
2  *  sensspeccommand.cpp
3  *  Mothur
4  *
5  *  Created by Pat Schloss on 7/6/10.
6  *  Copyright 2010 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "sensspeccommand.h"
11
12 //**********************************************************************************************************************
13 vector<string> SensSpecCommand::setParameters(){        
14         try {
15                 CommandParameter plist("list", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(plist);
16                 CommandParameter pphylip("phylip", "InputTypes", "", "", "PhylipColumn", "PhylipColumn", "none",false,false); parameters.push_back(pphylip);
17                 //CommandParameter pname("name", "InputTypes", "", "", "none", "none", "ColumnName",false,false); parameters.push_back(pname);
18                 CommandParameter pcolumn("column", "InputTypes", "", "", "PhylipColumn", "PhylipColumn", "none",false,false); parameters.push_back(pcolumn);
19                 CommandParameter plabel("label", "String", "", "", "", "", "",false,false); parameters.push_back(plabel);
20                 CommandParameter pcutoff("cutoff", "Number", "", "-1.00", "", "", "",false,false); parameters.push_back(pcutoff);
21                 CommandParameter pprecision("precision", "Number", "", "100", "", "", "",false,false); parameters.push_back(pprecision);
22                 CommandParameter phard("hard", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(phard);
23                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
24                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
25                 
26                 vector<string> myArray;
27                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
28                 return myArray;
29         }
30         catch(exception& e) {
31                 m->errorOut(e, "SensSpecCommand", "setParameters");
32                 exit(1);
33         }
34 }
35 //**********************************************************************************************************************
36 string SensSpecCommand::getHelpString(){        
37         try {
38                 string helpString = "";
39                 helpString += "The sens.spec command....\n";
40                 return helpString;
41         }
42         catch(exception& e) {
43                 m->errorOut(e, "SensSpecCommand", "getHelpString");
44                 exit(1);
45         }
46 }
47 //**********************************************************************************************************************
48 SensSpecCommand::SensSpecCommand(){     
49         try {
50                 abort = true; calledHelp = true; 
51                 setParameters();
52                 vector<string> tempOutNames;
53                 outputTypes["sensspec"] = tempOutNames;
54         }
55         catch(exception& e) {
56                 m->errorOut(e, "SensSpecCommand", "SensSpecCommand");
57                 exit(1);
58         }
59 }
60 //***************************************************************************************************************
61
62 SensSpecCommand::SensSpecCommand(string option)  {
63         try {
64                 
65                 abort = false; calledHelp = false;   
66                 
67                 //allow user to run help
68                 if(option == "help") { help(); abort = true; calledHelp = true; }
69                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
70                 
71                 else {
72                         string temp;
73                         
74                         vector<string> myArray = setParameters();
75                         
76                         OptionParser parser(option);
77                         map<string,string> parameters = parser.getParameters();
78                         
79                         ValidParameters validParameter;
80                         map<string,string>::iterator it;
81                         
82                         //check to make sure all parameters are valid for command
83                         for (it = parameters.begin(); it != parameters.end(); it++) { 
84                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
85                         }
86                         
87                         //initialize outputTypes
88                         vector<string> tempOutNames;
89                         outputTypes["sensspec"] = tempOutNames;
90                         
91                         //if the user changes the input directory command factory will send this info to us in the output parameter 
92                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
93                         if (inputDir == "not found"){   inputDir = "";          }
94                         else {
95                                 string path;
96                                 it = parameters.find("list");
97                                 //user has given a template file
98                                 if(it != parameters.end()){ 
99                                         path = m->hasPath(it->second);
100                                         //if the user has not given a path then, add inputdir. else leave path alone.
101                                         if (path == "") {       parameters["list"] = inputDir + it->second;             }
102                                 }
103                                 
104                                 it = parameters.find("phylip");
105                                 //user has given a template file
106                                 if(it != parameters.end()){ 
107                                         path = m->hasPath(it->second);
108                                         //if the user has not given a path then, add inputdir. else leave path alone.
109                                         if (path == "") {       parameters["phylip"] = inputDir + it->second;           }
110                                 }
111                                 
112                                 it = parameters.find("column");
113                                 //user has given a template file
114                                 if(it != parameters.end()){ 
115                                         path = m->hasPath(it->second);
116                                         //if the user has not given a path then, add inputdir. else leave path alone.
117                                         if (path == "") {       parameters["column"] = inputDir + it->second;           }
118                                 }
119                                 
120                                 //it = parameters.find("name");
121                                 //user has given a template file
122                                 //if(it != parameters.end()){ 
123                                         //path = m->hasPath(it->second);
124                                         //if the user has not given a path then, add inputdir. else leave path alone.
125                                         //if (path == "") {     parameters["name"] = inputDir + it->second;             }
126                                 //}
127                                 
128                         }
129                         //check for required parameters
130                         listFile = validParameter.validFile(parameters, "list", true);
131                         if (listFile == "not found") {          
132                                 listFile = m->getListFile(); 
133                                 if (listFile != "") { m->mothurOut("Using " + listFile + " as input file for the list parameter."); m->mothurOutEndLine(); }
134                                 else {  m->mothurOut("You have no current list file and the list parameter is required."); m->mothurOutEndLine(); abort = true; }
135                         }
136                         else if (listFile == "not open") { abort = true; }      
137                         
138                         phylipfile = validParameter.validFile(parameters, "phylip", true);
139                         if (phylipfile == "not found") { phylipfile = "";  }
140                         else if (phylipfile == "not open") { abort = true; }    
141                         else { distFile = phylipfile; format = "phylip";   }
142                         
143                         columnfile = validParameter.validFile(parameters, "column", true);
144                         if (columnfile == "not found") { columnfile = ""; }
145                         else if (columnfile == "not open") { abort = true; }    
146                         else { distFile = columnfile; format = "column";   }
147                         
148                         if ((phylipfile == "") && (columnfile == "")) { //is there are current file available for either of these?
149                                 //give priority to column, then phylip
150                                 columnfile = m->getColumnFile(); 
151                                 if (columnfile != "") {  distFile = columnfile; format = "column";  m->mothurOut("Using " + columnfile + " as input file for the column parameter."); m->mothurOutEndLine(); }
152                                 else { 
153                                         phylipfile = m->getPhylipFile(); 
154                                         if (phylipfile != "") {  distFile = phylipfile; format = "phylip"; m->mothurOut("Using " + phylipfile + " as input file for the phylip parameter."); m->mothurOutEndLine(); }
155                                         else { 
156                                                 m->mothurOut("No valid current files. You must provide a phylip or column file."); m->mothurOutEndLine(); 
157                                                 abort = true;
158                                         }
159                                 }
160                         }else if ((phylipfile != "") && (columnfile != "")) { m->mothurOut("When executing a sens.spec command you must enter ONLY ONE of the following: phylip or column."); m->mothurOutEndLine(); abort = true; }
161                         
162                         
163                         //if the user changes the output directory command factory will send this info to us in the output parameter 
164                         outputDir = validParameter.validFile(parameters, "outputdir", false);
165                         if (outputDir == "not found"){  
166                                 outputDir = ""; 
167                                 outputDir += m->hasPath(listFile); //if user entered a file with a path then preserve it        
168                         }
169
170                         //check for optional parameter and set defaults
171                         // ...at some point should added some additional type checking...
172                         temp = validParameter.validFile(parameters, "hard", false);
173                         if (temp == "not found"){       hard = 0;       }
174                         else if(!m->isTrue(temp))       {       hard = 0;       }
175                         else if(m->isTrue(temp))        {       hard = 1;       }
176                         
177 //                      temp = validParameter.validFile(parameters, "name", true);
178 //                      if (temp == "not found")        {       nameFile = "";          }
179 //                      else if(temp == "not open")     {       abort = true;           }
180 //                      else                                            {       nameFile = temp;        }
181 //                      cout << "name:\t" << nameFile << endl;
182
183                         temp = validParameter.validFile(parameters, "cutoff", false);           if (temp == "not found") { temp = "-1.00"; }
184                         convert(temp, cutoff);  
185 //                      cout << cutoff << endl;
186                         
187                         temp = validParameter.validFile(parameters, "precision", false);        if (temp == "not found") { temp = "100"; }
188                         convert(temp, precision);  
189 //                      cout << precision << endl;
190                         
191                         lineLabel = validParameter.validFile(parameters, "label", false);       if (lineLabel == "not found") { lineLabel = ""; }
192                         
193                         sensSpecFileName = outputDir + m->getRootName(m->getSimpleName(listFile)) + ".sensspec";
194                 }
195         }
196         catch(exception& e) {
197                 m->errorOut(e, "SensSpecCommand", "SensSpecCommand");
198                 exit(1);
199         }
200 }
201 //***************************************************************************************************************
202
203 int SensSpecCommand::execute(){
204         try{
205                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
206
207                 setUpOutput();
208                 outputNames.push_back(sensSpecFileName); outputTypes["sensspec"].push_back(sensSpecFileName);
209                 if(format == "phylip")          {       processPhylip();        }
210                 else if(format == "column")     {       processColumn();        }
211                 
212                 m->mothurOutEndLine();
213                 m->mothurOut("Output File Name: "); m->mothurOutEndLine();
214                 m->mothurOut(sensSpecFileName); m->mothurOutEndLine();  
215                 m->mothurOutEndLine();
216                 
217                 
218                 return 0;       
219         }
220         catch(exception& e) {
221                 m->errorOut(e, "SensSpecCommand", "execute");
222                 exit(1);
223         }
224 }
225
226 //***************************************************************************************************************
227
228 void SensSpecCommand::processPhylip(){
229         try{
230                 //probably need some checking to confirm that the names in the distance matrix are the same as those in the list file
231                 
232                 ifstream inputListFile;
233                 m->openInputFile(listFile, inputListFile);
234                 
235                 string origCutoff = "";
236                 bool getCutoff = 0;
237                 if(cutoff == -1.00)     {       getCutoff = 1;                                                                                                                  }
238                 else                            {       origCutoff = toString(cutoff);  cutoff += (0.49 / double(precision));   }
239                 
240                 string label;
241                 int numOTUs;
242
243                 map<string, int> seqMap;
244                 string seqList;
245                 
246                 while(inputListFile){
247                         inputListFile >> label >> numOTUs;
248                         for(int i=0;i<numOTUs;i++){
249                                 inputListFile >> seqList;
250                                 int seqListLength = seqList.length();
251                                 string seqName = "";
252                                 for(int j=0;j<seqListLength;j++){
253                                         
254                                         if(seqList[j] == ','){
255                                                 seqMap[seqName] = i;
256                                                 seqName = "";
257                                         }
258                                         else{
259                                                 seqName += seqList[j];
260                                         }
261                                         
262                                 }
263                                 seqMap[seqName] = i;
264                         }
265                         m->gobble(inputListFile);
266                 
267                         int lNumSeqs = seqMap.size();
268                         int pNumSeqs = 0;
269
270                         ifstream phylipFile;
271                         m->openInputFile(distFile, phylipFile);
272                         phylipFile >> pNumSeqs;
273                         if(pNumSeqs != lNumSeqs){       cout << "numSeq mismatch!" << endl;     }
274                         
275                         string seqName;
276                         double distance;
277                         vector<int> otuIndices(lNumSeqs, -1);
278                                 
279                         truePositives = 0;
280                         falsePositives = 0;
281                         trueNegatives = 0;
282                         falseNegatives = 0;
283                         
284                         if(getCutoff == 1){
285                                 if(label != "unique"){
286                                         origCutoff = label;
287                                         convert(label, cutoff);
288                                         if(hard == 0){  cutoff += (0.49 / double(precision));   }               
289                                 }
290                                 else{
291                                         origCutoff = "unique";
292                                         cutoff = 0.0000;
293                                 }
294                         }
295                                    
296                         cout << label << endl;
297                         
298                         for(int i=0;i<lNumSeqs;i++){
299                                 phylipFile >> seqName;
300                                 otuIndices[i] = seqMap[seqName];
301                                 
302                                 for(int j=0;j<i;j++){
303                                         phylipFile >> distance;
304                                         
305                                         if(distance <= cutoff){
306                                                 if(otuIndices[i] == otuIndices[j])      {       truePositives++;        }
307                                                 else                                                            {       falseNegatives++;       }
308                                         }
309                                         else{
310                                                 if(otuIndices[i] == otuIndices[j])      {       falsePositives++;       }
311                                                 else                                                            {       trueNegatives++;        }
312                                         }
313                                 }
314                         }
315                         phylipFile.close();
316                         
317                         outputStatistics(label, origCutoff);
318                 }
319                 inputListFile.close();
320
321         }
322         catch(exception& e) {
323                 m->errorOut(e, "SensSpecCommand", "processPhylip");
324                 exit(1);
325         }
326 }
327
328 //***************************************************************************************************************
329
330 void SensSpecCommand::processColumn(){
331         try{            
332                 ifstream inputListFile;
333                 m->openInputFile(listFile, inputListFile);
334                 
335                 string origCutoff = "";
336                 bool getCutoff = 0;
337                 if(cutoff == -1.00)     {       getCutoff = 1;                                                                                                                  }
338                 else                            {       origCutoff = toString(cutoff);  cutoff += (0.49 / double(precision));   }
339                 
340                 set<string> seqPairSet;
341                 
342                 string label, seqList;
343                 int numOTUs;
344                 int numSeqs;
345                 
346                 while(inputListFile){
347                         numSeqs = 0;
348                         
349                         inputListFile >> label >> numOTUs;
350                         for(int i=0;i<numOTUs;i++){
351                                 
352                                 vector<string> seqNameVector;
353                                 
354                                 inputListFile >> seqList;
355                                 int seqListLength = seqList.length();
356                                 string seqName = "";
357                                 for(int j=0;j<seqListLength;j++){
358                                         
359                                         if(seqList[j] == ','){
360                                                 seqNameVector.push_back(seqName);
361                                                 seqName = "";
362                                         }
363                                         else{
364                                                 seqName += seqList[j];
365                                         }
366                                 }
367                                 seqNameVector.push_back(seqName);
368
369                                 numSeqs += seqNameVector.size();
370                                 
371                                 int numSeqsInOTU = seqNameVector.size();
372                                 for(int j=0;j<numSeqsInOTU;j++){
373                                         string seqPairString = "";                              
374                                         for(int k=0;k<j;k++){
375                                                 if(seqNameVector[j] < seqNameVector[k]) {       seqPairString = seqNameVector[j] + '\t' + seqNameVector[k];     }
376                                                 else                                                                    {       seqPairString = seqNameVector[k] + '\t' + seqNameVector[j];     }
377                                                 seqPairSet.insert(seqPairString);
378                                         }
379                                 }
380                         }
381                         m->gobble(inputListFile);
382                         
383                         int numDists = (numSeqs * (numSeqs-1) / 2);
384
385                         ifstream columnFile;
386                         m->openInputFile(distFile, columnFile);
387                         string seqNameA, seqNameB, seqPairString;
388                         double distance;
389                         
390                         truePositives = 0;
391                         falsePositives = 0;
392                         trueNegatives = numDists;
393                         falseNegatives = 0;
394                         
395                         if(getCutoff == 1){
396                                 if(label != "unique"){
397                                         origCutoff = label;
398                                         convert(label, cutoff);
399                                         if(hard == 0){  cutoff += (0.49 / double(precision));   }               
400                                 }
401                                 else{
402                                         origCutoff = "unique";
403                                         cutoff = 0.0000;
404                                 }
405                         }
406                         
407                         cout << label << endl;
408                         
409                         while(columnFile){
410                                 columnFile >> seqNameA >> seqNameB >> distance;
411                                 if(seqNameA < seqNameB) {       seqPairString = seqNameA + '\t' + seqNameB;     }
412                                 else                                    {       seqPairString = seqNameB + '\t' + seqNameA;     }
413
414                                 set<string>::iterator it = seqPairSet.find(seqPairString);
415                         
416                                 if(distance <= cutoff){
417                                         if(it != seqPairSet.end()){
418                                                 truePositives++;
419                                                 seqPairSet.erase(it);   
420                                         }
421                                         else{
422                                                 falseNegatives++;
423                                         }
424                                         trueNegatives--;
425                                 }
426                                 else if(it != seqPairSet.end()){        
427                                         falsePositives++;
428                                         trueNegatives--;
429                                         seqPairSet.erase(it);   
430                                 }
431                                 
432                                 m->gobble(columnFile);
433                         }
434                         falsePositives += seqPairSet.size();
435                         
436                         outputStatistics(label, origCutoff);
437                 }
438         }
439         catch(exception& e) {
440                 m->errorOut(e, "SensSpecCommand", "processColumn");
441                 exit(1);
442         }
443 }
444
445 //***************************************************************************************************************
446
447 void SensSpecCommand::setUpOutput(){
448         try{            
449                 ofstream sensSpecFile;
450                 m->openOutputFile(sensSpecFileName, sensSpecFile);
451                 
452                 sensSpecFile << "label\tcutoff\ttp\ttn\tfp\tfn\tsensitivity\tspecificity\tppv\tnpv\tfdr\taccuracy\tmcc\tf1score\n";
453
454                 sensSpecFile.close();
455         }
456         catch(exception& e) {
457                 m->errorOut(e, "SensSpecCommand", "setUpOutput");
458                 exit(1);
459         }
460 }
461
462 //***************************************************************************************************************
463
464 void SensSpecCommand::outputStatistics(string label, string cutoff){
465         try{            
466                 double tp = (double) truePositives;
467                 double fp = (double) falsePositives;
468                 double tn = (double) trueNegatives;
469                 double fn = (double) falseNegatives;
470                 
471                 double p = tp + fn;
472                 double n = fp + tn;
473                 double pPrime = tp + fp;
474                 double nPrime = tn + fn;
475                 
476                 double sensitivity = tp / p;    
477                 double specificity = tn / n;
478                 double positivePredictiveValue = tp / pPrime;
479                 double negativePredictiveValue = tn / nPrime;
480                 double falseDiscoveryRate = fp / pPrime;
481                 
482                 double accuracy = (tp + tn) / (p + n);
483                 double matthewsCorrCoef = (tp * tn - fp * fn) / sqrt(p * n * pPrime * nPrime);  if(p == 0 || n == 0){   matthewsCorrCoef = 0;   }
484                 double f1Score = 2.0 * tp / (p + pPrime);
485                 
486                 
487                 if(p == 0)                      {       sensitivity = 0;        matthewsCorrCoef = 0;   }
488                 if(n == 0)                      {       specificity = 0;        matthewsCorrCoef = 0;   }
489                 if(p + n == 0)          {       accuracy = 0;                                                           }
490                 if(p + pPrime == 0)     {       f1Score = 0;                                                            }
491                 if(pPrime == 0)         {       positivePredictiveValue = 0;    falseDiscoveryRate = 0; matthewsCorrCoef = 0;   }
492                 if(nPrime == 0)         {       negativePredictiveValue = 0;    matthewsCorrCoef = 0;                                                   }
493                 
494                 ofstream sensSpecFile;
495                 m->openOutputFileAppend(sensSpecFileName, sensSpecFile);
496                 
497                 sensSpecFile << label << '\t' << cutoff << '\t';
498                 sensSpecFile << truePositives << '\t' << trueNegatives << '\t' << falsePositives << '\t' << falseNegatives << '\t';
499                 sensSpecFile << setprecision(4);
500                 sensSpecFile << sensitivity << '\t' << specificity << '\t' << positivePredictiveValue << '\t' << negativePredictiveValue << '\t';
501                 sensSpecFile << falseDiscoveryRate << '\t' << accuracy << '\t' << matthewsCorrCoef << '\t' << f1Score << endl;
502                 
503                 sensSpecFile.close();
504         }
505         catch(exception& e) {
506                 m->errorOut(e, "SensSpecCommand", "outputStatistics");
507                 exit(1);
508         }
509 }
510
511 //***************************************************************************************************************
512
513
514