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); parameters.push_back(paxes);
17 CommandParameter pphylip("phylip", "InputTypes", "", "", "none", "none", "none",false,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 NMDSCommand::NMDSCommand(){
60 abort = true; calledHelp = true;
62 vector<string> tempOutNames;
63 outputTypes["nmds"] = tempOutNames;
64 outputTypes["stress"] = tempOutNames;
65 outputTypes["iters"] = tempOutNames;
68 m->errorOut(e, "NMDSCommand", "NMDSCommand");
72 //**********************************************************************************************************************
74 NMDSCommand::NMDSCommand(string option) {
76 abort = false; calledHelp = false;
78 //allow user to run help
79 if(option == "help") { help(); abort = true; calledHelp = true; }
82 vector<string> myArray = setParameters();
84 OptionParser parser(option);
85 map<string, string> parameters = parser. getParameters();
87 ValidParameters validParameter;
88 map<string, string>::iterator it;
90 //check to make sure all parameters are valid for command
91 for (it = parameters.begin(); it != parameters.end(); it++) {
92 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
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("phylip");
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["phylip"] = inputDir + it->second; }
107 it = parameters.find("axes");
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["axes"] = inputDir + it->second; }
116 //initialize outputTypes
117 vector<string> tempOutNames;
118 outputTypes["nmds"] = tempOutNames;
119 outputTypes["iters"] = tempOutNames;
120 outputTypes["stress"] = tempOutNames;
122 //required parameters
123 phylipfile = validParameter.validFile(parameters, "phylip", true);
124 if (phylipfile == "not open") { phylipfile = ""; abort = true; }
125 else if (phylipfile == "not found") {
126 //if there is a current phylip file, use it
127 phylipfile = m->getPhylipFile();
128 if (phylipfile != "") { m->mothurOut("Using " + phylipfile + " as input file for the phylip parameter."); m->mothurOutEndLine(); }
129 else { m->mothurOut("You have no current phylip file and the phylip parameter is required."); m->mothurOutEndLine(); abort = true; }
132 axesfile = validParameter.validFile(parameters, "axes", true);
133 if (axesfile == "not open") { axesfile = ""; abort = true; }
134 else if (axesfile == "not found") { axesfile = ""; }
136 //if the user changes the output directory command factory will send this info to us in the output parameter
137 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){
139 outputDir += m->hasPath(phylipfile); //if user entered a file with a path then preserve it
142 string temp = validParameter.validFile(parameters, "mindim", false); if (temp == "not found") { temp = "2"; }
143 convert(temp, mindim);
145 temp = validParameter.validFile(parameters, "maxiters", false); if (temp == "not found") { temp = "500"; }
146 convert(temp, maxIters);
148 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "10"; }
149 convert(temp, iters);
151 temp = validParameter.validFile(parameters, "maxdim", false); if (temp == "not found") { temp = "2"; }
152 convert(temp, maxdim);
154 temp = validParameter.validFile(parameters, "epsilon", false); if (temp == "not found") { temp = "0.000000000001"; }
155 convert(temp, epsilon);
157 if (mindim < 1) { m->mothurOut("mindim must be at least 1."); m->mothurOutEndLine(); abort = true; }
158 if (maxdim < mindim) { m->mothurOut("maxdim must be greater than mindim."); m->mothurOutEndLine(); abort = true; }
162 catch(exception& e) {
163 m->errorOut(e, "NMDSCommand", "NMDSCommand");
167 //**********************************************************************************************************************
168 int NMDSCommand::execute(){
171 if (abort == true) { if (calledHelp) { return 0; } return 2; }
173 cout.setf(ios::fixed, ios::floatfield);
174 cout.setf(ios::showpoint);
176 vector<string> names;
177 vector< vector< double> > matrix;
179 //read in phylip file
180 ReadPhylipVector readFile(phylipfile);
181 names = readFile.read(matrix);
182 if (m->control_pressed) { return 0; }
185 vector< vector<double> > axes;
186 if (axesfile != "") { axes = readAxes(names); }
188 string outputFileName = outputDir + m->getRootName(m->getSimpleName(phylipfile)) + "nmds.iters";
189 string stressFileName = outputDir + m->getRootName(m->getSimpleName(phylipfile)) + "nmds.stress";
190 outputNames.push_back(outputFileName); outputTypes["iters"].push_back(outputFileName);
191 outputNames.push_back(stressFileName); outputTypes["stress"].push_back(stressFileName);
194 m->openOutputFile(outputFileName, out);
195 m->openOutputFile(stressFileName, out2);
197 out2.setf(ios::fixed, ios::floatfield);
198 out2.setf(ios::showpoint);
199 out.setf(ios::fixed, ios::floatfield);
200 out.setf(ios::showpoint);
202 out2 << "Dimension\tIter\tStress\tRsq" << endl;
204 double bestStress = 10000000;
205 double bestR2 = 10000000;
206 vector< vector<double> > bestConfig;
209 for (int i = mindim; i <= maxdim; i++) {
210 m->mothurOut("Processing Dimension: " + toString(i)); m->mothurOutEndLine();
212 for (int j = 0; j < iters; j++) {
213 m->mothurOut(toString(j+1)); m->mothurOutEndLine();
215 //get configuration - either randomly generate or resize to this dimension
216 vector< vector<double> > thisConfig;
217 if (axesfile == "") { thisConfig = generateStartingConfiguration(names.size(), i); }
218 else { thisConfig = getConfiguration(axes, i); }
219 if (m->control_pressed) { out.close(); out2.close(); for (int k = 0; k < outputNames.size(); k++) { remove(outputNames[k].c_str()); } return 0; }
221 //calc nmds for this dimension
223 vector< vector<double> > endConfig = nmdsCalc(matrix, thisConfig, stress);
224 if (m->control_pressed) { out.close(); out2.close(); for (int k = 0; k < outputNames.size(); k++) { remove(outputNames[k].c_str()); } return 0; }
226 //calc euclid distances for new config
227 vector< vector<double> > newEuclid = linearCalc.calculateEuclidianDistance(endConfig);
228 if (m->control_pressed) { out.close(); out2.close(); for (int k = 0; k < outputNames.size(); k++) { remove(outputNames[k].c_str()); } return 0; }
230 //calc correlation between original distances and euclidean distances from this config
231 double rsquared = linearCalc.calcPearson(newEuclid, matrix);
232 rsquared *= rsquared;
233 if (m->control_pressed) { out.close(); out2.close(); for (int k = 0; k < outputNames.size(); k++) { remove(outputNames[k].c_str()); } return 0; }
236 out << "Config" << (j+1) << '\t';
237 for (int k = 0; k < i; k++) { out << "axis" << (k+1) << '\t'; }
239 out2 << i << '\t' << (j+1) << '\t' << stress << '\t' << rsquared << endl;
241 output(endConfig, names, out);
244 if (stress < bestStress) {
248 bestConfig = endConfig;
251 if (m->control_pressed) { out.close(); out2.close(); for (int k = 0; k < outputNames.size(); k++) { remove(outputNames[k].c_str()); } return 0; }
255 out.close(); out2.close();
258 string BestFileName = outputDir + m->getRootName(m->getSimpleName(phylipfile)) + "nmds.axes";
259 outputNames.push_back(BestFileName); outputTypes["nmds"].push_back(BestFileName);
261 m->mothurOut("\nNumber of dimensions:\t" + toString(bestDim) + "\n");
262 m->mothurOut("Lowest stress :\t" + toString(bestStress) + "\n");
263 m->mothurOut("R-squared for configuration:\t" + toString(bestR2) + "\n");
266 m->openOutputFile(BestFileName, outBest);
267 outBest.setf(ios::fixed, ios::floatfield);
268 outBest.setf(ios::showpoint);
271 for (int k = 0; k < bestConfig.size(); k++) { outBest << "axis" << (k+1) << '\t'; }
274 output(bestConfig, names, outBest);
278 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } return 0; }
280 m->mothurOutEndLine();
281 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
282 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
283 m->mothurOutEndLine();
287 catch(exception& e) {
288 m->errorOut(e, "NMDSCommand", "execute");
292 //**********************************************************************************************************************
293 vector< vector<double> > NMDSCommand::nmdsCalc(vector< vector<double> >& matrix, vector< vector<double> >& config, double& stress1) {
296 vector< vector<double> > newConfig = config;
298 //calc euclid distances
299 vector< vector<double> > euclid = linearCalc.calculateEuclidianDistance(newConfig);
300 if (m->control_pressed) { return newConfig; }
302 double stress2 = calculateStress(matrix, euclid);
303 stress1 = stress2 + 1.0 + epsilon;
306 while ((count < maxIters) && (abs(stress1 - stress2) > epsilon)) {
311 if (m->control_pressed) { return newConfig; }
313 vector< vector<double> > b; b.resize(euclid.size());
314 for (int i = 0; i < b.size(); i++) { b[i].resize(euclid[i].size(), 0.0); }
316 vector<double> columnSums; columnSums.resize(euclid.size(), 0.0);
317 for (int i = 0; i < euclid.size(); i++) {
318 for (int j = 0; j < euclid[i].size(); j++) {
319 //eliminate divide by zero error
320 if (euclid[i][j] != 0) {
321 b[i][j] = matrix[i][j] / euclid[i][j];
322 columnSums[j] += b[i][j];
328 //put in diagonal sums
329 for (int i = 0; i < euclid.size(); i++) { b[i][i] = columnSums[i]; }
331 int numInLowerTriangle = matrix.size() * (matrix.size()-1) / 2.0;
332 double n = (1.0 + sqrt(1.0 + 8.0 * numInLowerTriangle)) / 2.0;
335 newConfig = linearCalc.matrix_mult(newConfig, b);
336 for (int i = 0; i < newConfig.size(); i++) {
337 for (int j = 0; j < newConfig[i].size(); j++) {
338 newConfig[i][j] *= (1.0 / n);
342 euclid = linearCalc.calculateEuclidianDistance(newConfig);
344 stress2 = calculateStress(matrix, euclid);
349 catch(exception& e) {
350 m->errorOut(e, "NMDSCommand", "generateStartingConfiguration");
355 //**********************************************************************************************************************
356 //generate random config
357 vector< vector<double> > NMDSCommand::generateStartingConfiguration(int numNames, int dimension) {
359 vector< vector<double> > axes; axes.resize(dimension);
360 for (int i = 0; i < axes.size(); i++) { axes[i].resize(numNames); }
362 //generate random number between -1 and 1, precision 6
363 for (int i = 0; i < axes.size(); i++) {
364 for (int j = 0; j < axes[i].size(); j++) {
366 if (m->control_pressed) { return axes; }
368 //generate random int between 0 and 99999
369 int myrand = (int)((float)(rand()) / ((RAND_MAX / 99998) + 1));
371 //generate random sign
372 int mysign = (int)((float)(rand()) / ((RAND_MAX / 99998) + 1));
374 //if mysign is even then sign = positive, else sign = negative
375 if ((mysign % 2) == 0) { mysign = 1.0; }
376 else { mysign = -1.0; }
378 axes[i][j] = mysign * myrand / (float) 100000;
384 catch(exception& e) {
385 m->errorOut(e, "NMDSCommand", "generateStartingConfiguration");
389 //**********************************************************************************************************************
390 //normalize configuration
391 int NMDSCommand::normalizeConfiguration(vector< vector<double> >& axes, int numNames, int dimension) {
393 vector<double> averageAxes; averageAxes.resize(dimension, 0.0);
396 for (int i = 0; i < axes.size(); i++) {
397 for (int j = 0; j < axes[i].size(); j++) { averageAxes[i] += axes[i][j]; }
399 averageAxes[i] /= (float) numNames;
403 double sumDenom = 0.0;
404 for (int i = 0; i < axes.size(); i++) {
405 for (int j = 0; j < axes[i].size(); j++) {
406 sumDenom += ((axes[i][j] - averageAxes[i]) * (axes[i][j] - averageAxes[i]));
410 double denom = sqrt((sumDenom / (float) (axes.size() * numNames)));
412 for (int i = 0; i < axes.size(); i++) {
413 for (int j = 0; j < axes[i].size(); j++) {
414 axes[i][j] = (axes[i][j] - averageAxes[i]) / denom;
420 catch(exception& e) {
421 m->errorOut(e, "NMDSCommand", "normalizeConfiguration");
425 //**********************************************************************************************************************
427 vector< vector<double> > NMDSCommand::getConfiguration(vector< vector<double> >& axes, int dimension) {
429 vector< vector<double> > newAxes; newAxes.resize(dimension);
431 for (int i = 0; i < dimension; i++) {
432 newAxes[i] = axes[i];
437 catch(exception& e) {
438 m->errorOut(e, "NMDSCommand", "getConfiguration");
442 //**********************************************************************************************************************
443 //find raw stress, and normalize using
444 double NMDSCommand::calculateStress(vector< vector<double> >& matrix, vector< vector<double> >& config) {
446 double normStress = 0.0;
448 double rawStress = 0.0;
451 for (int i = 0; i < matrix.size(); i++) {
452 for (int j = 0; j < matrix[i].size(); j++) {
453 if (m->control_pressed) { return normStress; }
455 rawStress += ((matrix[i][j] - config[i][j]) * (matrix[i][j] - config[i][j]));
456 denom += (config[i][j] * config[i][j]);
461 if ((rawStress != 0.0) && (denom != 0.0)) {
462 normStress = sqrt((rawStress / denom));
467 catch(exception& e) {
468 m->errorOut(e, "NMDSCommand", "calculateStress");
473 //**********************************************************************************************************************
474 int NMDSCommand::output(vector< vector<double> >& config, vector<string>& names, ofstream& out) {
477 for (int i = 0; i < names.size(); i++) {
479 out << names[i] << '\t';
481 for (int j = 0; j < config.size(); j++) {
482 out << config[j][i] << '\t';
492 catch(exception& e) {
493 m->errorOut(e, "NMDSCommand", "output");
497 /*****************************************************************/
498 vector< vector<double> > NMDSCommand::readAxes(vector<string> names){
501 m->openInputFile(axesfile, in);
503 string headerLine = m->getline(in); m->gobble(in);
505 //count the number of axis you are reading
509 int pos = headerLine.find("axis");
510 if (pos != string::npos) {
512 headerLine = headerLine.substr(pos+4);
513 }else { done = true; }
516 if (maxdim > count) {
517 m->mothurOut("You requested maxdim = " + toString(maxdim) + ", but your file only includes " + toString(count) + ". Using " + toString(count) + "."); m->mothurOutEndLine();
519 if (maxdim < mindim) { m->mothurOut("Also adjusting mindim to " + toString(maxdim-1) + "."); m->mothurOutEndLine(); }
522 vector< vector<double> > axes; axes.resize(maxdim);
523 for (int i = 0; i < axes.size(); i++) { axes[i].resize(names.size(), 0.0); }
525 map <string, vector<double> > orderedAxes;
526 map <string, vector<double> >::iterator it;
530 if (m->control_pressed) { in.close(); return axes; }
533 in >> group; m->gobble(in);
536 if (!m->inUsersGroups(group, names)) { ignore = true; m->mothurOut(group + " is in your axes file and not in your distance file, ignoring."); m->mothurOutEndLine(); }
538 vector<double> thisGroupsAxes;
539 for (int i = 0; i < count; i++) {
543 //only save the axis we want
544 if (i < maxdim) { thisGroupsAxes.push_back(temp); }
547 if (!ignore) { orderedAxes[group] = thisGroupsAxes; }
554 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; }
556 //put axes info in same order as distance file, just in case
557 for (int i = 0; i < names.size(); i++) {
558 it = orderedAxes.find(names[i]);
560 if (it != orderedAxes.end()) {
561 vector<double> thisGroupsAxes = it->second;
563 for (int j = 0; j < thisGroupsAxes.size(); j++) {
564 axes[j][i] = thisGroupsAxes[j];
567 }else { m->mothurOut("[ERROR]: your axes file does not match your distance file, aborting."); m->mothurOutEndLine(); m->control_pressed = true; return axes; }
572 catch(exception& e) {
573 m->errorOut(e, "NMDSCommand", "readAxes");
577 /**********************************************************************************************************************/