5 * Created by westcott on 1/11/11.
6 * Copyright 2011 Schloss Lab. All rights reserved.
10 #include "nmdscommand.h"
11 #include "readphylipvector.h"
13 //**********************************************************************************************************************
14 vector<string> NMDSCommand::setParameters(){
16 CommandParameter paxes("axes", "InputTypes", "", "", "none", "none", "none","",false,false,true); parameters.push_back(paxes);
17 CommandParameter pphylip("phylip", "InputTypes", "", "", "none", "none", "none","nmds-stress",false,true,true); parameters.push_back(pphylip);
18 CommandParameter pmaxdim("maxdim", "Number", "", "2", "", "", "","",false,false); parameters.push_back(pmaxdim);
19 CommandParameter pmindim("mindim", "Number", "", "2", "", "", "","",false,false); parameters.push_back(pmindim);
20 CommandParameter piters("iters", "Number", "", "10", "", "", "","",false,false); parameters.push_back(piters);
21 CommandParameter pmaxiters("maxiters", "Number", "", "500", "", "", "","",false,false); parameters.push_back(pmaxiters);
22 CommandParameter pepsilon("epsilon", "Number", "", "0.000000000001", "", "", "","",false,false); parameters.push_back(pepsilon);
23 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
24 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
26 vector<string> myArray;
27 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
31 m->errorOut(e, "NMDSCommand", "setParameters");
35 //**********************************************************************************************************************
36 string NMDSCommand::getHelpString(){
38 string helpString = "";
39 helpString += "The nmds command is modelled after the nmds code written in R by Sarah Goslee, using Non-metric multidimensional scaling function using the majorization algorithm from Borg & Groenen 1997, Modern Multidimensional Scaling.\n";
40 helpString += "The nmds command parameters are phylip, axes, mindim, maxdim, maxiters, iters and epsilon.\n";
41 helpString += "The phylip parameter allows you to enter your distance file.\n";
42 helpString += "The axes parameter allows you to enter a file containing a starting configuration.\n";
43 helpString += "The maxdim parameter allows you to select the maximum dimensions to use. Default=2\n";
44 helpString += "The mindim parameter allows you to select the minimum dimensions to use. Default=2\n";
45 helpString += "The maxiters parameter allows you to select the maximum number of iters to try with each random configuration. Default=500\n";
46 helpString += "The iters parameter allows you to select the number of random configuration to try. Default=10\n";
47 helpString += "The epsilon parameter allows you to select set an acceptable stopping point. Default=1e-12.\n";
48 helpString += "Example nmds(phylip=yourDistanceFile).\n";
49 helpString += "Note: No spaces between parameter labels (i.e. phylip), '=' and parameters (i.e.yourDistanceFile).\n";
53 m->errorOut(e, "NMDSCommand", "getHelpString");
57 //**********************************************************************************************************************
58 string NMDSCommand::getOutputPattern(string type) {
62 if (type == "nmds") { pattern = "[filename],nmds.axes"; }
63 else if (type == "stress") { pattern = "[filename],nmds.stress"; }
64 else if (type == "iters") { pattern = "[filename],nmds.iters"; }
65 else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true; }
70 m->errorOut(e, "NMDSCommand", "getOutputPattern");
75 //**********************************************************************************************************************
76 NMDSCommand::NMDSCommand(){
78 abort = true; calledHelp = true;
80 vector<string> tempOutNames;
81 outputTypes["nmds"] = tempOutNames;
82 outputTypes["stress"] = tempOutNames;
83 outputTypes["iters"] = tempOutNames;
86 m->errorOut(e, "NMDSCommand", "NMDSCommand");
90 //**********************************************************************************************************************
92 NMDSCommand::NMDSCommand(string option) {
94 abort = false; calledHelp = false;
96 //allow user to run help
97 if(option == "help") { help(); abort = true; calledHelp = true; }
98 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
101 vector<string> myArray = setParameters();
103 OptionParser parser(option);
104 map<string, string> parameters = parser. getParameters();
106 ValidParameters validParameter;
107 map<string, string>::iterator it;
109 //check to make sure all parameters are valid for command
110 for (it = parameters.begin(); it != parameters.end(); it++) {
111 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
113 //if the user changes the input directory command factory will send this info to us in the output parameter
114 string inputDir = validParameter.validFile(parameters, "inputdir", false);
115 if (inputDir == "not found"){ inputDir = ""; }
118 it = parameters.find("phylip");
119 //user has given a template file
120 if(it != parameters.end()){
121 path = m->hasPath(it->second);
122 //if the user has not given a path then, add inputdir. else leave path alone.
123 if (path == "") { parameters["phylip"] = inputDir + it->second; }
126 it = parameters.find("axes");
127 //user has given a template file
128 if(it != parameters.end()){
129 path = m->hasPath(it->second);
130 //if the user has not given a path then, add inputdir. else leave path alone.
131 if (path == "") { parameters["axes"] = inputDir + it->second; }
135 //initialize outputTypes
136 vector<string> tempOutNames;
137 outputTypes["nmds"] = tempOutNames;
138 outputTypes["iters"] = tempOutNames;
139 outputTypes["stress"] = tempOutNames;
141 //required parameters
142 phylipfile = validParameter.validFile(parameters, "phylip", true);
143 if (phylipfile == "not open") { phylipfile = ""; abort = true; }
144 else if (phylipfile == "not found") {
145 //if there is a current phylip file, use it
146 phylipfile = m->getPhylipFile();
147 if (phylipfile != "") { m->mothurOut("Using " + phylipfile + " as input file for the phylip parameter."); m->mothurOutEndLine(); }
148 else { m->mothurOut("You have no current phylip file and the phylip parameter is required."); m->mothurOutEndLine(); abort = true; }
149 }else { m->setPhylipFile(phylipfile); }
151 axesfile = validParameter.validFile(parameters, "axes", true);
152 if (axesfile == "not open") { axesfile = ""; abort = true; }
153 else if (axesfile == "not found") { axesfile = ""; }
155 //if the user changes the output directory command factory will send this info to us in the output parameter
156 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
158 outputDir += m->hasPath(phylipfile); //if user entered a file with a path then preserve it
161 string temp = validParameter.validFile(parameters, "mindim", false); if (temp == "not found") { temp = "2"; }
162 m->mothurConvert(temp, mindim);
164 temp = validParameter.validFile(parameters, "maxiters", false); if (temp == "not found") { temp = "500"; }
165 m->mothurConvert(temp, maxIters);
167 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "10"; }
168 m->mothurConvert(temp, iters);
170 temp = validParameter.validFile(parameters, "maxdim", false); if (temp == "not found") { temp = "2"; }
171 m->mothurConvert(temp, maxdim);
173 temp = validParameter.validFile(parameters, "epsilon", false); if (temp == "not found") { temp = "0.000000000001"; }
174 m->mothurConvert(temp, epsilon);
176 if (mindim < 1) { m->mothurOut("mindim must be at least 1."); m->mothurOutEndLine(); abort = true; }
177 if (maxdim < mindim) { maxdim = mindim; }
181 catch(exception& e) {
182 m->errorOut(e, "NMDSCommand", "NMDSCommand");
186 //**********************************************************************************************************************
187 int NMDSCommand::execute(){
190 if (abort == true) { if (calledHelp) { return 0; } return 2; }
192 cout.setf(ios::fixed, ios::floatfield);
193 cout.setf(ios::showpoint);
195 vector<string> names;
196 vector< vector< double> > matrix;
198 //read in phylip file
199 ReadPhylipVector readFile(phylipfile);
200 names = readFile.read(matrix);
201 if (m->control_pressed) { return 0; }
204 vector< vector<double> > axes;
205 if (axesfile != "") { axes = readAxes(names); }
207 map<string, string> variables;
208 variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(phylipfile));
209 string outputFileName = getOutputFileName("iters",variables);
210 string stressFileName = getOutputFileName("stress",variables);
211 outputNames.push_back(outputFileName); outputTypes["iters"].push_back(outputFileName);
212 outputNames.push_back(stressFileName); outputTypes["stress"].push_back(stressFileName);
215 m->openOutputFile(outputFileName, out);
216 m->openOutputFile(stressFileName, out2);
218 out2.setf(ios::fixed, ios::floatfield);
219 out2.setf(ios::showpoint);
220 out.setf(ios::fixed, ios::floatfield);
221 out.setf(ios::showpoint);
223 out2 << "Dimension\tIter\tStress\tRsq" << endl;
225 double bestStress = 10000000;
226 double bestR2 = 10000000;
227 vector< vector<double> > bestConfig;
230 for (int i = mindim; i <= maxdim; i++) {
231 m->mothurOut("Processing Dimension: " + toString(i)); m->mothurOutEndLine();
233 for (int j = 0; j < iters; j++) {
234 m->mothurOut(toString(j+1)); m->mothurOutEndLine();
236 //get configuration - either randomly generate or resize to this dimension
237 vector< vector<double> > thisConfig;
238 if (axesfile == "") { thisConfig = generateStartingConfiguration(names.size(), i); }
239 else { thisConfig = getConfiguration(axes, i); }
240 if (m->control_pressed) { out.close(); out2.close(); for (int k = 0; k < outputNames.size(); k++) { m->mothurRemove(outputNames[k]); } return 0; }
242 //calc nmds for this dimension
244 vector< vector<double> > endConfig = nmdsCalc(matrix, thisConfig, stress);
245 if (m->control_pressed) { out.close(); out2.close(); for (int k = 0; k < outputNames.size(); k++) { m->mothurRemove(outputNames[k]); } return 0; }
247 //calc euclid distances for new config
248 vector< vector<double> > newEuclid = linearCalc.calculateEuclidianDistance(endConfig);
249 if (m->control_pressed) { out.close(); out2.close(); for (int k = 0; k < outputNames.size(); k++) { m->mothurRemove(outputNames[k]); } return 0; }
251 //calc correlation between original distances and euclidean distances from this config
252 double rsquared = linearCalc.calcPearson(newEuclid, matrix);
253 rsquared *= rsquared;
254 if (m->control_pressed) { out.close(); out2.close(); for (int k = 0; k < outputNames.size(); k++) { m->mothurRemove(outputNames[k]); } return 0; }
257 out << "Config" << (j+1) << '\t';
258 for (int k = 0; k < i; k++) { out << "axis" << (k+1) << '\t'; }
260 out2 << i << '\t' << (j+1) << '\t' << stress << '\t' << rsquared << endl;
262 output(endConfig, names, out);
265 if (stress < bestStress) {
269 bestConfig = endConfig;
272 if (m->control_pressed) { out.close(); out2.close(); for (int k = 0; k < outputNames.size(); k++) { m->mothurRemove(outputNames[k]); } return 0; }
276 out.close(); out2.close();
279 string BestFileName = getOutputFileName("nmds",variables);
280 outputNames.push_back(BestFileName); outputTypes["nmds"].push_back(BestFileName);
282 m->mothurOut("\nNumber of dimensions:\t" + toString(bestDim) + "\n");
283 m->mothurOut("Lowest stress :\t" + toString(bestStress) + "\n");
284 m->mothurOut("R-squared for configuration:\t" + toString(bestR2) + "\n");
287 m->openOutputFile(BestFileName, outBest);
288 outBest.setf(ios::fixed, ios::floatfield);
289 outBest.setf(ios::showpoint);
292 for (int k = 0; k < bestConfig.size(); k++) { outBest << "axis" << (k+1) << '\t'; }
295 output(bestConfig, names, outBest);
299 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } return 0; }
301 m->mothurOutEndLine();
302 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
303 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
304 m->mothurOutEndLine();
308 catch(exception& e) {
309 m->errorOut(e, "NMDSCommand", "execute");
313 //**********************************************************************************************************************
314 vector< vector<double> > NMDSCommand::nmdsCalc(vector< vector<double> >& matrix, vector< vector<double> >& config, double& stress1) {
317 vector< vector<double> > newConfig = config;
319 //calc euclid distances
320 vector< vector<double> > euclid = linearCalc.calculateEuclidianDistance(newConfig);
321 if (m->control_pressed) { return newConfig; }
323 double stress2 = calculateStress(matrix, euclid);
324 stress1 = stress2 + 1.0 + epsilon;
327 while ((count < maxIters) && (abs(stress1 - stress2) > epsilon)) {
332 if (m->control_pressed) { return newConfig; }
334 vector< vector<double> > b; b.resize(euclid.size());
335 for (int i = 0; i < b.size(); i++) { b[i].resize(euclid[i].size(), 0.0); }
337 vector<double> columnSums; columnSums.resize(euclid.size(), 0.0);
338 for (int i = 0; i < euclid.size(); i++) {
339 for (int j = 0; j < euclid[i].size(); j++) {
340 //eliminate divide by zero error
341 if (euclid[i][j] != 0) {
342 b[i][j] = matrix[i][j] / euclid[i][j];
343 columnSums[j] += b[i][j];
349 //put in diagonal sums
350 for (int i = 0; i < euclid.size(); i++) { b[i][i] = columnSums[i]; }
352 int numInLowerTriangle = matrix.size() * (matrix.size()-1) / 2.0;
353 double n = (1.0 + sqrt(1.0 + 8.0 * numInLowerTriangle)) / 2.0;
356 newConfig = linearCalc.matrix_mult(newConfig, b);
357 for (int i = 0; i < newConfig.size(); i++) {
358 for (int j = 0; j < newConfig[i].size(); j++) {
359 newConfig[i][j] *= (1.0 / n);
363 euclid = linearCalc.calculateEuclidianDistance(newConfig);
365 stress2 = calculateStress(matrix, euclid);
370 catch(exception& e) {
371 m->errorOut(e, "NMDSCommand", "generateStartingConfiguration");
376 //**********************************************************************************************************************
377 //generate random config
378 vector< vector<double> > NMDSCommand::generateStartingConfiguration(int numNames, int dimension) {
380 vector< vector<double> > axes; axes.resize(dimension);
381 for (int i = 0; i < axes.size(); i++) { axes[i].resize(numNames); }
383 //generate random number between -1 and 1, precision 6
384 for (int i = 0; i < axes.size(); i++) {
385 for (int j = 0; j < axes[i].size(); j++) {
387 if (m->control_pressed) { return axes; }
389 //generate random int between 0 and 99999
390 int myrand = (int)((float)(rand()) / ((RAND_MAX / 99998) + 1));
392 //generate random sign
393 int mysign = (int)((float)(rand()) / ((RAND_MAX / 99998) + 1));
395 //if mysign is even then sign = positive, else sign = negative
396 if ((mysign % 2) == 0) { mysign = 1.0; }
397 else { mysign = -1.0; }
399 axes[i][j] = mysign * myrand / (float) 100000;
405 catch(exception& e) {
406 m->errorOut(e, "NMDSCommand", "generateStartingConfiguration");
410 //**********************************************************************************************************************
411 //normalize configuration
412 int NMDSCommand::normalizeConfiguration(vector< vector<double> >& axes, int numNames, int dimension) {
414 vector<double> averageAxes; averageAxes.resize(dimension, 0.0);
417 for (int i = 0; i < axes.size(); i++) {
418 for (int j = 0; j < axes[i].size(); j++) { averageAxes[i] += axes[i][j]; }
420 averageAxes[i] /= (float) numNames;
424 double sumDenom = 0.0;
425 for (int i = 0; i < axes.size(); i++) {
426 for (int j = 0; j < axes[i].size(); j++) {
427 sumDenom += ((axes[i][j] - averageAxes[i]) * (axes[i][j] - averageAxes[i]));
431 double denom = sqrt((sumDenom / (float) (axes.size() * numNames)));
433 for (int i = 0; i < axes.size(); i++) {
434 for (int j = 0; j < axes[i].size(); j++) {
435 axes[i][j] = (axes[i][j] - averageAxes[i]) / denom;
441 catch(exception& e) {
442 m->errorOut(e, "NMDSCommand", "normalizeConfiguration");
446 //**********************************************************************************************************************
448 vector< vector<double> > NMDSCommand::getConfiguration(vector< vector<double> >& axes, int dimension) {
450 vector< vector<double> > newAxes; newAxes.resize(dimension);
452 for (int i = 0; i < dimension; i++) {
453 newAxes[i] = axes[i];
458 catch(exception& e) {
459 m->errorOut(e, "NMDSCommand", "getConfiguration");
463 //**********************************************************************************************************************
464 //find raw stress, and normalize using
465 double NMDSCommand::calculateStress(vector< vector<double> >& matrix, vector< vector<double> >& config) {
467 double normStress = 0.0;
469 double rawStress = 0.0;
472 for (int i = 0; i < matrix.size(); i++) {
473 for (int j = 0; j < matrix[i].size(); j++) {
474 if (m->control_pressed) { return normStress; }
476 rawStress += ((matrix[i][j] - config[i][j]) * (matrix[i][j] - config[i][j]));
477 denom += (config[i][j] * config[i][j]);
482 if ((rawStress != 0.0) && (denom != 0.0)) {
483 normStress = sqrt((rawStress / denom));
488 catch(exception& e) {
489 m->errorOut(e, "NMDSCommand", "calculateStress");
494 //**********************************************************************************************************************
495 int NMDSCommand::output(vector< vector<double> >& config, vector<string>& names, ofstream& out) {
498 for (int i = 0; i < names.size(); i++) {
500 out << names[i] << '\t';
502 for (int j = 0; j < config.size(); j++) {
503 out << config[j][i] << '\t';
513 catch(exception& e) {
514 m->errorOut(e, "NMDSCommand", "output");
518 /*****************************************************************/
519 vector< vector<double> > NMDSCommand::readAxes(vector<string> names){
522 m->openInputFile(axesfile, in);
524 string headerLine = m->getline(in); m->gobble(in);
526 //count the number of axis you are reading
530 int pos = headerLine.find("axis");
531 if (pos != string::npos) {
533 headerLine = headerLine.substr(pos+4);
534 }else { done = true; }
537 if (maxdim > count) {
538 m->mothurOut("You requested maxdim = " + toString(maxdim) + ", but your file only includes " + toString(count) + ". Using " + toString(count) + "."); m->mothurOutEndLine();
540 if (maxdim < mindim) { m->mothurOut("Also adjusting mindim to " + toString(maxdim-1) + "."); m->mothurOutEndLine(); }
543 vector< vector<double> > axes; axes.resize(maxdim);
544 for (int i = 0; i < axes.size(); i++) { axes[i].resize(names.size(), 0.0); }
546 map <string, vector<double> > orderedAxes;
547 map <string, vector<double> >::iterator it;
551 if (m->control_pressed) { in.close(); return axes; }
554 in >> group; m->gobble(in);
557 if (!m->inUsersGroups(group, names)) { ignore = true; m->mothurOut(group + " is in your axes file and not in your distance file, ignoring."); m->mothurOutEndLine(); }
559 vector<double> thisGroupsAxes;
560 for (int i = 0; i < count; i++) {
564 //only save the axis we want
565 if (i < maxdim) { thisGroupsAxes.push_back(temp); }
568 if (!ignore) { orderedAxes[group] = thisGroupsAxes; }
575 if (names.size() != orderedAxes.size()) { m->mothurOut("[ERROR]: your axes file does not match your distance file, aborting."); m->mothurOutEndLine(); m->control_pressed = true; return axes; }
577 //put axes info in same order as distance file, just in case
578 for (int i = 0; i < names.size(); i++) {
579 it = orderedAxes.find(names[i]);
581 if (it != orderedAxes.end()) {
582 vector<double> thisGroupsAxes = it->second;
584 for (int j = 0; j < thisGroupsAxes.size(); j++) {
585 axes[j][i] = thisGroupsAxes[j];
588 }else { m->mothurOut("[ERROR]: your axes file does not match your distance file, aborting."); m->mothurOutEndLine(); m->control_pressed = true; return axes; }
593 catch(exception& e) {
594 m->errorOut(e, "NMDSCommand", "readAxes");
598 /**********************************************************************************************************************/