lhapdf is hosted by Hepforge, IPPP Durham
LHAPDF  6.2.3
Utils.h
1 // -*- C++ -*-
2 //
3 // This file is part of LHAPDF
4 // Copyright (C) 2012-2019 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 <stdexcept>
13 #include <vector>
14 #include <map>
15 #include <string>
16 #include <algorithm>
17 #include <memory>
18 #include <iostream>
19 #include <iomanip>
20 #include <sstream>
21 #include <limits>
22 #include <cmath>
23 
24 
26 namespace LHAPDF {
27 
28 
29  // Allow implicit use of the std namespace within namespace LHAPDF
30  using namespace std;
31 
32 
34 
35 
37  struct bad_lexical_cast : public std::runtime_error {
38  bad_lexical_cast(const std::string& what) : std::runtime_error(what) {}
39  };
40 
42  template<typename T, typename U>
43  T lexical_cast(const U& in) {
44  try {
45  std::stringstream ss;
46  ss << in;
47  T out;
48  ss >> out;
49  return out;
50  } catch (const std::exception& e) {
51  throw bad_lexical_cast(e.what());
52  }
53  }
54 
56  template <typename T>
57  inline std::string to_str(const T& val) {
58  return lexical_cast<string>(val);
59  }
60 
62  template <typename T>
63  inline std::string to_str(const std::vector<T>& vec) {
64  string rtn = "[";
65  for (size_t i = 0; i < vec.size(); ++i) {
66  rtn += to_str(vec[i]);
67  if (i < vec.size()-1) rtn += ", ";
68  }
69  rtn += "]";
70  return rtn;
71  }
72 
74  inline std::string to_str_zeropad(int val, size_t nchars=4) {
75  stringstream ss;
76  ss << setfill('0') << setw(nchars) << val;
77  return ss.str();
78  }
79 
81  inline std::string join(const std::vector<std::string>& svec, const std::string& sep) {
82  string rtn;
83  for (size_t i = 0; i < svec.size(); ++i) {
84  rtn += svec[i];
85  if (i < svec.size()-1) rtn += sep;
86  }
87  return rtn;
88  }
89 
91  inline std::vector<std::string> split(const std::string& s, const std::string& sep) {
92  vector<string> rtn;
93  string tmp = s; // non-const working copy, to be incrementally truncated
94  while (true) {
95  const size_t delim_pos = tmp.find(sep);
96  if (delim_pos == string::npos) break;
97  const string s = tmp.substr(0, delim_pos);
98  if (!s.empty()) rtn.push_back(s); // Don't insert "empties"
99  tmp.replace(0, delim_pos+1, ""); // Remove already-processed part
100  }
101  if (!tmp.empty()) rtn.push_back(tmp); // Don't forget the trailing component!
102  return rtn;
103  }
104 
106  inline bool contains(const std::string& s, const std::string& sub) {
107  return s.find(sub) != string::npos;
108  }
109 
111  inline bool startswith(const std::string& s, const std::string& sub) {
112  return s.find(sub) == 0;
113  }
114 
116  inline bool endswith(const std::string& s, const std::string& sub) {
117  return s.find(sub) == s.length()-sub.length();
118  }
119 
121  inline size_t countchar(const std::string& s, const char c) {
122  return std::count(s.begin(), s.end(), c);
123  }
124 
126  inline std::string trim(const std::string& s) {
127  const size_t firstnonspacepos = s.find_first_not_of(" ");
128  const size_t lastnonspacepos = s.find_last_not_of(" ");
129  if (firstnonspacepos == std::string::npos) return "";
130  return s.substr(firstnonspacepos, lastnonspacepos-firstnonspacepos+1);
131  }
132 
134  inline std::string to_lower(const std::string& s) {
135  string rtn = s;
136  transform(rtn.begin(), rtn.end(), rtn.begin(), (int(*)(int)) tolower);
137  return rtn;
138  }
139 
141  inline std::string to_upper(const std::string& s) {
142  string rtn = s;
143  transform(rtn.begin(), rtn.end(), rtn.begin(), (int(*)(int)) toupper);
144  return rtn;
145  }
146 
148 
149 
151 
152 
154  bool path_exists(const std::string& p,int mode=0);
155 
157  bool file_exists(const std::string& p,int mode=0);
158 
160  bool dir_exists(const std::string& p,int mode=0);
161 
163  inline std::string operator / (const std::string& a, const std::string& b) {
164  // Ensure that a doesn't end with a slash, and b doesn't start with one, to avoid "//"
165  const string anorm = (a.find("/") != std::string::npos) ? a.substr(0, a.find_last_not_of("/")+1) : a;
166  const string bnorm = (b.find("/") != std::string::npos) ? b.substr(b.find_first_not_of("/")) : b;
167  return anorm + "/" + bnorm;
168  }
169 
171  inline std::string basename(const std::string& p) {
172  if (!contains(p, "/")) return p;
173  return p.substr(p.rfind("/")+1);
174  }
175 
177  inline std::string dirname(const std::string& p) {
178  if (!contains(p, "/")) return "";
179  return p.substr(0, p.rfind("/"));
180  }
181 
183  inline std::string file_stem(const std::string& f) {
184  if (!contains(f, ".")) return f;
185  return f.substr(0, f.rfind("."));
186  }
187 
189  inline std::string file_extn(const std::string& f) {
190  if (!contains(f, ".")) return "";
191  return f.substr(f.rfind(".")+1);
192  }
193 
195 
197 
198 
200 
201 
203  template <typename N>
204  inline N sqr(const N& x) { return x*x; }
205 
207  template <typename N>
208  inline int sgn(N val) { return (N(0) < val) - (val < N(0)); }
209 
211  inline int in_range(double x, double low, double high) { return x >= low && x < high; }
212 
214  inline int in_closed_range(double x, double low, double high) { return x >= low && x <= high; }
215 
217  inline int in_open_range(double x, double low, double high) { return x > low && x < high; }
218 
220 
222  double norm_quantile(double p);
223 
225  double chisquared_quantile(double p, double ndf);
226 
228 
229 
231 
232 
234  template <typename T>
235  inline bool contains(const std::vector<T>& container, const T& item) {
236  return find(container.begin(), container.end(), item) != container.end();
237  }
238 
239  // /// Does the set<T> @a container contain @a item?
240  // template <typename T>
241  // inline bool contains(const std::set<T>& container, const T& item) {
242  // return container.find(item) != container.end();
243  // }
244 
246  template <typename K, typename T>
247  inline bool has_key(const std::map<K,T>& container, const K& key) {
248  return container.find(key) != container.end();
249  }
250 
251  // /// @name Implementation of generic begin/end container identification by traits
252  // /// taken from http://stackoverflow.com/a/9407420/91808 . Needs C++11 (or maybe just C++0x).
253  // //@{
254 
255  // #include <type_traits>
256 
257  // template<typename T>
258  // struct has_const_iterator {
259  // private:
260  // typedef char yes;
261  // typedef struct { char array[2]; } no;
262  // template<typename C> static yes test(typename C::const_iterator*);
263  // template<typename C> static no test(...);
264  // public:
265  // static const bool value = sizeof(test<T>(0)) == sizeof(yes);
266  // typedef T type;
267  // };
268 
269  // template <typename T>
270  // struct has_begin_end {
271  // template<typename C> static char (&f(typename std::enable_if<
272  // std::is_same<decltype(static_cast<typename C::const_iterator (C::*)() const>(&C::begin)),
273  // typename C::const_iterator(C::*)() const>::value, void>::type*))[1];
274 
275  // template<typename C> static char (&f(...))[2];
276 
277  // template<typename C> static char (&g(typename std::enable_if<
278  // std::is_same<decltype(static_cast<typename C::const_iterator (C::*)() const>(&C::end)),
279  // typename C::const_iterator(C::*)() const>::value, void>::type*))[1];
280 
281  // template<typename C> static char (&g(...))[2];
282 
283  // static bool const beg_value = sizeof(f<T>(0)) == 1;
284  // static bool const end_value = sizeof(g<T>(0)) == 1;
285  // };
286 
287  // template<typename T>
288  // struct is_container
289  // : std::integral_constant<bool, has_const_iterator<T>::value &&
290  // has_begin_end<T>::beg_value && has_begin_end<T>::end_value>
291  // { };
292 
294 
295 
296 }
297 #endif
int in_open_range(double x, double low, double high)
Check if a number is in a range (open-open)
Definition: Utils.h:217
std::string to_str(const T &val)
Make a string representation of val.
Definition: Utils.h:57
size_t countchar(const std::string &s, const char c)
How many times does a string s contain the character c?
Definition: Utils.h:121
int sgn(N val)
Get the sign of a number.
Definition: Utils.h:208
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:74
std::vector< std::string > split(const std::string &s, const std::string &sep)
Split a string by a given separator.
Definition: Utils.h:91
STL namespace.
bool startswith(const std::string &s, const std::string &sub)
Does a string s start with the sub substring?
Definition: Utils.h:111
bool file_exists(const std::string &p, int mode=0)
Check if a file p exists.
T lexical_cast(const U &in)
Convert between any types via stringstream.
Definition: Utils.h:43
std::string basename(const std::string &p)
Get the basename (i.e. terminal file name) from a path p.
Definition: Utils.h:171
bool path_exists(const std::string &p, int mode=0)
Check if a path p (either file or dir) exists.
std::string join(const std::vector< std::string > &svec, const std::string &sep)
Concatenate strings with separator strings between each element.
Definition: Utils.h:81
int in_closed_range(double x, double low, double high)
Check if a number is in a range (closed-closed)
Definition: Utils.h:214
When lexical_cast goes bad.
Definition: Utils.h:37
N sqr(const N &x)
Convenience function for squaring (of any type)
Definition: Utils.h:204
bool endswith(const std::string &s, const std::string &sub)
Does a string s end with the sub substring?
Definition: Utils.h:116
std::string to_lower(const std::string &s)
Convert a string to lower-case (not in-place)
Definition: Utils.h:134
std::string dirname(const std::string &p)
Get the dirname (i.e. path to the penultimate directory) from a path p.
Definition: Utils.h:177
bool dir_exists(const std::string &p, int mode=0)
Check if a dir p exists.
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:211
bool contains(const std::string &s, const std::string &sub)
Does a string s contain the sub substring?
Definition: Utils.h:106
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:183
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:247
std::string to_upper(const std::string &s)
Convert a string to upper-case (not in-place)
Definition: Utils.h:141
std::string trim(const std::string &s)
Strip leading and trailing spaces (not in-place)
Definition: Utils.h:126
std::string operator/(const std::string &a, const std::string &b)
Operator for joining strings a and b with filesystem separators.
Definition: Utils.h:163
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:189