bpp-core  2.2.0
ApplicationTools.cpp
Go to the documentation of this file.
1 //
2 // File: ApplicationTools.cpp
3 // Created by: Julien Dutheil
4 // Created on: Fri Oct 21 16:19 2005
5 // From old file created on: Sun Dec 14 09:36:26 2003
6 //
7 
8 /*
9 Copyright or © or Copr. Bio++ Development Team, (November 16, 2004)
10 
11 This software is a computer program whose purpose is to provide basal and
12 utilitary classes. This file belongs to the Bio++ Project.
13 
14 This software is governed by the CeCILL license under French law and
15 abiding by the rules of distribution of free software. You can use,
16 modify and/ or redistribute the software under the terms of the CeCILL
17 license as circulated by CEA, CNRS and INRIA at the following URL
18 "http://www.cecill.info".
19 
20 As a counterpart to the access to the source code and rights to copy,
21 modify and redistribute granted by the license, users are provided only
22 with a limited warranty and the software's author, the holder of the
23 economic rights, and the successive licensors have only limited
24 liability.
25 
26 In this respect, the user's attention is drawn to the risks associated
27 with loading, using, modifying and/or developing or reproducing the
28 software by the user in light of its specific status of free software,
29 that may mean that it is complicated to manipulate, and that also
30 therefore means that it is reserved for developers and experienced
31 professionals having in-depth computer knowledge. Users are therefore
32 encouraged to load and test the software's suitability as regards their
33 requirements in conditions enabling the security of their systems and/or
34 data to be ensured and, more generally, to use and operate it in the
35 same conditions as regards security.
36 
37 The fact that you are presently reading this means that you have had
38 knowledge of the CeCILL license and that you accept its terms.
39 */
40 
41 #include "ApplicationTools.h"
42 
43 using namespace bpp;
44 
45 // From the STL:
46 #include <cmath>
47 
48 using namespace std;
49 
50 /******************************************************************************/
51 
60 
61 /******************************************************************************/
62 
64  const std::string & parameterName,
65  std::map<std::string, std::string>& params)
66 {
67  return (params.find(parameterName) != params.end() && !TextTools::isEmpty(params[parameterName]));
68 }
69 
71  const std::string & parameterName,
72  std::vector<std::string>& params)
73 {
74  for (size_t i = 0; i < params.size(); ++i)
75  if (params[i] == parameterName)
76  return true;
77 
78  return false;
79 }
80 
81 /******************************************************************************/
82 
83 std::vector<std::string> ApplicationTools::matchingParameters(const std::string& pattern, std::map<std::string, std::string>& params)
84 {
85  vector<string> retv;
86 
87  map<string, string>::iterator it;
88  for (it=params.begin(); it!=params.end(); it++)
89  {
90  StringTokenizer stj(pattern, "*", true, false);
91  size_t pos1, pos2;
92  string parn = it->first;
93  bool flag(true);
94  string g = stj.nextToken();
95  pos1 = parn.find(g);
96  if (pos1 != 0)
97  flag = false;
98  pos1 += g.length();
99  while (flag && stj.hasMoreToken())
100  {
101  g = stj.nextToken();
102  pos2 = parn.find(g, pos1);
103  if (pos2 == string::npos)
104  {
105  flag = false;
106  break;
107  }
108  pos1 = pos2 + g.length();
109  }
110  if (flag &&
111  ((g.length() == 0) || (pos1 == parn.length()) || (parn.rfind(g) == parn.length() - g.length())))
112  retv.push_back(parn);
113  }
114 
115  return retv;
116 }
117 
118 std::vector<std::string> ApplicationTools::matchingParameters(const std::string& pattern, std::vector<std::string>& params)
119 {
120  vector<string> retv;
121 
122  for (size_t i=0;i<params.size();i++)
123  {
124  StringTokenizer stj(pattern, "*", true, false);
125  size_t pos1, pos2;
126  string parn = params[i];
127  bool flag(true);
128  string g = stj.nextToken();
129  pos1 = parn.find(g);
130  if (pos1 != 0)
131  flag = false;
132  pos1 += g.length();
133  while (flag && stj.hasMoreToken())
134  {
135  g = stj.nextToken();
136  pos2 = parn.find(g, pos1);
137  if (pos2 == string::npos)
138  {
139  flag = false;
140  break;
141  }
142  pos1 = pos2 + g.length();
143  }
144  if (flag &&
145  ((g.length() == 0) || (pos1 == parn.length()) || (parn.rfind(g) == parn.length() - g.length())))
146  retv.push_back(parn);
147  }
148 
149  return retv;
150 }
151 
152 /******************************************************************************/
153 
155  const string& parameter,
156  map<string, string>& params,
157  bool isRequired,
158  bool mustExist,
159  const string& suffix,
160  bool suffixIsOptional,
161  const string& defaultPath,
162  int warn) throw (Exception)
163 {
164  string filePath = getStringParameter(parameter, params, defaultPath, suffix, suffixIsOptional, warn);
165  if (filePath == "") filePath = "none";
166  if (filePath == "none" && isRequired)
167  {
168  throw Exception("You must specify a file for this parameter: " + parameter + (suffixIsOptional ? "" : suffix));
169  }
170  if(filePath == "none") return filePath;
171  if(mustExist && !FileTools::fileExists(filePath))
172  {
173  throw Exception("File does not exists: " + filePath);
174  }
175  return filePath;
176 }
177 
178 /******************************************************************************/
179 
181  const std::string& parameterName,
182  std::map<std::string, std::string>& params,
183  double defaultValue,
184  const std::string& suffix,
185  bool suffixIsOptional,
186  int warn)
187 {
188  double dParam = defaultValue;
189  if (parameterExists(parameterName + suffix, params))
190  {
191  dParam = TextTools::toDouble(params[parameterName + suffix]);
192  }
193  else if (suffixIsOptional && parameterExists(parameterName, params))
194  {
195  dParam = TextTools::toDouble(params[parameterName]);
196  }
197  else if(warn <= warningLevel)
198  {
199  displayWarning("Parameter " + parameterName + suffix + " not specified. Default used instead: " + TextTools::toString(defaultValue));
200  }
201  return dParam;
202 }
203 
204 /******************************************************************************/
205 
207  const std::string & parameterName,
208  std::map<std::string, std::string> & params,
209  int defaultValue,
210  const std::string & suffix,
211  bool suffixIsOptional,
212  int warn)
213 {
214  int iParam = defaultValue;
215  if (parameterExists(parameterName + suffix, params)) {
216  iParam = TextTools::toInt(params[parameterName + suffix]);
217  } else if(suffixIsOptional && parameterExists(parameterName, params)) {
218  iParam = TextTools::toInt(params[parameterName]);
219  } else if (warn <= warningLevel) {
220  displayWarning("Parameter " + parameterName + suffix + " not specified. Default used instead: " + TextTools::toString(defaultValue));
221  }
222  return iParam;
223 }
224 
225 /******************************************************************************/
226 
228  const std::string& parameterName,
229  std::map<std::string, std::string>& params,
230  const std::string& defaultValue,
231  const std::string& suffix,
232  bool suffixIsOptional,
233  int warn)
234 {
235  string sParam = defaultValue;
236  if (parameterExists(parameterName + suffix, params)) {
237  sParam = params[parameterName + suffix];
238  } else if (suffixIsOptional && parameterExists(parameterName, params)) {
239  sParam = params[parameterName];
240  } else if (warn <= warningLevel) {
241  displayWarning("Parameter " + parameterName + " not specified. Default used instead: " + defaultValue);
242  }
243  return sParam;
244 }
245 
246 /******************************************************************************/
247 
249  const std::string& parameterName,
250  std::map<std::string, std::string>& params,
251  bool defaultValue,
252  const std::string& suffix,
253  bool suffixIsOptional,
254  int warn)
255 {
256  string sParam;
257  bool bParam = defaultValue;
258  if (parameterExists(parameterName + suffix, params))
259  {
260  sParam = params[parameterName + suffix];
261  }
262  else if (suffixIsOptional && parameterExists(parameterName, params))
263  {
264  sParam = params[parameterName];
265  }
266  else {
267  if (warn <= warningLevel)
268  {
269  displayWarning("Parameter " + parameterName + " not specified. Default used instead: " + TextTools::toString(defaultValue));
270  }
271  return bParam;
272  }
273  if ((sParam == "true")
274  || (sParam == "TRUE")
275  || (sParam == "t")
276  || (sParam == "T")
277  || (sParam == "yes")
278  || (sParam == "YES")
279  || (sParam == "y")
280  || (sParam == "Y")
281  || (sParam == "1"))
282  bParam = true;
283  else if ((sParam == "false")
284  || (sParam == "FALSE")
285  || (sParam == "f")
286  || (sParam == "F")
287  || (sParam == "no")
288  || (sParam == "NO")
289  || (sParam == "n")
290  || (sParam == "N")
291  || (sParam == "0"))
292  bParam = false;
293  else throw Exception("ApplicationTools::getBooleanParameter. Wrong description:" + sParam);
294 
295  return bParam;
296 }
297 
298 /******************************************************************************/
299 
300 void ApplicationTools::displayMessage(const std::string& text) { if(message) (*message << text).endLine(); }
301 
302 void ApplicationTools::displayError(const std::string& text) { if(error) (*error << "ERROR!!! " << text).endLine(); }
303 
304 void ApplicationTools::displayWarning(const std::string& text) { if(warning) (*warning << "WARNING!!! " << text).endLine(); }
305 
306 void ApplicationTools::displayTask(const std::string& text, bool eof)
307 {
308  if (message)
309  {
310  *message << TextTools::resizeRight(text, static_cast<size_t>(static_cast<float>(terminalWidth) * terminalSplit - 1), '.') << ": ";
311  if (eof) message->endLine();
312  else message->flush();
313  }
314 }
315 
316 void ApplicationTools::displayTaskDone() { if(message) (*message << "Done.").endLine(); }
317 
318 /******************************************************************************/
319 
320 void ApplicationTools::displayGauge(size_t iter, size_t total, char symbol, const std::string& mes)
321 {
322  if (!message) return;
323  if (total == 0) return;//We do not display anything in that case.
324  size_t width = static_cast<size_t>(static_cast<float>(terminalWidth) * terminalSplit - 2);
325  string gauge = string(static_cast<size_t>((1. * static_cast<double>(iter) / static_cast<double>(total)) * static_cast<double>(width)), symbol);
326  string info = mes;
327  size_t step = static_cast<size_t>(ceil(1. * static_cast<double>(total) / static_cast<double>(width)));
328  size_t x = iter % step;
329  if (interactive)
330  {
331  string fill = string(width - gauge.length(), ' ');
332  gauge = "[" + gauge + fill + "] " + TextTools::resizeLeft(TextTools::toString(100 * iter / total), 3) + "%";
333  if (mes.size() > terminalWidth - gauge.size())
334  info = TextTools::resizeRight(mes, terminalWidth - gauge.size());
335  if (x == 0 || iter == total) { *message << '\r' + info + gauge; message->flush(); }
336  }
337  else
338  {
339  if (iter == 0)
340  {
341  *message << "[";
342  message->flush();
343  return;
344  }
345  if (iter >= total)
346  {
347  size_t fill = static_cast<size_t>(static_cast<float>(terminalWidth) * terminalSplit) - (total - 1) / step - 1;
348  *message << TextTools::resizeLeft("]", fill, symbol);
349  message->flush();
350  return;
351  }
352  if (x == 0) { *message << symbol; message->flush(); }
353  }
354 }
355 
356 /******************************************************************************/
357 
358 void ApplicationTools::displayUnlimitedGauge(size_t iter, const std::string& mes)
359 {
360  if (!message) return;
361  string chars = "-/-\\";
362  string info = mes;
363  if (interactive)
364  {
365  unsigned int i = iter % 4;
366  *message << '\r' << info << chars[i] << " " << TextTools::toString(iter);
367  message->flush();
368  }
369  else
370  {
371  if (iter == 0)
372  *message << info;
373  *message << "*";
374  message->flush();
375  return;
376  }
377 }
378 
379 /******************************************************************************/
380 
381 void ApplicationTools::displayTime(const std::string& msg)
382 {
383  time_t endTime;
384  time(&endTime);
385  if (message)
386  {
387  double nsec = difftime(endTime, startTime);
388  double nmin = floor(nsec/60.);
389  double nhou = floor(nmin/60.);
390  double nday = floor(nhou/24.);
391  nhou = nhou - nday * 24;
392  nmin = nmin - (nday * 24 + nhou) * 60;
393  nsec = nsec - ((nday * 24 + nhou) * 60 + nmin) * 60;
394  *message << msg << " ";
395  *message << nday << "d, ";
396  *message << nhou << "h, ";
397  *message << nmin << "m, ";
398  *message << nsec << "s.";
399  message->endLine();
400  }
401 }
402 
403 /******************************************************************************/
404 
406 {
407  time_t endTime;
408  time(&endTime);
409  return difftime(endTime, startTime);
410 }
411 
412 /******************************************************************************/
413 
static void displayTaskDone()
Print a task ended message.
static void displayWarning(const std::string &text)
Print a warning message.
static int getIntParameter(const std::string &parameterName, std::map< std::string, std::string > &params, int defaultValue, const std::string &suffix="", bool suffixIsOptional=true, int warn=0)
Get an integer parameter.
static std::string resizeLeft(const std::string &s, size_t newSize, char fill=' ')
Send a string of size &#39;newSize&#39;, which is a copy of &#39;s&#39; truncated or filled with character &#39;fill&#39; at ...
Definition: TextTools.cpp:334
A tokenizer for strings.
This class allows to perform a correspondence analysis.
static int warningLevel
Specify the amount of warning to display.
static void displayTime(const std::string &msg)
Display the current timer value to the &#39;message&#39; stream.
bool hasMoreToken() const
Tell if some tokens are still available.
static std::string resizeRight(const std::string &s, size_t newSize, char fill=' ')
Send a string of size &#39;newSize&#39;, which is a copy of &#39;s&#39; truncated or filled with character &#39;fill&#39; at ...
Definition: TextTools.cpp:324
static void displayTask(const std::string &text, bool eof=false)
Print a task message.
STL namespace.
static bool getBooleanParameter(const std::string &parameterName, std::map< std::string, std::string > &params, bool defaultValue, const std::string &suffix="", bool suffixIsOptional=true, int warn=0)
Get a boolean parameter.
const std::string & nextToken()
Get the next available token. If no token is availbale, throw an Exception.
static size_t terminalWidth
The width of the output terminal (in character).
static double getDoubleParameter(const std::string &parameterName, std::map< std::string, std::string > &params, double defaultValue, const std::string &suffix="", bool suffixIsOptional=true, int warn=0)
Get a double parameter.
Standard output stream.
Definition: OutputStream.h:266
static std::string toString(T t)
General template method to convert to a string.
Definition: TextTools.h:189
static int toInt(const std::string &s, char scientificNotation='e')
Convert from string to int.
Definition: TextTools.cpp:302
static std::string getAFilePath(const std::string &parameter, std::map< std::string, std::string > &params, bool isRequired=true, bool mustExist=true, const std::string &suffix="", bool suffixIsOptional=false, const std::string &defaultPath="none", int warn=0)
Get a file path.
static bool isEmpty(const std::string &s)
Tell if a string is empty.
Definition: TextTools.cpp:52
static time_t startTime
Timer variable.
static OutputStream * message
The output stream where messages have to be displayed.
Standard error stream.
Definition: OutputStream.h:304
static bool parameterExists(const std::string &parameterName, std::map< std::string, std::string > &params)
Tells if a parameter have been specified.
static bool interactive
Tell if the program is interactive (typically run in foreground). Default to yes. ...
static void displayMessage(const std::string &text)
Print a message.
OutputStream interface.
Definition: OutputStream.h:64
static float terminalSplit
The fraction of terminal width dedicated to messages.
Exception base class.
Definition: Exceptions.h:57
static void displayGauge(size_t iter, size_t total, char symbol='>', const std::string &mes="")
Display a gauge.
static std::string getStringParameter(const std::string &parameterName, std::map< std::string, std::string > &params, const std::string &defaultValue, const std::string &suffix="", bool suffixIsOptional=true, int warn=0)
Get a string parameter.
static bool fileExists(const std::string &filename)
Tells if a file exist.
Definition: FileTools.cpp:54
static OutputStream * error
The output stream where errors have to be displayed.
static void displayUnlimitedGauge(size_t iter, const std::string &mes="")
Display a gauge for unefined amount of iterations.
static std::vector< std::string > matchingParameters(const std::string &pattern, std::map< std::string, std::string > &params)
Returns a vector of parameter names that match a given pattern.
static OutputStream * warning
The output stream where warnings have to be displayed.
static double toDouble(const std::string &s, char dec='.', char scientificNotation='e')
Convert from string to double.
Definition: TextTools.cpp:313
static void displayError(const std::string &text)
Print an error message.
static double getTime()
Get the current timer value.