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