5 * Created by westcott on 1/7/11.
6 * Copyright 2011 Schloss Lab. All rights reserved.
10 #include "pcacommand.h"
11 #include "inputdata.h"
13 //**********************************************************************************************************************
14 vector<string> PCACommand::setParameters(){
16 CommandParameter pshared("shared", "InputTypes", "", "", "LRSS", "LRSS", "none",false,false); parameters.push_back(pshared);
17 CommandParameter prelabund("relabund", "InputTypes", "", "", "LRSS", "LRSS", "none",false,false); parameters.push_back(prelabund);
18 CommandParameter pgroups("groups", "String", "", "", "", "", "",false,false); parameters.push_back(pgroups);
19 CommandParameter pmetric("metric", "Boolean", "", "T", "", "", "",false,false); parameters.push_back(pmetric);
20 CommandParameter plabel("label", "String", "", "", "", "", "",false,false); parameters.push_back(plabel);
21 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
22 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
24 vector<string> myArray;
25 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
29 m->errorOut(e, "PCACommand", "setParameters");
33 //**********************************************************************************************************************
34 string PCACommand::getHelpString(){
36 string helpString = "";
37 helpString += "The pca command parameters are shared, relabund, label, groups and metric. shared or relabund is required unless you have a valid current file.";
38 helpString += "The label parameter is used to analyze specific labels in your input. Default is the first label in your shared or relabund file. Multiple labels may be separated by dashes.\n";
39 helpString += "The groups parameter allows you to specify which groups you would like analyzed. Groupnames are separated by dashes.\n";
40 helpString += "The metric parameter allows you to indicate if would like the pearson correlation coefficient calculated. Default=True";
41 helpString += "Example pca(groups=yourGroups).\n";
42 helpString += "Example pca(groups=A-B-C).\n";
43 helpString += "Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n";
47 m->errorOut(e, "PCACommand", "getHelpString");
51 //**********************************************************************************************************************
52 string PCACommand::getOutputFileNameTag(string type, string inputName=""){
54 string outputFileName = "";
55 map<string, vector<string> >::iterator it;
57 //is this a type this command creates
58 it = outputTypes.find(type);
59 if (it == outputTypes.end()) { m->mothurOut("[ERROR]: this command doesn't create a " + type + " output file.\n"); }
61 if (type == "pca") { outputFileName = "pca.axes"; }
62 else if (type == "loadings") { outputFileName = "pca.loadings"; }
63 else { m->mothurOut("[ERROR]: No definition for type " + type + " output file tag.\n"); m->control_pressed = true; }
65 return outputFileName;
68 m->errorOut(e, "PCACommand", "getOutputFileNameTag");
73 //**********************************************************************************************************************
74 PCACommand::PCACommand(){
76 abort = true; calledHelp = true;
78 vector<string> tempOutNames;
79 outputTypes["pca"] = tempOutNames;
80 outputTypes["loadings"] = tempOutNames;
83 m->errorOut(e, "PCACommand", "PCACommand");
87 //**********************************************************************************************************************
89 PCACommand::PCACommand(string option) {
91 abort = false; calledHelp = false;
93 //allow user to run help
94 if(option == "help") { help(); abort = true; calledHelp = true; }
95 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
98 vector<string> myArray = setParameters();
100 OptionParser parser(option);
101 map<string, string> parameters = parser. getParameters();
103 ValidParameters validParameter;
104 map<string, string>::iterator it;
106 //check to make sure all parameters are valid for command
107 for (it = parameters.begin(); it != parameters.end(); it++) {
108 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
111 //initialize outputTypes
112 vector<string> tempOutNames;
113 outputTypes["pca"] = tempOutNames;
114 outputTypes["loadings"] = tempOutNames;
116 //if the user changes the input directory command factory will send this info to us in the output parameter
117 string inputDir = validParameter.validFile(parameters, "inputdir", false);
118 if (inputDir == "not found"){ inputDir = ""; }
121 it = parameters.find("shared");
122 //user has given a template file
123 if(it != parameters.end()){
124 path = m->hasPath(it->second);
125 //if the user has not given a path then, add inputdir. else leave path alone.
126 if (path == "") { parameters["shared"] = inputDir + it->second; }
129 it = parameters.find("relabund");
130 //user has given a template file
131 if(it != parameters.end()){
132 path = m->hasPath(it->second);
133 //if the user has not given a path then, add inputdir. else leave path alone.
134 if (path == "") { parameters["relabund"] = inputDir + it->second; }
138 //check for required parameters
139 sharedfile = validParameter.validFile(parameters, "shared", true);
140 if (sharedfile == "not open") { sharedfile = ""; abort = true; }
141 else if (sharedfile == "not found") { sharedfile = ""; }
142 else { mode = "sharedfile"; inputFile = sharedfile; m->setSharedFile(sharedfile); }
144 relabundfile = validParameter.validFile(parameters, "relabund", true);
145 if (relabundfile == "not open") { relabundfile = ""; abort = true; }
146 else if (relabundfile == "not found") { relabundfile = ""; }
147 else { mode = "relabund"; inputFile = relabundfile; m->setRelAbundFile(relabundfile); }
150 if ((sharedfile == "") && (relabundfile == "")) {
151 //is there are current file available for any of these?
152 //give priority to shared, then list, then rabund, then sabund
153 //if there is a current shared file, use it
154 sharedfile = m->getSharedFile();
155 if (sharedfile != "") { inputFile = sharedfile; mode = "sharedfile"; m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
157 relabundfile = m->getRelAbundFile();
158 if (relabundfile != "") { inputFile = relabundfile; mode = "relabund"; m->mothurOut("Using " + relabundfile + " as input file for the relabund parameter."); m->mothurOutEndLine(); }
160 m->mothurOut("No valid current files. You must provide a relabund or shared file."); m->mothurOutEndLine();
166 //if the user changes the output directory command factory will send this info to us in the output parameter
167 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
169 outputDir += m->hasPath(inputFile); //if user entered a file with a path then preserve it
172 string temp = validParameter.validFile(parameters, "metric", false); if (temp == "not found"){ temp = "T"; }
173 metric = m->isTrue(temp);
175 label = validParameter.validFile(parameters, "label", false);
176 if (label == "not found") { label = ""; if(labels.size() == 0) { m->mothurOut("You did not provide a label, I will use the first label in your inputfile."); m->mothurOutEndLine(); } }
177 else { m->splitAtDash(label, labels); }
179 groups = validParameter.validFile(parameters, "groups", false);
180 if (groups == "not found") { groups = ""; }
181 else { m->splitAtDash(groups, Groups); }
182 m->setGroups(Groups);
187 catch(exception& e) {
188 m->errorOut(e, "PCACommand", "PCACommand");
192 //**********************************************************************************************************************
193 int PCACommand::execute(){
196 if (abort == true) { if (calledHelp) { return 0; } return 2; }
198 cout.setf(ios::fixed, ios::floatfield);
199 cout.setf(ios::showpoint);
200 cerr.setf(ios::fixed, ios::floatfield);
201 cerr.setf(ios::showpoint);
203 //get first line of shared file
204 vector< vector<double> > matrix;
206 if (mode == "sharedfile") {
207 input = new InputData(inputFile, "sharedfile");
208 }else if (mode == "relabund") {
209 input = new InputData(inputFile, "relabund");
210 }else { m->mothurOut("[ERROR]: filetype not recognized."); m->mothurOutEndLine(); return 0; }
212 vector<SharedRAbundFloatVector*> lookupFloat = input->getSharedRAbundFloatVectors();
213 string lastLabel = lookupFloat[0]->getLabel();
215 set<string> processedLabels;
216 set<string> userLabels = labels;
218 //if the user gave no labels, then use the first one read
219 if (labels.size() == 0) {
222 process(lookupFloat);
225 //as long as you are not at the end of the file or done wih the lines you want
226 while((lookupFloat[0] != NULL) && (userLabels.size() != 0)) {
228 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } delete input; for (int i = 0; i < lookupFloat.size(); i++) { delete lookupFloat[i]; } lookupFloat.clear(); return 0; }
230 if(labels.count(lookupFloat[0]->getLabel()) == 1){
231 processedLabels.insert(lookupFloat[0]->getLabel());
232 userLabels.erase(lookupFloat[0]->getLabel());
234 process(lookupFloat);
237 if ((m->anyLabelsToProcess(lookupFloat[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
238 string saveLabel = lookupFloat[0]->getLabel();
240 for (int i = 0; i < lookupFloat.size(); i++) { delete lookupFloat[i]; } lookupFloat.clear();
241 lookupFloat = input->getSharedRAbundFloatVectors(lastLabel);
243 process(lookupFloat);
245 processedLabels.insert(lookupFloat[0]->getLabel());
246 userLabels.erase(lookupFloat[0]->getLabel());
248 //restore real lastlabel to save below
249 lookupFloat[0]->setLabel(saveLabel);
252 lastLabel = lookupFloat[0]->getLabel();
254 //get next line to process
255 //prevent memory leak
256 for (int i = 0; i < lookupFloat.size(); i++) { delete lookupFloat[i]; } lookupFloat.clear();
257 lookupFloat = input->getSharedRAbundFloatVectors();
261 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } delete input; for (int i = 0; i < lookupFloat.size(); i++) { delete lookupFloat[i]; } lookupFloat.clear(); return 0; }
263 //output error messages about any remaining user labels
264 set<string>::iterator it;
265 bool needToRun = false;
266 for (it = userLabels.begin(); it != userLabels.end(); it++) {
267 m->mothurOut("Your file does not include the label " + *it);
268 if (processedLabels.count(lastLabel) != 1) {
269 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
272 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
276 //run last label if you need to
277 if (needToRun == true) {
278 for (int i = 0; i < lookupFloat.size(); i++) { if (lookupFloat[i] != NULL) { delete lookupFloat[i]; } } lookupFloat.clear();
279 lookupFloat = input->getSharedRAbundFloatVectors(lastLabel);
281 process(lookupFloat);
283 for (int i = 0; i < lookupFloat.size(); i++) { if (lookupFloat[i] != NULL) { delete lookupFloat[i]; } } lookupFloat.clear();
286 for (int i = 0; i < lookupFloat.size(); i++) { if (lookupFloat[i] != NULL) { delete lookupFloat[i]; } } lookupFloat.clear();
289 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } return 0; }
291 m->mothurOutEndLine();
292 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
293 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
294 m->mothurOutEndLine();
298 catch(exception& e) {
299 m->errorOut(e, "PCACommand", "execute");
304 /**********************************************************************************************************************
305 vector< vector<double> > PCACommand::createMatrix(vector<SharedRAbundFloatVector*> lookupFloat){
307 vector< vector<double> > matrix; matrix.resize(lookupFloat.size());
309 //fill matrix with shared files relative abundances
310 for (int i = 0; i < lookupFloat.size(); i++) {
311 for (int j = 0; j < lookupFloat[i]->getNumBins(); j++) {
312 matrix[i].push_back(lookupFloat[i]->getAbundance(j));
316 vector< vector<double> > transposeMatrix; transposeMatrix.resize(matrix[0].size());
317 for (int i = 0; i < transposeMatrix.size(); i++) {
318 for (int j = 0; j < matrix.size(); j++) {
319 transposeMatrix[i].push_back(matrix[j][i]);
323 matrix = linearCalc.matrix_mult(matrix, transposeMatrix);
327 catch(exception& e) {
328 m->errorOut(e, "PCACommand", "createMatrix");
332 //**********************************************************************************************************************
334 int PCACommand::process(vector<SharedRAbundFloatVector*>& lookupFloat){
336 m->mothurOut("\nProcessing " + lookupFloat[0]->getLabel()); m->mothurOutEndLine();
338 int numOTUs = lookupFloat[0]->getNumBins();
339 int numSamples = lookupFloat.size();
341 vector< vector<double> > matrix(numSamples);
342 vector<double> colMeans(numOTUs);
344 //fill matrix with shared relative abundances, re-center
345 for (int i = 0; i < lookupFloat.size(); i++) {
346 matrix[i].resize(numOTUs, 0);
348 for (int j = 0; j < numOTUs; j++) {
349 matrix[i][j] = lookupFloat[i]->getAbundance(j);
350 colMeans[j] += matrix[i][j];
355 for(int j=0;j<numOTUs;j++){
356 colMeans[j] = colMeans[j] / (double)numSamples;
359 vector<vector<double> > centered = matrix;
360 for(int i=0;i<numSamples;i++){
361 for(int j=0;j<numOTUs;j++){
362 centered[i][j] = centered[i][j] - colMeans[j];
367 vector< vector<double> > transpose(numOTUs);
368 for (int i = 0; i < numOTUs; i++) {
369 transpose[i].resize(numSamples, 0);
371 for (int j = 0; j < numSamples; j++) {
372 transpose[i][j] = centered[j][i];
376 vector<vector<double> > crossProduct = linearCalc.matrix_mult(transpose, centered);
381 linearCalc.tred2(crossProduct, d, e); if (m->control_pressed) { return 0; }
382 linearCalc.qtli(d, e, crossProduct); if (m->control_pressed) { return 0; }
384 vector<vector<double> > X = linearCalc.matrix_mult(centered, crossProduct);
386 if (m->control_pressed) { return 0; }
388 string fbase = outputDir + m->getRootName(m->getSimpleName(inputFile));
389 string outputFileName = fbase + lookupFloat[0]->getLabel();
390 output(outputFileName, m->getGroups(), X, d);
394 vector<vector<double> > observedEuclideanDistance = linearCalc.getObservedEuclideanDistance(centered);
396 for (int i = 1; i < 4; i++) {
398 vector< vector<double> > PCAEuclidDists = linearCalc.calculateEuclidianDistance(X, i); //G is the pca file
400 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } return 0; }
402 double corr = linearCalc.calcPearson(PCAEuclidDists, observedEuclideanDistance);
404 m->mothurOut("Rsq " + toString(i) + " axis: " + toString(corr * corr)); m->mothurOutEndLine();
406 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } return 0; }
412 catch(exception& e) {
413 m->errorOut(e, "PCACommand", "process");
417 /*********************************************************************************************************************************/
419 void PCACommand::output(string fnameRoot, vector<string> name_list, vector<vector<double> >& G, vector<double> d) {
422 int numEigenValues = d.size();
423 double dsum = 0.0000;
424 for(int i=0;i<numEigenValues;i++){
429 m->openOutputFile((fnameRoot+"."+getOutputFileNameTag("pca")), pcaData);
430 pcaData.setf(ios::fixed, ios::floatfield);
431 pcaData.setf(ios::showpoint);
432 outputNames.push_back(fnameRoot+"."+getOutputFileNameTag("pca"));
433 outputTypes["pca"].push_back(fnameRoot+"."+getOutputFileNameTag("pca"));
435 ofstream pcaLoadings;
436 m->openOutputFile((fnameRoot+"."+getOutputFileNameTag("loadings")), pcaLoadings);
437 pcaLoadings.setf(ios::fixed, ios::floatfield);
438 pcaLoadings.setf(ios::showpoint);
439 outputNames.push_back(fnameRoot+"."+getOutputFileNameTag("loadings"));
440 outputTypes["loadings"].push_back(fnameRoot+"."+getOutputFileNameTag("loadings"));
442 pcaLoadings << "axis\tloading\n";
443 for(int i=0;i<numEigenValues;i++){
444 pcaLoadings << i+1 << '\t' << d[i] * 100.0 / dsum << endl;
448 for(int i=0;i<numEigenValues;i++){
449 pcaData << '\t' << "axis" << i+1;
453 for(int i=0;i<name_list.size();i++){
454 pcaData << name_list[i] << '\t';
455 for(int j=0;j<numEigenValues;j++){
456 pcaData << G[i][j] << '\t';
461 catch(exception& e) {
462 m->errorOut(e, "PCACommand", "output");
466 /*********************************************************************************************************************************/