Jpp - the software that should make you happy
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
JTuneHV.cc
Go to the documentation of this file.
1 
2 #include <string>
3 #include <map>
4 #include <fstream>
5 #include <sstream>
6 
7 #include "JSystem/JDate.hh"
8 
9 #include "JLang/JUUID.hh"
10 
11 #include "Jeep/JPrint.hh"
12 #include "Jeep/JParser.hh"
13 #include "Jeep/JMessage.hh"
14 
15 #include "JTools/JRange.hh"
16 
17 #include "JSupport/JMeta.hh"
19 
20 #include "JDetector/JDetector.hh"
24 
25 #include "JDB/JUPI.hh"
26 #include "JDB/JUPI_t.hh"
27 #include "JDB/JDBSupportkit.hh"
28 
29 #include "JCalibrate/JFitToT.hh"
31 
32 #include "JROOT/JManager.hh"
33 
34 #include "JSon/JSon.hh"
35 
36 #include "TFile.h"
37 
38 namespace {
39 
40  /**
41  * Auxiliary class for creating a PMT-UPI look-up table from ASCII DB file.
42  */
43  struct JUPITable
44  {
45  /**
46  * Initialise
47  *
48  * \param fileName file name
49  */
50  JUPITable(const char* const fileName)
51  {
52  using namespace std;
53  using namespace JPP;
54 
55  ifstream in(fileName);
56 
57  for (string buffer; getline(in, buffer); ) {
58 
59  istringstream is(buffer);
60 
61  JUPI entry;
62 
63  if (is >> entry.PBS >> entry.VARIANT >> entry.VERSION >> entry.SERIALNUMBER) {
64 
65  if (entry.PBS.is_valid() &&
66  entry.PBS == PBS::PMT &&
67  entry.SERIALNUMBER >= 0) {
68 
69  number2upi[entry.PBS][entry.SERIALNUMBER] = JUPI_t(entry.PBS,
70  entry.VARIANT,
71  entry.VERSION,
72  entry.SERIALNUMBER);
73  }
74  }
75  }
76 
77  in.close();
78  }
79 
80 
81  /**
82  * Get %UPI.
83  *
84  * \param pbs %PBS
85  * \param number serial number
86  * \return %UPI
87  */
88  JDATABASE::JUPI_t operator()(const JDATABASE::JPBS_t& pbs, const int number)
89  {
90  using namespace std;
91  using namespace JPP;
92 
93  map<JPBS_t, map<int, JUPI_t>>::const_iterator p = number2upi.find(pbs);
94 
95  if (p != number2upi.end()) {
96 
97  map<int, JUPI_t>::const_iterator q = p->second.find(number);
98 
99  if (q != p->second.end()) {
100 
101  return q->second;
102 
103  } else {
104 
105  THROW(JValueOutOfRange, "Invalid serial number " << number);
106  }
107 
108  } else {
109 
110  THROW(JValueOutOfRange, "Invalid PBS " << pbs);
111  }
112  }
113 
114  protected:
116  };
117 }
118 
119 
120 /**
121  * \file
122  *
123  * Program for inter-/extrapolation of nominal high-voltage settings.
124  * \author acreusot, mdejong and bjung
125  */
126 int main(int argc, char **argv)
127 {
128  using namespace std;
129  using namespace JPP;
130 
131  string inputFile;
132  string detectorFile;
133  string outputFile;
134  string UPIFile;
135 
136  JDBAPIVersion APIversion;
137  string testType;
138  string login;
139  string locationID;
140  vector<int> runNumbers;
141  int elapsedTime = 0;
142 
143  double HVstepMin = 2 * 3.14; //!< Minimal HV step [V]
144  JRange<double> HVrange (-1500 + 1e-2,
145  -80 - 1e-2); //!< Allowed HV range [V]
146  JRange<double> gainRange(FITTOT_GAIN_MIN + 1e-2,
147  FITTOT_GAIN_MAX - 1e-2); //!< Allowed gain fit-range
148  double gainTarget = NOMINAL_GAIN; //!< Target nominal gain value
149 
150  int debug;
151 
152 
153  try {
154 
155  JProperties properties;
156 
157  properties.insert(gmake_property(APIversion));
158  properties.insert(gmake_property(testType));
159  properties.insert(gmake_property(login));
160  properties.insert(gmake_property(locationID));
161  properties.insert(gmake_property(runNumbers));
162  properties.insert(gmake_property(elapsedTime));
163 
164  JProperties settings;
165 
166  settings.insert(gmake_property(HVstepMin));
167  settings.insert(gmake_property(HVrange));
168  settings.insert(gmake_property(gainRange));
169  settings.insert(gmake_property(gainTarget));
170 
171  JParser<> zap("Example program to find optimal HV-settings.");
172 
173  zap['f'] = make_field(inputFile, "input file (ROOT format)");
174  zap['o'] = make_field(outputFile, "output file (json format)");
175  zap['a'] = make_field(detectorFile, "detector file");
176  zap['b'] = make_field(UPIFile, "PMT UPI ASCII table");
177  zap['#'] = make_field(properties, "database information") = JPARSER::initialised();
178  zap['@'] = make_field(settings, "interpolation settings") = JPARSER::initialised();
179  zap['d'] = make_field(debug, "debug") = 1;
180 
181  zap(argc, argv);
182  }
183  catch(const exception &error) {
184  FATAL(error.what() << endl);
185  }
186 
187  if (login.empty() || locationID.empty()) {
188 
189  FATAL("Missing user information (please specify via -#login and -#locationID).");
190 
191  } else if (!APIversion.is_valid()) {
192 
193  FATAL("Invalid database API version " << APIversion);
194 
195  } else if (testType.empty()) {
196 
197  FATAL("Missing database test type (please specify via -#testType).");
198 
199  } else if (getDBVersionTuneHV(testType) < 3 && runNumbers.empty()) {
200 
201  FATAL("Missing run numbers.");
202  }
203 
204 
205  JHVCalibration_t::setVersion(getDBVersionTuneHV(testType));
206 
207  const JUUID& UUID = JUUID::rndm();
208 
209  JDateAndTimeFormat format = ISO8601;
210  JDateAndTime timer;
211 
212  timer->tm_sec -= elapsedTime;
213 
215 
216  try {
217  load(detectorFile, detector);
218  }
219  catch (const exception& error) {
220  FATAL(error.what() << endl);
221  }
222 
223  JModuleRouter router (detector);
224 
225  JUPITable fetchUPI(UPIFile.c_str());
226 
227 
228  // Read input
229 
230  TFile input(inputFile.c_str(), "READ");
231 
232  JManager<string, TMultiGraph> manager(new TMultiGraph(), "%.HVxG");
233 
234  input >> manager;
235 
236  input.Close();
237 
238 
239  // Find optimal HV corresponding to a nominal gain of 1.0
240  // via linear interpolation in log-log scale
241 
242  JHVCalibration HVcalibrations;
243 
244  JHVInterpolator::setMinHVDistance(HVstepMin);
245  JHVInterpolator::setHVRange (HVrange);
246  JHVInterpolator::setGainRange (gainRange);
247 
248  NOTICE("Searching optimal high-voltage settings..." << endl <<
249  LEFT(30) << "UPI" << CENTER(35) << "(identifer / location)" << RIGHT(35) << "Inter-/Extrapolated high-voltage [-]" << endl);
250 
251  for (JManager<string, TMultiGraph>::iterator it = manager.begin(); it != manager.end(); ++it) {
252 
253  const string& name = it->first;
254  JHVInterpolator data(*(it->second));
255 
256  // Retrieve upi, location and serialID
257 
258  const int seppos = name.find('.');
259  const int moduleID = stoi(name.substr(0, seppos));
260  const int tdc = stoi(name.substr(seppos + 1, seppos + 3));
261 
262  const JModule& module = router.getModule(moduleID);
263  const JPMT& pmt = router.getPMT(JPMTIdentifier(moduleID, tdc));
264 
265  const JUPI_t& pmtUPI = fetchUPI(PBS::PMT, pmt.getID());
266  const string location = MAKE_STRING(right << FILL(4,'0') << module.getLocation().getString() << '.' <<
267  right << FILL(2,'0') << module.getLocation().getFloor() << '.' <<
268  right << FILL(2,'0') << tdc);
269 
270  NOTICE(LEFT(30) << pmtUPI << "(a.k.a. " << name << " / " << location << "): ");
271 
272  if (data.interpolate(gainTarget)) {
273 
274  const double result = -data.getTargetHV (gainTarget);
275  const double error = data.getTargetHVError(gainTarget);
276 
277  NOTICE(right << FIXED(20,2) << result << " +/- " << FIXED(4,2) << error << endl);
278 
279  HVcalibrations.push_back(JHVCalibration_t(pmtUPI, OK_t, result, runNumbers, gainTarget));
280 
281  } else {
282 
283  WARNING("Could not find high-voltage corresponding to target gain; Setting zero." << endl);
284 
285  HVcalibrations.push_back(JHVCalibration_t(pmtUPI, Failed_t, 0.0, runNumbers, 0.0));
286  }
287  }
288 
289  // Update graphical output
290 
291  vector<JMeta> metaInfo;
292  string metaInfoStr;
293 
294  metaInfo.push_back(JMeta(argc, argv));
295  metaInfoStr += MAKE_STRING(metaInfo.back());
296 
297  for (JSingleFileScanner<JMeta> in(inputFile); in.hasNext(); ) {
298 
299  metaInfo.push_back(*in.next());
300  metaInfoStr += MAKE_STRING(metaInfo.back());
301  }
302 
303  TFile output(inputFile.c_str(), "RECREATE");
304 
305  for (vector<JMeta>::iterator i = metaInfo.begin(); i != metaInfo.end(); ++i) {
306  putObject(&output, *i);
307  }
308 
309  output << manager;
310 
311  output.Close();
312 
313  // Write json output
314 
315  json js;
316 
317  if (APIversion.getMajorVersion() == 2) {
318 
319  json error = { {Message_t, "" },
320  {Code_t, OK_t },
321  {Arguments_t, json::array() } };
322 
323  json metaData = { {Configuration_t, metaInfoStr },
324  {UUID_t, MAKE_STRING(UUID) } };
325 
326  json data = { {Provenance_t + Info_t, json(metaData) },
327  {User_t, login },
328  {Location_t, locationID },
329  {Start_t + Time_t, timer.toString (format)},
330  {End_t + Time_t, timer().toString(format)},
331  {Test_t + Type_t, testType },
332  {Tests_t, json(HVcalibrations) } };
333 
334  js[APIVersion_t] = MAKE_STRING(APIversion);
335  js[Data_t + Type_t] = MAKE_STRING("ProductTestSession");
336  js[Encoding_t] = MAKE_STRING("NativeJSON");
337  js[Error_t] = json(error);
338  js[Start_t] = timer.toString(format);
339  js[End_t] = timer().toString(format);
340  js[Data_t][0] = json(data);
341 
342  } else {
343 
344  js[User_t] = login;
345  js[Location_t] = locationID;
346  js[Test_t + Type_t] = testType;
347  js[Start_t + Time_t] = timer.toString(format);
348  js[End_t + Time_t] = timer().toString(format);
349  js[Tests_t] = json(HVcalibrations);
350  }
351 
352  ofstream ofs(outputFile.c_str());
353 
354  ofs << setw(2) << setprecision(8);
355  ofs << js;
356 
357  ofs.close();
358 }
static JDBTestTypesTuneHV & getDBVersionTuneHV
Function object for looking up the HV-tuning database version number corresponding to a specific test...
Auxiliary class for ROOT I/O of application specific meta data.
Definition: JMeta.hh:70
Utility class to parse command line options.
Definition: JParser.hh:1500
static const std::string UUID_t
#define WARNING(A)
Definition: JMessage.hh:65
int main(int argc, char *argv[])
Definition: Main.cc:15
double getTargetHVError(const double gainTarget)
Get error estimate on high-voltage corresponding to given target gain value.
const JModule & getModule(const JObjectID &id) const
Get module parameters.
Data structure for a composite optical module.
Definition: JModule.hh:57
static const std::string Failed_t
static const std::string Time_t
#define gmake_property(A)
macro to convert (template) parameter to JPropertiesElement object
static const std::string Tests_t
static const JPBS_t PMT(3, 4, 2, 3)
PBS of photo-multiplier tube (PMT)
static const std::string OK_t
static const double FITTOT_GAIN_MAX
Default maximal gain.
Definition: JFitToT.hh:44
Detector data structure.
Definition: JDetector.hh:80
static const double FITTOT_GAIN_MIN
Default minimal gain.
Definition: JFitToT.hh:43
Router for direct addressing of module data in detector data structure.
#define THROW(JException_t, A)
Marco for throwing exception with std::ostream compatible message.
Definition: JException.hh:670
Utility class to parse parameter values.
Definition: JProperties.hh:496
static const std::string Location_t
Empty structure for specification of parser element that is initialised (i.e. does not require input)...
Definition: JParser.hh:66
JDateAndTimeFormat
Date and time formats.
Universal product identifier (UPI).
Definition: JUPI_t.hh:29
double getTargetHV(const double gainTarget)
Get high-voltage corresponding to given target gain value.
Dynamic ROOT object management.
Auxiliary data structure for floating point format specification.
Definition: JManip.hh:446
string outputFile
is
Definition: JDAQCHSM.chsm:167
static const std::string Encoding_t
Data structure for detector geometry and calibration.
#define MAKE_STRING(A)
Make string.
Definition: JPrint.hh:142
static const std::string Provenance_t
Date and time functions.
Auxiliary data structure for alignment of data.
Definition: JManip.hh:366
Scanning of objects from a single file according a format that follows from the extension of each fil...
static const std::string Arguments_t
Auxiliary class to manage set of compatible ROOT objects (e.g. histograms) using unique keys...
Definition: JManager.hh:43
int SERIALNUMBER
Definition: JUPI.hh:27
static const std::string Configuration_t
I/O formatting auxiliaries.
Detector file.
Definition: JHead.hh:196
bool interpolate(const double gainTarget)
Inter-/Extrapolate the high-voltage value corresponding to the target gain value. ...
Auxiliary data structure to store high-voltage versus gain data and interpolate the nominal high-volt...
#define make_field(A,...)
macro to convert parameter to JParserTemplateElement object
Definition: JParser.hh:1961
Auxiliary data structure for I/O of database API versions.
return result
Definition: JPolint.hh:727
int getID() const
Get identifier.
Definition: JObjectID.hh:50
Data structure for PMT geometry and calibration.
Definition: JPMT.hh:47
ROOT I/O of application specific meta data.
#define NOTICE(A)
Definition: JMessage.hh:64
std::istream & getline(std::istream &in, JString &object)
Read string from input stream until end of line.
Definition: JString.hh:478
static const std::string Code_t
static const std::string Test_t
ISO-8601 standard.
static const std::string Info_t
bool is_valid() const
Check validity.
Definition: JPBS_t.hh:110
static const std::string Message_t
int debug
debug level
Definition: JSirene.cc:63
const double NOMINAL_GAIN
Specification for normalized gain corresponding to a one photo-electron pulse.
General purpose messaging.
Auxiliary data structure for sequence of same character.
Definition: JManip.hh:328
#define FATAL(A)
Definition: JMessage.hh:67
const JPMT & getPMT(const JPMTIdentifier &id) const
Get PMT parameters.
Direct access to module in detector data structure.
then echo n User name
Definition: JCookie.sh:45
int VERSION
Definition: JUPI.hh:26
std::string VARIANT
Definition: JUPI.hh:25
void load(const std::string &file_name, JDetector &detector)
Load detector from input file.
Auxiliary class to define a range between two values.
Auxililary class to get date and time.
Utility class to parse command line options.
Simple wrapper for UUID.
Definition: JUUID.hh:22
Data structure for PMT high-voltage calibration.
nlohmann::json json
static const std::string Type_t
static const std::string APIVersion_t
Product breakdown structure (PBS).
Definition: JPBS_t.hh:25
static const std::string User_t
Detector calibration key words for JSON I/O.
Object reading from a list of files.
Exception for accessing a value in a collection that is outside of its range.
Definition: JException.hh:162
JPBS_t PBS
constraint
Definition: JUPI.hh:24
static const std::string Error_t
do set_variable DETECTOR_TXT $WORKDIR detector
then fatal Wrong number of arguments fi set_variable DETECTOR $argv[1] set_variable INPUT_FILE $argv[2] eval JPrintDetector a $DETECTOR O IDENTIFIER eval JPrintDetector a $DETECTOR O SUMMARY source JAcoustics sh $DETECTOR_ID CHECK_EXIT_CODE typeset A TRIPODS get_tripods $WORKDIR tripod txt TRIPODS for EMITTER in
Definition: JCanberra.sh:38
static const std::string Data_t
static const std::string End_t
static const std::string Start_t
bool putObject(TDirectory *dir, const T &object)
Write object to ROOT directory.