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 PCACommand::PCACommand(){
54 abort = true; calledHelp = true;
56 vector<string> tempOutNames;
57 outputTypes["pca"] = tempOutNames;
58 outputTypes["loadings"] = tempOutNames;
61 m->errorOut(e, "PCACommand", "PCACommand");
65 //**********************************************************************************************************************
67 PCACommand::PCACommand(string option) {
69 abort = false; calledHelp = false;
71 //allow user to run help
72 if(option == "help") { help(); abort = true; calledHelp = true; }
73 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
76 vector<string> myArray = setParameters();
78 OptionParser parser(option);
79 map<string, string> parameters = parser. getParameters();
81 ValidParameters validParameter;
82 map<string, string>::iterator it;
84 //check to make sure all parameters are valid for command
85 for (it = parameters.begin(); it != parameters.end(); it++) {
86 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
89 //initialize outputTypes
90 vector<string> tempOutNames;
91 outputTypes["pca"] = tempOutNames;
92 outputTypes["loadings"] = tempOutNames;
94 //if the user changes the input directory command factory will send this info to us in the output parameter
95 string inputDir = validParameter.validFile(parameters, "inputdir", false);
96 if (inputDir == "not found"){ inputDir = ""; }
99 it = parameters.find("shared");
100 //user has given a template file
101 if(it != parameters.end()){
102 path = m->hasPath(it->second);
103 //if the user has not given a path then, add inputdir. else leave path alone.
104 if (path == "") { parameters["shared"] = inputDir + it->second; }
107 it = parameters.find("relabund");
108 //user has given a template file
109 if(it != parameters.end()){
110 path = m->hasPath(it->second);
111 //if the user has not given a path then, add inputdir. else leave path alone.
112 if (path == "") { parameters["relabund"] = inputDir + it->second; }
116 //check for required parameters
117 sharedfile = validParameter.validFile(parameters, "shared", true);
118 if (sharedfile == "not open") { sharedfile = ""; abort = true; }
119 else if (sharedfile == "not found") { sharedfile = ""; }
120 else { mode = "sharedfile"; inputFile = sharedfile; m->setSharedFile(sharedfile); }
122 relabundfile = validParameter.validFile(parameters, "relabund", true);
123 if (relabundfile == "not open") { relabundfile = ""; abort = true; }
124 else if (relabundfile == "not found") { relabundfile = ""; }
125 else { mode = "relabund"; inputFile = relabundfile; m->setRelAbundFile(relabundfile); }
128 if ((sharedfile == "") && (relabundfile == "")) {
129 //is there are current file available for any of these?
130 //give priority to shared, then list, then rabund, then sabund
131 //if there is a current shared file, use it
132 sharedfile = m->getSharedFile();
133 if (sharedfile != "") { inputFile = sharedfile; mode = "sharedfile"; m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
135 relabundfile = m->getRelAbundFile();
136 if (relabundfile != "") { inputFile = relabundfile; mode = "relabund"; m->mothurOut("Using " + relabundfile + " as input file for the relabund parameter."); m->mothurOutEndLine(); }
138 m->mothurOut("No valid current files. You must provide a relabund or shared file."); m->mothurOutEndLine();
144 //if the user changes the output directory command factory will send this info to us in the output parameter
145 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
147 outputDir += m->hasPath(inputFile); //if user entered a file with a path then preserve it
150 string temp = validParameter.validFile(parameters, "metric", false); if (temp == "not found"){ temp = "T"; }
151 metric = m->isTrue(temp);
153 label = validParameter.validFile(parameters, "label", false);
154 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(); } }
155 else { m->splitAtDash(label, labels); }
157 groups = validParameter.validFile(parameters, "groups", false);
158 if (groups == "not found") { groups = ""; }
159 else { m->splitAtDash(groups, Groups); }
165 catch(exception& e) {
166 m->errorOut(e, "PCACommand", "PCACommand");
170 //**********************************************************************************************************************
171 int PCACommand::execute(){
174 if (abort == true) { if (calledHelp) { return 0; } return 2; }
176 cout.setf(ios::fixed, ios::floatfield);
177 cout.setf(ios::showpoint);
178 cerr.setf(ios::fixed, ios::floatfield);
179 cerr.setf(ios::showpoint);
181 //get first line of shared file
182 vector< vector<double> > matrix;
184 if (mode == "sharedfile") {
185 input = new InputData(inputFile, "sharedfile");
186 }else if (mode == "relabund") {
187 input = new InputData(inputFile, "relabund");
188 }else { m->mothurOut("[ERROR]: filetype not recognized."); m->mothurOutEndLine(); return 0; }
190 vector<SharedRAbundFloatVector*> lookupFloat = input->getSharedRAbundFloatVectors();
191 string lastLabel = lookupFloat[0]->getLabel();
193 set<string> processedLabels;
194 set<string> userLabels = labels;
196 //if the user gave no labels, then use the first one read
197 if (labels.size() == 0) {
200 process(lookupFloat);
203 //as long as you are not at the end of the file or done wih the lines you want
204 while((lookupFloat[0] != NULL) && (userLabels.size() != 0)) {
206 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } delete input; for (int i = 0; i < lookupFloat.size(); i++) { delete lookupFloat[i]; } lookupFloat.clear(); return 0; }
208 if(labels.count(lookupFloat[0]->getLabel()) == 1){
209 processedLabels.insert(lookupFloat[0]->getLabel());
210 userLabels.erase(lookupFloat[0]->getLabel());
212 process(lookupFloat);
215 if ((m->anyLabelsToProcess(lookupFloat[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
216 string saveLabel = lookupFloat[0]->getLabel();
218 for (int i = 0; i < lookupFloat.size(); i++) { delete lookupFloat[i]; } lookupFloat.clear();
219 lookupFloat = input->getSharedRAbundFloatVectors(lastLabel);
221 process(lookupFloat);
223 processedLabels.insert(lookupFloat[0]->getLabel());
224 userLabels.erase(lookupFloat[0]->getLabel());
226 //restore real lastlabel to save below
227 lookupFloat[0]->setLabel(saveLabel);
230 lastLabel = lookupFloat[0]->getLabel();
232 //get next line to process
233 //prevent memory leak
234 for (int i = 0; i < lookupFloat.size(); i++) { delete lookupFloat[i]; } lookupFloat.clear();
235 lookupFloat = input->getSharedRAbundFloatVectors();
239 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } delete input; for (int i = 0; i < lookupFloat.size(); i++) { delete lookupFloat[i]; } lookupFloat.clear(); return 0; }
241 //output error messages about any remaining user labels
242 set<string>::iterator it;
243 bool needToRun = false;
244 for (it = userLabels.begin(); it != userLabels.end(); it++) {
245 m->mothurOut("Your file does not include the label " + *it);
246 if (processedLabels.count(lastLabel) != 1) {
247 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
250 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
254 //run last label if you need to
255 if (needToRun == true) {
256 for (int i = 0; i < lookupFloat.size(); i++) { if (lookupFloat[i] != NULL) { delete lookupFloat[i]; } } lookupFloat.clear();
257 lookupFloat = input->getSharedRAbundFloatVectors(lastLabel);
259 process(lookupFloat);
261 for (int i = 0; i < lookupFloat.size(); i++) { if (lookupFloat[i] != NULL) { delete lookupFloat[i]; } } lookupFloat.clear();
264 for (int i = 0; i < lookupFloat.size(); i++) { if (lookupFloat[i] != NULL) { delete lookupFloat[i]; } } lookupFloat.clear();
267 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
269 m->mothurOutEndLine();
270 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
271 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
272 m->mothurOutEndLine();
276 catch(exception& e) {
277 m->errorOut(e, "PCACommand", "execute");
282 /**********************************************************************************************************************
283 vector< vector<double> > PCACommand::createMatrix(vector<SharedRAbundFloatVector*> lookupFloat){
285 vector< vector<double> > matrix; matrix.resize(lookupFloat.size());
287 //fill matrix with shared files relative abundances
288 for (int i = 0; i < lookupFloat.size(); i++) {
289 for (int j = 0; j < lookupFloat[i]->getNumBins(); j++) {
290 matrix[i].push_back(lookupFloat[i]->getAbundance(j));
294 vector< vector<double> > transposeMatrix; transposeMatrix.resize(matrix[0].size());
295 for (int i = 0; i < transposeMatrix.size(); i++) {
296 for (int j = 0; j < matrix.size(); j++) {
297 transposeMatrix[i].push_back(matrix[j][i]);
301 matrix = linearCalc.matrix_mult(matrix, transposeMatrix);
305 catch(exception& e) {
306 m->errorOut(e, "PCACommand", "createMatrix");
310 //**********************************************************************************************************************
312 int PCACommand::process(vector<SharedRAbundFloatVector*>& lookupFloat){
314 m->mothurOut("\nProcessing " + lookupFloat[0]->getLabel()); m->mothurOutEndLine();
316 int numOTUs = lookupFloat[0]->getNumBins();
317 int numSamples = lookupFloat.size();
319 vector< vector<double> > matrix(numSamples);
320 vector<double> colMeans(numOTUs);
322 //fill matrix with shared relative abundances, re-center
323 for (int i = 0; i < lookupFloat.size(); i++) {
324 matrix[i].resize(numOTUs, 0);
326 for (int j = 0; j < numOTUs; j++) {
327 matrix[i][j] = lookupFloat[i]->getAbundance(j);
328 colMeans[j] += matrix[i][j];
333 for(int j=0;j<numOTUs;j++){
334 colMeans[j] = colMeans[j] / (double)numSamples;
337 vector<vector<double> > centered = matrix;
338 for(int i=0;i<numSamples;i++){
339 for(int j=0;j<numOTUs;j++){
340 centered[i][j] = centered[i][j] - colMeans[j];
345 vector< vector<double> > transpose(numOTUs);
346 for (int i = 0; i < numOTUs; i++) {
347 transpose[i].resize(numSamples, 0);
349 for (int j = 0; j < numSamples; j++) {
350 transpose[i][j] = centered[j][i];
354 vector<vector<double> > crossProduct = linearCalc.matrix_mult(transpose, centered);
359 linearCalc.tred2(crossProduct, d, e); if (m->control_pressed) { return 0; }
360 linearCalc.qtli(d, e, crossProduct); if (m->control_pressed) { return 0; }
362 vector<vector<double> > X = linearCalc.matrix_mult(centered, crossProduct);
364 if (m->control_pressed) { return 0; }
366 string fbase = outputDir + m->getRootName(m->getSimpleName(inputFile));
367 string outputFileName = fbase + lookupFloat[0]->getLabel();
368 output(outputFileName, m->Groups, X, d);
372 vector<vector<double> > observedEuclideanDistance = linearCalc.getObservedEuclideanDistance(centered);
374 for (int i = 1; i < 4; i++) {
376 vector< vector<double> > PCAEuclidDists = linearCalc.calculateEuclidianDistance(X, i); //G is the pca file
378 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
380 double corr = linearCalc.calcPearson(PCAEuclidDists, observedEuclideanDistance);
382 m->mothurOut("Rsq " + toString(i) + " axis: " + toString(corr * corr)); m->mothurOutEndLine();
384 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
390 catch(exception& e) {
391 m->errorOut(e, "PCACommand", "process");
395 /*********************************************************************************************************************************/
397 void PCACommand::output(string fnameRoot, vector<string> name_list, vector<vector<double> >& G, vector<double> d) {
400 int numEigenValues = d.size();
401 double dsum = 0.0000;
402 for(int i=0;i<numEigenValues;i++){
406 ofstream pcaData((fnameRoot+".pca.axes").c_str(), ios::trunc);
407 pcaData.setf(ios::fixed, ios::floatfield);
408 pcaData.setf(ios::showpoint);
409 outputNames.push_back(fnameRoot+".pca.axes");
410 outputTypes["pca"].push_back(fnameRoot+".pca.axes");
412 ofstream pcaLoadings((fnameRoot+".pca.loadings").c_str(), ios::trunc);
413 pcaLoadings.setf(ios::fixed, ios::floatfield);
414 pcaLoadings.setf(ios::showpoint);
415 outputNames.push_back(fnameRoot+".pca.loadings");
416 outputTypes["loadings"].push_back(fnameRoot+".pca.loadings");
418 pcaLoadings << "axis\tloading\n";
419 for(int i=0;i<numEigenValues;i++){
420 pcaLoadings << i+1 << '\t' << d[i] * 100.0 / dsum << endl;
424 for(int i=0;i<numEigenValues;i++){
425 pcaData << '\t' << "axis" << i+1;
429 for(int i=0;i<name_list.size();i++){
430 pcaData << name_list[i] << '\t';
431 for(int j=0;j<numEigenValues;j++){
432 pcaData << G[i][j] << '\t';
437 catch(exception& e) {
438 m->errorOut(e, "PCACommand", "output");
442 /*********************************************************************************************************************************/