CMS 3D CMS Logo

ZIterativeAlgorithmWithFit.cc
Go to the documentation of this file.
1 /* ******************************************
2  * ZIterativeAlgorithmWithFit.cc
3  *
4  *
5  * Paolo Meridiani 06/07/2005
6  * Rewritten for CMSSW 04/06/2007
7  ********************************************/
8 
12 
16 
17 #include <TMath.h>
18 #include <TCanvas.h>
19 #include "TH1.h"
20 #include "TH2.h"
21 #include "TF1.h"
22 #include "TH1F.h"
23 #include "TMinuit.h"
24 #include "TGraphErrors.h"
25 #include "THStack.h"
26 #include "TLegend.h"
27 
28 #include <fstream>
29 #include <iostream>
30 #include <vector>
31 
32 //#include "Tools.C"
33 
34 //Scale and Bins for calibration factor histograms
35 #define MIN_RESCALE -0.5
36 #define MAX_RESCALE 0.5
37 #define NBINS_LOWETA 100
38 #define NBINS_HIGHETA 50
39 
40 const double ZIterativeAlgorithmWithFit::M_Z_ = 91.187;
41 
42 // #if !defined(__CINT__)
43 // ClassImp(Electron)
44 // #endif
45 
47  // std::cout<< "ZIterativeAlgorithmWithFit::Called Construnctor" << std::endl;
49  channels_ = 1;
50  totalEvents_ = 0;
51  currentEvent_ = 0;
57  calib_fac_.resize(channels_);
58  weight_sum_.resize(channels_);
59  electrons_.resize(1);
60  massReco_.resize(1);
61 }
62 
64 //k, unsigned int events)
65 {
66  //std::cout<< "ZIterativeAlgorithmWithFit::Called Constructor" << std::endl;
67  numberOfIterations_ = ps.getUntrackedParameter<unsigned int>("maxLoops", 0);
68  massMethod = ps.getUntrackedParameter<std::string>("ZCalib_InvMass", "SCMass");
69  calibType_ = ps.getUntrackedParameter<std::string>("ZCalib_CalibType", "RING");
70 
71  if (calibType_ == "RING")
73  else if (calibType_ == "MODULE")
74 
76  else if (calibType_ == "ABS_SCALE")
77  channels_ = 1;
78  else if (calibType_ == "ETA_ET_MODE")
80 
81  std::cout << "[ZIterativeAlgorithmWithFit::ZIterativeAlgorithmWithFit] channels_ = " << channels_ << std::endl;
82 
83  nCrystalCut_ = ps.getUntrackedParameter<int>("ZCalib_nCrystalCut", -1);
84 
85  //Resetting currentEvent & iteration
86  currentEvent_ = 0;
88  totalEvents_ = 0;
89 
94  calib_fac_.resize(channels_);
95  weight_sum_.resize(channels_);
96 
97  //Creating and booking histograms
100 
101  //Setting up rescaling if needed
102  UseStatWeights_ = ps.getUntrackedParameter<bool>("ZCalib_UseStatWeights", false);
103  if (UseStatWeights_) {
104  WeightFileName_ = "weights.txt";
105  StatWeights_.resize(channels_);
107  // Event_Weight_.resize(events);
108  }
109 }
110 
112  if (!thePlots_)
113  return;
114 
115  for (unsigned int i2 = 0; i2 < numberOfIterations_; i2++) {
116  for (unsigned int i1 = 0; i1 < channels_; i1++) {
117  char histoName[200];
118  char histoTitle[200];
119 
120  //WeightedRescaling factor
121  sprintf(histoName, "WeightedRescaleFactor_channel_%d_Iteration_%d", i1, i2);
122  sprintf(histoTitle, "WeightedRescaleFactor Channel_%d Iteration %d", i1, i2);
123  if (i1 > 15 && i1 < 155)
125  new TH1F(histoName, histoTitle, NBINS_LOWETA, MIN_RESCALE, MAX_RESCALE);
126  else
128  new TH1F(histoName, histoTitle, NBINS_HIGHETA, MIN_RESCALE, MAX_RESCALE);
129  thePlots_->weightedRescaleFactor[i2][i1]->GetXaxis()->SetTitle("Rescale factor");
130  thePlots_->weightedRescaleFactor[i2][i1]->GetYaxis()->SetTitle("a.u.");
131 
132  //UnweightedRescaling factor
133  sprintf(histoName, "UnweightedRescaleFactor_channel_%d_Iteration_%d", i1, i2);
134  sprintf(histoTitle, "UnweightedRescaleFactor Channel_%d Iteration %d", i1, i2);
135  if (i1 > 15 && i1 < 155)
137  new TH1F(histoName, histoTitle, NBINS_LOWETA, MIN_RESCALE, MAX_RESCALE);
138  else
140  new TH1F(histoName, histoTitle, NBINS_HIGHETA, MIN_RESCALE, MAX_RESCALE);
141  thePlots_->unweightedRescaleFactor[i2][i1]->GetXaxis()->SetTitle("Rescale factor");
142  thePlots_->unweightedRescaleFactor[i2][i1]->GetYaxis()->SetTitle("a.u.");
143 
144  //Weights
145  sprintf(histoName, "Weight_channel_%d_Iteration_%d", i1, i2);
146  sprintf(histoTitle, "Weight Channel_%d Iteration %d", i1, i2);
147  thePlots_->weight[i2][i1] = new TH1F(histoName, histoTitle, 100, 0., 1.);
148  thePlots_->weight[i2][i1]->GetXaxis()->SetTitle("Weight");
149  thePlots_->weight[i2][i1]->GetYaxis()->SetTitle("a.u.");
150  }
151  }
152 }
153 
155  std::ifstream statfile;
156  statfile.open(file.c_str());
157  if (!statfile) {
158  std::cout << "ZIterativeAlgorithmWithFit::FATAL: stat weight file " << file << " not found" << std::endl;
159  exit(-1);
160  }
161  for (unsigned int i = 0; i < channels_; i++) {
162  int imod;
163  statfile >> imod >> StatWeights_[i];
164  //std::cout << "Read Stat Weight for module " << imod << ": " << StatWeights_[i] << std::endl;
165  }
166 }
167 
169  totalEvents_ = 0;
170  currentEvent_ = 0;
171 
172  //Reset correction
173  massReco_.clear();
174  for (unsigned int i = 0; i < channels_; i++)
175  calib_fac_[i] = 0.;
176  for (unsigned int i = 0; i < channels_; i++)
177  weight_sum_[i] = 0.;
178 
179  return kTRUE;
180 }
181 
183  //Found optimized coefficients
184  for (int i = 0; i < (int)channels_; i++) {
185  //RP if (weight_sum_[i]!=0. && calib_fac_[i]!=0.) {
186  if ((nCrystalCut_ == -1) ||
187  ((!(i <= nCrystalCut_ - 1)) && !((i > (19 - nCrystalCut_)) && (i <= (19 + nCrystalCut_))) &&
188  !((i > (39 - nCrystalCut_)) && (i <= (39 + nCrystalCut_))) &&
189  !((i > (59 - nCrystalCut_)) && (i <= (59 + nCrystalCut_))) &&
190  !((i > (84 - nCrystalCut_)) && (i <= (84 + nCrystalCut_))) &&
191  !((i > (109 - nCrystalCut_)) && (i <= (109 + nCrystalCut_))) &&
192  !((i > (129 - nCrystalCut_)) && (i <= (129 + nCrystalCut_))) &&
193  !((i > (149 - nCrystalCut_)) && (i <= (149 + nCrystalCut_))) && !(i > (169 - nCrystalCut_)))) {
194  if (weight_sum_[i] != 0.) {
195  //optimizedCoefficients_[i] = calib_fac_[i]/weight_sum_[i];
196 
197  double gausFitParameters[3], gausFitParameterErrors[3], gausFitChi2;
198  int gausFitIterations;
199 
201  gausFitParameters,
202  gausFitParameterErrors,
203  2.5,
204  2.5,
205  &gausFitChi2,
206  &gausFitIterations);
207 
208  float peak = gausFitParameters[1];
209  float peakError = gausFitParameterErrors[1];
210  float chi2 = gausFitChi2;
211 
212  int iters = gausFitIterations;
213 
214  optimizedCoefficientsError_[i] = peakError;
216  optimizedIterations_[i] = iters;
217 
218  if (peak >= MIN_RESCALE && peak <= MAX_RESCALE)
219  optimizedCoefficients_[i] = 1 / (1 + peak);
220  else
222 
223  } else {
226  optimizedChiSquare_[i] = -1.;
227  optimizedIterations_[i] = 0;
228  }
229 
230  }
231 
232  else {
235  optimizedChiSquare_[i] = -1.;
236  optimizedIterations_[i] = 0;
237  // EcalCalibMap::getMap()->setRingCalib(i, optimizedCoefficients_[i]);
238  // // initialCoefficients_[i] *= optimizedCoefficients_[i];
239  }
240 
241  std::cout << "ZIterativeAlgorithmWithFit::run():Energy Rescaling Coefficient for region " << i << " is "
242  << optimizedCoefficients_[i] << ", with error " << optimizedCoefficientsError_[i]
243  << " - number of events: " << weight_sum_[i] << std::endl;
244  }
245 
247  return kTRUE;
248 }
249 
251  calib::CalibElectron* ele2,
252  float invMassRescFactor) {
253  totalEvents_++;
254  std::pair<calib::CalibElectron*, calib::CalibElectron*> Electrons(ele1, ele2);
255 #ifdef DEBUG
256  std::cout << "In addEvent ";
257  std::cout << ele1->getRecoElectron()->superCluster()->rawEnergy() << " ";
258  std::cout << ele1->getRecoElectron()->superCluster()->position().eta() << " ";
259  std::cout << ele2->getRecoElectron()->superCluster()->rawEnergy() << " ";
260  std::cout << ele2->getRecoElectron()->superCluster()->position().eta() << " ";
261  std::cout << std::endl;
262 #endif
263 
264  if (massMethod == "SCTRMass") {
265  massReco_.push_back(invMassCalc(ele1->getRecoElectron()->superCluster()->energy(),
266  ele1->getRecoElectron()->eta(),
267  ele1->getRecoElectron()->phi(),
268  ele2->getRecoElectron()->superCluster()->energy(),
269  ele2->getRecoElectron()->eta(),
270  ele2->getRecoElectron()->phi()));
271  }
272 
273  else if (massMethod == "SCMass") {
274  massReco_.push_back(invMassCalc(ele1->getRecoElectron()->superCluster()->energy(),
275  ele1->getRecoElectron()->superCluster()->position().eta(),
276  ele1->getRecoElectron()->superCluster()->position().phi(),
277  ele2->getRecoElectron()->superCluster()->energy(),
278  ele2->getRecoElectron()->superCluster()->position().eta(),
279  ele2->getRecoElectron()->superCluster()->position().phi()));
280  }
281 
282 #ifdef DEBUG
283  std::cout << "Mass calculated " << massReco_[currentEvent_] << std::endl;
284 #endif
285 
286  if ((ele2->getRecoElectron()->superCluster()->position().eta() > -10.) &&
287  (ele2->getRecoElectron()->superCluster()->position().eta() < 10.) &&
288  (ele2->getRecoElectron()->superCluster()->position().phi() > -10.) &&
289  (ele2->getRecoElectron()->superCluster()->position().phi() < 10.)) {
290  getWeight(currentEvent_, Electrons, invMassRescFactor);
291  }
292 
293  currentEvent_++;
294  return kTRUE;
295 }
296 
297 void ZIterativeAlgorithmWithFit::getWeight(unsigned int event_id,
298  std::pair<calib::CalibElectron*, calib::CalibElectron*> elepair,
299  float invMassRescFactor) {
300  getWeight(event_id, elepair.first, invMassRescFactor);
301  getWeight(event_id, elepair.second, invMassRescFactor);
302 }
303 
304 float ZIterativeAlgorithmWithFit::getEventWeight(unsigned int event_id) { return 1.; }
305 
306 void ZIterativeAlgorithmWithFit::getWeight(unsigned int event_id, calib::CalibElectron* ele, float evweight) {
307  // std::cout<< "getting weight for module " << module << " in electron " << ele << std::endl;
308 
309  std::vector<std::pair<int, float> > modules = (*ele).getCalibModulesWeights(calibType_);
310 
311  for (int imod = 0; imod < (int)modules.size(); imod++) {
312  int mod = (int)modules[imod].first;
313 
314  if (mod < (int)channels_ && mod >= 0) {
315  if (modules[imod].second >= 0.12 && modules[imod].second < 10000.) {
316  if ((nCrystalCut_ == -1) ||
317  ((!(mod <= nCrystalCut_ - 1)) && !((mod > (19 - nCrystalCut_)) && (mod <= (19 + nCrystalCut_))) &&
318  !((mod > (39 - nCrystalCut_)) && (mod <= (39 + nCrystalCut_))) &&
319  !((mod > (59 - nCrystalCut_)) && (mod <= (59 + nCrystalCut_))) &&
320  !((mod > (84 - nCrystalCut_)) && (mod <= (84 + nCrystalCut_))) &&
321  !((mod > (109 - nCrystalCut_)) && (mod <= (109 + nCrystalCut_))) &&
322  !((mod > (129 - nCrystalCut_)) && (mod <= (129 + nCrystalCut_))) &&
323  !((mod > (149 - nCrystalCut_)) && (mod <= (149 + nCrystalCut_))) && !(mod > (169 - nCrystalCut_)))) {
324  float weight2 = modules[imod].second / ele->getRecoElectron()->superCluster()->rawEnergy();
325 #ifdef DEBUG
326  std::cout << "w2 " << weight2 << std::endl;
327 #endif
328  if (weight2 >= 0. && weight2 <= 1.) {
329  float rescale = (TMath::Power((massReco_[event_id] / evweight), 2.) - 1) / 2.;
330 #ifdef DEBUG
331  std::cout << "rescale " << rescale << std::endl;
332 #endif
333  if (rescale >= MIN_RESCALE && rescale <= MAX_RESCALE) {
334  calib_fac_[mod] += weight2 * rescale;
335  weight_sum_[mod] += weight2;
336 
339  thePlots_->weight[currentIteration_][mod]->Fill(weight2, 1.);
340  } else {
341  std::cout << "[ZIterativeAlgorithmWithFit]::[getWeight]::rescale out " << rescale << std::endl;
342  }
343  }
344  }
345  }
346  } else {
347  std::cout << "ZIterativeAlgorithmWithFit::FATAL:found a wrong module_id " << mod << " channels " << channels_
348  << std::endl;
349  }
350  }
351 }
352 
354 
356  TH1F* histoou, double* par, double* errpar, float nsigmalow, float nsigmaup, double* myChi2, int* iterations) {
357  auto gausa = std::make_unique<TF1>(
358  "gausa", "gaus", histoou->GetMean() - 3 * histoou->GetRMS(), histoou->GetMean() + 3 * histoou->GetRMS());
359 
360  gausa->SetParameters(histoou->GetMaximum(), histoou->GetMean(), histoou->GetRMS());
361 
362  histoou->Fit(gausa.get(), "qR0N");
363 
364  double p1 = gausa->GetParameter(1);
365  double sigma = gausa->GetParameter(2);
366  double nor = gausa->GetParameter(0);
367 
368  double xmi, xma, xmin_fit, xmax_fit;
369  double chi2 = 100;
370  int iter = 0;
371 
372  while ((chi2 > 1. && iter < 5) || iter < 2) {
373  xmin_fit = p1 - nsigmalow * sigma;
374  xmax_fit = p1 + nsigmaup * sigma;
375  xmi = p1 - 5 * sigma;
376  xma = p1 + 5 * sigma;
377 
378  char suffix[20];
379  sprintf(suffix, "_iter_%d", iter);
380  auto fitFunc = std::make_unique<TF1>("FitFunc" + TString(suffix), "gaus", xmin_fit, xmax_fit);
381  fitFunc->SetParameters(nor, p1, sigma);
382  fitFunc->SetLineColor((int)(iter + 1));
383  fitFunc->SetLineWidth(1);
384  //histoou->Fit("FitFunc","lR+","");
385  histoou->Fit(fitFunc.get(), "qR0+", "");
386 
387  histoou->GetXaxis()->SetRangeUser(xmi, xma);
388  histoou->GetXaxis()->SetLabelSize(0.055);
389 
390  // std::cout << fitFunc->GetParameters() << "," << par << std::endl;
391  par[0] = (fitFunc->GetParameters())[0];
392  par[1] = (fitFunc->GetParameters())[1];
393  par[2] = (fitFunc->GetParameters())[2];
394  errpar[0] = (fitFunc->GetParErrors())[0];
395  errpar[1] = (fitFunc->GetParErrors())[1];
396  errpar[2] = (fitFunc->GetParErrors())[2];
397  if (fitFunc->GetNDF() != 0) {
398  chi2 = fitFunc->GetChisquare() / (fitFunc->GetNDF());
399  *myChi2 = chi2;
400 
401  } else {
402  chi2 = 100.;
403  // par[0]=-99;
404  // par[1]=-99;
405  // par[2]=-99;
406  std::cout << "WARNING: Not enough NDF" << std::endl;
407  // return 0;
408  }
409 
410  // Non visualizzare
411  // histoou->Draw();
412  // c1->Update();
413 
414  // std::cout << "iter " << iter << " chi2 " << chi2 << std::endl;
415  nor = par[0];
416  p1 = par[1];
417  sigma = par[2];
418  iter++;
419  *iterations = iter;
420  }
421  return;
422 }
std::vector< std::pair< calib::CalibElectron *, calib::CalibElectron * > > electrons_
static constexpr short N_MODULES_BARREL
ZIterativeAlgorithmWithFit()
Default constructor.
void getWeight(unsigned int evid, std::pair< calib::CalibElectron *, calib::CalibElectron *>, float)
#define MAX_RESCALE
virtual ~ZIterativeAlgorithmWithFit()
Destructor.
bool addEvent(calib::CalibElectron *, calib::CalibElectron *, float)
std::vector< float > optimizedCoefficients_
static void gausfit(TH1F *histoou, double *par, double *errpar, float nsigmalow, float nsigmaup, double *mychi2, int *iterations)
#define NBINS_HIGHETA
T getUntrackedParameter(std::string const &, T const &) const
U second(std::pair< T, U > const &p)
#define MIN_RESCALE
static EcalIndexingTools * getInstance()
static constexpr short N_RING_TOTAL
float getEventWeight(unsigned int event_id)
#define NBINS_LOWETA
static float invMassCalc(float Energy1, float Eta1, float Phi1, float Energy2, float Eta2, float Phi2)
ZIterativeAlgorithmWithFitPlots * thePlots_
const reco::GsfElectron * getRecoElectron()
Definition: CalibElectron.h:24
void getStatWeights(const std::string &file)
std::vector< float > optimizedCoefficientsError_
double phi() const final
momentum azimuthal angle
T mod(const T &a, const T &b)
Definition: ecalDccMap.h:4
SuperClusterRef superCluster() const override
reference to a SuperCluster
Definition: GsfElectron.h:155
def exit(msg="")
double eta() const final
momentum pseudorapidity