Jpp  18.6.0-rc.1
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 
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 (testType.empty()) {
192 
193  FATAL("Missing database test type (please specify via -#testType).");
194 
195  } else if (getDBVersionTuneHV(testType) < 3 && runNumbers.empty()) {
196 
197  FATAL("Missing run numbers.");
198  }
199 
200 
201  JHVCalibration_t::setVersion(getDBVersionTuneHV(testType));
202 
203  const JUUID& UUID = JUUID::rndm();
204 
205  JDateAndTime timer;
206 
207  timer.sub(elapsedTime);
208 
210 
211  try {
212  load(detectorFile, detector);
213  }
214  catch (const exception& error) {
215  FATAL(error.what() << endl);
216  }
217 
218  JModuleRouter router (detector);
219 
220  JUPITable fetchUPI(UPIFile.c_str());
221 
222 
223  // Read input
224 
225  TFile input(inputFile.c_str(), "READ");
226 
227  JManager<string, TMultiGraph> manager(new TMultiGraph(), "%.HVxG");
228 
229  input >> manager;
230 
231  input.Close();
232 
233 
234  // Find optimal HV corresponding to a nominal gain of 1.0
235  // via linear interpolation in log-log scale
236 
237  JHVCalibration HVcalibrations;
238 
239  JHVInterpolator::setMinHVDistance(HVstepMin);
240  JHVInterpolator::setHVRange (HVrange);
241  JHVInterpolator::setGainRange (gainRange);
242 
243  NOTICE("Searching optimal high-voltage settings..." << endl <<
244  LEFT(30) << "UPI" << CENTER(35) << "(identifer / location)" << RIGHT(35) << "Inter-/Extrapolated high-voltage [-]" << endl);
245 
246  for (JManager<string, TMultiGraph>::iterator it = manager.begin(); it != manager.end(); ++it) {
247 
248  const string& name = it->first;
249  JHVInterpolator data(*(it->second));
250 
251  // Retrieve upi, location and serialID
252 
253  const int seppos = name.find('.');
254  const int moduleID = stoi(name.substr(0, seppos));
255  const int tdc = stoi(name.substr(seppos + 1, seppos + 3));
256 
257  const JModule& module = router.getModule(moduleID);
258  const JPMT& pmt = router.getPMT(JPMTIdentifier(moduleID, tdc));
259 
260  const JUPI_t& pmtUPI = fetchUPI(PBS::PMT, pmt.getID());
261  const string location = MAKE_STRING(right << FILL(4,'0') << module.getLocation().getString() << '.' <<
262  right << FILL(2,'0') << module.getLocation().getFloor() << '.' <<
263  right << FILL(2,'0') << tdc);
264 
265  NOTICE(LEFT(30) << pmtUPI << "(a.k.a. " << name << " / " << location << "): ");
266 
267  if (data.interpolateHV(gainTarget)) {
268 
269  const double result = -data.getHV ();
270  const double error = data.getHVError();
271 
272  NOTICE(right << FIXED(20,2) << result << " +/- " << FIXED(4,2) << error << endl);
273 
274  HVcalibrations.push_back(JHVCalibration_t(pmtUPI, OK_t, result, runNumbers, gainTarget));
275 
276  } else {
277 
278  WARNING("Could not find high-voltage corresponding to target gain; Setting zero." << endl);
279 
280  HVcalibrations.push_back(JHVCalibration_t(pmtUPI, Fail_t, 0.0, runNumbers, 0.0));
281  }
282  }
283 
284  // Update graphical output
285 
286  vector<JMeta> metaInfo;
287  string metaInfoStr;
288 
289  metaInfo.push_back(JMeta(argc, argv));
290  metaInfoStr += MAKE_STRING(metaInfo.back());
291 
292  for (JSingleFileScanner<JMeta> in(inputFile); in.hasNext(); ) {
293 
294  metaInfo.push_back(*in.next());
295  metaInfoStr += MAKE_STRING(metaInfo.back());
296  }
297 
298  TFile output(inputFile.c_str(), "RECREATE");
299 
300  for (vector<JMeta>::iterator i = metaInfo.begin(); i != metaInfo.end(); ++i) {
301  putObject(output, *i);
302  }
303 
304  output << manager;
305 
306  output.Close();
307 
308  // Write json output
309 
310  json js;
311 
312  if (APIversion.getMajorVersion() == 2) {
313 
314  json error = { {Message_t, "" },
315  {Code_t, OK_t },
316  {Arguments_t, json::array() } };
317 
318  json metaData = { {Configuration_t, metaInfoStr },
319  {UUID_t, MAKE_STRING(UUID) } };
320 
321  json data = { {Provenance_t + Info_t, json(metaData) },
322  {User_t, login },
323  {Location_t, locationID },
324  {Start_t + Time_t, timer.toString() },
325  {End_t + Time_t, timer().toString() },
326  {Test_t + Type_t, testType },
327  {Tests_t, json(HVcalibrations) } };
328 
329  js[APIVersion_t] = MAKE_STRING(APIversion);
330  js[Data_t + Type_t] = MAKE_STRING("ProductTestSession");
331  js[Encoding_t] = MAKE_STRING("NativeJSON");
332  js[Error_t] = json(error);
333  js[Start_t] = timer.toString();
334  js[End_t] = timer().toString();
335  js[Data_t][0] = json(data);
336 
337  } else if (APIversion.getMajorVersion() == 1) {
338 
339  js[User_t] = login;
340  js[Location_t] = locationID;
341  js[Test_t + Type_t] = testType;
342  js[Start_t + Time_t] = timer.toString();
343  js[End_t + Time_t] = timer().toString();
344  js[Tests_t] = json(HVcalibrations);
345 
346  } else {
347 
348  FATAL("Invalid API version <" << APIversion << "> accepted major versions 1 and 2." << endl);
349  }
350 
351  ofstream ofs(outputFile.c_str());
352 
353  ofs << setw(2) << setprecision(8);
354  ofs << js;
355 
356  ofs.close();
357 }
static JDBTestTypesTuneHV & getDBVersionTuneHV
Function object for looking up the HV-tuning database version number corresponding to a specific test...
static const std::string Arguments_t
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:1711
static const std::string Start_t
#define WARNING(A)
Definition: JMessage.hh:65
static const std::string Location_t
int main(int argc, char *argv[])
Definition: Main.cc:15
static const std::string Code_t
const JModule & getModule(const JObjectID &id) const
Get module parameters.
Data structure for a composite optical module.
Definition: JModule.hh:67
static const std::string Encoding_t
#define gmake_property(A)
macros to convert (template) parameter to JPropertiesElement object
static const JPBS_t PMT(3, 4, 2, 3)
PBS of photo-multiplier tube (PMT)
static const double FITTOT_GAIN_MAX
Default maximal gain.
Definition: JFitToT.hh:45
Detector data structure.
Definition: JDetector.hh:89
static const double FITTOT_GAIN_MIN
Default minimal gain.
Definition: JFitToT.hh:44
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:712
static const std::string Error_t
Utility class to parse parameter values.
Definition: JProperties.hh:497
Empty structure for specification of parser element that is initialised (i.e. does not require input)...
Definition: JParser.hh:84
Universal product identifier (UPI).
Definition: JUPI_t.hh:30
Dynamic ROOT object management.
Auxiliary data structure for floating point format specification.
Definition: JManip.hh:446
string outputFile
is
Definition: JDAQCHSM.chsm:167
Data structure for detector geometry and calibration.
void sub(const time_t t1)
Subtract given time.
Date and time functions.
#define MAKE_STRING(A)
Make string.
Definition: JPrint.hh:127
static const std::string Time_t
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 APIVersion_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
I/O formatting auxiliaries.
Detector file.
Definition: JHead.hh:226
static const std::string Configuration_t
Auxiliary data structure to store high-voltage versus gain data and interpolate the nominal high-volt...
static const std::string Test_t
#define make_field(A,...)
macro to convert parameter to JParserTemplateElement object
Definition: JParser.hh:2158
double getHV() const
Get interpolated high-voltage.
int getID() const
Get identifier.
Definition: JObjectID.hh:50
Data structure for PMT geometry, calibration and status.
Definition: JPMT.hh:43
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
bool is_valid() const
Check validity.
Definition: JPBS_t.hh:112
bool putObject(TDirectory &dir, const TObject &object)
Write object to ROOT directory.
static const std::string End_t
const double NOMINAL_GAIN
Specification for normalized gain corresponding to a one photo-electron pulse.
static const std::string Info_t
General purpose messaging.
Auxiliary data structure for sequence of same character.
Definition: JManip.hh:328
double getHVError() const
Get error estimate on interpolated high-voltage.
then fatal The output file must have the wildcard in the name
Definition: JCanberra.sh:31
static const std::string Message_t
#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.
int VERSION
Definition: JUPI.hh:26
std::string VARIANT
Definition: JUPI.hh:25
static const std::string Data_t
void load(const std::string &file_name, JDetector &detector)
Load detector from input file.
Auxiliary class to define a range between two values.
then fatal The output file must have the wildcard in the e g root fi eval JPrintDetector a $DETECTOR O IDENTIFIER eval JPrintDetector a $DETECTOR O SUMMARY JAcoustics sh $DETECTOR_ID source JAcousticsToolkit sh CHECK_EXIT_CODE typeset A EMITTERS get_tripods $WORKDIR tripod txt EMITTERS get_transmitters $WORKDIR transmitter txt EMITTERS for EMITTER in
Definition: JCanberra.sh:48
Auxiliary class for date and time.
Definition: JDateAndTime.hh:78
Utility class to parse command line options.
Simple wrapper for UUID.
Definition: JUUID.hh:22
Data structure for PMT high-voltage calibration.
Product breakdown structure (PBS).
Definition: JPBS_t.hh:27
static const std::string Type_t
Object reading from a list of files.
Exception for accessing a value in a collection that is outside of its range.
Definition: JException.hh:178
static const std::string Provenance_t
JPBS_t PBS
constraint
Definition: JUPI.hh:24
do set_variable DETECTOR_TXT $WORKDIR detector
Auxiliary data structure for general purpose version number.
static const std::string UUID_t
static const std::string Tests_t
int debug
debug level
static const std::string OK_t
static const std::string Fail_t
nlohmann::json json
static const std::string User_t
bool interpolateHV(const double gainTarget)
Inter-/Extrapolate the high-voltage value corresponding to the target gain value. ...