]> git.donarmstrong.com Git - mothur.git/blob - pcacommand.cpp
added set.dir command and modified commands to redirect input and output, removed...
[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
15 PCACommand::PCACommand(string option){
16         try {
17                 abort = false;
18                 
19                 //allow user to run help
20                 if(option == "help") { help(); abort = true; }
21                 
22                 else {
23                         //valid paramters for this command
24                         string Array[] =  {"phylip","outputdir", "inputdir"};
25                         vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
26                         
27                         OptionParser parser(option);
28                         map<string, string> parameters = parser. getParameters();
29                         
30                         ValidParameters validParameter;
31                         map<string, string>::iterator it;
32                 
33                         //check to make sure all parameters are valid for command
34                         for (it = parameters.begin(); it != parameters.end(); it++) { 
35                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
36                         }
37                         //if the user changes the input directory command factory will send this info to us in the output parameter 
38                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
39                         if (inputDir == "not found"){   inputDir = "";          }
40                         else {
41                                 string path;
42                                 it = parameters.find("phylip");
43                                 //user has given a template file
44                                 if(it != parameters.end()){ 
45                                         path = hasPath(it->second);
46                                         //if the user has not given a path then, add inputdir. else leave path alone.
47                                         if (path == "") {       parameters["phylip"] = inputDir + it->second;           }
48                                 }
49                         }
50
51                         //required parameters
52                         phylipfile = validParameter.validFile(parameters, "phylip", true);
53                         if (phylipfile == "not open") { abort = true; }
54                         else if (phylipfile == "not found") { phylipfile = ""; abort = true; }  
55                         else {  filename = phylipfile;  }
56                         
57                         //if the user changes the output directory command factory will send this info to us in the output parameter 
58                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
59                                 outputDir = ""; 
60                                 outputDir += hasPath(phylipfile); //if user entered a file with a path then preserve it 
61                         }
62                         
63                         //error checking on files       
64                         if (phylipfile == "")   { mothurOut("You must provide a distance file before running the pca command."); mothurOutEndLine(); abort = true; }            
65                 }
66
67         }
68         catch(exception& e) {
69                 errorOut(e, "PCACommand", "PCACommand");
70                 exit(1);
71         }
72 }
73 //**********************************************************************************************************************
74 void PCACommand::help(){
75         try {
76         
77                 mothurOut("The pca command..."); mothurOutEndLine();
78         }
79         catch(exception& e) {
80                 errorOut(e, "PCACommand", "help");
81                 exit(1);
82         }
83 }
84 //**********************************************************************************************************************
85 PCACommand::~PCACommand(){}
86 //**********************************************************************************************************************
87 int PCACommand::execute(){
88         try {
89         
90                 if (abort == true) { return 0; }
91                 
92                 cout.setf(ios::fixed, ios::floatfield);
93                 cout.setf(ios::showpoint);
94                 cerr.setf(ios::fixed, ios::floatfield);
95                 cerr.setf(ios::showpoint);
96                 
97                 vector<string> names;
98                 vector<vector<double> > D;
99         
100                 //fbase = filename;
101                 //if(fbase.find_last_of(".")!=string::npos){
102                 //      fbase.erase(fbase.find_last_of(".")+1); 
103                 //}
104                 //else{
105                 //      fbase += ".";
106                 //}
107                 
108                 fbase = outputDir + getRootName(getSimpleName(filename));
109                 
110                 read(filename, names, D);
111         
112                 double offset = 0.0000;
113                 vector<double> d;
114                 vector<double> e;
115                 vector<vector<double> > G = D;
116                 vector<vector<double> > copy_G;
117                 //int rank = D.size();
118                 
119                 cout << "\nProcessing...\n";
120                 
121                 for(int count=0;count<2;count++){
122                         recenter(offset, D, G);   
123                         tred2(G, d, e);
124                         qtli(d, e, G);
125                         offset = d[d.size()-1];
126                         if(offset > 0.0) break;
127                 } 
128                 
129                 
130                 output(fbase, names, G, d);
131                 
132                 return 0;
133         }
134         catch(exception& e) {
135                 errorOut(e, "PCACommand", "execute");
136                 exit(1);
137         }
138 }
139 /*********************************************************************************************************************************/
140
141 inline double SIGN(const double a, const double b)
142 {
143     return b>=0 ? (a>=0 ? a:-a) : (a>=0 ? -a:a);
144 }
145
146 /*********************************************************************************************************************************/
147
148 void PCACommand::get_comment(istream& f, char begin, char end){
149         try {
150                 char d=f.get();
151                 while(d != end){        d = f.get();    }
152                 d = f.peek();
153         }
154         catch(exception& e) {
155                 errorOut(e, "PCACommand", "get_comment");
156                 exit(1);
157         }
158 }       
159
160 /*********************************************************************************************************************************/
161
162 void PCACommand::read_mega(istream& f, vector<string>& name_list, vector<vector<double> >& d){
163         try {
164                 get_comment(f, '#', '\n');
165                 
166                 char test = f.peek();
167                 
168                 while(test == '!'){                                                             //get header comments
169                         get_comment(f, '!', ';');
170                         while(isspace(test=f.get()))            {;}
171                         f.putback(test);
172                         test = f.peek();
173                 }
174                 while(test != '\n'){                                                    //get sequence names
175                         get_comment(f, '[', ']');
176                         char d = f.get();
177                         d = f.get();
178                         if(d == '#'){
179                                 string name;
180                                 f >> name;
181                                 name_list.push_back(name);
182                                 while(isspace(test=f.get()))            {;}
183                                 f.putback(test);
184                         }
185                         else{
186                                 break;
187                         }
188                 }
189                 int rank = name_list.size();
190                 d.resize(rank);
191                 for(int i=0;i<rank;i++){                d[i].resize(rank);              }
192                 
193                 d[0][0] = 0.0000;
194                 get_comment(f, '[', ']');
195                 for(int i=1;i<rank;i++){
196                         get_comment(f, '[', ']');
197                         d[i][i]=0.0000;
198                         for(int j=0;j<i;j++){
199                                 f >> d[i][j];
200                                 if (d[i][j] == -0.0000)
201                                         d[i][j] = 0.0000;
202                                 d[j][i]=d[i][j];
203                         }
204                 }
205         }
206         catch(exception& e) {
207                 errorOut(e, "PCACommand", "read_mega");
208                 exit(1);
209         }
210 }
211
212 /*********************************************************************************************************************************/
213
214 void PCACommand::read_phylip(istream& f, int square_m, vector<string>& name_list, vector<vector<double> >& d){
215         try {
216                 //     int count1=0;
217                 //     int count2=0;
218                 
219                 int rank;
220                 f >> rank;
221                 
222                 name_list.resize(rank);
223                 d.resize(rank);
224                 if(square_m == 1){
225                         for(int i=0;i<rank;i++)
226                                 d[i].resize(rank);
227                         for(int i=0;i<rank;i++) {
228                                 f >> name_list[i];
229                                 //                      cout << i << "\t" << name_list[i] << endl;
230                                 for(int j=0;j<rank;j++) {
231                                         f >> d[i][j];
232                                         if (d[i][j] == -0.0000)
233                                                 d[i][j] = 0.0000;
234                                 }
235                         }
236                 }
237                 else if(square_m == 2){
238                         for(int i=0;i<rank;i++){
239                                 d[i].resize(rank);
240                         }
241                         d[0][0] = 0.0000;
242                         f >> name_list[0];
243                         for(int i=1;i<rank;i++){
244                                 f >> name_list[i];
245                                 d[i][i]=0.0000;
246                                 for(int j=0;j<i;j++){
247                                         f >> d[i][j];
248                                         if (d[i][j] == -0.0000)
249                                                 d[i][j] = 0.0000;
250                                         d[j][i]=d[i][j];
251                                 }
252                         }
253                 }
254         }
255         catch(exception& e) {
256                 errorOut(e, "PCACommand", "read_phylip");
257                 exit(1);
258         }
259
260 }
261
262 /*********************************************************************************************************************************/
263
264 void PCACommand::read(string fname, vector<string>& names, vector<vector<double> >& D){
265         try {
266                 ifstream f;
267                 openInputFile(fname, f);
268                 
269                 char test = f.peek();
270                 
271                 if(test == '#'){
272                         read_mega(f, names, D);
273                 }
274                 else{
275                         //check whether matrix is square
276                         char d;
277                         int m = 1;
278                         int numSeqs;
279                         string name;
280                         
281                         f >> numSeqs >> name; 
282                         
283                         while((d=f.get()) != EOF){
284                                 
285                                 //is d a number meaning its square
286                                 if(isalnum(d)){ 
287                                         m = 1; 
288                                         break; 
289                                 }
290                                 
291                                 //is d a line return meaning its lower triangle
292                                 if(d == '\n'){
293                                         m = 2;
294                                         break;
295                                 }
296                         }
297                         f.close();
298                         
299                         //reopen to get back to beginning
300                         openInputFile(fname, f);                        
301                         read_phylip(f, m, names, D);
302                 }
303                 
304                 //int rank = D.size();
305         }
306         catch(exception& e) {
307                 errorOut(e, "PCACommand", "read");
308                 exit(1);
309         }
310 }
311
312 /*********************************************************************************************************************************/
313 double PCACommand::pythag(double a, double b){
314     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                 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                 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                 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                 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+"pca").c_str(), ios::trunc);
570                 pcaData.setf(ios::fixed, ios::floatfield);
571                 pcaData.setf(ios::showpoint);   
572                 
573                 ofstream pcaLoadings((fnameRoot+"pca.loadings").c_str(), ios::trunc);
574                 pcaLoadings.setf(ios::fixed, ios::floatfield);
575                 pcaLoadings.setf(ios::showpoint);       
576                 
577                 pcaLoadings << "axis\tloading\n";
578                 for(int i=0;i<rank;i++){
579                         pcaLoadings << i+1 << '\t' << d[i] * 100.0 / dsum << endl;
580                 }
581                 
582                 pcaData << "SeqName";
583                 for(int i=0;i<rank;i++){
584                         pcaData << '\t' << "axis" << i+1;
585                 }
586                 pcaData << endl;
587                 
588                 for(int i=0;i<rank;i++){
589                         pcaData << name_list[i] << '\t';
590                         for(int j=0;j<rank;j++){
591                                 pcaData << G[i][j] << '\t';
592                         }
593                         pcaData << endl;
594                 }
595         }
596         catch(exception& e) {
597                 errorOut(e, "PCACommand", "output");
598                 exit(1);
599         }
600 }
601
602 /*********************************************************************************************************************************/
603
604 void PCACommand::print_matrix(vector<vector<double> > A) {
605         try {
606                 int rank = A.size();
607                 for(int i=0;i<rank;i++){
608                         for(int j=0;j<rank;j++){
609                                 cout << A[i][j] << "  ";
610                         }
611                         cout << endl;
612                 }
613         }
614         catch(exception& e) {
615                 errorOut(e, "PCACommand", "print_matrix");
616                 exit(1);
617         }
618 }
619 /*********************************************************************************************************************************/
620