LHAPDF is hosted by Hepforge, IPPP Durham
LHAPDF  6.1.6
Utils.h
1 // -*- C++ -*-
2 //
3 // This file is part of LHAPDF
4 // Copyright (C) 2012-2016 The LHAPDF collaboration (see AUTHORS for details)
5 //
6 #pragma once
7 #ifndef LHAPDF_Utils_H
8 #define LHAPDF_Utils_H
9 
10 // STL includes
11 #include <cassert>
12 #include <vector>
13 #include <map>
14 #include <string>
15 #include <algorithm>
16 #include <memory>
17 #include <iostream>
18 #include <iomanip>
19 #include <sstream>
20 #include <fstream>
21 #include <limits>
22 #include <cmath>
23 // System includes
24 #include "sys/stat.h"
25 
26 
28 namespace LHAPDF {
29 
30 
31  // Allow implicit use of the std namespace within namespace LHAPDF
32  using namespace std;
33 
34 
36 
37 
39  struct bad_lexical_cast : public std::runtime_error {
40  bad_lexical_cast(const std::string& what) : std::runtime_error(what) {}
41  };
42 
46  template<typename T, typename U>
47  T lexical_cast(const U& in) {
48  try {
49  std::stringstream ss;
50  ss << in;
51  T out;
52  ss >> out;
53  return out;
54  } catch (const std::exception& e) {
55  throw bad_lexical_cast(e.what());
56  }
57  }
58 
60  template <typename T>
61  inline std::string to_str(const T& val) {
62  return lexical_cast<string>(val);
63  }
64 
66  template <typename T>
67  inline std::string to_str(const std::vector<T>& vec) {
68  string rtn = "[";
69  for (size_t i = 0; i < vec.size(); ++i) {
70  rtn += to_str(vec[i]);
71  if (i < vec.size()-1) rtn += ", ";
72  }
73  rtn += "]";
74  return rtn;
75  }
76 
78  inline std::string to_str_zeropad(int val, size_t nchars=4) {
79  stringstream ss;
80  ss << setfill('0') << setw(nchars) << val;
81  return ss.str();
82  }
83 
85  inline std::string join(const std::vector<std::string>& svec, const std::string& sep) {
86  string rtn;
87  for (size_t i = 0; i < svec.size(); ++i) {
88  rtn += svec[i];
89  if (i < svec.size()-1) rtn += ", ";
90  }
91  return rtn;
92  }
93 
95  inline std::vector<std::string> split(const std::string& s, const std::string& sep) {
96  vector<string> rtn;
97  string tmp = s; // non-const working copy, to be incrementally truncated
98  while (true) {
99  const size_t delim_pos = tmp.find(sep);
100  if (delim_pos == string::npos) break;
101  const string s = tmp.substr(0, delim_pos);
102  if (!s.empty()) rtn.push_back(s); // Don't insert "empties"
103  tmp.replace(0, delim_pos+1, ""); // Remove already-processed part
104  }
105  if (!tmp.empty()) rtn.push_back(tmp); // Don't forget the trailing component!
106  return rtn;
107  }
108 
110  inline bool contains(const std::string& s, const std::string& sub) {
111  return s.find(sub) != string::npos;
112  }
113 
115  inline bool startswith(const std::string& s, const std::string& sub) {
116  return s.find(sub) == 0;
117  }
118 
120  inline bool endswith(const std::string& s, const std::string& sub) {
121  return s.find(sub) == s.length()-sub.length();
122  }
123 
125  inline size_t countchar(const std::string& s, const char c) {
126  return std::count(s.begin(), s.end(), c);
127  }
128 
130  inline std::string trim(const std::string& s) {
131  const size_t firstnonspacepos = s.find_first_not_of(" ");
132  const size_t lastnonspacepos = s.find_last_not_of(" ");
133  if (firstnonspacepos == std::string::npos) return "";
134  return s.substr(firstnonspacepos, lastnonspacepos-firstnonspacepos+1);
135  }
136 
138  inline std::string to_lower(const std::string& s) {
139  string rtn = s;
140  transform(rtn.begin(), rtn.end(), rtn.begin(), (int(*)(int)) tolower);
141  return rtn;
142  }
143 
145  inline std::string to_upper(const std::string& s) {
146  string rtn = s;
147  transform(rtn.begin(), rtn.end(), rtn.begin(), (int(*)(int)) toupper);
148  return rtn;
149  }
150 
152 
153 
155 
156 
158  inline bool path_exists(const std::string& p) {
159  struct stat st;
160  return (stat(p.c_str(), &st) == 0);
161  }
162 
164  inline bool file_exists(const std::string& p) {
165  struct stat st;
166  return (stat(p.c_str(), &st) == 0 && S_ISREG(st.st_mode));
167  }
168 
170  inline bool dir_exists(const std::string& p) {
171  struct stat st;
172  return (stat(p.c_str(), &st) == 0 && S_ISDIR(st.st_mode));
173  }
174 
176  inline std::string operator / (const std::string& a, const std::string& b) {
177  // Ensure that a doesn't end with a slash, and b doesn't start with one, to avoid "//"
178  const string anorm = (a.find("/") != std::string::npos) ? a.substr(0, a.find_last_not_of("/")+1) : a;
179  const string bnorm = (b.find("/") != std::string::npos) ? b.substr(b.find_first_not_of("/")) : b;
180  return anorm + "/" + bnorm;
181  }
182 
184  inline std::string basename(const std::string& p) {
185  if (!contains(p, "/")) return p;
186  return p.substr(p.rfind("/")+1);
187  }
188 
190  inline std::string dirname(const std::string& p) {
191  if (!contains(p, "/")) return "";
192  return p.substr(0, p.rfind("/"));
193  }
194 
196  inline std::string file_stem(const std::string& f) {
197  if (!contains(f, ".")) return f;
198  return f.substr(0, f.rfind("."));
199  }
200 
202  inline std::string file_extn(const std::string& f) {
203  if (!contains(f, ".")) return "";
204  return f.substr(f.rfind(".")+1);
205  }
206 
208 
210 
211 
213 
214 
216  template <typename N>
217  inline N sqr(const N& x) { return x*x; }
218 
220  template <typename N>
221  inline int sgn(N val) { return (N(0) < val) - (val < N(0)); }
222 
224  inline int in_range(double x, double low, double high) { return x >= low && x < high; }
225 
227  inline int in_closed_range(double x, double low, double high) { return x >= low && x <= high; }
228 
230  inline int in_open_range(double x, double low, double high) { return x > low && x < high; }
231 
233 
235  double norm_quantile(double p);
236 
238  double chisquared_quantile(double p, double ndf);
239 
241 
242 
244 
245 
247  template <typename T>
248  inline bool contains(const std::vector<T>& container, const T& item) {
249  return find(container.begin(), container.end(), item) != container.end();
250  }
251 
252  // /// Does the set<T> @a container contain @a item?
253  // template <typename T>
254  // inline bool contains(const std::set<T>& container, const T& item) {
255  // return container.find(item) != container.end();
256  // }
257 
259  template <typename K, typename T>
260  inline bool has_key(const std::map<K,T>& container, const K& key) {
261  return container.find(key) != container.end();
262  }
263 
264  // /// @name Implementation of generic begin/end container identification by traits
265  // /// taken from http://stackoverflow.com/a/9407420/91808 . Needs C++11 (or maybe just C++0x).
266  // //@{
267 
268  // #include <type_traits>
269 
270  // template<typename T>
271  // struct has_const_iterator {
272  // private:
273  // typedef char yes;
274  // typedef struct { char array[2]; } no;
275  // template<typename C> static yes test(typename C::const_iterator*);
276  // template<typename C> static no test(...);
277  // public:
278  // static const bool value = sizeof(test<T>(0)) == sizeof(yes);
279  // typedef T type;
280  // };
281 
282  // template <typename T>
283  // struct has_begin_end {
284  // template<typename C> static char (&f(typename std::enable_if<
285  // std::is_same<decltype(static_cast<typename C::const_iterator (C::*)() const>(&C::begin)),
286  // typename C::const_iterator(C::*)() const>::value, void>::type*))[1];
287 
288  // template<typename C> static char (&f(...))[2];
289 
290  // template<typename C> static char (&g(typename std::enable_if<
291  // std::is_same<decltype(static_cast<typename C::const_iterator (C::*)() const>(&C::end)),
292  // typename C::const_iterator(C::*)() const>::value, void>::type*))[1];
293 
294  // template<typename C> static char (&g(...))[2];
295 
296  // static bool const beg_value = sizeof(f<T>(0)) == 1;
297  // static bool const end_value = sizeof(g<T>(0)) == 1;
298  // };
299 
300  // template<typename T>
301  // struct is_container
302  // : std::integral_constant<bool, has_const_iterator<T>::value &&
303  // has_begin_end<T>::beg_value && has_begin_end<T>::end_value>
304  // { };
305 
307 
308 }
309 #endif
int in_open_range(double x, double low, double high)
Check if a number is in a range (open-open)
Definition: Utils.h:230
std::string to_str(const T &val)
Make a string representation of val.
Definition: Utils.h:61
size_t countchar(const std::string &s, const char c)
How many times does a string s contain the character c?
Definition: Utils.h:125
int sgn(N val)
Get the sign of a number.
Definition: Utils.h:221
std::string to_str_zeropad(int val, size_t nchars=4)
Format an integer val as a zero-padded string of length nchars.
Definition: Utils.h:78
std::vector< std::string > split(const std::string &s, const std::string &sep)
Split a string by a given separator.
Definition: Utils.h:95
STL namespace.
bool startswith(const std::string &s, const std::string &sub)
Does a string s start with the sub substring?
Definition: Utils.h:115
T lexical_cast(const U &in)
Convert between any types via stringstream.
Definition: Utils.h:47
std::string basename(const std::string &p)
Get the basename (i.e. terminal file name) from a path p.
Definition: Utils.h:184
bool file_exists(const std::string &p)
Check if a file p exists.
Definition: Utils.h:164
std::string join(const std::vector< std::string > &svec, const std::string &sep)
Concatenate strings with separator strings between each element.
Definition: Utils.h:85
int in_closed_range(double x, double low, double high)
Check if a number is in a range (closed-closed)
Definition: Utils.h:227
Local alternative to Boost bad_lexical_cast.
Definition: Utils.h:39
N sqr(const N &x)
Convenience function for squaring (of any type)
Definition: Utils.h:217
bool endswith(const std::string &s, const std::string &sub)
Does a string s end with the sub substring?
Definition: Utils.h:120
std::string to_lower(const std::string &s)
Convert a string to lower-case (not in-place)
Definition: Utils.h:138
std::string dirname(const std::string &p)
Get the dirname (i.e. path to the penultimate directory) from a path p.
Definition: Utils.h:190
double chisquared_quantile(double p, double ndf)
Quantiles of the chi-squared probability distribution function.
Namespace for all LHAPDF functions and classes.
Definition: AlphaS.h:14
int in_range(double x, double low, double high)
Check if a number is in a range (closed-open)
Definition: Utils.h:224
bool contains(const std::string &s, const std::string &sub)
Does a string s contain the sub substring?
Definition: Utils.h:110
std::string file_stem(const std::string &f)
Get the stem (i.e. part without a file extension) from a filename f.
Definition: Utils.h:196
bool dir_exists(const std::string &p)
Check if a dir p exists.
Definition: Utils.h:170
bool has_key(const std::map< K, T > &container, const K &key)
Does the map<K,T> container have a key K key?
Definition: Utils.h:260
std::string to_upper(const std::string &s)
Convert a string to upper-case (not in-place)
Definition: Utils.h:145
std::string trim(const std::string &s)
Strip leading and trailing spaces (not in-place)
Definition: Utils.h:130
std::string operator/(const std::string &a, const std::string &b)
Operator for joining strings a and b with filesystem separators.
Definition: Utils.h:176
double norm_quantile(double p)
Quantiles of the standard normal probability distribution function.
std::string file_extn(const std::string &f)
Get the file extension from a filename f.
Definition: Utils.h:202
bool path_exists(const std::string &p)
Check if a path p (either file or dir) exists.
Definition: Utils.h:158