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