REST-for-Physics  v2.3
Rare Event Searches ToolKit for Physics
TRestTools.h
1/*************************************************************************
2 * This file is part of the REST software framework. *
3 * *
4 * Copyright (C) 2016 GIFNA/TREX (University of Zaragoza) *
5 * For more information see http://gifna.unizar.es/trex *
6 * *
7 * REST is free software: you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation, either version 3 of the License, or *
10 * (at your option) any later version. *
11 * *
12 * REST is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU General Public License for more details. *
16 * *
17 * You should have a copy of the GNU General Public License along with *
18 * REST in $REST_PATH/LICENSE. *
19 * If not, see http://www.gnu.org/licenses/. *
20 * For the list of contributors see $REST_PATH/CREDITS. *
21 *************************************************************************/
22
23#ifndef RestCore_TRestTools
24#define RestCore_TRestTools
25
26#include <TObject.h>
27#include <TString.h>
28#include <TVector3.h>
29
30#include <map>
31#include <memory>
32#include <set>
33#include <string>
34#include <vector>
35
36#define UNUSED(x) (void)x
37
38#ifdef WIN32
39#define EXTERN_DEF __declspec(dllimport)
40#define EXTERN_IMP __declspec(dllexport)
41#else
42#define EXTERN_DEF extern
43#define EXTERN_IMP
44#endif
45
46#ifndef WIN32
47#include <unistd.h>
48#endif
49
50const std::string PARAMETER_NOT_FOUND_STR = "NO_SUCH_PARA";
51const double PARAMETER_NOT_FOUND_DBL = -99999999;
52
53EXTERN_DEF std::string REST_COMMIT;
54EXTERN_DEF std::string REST_PATH;
55EXTERN_DEF std::string REST_USER;
56EXTERN_DEF std::string REST_USER_PATH;
57EXTERN_DEF std::string REST_TMP_PATH;
58EXTERN_DEF std::map<std::string, std::string> REST_ARGS;
59
60class TFile;
61class TRestTools;
62
63enum class TRestRootFileMode { Read, Recreate, Update };
64
72 private:
73 friend class TRestTools;
74
75 std::unique_ptr<TFile> fFile;
76 std::string fError;
77
78 public:
79 TRestRootFileHandle() = default;
80 static TRestRootFileHandle Open(const std::string& filename, TRestRootFileMode mode);
81
83 TRestRootFileHandle& operator=(const TRestRootFileHandle&) = delete;
85 TRestRootFileHandle& operator=(TRestRootFileHandle&& other) noexcept;
87
88 explicit operator bool() const noexcept { return fFile != nullptr; }
90 TFile* Get() const noexcept { return fFile.get(); }
91 TFile* operator->() const noexcept { return fFile.get(); }
92 TFile& operator*() const noexcept { return *fFile; }
93 const std::string& Error() const noexcept { return fError; }
94
97 bool Close() noexcept;
98
102 static bool PrepareBorrowedUpdate(TFile& file, std::string* error = nullptr);
103};
104
107 public:
108 static std::vector<std::string> GetOptions(std::string optionsStr);
109
110 static void LoadRESTLibrary(bool silent = false);
111
112 static int ReadASCIITable(std::string fName, std::vector<std::vector<Double_t>>& data,
113 Int_t skipLines = 0, std::string separator = "\t");
114 static int ReadASCIITable(std::string fName, std::vector<std::vector<Float_t>>& data, Int_t skipLines = 0,
115 std::string separator = "\t");
116 static int ReadASCIITable(std::string fName, std::vector<std::vector<std::string>>& data,
117 Int_t skipLines = 0, std::string separator = "\t");
118
119 static int ReadCSVFile(std::string fName, std::vector<std::vector<Double_t>>& data, Int_t skipLines = 0);
120 static int ReadCSVFile(std::string fName, std::vector<std::vector<Float_t>>& data, Int_t skipLines = 0);
121
122 template <typename T>
123 static void TransposeTable(std::vector<std::vector<T>>& data);
124
125 template <typename T>
126 static int ReadBinaryTable(std::string fName, std::vector<std::vector<T>>& data, Int_t columns = -1);
127
128 static Bool_t IsBinaryFile(std::string fname);
129
130 static std::string GetFileNameExtension(const std::string& fullname);
131 static std::string GetFileNameRoot(const std::string& fullname);
132 static std::vector<std::string> GetObservablesInString(const std::string& observablesStr,
133 bool removeDuplicates = true);
134 static std::set<std::string> GetMatchingStrings(const std::vector<std::string>& stack,
135 const std::vector<std::string>& wantedStrings);
136
137 static int GetBinaryFileColumns(std::string fname);
138
139 template <typename T>
140 static T GetMaxValueFromTable(const std::vector<std::vector<T>>& data, Int_t column = -1);
141
142 template <typename T>
143 static T GetMinValueFromTable(const std::vector<std::vector<T>>& data, Int_t column = -1);
144
145 template <typename T>
146 static T GetLowestIncreaseFromTable(std::vector<std::vector<T>> data, Int_t column);
147
148 template <typename T>
149 static T GetIntegralFromTable(const std::vector<std::vector<T>>& data);
150
151 template <typename T>
152 static std::vector<T> GetColumnFromTable(const std::vector<std::vector<T>>& data, unsigned int column);
153
154 template <typename T>
155 static int PrintTable(std::vector<std::vector<T>> data, Int_t start = 0, Int_t end = 0);
156
157 template <typename T>
158 static int ExportASCIITable(std::string fname, std::vector<std::vector<T>>& data);
159
160 template <typename T>
161 static int ExportBinaryTable(std::string fname, std::vector<std::vector<T>>& data);
162
163 static Int_t isValidFile(const std::string& path);
164 static bool fileExists(const std::string& filename);
165 static bool isRootFile(const std::string& filename);
166 static bool isRunFile(const std::string& filename);
167 static bool isDataSet(const std::string& filename);
168 static bool isURL(const std::string& filename);
169 static bool IsRemoteRootPath(const std::string& filename);
170
180 static bool MergeRootFilesTransactionally(const std::string& outputFile,
181 const std::vector<std::string>& inputFiles,
182 const std::string& existingTarget = "",
183 bool removeInputsOnSuccess = true,
184 std::string* error = nullptr);
185
186#ifdef REST_TESTING_ENABLED
189 static void ForceNextRootUpdatePreflightFailureForTesting();
190
193 static void ForceNextTransactionalMergeValidationFailureForTesting();
194#endif
195
196 static bool isPathWritable(const std::string& path);
197 static bool isAbsolutePath(const std::string& path);
198 static std::string RemoveMultipleSlash(std::string);
199 static std::string ToAbsoluteName(const std::string& filename);
200 static std::vector<std::string> GetSubdirectories(const std::string& path, int recursion = -1);
201 static std::pair<std::string, std::string> SeparatePathAndName(const std::string& fullname);
202 static std::string GetPureFileName(const std::string& fullPathFileName);
203 static std::string SearchFileInPath(std::vector<std::string> path, std::string filename);
204 static bool CheckFileIsAccessible(const std::string&);
205 static std::vector<std::string> GetFilesMatchingPattern(std::string pattern, bool unlimited = false);
206 static int ConvertVersionCode(std::string in);
207 static std::istream& GetLine(std::istream& is, std::string& t);
208
209 static std::string Execute(std::string cmd);
210
211 static std::string DownloadRemoteFile(const std::string& remoteFile, bool pidPrefix = false);
212 static int DownloadRemoteFile(std::string remoteFile, std::string localFile);
213 static int UploadToServer(std::string localFile, std::string remoteFile, std::string methodUrl = "");
214
215 static std::string POSTRequest(const std::string& url, const std::map<std::string, std::string>& keys);
216 static void ChangeDirectory(const std::string& toDirectory);
217
218 static std::vector<int> CanvasDivisions(int n);
219};
220
221namespace REST_InitTools {
222
223template <class T>
225 static int level;
226};
227template <class T>
229
230template <class T>
231inline bool CanOverwrite(T* name, int level) {
232 if (level > GlobalVarInit<T>::level) {
233 return true;
234 }
235 return false;
236}
237
238template <class T>
239inline void SetInitLevel(T* name, int level) {
240 GlobalVarInit<T>::level = level;
241}
242
243// Initialize global variable with certain class, overwriting the dummy variable of its base class.
244// For example, we initialize gDataBase as TRestDataBase in Framework
245// library. When we load restP3DB library, this object will be overwritten
246// by a new TRestDataBaseP3DB class object, by calling this macro
247#define MakeGlobal(classname, objName, level) \
248 struct __##classname##_Init { \
249 __##classname##_Init() { \
250 REST_ARGS[#objName] = #classname; \
251 if ((objName) != nullptr) { \
252 if (REST_InitTools::CanOverwrite(objName, level)) { \
253 delete (objName); \
254 (objName) = new classname(); \
255 REST_InitTools::SetInitLevel(objName, level); \
256 } \
257 } else { \
258 (objName) = new classname(); \
259 REST_InitTools::SetInitLevel(objName, level); \
260 } \
261 } \
262 }; \
263 const __##classname##_Init classname##_Init;
264
265} // namespace REST_InitTools
266
267enum Quantities { ENERGY, LENGTH, TIME };
269 public:
270 ValueWithQuantity(double value, Quantities quantity) : fValue(value), fQuantity(quantity){};
271 double GetValue() const { return fValue; }
272 std::string ToString() const;
273
274 inline operator std::string() const { return ToString(); }
275
276 private:
277 const double fValue;
278 const Quantities fQuantity;
279};
280
281inline std::string ToEnergyString(double value) { return (std::string)ValueWithQuantity(value, ENERGY); }
282inline std::string ToTimeString(double value) { return (std::string)ValueWithQuantity(value, TIME); }
283inline std::string ToLengthString(double value) { return (std::string)ValueWithQuantity(value, LENGTH); }
284
285std::string ToTimeStringLong(double value);
286
287inline std::string VectorToString(const TVector3& v) {
288 return TString::Format("(%0.3f, %0.3f, %0.3f)", v.X(), v.Y(), v.Z()).Data();
289}
290
291inline std::string VectorToString(const TVector2& v) {
292 return TString::Format("(%0.3f, %0.3f)", v.X(), v.Y()).Data();
293}
294
295#endif
bool Close() noexcept
Definition: TRestTools.cxx:662
TFile * Get() const noexcept
Borrow the file without transferring ownership; do not delete or outlive the handle.
Definition: TRestTools.h:90
static TRestRootFileHandle Open(const std::string &filename, TRestRootFileMode mode)
Definition: TRestTools.cxx:597
static bool PrepareBorrowedUpdate(TFile &file, std::string *error=nullptr)
Definition: TRestTools.cxx:678
A generic class with useful static methods.
Definition: TRestTools.h:106
static std::string Execute(std::string cmd)
Executes a shell command and returns its output in a string.
static std::pair< std::string, std::string > SeparatePathAndName(const std::string &fullname)
Separate path and filename in a full path+filename string, returns a pair of string.
static Int_t isValidFile(const std::string &path)
Returns true if the file with path filename exists.
static bool IsRemoteRootPath(const std::string &filename)
Returns true when ROOT resolves filename to a non-local protocol.
static std::string GetFileNameExtension(const std::string &fullname)
Gets the file extension as the substring found after the latest ".".
static std::string POSTRequest(const std::string &url, const std::map< std::string, std::string > &keys)
It performs a POST web protocol request using a set of keys and values given by argument,...
static std::vector< std::string > GetSubdirectories(const std::string &path, int recursion=-1)
It lists all the subdirectories inside path and adds them to the result vector.
static int ReadASCIITable(std::string fName, std::vector< std::vector< Double_t > > &data, Int_t skipLines=0, std::string separator="\t")
Reads an ASCII file containing a table with values.
static bool CheckFileIsAccessible(const std::string &)
Checks if the config file can be opened (and thus exists). It returns true in case of success,...
static std::string GetPureFileName(const std::string &fullPathFileName)
Removes all directories in the full path filename description given in the argument.
static int ReadBinaryTable(std::string fName, std::vector< std::vector< T > > &data, Int_t columns=-1)
Reads a binary file containing a fixed-columns table with values.
Definition: TRestTools.cxx:887
static int GetBinaryFileColumns(std::string fname)
It extracts the number of columns from the filename extension given by argument. The file should cont...
Definition: TRestTools.cxx:949
static std::vector< std::string > GetOptions(std::string optionsStr)
Returns all the options in an option string.
Definition: TRestTools.cxx:720
static int PrintTable(std::vector< std::vector< T > > data, Int_t start=0, Int_t end=0)
Prints the contents of the vector table given as argument in screen. Allowed types are Int_t,...
Definition: TRestTools.cxx:797
static std::string GetFileNameRoot(const std::string &fullname)
Gets the filename root as the substring found before the latest ".".
static T GetMaxValueFromTable(const std::vector< std::vector< T > > &data, Int_t column=-1)
It returns the maximum value for a particular column from the table given by argument....
static T GetLowestIncreaseFromTable(std::vector< std::vector< T > > data, Int_t column)
It returns the lowest increase, different from zero, between the elements of a particular column from...
static void LoadRESTLibrary(bool silent=false)
Calls gSystem to load REST library.
Definition: TRestTools.cxx:729
static int ReadCSVFile(std::string fName, std::vector< std::vector< Double_t > > &data, Int_t skipLines=0)
Reads a CSV file containing a table with comma separated values.
static bool isRunFile(const std::string &filename)
It checks if the file has been processed using a REST event processing chain.
static int ExportASCIITable(std::string fname, std::vector< std::vector< T > > &data)
Writes the contents of the vector table given as argument to fname. Allowed types are Int_t,...
Definition: TRestTools.cxx:819
static bool fileExists(const std::string &filename)
Returns true if the file (or directory) with path filename exists.
static std::set< std::string > GetMatchingStrings(const std::vector< std::string > &stack, const std::vector< std::string > &wantedStrings)
Returns a set of strings that match the wanted strings from the stack. The wanted strings can contain...
static std::vector< int > CanvasDivisions(int n)
It returns a vector with 2 components {a,b}, the components satisfy that a x b = n,...
static std::string DownloadRemoteFile(const std::string &remoteFile, bool pidPrefix=false)
download the remote file automatically, returns the downloaded file name.
static T GetMinValueFromTable(const std::vector< std::vector< T > > &data, Int_t column=-1)
It returns the minimum value for a particular column from the table given by argument....
static std::vector< std::string > GetFilesMatchingPattern(std::string pattern, bool unlimited=false)
Returns a list of files whose name match the pattern string. Key word is "*". e.g....
static int ConvertVersionCode(std::string in)
Convert version to a unique string.
static bool isPathWritable(const std::string &path)
Returns true if the path given by argument is writable.
static T GetIntegralFromTable(const std::vector< std::vector< T > > &data)
It returns the lowest increase, different from zero, between the elements of a particular column from...
static bool isAbsolutePath(const std::string &path)
Check if the path is absolute path or not.
static int ExportBinaryTable(std::string fname, std::vector< std::vector< T > > &data)
Writes the contents of the vector table given as argument to fname as a binary file....
Definition: TRestTools.cxx:848
static Bool_t IsBinaryFile(std::string fname)
It identifies if the filename extension follows the formatting ".Nxyzf", where the number of columns ...
Definition: TRestTools.cxx:937
static std::string RemoveMultipleSlash(std::string)
Returns the input string but without multiple slashes ("/")
static bool isDataSet(const std::string &filename)
It checks if the file contains a dataset object.
static bool isURL(const std::string &filename)
Returns true if filename is an http address.
static std::istream & GetLine(std::istream &is, std::string &t)
It reads the next line from the incoming istream and puts it in the string argument t....
static std::vector< std::string > GetObservablesInString(const std::string &observablesStr, bool removeDuplicates=true)
Returns a vector with the observables names found in the input string. The observables names must con...
static int UploadToServer(std::string localFile, std::string remoteFile, std::string methodUrl="")
static bool isRootFile(const std::string &filename)
Returns true if the filename has *.root* extension.
static std::string SearchFileInPath(std::vector< std::string > path, std::string filename)
Search file in the given vector of path strings, return a full name if found, return "" if not.
static void TransposeTable(std::vector< std::vector< T > > &data)
It transposes the std::vector<std::vector> table given in the argument. It will transform rows in col...
Definition: TRestTools.cxx:979
static std::vector< T > GetColumnFromTable(const std::vector< std::vector< T > > &data, unsigned int column)
It returns a vector with the values extracted from the particular column inside the data table given ...
static bool MergeRootFilesTransactionally(const std::string &outputFile, const std::vector< std::string > &inputFiles, const std::string &existingTarget="", bool removeInputsOnSuccess=true, std::string *error=nullptr)
Merge REST worker outputs using a validated candidate and rollback backup.
static std::string ToAbsoluteName(const std::string &filename)
It takes a path and returns its absolute path.