6 * Created by westcott on 1/4/10.
7 * Copyright 2010 Schloss Lab. All rights reserved.
11 #include "pcacommand.h"
13 //**********************************************************************************************************************
15 PCACommand::PCACommand(string option){
19 //allow user to run help
20 if(option == "help") { help(); abort = true; }
23 //valid paramters for this command
24 string Array[] = {"phylip","outputdir", "inputdir"};
25 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
27 OptionParser parser(option);
28 map<string, string> parameters = parser. getParameters();
30 ValidParameters validParameter;
31 map<string, string>::iterator it;
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; }
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 = ""; }
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; }
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; }
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"){
60 outputDir += hasPath(phylipfile); //if user entered a file with a path then preserve it
63 //error checking on files
64 if (phylipfile == "") { mothurOut("You must provide a distance file before running the pca command."); mothurOutEndLine(); abort = true; }
69 errorOut(e, "PCACommand", "PCACommand");
73 //**********************************************************************************************************************
74 void PCACommand::help(){
77 mothurOut("The pca command..."); mothurOutEndLine();
80 errorOut(e, "PCACommand", "help");
84 //**********************************************************************************************************************
85 PCACommand::~PCACommand(){}
86 //**********************************************************************************************************************
87 int PCACommand::execute(){
90 if (abort == true) { return 0; }
92 cout.setf(ios::fixed, ios::floatfield);
93 cout.setf(ios::showpoint);
94 cerr.setf(ios::fixed, ios::floatfield);
95 cerr.setf(ios::showpoint);
98 vector<vector<double> > D;
101 //if(fbase.find_last_of(".")!=string::npos){
102 // fbase.erase(fbase.find_last_of(".")+1);
108 fbase = outputDir + getRootName(getSimpleName(filename));
110 read(filename, names, D);
112 double offset = 0.0000;
115 vector<vector<double> > G = D;
116 vector<vector<double> > copy_G;
117 //int rank = D.size();
119 cout << "\nProcessing...\n";
121 for(int count=0;count<2;count++){
122 recenter(offset, D, G);
125 offset = d[d.size()-1];
126 if(offset > 0.0) break;
130 output(fbase, names, G, d);
134 catch(exception& e) {
135 errorOut(e, "PCACommand", "execute");
139 /*********************************************************************************************************************************/
141 inline double SIGN(const double a, const double b)
143 return b>=0 ? (a>=0 ? a:-a) : (a>=0 ? -a:a);
146 /*********************************************************************************************************************************/
148 void PCACommand::get_comment(istream& f, char begin, char end){
151 while(d != end){ d = f.get(); }
154 catch(exception& e) {
155 errorOut(e, "PCACommand", "get_comment");
160 /*********************************************************************************************************************************/
162 void PCACommand::read_mega(istream& f, vector<string>& name_list, vector<vector<double> >& d){
164 get_comment(f, '#', '\n');
166 char test = f.peek();
168 while(test == '!'){ //get header comments
169 get_comment(f, '!', ';');
170 while(isspace(test=f.get())) {;}
174 while(test != '\n'){ //get sequence names
175 get_comment(f, '[', ']');
181 name_list.push_back(name);
182 while(isspace(test=f.get())) {;}
189 int rank = name_list.size();
191 for(int i=0;i<rank;i++){ d[i].resize(rank); }
194 get_comment(f, '[', ']');
195 for(int i=1;i<rank;i++){
196 get_comment(f, '[', ']');
198 for(int j=0;j<i;j++){
200 if (d[i][j] == -0.0000)
206 catch(exception& e) {
207 errorOut(e, "PCACommand", "read_mega");
212 /*********************************************************************************************************************************/
214 void PCACommand::read_phylip(istream& f, int square_m, vector<string>& name_list, vector<vector<double> >& d){
222 name_list.resize(rank);
225 for(int i=0;i<rank;i++)
227 for(int i=0;i<rank;i++) {
229 // cout << i << "\t" << name_list[i] << endl;
230 for(int j=0;j<rank;j++) {
232 if (d[i][j] == -0.0000)
237 else if(square_m == 2){
238 for(int i=0;i<rank;i++){
243 for(int i=1;i<rank;i++){
246 for(int j=0;j<i;j++){
248 if (d[i][j] == -0.0000)
255 catch(exception& e) {
256 errorOut(e, "PCACommand", "read_phylip");
262 /*********************************************************************************************************************************/
264 void PCACommand::read(string fname, vector<string>& names, vector<vector<double> >& D){
267 openInputFile(fname, f);
269 char test = f.peek();
272 read_mega(f, names, D);
275 //check whether matrix is square
281 f >> numSeqs >> name;
283 while((d=f.get()) != EOF){
285 //is d a number meaning its square
291 //is d a line return meaning its lower triangle
299 //reopen to get back to beginning
300 openInputFile(fname, f);
301 read_phylip(f, m, names, D);
304 //int rank = D.size();
306 catch(exception& e) {
307 errorOut(e, "PCACommand", "read");
312 /*********************************************************************************************************************************/
313 double PCACommand::pythag(double a, double b){
314 return(pow(a*a+b*b,0.5));
316 /*********************************************************************************************************************************/
318 void PCACommand::matrix_mult(vector<vector<double> > first, vector<vector<double> > second, vector<vector<double> >& product){
320 int first_rows = first.size();
321 int first_cols = first[0].size();
322 int second_cols = second[0].size();
324 product.resize(first_rows);
325 for(int i=0;i<first_rows;i++){
326 product[i].resize(second_cols);
329 for(int i=0;i<first_rows;i++){
330 for(int j=0;j<second_cols;j++){
332 for(int k=0;k<first_cols;k++){
333 product[i][j] += first[i][k] * second[k][j];
338 catch(exception& e) {
339 errorOut(e, "PCACommand", "matrix_mult");
345 /*********************************************************************************************************************************/
347 void PCACommand::recenter(double offset, vector<vector<double> > D, vector<vector<double> >& G){
351 vector<vector<double> > A(rank);
352 vector<vector<double> > C(rank);
353 for(int i=0;i<rank;i++){
358 double scale = -1.0000 / (double) rank;
360 for(int i=0;i<rank;i++){
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;
372 catch(exception& e) {
373 errorOut(e, "PCACommand", "recenter");
379 /*********************************************************************************************************************************/
381 // This function is taken from Numerical Recipes in C++ by Press et al., 2nd edition, pg. 479
383 void PCACommand::tred2(vector<vector<double> >& a, vector<double>& d, vector<double>& e){
385 double scale, hh, h, g, f;
392 for(int i=n-1;i>0;i--){
396 for(int k=0;k<l+1;k++){
397 scale += fabs(a[i][k]);
403 for(int k=0;k<l+1;k++){
405 h += a[i][k] * a[i][k];
408 g = (f >= 0.0 ? -sqrt(h) : sqrt(h));
413 for(int j=0;j<l+1;j++){
414 a[j][i] = a[i][j] / h;
416 for(int k=0;k<j+1;k++){
417 g += a[j][k] * a[i][k];
419 for(int k=j+1;k<l+1;k++){
420 g += a[k][j] * a[i][k];
426 for(int j=0;j<l+1;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]);
445 for(int i=0;i<n;i++){
448 for(int j=0;j<l;j++){
450 for(int k=0;k<l;k++){
451 g += a[i][k] * a[k][j];
453 for(int k=0;k<l;k++){
454 a[k][j] -= g * a[k][i];
460 for(int j=0;j<l;j++){
461 a[j][i] = a[i][j] = 0.0;
465 catch(exception& e) {
466 errorOut(e, "PCACommand", "tred2");
472 /*********************************************************************************************************************************/
474 // This function is taken from Numerical Recipes in C++ by Press et al., 2nd edition, pg. 479
476 void PCACommand::qtli(vector<double>& d, vector<double>& e, vector<vector<double> >& z) {
479 double s, r, p, g, f, dd, c, b;
482 for(int i=1;i<=n;i++){
487 for(int l=0;l<n;l++){
491 dd = fabs(d[m]) + fabs(d[m+1]);
492 if(fabs(e[m])+dd == dd) break;
495 if(iter++ == 30) cerr << "Too many iterations in tqli\n";
496 g = (d[l+1]-d[l]) / (2.0 * e[l]);
498 g = d[m] - d[l] + e[l] / (g + SIGN(r,g));
504 e[i+1] = (r=pythag(f,g));
513 r = (d[i] - g) * s + 2.0 * c * b;
514 d[i+1] = g + ( p = s * r);
516 for(int k=0;k<n;k++){
518 z[k][i+1] = s * z[k][i] + c * f;
519 z[k][i] = c * z[k][i] - s * f;
522 if(r == 0.00 && i >= l) continue;
531 for(int i=0;i<n;i++){
533 for(int j=i;j<n;j++){
541 for(int j=0;j<n;j++){
549 catch(exception& e) {
550 errorOut(e, "PCACommand", "qtli");
555 /*********************************************************************************************************************************/
557 void PCACommand::output(string fnameRoot, vector<string> name_list, vector<vector<double> > G, vector<double> d) {
559 int rank = name_list.size();
560 double dsum = 0.0000;
561 for(int i=0;i<rank;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; }
569 ofstream pcaData((fnameRoot+"pca").c_str(), ios::trunc);
570 pcaData.setf(ios::fixed, ios::floatfield);
571 pcaData.setf(ios::showpoint);
573 ofstream pcaLoadings((fnameRoot+"pca.loadings").c_str(), ios::trunc);
574 pcaLoadings.setf(ios::fixed, ios::floatfield);
575 pcaLoadings.setf(ios::showpoint);
577 pcaLoadings << "axis\tloading\n";
578 for(int i=0;i<rank;i++){
579 pcaLoadings << i+1 << '\t' << d[i] * 100.0 / dsum << endl;
582 pcaData << "SeqName";
583 for(int i=0;i<rank;i++){
584 pcaData << '\t' << "axis" << i+1;
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';
596 catch(exception& e) {
597 errorOut(e, "PCACommand", "output");
602 /*********************************************************************************************************************************/
604 void PCACommand::print_matrix(vector<vector<double> > A) {
607 for(int i=0;i<rank;i++){
608 for(int j=0;j<rank;j++){
609 cout << A[i][j] << " ";
614 catch(exception& e) {
615 errorOut(e, "PCACommand", "print_matrix");
619 /*********************************************************************************************************************************/