Jpp
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
JFitToT.cc
Go to the documentation of this file.
1 #include <string>
2 #include <iostream>
3 #include <iomanip>
4 
5 #include "TROOT.h"
6 #include "TFile.h"
7 #include "TH1D.h"
8 #include "TH2D.h"
9 #include "TF1.h"
10 #include "TFitResult.h"
11 #include "TMath.h"
12 
13 #include "JLang/JLangToolkit.hh"
14 #include "JPhysics/JConstants.hh"
16 
17 #include "JDetector/JDetector.hh"
21 
22 #include "JROOT/JRootToolkit.hh"
23 #include "JTools/JRange.hh"
24 #include "JSupport/JMeta.hh"
25 
27 #include "JCalibrate/JFitToT.hh"
28 
29 #include "Jeep/JPrint.hh"
30 #include "Jeep/JParser.hh"
31 #include "Jeep/JMessage.hh"
32 
33 namespace {
34 
35  /**
36  * Wild card for histogram naming.\n
37  * The wild card will replaced by the module identifier.
38  */
39  static const char* const WILDCARD = "%";
40 }
41 
42 
43 /**
44  * \file
45  *
46  * Auxiliary program to fit time-over-threshold distributions.
47  * The fitted parameters are the PMT gain and gain spread.
48  * \author mkarel
49  */
50 int main(int argc, char **argv)
51 {
52  using namespace std;
53  using namespace JPP;
54  using namespace KM3NETDAQ;
55 
56  typedef JRange<double> JRange_t;
57 
58  string inputFile;
59  string outputFile;
60  string detectorFile;
61  string pmtFile;
62  bool writeFits;
63 
64  double Wmin = 5e3; //!< Minimal histogram weight in fit range
65  double LeftMargin = 10.0; //!< Fit range left of time-over-threshold peak
66  double RightMargin = 10.0; //!< Fit range right of time-over-threshold peak
67  double gradientThreshold = -0.005; //!< Minimal right-to-left gradient value in time-over-threshold peak-search, normalized with respect to the total number of histogram entries
68 
69  JRange_t fitRange;
70  string option;
71 
72  string regexp;
73  int debug;
74 
75  try {
76 
77  JProperties properties;
78 
79  properties.insert(gmake_property(Wmin));
80  properties.insert(gmake_property(LeftMargin));
81  properties.insert(gmake_property(RightMargin));
82 
83  properties.insert(gmake_property(gradientThreshold));
84 
85 
86  JParser<> zap("Auxiliary program to fit time-over-threshold distributions.");
87 
88  zap['f'] = make_field(inputFile, "input file (output from JCalibrateToT).");
89  zap['o'] = make_field(outputFile, "output file.") = "fit.root";
90  zap['a'] = make_field(detectorFile, "detector file.");
91  zap['P'] = make_field(pmtFile, "specify PMT file name that can be given to JTriggerEfficiency.") = "";
92  zap['w'] = make_field(writeFits, "write fit results.");
93  zap['O'] = make_field(option, "ROOT fit options, see TH1::Fit") = "";
94  zap['@'] = make_field(properties) = JPARSER::initialised();
95  zap['x'] = make_field(fitRange, "ROOT fit range (time-over-threshold).") = JRange_t(0.0, 35.0);
96  zap['R'] = make_field(regexp, "regular expression for histogram name.") = MAKE_CSTRING(WILDCARD << _2SToT);
97  zap['d'] = make_field(debug, "debug.") = 1;
98 
99  zap(argc, argv);
100  }
101  catch(const exception &error) {
102  FATAL(error.what() << endl);
103  }
104 
105 
106  //----------------------------------------------------------
107  // load detector file and PMT parameters
108  //----------------------------------------------------------
109 
111 
112  try {
113  load(detectorFile, detector);
114  }
115  catch(const JException& error) {
116  FATAL(error);
117  }
118 
119 
121 
122  if (pmtFile != "") {
123  try {
124  parameters.load(pmtFile.c_str());
125  }
126  catch(const JException& error) {}
127  }
128 
129  parameters.comment.add(JMeta(argc, argv));
130 
131  // Set ROOT fit options
132  if (option.find('R') == string::npos) { option += 'R'; }
133  if (option.find('S') == string::npos) { option += 'S'; }
134  if (option.find('Q') == string::npos && debug < JEEP::debug_t) { option += 'Q'; }
135 
136 
137  TFile* in = TFile::Open(inputFile.c_str(), "exist");
138 
139  if (in == NULL || !in->IsOpen()) {
140  FATAL("File: " << inputFile << " not opened." << endl);
141  }
142 
143 
144  TH2D gain("gain", NULL,
145  100, 0.0, 2.0,
146  100, 0.0, 1.0);
147  TH1D chi2("chi2", NULL, 100, 0.0, 5.0);
148 
149 
150  TFile out(outputFile.c_str(), "recreate");
151 
152  //----------------------------------------------------------
153  // loop over modules in detector file to fit histogram
154  //----------------------------------------------------------
155 
156  for (JDetector::iterator module = detector.begin(); module != detector.end(); ++module) {
157 
158  NOTICE("Module " << setw(10) << module->getID() << ' ' << module->getLocation() << endl);
159 
160  if (module->empty()) {
161  continue;
162  }
163 
164  //----------------------------------------------------------
165  // get histogram for this module
166  //----------------------------------------------------------
167 
168  TH2D* h2s = (TH2D*) in->Get(replace(regexp, WILDCARD, MAKE_STRING(module->getID())).c_str());
169 
170  if (h2s == NULL) {
171 
172  WARNING("No histogram " << module->getID() << "; skip fit." << endl);
173 
174  continue;
175  }
176 
177  const double ny = h2s->GetYaxis()->GetNbins();
178  const double ymin = h2s->GetYaxis()->GetXmin();
179  const double ymax = h2s->GetYaxis()->GetXmax();
180 
181  TH1D chi2_1d (MAKE_CSTRING(module->getID() << ".1chi2"), NULL, NUMBER_OF_PMTS, -0.5, NUMBER_OF_PMTS-0.5);
182  TH1D gain_1d (MAKE_CSTRING(module->getID() << ".1gain"), NULL, NUMBER_OF_PMTS, -0.5, NUMBER_OF_PMTS-0.5);
183  TH1D gainspread_1d(MAKE_CSTRING(module->getID() << ".1gainspread"), NULL, NUMBER_OF_PMTS, -0.5, NUMBER_OF_PMTS-0.5);
184 
185  for (int ix = 1; ix <= h2s->GetXaxis()->GetNbins(); ++ix) {
186 
187  const JPMTIdentifier id(module->getID(), ix-1);
188 
189  parameters[id].setPMTParameters(parameters.getDefaultPMTParameters());
190 
191  const string name = MAKE_STRING(module->getID() << FITTOT_SEPARATOR << FILL(2, '0') <<
192  id.getPMTAddress() << FITTOT_SEPARATOR << FITTOT_SUFFIX);
193  TH1D h1(name.c_str(), NULL, ny, ymin, ymax);
194 
195  h1.Sumw2();
196 
197  for (int iy = h2s->GetNbinsY(); iy >= 1; --iy) {
198 
199  const double w = h1.GetBinWidth (iy);
200  const double y = h2s->GetBinContent(ix, iy);
201 
202  h1.SetBinContent(iy, y/w);
203  h1.SetBinError (iy, sqrt(y)/w);
204  }
205 
206  const double weight = h1.Integral(h1.FindBin(fitRange.getLowerLimit()),
207  h1.FindBin(fitRange.getUpperLimit()));
208 
209  if (weight <= Wmin) {
210 
211  WARNING("Insufficient histogram entries for PMT " << id <<
212  "(" << weight << " < " << Wmin << "); skip fit." << endl);
213 
214  if (writeFits) {
215  out << h1;
216  }
217 
218  continue;
219  }
220 
221  //----------------------------------------------------------
222  // find the mode of the time-over-threshold distribution
223  //----------------------------------------------------------
224 
225  double ToTmode = JDETECTOR::TIME_OVER_THRESHOLD_NS;
226  double max = 0.0;
227 
228  for (int i = h1.GetBinCenter(ny-1);
229  i > h1.GetBinCenter(h1.FindBin(parameters[id].mean_ns + parameters[id].sigma_ns));
230  --i) {
231 
232  const double x = h1.GetBinCenter (i);
233  const double y = h1.GetBinContent(i);
234 
235  const double gradient = ( (h1.GetBinContent(i-1) - h1.GetBinContent(i+1)) /
236  (h1.GetBinCenter (i+1) - h1.GetBinCenter (i-1)) );
237 
238  if (y > max) {
239 
240  ToTmode = x;
241  max = y;
242 
243  } else if (gradient < -fabs(gradientThreshold) * h1.Integral()) {
244 
245  break;
246  }
247  }
248 
249  //----------------------------------------------------------
250  // set fit range
251  //----------------------------------------------------------
252 
253  if (!fitRange.is_valid()) {
254  fitRange.setRange(ToTmode - LeftMargin,
255  ToTmode + RightMargin);
256  }
257 
258  fitRange.setRange(std::max(h1.GetXaxis()->GetXmin(), fitRange.getLowerLimit()),
259  std::min(h1.GetXaxis()->GetXmax(), fitRange.getUpperLimit()));
260 
261  //----------------------------------------------------------
262  // perform minimum chi-square fit
263  //----------------------------------------------------------
264 
265  JFitToT fit(parameters[id], fitRange);
266 
267  const double initGain = fit.getCPU().getNPE(ToTmode);
268  const double initGainSpread = initGain / 3.0;
269 
270  if (initGain > FITTOT_GAIN_MAX || initGain < FITTOT_GAIN_MIN) { // Invalid initial gain value
271 
272  WARNING("Invalid initial gain for PMT " << id << "; set default values." << endl);
273 
274  parameters[id].gain = (initGain > FITTOT_GAIN_MAX ? FITTOT_GAIN_MAX : FITTOT_GAIN_MIN);
275  parameters[id].gainSpread = (initGain > FITTOT_GAIN_MAX ? FITTOT_GAINSPREAD_MAX : FITTOT_GAINSPREAD_MIN);
276 
277  if (writeFits) {
278  out << h1;
279  }
280 
281  continue;
282  }
283 
284  fit.gain = initGain;
285  fit.gainSpread = initGainSpread;
286 
287  const TFitResultPtr result = fit(h1, option);
288 
289  if (int(result) < 0 || !result->IsValid()) { // Fit failed
290 
291  WARNING("Fit failure for PMT " << id << "; set initialization values." << endl);
292 
293  h1.GetListOfFunctions()->Clear();
294 
295  parameters[id].gain = initGain;
296  parameters[id].gainSpread = initGainSpread;
297 
298  if (writeFits) {
299  out << h1;
300  }
301 
302  continue;
303  }
304 
305  if ((ymin < fitRange.getLowerLimit() || ymax > fitRange.getUpperLimit()) &&
306  (option.find("0") == string::npos && option.find("N") == string::npos)) {
307 
308  // add function with full range
309 
310  TF1* f1 = new TF1(MAKE_CSTRING(FITTOT_FNAME << "_fullRange"),
311  &fit,
313  ymin,
314  ymax,
315  JFitToT::getNumberOfModelParameters());
316  f1->SetParameters(fit.GetParameters());
317  f1->SetLineStyle(kDotted);
318  f1->SetNpx(1000);
319 
320  h1.GetListOfFunctions()->Add(f1);
321  }
322 
323  // store fit results
324 
325  const double reducedChi2 = result->Chi2() / result->Ndf();
326 
327  const JFitToTParameters values(fit.GetParameters());
328  const JFitToTParameters errors(fit.GetParErrors());
329 
330  chi2_1d. SetBinContent(ix, reducedChi2);
331  gain_1d. SetBinContent(ix, values.gain);
332  gain_1d. SetBinError (ix, errors.gain);
333  gainspread_1d.SetBinContent(ix, values.gainSpread);
334  gainspread_1d.SetBinError (ix, errors.gainSpread);
335 
336  gain.Fill(fit.gain, fit.gainSpread);
337  chi2.Fill(TMath::Log10(reducedChi2));
338 
339  NOTICE("PMT " << id << " chi2 / NDF " << result->Chi2() << ' ' << result->Ndf() << endl);
340 
341  parameters[id].gain = fit.gain;
342  parameters[id].gainSpread = fit.gainSpread;
343 
344  if (writeFits) {
345  out << h1;
346  }
347  }
348 
349  if (writeFits) {
350  out << chi2_1d << gain_1d << gainspread_1d;
351  }
352  }
353 
354  if (pmtFile != "") {
355  parameters.store(pmtFile.c_str());
356  }
357 
358  out << gain << chi2;
359 
360  out.Write();
361  out.Close();
362 }
363 
364 
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
General exception.
Definition: JException.hh:23
data_type w[N+1][M+1]
Definition: JPolint.hh:741
#define WARNING(A)
Definition: JMessage.hh:65
double getValue(const JScale_t scale)
Get numerical value corresponding to scale.
Definition: JScale.hh:47
debug
Definition: JMessage.hh:29
TString replace(const TString &target, const TRegexp &regexp, const T &replacement)
Replace regular expression in input by given replacement.
Definition: JPrintResult.cc:63
#define gmake_property(A)
macro to convert (template) parameter to JPropertiesElement object
static const double FITTOT_GAIN_MAX
Default maximal gain.
Definition: JFitToT.hh:41
Detector data structure.
Definition: JDetector.hh:80
Double_t gainSpread
PMT gain spread.
Definition: JFitToT.hh:166
const double TIME_OVER_THRESHOLD_NS
Specification for time-over-threshold corresponding to a one photo-electron pulse.
static const double FITTOT_GAIN_MIN
Default minimal gain.
Definition: JFitToT.hh:40
Utility class to parse parameter values.
Definition: JProperties.hh:496
*fatal Wrong number of arguments esac JCookie sh typeset Z DETECTOR typeset Z SOURCE_RUN typeset Z TARGET_RUN set_variable PARAMETERS_FILE $WORKDIR parameters
Definition: diff-Tuna.sh:38
#define MAKE_CSTRING(A)
Make C-string.
Definition: JPrint.hh:151
then for HISTOGRAM in h0 h1
Definition: JMatrixNZ.sh:69
Empty structure for specification of parser element that is initialised (i.e. does not require input)...
Definition: JParser.hh:66
string outputFile
Parametrisation of time-over-threshold distribution.
Definition: JFitToT.hh:176
Data structure for detector geometry and calibration.
Fit parameters for two-fold coincidence rate due to K40.
Definition: JFitToT.hh:50
#define MAKE_STRING(A)
Make string.
Definition: JPrint.hh:142
const JPMTAnalogueSignalProcessor & getCPU() const
Access method for the analogue signal processor.
Definition: JFitToT.hh:207
static const std::string FITTOT_SUFFIX
Definition: JFitToT.hh:37
I/O formatting auxiliaries.
Detector file.
Definition: JHead.hh:196
static const char FITTOT_SEPARATOR
Definition: JFitToT.hh:36
static const double FITTOT_GAINSPREAD_MAX
Default maximal gain spread.
Definition: JFitToT.hh:44
#define make_field(A,...)
macro to convert parameter to JParserTemplateElement object
Definition: JParser.hh:1961
return result
Definition: JPolint.hh:727
ROOT I/O of application specific meta data.
#define NOTICE(A)
Definition: JMessage.hh:64
Physics constants.
Auxiliary class for map of PMT parameters.
Double_t gain
PMT gain.
Definition: JFitToT.hh:165
int debug
debug level
Definition: JSirene.cc:63
General purpose messaging.
Auxiliary data structure for sequence of same character.
Definition: JManip.hh:327
#define FATAL(A)
Definition: JMessage.hh:67
then echo n User name
Definition: JCookie.sh:45
then $JPP_DIR examples JDetector JToT o $OUTPUT_FILE n N $NPE P gain
Definition: JToT.sh:45
virtual double getNPE(const double tot_ns, const double eps=1.0e-3) const
Get number of photo-electrons.
void load(const std::string &file_name, JDetector &detector)
Load detector from input file.
Auxiliary class to define a range between two values.
Utility class to parse command line options.
static const char *const _2SToT
Histogram naming.
PMT analogue signal processor.
static const double FITTOT_GAINSPREAD_MIN
Default minimal gain spread.
Definition: JFitToT.hh:43
possible values
do set_variable DETECTOR_TXT $WORKDIR detector
KM3NeT DAQ constants, bit handling, etc.
static const int NUMBER_OF_PMTS
Total number of PMTs in module.
Definition: JDAQ.hh:26
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 typeset A TRIPODS get_tripods $WORKDIR tripod txt TRIPODS for EMITTER in
Definition: JCanberra.sh:36
static const std::string FITTOT_FNAME
Definition: JFitToT.hh:38
std::vector< double > weight
Definition: JAlgorithm.hh:428
int main(int argc, char *argv[])
Definition: Main.cpp:15