CMS 3D CMS Logo

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