CMS 3D CMS Logo

BSFitter.cc
Go to the documentation of this file.
1 
13 #include "Minuit2/FunctionMinimum.h"
14 #include "Minuit2/MnPrint.h"
15 #include "Minuit2/MnMigrad.h"
16 #include "Minuit2/MnUserParameterState.h"
17 //#include "CLHEP/config/CLHEP.h"
18 
19 // C++ standard
20 #include <vector>
21 #include <cmath>
22 
23 // CMS
28 
29 // ROOT
30 #include "TMatrixD.h"
31 #include "TMatrixDSym.h"
32 #include "TDecompBK.h"
33 #include "TH1.h"
34 #include "TF1.h"
35 #include "TMinuitMinimizer.h"
36 
37 using namespace ROOT::Minuit2;
38 
39 //_____________________________________________________________________
41  fbeamtype = reco::BeamSpot::Unknown;
42 
43  //In order to make fitting ROOT histograms thread safe
44  // one must call this undocumented function
45  TMinuitMinimizer::UseStaticMinuit(false);
46 }
47 
48 //_____________________________________________________________________
49 BSFitter::BSFitter(const std::vector<BSTrkParameters> &BSvector) {
50  //In order to make fitting ROOT histograms thread safe
51  // one must call this undocumented function
52  TMinuitMinimizer::UseStaticMinuit(false);
53 
54  ffit_type = "default";
55  ffit_variable = "default";
56 
57  fBSvector = BSvector;
58 
59  fsqrt2pi = sqrt(2. * TMath::Pi());
60 
61  fpar_name[0] = "z0 ";
62  fpar_name[1] = "SigmaZ0 ";
63  fpar_name[2] = "X0 ";
64  fpar_name[3] = "Y0 ";
65  fpar_name[4] = "dxdz ";
66  fpar_name[5] = "dydz ";
67  fpar_name[6] = "SigmaBeam ";
68 
69  //if (theGausszFcn == 0 ) {
70  thePDF = new BSpdfsFcn();
71 
72  //}
73 
74  fapplyd0cut = false;
75  fapplychi2cut = false;
76  ftmprow = 0;
77  ftmp.ResizeTo(4, 1);
78  ftmp.Zero();
79  fnthite = 0;
80  fMaxZ = 50.; //cm
81  fconvergence = 0.5; // stop fit when 50% of the input collection has been removed.
82  fminNtrks = 100;
83  finputBeamWidth = -1; // no input
84 
85  h1z = new TH1F("h1z", "z distribution", 200, -fMaxZ, fMaxZ);
86 }
87 
88 //______________________________________________________________________
90  //delete fBSvector;
91  delete thePDF;
92 }
93 
94 //______________________________________________________________________
95 reco::BeamSpot BSFitter::Fit() { return this->Fit(nullptr); }
96 
97 //______________________________________________________________________
98 reco::BeamSpot BSFitter::Fit(double *inipar = nullptr) {
99  fbeamtype = reco::BeamSpot::Unknown;
100  if (ffit_variable == "z") {
101  if (ffit_type == "chi2") {
102  return Fit_z_chi2(inipar);
103 
104  } else if (ffit_type == "likelihood") {
105  return Fit_z_likelihood(inipar);
106 
107  } else if (ffit_type == "combined") {
108  reco::BeamSpot tmp_beamspot = Fit_z_chi2(inipar);
109  double tmp_par[2] = {tmp_beamspot.z0(), tmp_beamspot.sigmaZ()};
110  return Fit_z_likelihood(tmp_par);
111 
112  } else {
113  throw cms::Exception("LogicError")
114  << "Error in BeamSpotProducer/BSFitter: "
115  << "Illegal fit type, options are chi2,likelihood or combined(ie. first chi2 then likelihood)";
116  }
117  } else if (ffit_variable == "d") {
118  if (ffit_type == "d0phi") {
119  this->d0phi_Init();
120  return Fit_d0phi();
121 
122  } else if (ffit_type == "likelihood") {
123  return Fit_d_likelihood(inipar);
124 
125  } else if (ffit_type == "combined") {
126  this->d0phi_Init();
127  reco::BeamSpot tmp_beamspot = Fit_d0phi();
128  double tmp_par[4] = {tmp_beamspot.x0(), tmp_beamspot.y0(), tmp_beamspot.dxdz(), tmp_beamspot.dydz()};
129  return Fit_d_likelihood(tmp_par);
130 
131  } else {
132  throw cms::Exception("LogicError") << "Error in BeamSpotProducer/BSFitter: "
133  << "Illegal fit type, options are d0phi, likelihood or combined";
134  }
135  } else if (ffit_variable == "d*z" || ffit_variable == "default") {
136  if (ffit_type == "likelihood" || ffit_type == "default") {
138  // we are now fitting Z inside d0phi fitter
139  // first fit z distribution using a chi2 fit
140  //reco::BeamSpot tmp_z = Fit_z_chi2(inipar);
141  //for (int j = 2 ; j < 4 ; ++j) {
142  //for(int k = j ; k < 4 ; ++k) {
143  // matrix(j,k) = tmp_z.covariance()(j,k);
144  //}
145  //}
146 
147  // use d0-phi algorithm to extract transverse position
148  this->d0phi_Init();
149  //reco::BeamSpot tmp_d0phi= Fit_d0phi(); // change to iterative procedure:
150  this->Setd0Cut_d0phi(4.0);
151  reco::BeamSpot tmp_d0phi = Fit_ited0phi();
152 
153  //for (int j = 0 ; j < 2 ; ++j) {
154  // for(int k = j ; k < 2 ; ++k) {
155  // matrix(j,k) = tmp_d0phi.covariance()(j,k);
156  //}
157  //}
158  // slopes
159  //for (int j = 4 ; j < 6 ; ++j) {
160  // for(int k = j ; k < 6 ; ++k) {
161  // matrix(j,k) = tmp_d0phi.covariance()(j,k);
162  // }
163  //}
164 
165  // put everything into one object
166  reco::BeamSpot spot(reco::BeamSpot::Point(tmp_d0phi.x0(), tmp_d0phi.y0(), tmp_d0phi.z0()),
167  tmp_d0phi.sigmaZ(),
168  tmp_d0phi.dxdz(),
169  tmp_d0phi.dydz(),
170  0.,
171  tmp_d0phi.covariance(),
172  fbeamtype);
173 
174  //reco::BeamSpot tmp_z = Fit_z_chi2(inipar);
175 
176  //reco::BeamSpot tmp_d0phi = Fit_d0phi();
177 
178  // log-likelihood fit
179  if (ffit_type == "likelihood") {
180  double tmp_par[7] = {
181  tmp_d0phi.x0(), tmp_d0phi.y0(), tmp_d0phi.z0(), tmp_d0phi.sigmaZ(), tmp_d0phi.dxdz(), tmp_d0phi.dydz(), 0.0};
182 
183  double tmp_error_par[7];
184  for (int s = 0; s < 6; s++) {
185  tmp_error_par[s] = pow(tmp_d0phi.covariance()(s, s), 0.5);
186  }
187  tmp_error_par[6] = 0.0;
188 
189  reco::BeamSpot tmp_lh = Fit_d_z_likelihood(tmp_par, tmp_error_par);
190 
191  if (edm::isNotFinite(ff_minimum)) {
192  edm::LogWarning("BSFitter")
193  << "BSFitter: Result is non physical. Log-Likelihood fit to extract beam width did not converge."
194  << std::endl;
196  return tmp_lh;
197  }
198  return tmp_lh;
199 
200  } else {
201  edm::LogInfo("BSFitter") << "default track-based fit does not extract beam width." << std::endl;
202  return spot;
203  }
204 
205  } else if (ffit_type == "resolution") {
206  reco::BeamSpot tmp_z = Fit_z_chi2(inipar);
207  this->d0phi_Init();
208  reco::BeamSpot tmp_d0phi = Fit_d0phi();
209 
210  double tmp_par[7] = {
211  tmp_d0phi.x0(), tmp_d0phi.y0(), tmp_z.z0(), tmp_z.sigmaZ(), tmp_d0phi.dxdz(), tmp_d0phi.dydz(), 0.0};
212  double tmp_error_par[7];
213  for (int s = 0; s < 6; s++) {
214  tmp_error_par[s] = pow(tmp_par[s], 0.5);
215  }
216  tmp_error_par[6] = 0.0;
217 
218  reco::BeamSpot tmp_beam = Fit_d_z_likelihood(tmp_par, tmp_error_par);
219 
220  double tmp_par2[7] = {tmp_beam.x0(),
221  tmp_beam.y0(),
222  tmp_beam.z0(),
223  tmp_beam.sigmaZ(),
224  tmp_beam.dxdz(),
225  tmp_beam.dydz(),
226  tmp_beam.BeamWidthX()};
227 
228  reco::BeamSpot tmp_lh = Fit_dres_z_likelihood(tmp_par2);
229 
230  if (edm::isNotFinite(ff_minimum)) {
231  edm::LogWarning("BSFitter") << "Result is non physical. Log-Likelihood fit did not converge." << std::endl;
233  return tmp_lh;
234  }
235  return tmp_lh;
236 
237  } else {
238  throw cms::Exception("LogicError") << "Error in BeamSpotProducer/BSFitter: "
239  << "Illegal fit type, options are likelihood or resolution";
240  }
241  } else {
242  throw cms::Exception("LogicError") << "Error in BeamSpotProducer/BSFitter: "
243  << "Illegal variable type, options are \"z\", \"d\", or \"d*z\"";
244  }
245 }
246 
247 //______________________________________________________________________
249  //std::cout << "Fit_z(double *) called" << std::endl;
250  //std::cout << "inipar[0]= " << inipar[0] << std::endl;
251  //std::cout << "inipar[1]= " << inipar[1] << std::endl;
252 
253  std::vector<double> par(2, 0);
254  std::vector<double> err(2, 0);
255 
256  par.push_back(0.0);
257  par.push_back(7.0);
258  err.push_back(0.0001);
259  err.push_back(0.0001);
260  //par[0] = 0.0; err[0] = 0.0;
261  //par[1] = 7.0; err[1] = 0.0;
262 
263  thePDF->SetPDFs("PDFGauss_z");
264  thePDF->SetData(fBSvector);
265  //std::cout << "data loaded"<< std::endl;
266 
267  MnUserParameters upar;
268  upar.Add("X0", 0., 0.);
269  upar.Add("Y0", 0., 0.);
270  upar.Add("Z0", inipar[0], 0.001);
271  upar.Add("sigmaZ", inipar[1], 0.001);
272 
273  MnMigrad migrad(*thePDF, upar);
274 
275  FunctionMinimum fmin = migrad();
276  ff_minimum = fmin.Fval();
277  //std::cout << " eval= " << ff_minimum
278  // << "/n params[0]= " << fmin.Parameters().Vec()(0) << std::endl;
279 
280  /*
281  TMinuit *gmMinuit = new TMinuit(2);
282 
283  //gmMinuit->SetFCN(z_fcn);
284  gmMinuit->SetFCN(myFitz_fcn);
285 
286 
287  int ierflg = 0;
288  double step[2] = {0.001,0.001};
289 
290  for (int i = 0; i<2; i++) {
291  gmMinuit->mnparm(i,fpar_name[i].c_str(),inipar[i],step[i],0,0,ierflg);
292  }
293  gmMinuit->Migrad();
294  */
296 
297  for (int j = 2; j < 4; ++j) {
298  for (int k = j; k < 4; ++k) {
299  matrix(j, k) = fmin.Error().Matrix()(j, k);
300  }
301  }
302 
303  return reco::BeamSpot(reco::BeamSpot::Point(0., 0., fmin.Parameters().Vec()(2)),
304  fmin.Parameters().Vec()(3),
305  0.,
306  0.,
307  0.,
308  matrix,
309  fbeamtype);
310 }
311 
312 //______________________________________________________________________
314  // N.B. this fit is not performed anymore but now
315  // Z is fitted in the same track set used in the d0-phi fit after
316  // each iteration
317 
318  //std::cout << "Fit_z_chi2() called" << std::endl;
319  // FIXME: include whole tracker z length for the time being
320  // ==> add protection and z0 cut
321  h1z = new TH1F("h1z", "z distribution", 200, -fMaxZ, fMaxZ);
322 
323  std::vector<BSTrkParameters>::const_iterator iparam = fBSvector.begin();
324 
325  // HERE check size of track vector
326 
327  for (iparam = fBSvector.begin(); iparam != fBSvector.end(); ++iparam) {
328  h1z->Fill(iparam->z0());
329  //std::cout<<"z0="<<iparam->z0()<<"; sigZ0="<<iparam->sigz0()<<std::endl;
330  }
331 
332  //Use our own copy for thread safety
333  // also do not add to global list of functions
334  TF1 fgaus("fgaus", "gaus", 0., 1., TF1::EAddToList::kNo);
335  h1z->Fit(&fgaus, "QLMN0 SERIAL");
336  //std::cout << "fitted "<< std::endl;
337 
338  //std::cout << "got function" << std::endl;
339  double fpar[2] = {fgaus.GetParameter(1), fgaus.GetParameter(2)};
340  //std::cout<<"Debug fpar[2] = (" <<fpar[0]<<","<<fpar[1]<<")"<<std::endl;
342  // add matrix values.
343  matrix(2, 2) = fgaus.GetParError(1) * fgaus.GetParError(1);
344  matrix(3, 3) = fgaus.GetParError(2) * fgaus.GetParError(2);
345 
346  //delete h1z;
347 
348  return reco::BeamSpot(reco::BeamSpot::Point(0., 0., fpar[0]), fpar[1], 0., 0., 0., matrix, fbeamtype);
349 }
350 
351 //______________________________________________________________________
353  this->d0phi_Init();
354  edm::LogInfo("BSFitter") << "number of total input tracks: " << fBSvector.size() << std::endl;
355 
356  reco::BeamSpot theanswer;
357 
358  if ((int)fBSvector.size() <= fminNtrks) {
359  edm::LogWarning("BSFitter") << "need at least " << fminNtrks << " tracks to run beamline fitter." << std::endl;
360  fbeamtype = reco::BeamSpot::Fake;
361  theanswer.setType(fbeamtype);
362  return theanswer;
363  }
364 
365  theanswer = Fit_d0phi(); //get initial ftmp and ftmprow
366  if (goodfit)
367  fnthite++;
368  //std::cout << "Initial tempanswer (iteration 0): " << theanswer << std::endl;
369 
370  reco::BeamSpot preanswer = theanswer;
371 
372  while (goodfit && ftmprow > fconvergence * fBSvector.size() && ftmprow > fminNtrks) {
373  theanswer = Fit_d0phi();
374  fd0cut /= 1.5;
375  fchi2cut /= 1.5;
376  if (goodfit && ftmprow > fconvergence * fBSvector.size() && ftmprow > fminNtrks) {
377  preanswer = theanswer;
378  //std::cout << "Iteration " << fnthite << ": " << preanswer << std::endl;
379  fnthite++;
380  }
381  }
382  // FIXME: return fit results from previous iteration for both bad fit and for >50% tracks thrown away
383  //std::cout << "The last iteration, theanswer: " << theanswer << std::endl;
384  theanswer = preanswer;
385  //std::cout << "Use previous results from iteration #" << ( fnthite > 0 ? fnthite-1 : 0 ) << std::endl;
386  //if ( fnthite > 1 ) std::cout << theanswer << std::endl;
387 
388  edm::LogInfo("BSFitter") << "Total number of successful iterations = " << (goodfit ? (fnthite + 1) : fnthite)
389  << std::endl;
390  if (goodfit) {
391  fbeamtype = reco::BeamSpot::Tracker;
392  theanswer.setType(fbeamtype);
393  } else {
394  edm::LogWarning("BSFitter") << "Fit doesn't converge!!!" << std::endl;
395  fbeamtype = reco::BeamSpot::Unknown;
396  theanswer.setType(fbeamtype);
397  }
398  return theanswer;
399 }
400 
401 //______________________________________________________________________
403  //LogDebug ("BSFitter") << " we will use " << fBSvector.size() << " tracks.";
404  if (fnthite > 0)
405  edm::LogInfo("BSFitter") << " number of tracks used: " << ftmprow << std::endl;
406  //std::cout << " ftmp = matrix("<<ftmp.GetNrows()<<","<<ftmp.GetNcols()<<")"<<std::endl;
407  //std::cout << " ftmp(0,0)="<<ftmp(0,0)<<std::endl;
408  //std::cout << " ftmp(1,0)="<<ftmp(1,0)<<std::endl;
409  //std::cout << " ftmp(2,0)="<<ftmp(2,0)<<std::endl;
410  //std::cout << " ftmp(3,0)="<<ftmp(3,0)<<std::endl;
411 
412  h1z->Reset();
413 
414  TMatrixD x_result(4, 1);
415  TMatrixDSym V_result(4);
416 
417  TMatrixDSym Vint(4);
418  TMatrixD b(4, 1);
419 
420  //Double_t weightsum = 0;
421 
422  Vint.Zero();
423  b.Zero();
424 
425  TMatrixD g(4, 1);
426  TMatrixDSym temp(4);
427 
428  std::vector<BSTrkParameters>::iterator iparam = fBSvector.begin();
429  ftmprow = 0;
430 
431  //edm::LogInfo ("BSFitter") << " test";
432 
433  //std::cout << "BSFitter: fit" << std::endl;
434 
435  for (iparam = fBSvector.begin(); iparam != fBSvector.end(); ++iparam) {
436  //if(i->weight2 == 0) continue;
437 
438  //if (ftmprow==0) {
439  //std::cout << "d0=" << iparam->d0() << " sigd0=" << iparam->sigd0()
440  //<< " phi0="<< iparam->phi0() << " z0=" << iparam->z0() << std::endl;
441  //std::cout << "d0phi_d0=" << iparam->d0phi_d0() << " d0phi_chi2="<<iparam->d0phi_chi2() << std::endl;
442  //}
443  g(0, 0) = sin(iparam->phi0());
444  g(1, 0) = -cos(iparam->phi0());
445  g(2, 0) = iparam->z0() * g(0, 0);
446  g(3, 0) = iparam->z0() * g(1, 0);
447 
448  // average transverse beam width
449  double sigmabeam2 = 0.006 * 0.006;
450  if (finputBeamWidth > 0)
451  sigmabeam2 = finputBeamWidth * finputBeamWidth;
452  else {
453  //edm::LogWarning("BSFitter") << "using in fit beam width = " << sqrt(sigmabeam2) << std::endl;
454  }
455 
456  //double sigma2 = sigmabeam2 + (iparam->sigd0())* (iparam->sigd0()) / iparam->weight2;
457  // this should be 2*sigmabeam2?
458  double sigma2 = sigmabeam2 + (iparam->sigd0()) * (iparam->sigd0());
459 
460  TMatrixD ftmptrans(1, 4);
461  ftmptrans = ftmptrans.Transpose(ftmp);
462  TMatrixD dcor = ftmptrans * g;
463  double chi2tmp = (iparam->d0() - dcor(0, 0)) * (iparam->d0() - dcor(0, 0)) / sigma2;
464  (*iparam) = BSTrkParameters(
465  iparam->z0(), iparam->sigz0(), iparam->d0(), iparam->sigd0(), iparam->phi0(), iparam->pt(), dcor(0, 0), chi2tmp);
466 
467  bool pass = true;
468  if (fapplyd0cut && fnthite > 0) {
469  if (std::abs(iparam->d0() - dcor(0, 0)) > fd0cut)
470  pass = false;
471  }
472  if (fapplychi2cut && fnthite > 0) {
473  if (chi2tmp > fchi2cut)
474  pass = false;
475  }
476 
477  if (pass) {
478  temp.Zero();
479  for (int j = 0; j < 4; ++j) {
480  for (int k = j; k < 4; ++k) {
481  temp(j, k) += g(j, 0) * g(k, 0);
482  }
483  }
484 
485  Vint += (temp * (1 / sigma2));
486  b += (iparam->d0() / sigma2 * g);
487  //weightsum += sqrt(i->weight2);
488  ftmprow++;
489  h1z->Fill(iparam->z0());
490  }
491  }
492  Double_t determinant;
493  TDecompBK bk(Vint);
494  bk.SetTol(1e-11); //FIXME: find a better way to solve x_result
495  if (!bk.Decompose()) {
496  goodfit = false;
497  edm::LogWarning("BSFitter") << "Decomposition failed, matrix singular ?" << std::endl
498  << "condition number = " << bk.Condition() << std::endl;
499  } else {
500  V_result = Vint.InvertFast(&determinant);
501  x_result = V_result * b;
502  }
503  // for(int j = 0 ; j < 4 ; ++j) {
504  // for(int k = 0 ; k < 4 ; ++k) {
505  // std::cout<<"V_result("<<j<<","<<k<<")="<<V_result(j,k)<<std::endl;
506  // }
507  // }
508  // for (int j=0;j<4;++j){
509  // std::cout<<"x_result("<<j<<",0)="<<x_result(j,0)<<std::endl;
510  // }
511  //LogDebug ("BSFitter") << " d0-phi fit done.";
512  //std::cout<< " d0-phi fit done." << std::endl;
513 
514  //Use our own copy for thread safety
515  // also do not add to global list of functions
516  TF1 fgaus("fgaus", "gaus", 0., 1., TF1::EAddToList::kNo);
517  //returns 0 if OK
518  //auto status = h1z->Fit(&fgaus,"QLM0","",h1z->GetMean() -2.*h1z->GetRMS(),h1z->GetMean() +2.*h1z->GetRMS());
519  auto status =
520  h1z->Fit(&fgaus, "QLN0 SERIAL", "", h1z->GetMean() - 2. * h1z->GetRMS(), h1z->GetMean() + 2. * h1z->GetRMS());
521 
522  //std::cout << "fitted "<< std::endl;
523 
524  //std::cout << "got function" << std::endl;
525  if (status) {
526  //edm::LogError("NoBeamSpotFit")<<"gaussian fit failed. no BS d0 fit";
527 
528  goodfit = false;
529  return reco::BeamSpot();
530  }
531  double fpar[2] = {fgaus.GetParameter(1), fgaus.GetParameter(2)};
532 
534  // first two parameters
535  for (int j = 0; j < 2; ++j) {
536  for (int k = j; k < 2; ++k) {
537  matrix(j, k) = V_result(j, k);
538  }
539  }
540  // slope parameters
541  for (int j = 4; j < 6; ++j) {
542  for (int k = j; k < 6; ++k) {
543  matrix(j, k) = V_result(j - 2, k - 2);
544  }
545  }
546 
547  // Z0 and sigmaZ
548  matrix(2, 2) = fgaus.GetParError(1) * fgaus.GetParError(1);
549  matrix(3, 3) = fgaus.GetParError(2) * fgaus.GetParError(2);
550 
551  ftmp = x_result;
552 
553  // x0 and y0 are *not* x,y at z=0, but actually at z=0
554  // to correct for this, we need to translate them to z=z0
555  // using the measured slopes
556  //
557  double x0tmp = x_result(0, 0);
558  double y0tmp = x_result(1, 0);
559 
560  x0tmp += x_result(2, 0) * fpar[0];
561  y0tmp += x_result(3, 0) * fpar[0];
562 
563  return reco::BeamSpot(
564  reco::BeamSpot::Point(x0tmp, y0tmp, fpar[0]), fpar[1], x_result(2, 0), x_result(3, 0), 0., matrix, fbeamtype);
565 }
566 
567 //______________________________________________________________________
568 void BSFitter::Setd0Cut_d0phi(double d0cut) {
569  fapplyd0cut = true;
570 
571  //fBSforCuts = BSfitted;
572  fd0cut = d0cut;
573 }
574 
575 //______________________________________________________________________
577  fapplychi2cut = true;
578 
579  //fBSforCuts = BSfitted;
580  fchi2cut = chi2cut;
581 }
582 
583 //______________________________________________________________________
585  thePDF->SetPDFs("PDFGauss_d");
586  thePDF->SetData(fBSvector);
587 
588  MnUserParameters upar;
589  upar.Add("X0", inipar[0], 0.001);
590  upar.Add("Y0", inipar[1], 0.001);
591  upar.Add("Z0", 0., 0.001);
592  upar.Add("sigmaZ", 0., 0.001);
593  upar.Add("dxdz", inipar[2], 0.001);
594  upar.Add("dydz", inipar[3], 0.001);
595 
596  MnMigrad migrad(*thePDF, upar);
597 
598  FunctionMinimum fmin = migrad();
599  ff_minimum = fmin.Fval();
600 
602  for (int j = 0; j < 6; ++j) {
603  for (int k = j; k < 6; ++k) {
604  matrix(j, k) = fmin.Error().Matrix()(j, k);
605  }
606  }
607 
608  return reco::BeamSpot(reco::BeamSpot::Point(fmin.Parameters().Vec()(0), fmin.Parameters().Vec()(1), 0.),
609  0.,
610  fmin.Parameters().Vec()(4),
611  fmin.Parameters().Vec()(5),
612  0.,
613  matrix,
614  fbeamtype);
615 }
616 //______________________________________________________________________
617 double BSFitter::scanPDF(double *init_pars, int &tracksfixed, int option) {
618  if (option == 1)
619  init_pars[6] = 0.0005; //starting value for any given configuration
620 
621  //local vairables with initial values
622  double fsqrt2pi = 0.0;
623  double d_sig = 0.0;
624  double d_dprime = 0.0;
625  double d_result = 0.0;
626  double z_sig = 0.0;
627  double z_result = 0.0;
628  double function = 0.0;
629  double tot_pdf = 0.0;
630  double last_minvalue = 1.0e+10;
631  double init_bw = -99.99;
632  int iters = 0;
633 
634  //used to remove tracks if far away from bs by this
635  double DeltadCut = 0.1000;
636  if (init_pars[6] < 0.0200) {
637  DeltadCut = 0.0900;
638  } //worked for high 2.36TeV
639  if (init_pars[6] < 0.0100) {
640  DeltadCut = 0.0700;
641  } //just a guesss for 7 TeV but one should scan for actual values
642 
643  std::vector<BSTrkParameters>::const_iterator iparam = fBSvector.begin();
644 
645  if (option == 1)
646  iters = 500;
647  if (option == 2)
648  iters = 1;
649 
650  for (int p = 0; p < iters; p++) {
651  if (iters == 500)
652  init_pars[6] += 0.0002;
653  tracksfixed = 0;
654 
655  for (iparam = fBSvector.begin(); iparam != fBSvector.end(); ++iparam) {
656  fsqrt2pi = sqrt(2. * TMath::Pi());
657  d_sig = sqrt(init_pars[6] * init_pars[6] + (iparam->sigd0()) * (iparam->sigd0()));
658  d_dprime = iparam->d0() - (((init_pars[0] + iparam->z0() * (init_pars[4])) * sin(iparam->phi0())) -
659  ((init_pars[1] + iparam->z0() * (init_pars[5])) * cos(iparam->phi0())));
660 
661  //***Remove tracks before the fit which gives low pdf values to blow up the pdf
662  if (std::abs(d_dprime) < DeltadCut && option == 2) {
663  fBSvectorBW.push_back(*iparam);
664  }
665 
666  d_result = (exp(-(d_dprime * d_dprime) / (2.0 * d_sig * d_sig))) / (d_sig * fsqrt2pi);
667  z_sig = sqrt(iparam->sigz0() * iparam->sigz0() + init_pars[3] * init_pars[3]);
668  z_result = (exp(-((iparam->z0() - init_pars[2]) * (iparam->z0() - init_pars[2])) / (2.0 * z_sig * z_sig))) /
669  (z_sig * fsqrt2pi);
670  tot_pdf = z_result * d_result;
671 
672  //for those trcks which gives problems due to very tiny pdf_d values.
673  //Update: This protection will NOT be used with the dprime cut above but still kept here to get
674  // the intial value of beam width reasonably
675  //A warning will appear if there were any tracks with < 10^-5 for pdf_d so that (d-dprime) cut can be lowered
676  if (d_result < 1.0e-05) {
677  tot_pdf = z_result * 1.0e-05;
678  //if(option==2)std::cout<<"last Iter d-d' = "<<(std::abs(d_dprime))<<std::endl;
679  tracksfixed++;
680  }
681 
682  function = function + log(tot_pdf);
683 
684  } //loop over tracks
685 
686  function = -2.0 * function;
687  if (function < last_minvalue) {
688  init_bw = init_pars[6];
689  last_minvalue = function;
690  }
691  function = 0.0;
692  } //loop over beam width
693 
694  if (init_bw > 0) {
695  init_bw = init_bw + (0.20 * init_bw); //start with 20 % more
696 
697  } else {
698  if (option == 1) {
699  edm::LogWarning("BSFitter")
700  << "scanPDF:====>>>> WARNING***: The initial guess value of Beam width is negative!!!!!!" << std::endl
701  << "scanPDF:====>>>> Assigning beam width a starting value of " << init_bw << " cm" << std::endl;
702  init_bw = 0.0200;
703  }
704  }
705 
706  return init_bw;
707 }
708 
709 //________________________________________________________________________________
710 reco::BeamSpot BSFitter::Fit_d_z_likelihood(double *inipar, double *error_par) {
711  int tracksFailed = 0;
712 
713  //estimate first guess of beam width and tame 20% extra of it to start
714  inipar[6] = scanPDF(inipar, tracksFailed, 1);
715  error_par[6] = (inipar[6]) * 0.20;
716 
717  //Here remove the tracks which give low pdf and fill into a new vector
718  //std::cout<<"Size of Old vector = "<<(fBSvector.size())<<std::endl;
719  /* double junk= */ scanPDF(inipar, tracksFailed, 2);
720  //std::cout<<"Size of New vector = "<<(fBSvectorBW.size())<<std::endl;
721 
722  //Refill the fBSVector again with new sets of tracks
723  fBSvector.clear();
724  std::vector<BSTrkParameters>::const_iterator iparamBW = fBSvectorBW.begin();
725  for (iparamBW = fBSvectorBW.begin(); iparamBW != fBSvectorBW.end(); ++iparamBW) {
726  fBSvector.push_back(*iparamBW);
727  }
728 
729  thePDF->SetPDFs("PDFGauss_d*PDFGauss_z");
730  thePDF->SetData(fBSvector);
731  MnUserParameters upar;
732 
733  upar.Add("X0", inipar[0], error_par[0]);
734  upar.Add("Y0", inipar[1], error_par[1]);
735  upar.Add("Z0", inipar[2], error_par[2]);
736  upar.Add("sigmaZ", inipar[3], error_par[3]);
737  upar.Add("dxdz", inipar[4], error_par[4]);
738  upar.Add("dydz", inipar[5], error_par[5]);
739  upar.Add("BeamWidthX", inipar[6], error_par[6]);
740 
741  MnMigrad migrad(*thePDF, upar);
742 
743  FunctionMinimum fmin = migrad();
744 
745  // std::cout<<"-----how the fit evoves------"<<std::endl;
746  // std::cout<<fmin<<std::endl;
747 
748  ff_minimum = fmin.Fval();
749 
750  bool ff_nfcn = fmin.HasReachedCallLimit();
751  bool ff_cov = fmin.HasCovariance();
752  bool testing = fmin.IsValid();
753 
754  //Print WARNINGS if minimum did not converged
755  if (!testing) {
756  edm::LogWarning("BSFitter") << "===========>>>>>** WARNING: MINUIT DID NOT CONVERGES PROPERLY !!!!!!" << std::endl;
757  if (ff_nfcn)
758  edm::LogWarning("BSFitter") << "===========>>>>>** WARNING: No. of Calls Exhausted" << std::endl;
759  if (!ff_cov)
760  edm::LogWarning("BSFitter") << "===========>>>>>** WARNING: Covariance did not found" << std::endl;
761  }
762 
763  edm::LogInfo("BSFitter") << "The Total # Tracks used for beam width fit = " << (fBSvectorBW.size()) << std::endl;
764 
765  //Checks after fit is performed
766  double lastIter_pars[7];
767 
768  for (int ip = 0; ip < 7; ip++) {
769  lastIter_pars[ip] = fmin.Parameters().Vec()(ip);
770  }
771 
772  tracksFailed = 0;
773  /* double lastIter_scan= */ scanPDF(lastIter_pars, tracksFailed, 2);
774 
775  edm::LogWarning("BSFitter") << "WARNING: # of tracks which have very low pdf value (pdf_d < 1.0e-05) are = "
776  << tracksFailed << std::endl;
777 
778  //std::cout << " eval= " << ff_minimum
779  // << "/n params[0]= " << fmin.Parameters().Vec()(0) << std::endl;
780 
782 
783  for (int j = 0; j < 7; ++j) {
784  for (int k = j; k < 7; ++k) {
785  matrix(j, k) = fmin.Error().Matrix()(j, k);
786  }
787  }
788 
789  return reco::BeamSpot(
790  reco::BeamSpot::Point(fmin.Parameters().Vec()(0), fmin.Parameters().Vec()(1), fmin.Parameters().Vec()(2)),
791  fmin.Parameters().Vec()(3),
792  fmin.Parameters().Vec()(4),
793  fmin.Parameters().Vec()(5),
794  fmin.Parameters().Vec()(6),
795 
796  matrix,
797  fbeamtype);
798 }
799 
800 //______________________________________________________________________
802  thePDF->SetPDFs("PDFGauss_d_resolution*PDFGauss_z");
803  thePDF->SetData(fBSvector);
804 
805  MnUserParameters upar;
806  upar.Add("X0", inipar[0], 0.001);
807  upar.Add("Y0", inipar[1], 0.001);
808  upar.Add("Z0", inipar[2], 0.001);
809  upar.Add("sigmaZ", inipar[3], 0.001);
810  upar.Add("dxdz", inipar[4], 0.001);
811  upar.Add("dydz", inipar[5], 0.001);
812  upar.Add("BeamWidthX", inipar[6], 0.0001);
813  upar.Add("c0", 0.0010, 0.0001);
814  upar.Add("c1", 0.0090, 0.0001);
815 
816  // fix beam width
817  upar.Fix("BeamWidthX");
818  // number of parameters in fit are 9-1 = 8
819 
820  MnMigrad migrad(*thePDF, upar);
821 
822  FunctionMinimum fmin = migrad();
823  ff_minimum = fmin.Fval();
824 
826 
827  for (int j = 0; j < 6; ++j) {
828  for (int k = j; k < 6; ++k) {
829  matrix(j, k) = fmin.Error().Matrix()(j, k);
830  }
831  }
832 
833  //std::cout << " fill resolution values" << std::endl;
834  //std::cout << " matrix size= " << fmin.Error().Matrix().size() << std::endl;
835  //std::cout << " vec(6)="<< fmin.Parameters().Vec()(6) << std::endl;
836  //std::cout << " vec(7)="<< fmin.Parameters().Vec()(7) << std::endl;
837 
838  fresolution_c0 = fmin.Parameters().Vec()(6);
839  fresolution_c1 = fmin.Parameters().Vec()(7);
840  fres_c0_err = sqrt(fmin.Error().Matrix()(6, 6));
841  fres_c1_err = sqrt(fmin.Error().Matrix()(7, 7));
842 
843  for (int j = 6; j < 8; ++j) {
844  for (int k = 6; k < 8; ++k) {
845  fres_matrix(j - 6, k - 6) = fmin.Error().Matrix()(j, k);
846  }
847  }
848 
849  return reco::BeamSpot(
850  reco::BeamSpot::Point(fmin.Parameters().Vec()(0), fmin.Parameters().Vec()(1), fmin.Parameters().Vec()(2)),
851  fmin.Parameters().Vec()(3),
852  fmin.Parameters().Vec()(4),
853  fmin.Parameters().Vec()(5),
854  inipar[6],
855  matrix,
856  fbeamtype);
857 }
reco::BeamSpot Fit_d_likelihood(double *inipar)
Definition: BSFitter.cc:584
const double Pi
math::Error< dimension >::type CovarianceMatrix
Definition: BeamSpot.h:29
double BeamWidthX() const
beam width X
Definition: BeamSpot.h:82
virtual ~BSFitter()
Definition: BSFitter.cc:89
bool testing
reco::BeamSpot Fit()
Definition: BSFitter.cc:95
constexpr bool isNotFinite(T x)
Definition: isFinite.h:9
reco::BeamSpot Fit_z_likelihood(double *inipar)
Definition: BSFitter.cc:248
Sin< T >::type sin(const T &t)
Definition: Sin.h:22
math::XYZPoint Point
point in the space
Definition: BeamSpot.h:27
double dydz() const
dydz slope
Definition: BeamSpot.h:80
double scanPDF(double *init_pars, int &tracksFailed, int option)
Definition: BSFitter.cc:617
The Signals That Services Can Subscribe To This is based on ActivityRegistry and is current per Services can connect to the signals distributed by the ActivityRegistry in order to monitor the activity of the application Each possible callback has some defined which we here list in angle e g
Definition: Activities.doc:4
reco::BeamSpot Fit_dres_z_likelihood(double *inipar)
Definition: BSFitter.cc:801
void setType(BeamType type)
set beam type
Definition: BeamSpot.h:124
double x0() const
x coordinate
Definition: BeamSpot.h:61
Definition: Fit.h:32
T sqrt(T t)
Definition: SSEVec.h:23
Cos< T >::type cos(const T &t)
Definition: Cos.h:22
BSFitter()
Definition: BSFitter.cc:40
Abs< T >::type abs(const T &t)
Definition: Abs.h:22
double y0() const
y coordinate
Definition: BeamSpot.h:63
Log< level::Info, false > LogInfo
double sigmaZ() const
sigma z
Definition: BeamSpot.h:76
reco::BeamSpot Fit_ited0phi()
Definition: BSFitter.cc:352
double dxdz() const
dxdz slope
Definition: BeamSpot.h:78
double b
Definition: hdecay.h:120
reco::BeamSpot Fit_z_chi2(double *inipar)
Definition: BSFitter.cc:313
void Setd0Cut_d0phi(double d0cut)
Definition: BSFitter.cc:568
double covariance(int i, int j) const
(i,j)-th element of error matrix
Definition: BeamSpot.h:108
double z0() const
z coordinate
Definition: BeamSpot.h:65
void SetChi2Cut_d0phi(double chi2cut)
Definition: BSFitter.cc:576
Log< level::Warning, false > LogWarning
reco::BeamSpot Fit_d0phi()
Definition: BSFitter.cc:402
reco::BeamSpot Fit_d_z_likelihood(double *inipar, double *error_par)
Definition: BSFitter.cc:710
Power< A, B >::type pow(const A &a, const B &b)
Definition: Power.h:29