CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_5_3_3/src/DQM/BeamMonitor/plugins/BeamMonitor.cc

Go to the documentation of this file.
00001 /*
00002  * \file BeamMonitor.cc
00003  * \author Geng-yuan Jeng/UC Riverside
00004  *         Francisco Yumiceva/FNAL
00005  * $Date: 2012/03/13 13:27:28 $
00006  * $Revision: 1.76 $
00007  */
00008 
00009 
00010 /*
00011 The code has been modified for running average
00012 mode, and it gives results for the last NLS which is
00013 configurable.
00014 Sushil S. Chauhan /UCDavis
00015 Evan Friis        /UCDavis
00016 The last tag for working versions without this change is
00017 V00-03-25
00018 */
00019 
00020 
00021 
00022 #include "DQM/BeamMonitor/plugins/BeamMonitor.h"
00023 #include "DQMServices/Core/interface/QReport.h"
00024 #include "FWCore/ServiceRegistry/interface/Service.h"
00025 #include "DataFormats/BeamSpot/interface/BeamSpot.h"
00026 #include "DataFormats/VertexReco/interface/Vertex.h"
00027 #include "DataFormats/VertexReco/interface/VertexFwd.h"
00028 #include "DataFormats/TrackCandidate/interface/TrackCandidate.h"
00029 #include "DataFormats/TrackCandidate/interface/TrackCandidateCollection.h"
00030 #include "DataFormats/TrackReco/interface/Track.h"
00031 #include "DataFormats/TrackReco/interface/TrackFwd.h"
00032 #include "DataFormats/Common/interface/View.h"
00033 #include "RecoVertex/BeamSpotProducer/interface/BSFitter.h"
00034 #include "FWCore/Framework/interface/MakerMacros.h"
00035 #include "FWCore/Framework/interface/LuminosityBlock.h"
00036 #include "FWCore/Framework/interface/Run.h"
00037 #include "FWCore/MessageLogger/interface/MessageLogger.h"
00038 #include "DataFormats/Common/interface/TriggerResults.h"
00039 #include "FWCore/Common/interface/TriggerNames.h"
00040 #include "DataFormats/HLTReco/interface/TriggerEvent.h"
00041 #include <numeric>
00042 #include <math.h>
00043 #include <TMath.h>
00044 #include <iostream>
00045 #include <TStyle.h>
00046 
00047 using namespace std;
00048 using namespace edm;
00049 
00050 const char * BeamMonitor::formatFitTime( const time_t & t )  {
00051 #define CET (+1)
00052 #define CEST (+2)
00053 
00054   static char ts[] = "yyyy-Mm-dd hh:mm:ss";
00055   tm * ptm;
00056   ptm = gmtime ( &t );
00057   int year = ptm->tm_year;
00058   if (year < 1995) {
00059     edm::LogError("BadTimeStamp") << "year reported is " << year << "!! resetting to 2011..." << std::endl;
00060     year = 2012;
00061   }
00062   sprintf( ts, "%4d-%02d-%02d %02d:%02d:%02d", year,ptm->tm_mon+1,ptm->tm_mday,(ptm->tm_hour+CEST)%24, ptm->tm_min, ptm->tm_sec);
00063 
00064 #ifdef STRIP_TRAILING_BLANKS_IN_TIMEZONE
00065   unsigned int b = strlen(ts);
00066   while (ts[--b] == ' ') {ts[b] = 0;}
00067 #endif
00068   return ts;
00069 
00070 }
00071 
00072 #define buffTime (23)
00073 
00074 //
00075 // constructors and destructor
00076 //
00077 BeamMonitor::BeamMonitor( const ParameterSet& ps ) :
00078   countEvt_(0),countLumi_(0),nthBSTrk_(0),nFitElements_(3),resetHistos_(false),StartAverage_(false),firstAverageFit_(0),countGapLumi_(0) {
00079 
00080   parameters_     = ps;
00081   monitorName_    = parameters_.getUntrackedParameter<string>("monitorName","YourSubsystemName");
00082   bsSrc_          = parameters_.getUntrackedParameter<InputTag>("beamSpot");
00083   pvSrc_          = parameters_.getUntrackedParameter<InputTag>("primaryVertex");
00084   hltSrc_         = parameters_.getParameter<InputTag>("hltResults");
00085   intervalInSec_  = parameters_.getUntrackedParameter<int>("timeInterval",920);//40 LS X 23"
00086   fitNLumi_       = parameters_.getUntrackedParameter<int>("fitEveryNLumi",-1);
00087   resetFitNLumi_  = parameters_.getUntrackedParameter<int>("resetEveryNLumi",-1);
00088   fitPVNLumi_     = parameters_.getUntrackedParameter<int>("fitPVEveryNLumi",-1);
00089   resetPVNLumi_   = parameters_.getUntrackedParameter<int>("resetPVEveryNLumi",-1);
00090   deltaSigCut_    = parameters_.getUntrackedParameter<double>("deltaSignificanceCut",15);
00091   debug_          = parameters_.getUntrackedParameter<bool>("Debug");
00092   onlineMode_     = parameters_.getUntrackedParameter<bool>("OnlineMode");
00093   jetTrigger_     = parameters_.getUntrackedParameter<std::vector<std::string> >("jetTrigger");
00094   tracksLabel_    = parameters_.getParameter<ParameterSet>("BeamFitter").getUntrackedParameter<InputTag>("TrackCollection");
00095   min_Ntrks_      = parameters_.getParameter<ParameterSet>("BeamFitter").getUntrackedParameter<int>("MinimumInputTracks");
00096   maxZ_           = parameters_.getParameter<ParameterSet>("BeamFitter").getUntrackedParameter<double>("MaximumZ");
00097   minNrVertices_  = parameters_.getParameter<ParameterSet>("PVFitter").getUntrackedParameter<unsigned int>("minNrVerticesForFit");
00098   minVtxNdf_      = parameters_.getParameter<ParameterSet>("PVFitter").getUntrackedParameter<double>("minVertexNdf");
00099   minVtxWgt_      = parameters_.getParameter<ParameterSet>("PVFitter").getUntrackedParameter<double>("minVertexMeanWeight");
00100 
00101   dbe_            = Service<DQMStore>().operator->();
00102 
00103   if (monitorName_ != "" ) monitorName_ = monitorName_+"/" ;
00104 
00105   theBeamFitter = new BeamFitter(parameters_);
00106   theBeamFitter->resetTrkVector();
00107   theBeamFitter->resetLSRange();
00108   theBeamFitter->resetRefTime();
00109   theBeamFitter->resetPVFitter();
00110 
00111   if (fitNLumi_ <= 0) fitNLumi_ = 1;
00112   nFits_ = beginLumiOfBSFit_ = endLumiOfBSFit_ = beginLumiOfPVFit_ = endLumiOfPVFit_ = 0;
00113   refBStime[0] = refBStime[1] = refPVtime[0] = refPVtime[1] = 0;
00114   maxZ_ = std::fabs(maxZ_);
00115   lastlumi_ = 0;
00116   nextlumi_ = 0;
00117   processed_ = false;
00118 }
00119 
00120 
00121 BeamMonitor::~BeamMonitor() {
00122   delete theBeamFitter;
00123 }
00124 
00125 
00126 //--------------------------------------------------------
00127 void BeamMonitor::beginJob() {
00128 
00129 
00130   // book some histograms here
00131   const int    dxBin = parameters_.getParameter<int>("dxBin");
00132   const double dxMin  = parameters_.getParameter<double>("dxMin");
00133   const double dxMax  = parameters_.getParameter<double>("dxMax");
00134 
00135   const int    vxBin = parameters_.getParameter<int>("vxBin");
00136   const double vxMin  = parameters_.getParameter<double>("vxMin");
00137   const double vxMax  = parameters_.getParameter<double>("vxMax");
00138 
00139   const int    phiBin = parameters_.getParameter<int>("phiBin");
00140   const double phiMin  = parameters_.getParameter<double>("phiMin");
00141   const double phiMax  = parameters_.getParameter<double>("phiMax");
00142 
00143   const int    dzBin = parameters_.getParameter<int>("dzBin");
00144   const double dzMin  = parameters_.getParameter<double>("dzMin");
00145   const double dzMax  = parameters_.getParameter<double>("dzMax");
00146 
00147   // create and cd into new folder
00148   dbe_->setCurrentFolder(monitorName_+"Fit");
00149 
00150   h_nTrk_lumi=dbe_->book1D("nTrk_lumi","Num. of selected tracks vs lumi",20,0.5,20.5);
00151   h_nTrk_lumi->setAxisTitle("Lumisection",1);
00152   h_nTrk_lumi->setAxisTitle("Num of Tracks",2);
00153 
00154   h_d0_phi0 = dbe_->bookProfile("d0_phi0","d_{0} vs. #phi_{0} (Selected Tracks)",phiBin,phiMin,phiMax,dxBin,dxMin,dxMax,"");
00155   h_d0_phi0->setAxisTitle("#phi_{0} (rad)",1);
00156   h_d0_phi0->setAxisTitle("d_{0} (cm)",2);
00157 
00158   h_vx_vy = dbe_->book2D("trk_vx_vy","Vertex (PCA) position of selected tracks",vxBin,vxMin,vxMax,vxBin,vxMin,vxMax);
00159   h_vx_vy->getTH2F()->SetOption("COLZ");
00160   //   h_vx_vy->getTH1()->SetBit(TH1::kCanRebin);
00161   h_vx_vy->setAxisTitle("x coordinate of input track at PCA (cm)",1);
00162   h_vx_vy->setAxisTitle("y coordinate of input track at PCA (cm)",2);
00163 
00164   TDatime *da = new TDatime();
00165   gStyle->SetTimeOffset(da->Convert(kTRUE));
00166 
00167   const int nvar_ = 6;
00168   string coord[nvar_] = {"x","y","z","sigmaX","sigmaY","sigmaZ"};
00169   string label[nvar_] = {"x_{0} (cm)","y_{0} (cm)","z_{0} (cm)",
00170                          "#sigma_{X_{0}} (cm)","#sigma_{Y_{0}} (cm)","#sigma_{Z_{0}} (cm)"};
00171   for (int i = 0; i < 4; i++) {
00172     dbe_->setCurrentFolder(monitorName_+"Fit");
00173     for (int ic=0; ic<nvar_; ++ic) {
00174       TString histName(coord[ic]);
00175       TString histTitle(coord[ic]);
00176       string ytitle(label[ic]);
00177       string xtitle("");
00178       string options("E1");
00179       bool createHisto = true;
00180       switch(i) {
00181       case 1: // BS vs time
00182         histName += "0_time";
00183         xtitle = "Time [UTC]";
00184         if (ic < 3)
00185           histTitle += " coordinate of beam spot vs time (Fit)";
00186         else
00187           histTitle = histTitle.Insert(5," ") + " of beam spot vs time (Fit)";
00188         break;
00189       case 2: // PV vs lumi
00190         if (ic < 3) {
00191           dbe_->setCurrentFolder(monitorName_+"PrimaryVertex");
00192           histName.Insert(0,"PV");
00193           histName += "_lumi";
00194           histTitle.Insert(0,"Avg. ");
00195           histTitle += " position of primary vtx vs lumi";
00196           xtitle = "Lumisection";
00197           ytitle.insert(0,"PV");
00198           ytitle += " #pm #sigma_{PV";
00199           ytitle += coord[ic];
00200           ytitle += "} (cm)";
00201         }
00202         else createHisto = false;
00203         break;
00204       case 3: // PV vs time
00205         if (ic < 3) {
00206           dbe_->setCurrentFolder(monitorName_+"PrimaryVertex");
00207           histName.Insert(0,"PV");
00208           histName += "_time";
00209           histTitle.Insert(0,"Avg. ");
00210           histTitle += " position of primary vtx vs time";
00211           xtitle = "Time [UTC]";
00212           ytitle.insert(0,"PV");
00213           ytitle += " #pm #sigma_{PV";
00214           ytitle += coord[ic];
00215           ytitle += "} (cm)";
00216         }
00217         else createHisto = false;
00218         break;
00219       default: // BS vs lumi
00220         histName += "0_lumi";
00221         xtitle = "Lumisection";
00222         if (ic < 3)
00223           histTitle += " coordinate of beam spot vs lumi (Fit)";
00224         else
00225           histTitle = histTitle.Insert(5," ") + " of beam spot vs lumi (Fit)";
00226         break;
00227       }
00228       if (createHisto) {
00229         edm::LogInfo("BeamMonitor") << "hitsName = " << histName << "; histTitle = " << histTitle << std::endl;
00230         hs[histName] = dbe_->book1D(histName,histTitle,40,0.5,40.5);
00231         hs[histName]->setAxisTitle(xtitle,1);
00232         hs[histName]->setAxisTitle(ytitle,2);
00233         hs[histName]->getTH1()->SetOption("E1");
00234         if (histName.Contains("time")) {
00235           //int nbins = (intervalInSec_/23 > 0 ? intervalInSec_/23 : 40);
00236           hs[histName]->getTH1()->SetBins(intervalInSec_,0.5,intervalInSec_+0.5);
00237           hs[histName]->setAxisTimeDisplay(1);
00238           hs[histName]->setAxisTimeFormat("%H:%M:%S",1);
00239         }
00240         histName += "_all";
00241         histTitle += " all";
00242         hs[histName] = dbe_->book1D(histName,histTitle,40,0.5,40.5);
00243         hs[histName]->getTH1()->SetBit(TH1::kCanRebin);
00244         hs[histName]->setAxisTitle(xtitle,1);
00245         hs[histName]->setAxisTitle(ytitle,2);
00246         hs[histName]->getTH1()->SetOption("E1");
00247         if (histName.Contains("time")) {
00248           //int nbins = (intervalInSec_/23 > 0 ? intervalInSec_/23 : 40);
00249           hs[histName]->getTH1()->SetBins(intervalInSec_,0.5,intervalInSec_+0.5);
00250           hs[histName]->setAxisTimeDisplay(1);
00251           hs[histName]->setAxisTimeFormat("%H:%M:%S",1);
00252         }
00253       }
00254     }
00255   }
00256   dbe_->setCurrentFolder(monitorName_+"Fit");
00257 
00258   h_trk_z0 = dbe_->book1D("trk_z0","z_{0} of selected tracks",dzBin,dzMin,dzMax);
00259   h_trk_z0->setAxisTitle("z_{0} of selected tracks (cm)",1);
00260 
00261   h_vx_dz = dbe_->bookProfile("vx_dz","v_{x} vs. dz of selected tracks",dzBin,dzMin,dzMax,dxBin,dxMin,dxMax,"");
00262   h_vx_dz->setAxisTitle("dz (cm)",1);
00263   h_vx_dz->setAxisTitle("x coordinate of input track at PCA (cm)",2);
00264 
00265   h_vy_dz = dbe_->bookProfile("vy_dz","v_{y} vs. dz of selected tracks",dzBin,dzMin,dzMax,dxBin,dxMin,dxMax,"");
00266   h_vy_dz->setAxisTitle("dz (cm)",1);
00267   h_vy_dz->setAxisTitle("x coordinate of input track at PCA (cm)",2);
00268 
00269   h_x0 = dbe_->book1D("BeamMonitorFeedBack_x0","x coordinate of beam spot (Fit)",100,-0.01,0.01);
00270   h_x0->setAxisTitle("x_{0} (cm)",1);
00271   h_x0->getTH1()->SetBit(TH1::kCanRebin);
00272 
00273   h_y0 = dbe_->book1D("BeamMonitorFeedBack_y0","y coordinate of beam spot (Fit)",100,-0.01,0.01);
00274   h_y0->setAxisTitle("y_{0} (cm)",1);
00275   h_y0->getTH1()->SetBit(TH1::kCanRebin);
00276 
00277   h_z0 = dbe_->book1D("BeamMonitorFeedBack_z0","z coordinate of beam spot (Fit)",dzBin,dzMin,dzMax);
00278   h_z0->setAxisTitle("z_{0} (cm)",1);
00279   h_z0->getTH1()->SetBit(TH1::kCanRebin);
00280 
00281   h_sigmaX0 = dbe_->book1D("BeamMonitorFeedBack_sigmaX0","sigma x0 of beam spot (Fit)",100,0,0.05);
00282   h_sigmaX0->setAxisTitle("#sigma_{X_{0}} (cm)",1);
00283   h_sigmaX0->getTH1()->SetBit(TH1::kCanRebin);
00284 
00285   h_sigmaY0 = dbe_->book1D("BeamMonitorFeedBack_sigmaY0","sigma y0 of beam spot (Fit)",100,0,0.05);
00286   h_sigmaY0->setAxisTitle("#sigma_{Y_{0}} (cm)",1);
00287   h_sigmaY0->getTH1()->SetBit(TH1::kCanRebin);
00288 
00289   h_sigmaZ0 = dbe_->book1D("BeamMonitorFeedBack_sigmaZ0","sigma z0 of beam spot (Fit)",100,0,10);
00290   h_sigmaZ0->setAxisTitle("#sigma_{Z_{0}} (cm)",1);
00291   h_sigmaZ0->getTH1()->SetBit(TH1::kCanRebin);
00292 
00293   // Histograms of all reco tracks (without cuts):
00294   h_trkPt=dbe_->book1D("trkPt","p_{T} of all reco'd tracks (no selection)",200,0.,50.);
00295   h_trkPt->setAxisTitle("p_{T} (GeV/c)",1);
00296 
00297   h_trkVz=dbe_->book1D("trkVz","Z coordinate of PCA of all reco'd tracks (no selection)",dzBin,dzMin,dzMax);
00298   h_trkVz->setAxisTitle("V_{Z} (cm)",1);
00299 
00300   cutFlowTable = dbe_->book1D("cutFlowTable","Cut flow table of track selection", 9, 0, 9 );
00301 
00302   // Results of previous good fit:
00303   fitResults=dbe_->book2D("fitResults","Results of previous good beam fit",2,0,2,8,0,8);
00304   fitResults->setAxisTitle("Fitted Beam Spot (cm)",1);
00305   fitResults->setBinLabel(8,"x_{0}",2);
00306   fitResults->setBinLabel(7,"y_{0}",2);
00307   fitResults->setBinLabel(6,"z_{0}",2);
00308   fitResults->setBinLabel(5,"#sigma_{Z}",2);
00309   fitResults->setBinLabel(4,"#frac{dx}{dz} (rad)",2);
00310   fitResults->setBinLabel(3,"#frac{dy}{dz} (rad)",2);
00311   fitResults->setBinLabel(2,"#sigma_{X}",2);
00312   fitResults->setBinLabel(1,"#sigma_{Y}",2);
00313   fitResults->setBinLabel(1,"Mean",1);
00314   fitResults->setBinLabel(2,"Stat. Error",1);
00315   fitResults->getTH1()->SetOption("text");
00316 
00317   // Histos of PrimaryVertices:
00318   dbe_->setCurrentFolder(monitorName_+"PrimaryVertex");
00319 
00320   h_nVtx = dbe_->book1D("vtxNbr","Reconstructed Vertices(non-fake) in all Event",60,-0.5,59.5);
00321   h_nVtx->setAxisTitle("Num. of reco. vertices",1);
00322   
00323   //For one Trigger only
00324   h_nVtx_st = dbe_->book1D("vtxNbr_SelectedTriggers","Reconstructed Vertices(non-fake) in Events",60,-0.5,59.5);
00325   //h_nVtx_st->setAxisTitle("Num. of reco. vertices for Un-Prescaled Jet Trigger",1);
00326 
00327   // Monitor only the PV with highest sum pt of assoc. trks:
00328   h_PVx[0] = dbe_->book1D("PVX","x coordinate of Primary Vtx",50,-0.01,0.01);
00329   h_PVx[0]->setAxisTitle("PVx (cm)",1);
00330   h_PVx[0]->getTH1()->SetBit(TH1::kCanRebin);
00331 
00332   h_PVy[0] = dbe_->book1D("PVY","y coordinate of Primary Vtx",50,-0.01,0.01);
00333   h_PVy[0]->setAxisTitle("PVy (cm)",1);
00334   h_PVy[0]->getTH1()->SetBit(TH1::kCanRebin);
00335 
00336   h_PVz[0] = dbe_->book1D("PVZ","z coordinate of Primary Vtx",dzBin,dzMin,dzMax);
00337   h_PVz[0]->setAxisTitle("PVz (cm)",1);
00338 
00339   h_PVx[1] = dbe_->book1D("PVXFit","x coordinate of Primary Vtx (Last Fit)",50,-0.01,0.01);
00340   h_PVx[1]->setAxisTitle("PVx (cm)",1);
00341   h_PVx[1]->getTH1()->SetBit(TH1::kCanRebin);
00342 
00343   h_PVy[1] = dbe_->book1D("PVYFit","y coordinate of Primary Vtx (Last Fit)",50,-0.01,0.01);
00344   h_PVy[1]->setAxisTitle("PVy (cm)",1);
00345   h_PVy[1]->getTH1()->SetBit(TH1::kCanRebin);
00346 
00347   h_PVz[1] = dbe_->book1D("PVZFit","z coordinate of Primary Vtx (Last Fit)",dzBin,dzMin,dzMax);
00348   h_PVz[1]->setAxisTitle("PVz (cm)",1);
00349 
00350   h_PVxz = dbe_->bookProfile("PVxz","PVx vs. PVz",dzBin/2,dzMin,dzMax,dxBin/2,dxMin,dxMax,"");
00351   h_PVxz->setAxisTitle("PVz (cm)",1);
00352   h_PVxz->setAxisTitle("PVx (cm)",2);
00353 
00354   h_PVyz = dbe_->bookProfile("PVyz","PVy vs. PVz",dzBin/2,dzMin,dzMax,dxBin/2,dxMin,dxMax,"");
00355   h_PVyz->setAxisTitle("PVz (cm)",1);
00356   h_PVyz->setAxisTitle("PVy (cm)",2);
00357 
00358   // Results of previous good fit:
00359   pvResults=dbe_->book2D("pvResults","Results of fitting Primary Vertices",2,0,2,6,0,6);
00360   pvResults->setAxisTitle("Fitted Primary Vertex (cm)",1);
00361   pvResults->setBinLabel(6,"PVx",2);
00362   pvResults->setBinLabel(5,"PVy",2);
00363   pvResults->setBinLabel(4,"PVz",2);
00364   pvResults->setBinLabel(3,"#sigma_{X}",2);
00365   pvResults->setBinLabel(2,"#sigma_{Y}",2);
00366   pvResults->setBinLabel(1,"#sigma_{Z}",2);
00367   pvResults->setBinLabel(1,"Mean",1);
00368   pvResults->setBinLabel(2,"Stat. Error",1);
00369   pvResults->getTH1()->SetOption("text");
00370 
00371   // Summary plots:
00372   dbe_->setCurrentFolder(monitorName_+"EventInfo");
00373   reportSummary = dbe_->get(monitorName_+"EventInfo/reportSummary");
00374   if (reportSummary) dbe_->removeElement(reportSummary->getName());
00375 
00376   reportSummary = dbe_->bookFloat("reportSummary");
00377   if(reportSummary) reportSummary->Fill(std::numeric_limits<double>::quiet_NaN());
00378 
00379   char histo[20];
00380   dbe_->setCurrentFolder(monitorName_+"EventInfo/reportSummaryContents");
00381   for (int n = 0; n < nFitElements_; n++) {
00382     switch(n){
00383     case 0 : sprintf(histo,"x0_status"); break;
00384     case 1 : sprintf(histo,"y0_status"); break;
00385     case 2 : sprintf(histo,"z0_status"); break;
00386     }
00387     reportSummaryContents[n] = dbe_->bookFloat(histo);
00388   }
00389 
00390   for (int i = 0; i < nFitElements_; i++) {
00391     summaryContent_[i] = 0.;
00392     reportSummaryContents[i]->Fill(std::numeric_limits<double>::quiet_NaN());
00393   }
00394 
00395   dbe_->setCurrentFolder(monitorName_+"EventInfo");
00396 
00397   reportSummaryMap = dbe_->get(monitorName_+"EventInfo/reportSummaryMap");
00398   if (reportSummaryMap) dbe_->removeElement(reportSummaryMap->getName());
00399 
00400   reportSummaryMap = dbe_->book2D("reportSummaryMap", "Beam Spot Summary Map", 1, 0, 1, 3, 0, 3);
00401   reportSummaryMap->setAxisTitle("",1);
00402   reportSummaryMap->setAxisTitle("Fitted Beam Spot",2);
00403   reportSummaryMap->setBinLabel(1," ",1);
00404   reportSummaryMap->setBinLabel(1,"x_{0}",2);
00405   reportSummaryMap->setBinLabel(2,"y_{0}",2);
00406   reportSummaryMap->setBinLabel(3,"z_{0}",2);
00407   for (int i = 0; i < nFitElements_; i++) {
00408     reportSummaryMap->setBinContent(1,i+1,-1.);
00409   }
00410 }
00411 
00412 //--------------------------------------------------------
00413 void BeamMonitor::beginRun(const edm::Run& r, const EventSetup& context) {
00414 
00415   frun = r.run();
00416   ftimestamp = r.beginTime().value();
00417   tmpTime = ftimestamp >> 32;
00418   startTime = refTime =  tmpTime;
00419   const char* eventTime = formatFitTime(tmpTime);
00420   std::cout << "TimeOffset = " << eventTime << std::endl;
00421   TDatime da(eventTime);
00422   if (debug_) {
00423     edm::LogInfo("BeamMonitor") << "TimeOffset = ";
00424     da.Print();
00425   }
00426   for (std::map<TString,MonitorElement*>::iterator it = hs.begin();
00427        it != hs.end(); ++it) {
00428     if ((*it).first.Contains("time"))
00429       (*it).second->getTH1()->GetXaxis()->SetTimeOffset(da.Convert(kTRUE));
00430   }
00431 }
00432 
00433 //--------------------------------------------------------
00434 void BeamMonitor::beginLuminosityBlock(const LuminosityBlock& lumiSeg,
00435                                        const EventSetup& context) {
00436   int nthlumi = lumiSeg.luminosityBlock();
00437   const edm::TimeValue_t fbegintimestamp = lumiSeg.beginTime().value();
00438   const std::time_t ftmptime = fbegintimestamp >> 32;
00439 
00440 
00441  if (countLumi_ == 0 && (!processed_)) {
00442     beginLumiOfBSFit_ = beginLumiOfPVFit_ = nthlumi;
00443     refBStime[0] = refPVtime[0] = ftmptime;
00444     mapBeginBSLS[countLumi_]   = nthlumi;
00445     mapBeginPVLS[countLumi_]   = nthlumi;
00446     mapBeginBSTime[countLumi_] = ftmptime;
00447     mapBeginPVTime[countLumi_] = ftmptime;
00448     }//for the first record
00449 
00450 if(nthlumi > nextlumi_){
00451    if(processed_){ countLumi_++;
00452     //store here them will need when we remove the first one of Last N LS
00453     mapBeginBSLS[countLumi_]   = nthlumi;
00454     mapBeginPVLS[countLumi_]   = nthlumi;
00455     mapBeginBSTime[countLumi_] = ftmptime;
00456     mapBeginPVTime[countLumi_] = ftmptime;
00457    }//processed passed but not the first lumi
00458    if((!processed_) && countLumi_ !=0){
00459        mapBeginBSLS[countLumi_]   = nthlumi;
00460        mapBeginPVLS[countLumi_]   = nthlumi;
00461        mapBeginBSTime[countLumi_] = ftmptime;
00462        mapBeginPVTime[countLumi_] = ftmptime;
00463    }//processed fails for last lumi
00464   }//nthLumi > nextlumi
00465 
00466 
00467    if(StartAverage_ ){
00468      //Just Make sure it get rest
00469      refBStime[0] =0;
00470      refPVtime[0] =0;
00471      beginLumiOfPVFit_ =0;
00472      beginLumiOfBSFit_ =0;
00473 
00474      if(debug_)edm::LogInfo("BeamMonitor") << " beginLuminosityBlock:  Size of mapBeginBSLS before =  "<< mapBeginBSLS.size()<<endl;
00475      if(nthlumi> nextlumi_){ //this make sure that it does not take into account this lumi for fitting and only look forward for new lumi
00476                              //as countLumi also remains the same so map value  get overwritten once return to normal running.
00477      //even if few LS are misssing and DQM module do not sees them then it catchs up again
00478      map<int, int>::iterator itbs=mapBeginBSLS.begin();
00479      map<int, int>::iterator itpv=mapBeginPVLS.begin();
00480      map<int, std::time_t>::iterator itbstime=mapBeginBSTime.begin();
00481      map<int, std::time_t>::iterator itpvtime=mapBeginPVTime.begin();
00482 
00483      mapBeginBSLS.erase(itbs);
00484      mapBeginPVLS.erase(itpv);
00485      mapBeginBSTime.erase(itbstime);
00486      mapBeginPVTime.erase(itpvtime);
00487 
00488             /*//not sure if want this or not ??
00489             map<int, int>::iterator itgapb=mapBeginBSLS.begin();
00490             map<int, int>::iterator itgape=mapBeginBSLS.end(); itgape--;
00491             countGapLumi_ = ( (itgape->second) - (itgapb->second) );
00492             //if we see Gap more than then 2*resetNFitLumi !!!!!!!
00493             //for example if 10-15 is fitted and if 16-25 are missing then we next fit will be for range 11-26 but BS can change in between
00494             // so better start  as fresh  and reset everything like starting in the begining!
00495             if(countGapLumi_ >= 2*resetFitNLumi_){RestartFitting(); mapBeginBSLS[countLumi_]   = nthlumi;}
00496             */
00497      }
00498 
00499     if(debug_) edm::LogInfo("BeamMonitor") << " beginLuminosityBlock::  Size of mapBeginBSLS After = "<< mapBeginBSLS.size()<<endl;
00500 
00501      map<int, int>::iterator  bbs = mapBeginBSLS.begin();
00502      map<int, int>::iterator  bpv = mapBeginPVLS.begin();
00503      map<int, std::time_t>::iterator bbst = mapBeginBSTime.begin();
00504      map<int, std::time_t>::iterator bpvt = mapBeginPVTime.begin();
00505 
00506 
00507      if (beginLumiOfPVFit_ == 0) beginLumiOfPVFit_ = bpv->second;     //new begin time after removing the LS
00508      if (beginLumiOfBSFit_ == 0) beginLumiOfBSFit_ = bbs->second;
00509      if (refBStime[0] == 0) refBStime[0] = bbst->second;
00510      if (refPVtime[0] == 0) refPVtime[0] = bpvt->second;
00511 
00512     }//same logic for average fit as above commented line
00513 
00514 
00515     map<int, std::time_t>::iterator nbbst = mapBeginBSTime.begin();
00516     map<int, std::time_t>::iterator nbpvt = mapBeginPVTime.begin();
00517 
00518 
00519   if (onlineMode_ && (nthlumi < nextlumi_)) return;
00520 
00521   if (onlineMode_) {
00522     if (nthlumi > nextlumi_) {
00523       if (countLumi_ != 0 && processed_) FitAndFill(lumiSeg,lastlumi_,nextlumi_,nthlumi);
00524       nextlumi_ = nthlumi;
00525       edm::LogInfo("BeamMonitor") << "beginLuminosityBlock:: Next Lumi to Fit: " << nextlumi_ << endl;
00526       if((StartAverage_) && refBStime[0] == 0) refBStime[0] = nbbst->second;
00527       if((StartAverage_) && refPVtime[0] == 0) refPVtime[0] = nbpvt->second;
00528     }
00529   }
00530   else{
00531     if (processed_) FitAndFill(lumiSeg,lastlumi_,nextlumi_,nthlumi);
00532     nextlumi_ = nthlumi;
00533     edm::LogInfo("BeamMonitor") << " beginLuminosityBlock:: Next Lumi to Fit: " << nextlumi_ << endl;
00534     if ((StartAverage_) && refBStime[0] == 0) refBStime[0] = nbbst->second;
00535     if ((StartAverage_) && refPVtime[0] == 0) refPVtime[0] = nbpvt->second;
00536   }
00537 
00538   //countLumi_++;
00539   if (processed_) processed_ = false;
00540   edm::LogInfo("BeamMonitor") << " beginLuminosityBlock::  Begin of Lumi: " << nthlumi << endl;
00541 }
00542 
00543 // ----------------------------------------------------------
00544 void BeamMonitor::analyze(const Event& iEvent,
00545                           const EventSetup& iSetup ) {
00546   const int nthlumi = iEvent.luminosityBlock();
00547   if (onlineMode_ && (nthlumi < nextlumi_)) {
00548     edm::LogInfo("BeamMonitor") << "analyze::  Spilt event from previous lumi section!" << std::endl;
00549     return;
00550   }
00551   if (onlineMode_ && (nthlumi > nextlumi_)) {
00552     edm::LogInfo("BeamMonitor") << "analyze::  Spilt event from next lumi section!!!" << std::endl;
00553     return;
00554   }
00555 
00556   countEvt_++;
00557   theBeamFitter->readEvent(iEvent); //Remember when track fitter read the event in the same place the PVFitter read the events !!!!!!!!!
00558 
00559   Handle<reco::BeamSpot> recoBeamSpotHandle;
00560   iEvent.getByLabel(bsSrc_,recoBeamSpotHandle);
00561   refBS = *recoBeamSpotHandle;
00562 
00563   dbe_->setCurrentFolder(monitorName_+"Fit/");
00564 
00565   //------Cut Flow Table filled every event!--------------------------------------
00566   std::string cutFlowTableName = cutFlowTable->getName();
00567   // Make a copy of the cut flow table from the beam fitter.
00568   TH1F * tmphisto =
00569     static_cast<TH1F*>((theBeamFitter->getCutFlow())->Clone("tmphisto"));
00570   cutFlowTable->getTH1()->SetBins(
00571       tmphisto->GetNbinsX(),
00572       tmphisto->GetXaxis()->GetXmin(),
00573       tmphisto->GetXaxis()->GetXmax());
00574   // Update the bin labels
00575   if (countEvt_ == 1) // SetLabel just once
00576     for(int n=0; n < tmphisto->GetNbinsX(); n++)
00577       cutFlowTable->setBinLabel(n+1,tmphisto->GetXaxis()->GetBinLabel(n+1),1);
00578   cutFlowTable = dbe_->book1D(cutFlowTableName, tmphisto);
00579 
00580   //----Reco tracks -------------------------------------
00581   Handle<reco::TrackCollection> TrackCollection;
00582   iEvent.getByLabel(tracksLabel_, TrackCollection);
00583   const reco::TrackCollection *tracks = TrackCollection.product();
00584   for ( reco::TrackCollection::const_iterator track = tracks->begin();
00585       track != tracks->end(); ++track ) {
00586     h_trkPt->Fill(track->pt());  //no need to change  here for average bs
00587     h_trkVz->Fill(track->vz());
00588   }
00589 
00590    //-------HLT Trigger --------------------------------
00591    edm::Handle<TriggerResults> triggerResults;
00592    bool JetTrigPass= false;
00593   if(iEvent.getByLabel(hltSrc_, triggerResults)){
00594      const edm::TriggerNames & trigNames = iEvent.triggerNames(*triggerResults); 
00595       for (unsigned int i=0; i< triggerResults->size(); i++){
00596            std::string trigName = trigNames.triggerName(i);
00597 
00598          if(JetTrigPass) continue;
00599 
00600         for(size_t t=0; t <jetTrigger_.size(); ++t){
00601   
00602          if(JetTrigPass) continue;
00603 
00604           string string_search (jetTrigger_[t]);
00605           size_t found = trigName.find(string_search); 
00606 
00607           if(found != string::npos){
00608              int thisTrigger_ = trigNames.triggerIndex(trigName);
00609              if(triggerResults->accept(thisTrigger_))JetTrigPass = true;
00610              }//if trigger found
00611         }//for(t=0;..)
00612       }//for(i=0; ..)
00613    }//if trigger colleciton exist)
00614 
00615   //------ Primary Vertices-------
00616   edm::Handle< reco::VertexCollection > PVCollection;
00617 
00618   if (iEvent.getByLabel(pvSrc_, PVCollection )) {
00619     int nPVcount = 0;
00620     int nPVcount_ST =0;   //For Single Trigger(hence ST)
00621 
00622     for (reco::VertexCollection::const_iterator pv = PVCollection->begin(); pv != PVCollection->end(); ++pv) {
00623       //--- vertex selection
00624       if (pv->isFake() || pv->tracksSize()==0)  continue;
00625       nPVcount++; // count non fake pv:
00626 
00627       if(JetTrigPass)nPVcount_ST++; //non-fake pv with a specific trigger
00628 
00629       if (pv->ndof() < minVtxNdf_ || (pv->ndof()+3.)/pv->tracksSize() < 2*minVtxWgt_)  continue;
00630 
00631       //Fill this map to store xyx for pv so that later we can remove the first one for run aver
00632       mapPVx[countLumi_].push_back(pv->x());
00633       mapPVy[countLumi_].push_back(pv->y());
00634       mapPVz[countLumi_].push_back(pv->z());
00635 
00636       if(!StartAverage_){//for first N LS
00637         h_PVx[0]->Fill(pv->x());
00638         h_PVy[0]->Fill(pv->y());
00639         h_PVz[0]->Fill(pv->z());
00640         h_PVxz->Fill(pv->z(),pv->x());
00641         h_PVyz->Fill(pv->z(),pv->y());
00642       }//for first N LiS
00643      else{
00644       h_PVxz->Fill(pv->z(),pv->x());
00645       h_PVyz->Fill(pv->z(),pv->y());}
00646 
00647     }//loop over pvs
00648 
00649 
00650     h_nVtx->Fill(nPVcount*1.); //no need to change it for average BS
00651 
00652     mapNPV[countLumi_].push_back((nPVcount_ST));
00653 
00654     if(!StartAverage_){ h_nVtx_st->Fill(nPVcount_ST*1.);}
00655 
00656   }//if pv collection is availaable
00657 
00658 
00659   if(StartAverage_)
00660   {
00661     map<int, std::vector<float> >::iterator itpvx=mapPVx.begin();
00662     map<int, std::vector<float> >::iterator itpvy=mapPVy.begin();
00663     map<int, std::vector<float> >::iterator itpvz=mapPVz.begin();
00664 
00665     map<int, std::vector<int> >::iterator itbspvinfo=mapNPV.begin();
00666 
00667     if( (int)mapPVx.size() > resetFitNLumi_){  //sometimes the events is not there but LS is there!
00668       mapPVx.erase(itpvx);
00669       mapPVy.erase(itpvy);
00670       mapPVz.erase(itpvz);
00671       mapNPV.erase(itbspvinfo);
00672     }//loop over Last N lumi collected
00673 
00674   }//StartAverage==true
00675 
00676   processed_ = true;
00677 }
00678 
00679 
00680 //--------------------------------------------------------
00681 void BeamMonitor::endLuminosityBlock(const LuminosityBlock& lumiSeg,
00682                                      const EventSetup& iSetup) {
00683   int nthlumi = lumiSeg.id().luminosityBlock();
00684   edm::LogInfo("BeamMonitor") << "endLuminosityBlock:: Lumi of the last event before endLuminosityBlock: " << nthlumi << endl;
00685 
00686   if (onlineMode_ && nthlumi < nextlumi_) return;
00687   const edm::TimeValue_t fendtimestamp = lumiSeg.endTime().value();
00688   const std::time_t fendtime = fendtimestamp >> 32;
00689   tmpTime = refBStime[1] = refPVtime[1] = fendtime;
00690 }
00691 
00692 //--------------------------------------------------------
00693 void BeamMonitor::FitAndFill(const LuminosityBlock& lumiSeg,int &lastlumi,int &nextlumi,int &nthlumi){
00694   if (onlineMode_ && (nthlumi <= nextlumi)) return;
00695 
00696   //set the correct run number when no event in the LS for fake output
00697   if((processed_) && theBeamFitter->getRunNumber() != frun)theBeamFitter->setRun(frun);
00698 
00699   int currentlumi = nextlumi;
00700   edm::LogInfo("BeamMonitor") << "FitAndFill::  Lumi of the current fit: " << currentlumi << endl;
00701   lastlumi = currentlumi;
00702   endLumiOfBSFit_ = currentlumi;
00703   endLumiOfPVFit_ = currentlumi;
00704 
00705 
00706      //---------Fix for Runninv average-------------
00707       mapLSPVStoreSize[countLumi_]= theBeamFitter->getPVvectorSize();
00708 
00709       if(StartAverage_)
00710       {
00711         std::map<int, std::size_t>::iterator rmLSPVi = mapLSPVStoreSize.begin();
00712         size_t SizeToRemovePV= rmLSPVi->second;
00713         for(std::map<int, std::size_t>::iterator rmLSPVe = mapLSPVStoreSize.end(); ++rmLSPVi != rmLSPVe;)
00714           rmLSPVi->second  -= SizeToRemovePV;
00715 
00716       theBeamFitter->resizePVvector(SizeToRemovePV);
00717 
00718       map<int, std::size_t >::iterator tmpItpv=mapLSPVStoreSize.begin();
00719       mapLSPVStoreSize.erase(tmpItpv);
00720       }
00721       if(debug_)edm::LogInfo("BeamMonitor") << "FitAndFill:: Size of thePVvector After removing the PVs = " << theBeamFitter->getPVvectorSize()<<endl;
00722 
00723 
00724       //lets filt the PV for GUI here: It was in analyzer in preivous versiton but moved here due to absence of event in some lumis, works OK
00725       bool resetHistoFlag_=false;
00726       if((int)mapPVx.size() >= resetFitNLumi_ && (StartAverage_)){
00727       h_PVx[0]->Reset();
00728       h_PVy[0]->Reset();
00729       h_PVz[0]->Reset();
00730       h_nVtx_st->Reset();
00731       resetHistoFlag_ = true;
00732       }
00733 
00734       int MaxPVs = 0;
00735       int countEvtLastNLS_=0;
00736       int countTotPV_= 0;      
00737 
00738       std::map< int, std::vector<int> >::iterator mnpv=mapNPV.begin();
00739       std::map< int, std::vector<float> >::iterator mpv2=mapPVy.begin();
00740       std::map< int, std::vector<float> >::iterator mpv3=mapPVz.begin();
00741 
00742      for(std::map< int, std::vector<float> >::iterator mpv1=mapPVx.begin(); mpv1 != mapPVx.end(); ++mpv1, ++mpv2, ++mpv3, ++mnpv)
00743      {
00744         std::vector<float>::iterator mpvs2 = (mpv2->second).begin();
00745         std::vector<float>::iterator mpvs3 = (mpv3->second).begin();
00746       for(std::vector<float>::iterator mpvs1=(mpv1->second).begin(); mpvs1 !=(mpv1->second).end(); ++mpvs1, ++mpvs2, ++mpvs3){
00747         if(resetHistoFlag_)
00748             {h_PVx[0]->Fill( *mpvs1 ); //these histogram are reset after StartAverage_ flag is ON
00749              h_PVy[0]->Fill( *mpvs2 );
00750              h_PVz[0]->Fill( *mpvs3 );
00751             }
00752         }//loop over second 
00753    
00754        //Do the same here for nPV distr.
00755       for(std::vector<int>::iterator mnpvs = (mnpv->second).begin(); mnpvs != (mnpv->second).end(); ++mnpvs){
00756         if((*mnpvs > 0) && (resetHistoFlag_) )h_nVtx_st->Fill( (*mnpvs)*(1.0) );
00757          countEvtLastNLS_++;
00758          countTotPV_ += (*mnpvs);  
00759         if((*mnpvs) > MaxPVs) MaxPVs =  (*mnpvs);
00760        }//loop over second of mapNPV
00761 
00762      }//loop over last N lumis
00763 
00764      char tmpTitlePV[100];               
00765      sprintf(tmpTitlePV,"%s %i %s %i","Num. of reco. vertices for LS: ",beginLumiOfPVFit_," to ",endLumiOfPVFit_);   
00766      h_nVtx_st->setAxisTitle(tmpTitlePV,1);
00767 
00768      std::vector<float> DipPVInfo_;
00769      DipPVInfo_.clear();
00770 
00771    if(countTotPV_ != 0 ){
00772      DipPVInfo_.push_back((float)countEvtLastNLS_);
00773      DipPVInfo_.push_back(h_nVtx_st->getMean());
00774      DipPVInfo_.push_back(h_nVtx_st->getMeanError());
00775      DipPVInfo_.push_back(h_nVtx_st->getRMS());
00776      DipPVInfo_.push_back(h_nVtx_st->getRMSError());
00777      DipPVInfo_.push_back((float)MaxPVs);
00778      DipPVInfo_.push_back((float)countTotPV_);
00779      MaxPVs =0;
00780     }
00781    else{ for(size_t i= 0; i < 7; i++){if(i>0)DipPVInfo_.push_back(0.);
00782                                       else DipPVInfo_.push_back((float)countEvtLastNLS_);}
00783        }
00784      theBeamFitter->SetPVInfo(DipPVInfo_);      
00785      countEvtLastNLS_=0;
00786 
00787 
00788 
00789   if (onlineMode_) { // filling LS gap
00790     // FIXME: need to add protection for the case if the gap is at the resetting LS!
00791     const int countLS_bs = hs["x0_lumi"]->getTH1()->GetEntries();
00792     const int countLS_pv = hs["PVx_lumi"]->getTH1()->GetEntries();
00793     edm::LogInfo("BeamMonitor") << "FitAndFill:: countLS_bs = " << countLS_bs << " ; countLS_pv = " << countLS_pv << std::endl;
00794     int LSgap_bs = currentlumi/fitNLumi_ - countLS_bs;
00795     int LSgap_pv = currentlumi/fitPVNLumi_ - countLS_pv;
00796     if (currentlumi%fitNLumi_ == 0)
00797       LSgap_bs--;
00798     if (currentlumi%fitPVNLumi_ == 0)
00799       LSgap_pv--;
00800     edm::LogInfo("BeamMonitor") << "FitAndFill::  LSgap_bs = " << LSgap_bs << " ; LSgap_pv = " << LSgap_pv << std::endl;
00801     // filling previous fits if LS gap ever exists
00802     for (int ig = 0; ig < LSgap_bs; ig++) {
00803       hs["x0_lumi"]->ShiftFillLast( 0., 0., fitNLumi_ );//x0 , x0err, fitNLumi_;  see DQMCore....
00804       hs["y0_lumi"]->ShiftFillLast( 0., 0., fitNLumi_ );
00805       hs["z0_lumi"]->ShiftFillLast( 0., 0., fitNLumi_ );
00806       hs["sigmaX0_lumi"]->ShiftFillLast( 0., 0., fitNLumi_ );
00807       hs["sigmaY0_lumi"]->ShiftFillLast( 0., 0., fitNLumi_ );
00808       hs["sigmaZ0_lumi"]->ShiftFillLast( 0., 0., fitNLumi_ );
00809     }
00810     for (int ig = 0; ig < LSgap_pv; ig++) {
00811       hs["PVx_lumi"]->ShiftFillLast( 0., 0., fitPVNLumi_ );
00812       hs["PVy_lumi"]->ShiftFillLast( 0., 0., fitPVNLumi_ );
00813       hs["PVz_lumi"]->ShiftFillLast( 0., 0., fitPVNLumi_ );
00814     }
00815     const int previousLS = h_nTrk_lumi->getTH1()->GetEntries();
00816     for (int i=1;i < (currentlumi - previousLS);i++)//if (current-previoius)= 1 then never go inside the for loop!!!!!!!!!!!
00817       h_nTrk_lumi->ShiftFillLast(nthBSTrk_);
00818   }
00819 
00820   edm::LogInfo("BeamMonitor") << "FitAndFill:: Time lapsed since last scroll = " << tmpTime - refTime << std:: endl;
00821 
00822   if (testScroll(tmpTime,refTime)) {
00823     scrollTH1(hs["x0_time"]->getTH1(),refTime);
00824     scrollTH1(hs["y0_time"]->getTH1(),refTime);
00825     scrollTH1(hs["z0_time"]->getTH1(),refTime);
00826     scrollTH1(hs["sigmaX0_time"]->getTH1(),refTime);
00827     scrollTH1(hs["sigmaY0_time"]->getTH1(),refTime);
00828     scrollTH1(hs["sigmaZ0_time"]->getTH1(),refTime);
00829     scrollTH1(hs["PVx_time"]->getTH1(),refTime);
00830     scrollTH1(hs["PVy_time"]->getTH1(),refTime);
00831     scrollTH1(hs["PVz_time"]->getTH1(),refTime);
00832   }
00833 
00834   bool doPVFit = false;
00835 
00836   if (fitPVNLumi_ > 0) {
00837     if (onlineMode_) {
00838       if (currentlumi%fitPVNLumi_ == 0)
00839         doPVFit = true;
00840     }
00841     else
00842       if (countLumi_%fitPVNLumi_ == 0)
00843         doPVFit = true;
00844   }
00845   else
00846     doPVFit = true;
00847 
00848 
00849   if (doPVFit) {
00850     edm::LogInfo("BeamMonitor") << "FitAndFill:: Do PV Fitting for LS = " << beginLumiOfPVFit_ << " to " << endLumiOfPVFit_ << std::endl;
00851     // Primary Vertex Fit:
00852     if (h_PVx[0]->getTH1()->GetEntries() > minNrVertices_) {
00853 
00854       pvResults->Reset();
00855       char tmpTitle[50];
00856       sprintf(tmpTitle,"%s %i %s %i","Fitted Primary Vertex (cm) of LS: ",beginLumiOfPVFit_," to ",endLumiOfPVFit_);
00857       pvResults->setAxisTitle(tmpTitle,1);
00858 
00859       TF1 *fgaus = new TF1("fgaus","gaus");
00860       double mean,width,meanErr,widthErr;
00861       fgaus->SetLineColor(4);
00862       h_PVx[0]->getTH1()->Fit("fgaus","QLM0");
00863       mean = fgaus->GetParameter(1);
00864       width = fgaus->GetParameter(2);
00865       meanErr = fgaus->GetParError(1);
00866       widthErr = fgaus->GetParError(2);
00867 
00868 
00869       hs["PVx_lumi"]->ShiftFillLast(mean,width,fitPVNLumi_);
00870       hs["PVx_lumi_all"]->setBinContent(currentlumi,mean);
00871       hs["PVx_lumi_all"]->setBinError(currentlumi,width);
00872       int nthBin = tmpTime - refTime;
00873       if (nthBin < 0)
00874         edm::LogInfo("BeamMonitor") << "FitAndFill::  Event time outside current range of time histograms!" << std::endl;
00875       if (nthBin > 0) {
00876         hs["PVx_time"]->setBinContent(nthBin,mean);
00877         hs["PVx_time"]->setBinError(nthBin,width);
00878       }
00879       int jthBin = tmpTime - startTime;
00880       if (jthBin > 0) {
00881         hs["PVx_time_all"]->setBinContent(jthBin,mean);
00882         hs["PVx_time_all"]->setBinError(jthBin,width);
00883       }
00884       pvResults->setBinContent(1,6,mean);
00885       pvResults->setBinContent(1,3,width);
00886       pvResults->setBinContent(2,6,meanErr);
00887       pvResults->setBinContent(2,3,widthErr);
00888 
00889       dbe_->setCurrentFolder(monitorName_+"PrimaryVertex/");
00890       const char* tmpfile;
00891       TH1D * tmphisto;
00892       // snap shot of the fit
00893       tmpfile= (h_PVx[1]->getName()).c_str();
00894       tmphisto = static_cast<TH1D *>((h_PVx[0]->getTH1())->Clone("tmphisto"));
00895       h_PVx[1]->getTH1()->SetBins(tmphisto->GetNbinsX(),tmphisto->GetXaxis()->GetXmin(),tmphisto->GetXaxis()->GetXmax());
00896       h_PVx[1] = dbe_->book1D(tmpfile,h_PVx[0]->getTH1F());
00897       h_PVx[1]->getTH1()->Fit("fgaus","QLM");
00898 
00899 
00900       h_PVy[0]->getTH1()->Fit("fgaus","QLM0");
00901       mean = fgaus->GetParameter(1);
00902       width = fgaus->GetParameter(2);
00903       meanErr = fgaus->GetParError(1);
00904       widthErr = fgaus->GetParError(2);
00905       hs["PVy_lumi"]->ShiftFillLast(mean,width,fitPVNLumi_);
00906       hs["PVy_lumi_all"]->setBinContent(currentlumi,mean);
00907       hs["PVy_lumi_all"]->setBinError(currentlumi,width);
00908       if (nthBin > 0) {
00909         hs["PVy_time"]->setBinContent(nthBin,mean);
00910         hs["PVy_time"]->setBinError(nthBin,width);
00911       }
00912       if (jthBin > 0) {
00913         hs["PVy_time_all"]->setBinContent(jthBin,mean);
00914         hs["PVy_time_all"]->setBinError(jthBin,width);
00915       }
00916       pvResults->setBinContent(1,5,mean);
00917       pvResults->setBinContent(1,2,width);
00918       pvResults->setBinContent(2,5,meanErr);
00919       pvResults->setBinContent(2,2,widthErr);
00920       // snap shot of the fit
00921       tmpfile= (h_PVy[1]->getName()).c_str();
00922       tmphisto = static_cast<TH1D *>((h_PVy[0]->getTH1())->Clone("tmphisto"));
00923       h_PVy[1]->getTH1()->SetBins(tmphisto->GetNbinsX(),tmphisto->GetXaxis()->GetXmin(),tmphisto->GetXaxis()->GetXmax());
00924       h_PVy[1]->update();
00925       h_PVy[1] = dbe_->book1D(tmpfile,h_PVy[0]->getTH1F());
00926       h_PVy[1]->getTH1()->Fit("fgaus","QLM");
00927 
00928 
00929       h_PVz[0]->getTH1()->Fit("fgaus","QLM0");
00930       mean = fgaus->GetParameter(1);
00931       width = fgaus->GetParameter(2);
00932       meanErr = fgaus->GetParError(1);
00933       widthErr = fgaus->GetParError(2);
00934       hs["PVz_lumi"]->ShiftFillLast(mean,width,fitPVNLumi_);
00935       hs["PVz_lumi_all"]->setBinContent(currentlumi,mean);
00936       hs["PVz_lumi_all"]->setBinError(currentlumi,width);
00937       if (nthBin > 0) {
00938         hs["PVz_time"]->setBinContent(nthBin,mean);
00939         hs["PVz_time"]->setBinError(nthBin,width);
00940       }
00941       if (jthBin > 0) {
00942         hs["PVz_time_all"]->setBinContent(jthBin,mean);
00943         hs["PVz_time_all"]->setBinError(jthBin,width);
00944       }
00945       pvResults->setBinContent(1,4,mean);
00946       pvResults->setBinContent(1,1,width);
00947       pvResults->setBinContent(2,4,meanErr);
00948       pvResults->setBinContent(2,1,widthErr);
00949       // snap shot of the fit
00950       tmpfile= (h_PVz[1]->getName()).c_str();
00951       tmphisto = static_cast<TH1D *>((h_PVz[0]->getTH1())->Clone("tmphisto"));
00952       h_PVz[1]->getTH1()->SetBins(tmphisto->GetNbinsX(),tmphisto->GetXaxis()->GetXmin(),tmphisto->GetXaxis()->GetXmax());
00953       h_PVz[1]->update();
00954       h_PVz[1] = dbe_->book1D(tmpfile,h_PVz[0]->getTH1F());
00955       h_PVz[1]->getTH1()->Fit("fgaus","QLM");
00956 
00957     }//check if found min Vertices
00958   }//do PVfit
00959 
00960   if ((resetPVNLumi_ > 0 && countLumi_ == resetPVNLumi_) || StartAverage_){
00961     beginLumiOfPVFit_=0;
00962     refPVtime[0] = 0;
00963     }
00964 
00965 
00966 
00967 
00968      //---------Readjustment of theBSvector, RefTime, beginLSofFit---------
00969      vector<BSTrkParameters> theBSvector1 = theBeamFitter->getBSvector();
00970      mapLSBSTrkSize[countLumi_]= (theBSvector1.size());
00971       size_t PreviousRecords=0;     //needed to fill nth record of tracks in GUI
00972 
00973       if(StartAverage_){
00974       size_t SizeToRemove=0;
00975       std::map<int, std::size_t>::iterator rmls=mapLSBSTrkSize.begin();
00976       SizeToRemove = rmls->second;
00977       if(debug_)edm::LogInfo("BeamMonitor")<< "  The size to remove is =  "<< SizeToRemove << endl;
00978       int changedAfterThis=0;
00979       for(std::map<int, std::size_t>::iterator rmLS = mapLSBSTrkSize.begin(); rmLS!=mapLSBSTrkSize.end(); ++rmLS, ++changedAfterThis){
00980          if(changedAfterThis > 0 ){(rmLS->second)  = (rmLS->second)-SizeToRemove;
00981                                     if((mapLSBSTrkSize.size()- (size_t)changedAfterThis) == 2 )PreviousRecords = (rmLS->second);
00982                                   } }
00983 
00984       theBeamFitter->resizeBSvector(SizeToRemove);
00985 
00986       map<int, std::size_t >::iterator tmpIt=mapLSBSTrkSize.begin();
00987       mapLSBSTrkSize.erase(tmpIt);
00988 
00989       std::pair<int,int> checkfitLS = theBeamFitter->getFitLSRange();
00990       std::pair<time_t,time_t> checkfitTime =theBeamFitter->getRefTime();
00991       theBeamFitter->setFitLSRange(beginLumiOfBSFit_, checkfitLS.second);
00992       theBeamFitter->setRefTime(refBStime[0], checkfitTime.second);
00993       }
00994 
00995       //Fill the track for this fit
00996       vector<BSTrkParameters> theBSvector = theBeamFitter->getBSvector();
00997       h_nTrk_lumi->ShiftFillLast( theBSvector.size() );
00998 
00999       if(debug_)edm::LogInfo("BeamMonitor")<< "FitAndFill::   Size of  theBSViector.size()  After =" << theBSvector.size() << endl;
01000 
01001 
01002 
01003   bool countFitting = false;
01004   if (theBSvector.size() >= PreviousRecords  && theBSvector.size() >= min_Ntrks_) {
01005       countFitting = true;
01006      }
01007 
01008 
01009    //---Fix for Cut Flow Table for Running average in a same way//the previous code  has problem for resetting!!!
01010    mapLSCF[countLumi_] = *theBeamFitter->getCutFlow();
01011    if(StartAverage_ && mapLSCF.size()){
01012      const TH1F& cutFlowToSubtract = mapLSCF.begin()->second;
01013      // Subtract the last cut flow from all of the others.
01014      std::map<int, TH1F>::iterator cf = mapLSCF.begin();
01015      // Start on second entry
01016      for(; cf != mapLSCF.end(); ++cf) {
01017        cf->second.Add(&cutFlowToSubtract, -1);
01018      }
01019      theBeamFitter->subtractFromCutFlow(&cutFlowToSubtract);
01020      // Remove the obsolete lumi section
01021      mapLSCF.erase(mapLSCF.begin());
01022    }
01023 
01024   if (resetHistos_) {
01025     h_d0_phi0->Reset();
01026     h_vx_vy->Reset();
01027     h_vx_dz->Reset();
01028     h_vy_dz->Reset();
01029     h_trk_z0->Reset();
01030     resetHistos_ = false;
01031   }
01032 
01033   if(StartAverage_) nthBSTrk_  = PreviousRecords; //after average proccess is ON//for 2-6 LS fit PreviousRecords is size from 2-5 LS
01034 
01035   edm::LogInfo("BeamMonitor")<<" The Previous Recored for this fit is  ="<<nthBSTrk_<<endl;
01036 
01037   unsigned int itrk = 0;
01038   for (vector<BSTrkParameters>::const_iterator BSTrk = theBSvector.begin();
01039        BSTrk != theBSvector.end();  ++BSTrk, ++itrk){
01040     if (itrk >= nthBSTrk_){//fill for this record only !!
01041       h_d0_phi0->Fill( BSTrk->phi0(), BSTrk->d0() );
01042       double vx = BSTrk->vx();
01043       double vy = BSTrk->vy();
01044       double z0 = BSTrk->z0();
01045       h_vx_vy->Fill( vx, vy );
01046       h_vx_dz->Fill( z0, vx );
01047       h_vy_dz->Fill( z0, vy );
01048       h_trk_z0->Fill( z0 );
01049      }
01050   }
01051 
01052 
01053    nthBSTrk_ = theBSvector.size(); // keep track of num of tracks filled so far
01054 
01055    edm::LogInfo("BeamMonitor")<<" The Current Recored for this fit is  ="<<nthBSTrk_<<endl;
01056 
01057   if (countFitting) edm::LogInfo("BeamMonitor") << "FitAndFill::  Num of tracks collected = " << nthBSTrk_ << endl;
01058 
01059 
01060   if (fitNLumi_ > 0) {
01061     if (onlineMode_){
01062       if (currentlumi%fitNLumi_!=0) {
01063 //      for (std::map<TString,MonitorElement*>::iterator itAll = hs.begin();
01064 //           itAll != hs.end(); ++itAll) {
01065 //        if ((*itAll).first.Contains("all")) {
01066 //          (*itAll).second->setBinContent(currentlumi,0.);
01067 //          (*itAll).second->setBinError(currentlumi,0.);
01068 //        }
01069 //      }
01070         return;
01071       }
01072     }
01073     else
01074       if (countLumi_%fitNLumi_!=0) return;
01075   }
01076 
01077   edm::LogInfo("BeamMonitor") << "FitAndFill:: [DebugTime] refBStime[0] = " << refBStime[0]
01078                               << "; address =  " << &refBStime[0] << std::endl;
01079   edm::LogInfo("BeamMonitor") << "FitAndFill:: [DebugTime] refBStime[1] = " << refBStime[1]
01080                               << "; address =  " << &refBStime[1] << std::endl;
01081 
01082   if (countFitting) {
01083     nFits_++;
01084     std::pair<int,int> fitLS = theBeamFitter->getFitLSRange();
01085     edm::LogInfo("BeamMonitor") << "FitAndFill::  [BeamFitter] Do BeamSpot Fit for LS = " << fitLS.first << " to " << fitLS.second << std::endl;
01086     edm::LogInfo("BeamMonitor") << "FitAndFill::  [BeamMonitor] Do BeamSpot Fit for LS = " << beginLumiOfBSFit_ << " to " << endLumiOfBSFit_ << std::endl;
01087 
01088     //Now Run the PV and Track Fitter over the collected tracks and pvs
01089     if (theBeamFitter->runPVandTrkFitter()) {
01090       reco::BeamSpot bs = theBeamFitter->getBeamSpot();
01091       if (bs.type() > 0) // with good beamwidth fit
01092         preBS = bs; // cache good fit results
01093 
01094       edm::LogInfo("BeamMonitor") << "\n RESULTS OF DEFAULT FIT:" << endl;
01095       edm::LogInfo("BeamMonitor") << bs << endl;
01096       edm::LogInfo("BeamMonitor") << "[BeamFitter] fitting done \n" << endl;
01097 
01098       hs["x0_lumi"]->ShiftFillLast( bs.x0(), bs.x0Error(), fitNLumi_ );
01099       hs["y0_lumi"]->ShiftFillLast( bs.y0(), bs.y0Error(), fitNLumi_ );
01100       hs["z0_lumi"]->ShiftFillLast( bs.z0(), bs.z0Error(), fitNLumi_ );
01101       hs["sigmaX0_lumi"]->ShiftFillLast( bs.BeamWidthX(), bs.BeamWidthXError(), fitNLumi_ );
01102       hs["sigmaY0_lumi"]->ShiftFillLast( bs.BeamWidthY(), bs.BeamWidthYError(), fitNLumi_ );
01103       hs["sigmaZ0_lumi"]->ShiftFillLast( bs.sigmaZ(), bs.sigmaZ0Error(), fitNLumi_ );
01104       hs["x0_lumi_all"]->setBinContent(currentlumi,bs.x0());
01105       hs["x0_lumi_all"]->setBinError(currentlumi,bs.x0Error());
01106       hs["y0_lumi_all"]->setBinContent(currentlumi,bs.y0());
01107       hs["y0_lumi_all"]->setBinError(currentlumi,bs.y0Error());
01108       hs["z0_lumi_all"]->setBinContent(currentlumi,bs.z0());
01109       hs["z0_lumi_all"]->setBinError(currentlumi,bs.z0Error());
01110       hs["sigmaX0_lumi_all"]->setBinContent(currentlumi, bs.BeamWidthX());
01111       hs["sigmaX0_lumi_all"]->setBinError(currentlumi, bs.BeamWidthXError());
01112       hs["sigmaY0_lumi_all"]->setBinContent(currentlumi, bs.BeamWidthY());
01113       hs["sigmaY0_lumi_all"]->setBinError(currentlumi, bs.BeamWidthYError());
01114       hs["sigmaZ0_lumi_all"]->setBinContent(currentlumi, bs.sigmaZ());
01115       hs["sigmaZ0_lumi_all"]->setBinError(currentlumi, bs.sigmaZ0Error());
01116 
01117       int nthBin = tmpTime - refTime;
01118       if (nthBin > 0) {
01119         hs["x0_time"]->setBinContent(nthBin, bs.x0());
01120         hs["y0_time"]->setBinContent(nthBin, bs.y0());
01121         hs["z0_time"]->setBinContent(nthBin, bs.z0());
01122         hs["sigmaX0_time"]->setBinContent(nthBin, bs.BeamWidthX());
01123         hs["sigmaY0_time"]->setBinContent(nthBin, bs.BeamWidthY());
01124         hs["sigmaZ0_time"]->setBinContent(nthBin, bs.sigmaZ());
01125         hs["x0_time"]->setBinError(nthBin, bs.x0Error());
01126         hs["y0_time"]->setBinError(nthBin, bs.y0Error());
01127         hs["z0_time"]->setBinError(nthBin, bs.z0Error());
01128         hs["sigmaX0_time"]->setBinError(nthBin, bs.BeamWidthXError());
01129         hs["sigmaY0_time"]->setBinError(nthBin, bs.BeamWidthYError());
01130         hs["sigmaZ0_time"]->setBinError(nthBin, bs.sigmaZ0Error());
01131       }
01132 
01133       int jthBin = tmpTime - startTime;
01134       if (jthBin > 0) {
01135         hs["x0_time_all"]->setBinContent(jthBin, bs.x0());
01136         hs["y0_time_all"]->setBinContent(jthBin, bs.y0());
01137         hs["z0_time_all"]->setBinContent(jthBin, bs.z0());
01138         hs["sigmaX0_time_all"]->setBinContent(jthBin, bs.BeamWidthX());
01139         hs["sigmaY0_time_all"]->setBinContent(jthBin, bs.BeamWidthY());
01140         hs["sigmaZ0_time_all"]->setBinContent(jthBin, bs.sigmaZ());
01141         hs["x0_time_all"]->setBinError(jthBin, bs.x0Error());
01142         hs["y0_time_all"]->setBinError(jthBin, bs.y0Error());
01143         hs["z0_time_all"]->setBinError(jthBin, bs.z0Error());
01144         hs["sigmaX0_time_all"]->setBinError(jthBin, bs.BeamWidthXError());
01145         hs["sigmaY0_time_all"]->setBinError(jthBin, bs.BeamWidthYError());
01146         hs["sigmaZ0_time_all"]->setBinError(jthBin, bs.sigmaZ0Error());
01147       }
01148 
01149       h_x0->Fill( bs.x0());
01150       h_y0->Fill( bs.y0());
01151       h_z0->Fill( bs.z0());
01152       if (bs.type() > 0) { // with good beamwidth fit
01153         h_sigmaX0->Fill( bs.BeamWidthX());
01154         h_sigmaY0->Fill( bs.BeamWidthY());
01155       }
01156       h_sigmaZ0->Fill( bs.sigmaZ());
01157 
01158       if (nthBSTrk_ >= 2*min_Ntrks_) {
01159         double amp = std::sqrt(bs.x0()*bs.x0()+bs.y0()*bs.y0());
01160         double alpha = std::atan2(bs.y0(),bs.x0());
01161         TF1 *f1 = new TF1("f1","[0]*sin(x-[1])",-3.14,3.14);
01162         f1->SetParameters(amp,alpha);
01163         f1->SetParLimits(0,amp-0.1,amp+0.1);
01164         f1->SetParLimits(1,alpha-0.577,alpha+0.577);
01165         f1->SetLineColor(4);
01166         h_d0_phi0->getTProfile()->Fit("f1","QR");
01167 
01168         double mean = bs.z0();
01169         double width = bs.sigmaZ();
01170         TF1 *fgaus = new TF1("fgaus","gaus");
01171         fgaus->SetParameters(mean,width);
01172         fgaus->SetLineColor(4);
01173         h_trk_z0->getTH1()->Fit("fgaus","QLRM","",mean-3*width,mean+3*width);
01174       }
01175 
01176       fitResults->Reset();
01177       std::pair<int,int> LSRange = theBeamFitter->getFitLSRange();
01178       char tmpTitle[50];
01179       sprintf(tmpTitle,"%s %i %s %i","Fitted Beam Spot (cm) of LS: ",LSRange.first," to ",LSRange.second);
01180       fitResults->setAxisTitle(tmpTitle,1);
01181       fitResults->setBinContent(1,8,bs.x0());
01182       fitResults->setBinContent(1,7,bs.y0());
01183       fitResults->setBinContent(1,6,bs.z0());
01184       fitResults->setBinContent(1,5,bs.sigmaZ());
01185       fitResults->setBinContent(1,4,bs.dxdz());
01186       fitResults->setBinContent(1,3,bs.dydz());
01187       if (bs.type() > 0) { // with good beamwidth fit
01188         fitResults->setBinContent(1,2,bs.BeamWidthX());
01189         fitResults->setBinContent(1,1,bs.BeamWidthY());
01190       }
01191       else { // fill cached widths
01192         fitResults->setBinContent(1,2,preBS.BeamWidthX());
01193         fitResults->setBinContent(1,1,preBS.BeamWidthY());
01194       }
01195 
01196       fitResults->setBinContent(2,8,bs.x0Error());
01197       fitResults->setBinContent(2,7,bs.y0Error());
01198       fitResults->setBinContent(2,6,bs.z0Error());
01199       fitResults->setBinContent(2,5,bs.sigmaZ0Error());
01200       fitResults->setBinContent(2,4,bs.dxdzError());
01201       fitResults->setBinContent(2,3,bs.dydzError());
01202       if (bs.type() > 0) { // with good beamwidth fit
01203         fitResults->setBinContent(2,2,bs.BeamWidthXError());
01204         fitResults->setBinContent(2,1,bs.BeamWidthYError());
01205       }
01206       else { // fill cached width errors
01207         fitResults->setBinContent(2,2,preBS.BeamWidthXError());
01208         fitResults->setBinContent(2,1,preBS.BeamWidthYError());
01209       }
01210 
01211       // count good fit
01212       //     if (std::fabs(refBS.x0()-bs.x0())/bs.x0Error() < deltaSigCut_) { // disabled temporarily
01213       summaryContent_[0] += 1.;
01214       //     }
01215       //     if (std::fabs(refBS.y0()-bs.y0())/bs.y0Error() < deltaSigCut_) { // disabled temporarily
01216       summaryContent_[1] += 1.;
01217       //     }
01218       //     if (std::fabs(refBS.z0()-bs.z0())/bs.z0Error() < deltaSigCut_) { // disabled temporarily
01219       summaryContent_[2] += 1.;
01220       //     }
01221 
01222     } //if (theBeamFitter->runPVandTrkFitter())
01223     else { // beam fit fails
01224       reco::BeamSpot bs = theBeamFitter->getBeamSpot();
01225       edm::LogInfo("BeamMonitor") << "FitAndFill::   [BeamMonitor] Beam fit fails!!! \n" << endl;
01226       edm::LogInfo("BeamMonitor") << "FitAndFill::   [BeamMonitor] Output beam spot for DIP \n" << endl;
01227       edm::LogInfo("BeamMonitor") << bs << endl;
01228 
01229       hs["sigmaX0_lumi"]->ShiftFillLast( bs.BeamWidthX(), bs.BeamWidthXError(), fitNLumi_ );
01230       hs["sigmaY0_lumi"]->ShiftFillLast( bs.BeamWidthY(), bs.BeamWidthYError(), fitNLumi_ );
01231       hs["sigmaZ0_lumi"]->ShiftFillLast( bs.sigmaZ(), bs.sigmaZ0Error(), fitNLumi_ );
01232       hs["x0_lumi"]->ShiftFillLast( bs.x0(), bs.x0Error(), fitNLumi_ );
01233       hs["y0_lumi"]->ShiftFillLast( bs.y0(), bs.y0Error(), fitNLumi_ );
01234       hs["z0_lumi"]->ShiftFillLast( bs.z0(), bs.z0Error(), fitNLumi_ );
01235     } // end of beam fit fails
01236 
01237 
01238   } //-------- end of countFitting------------------------------------------
01239  else { // no fit
01240     // Overwrite Fit LS and fit time when no event processed or no track selected
01241     theBeamFitter->setFitLSRange(beginLumiOfBSFit_,endLumiOfBSFit_);
01242     theBeamFitter->setRefTime(refBStime[0],refBStime[1]);
01243     if (theBeamFitter->runPVandTrkFitter()) {} // Dump fake beam spot for DIP
01244     reco::BeamSpot bs = theBeamFitter->getBeamSpot();
01245     edm::LogInfo("BeamMonitor") << "FitAndFill::  [BeamMonitor] No fitting \n" << endl;
01246     edm::LogInfo("BeamMonitor") << "FitAndFill::  [BeamMonitor] Output fake beam spot for DIP \n" << endl;
01247     edm::LogInfo("BeamMonitor") << bs << endl;
01248 
01249     hs["sigmaX0_lumi"]->ShiftFillLast( bs.BeamWidthX(), bs.BeamWidthXError(), fitNLumi_ );
01250     hs["sigmaY0_lumi"]->ShiftFillLast( bs.BeamWidthY(), bs.BeamWidthYError(), fitNLumi_ );
01251     hs["sigmaZ0_lumi"]->ShiftFillLast( bs.sigmaZ(), bs.sigmaZ0Error(), fitNLumi_ );
01252     hs["x0_lumi"]->ShiftFillLast( bs.x0(), bs.x0Error(), fitNLumi_ );
01253     hs["y0_lumi"]->ShiftFillLast( bs.y0(), bs.y0Error(), fitNLumi_ );
01254     hs["z0_lumi"]->ShiftFillLast( bs.z0(), bs.z0Error(), fitNLumi_ );
01255   }
01256 
01257 
01258 
01259   // Fill summary report
01260   if (countFitting) {
01261     for (int n = 0; n < nFitElements_; n++) {
01262       reportSummaryContents[n]->Fill( summaryContent_[n] / (float)nFits_ );
01263     }
01264 
01265     summarySum_ = 0;
01266     for (int ii = 0; ii < nFitElements_; ii++) {
01267       summarySum_ += summaryContent_[ii];
01268     }
01269     reportSummary_ = summarySum_ / (nFitElements_ * nFits_);
01270     if (reportSummary) reportSummary->Fill(reportSummary_);
01271 
01272     for ( int bi = 0; bi < nFitElements_ ; bi++) {
01273       reportSummaryMap->setBinContent(1,bi+1,summaryContent_[bi] / (float)nFits_);
01274     }
01275   }
01276 
01277 
01278 
01279 
01280   if ( ( resetFitNLumi_ > 0 &&
01281         ((onlineMode_ && countLumi_==resetFitNLumi_ ) ||  //OR it should be currentLumi_ (if in sequence then does not mattar)
01282         (!onlineMode_ && countLumi_==resetFitNLumi_ ))
01283        )  || (StartAverage_) ){
01284 
01285     edm::LogInfo("BeamMonitor") << "FitAndFill:: The flag is ON for running average Beam Spot fit"<<endl;
01286     StartAverage_    = true;
01287     firstAverageFit_++;
01288     resetHistos_     = true;
01289     nthBSTrk_        = 0;
01290     beginLumiOfBSFit_= 0;
01291     refBStime[0]     = 0;
01292 
01293     }
01294 
01295 
01296 
01297 }
01298 
01299 //--------------------------------------------------------
01300 void BeamMonitor::RestartFitting(){
01301  if(debug_)edm::LogInfo("BeamMonitor") << " RestartingFitting:: Restart Beami everything to a fresh start !!! because Gap is > 10 LS" <<endl;
01302                                                 //track based fit reset here
01303                                                 resetHistos_ = true;
01304                                                 nthBSTrk_ = 0;
01305                                                 theBeamFitter->resetTrkVector();
01306                                                 theBeamFitter->resetLSRange();
01307                                                 theBeamFitter->resetRefTime();
01308                                                 theBeamFitter->resetPVFitter();
01309                                                 theBeamFitter->resetCutFlow();
01310                                                 beginLumiOfBSFit_ = 0;
01311                                                 refBStime[0] = 0;
01312                                                 //pv based fit iis reset here
01313                                                 h_PVx[0]->Reset();
01314                                                 h_PVy[0]->Reset();
01315                                                 h_PVz[0]->Reset();
01316                                                 beginLumiOfPVFit_ = 0;
01317                                                 refPVtime[0] = 0;
01318                                                 //Clear all the Maps here
01319                                                 mapPVx.clear();
01320                                                 mapPVy.clear();
01321                                                 mapPVz.clear();
01322                                                 mapNPV.clear();
01323                                                 mapBeginBSLS.clear();
01324                                                 mapBeginPVLS.clear();
01325                                                 mapBeginBSTime.clear();
01326                                                 mapBeginPVTime.clear();
01327                                                 mapLSBSTrkSize.clear();
01328                                                 mapLSPVStoreSize.clear();
01329                                                 mapLSCF.clear(); countGapLumi_=0; countLumi_=0; StartAverage_=false;
01330 
01331 }
01332 
01333 //-------------------------------------------------------
01334 void BeamMonitor::endRun(const Run& r, const EventSetup& context){
01335 
01336 if(debug_)edm::LogInfo("BeamMonitor") << "endRun:: Clearing all the Maps "<<endl;
01337 //Clear all the Maps here
01338 mapPVx.clear();
01339 mapPVy.clear();
01340 mapPVz.clear();
01341 mapNPV.clear();
01342 mapBeginBSLS.clear();
01343 mapBeginPVLS.clear();
01344 mapBeginBSTime.clear();
01345 mapBeginPVTime.clear();
01346 mapLSBSTrkSize.clear();
01347 mapLSPVStoreSize.clear();
01348 mapLSCF.clear();
01349 
01350 
01351 }
01352 
01353 //--------------------------------------------------------
01354 void BeamMonitor::endJob(const LuminosityBlock& lumiSeg,
01355                          const EventSetup& iSetup){
01356   if (!onlineMode_) endLuminosityBlock(lumiSeg, iSetup);
01357 }
01358 
01359 //--------------------------------------------------------
01360 void BeamMonitor::scrollTH1(TH1 * h, time_t ref) {
01361   const char* offsetTime = formatFitTime(ref);
01362   TDatime da(offsetTime);
01363   if (lastNZbin > 0) {
01364     double val = h->GetBinContent(lastNZbin);
01365     double valErr = h->GetBinError(lastNZbin);
01366     h->Reset();
01367     h->GetXaxis()->SetTimeOffset(da.Convert(kTRUE));
01368     int bin = (lastNZbin > buffTime ? buffTime : 1);
01369     h->SetBinContent(bin,val);
01370     h->SetBinError(bin,valErr);
01371   }
01372   else {
01373     h->Reset();
01374     h->GetXaxis()->SetTimeOffset(da.Convert(kTRUE));
01375   }
01376 }
01377 
01378 //--------------------------------------------------------
01379 // Method to check whether to chane histogram time offset (forward only)
01380 bool BeamMonitor::testScroll(time_t & tmpTime_, time_t & refTime_){
01381   bool scroll_ = false;
01382   if (tmpTime_ - refTime_ >= intervalInSec_) {
01383     scroll_ = true;
01384     edm::LogInfo("BeamMonitor") << "testScroll::  Reset Time Offset" << std::endl;
01385     lastNZbin = intervalInSec_;
01386     for (int bin = intervalInSec_; bin >= 1; bin--) {
01387       if (hs["x0_time"]->getBinContent(bin) > 0) {
01388         lastNZbin = bin;
01389         break;
01390       }
01391     }
01392     edm::LogInfo("BeamMonitor") << "testScroll::  Last non zero bin = " << lastNZbin << std::endl;
01393     if (tmpTime_ - refTime_ >= intervalInSec_ + lastNZbin) {
01394       edm::LogInfo("BeamMonitor") << "testScroll::  Time difference too large since last readout" << std::endl;
01395       lastNZbin = 0;
01396       refTime_ = tmpTime_ - buffTime;
01397     }
01398     else{
01399       edm::LogInfo("BeamMonitor") << "testScroll::  Offset to last record" << std::endl;
01400       int offset = ((lastNZbin > buffTime) ? (lastNZbin - buffTime) : (lastNZbin - 1));
01401       refTime_ += offset;
01402     }
01403   }
01404   return scroll_;
01405 }
01406 
01407 DEFINE_FWK_MODULE(BeamMonitor);