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