]> git.donarmstrong.com Git - mothur.git/blob - pcacommand.cpp
fixes while testing
[mothur.git] / pcacommand.cpp
1
2 /*
3  *  pcacommand.cpp
4  *  Mothur
5  *
6  *  Created by westcott on 1/4/10.
7  *  Copyright 2010 Schloss Lab. All rights reserved.
8  *
9  */
10
11 #include "pcacommand.h"
12
13 //**********************************************************************************************************************
14 vector<string> PCACommand::getValidParameters(){        
15         try {
16                 string Array[] =  {"phylip", "outputdir","inputdir"};
17                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
18                 return myArray;
19         }
20         catch(exception& e) {
21                 m->errorOut(e, "PCACommand", "getValidParameters");
22                 exit(1);
23         }
24 }
25 //**********************************************************************************************************************
26 PCACommand::PCACommand(){       
27         try {
28                 abort = true;
29                 //initialize outputTypes
30                 vector<string> tempOutNames;
31                 outputTypes["pcoa"] = tempOutNames;
32                 outputTypes["loadings"] = tempOutNames;
33         }
34         catch(exception& e) {
35                 m->errorOut(e, "PCACommand", "PCACommand");
36                 exit(1);
37         }
38 }
39 //**********************************************************************************************************************
40 vector<string> PCACommand::getRequiredParameters(){     
41         try {
42                 string Array[] =  {"phylip"};
43                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
44                 return myArray;
45         }
46         catch(exception& e) {
47                 m->errorOut(e, "PCACommand", "getRequiredParameters");
48                 exit(1);
49         }
50 }
51 //**********************************************************************************************************************
52 vector<string> PCACommand::getRequiredFiles(){  
53         try {
54                 vector<string> myArray;
55                 return myArray;
56         }
57         catch(exception& e) {
58                 m->errorOut(e, "PCACommand", "getRequiredFiles");
59                 exit(1);
60         }
61 }
62 //**********************************************************************************************************************
63
64 PCACommand::PCACommand(string option)  {
65         try {
66                 abort = false;
67                 
68                 //allow user to run help
69                 if(option == "help") { help(); abort = true; }
70                 
71                 else {
72                         //valid paramters for this command
73                         string Array[] =  {"phylip","outputdir", "inputdir"};
74                         vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
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                         //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("phylip");
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["phylip"] = inputDir + it->second;           }
97                                 }
98                         }
99                         
100                         //initialize outputTypes
101                         vector<string> tempOutNames;
102                         outputTypes["pcoa"] = tempOutNames;
103                         outputTypes["loadings"] = tempOutNames;
104                         
105                         //required parameters
106                         phylipfile = validParameter.validFile(parameters, "phylip", true);
107                         if (phylipfile == "not open") { abort = true; }
108                         else if (phylipfile == "not found") { phylipfile = ""; abort = true; }  
109                         else {  filename = phylipfile;  }
110                         
111                         //if the user changes the output directory command factory will send this info to us in the output parameter 
112                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
113                                 outputDir = ""; 
114                                 outputDir += m->hasPath(phylipfile); //if user entered a file with a path then preserve it      
115                         }
116                         
117                         //error checking on files       
118                         if (phylipfile == "")   { m->mothurOut("You must provide a distance file before running the pca command."); m->mothurOutEndLine(); abort = true; }              
119                 }
120
121         }
122         catch(exception& e) {
123                 m->errorOut(e, "PCACommand", "PCACommand");
124                 exit(1);
125         }
126 }
127 //**********************************************************************************************************************
128 void PCACommand::help(){
129         try {
130         
131                 m->mothurOut("The pca command..."); m->mothurOutEndLine();
132         }
133         catch(exception& e) {
134                 m->errorOut(e, "PCACommand", "help");
135                 exit(1);
136         }
137 }
138 //**********************************************************************************************************************
139 PCACommand::~PCACommand(){}
140 //**********************************************************************************************************************
141 int PCACommand::execute(){
142         try {
143         
144                 if (abort == true) { return 0; }
145                 
146                 cout.setf(ios::fixed, ios::floatfield);
147                 cout.setf(ios::showpoint);
148                 cerr.setf(ios::fixed, ios::floatfield);
149                 cerr.setf(ios::showpoint);
150                 
151                 vector<string> names;
152                 vector<vector<double> > D;
153         
154                 fbase = outputDir + m->getRootName(m->getSimpleName(filename));
155                 
156                 read(filename, names, D);
157                 
158                 if (m->control_pressed) { return 0; }
159         
160                 double offset = 0.0000;
161                 vector<double> d;
162                 vector<double> e;
163                 vector<vector<double> > G = D;
164                 vector<vector<double> > copy_G;
165                 //int rank = D.size();
166                 
167                 m->mothurOut("\nProcessing...\n");
168                 
169                 for(int count=0;count<2;count++){
170                         recenter(offset, D, G);         if (m->control_pressed) { return 0; }
171                         tred2(G, d, e);                         if (m->control_pressed) { return 0; }
172                         qtli(d, e, G);                          if (m->control_pressed) { return 0; }
173                         offset = d[d.size()-1];
174                         if(offset > 0.0) break;
175                 } 
176                 
177                 if (m->control_pressed) { return 0; }
178                 
179                 output(fbase, names, G, d);
180                 
181                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        remove(outputNames[i].c_str());  } return 0; }
182                 
183                 m->mothurOutEndLine();
184                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
185                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
186                 m->mothurOutEndLine();
187                 
188                 return 0;
189         }
190         catch(exception& e) {
191                 m->errorOut(e, "PCACommand", "execute");
192                 exit(1);
193         }
194 }
195 /*********************************************************************************************************************************/
196
197 inline double SIGN(const double a, const double b)
198 {
199     return b>=0 ? (a>=0 ? a:-a) : (a>=0 ? -a:a);
200 }
201
202 /*********************************************************************************************************************************/
203
204 void PCACommand::get_comment(istream& f, char begin, char end){
205         try {
206                 char d=f.get();
207                 while(d != end){        d = f.get();    }
208                 d = f.peek();
209         }
210         catch(exception& e) {
211                 m->errorOut(e, "PCACommand", "get_comment");
212                 exit(1);
213         }
214 }       
215
216 /*********************************************************************************************************************************/
217
218 int PCACommand::read_phylip(istream& f, int square_m, vector<string>& name_list, vector<vector<double> >& d){
219         try {
220                 //     int count1=0;
221                 //     int count2=0;
222                 
223                 int rank;
224                 f >> rank;
225                 
226                 name_list.resize(rank);
227                 d.resize(rank);
228                 if(square_m == 1){
229                         for(int i=0;i<rank;i++)
230                                 d[i].resize(rank);
231                         for(int i=0;i<rank;i++) {
232                                 f >> name_list[i];
233                                 //                      cout << i << "\t" << name_list[i] << endl;
234                                 for(int j=0;j<rank;j++) {
235                                         if (m->control_pressed) { return 0; }
236                                         
237                                         f >> d[i][j];
238                                         if (d[i][j] == -0.0000)
239                                                 d[i][j] = 0.0000;
240                                 }
241                         }
242                 }
243                 else if(square_m == 2){
244                         for(int i=0;i<rank;i++){
245                                 d[i].resize(rank);
246                         }
247                         d[0][0] = 0.0000;
248                         f >> name_list[0];
249                         for(int i=1;i<rank;i++){
250                                 f >> name_list[i];
251                                 d[i][i]=0.0000;
252                                 for(int j=0;j<i;j++){
253                                         if (m->control_pressed) { return 0; }
254                                         f >> d[i][j];
255                                         if (d[i][j] == -0.0000)
256                                                 d[i][j] = 0.0000;
257                                         d[j][i]=d[i][j];
258                                 }
259                         }
260                 }
261                 
262                 return 0;
263         }
264         catch(exception& e) {
265                 m->errorOut(e, "PCACommand", "read_phylip");
266                 exit(1);
267         }
268
269 }
270
271 /*********************************************************************************************************************************/
272
273 void PCACommand::read(string fname, vector<string>& names, vector<vector<double> >& D){
274         try {
275                 ifstream f;
276                 m->openInputFile(fname, f);
277                         
278                 //check whether matrix is square
279                 char d;
280                 int q = 1;
281                 int numSeqs;
282                 string name;
283                 
284                 f >> numSeqs >> name; 
285                 
286                 while((d=f.get()) != EOF){
287                         
288                         //is d a number meaning its square
289                         if(isalnum(d)){ 
290                                 q = 1; 
291                                 break; 
292                         }
293                         
294                         //is d a line return meaning its lower triangle
295                         if(d == '\n'){
296                                 q = 2;
297                                 break;
298                         }
299                 }
300                 f.close();
301                 
302                 //reopen to get back to beginning
303                 m->openInputFile(fname, f);                     
304                 read_phylip(f, q, names, D);
305         }
306                 catch(exception& e) {
307                 m->errorOut(e, "PCACommand", "read");
308                 exit(1);
309         }
310 }
311
312 /*********************************************************************************************************************************/
313
314 double PCACommand::pythag(double a, double b)   {       return(pow(a*a+b*b,0.5));       }
315
316 /*********************************************************************************************************************************/
317
318 void PCACommand::matrix_mult(vector<vector<double> > first, vector<vector<double> > second, vector<vector<double> >& product){
319         try {
320                 int first_rows = first.size();
321                 int first_cols = first[0].size();
322                 int second_cols = second[0].size();
323                 
324                 product.resize(first_rows);
325                 for(int i=0;i<first_rows;i++){
326                         product[i].resize(second_cols);
327                 }
328                 
329                 for(int i=0;i<first_rows;i++){
330                         for(int j=0;j<second_cols;j++){
331                                 product[i][j] = 0.0;
332                                 for(int k=0;k<first_cols;k++){
333                                         product[i][j] += first[i][k] * second[k][j];
334                                 }
335                         }
336                 }
337         }
338         catch(exception& e) {
339                 m->errorOut(e, "PCACommand", "matrix_mult");
340                 exit(1);
341         }
342
343 }
344
345 /*********************************************************************************************************************************/
346
347 void PCACommand::recenter(double offset, vector<vector<double> > D, vector<vector<double> >& G){
348         try {
349                 int rank = D.size();
350                 
351                 vector<vector<double> > A(rank);
352                 vector<vector<double> > C(rank);
353                 for(int i=0;i<rank;i++){
354                         A[i].resize(rank);
355                         C[i].resize(rank);
356                 }
357                 
358                 double scale = -1.0000 / (double) rank;
359                 
360                 for(int i=0;i<rank;i++){
361                         A[i][i] = 0.0000;
362                         C[i][i] = 1.0000 + scale;
363                         for(int j=i+1;j<rank;j++){
364                                 A[i][j] = A[j][i] = -0.5 * D[i][j] * D[i][j] + offset;
365                                 C[i][j] = C[j][i] = scale;
366                         }
367                 }
368                 
369                 matrix_mult(C,A,A);
370                 matrix_mult(A,C,G);
371         }
372         catch(exception& e) {
373                 m->errorOut(e, "PCACommand", "recenter");
374                 exit(1);
375         }
376
377 }
378
379 /*********************************************************************************************************************************/
380
381 //  This function is taken from Numerical Recipes in C++ by Press et al., 2nd edition, pg. 479
382
383 void PCACommand::tred2(vector<vector<double> >& a, vector<double>& d, vector<double>& e){
384         try {
385                 double scale, hh, h, g, f;
386                 
387                 int n = a.size();
388                 
389                 d.resize(n);
390                 e.resize(n);
391                 
392                 for(int i=n-1;i>0;i--){
393                         int l=i-1;
394                         h = scale = 0.0000;
395                         if(l>0){
396                                 for(int k=0;k<l+1;k++){
397                                         scale += fabs(a[i][k]);
398                                 }
399                                 if(scale == 0.0){
400                                         e[i] = a[i][l];
401                                 }
402                                 else{
403                                         for(int k=0;k<l+1;k++){
404                                                 a[i][k] /= scale;
405                                                 h += a[i][k] * a[i][k];
406                                         }
407                                         f = a[i][l];
408                                         g = (f >= 0.0 ? -sqrt(h) : sqrt(h));
409                                         e[i] = scale * g;
410                                         h -= f * g;
411                                         a[i][l] = f - g;
412                                         f = 0.0;
413                                         for(int j=0;j<l+1;j++){
414                                                 a[j][i] = a[i][j] / h;
415                                                 g = 0.0;
416                                                 for(int k=0;k<j+1;k++){
417                                                         g += a[j][k] * a[i][k];
418                                                 }
419                                                 for(int k=j+1;k<l+1;k++){
420                                                         g += a[k][j] * a[i][k];
421                                                 }
422                                                 e[j] = g / h;
423                                                 f += e[j] * a[i][j];
424                                         }
425                                         hh = f / (h + h);
426                                         for(int j=0;j<l+1;j++){
427                                                 f = a[i][j];
428                                                 e[j] = g = e[j] - hh * f;
429                                                 for(int k=0;k<j+1;k++){
430                                                         a[j][k] -= (f * e[k] + g * a[i][k]);
431                                                 }
432                                         }
433                                 }
434                         }
435                         else{
436                                 e[i] = a[i][l];
437                         }
438                         
439                         d[i] = h;
440                 }
441                 
442                 d[0] = 0.0000;
443                 e[0] = 0.0000;
444                 
445                 for(int i=0;i<n;i++){
446                         int l = i;
447                         if(d[i] != 0.0){
448                                 for(int j=0;j<l;j++){
449                                         g = 0.0000;
450                                         for(int k=0;k<l;k++){
451                                                 g += a[i][k] * a[k][j];
452                                         }
453                                         for(int k=0;k<l;k++){
454                                                 a[k][j] -= g * a[k][i];
455                                         }
456                                 }
457                         }
458                         d[i] = a[i][i];
459                         a[i][i] = 1.0000;
460                         for(int j=0;j<l;j++){
461                                 a[j][i] = a[i][j] = 0.0;
462                         }
463                 }
464         }
465         catch(exception& e) {
466                 m->errorOut(e, "PCACommand", "tred2");
467                 exit(1);
468         }
469
470 }
471
472 /*********************************************************************************************************************************/
473
474 //  This function is taken from Numerical Recipes in C++ by Press et al., 2nd edition, pg. 479
475
476 void PCACommand::qtli(vector<double>& d, vector<double>& e, vector<vector<double> >& z) {
477         try {
478                 int m, i, iter;
479                 double s, r, p, g, f, dd, c, b;
480                 
481                 int n = d.size();
482                 for(int i=1;i<=n;i++){
483                         e[i-1] = e[i];
484                 }
485                 e[n-1] = 0.0000;
486                 
487                 for(int l=0;l<n;l++){
488                         iter = 0;
489                         do {
490                                 for(m=l;m<n-1;m++){
491                                         dd = fabs(d[m]) + fabs(d[m+1]);
492                                         if(fabs(e[m])+dd == dd) break;
493                                 }
494                                 if(m != l){
495                                         if(iter++ == 30) cerr << "Too many iterations in tqli\n";
496                                         g = (d[l+1]-d[l]) / (2.0 * e[l]);
497                                         r = pythag(g, 1.0);
498                                         g = d[m] - d[l] + e[l] / (g + SIGN(r,g));
499                                         s = c = 1.0;
500                                         p = 0.0000;
501                                         for(i=m-1;i>=l;i--){
502                                                 f = s * e[i];
503                                                 b = c * e[i];
504                                                 e[i+1] = (r=pythag(f,g));
505                                                 if(r==0.0){
506                                                         d[i+1] -= p;
507                                                         e[m] = 0.0000;
508                                                         break;
509                                                 }
510                                                 s = f / r;
511                                                 c = g / r;
512                                                 g = d[i+1] - p;
513                                                 r = (d[i] - g) * s + 2.0 * c * b;
514                                                 d[i+1] = g + ( p = s * r);
515                                                 g = c * r - b;
516                                                 for(int k=0;k<n;k++){
517                                                         f = z[k][i+1];
518                                                         z[k][i+1] = s * z[k][i] + c * f;
519                                                         z[k][i] = c * z[k][i] - s * f;
520                                                 }
521                                         }
522                                         if(r == 0.00 && i >= l) continue;
523                                         d[l] -= p;
524                                         e[l] = g;
525                                         e[m] = 0.0;
526                                 }
527                         } while (m != l);
528                 }
529                 
530                 int k;
531                 for(int i=0;i<n;i++){
532                         p=d[k=i];
533                         for(int j=i;j<n;j++){
534                                 if(d[j] >= p){
535                                         p=d[k=j];
536                                 }
537                         }
538                         if(k!=i){
539                                 d[k]=d[i];
540                                 d[i]=p;
541                                 for(int j=0;j<n;j++){
542                                         p=z[j][i];
543                                         z[j][i] = z[j][k];
544                                         z[j][k] = p;
545                                 }
546                         }
547                 }
548         }
549         catch(exception& e) {
550                 m->errorOut(e, "PCACommand", "qtli");
551                 exit(1);
552         }
553 }
554
555 /*********************************************************************************************************************************/
556
557 void PCACommand::output(string fnameRoot, vector<string> name_list, vector<vector<double> > G, vector<double> d) {
558         try {
559                 int rank = name_list.size();
560                 double dsum = 0.0000;
561                 for(int i=0;i<rank;i++){
562                         dsum += d[i];
563                         for(int j=0;j<rank;j++){
564                                 if(d[j] >= 0)   {       G[i][j] *= pow(d[j],0.5);       }
565                                 else                    {       G[i][j] = 0.00000;                      }
566                         }
567                 }
568                 
569                 ofstream pcaData((fnameRoot+"pcoa").c_str(), ios::trunc);
570                 pcaData.setf(ios::fixed, ios::floatfield);
571                 pcaData.setf(ios::showpoint);   
572                 outputNames.push_back(fnameRoot+"pcoa");
573                 outputTypes["pcoa"].push_back(fnameRoot+"pcoa");
574                 
575                 ofstream pcaLoadings((fnameRoot+"pcoa.loadings").c_str(), ios::trunc);
576                 pcaLoadings.setf(ios::fixed, ios::floatfield);
577                 pcaLoadings.setf(ios::showpoint);
578                 outputNames.push_back(fnameRoot+"pcoa.loadings");
579                 outputTypes["loadings"].push_back(fnameRoot+"pcoa.loadings");   
580                 
581                 pcaLoadings << "axis\tloading\n";
582                 for(int i=0;i<rank;i++){
583                         pcaLoadings << i+1 << '\t' << d[i] * 100.0 / dsum << endl;
584                 }
585                 
586                 pcaData << "group";
587                 for(int i=0;i<rank;i++){
588                         pcaData << '\t' << "axis" << i+1;
589                 }
590                 pcaData << endl;
591                 
592                 for(int i=0;i<rank;i++){
593                         pcaData << name_list[i] << '\t';
594                         for(int j=0;j<rank;j++){
595                                 pcaData << G[i][j] << '\t';
596                         }
597                         pcaData << endl;
598                 }
599         }
600         catch(exception& e) {
601                 m->errorOut(e, "PCACommand", "output");
602                 exit(1);
603         }
604 }
605
606 /*********************************************************************************************************************************/
607