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