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