CMS 3D CMS Logo

/data/doxygen/doxygen-1.7.3/gen/CMSSW_4_2_8/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: 2011/05/12 11:46:55 $
00006  * $Revision: 1.72 $
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 = 2011;
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",20,-0.5,19.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",20,-0.5,19.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(0./0.);
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(0./0.);
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     if (nPVcount> 0 )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_){ if (nPVcount_ST>0 ) 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       size_t SizeToRemovePV=0;
00712       std::map<int, std::size_t>::iterator rmlspv = mapLSPVStoreSize.begin();
00713       SizeToRemovePV= rmlspv->second;
00714       int changedAfterThisPV=0;
00715       for(std::map<int, std::size_t>::iterator rmLSPV = mapLSPVStoreSize.begin(); rmLSPV!=mapLSPVStoreSize.end(); ++rmLSPV, ++changedAfterThisPV){
00716          if(changedAfterThisPV > 0 ){ (rmLSPV->second)  =  (rmLSPV->second)-SizeToRemovePV;}
00717                                }
00718 
00719       theBeamFitter->resizePVvector(SizeToRemovePV);
00720 
00721       map<int, std::size_t >::iterator tmpItpv=mapLSPVStoreSize.begin();
00722       mapLSPVStoreSize.erase(tmpItpv);
00723       }
00724       if(debug_)edm::LogInfo("BeamMonitor") << "FitAndFill:: Size of thePVvector After removing the PVs = " << theBeamFitter->getPVvectorSize()<<endl;
00725 
00726 
00727       //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
00728       bool resetHistoFlag_=false;
00729       if((int)mapPVx.size() >= resetFitNLumi_ && (StartAverage_)){
00730       h_PVx[0]->Reset();
00731       h_PVy[0]->Reset();
00732       h_PVz[0]->Reset();
00733       h_nVtx_st->Reset();
00734       resetHistoFlag_ = true;
00735       }
00736 
00737       int MaxPVs = 0;
00738       int countEvtLastNLS_=0;
00739       int countTotPV_= 0;      
00740 
00741       std::map< int, std::vector<int> >::iterator mnpv=mapNPV.begin();
00742       std::map< int, std::vector<float> >::iterator mpv2=mapPVy.begin();
00743       std::map< int, std::vector<float> >::iterator mpv3=mapPVz.begin();
00744 
00745      for(std::map< int, std::vector<float> >::iterator mpv1=mapPVx.begin(); mpv1 != mapPVx.end(); ++mpv1, ++mpv2, ++mpv3, ++mnpv)
00746      {
00747         std::vector<float>::iterator mpvs2 = (mpv2->second).begin();
00748         std::vector<float>::iterator mpvs3 = (mpv3->second).begin();
00749       for(std::vector<float>::iterator mpvs1=(mpv1->second).begin(); mpvs1 !=(mpv1->second).end(); ++mpvs1, ++mpvs2, ++mpvs3){
00750         if(resetHistoFlag_)
00751             {h_PVx[0]->Fill( *mpvs1 ); //these histogram are reset after StartAverage_ flag is ON
00752              h_PVy[0]->Fill( *mpvs2 );
00753              h_PVz[0]->Fill( *mpvs3 );
00754             }
00755         }//loop over second 
00756    
00757        //Do the same here for nPV distr.
00758       for(std::vector<int>::iterator mnpvs = (mnpv->second).begin(); mnpvs != (mnpv->second).end(); ++mnpvs){
00759         if((*mnpvs > 0) && (resetHistoFlag_) )h_nVtx_st->Fill( (*mnpvs)*(1.0) );
00760          countEvtLastNLS_++;
00761          countTotPV_ += (*mnpvs);  
00762         if((*mnpvs) > MaxPVs) MaxPVs =  (*mnpvs);
00763        }//loop over second of mapNPV
00764 
00765      }//loop over last N lumis
00766 
00767      char tmpTitlePV[100];               
00768      sprintf(tmpTitlePV,"%s %i %s %i","Num. of reco. vertices for LS: ",beginLumiOfPVFit_," to ",endLumiOfPVFit_);   
00769      h_nVtx_st->setAxisTitle(tmpTitlePV,1);
00770 
00771      std::vector<float> DipPVInfo_;
00772      DipPVInfo_.clear();
00773 
00774    if(countTotPV_ != 0 ){
00775      DipPVInfo_.push_back((float)countEvtLastNLS_);
00776      DipPVInfo_.push_back(h_nVtx_st->getMean());
00777      DipPVInfo_.push_back(h_nVtx_st->getMeanError());
00778      DipPVInfo_.push_back(h_nVtx_st->getRMS());
00779      DipPVInfo_.push_back(h_nVtx_st->getRMSError());
00780      DipPVInfo_.push_back((float)MaxPVs);
00781      DipPVInfo_.push_back((float)countTotPV_);
00782      MaxPVs =0;
00783     }
00784    else{ for(size_t i= 0; i < 7; i++){if(i>0)DipPVInfo_.push_back(0.);
00785                                       else DipPVInfo_.push_back((float)countEvtLastNLS_);}
00786        }
00787      theBeamFitter->SetPVInfo(DipPVInfo_);      
00788      countEvtLastNLS_=0;
00789 
00790 
00791 
00792   if (onlineMode_) { // filling LS gap
00793     // FIXME: need to add protection for the case if the gap is at the resetting LS!
00794     const int countLS_bs = hs["x0_lumi"]->getTH1()->GetEntries();
00795     const int countLS_pv = hs["PVx_lumi"]->getTH1()->GetEntries();
00796     edm::LogInfo("BeamMonitor") << "FitAndFill:: countLS_bs = " << countLS_bs << " ; countLS_pv = " << countLS_pv << std::endl;
00797     int LSgap_bs = currentlumi/fitNLumi_ - countLS_bs;
00798     int LSgap_pv = currentlumi/fitPVNLumi_ - countLS_pv;
00799     if (currentlumi%fitNLumi_ == 0)
00800       LSgap_bs--;
00801     if (currentlumi%fitPVNLumi_ == 0)
00802       LSgap_pv--;
00803     edm::LogInfo("BeamMonitor") << "FitAndFill::  LSgap_bs = " << LSgap_bs << " ; LSgap_pv = " << LSgap_pv << std::endl;
00804     // filling previous fits if LS gap ever exists
00805     for (int ig = 0; ig < LSgap_bs; ig++) {
00806       hs["x0_lumi"]->ShiftFillLast( 0., 0., fitNLumi_ );//x0 , x0err, fitNLumi_;  see DQMCore....
00807       hs["y0_lumi"]->ShiftFillLast( 0., 0., fitNLumi_ );
00808       hs["z0_lumi"]->ShiftFillLast( 0., 0., fitNLumi_ );
00809       hs["sigmaX0_lumi"]->ShiftFillLast( 0., 0., fitNLumi_ );
00810       hs["sigmaY0_lumi"]->ShiftFillLast( 0., 0., fitNLumi_ );
00811       hs["sigmaZ0_lumi"]->ShiftFillLast( 0., 0., fitNLumi_ );
00812     }
00813     for (int ig = 0; ig < LSgap_pv; ig++) {
00814       hs["PVx_lumi"]->ShiftFillLast( 0., 0., fitPVNLumi_ );
00815       hs["PVy_lumi"]->ShiftFillLast( 0., 0., fitPVNLumi_ );
00816       hs["PVz_lumi"]->ShiftFillLast( 0., 0., fitPVNLumi_ );
00817     }
00818     const int previousLS = h_nTrk_lumi->getTH1()->GetEntries();
00819     for (int i=1;i < (currentlumi - previousLS);i++)//if (current-previoius)= 1 then never go inside the for loop!!!!!!!!!!!
00820       h_nTrk_lumi->ShiftFillLast(nthBSTrk_);
00821   }
00822 
00823   edm::LogInfo("BeamMonitor") << "FitAndFill:: Time lapsed since last scroll = " << tmpTime - refTime << std:: endl;
00824 
00825   if (testScroll(tmpTime,refTime)) {
00826     scrollTH1(hs["x0_time"]->getTH1(),refTime);
00827     scrollTH1(hs["y0_time"]->getTH1(),refTime);
00828     scrollTH1(hs["z0_time"]->getTH1(),refTime);
00829     scrollTH1(hs["sigmaX0_time"]->getTH1(),refTime);
00830     scrollTH1(hs["sigmaY0_time"]->getTH1(),refTime);
00831     scrollTH1(hs["sigmaZ0_time"]->getTH1(),refTime);
00832     scrollTH1(hs["PVx_time"]->getTH1(),refTime);
00833     scrollTH1(hs["PVy_time"]->getTH1(),refTime);
00834     scrollTH1(hs["PVz_time"]->getTH1(),refTime);
00835   }
00836 
00837   bool doPVFit = false;
00838 
00839   if (fitPVNLumi_ > 0) {
00840     if (onlineMode_) {
00841       if (currentlumi%fitPVNLumi_ == 0)
00842         doPVFit = true;
00843     }
00844     else
00845       if (countLumi_%fitPVNLumi_ == 0)
00846         doPVFit = true;
00847   }
00848   else
00849     doPVFit = true;
00850 
00851 
00852   if (doPVFit) {
00853     edm::LogInfo("BeamMonitor") << "FitAndFill:: Do PV Fitting for LS = " << beginLumiOfPVFit_ << " to " << endLumiOfPVFit_ << std::endl;
00854     // Primary Vertex Fit:
00855     if (h_PVx[0]->getTH1()->GetEntries() > minNrVertices_) {
00856 
00857       pvResults->Reset();
00858       char tmpTitle[50];
00859       sprintf(tmpTitle,"%s %i %s %i","Fitted Primary Vertex (cm) of LS: ",beginLumiOfPVFit_," to ",endLumiOfPVFit_);
00860       pvResults->setAxisTitle(tmpTitle,1);
00861 
00862       TF1 *fgaus = new TF1("fgaus","gaus");
00863       double mean,width,meanErr,widthErr;
00864       fgaus->SetLineColor(4);
00865       h_PVx[0]->getTH1()->Fit("fgaus","QLM0");
00866       mean = fgaus->GetParameter(1);
00867       width = fgaus->GetParameter(2);
00868       meanErr = fgaus->GetParError(1);
00869       widthErr = fgaus->GetParError(2);
00870 
00871 
00872       hs["PVx_lumi"]->ShiftFillLast(mean,width,fitPVNLumi_);
00873       hs["PVx_lumi_all"]->setBinContent(currentlumi,mean);
00874       hs["PVx_lumi_all"]->setBinError(currentlumi,width);
00875       int nthBin = tmpTime - refTime;
00876       if (nthBin < 0)
00877         edm::LogInfo("BeamMonitor") << "FitAndFill::  Event time outside current range of time histograms!" << std::endl;
00878       if (nthBin > 0) {
00879         hs["PVx_time"]->setBinContent(nthBin,mean);
00880         hs["PVx_time"]->setBinError(nthBin,width);
00881       }
00882       int jthBin = tmpTime - startTime;
00883       if (jthBin > 0) {
00884         hs["PVx_time_all"]->setBinContent(jthBin,mean);
00885         hs["PVx_time_all"]->setBinError(jthBin,width);
00886       }
00887       pvResults->setBinContent(1,6,mean);
00888       pvResults->setBinContent(1,3,width);
00889       pvResults->setBinContent(2,6,meanErr);
00890       pvResults->setBinContent(2,3,widthErr);
00891 
00892       dbe_->setCurrentFolder(monitorName_+"PrimaryVertex/");
00893       const char* tmpfile;
00894       TH1D * tmphisto;
00895       // snap shot of the fit
00896       tmpfile= (h_PVx[1]->getName()).c_str();
00897       tmphisto = static_cast<TH1D *>((h_PVx[0]->getTH1())->Clone("tmphisto"));
00898       h_PVx[1]->getTH1()->SetBins(tmphisto->GetNbinsX(),tmphisto->GetXaxis()->GetXmin(),tmphisto->GetXaxis()->GetXmax());
00899       h_PVx[1] = dbe_->book1D(tmpfile,h_PVx[0]->getTH1F());
00900       h_PVx[1]->getTH1()->Fit("fgaus","QLM");
00901 
00902 
00903       h_PVy[0]->getTH1()->Fit("fgaus","QLM0");
00904       mean = fgaus->GetParameter(1);
00905       width = fgaus->GetParameter(2);
00906       meanErr = fgaus->GetParError(1);
00907       widthErr = fgaus->GetParError(2);
00908       hs["PVy_lumi"]->ShiftFillLast(mean,width,fitPVNLumi_);
00909       hs["PVy_lumi_all"]->setBinContent(currentlumi,mean);
00910       hs["PVy_lumi_all"]->setBinError(currentlumi,width);
00911       if (nthBin > 0) {
00912         hs["PVy_time"]->setBinContent(nthBin,mean);
00913         hs["PVy_time"]->setBinError(nthBin,width);
00914       }
00915       if (jthBin > 0) {
00916         hs["PVy_time_all"]->setBinContent(jthBin,mean);
00917         hs["PVy_time_all"]->setBinError(jthBin,width);
00918       }
00919       pvResults->setBinContent(1,5,mean);
00920       pvResults->setBinContent(1,2,width);
00921       pvResults->setBinContent(2,5,meanErr);
00922       pvResults->setBinContent(2,2,widthErr);
00923       // snap shot of the fit
00924       tmpfile= (h_PVy[1]->getName()).c_str();
00925       tmphisto = static_cast<TH1D *>((h_PVy[0]->getTH1())->Clone("tmphisto"));
00926       h_PVy[1]->getTH1()->SetBins(tmphisto->GetNbinsX(),tmphisto->GetXaxis()->GetXmin(),tmphisto->GetXaxis()->GetXmax());
00927       h_PVy[1]->update();
00928       h_PVy[1] = dbe_->book1D(tmpfile,h_PVy[0]->getTH1F());
00929       h_PVy[1]->getTH1()->Fit("fgaus","QLM");
00930 
00931 
00932       h_PVz[0]->getTH1()->Fit("fgaus","QLM0");
00933       mean = fgaus->GetParameter(1);
00934       width = fgaus->GetParameter(2);
00935       meanErr = fgaus->GetParError(1);
00936       widthErr = fgaus->GetParError(2);
00937       hs["PVz_lumi"]->ShiftFillLast(mean,width,fitPVNLumi_);
00938       hs["PVz_lumi_all"]->setBinContent(currentlumi,mean);
00939       hs["PVz_lumi_all"]->setBinError(currentlumi,width);
00940       if (nthBin > 0) {
00941         hs["PVz_time"]->setBinContent(nthBin,mean);
00942         hs["PVz_time"]->setBinError(nthBin,width);
00943       }
00944       if (jthBin > 0) {
00945         hs["PVz_time_all"]->setBinContent(jthBin,mean);
00946         hs["PVz_time_all"]->setBinError(jthBin,width);
00947       }
00948       pvResults->setBinContent(1,4,mean);
00949       pvResults->setBinContent(1,1,width);
00950       pvResults->setBinContent(2,4,meanErr);
00951       pvResults->setBinContent(2,1,widthErr);
00952       // snap shot of the fit
00953       tmpfile= (h_PVz[1]->getName()).c_str();
00954       tmphisto = static_cast<TH1D *>((h_PVz[0]->getTH1())->Clone("tmphisto"));
00955       h_PVz[1]->getTH1()->SetBins(tmphisto->GetNbinsX(),tmphisto->GetXaxis()->GetXmin(),tmphisto->GetXaxis()->GetXmax());
00956       h_PVz[1]->update();
00957       h_PVz[1] = dbe_->book1D(tmpfile,h_PVz[0]->getTH1F());
00958       h_PVz[1]->getTH1()->Fit("fgaus","QLM");
00959 
00960     }//check if found min Vertices
00961   }//do PVfit
00962 
00963   if ((resetPVNLumi_ > 0 && countLumi_ == resetPVNLumi_) || StartAverage_){
00964     beginLumiOfPVFit_=0;
00965     refPVtime[0] = 0;
00966     }
00967 
00968 
00969 
00970 
00971      //---------Readjustment of theBSvector, RefTime, beginLSofFit---------
00972      vector<BSTrkParameters> theBSvector1 = theBeamFitter->getBSvector();
00973      mapLSBSTrkSize[countLumi_]= (theBSvector1.size());
00974       size_t PreviousRecords=0;     //needed to fill nth record of tracks in GUI
00975 
00976       if(StartAverage_){
00977       size_t SizeToRemove=0;
00978       std::map<int, std::size_t>::iterator rmls=mapLSBSTrkSize.begin();
00979       SizeToRemove = rmls->second;
00980       if(debug_)edm::LogInfo("BeamMonitor")<< "  The size to remove is =  "<< SizeToRemove << endl;
00981       int changedAfterThis=0;
00982       for(std::map<int, std::size_t>::iterator rmLS = mapLSBSTrkSize.begin(); rmLS!=mapLSBSTrkSize.end(); ++rmLS, ++changedAfterThis){
00983          if(changedAfterThis > 0 ){(rmLS->second)  = (rmLS->second)-SizeToRemove;
00984                                     if((mapLSBSTrkSize.size()- (size_t)changedAfterThis) == 2 )PreviousRecords = (rmLS->second);
00985                                   } }
00986 
00987       theBeamFitter->resizeBSvector(SizeToRemove);
00988 
00989       map<int, std::size_t >::iterator tmpIt=mapLSBSTrkSize.begin();
00990       mapLSBSTrkSize.erase(tmpIt);
00991 
00992       std::pair<int,int> checkfitLS = theBeamFitter->getFitLSRange();
00993       std::pair<time_t,time_t> checkfitTime =theBeamFitter->getRefTime();
00994       theBeamFitter->setFitLSRange(beginLumiOfBSFit_, checkfitLS.second);
00995       theBeamFitter->setRefTime(refBStime[0], checkfitTime.second);
00996       }
00997 
00998       //Fill the track for this fit
00999       vector<BSTrkParameters> theBSvector = theBeamFitter->getBSvector();
01000       h_nTrk_lumi->ShiftFillLast( theBSvector.size() );
01001 
01002       if(debug_)edm::LogInfo("BeamMonitor")<< "FitAndFill::   Size of  theBSViector.size()  After =" << theBSvector.size() << endl;
01003 
01004 
01005 
01006   bool countFitting = false;
01007   if (theBSvector.size() >= PreviousRecords  && theBSvector.size() >= min_Ntrks_) {
01008       countFitting = true;
01009      }
01010 
01011 
01012    //---Fix for Cut Flow Table for Running average in a same way//the previous code  has problem for resetting!!!
01013    mapLSCF[countLumi_] = *theBeamFitter->getCutFlow();
01014    if(StartAverage_ && mapLSCF.size()){
01015      const TH1F& cutFlowToSubtract = mapLSCF.begin()->second;
01016      // Subtract the last cut flow from all of the others.
01017      std::map<int, TH1F>::iterator cf = mapLSCF.begin();
01018      // Start on second entry
01019      for(; cf != mapLSCF.end(); ++cf) {
01020        cf->second.Add(&cutFlowToSubtract, -1);
01021      }
01022      theBeamFitter->subtractFromCutFlow(&cutFlowToSubtract);
01023      // Remove the obsolete lumi section
01024      mapLSCF.erase(mapLSCF.begin());
01025    }
01026 
01027   if (resetHistos_) {
01028     h_d0_phi0->Reset();
01029     h_vx_vy->Reset();
01030     h_vx_dz->Reset();
01031     h_vy_dz->Reset();
01032     h_trk_z0->Reset();
01033     resetHistos_ = false;
01034   }
01035 
01036   if(StartAverage_) nthBSTrk_  = PreviousRecords; //after average proccess is ON//for 2-6 LS fit PreviousRecords is size from 2-5 LS
01037 
01038   edm::LogInfo("BeamMonitor")<<" The Previous Recored for this fit is  ="<<nthBSTrk_<<endl;
01039 
01040   unsigned int itrk = 0;
01041   for (vector<BSTrkParameters>::const_iterator BSTrk = theBSvector.begin();
01042        BSTrk != theBSvector.end();  ++BSTrk, ++itrk){
01043     if (itrk >= nthBSTrk_){//fill for this record only !!
01044       h_d0_phi0->Fill( BSTrk->phi0(), BSTrk->d0() );
01045       double vx = BSTrk->vx();
01046       double vy = BSTrk->vy();
01047       double z0 = BSTrk->z0();
01048       h_vx_vy->Fill( vx, vy );
01049       h_vx_dz->Fill( z0, vx );
01050       h_vy_dz->Fill( z0, vy );
01051       h_trk_z0->Fill( z0 );
01052      }
01053   }
01054 
01055 
01056    nthBSTrk_ = theBSvector.size(); // keep track of num of tracks filled so far
01057 
01058    edm::LogInfo("BeamMonitor")<<" The Current Recored for this fit is  ="<<nthBSTrk_<<endl;
01059 
01060   if (countFitting) edm::LogInfo("BeamMonitor") << "FitAndFill::  Num of tracks collected = " << nthBSTrk_ << endl;
01061 
01062 
01063   if (fitNLumi_ > 0) {
01064     if (onlineMode_){
01065       if (currentlumi%fitNLumi_!=0) {
01066 //      for (std::map<TString,MonitorElement*>::iterator itAll = hs.begin();
01067 //           itAll != hs.end(); ++itAll) {
01068 //        if ((*itAll).first.Contains("all")) {
01069 //          (*itAll).second->setBinContent(currentlumi,0.);
01070 //          (*itAll).second->setBinError(currentlumi,0.);
01071 //        }
01072 //      }
01073         return;
01074       }
01075     }
01076     else
01077       if (countLumi_%fitNLumi_!=0) return;
01078   }
01079 
01080   edm::LogInfo("BeamMonitor") << "FitAndFill:: [DebugTime] refBStime[0] = " << refBStime[0]
01081                               << "; address =  " << &refBStime[0] << std::endl;
01082   edm::LogInfo("BeamMonitor") << "FitAndFill:: [DebugTime] refBStime[1] = " << refBStime[1]
01083                               << "; address =  " << &refBStime[1] << std::endl;
01084 
01085   if (countFitting) {
01086     nFits_++;
01087     std::pair<int,int> fitLS = theBeamFitter->getFitLSRange();
01088     edm::LogInfo("BeamMonitor") << "FitAndFill::  [BeamFitter] Do BeamSpot Fit for LS = " << fitLS.first << " to " << fitLS.second << std::endl;
01089     edm::LogInfo("BeamMonitor") << "FitAndFill::  [BeamMonitor] Do BeamSpot Fit for LS = " << beginLumiOfBSFit_ << " to " << endLumiOfBSFit_ << std::endl;
01090 
01091     //Now Run the PV and Track Fitter over the collected tracks and pvs
01092     if (theBeamFitter->runPVandTrkFitter()) {
01093       reco::BeamSpot bs = theBeamFitter->getBeamSpot();
01094       if (bs.type() > 0) // with good beamwidth fit
01095         preBS = bs; // cache good fit results
01096 
01097       edm::LogInfo("BeamMonitor") << "\n RESULTS OF DEFAULT FIT:" << endl;
01098       edm::LogInfo("BeamMonitor") << bs << endl;
01099       edm::LogInfo("BeamMonitor") << "[BeamFitter] fitting done \n" << endl;
01100 
01101       hs["x0_lumi"]->ShiftFillLast( bs.x0(), bs.x0Error(), fitNLumi_ );
01102       hs["y0_lumi"]->ShiftFillLast( bs.y0(), bs.y0Error(), fitNLumi_ );
01103       hs["z0_lumi"]->ShiftFillLast( bs.z0(), bs.z0Error(), fitNLumi_ );
01104       hs["sigmaX0_lumi"]->ShiftFillLast( bs.BeamWidthX(), bs.BeamWidthXError(), fitNLumi_ );
01105       hs["sigmaY0_lumi"]->ShiftFillLast( bs.BeamWidthY(), bs.BeamWidthYError(), fitNLumi_ );
01106       hs["sigmaZ0_lumi"]->ShiftFillLast( bs.sigmaZ(), bs.sigmaZ0Error(), fitNLumi_ );
01107       hs["x0_lumi_all"]->setBinContent(currentlumi,bs.x0());
01108       hs["x0_lumi_all"]->setBinError(currentlumi,bs.x0Error());
01109       hs["y0_lumi_all"]->setBinContent(currentlumi,bs.y0());
01110       hs["y0_lumi_all"]->setBinError(currentlumi,bs.y0Error());
01111       hs["z0_lumi_all"]->setBinContent(currentlumi,bs.z0());
01112       hs["z0_lumi_all"]->setBinError(currentlumi,bs.z0Error());
01113       hs["sigmaX0_lumi_all"]->setBinContent(currentlumi, bs.BeamWidthX());
01114       hs["sigmaX0_lumi_all"]->setBinError(currentlumi, bs.BeamWidthXError());
01115       hs["sigmaY0_lumi_all"]->setBinContent(currentlumi, bs.BeamWidthY());
01116       hs["sigmaY0_lumi_all"]->setBinError(currentlumi, bs.BeamWidthYError());
01117       hs["sigmaZ0_lumi_all"]->setBinContent(currentlumi, bs.sigmaZ());
01118       hs["sigmaZ0_lumi_all"]->setBinError(currentlumi, bs.sigmaZ0Error());
01119 
01120       int nthBin = tmpTime - refTime;
01121       if (nthBin > 0) {
01122         hs["x0_time"]->setBinContent(nthBin, bs.x0());
01123         hs["y0_time"]->setBinContent(nthBin, bs.y0());
01124         hs["z0_time"]->setBinContent(nthBin, bs.z0());
01125         hs["sigmaX0_time"]->setBinContent(nthBin, bs.BeamWidthX());
01126         hs["sigmaY0_time"]->setBinContent(nthBin, bs.BeamWidthY());
01127         hs["sigmaZ0_time"]->setBinContent(nthBin, bs.sigmaZ());
01128         hs["x0_time"]->setBinError(nthBin, bs.x0Error());
01129         hs["y0_time"]->setBinError(nthBin, bs.y0Error());
01130         hs["z0_time"]->setBinError(nthBin, bs.z0Error());
01131         hs["sigmaX0_time"]->setBinError(nthBin, bs.BeamWidthXError());
01132         hs["sigmaY0_time"]->setBinError(nthBin, bs.BeamWidthYError());
01133         hs["sigmaZ0_time"]->setBinError(nthBin, bs.sigmaZ0Error());
01134       }
01135 
01136       int jthBin = tmpTime - startTime;
01137       if (jthBin > 0) {
01138         hs["x0_time_all"]->setBinContent(jthBin, bs.x0());
01139         hs["y0_time_all"]->setBinContent(jthBin, bs.y0());
01140         hs["z0_time_all"]->setBinContent(jthBin, bs.z0());
01141         hs["sigmaX0_time_all"]->setBinContent(jthBin, bs.BeamWidthX());
01142         hs["sigmaY0_time_all"]->setBinContent(jthBin, bs.BeamWidthY());
01143         hs["sigmaZ0_time_all"]->setBinContent(jthBin, bs.sigmaZ());
01144         hs["x0_time_all"]->setBinError(jthBin, bs.x0Error());
01145         hs["y0_time_all"]->setBinError(jthBin, bs.y0Error());
01146         hs["z0_time_all"]->setBinError(jthBin, bs.z0Error());
01147         hs["sigmaX0_time_all"]->setBinError(jthBin, bs.BeamWidthXError());
01148         hs["sigmaY0_time_all"]->setBinError(jthBin, bs.BeamWidthYError());
01149         hs["sigmaZ0_time_all"]->setBinError(jthBin, bs.sigmaZ0Error());
01150       }
01151 
01152       h_x0->Fill( bs.x0());
01153       h_y0->Fill( bs.y0());
01154       h_z0->Fill( bs.z0());
01155       if (bs.type() > 0) { // with good beamwidth fit
01156         h_sigmaX0->Fill( bs.BeamWidthX());
01157         h_sigmaY0->Fill( bs.BeamWidthY());
01158       }
01159       h_sigmaZ0->Fill( bs.sigmaZ());
01160 
01161       if (nthBSTrk_ >= 2*min_Ntrks_) {
01162         double amp = std::sqrt(bs.x0()*bs.x0()+bs.y0()*bs.y0());
01163         double alpha = std::atan2(bs.y0(),bs.x0());
01164         TF1 *f1 = new TF1("f1","[0]*sin(x-[1])",-3.14,3.14);
01165         f1->SetParameters(amp,alpha);
01166         f1->SetParLimits(0,amp-0.1,amp+0.1);
01167         f1->SetParLimits(1,alpha-0.577,alpha+0.577);
01168         f1->SetLineColor(4);
01169         h_d0_phi0->getTProfile()->Fit("f1","QR");
01170 
01171         double mean = bs.z0();
01172         double width = bs.sigmaZ();
01173         TF1 *fgaus = new TF1("fgaus","gaus");
01174         fgaus->SetParameters(mean,width);
01175         fgaus->SetLineColor(4);
01176         h_trk_z0->getTH1()->Fit("fgaus","QLRM","",mean-3*width,mean+3*width);
01177       }
01178 
01179       fitResults->Reset();
01180       std::pair<int,int> LSRange = theBeamFitter->getFitLSRange();
01181       char tmpTitle[50];
01182       sprintf(tmpTitle,"%s %i %s %i","Fitted Beam Spot (cm) of LS: ",LSRange.first," to ",LSRange.second);
01183       fitResults->setAxisTitle(tmpTitle,1);
01184       fitResults->setBinContent(1,8,bs.x0());
01185       fitResults->setBinContent(1,7,bs.y0());
01186       fitResults->setBinContent(1,6,bs.z0());
01187       fitResults->setBinContent(1,5,bs.sigmaZ());
01188       fitResults->setBinContent(1,4,bs.dxdz());
01189       fitResults->setBinContent(1,3,bs.dydz());
01190       if (bs.type() > 0) { // with good beamwidth fit
01191         fitResults->setBinContent(1,2,bs.BeamWidthX());
01192         fitResults->setBinContent(1,1,bs.BeamWidthY());
01193       }
01194       else { // fill cached widths
01195         fitResults->setBinContent(1,2,preBS.BeamWidthX());
01196         fitResults->setBinContent(1,1,preBS.BeamWidthY());
01197       }
01198 
01199       fitResults->setBinContent(2,8,bs.x0Error());
01200       fitResults->setBinContent(2,7,bs.y0Error());
01201       fitResults->setBinContent(2,6,bs.z0Error());
01202       fitResults->setBinContent(2,5,bs.sigmaZ0Error());
01203       fitResults->setBinContent(2,4,bs.dxdzError());
01204       fitResults->setBinContent(2,3,bs.dydzError());
01205       if (bs.type() > 0) { // with good beamwidth fit
01206         fitResults->setBinContent(2,2,bs.BeamWidthXError());
01207         fitResults->setBinContent(2,1,bs.BeamWidthYError());
01208       }
01209       else { // fill cached width errors
01210         fitResults->setBinContent(2,2,preBS.BeamWidthXError());
01211         fitResults->setBinContent(2,1,preBS.BeamWidthYError());
01212       }
01213 
01214       // count good fit
01215       //     if (std::fabs(refBS.x0()-bs.x0())/bs.x0Error() < deltaSigCut_) { // disabled temporarily
01216       summaryContent_[0] += 1.;
01217       //     }
01218       //     if (std::fabs(refBS.y0()-bs.y0())/bs.y0Error() < deltaSigCut_) { // disabled temporarily
01219       summaryContent_[1] += 1.;
01220       //     }
01221       //     if (std::fabs(refBS.z0()-bs.z0())/bs.z0Error() < deltaSigCut_) { // disabled temporarily
01222       summaryContent_[2] += 1.;
01223       //     }
01224 
01225     } //if (theBeamFitter->runPVandTrkFitter())
01226     else { // beam fit fails
01227       reco::BeamSpot bs = theBeamFitter->getBeamSpot();
01228       edm::LogInfo("BeamMonitor") << "FitAndFill::   [BeamMonitor] Beam fit fails!!! \n" << endl;
01229       edm::LogInfo("BeamMonitor") << "FitAndFill::   [BeamMonitor] Output beam spot for DIP \n" << endl;
01230       edm::LogInfo("BeamMonitor") << bs << endl;
01231 
01232       hs["sigmaX0_lumi"]->ShiftFillLast( bs.BeamWidthX(), bs.BeamWidthXError(), fitNLumi_ );
01233       hs["sigmaY0_lumi"]->ShiftFillLast( bs.BeamWidthY(), bs.BeamWidthYError(), fitNLumi_ );
01234       hs["sigmaZ0_lumi"]->ShiftFillLast( bs.sigmaZ(), bs.sigmaZ0Error(), fitNLumi_ );
01235       hs["x0_lumi"]->ShiftFillLast( bs.x0(), bs.x0Error(), fitNLumi_ );
01236       hs["y0_lumi"]->ShiftFillLast( bs.y0(), bs.y0Error(), fitNLumi_ );
01237       hs["z0_lumi"]->ShiftFillLast( bs.z0(), bs.z0Error(), fitNLumi_ );
01238     } // end of beam fit fails
01239 
01240 
01241   } //-------- end of countFitting------------------------------------------
01242  else { // no fit
01243     // Overwrite Fit LS and fit time when no event processed or no track selected
01244     theBeamFitter->setFitLSRange(beginLumiOfBSFit_,endLumiOfBSFit_);
01245     theBeamFitter->setRefTime(refBStime[0],refBStime[1]);
01246     if (theBeamFitter->runPVandTrkFitter()) {} // Dump fake beam spot for DIP
01247     reco::BeamSpot bs = theBeamFitter->getBeamSpot();
01248     edm::LogInfo("BeamMonitor") << "FitAndFill::  [BeamMonitor] No fitting \n" << endl;
01249     edm::LogInfo("BeamMonitor") << "FitAndFill::  [BeamMonitor] Output fake beam spot for DIP \n" << endl;
01250     edm::LogInfo("BeamMonitor") << bs << endl;
01251 
01252     hs["sigmaX0_lumi"]->ShiftFillLast( bs.BeamWidthX(), bs.BeamWidthXError(), fitNLumi_ );
01253     hs["sigmaY0_lumi"]->ShiftFillLast( bs.BeamWidthY(), bs.BeamWidthYError(), fitNLumi_ );
01254     hs["sigmaZ0_lumi"]->ShiftFillLast( bs.sigmaZ(), bs.sigmaZ0Error(), fitNLumi_ );
01255     hs["x0_lumi"]->ShiftFillLast( bs.x0(), bs.x0Error(), fitNLumi_ );
01256     hs["y0_lumi"]->ShiftFillLast( bs.y0(), bs.y0Error(), fitNLumi_ );
01257     hs["z0_lumi"]->ShiftFillLast( bs.z0(), bs.z0Error(), fitNLumi_ );
01258   }
01259 
01260 
01261 
01262   // Fill summary report
01263   if (countFitting) {
01264     for (int n = 0; n < nFitElements_; n++) {
01265       reportSummaryContents[n]->Fill( summaryContent_[n] / (float)nFits_ );
01266     }
01267 
01268     summarySum_ = 0;
01269     for (int ii = 0; ii < nFitElements_; ii++) {
01270       summarySum_ += summaryContent_[ii];
01271     }
01272     reportSummary_ = summarySum_ / (nFitElements_ * nFits_);
01273     if (reportSummary) reportSummary->Fill(reportSummary_);
01274 
01275     for ( int bi = 0; bi < nFitElements_ ; bi++) {
01276       reportSummaryMap->setBinContent(1,bi+1,summaryContent_[bi] / (float)nFits_);
01277     }
01278   }
01279 
01280 
01281 
01282 
01283   if ( ( resetFitNLumi_ > 0 &&
01284         ((onlineMode_ && countLumi_==resetFitNLumi_ ) ||  //OR it should be currentLumi_ (if in sequence then does not mattar)
01285         (!onlineMode_ && countLumi_==resetFitNLumi_ ))
01286        )  || (StartAverage_) ){
01287 
01288     edm::LogInfo("BeamMonitor") << "FitAndFill:: The flag is ON for running average Beam Spot fit"<<endl;
01289     StartAverage_    = true;
01290     firstAverageFit_++;
01291     resetHistos_     = true;
01292     nthBSTrk_        = 0;
01293     beginLumiOfBSFit_= 0;
01294     refBStime[0]     = 0;
01295 
01296     }
01297 
01298 
01299 
01300 }
01301 
01302 //--------------------------------------------------------
01303 void BeamMonitor::RestartFitting(){
01304  if(debug_)edm::LogInfo("BeamMonitor") << " RestartingFitting:: Restart Beami everything to a fresh start !!! because Gap is > 10 LS" <<endl;
01305                                                 //track based fit reset here
01306                                                 resetHistos_ = true;
01307                                                 nthBSTrk_ = 0;
01308                                                 theBeamFitter->resetTrkVector();
01309                                                 theBeamFitter->resetLSRange();
01310                                                 theBeamFitter->resetRefTime();
01311                                                 theBeamFitter->resetPVFitter();
01312                                                 theBeamFitter->resetCutFlow();
01313                                                 beginLumiOfBSFit_ = 0;
01314                                                 refBStime[0] = 0;
01315                                                 //pv based fit iis reset here
01316                                                 h_PVx[0]->Reset();
01317                                                 h_PVy[0]->Reset();
01318                                                 h_PVz[0]->Reset();
01319                                                 beginLumiOfPVFit_ = 0;
01320                                                 refPVtime[0] = 0;
01321                                                 //Clear all the Maps here
01322                                                 mapPVx.clear();
01323                                                 mapPVy.clear();
01324                                                 mapPVz.clear();
01325                                                 mapNPV.clear();
01326                                                 mapBeginBSLS.clear();
01327                                                 mapBeginPVLS.clear();
01328                                                 mapBeginBSTime.clear();
01329                                                 mapBeginPVTime.clear();
01330                                                 mapLSBSTrkSize.clear();
01331                                                 mapLSPVStoreSize.clear();
01332                                                 mapLSCF.clear(); countGapLumi_=0; countLumi_=0; StartAverage_=false;
01333 
01334 }
01335 
01336 //-------------------------------------------------------
01337 void BeamMonitor::endRun(const Run& r, const EventSetup& context){
01338 
01339 if(debug_)edm::LogInfo("BeamMonitor") << "endRun:: Clearing all the Maps "<<endl;
01340 //Clear all the Maps here
01341 mapPVx.clear();
01342 mapPVy.clear();
01343 mapPVz.clear();
01344 mapNPV.clear();
01345 mapBeginBSLS.clear();
01346 mapBeginPVLS.clear();
01347 mapBeginBSTime.clear();
01348 mapBeginPVTime.clear();
01349 mapLSBSTrkSize.clear();
01350 mapLSPVStoreSize.clear();
01351 mapLSCF.clear();
01352 
01353 
01354 }
01355 
01356 //--------------------------------------------------------
01357 void BeamMonitor::endJob(const LuminosityBlock& lumiSeg,
01358                          const EventSetup& iSetup){
01359   if (!onlineMode_) endLuminosityBlock(lumiSeg, iSetup);
01360 }
01361 
01362 //--------------------------------------------------------
01363 void BeamMonitor::scrollTH1(TH1 * h, time_t ref) {
01364   const char* offsetTime = formatFitTime(ref);
01365   TDatime da(offsetTime);
01366   if (lastNZbin > 0) {
01367     double val = h->GetBinContent(lastNZbin);
01368     double valErr = h->GetBinError(lastNZbin);
01369     h->Reset();
01370     h->GetXaxis()->SetTimeOffset(da.Convert(kTRUE));
01371     int bin = (lastNZbin > buffTime ? buffTime : 1);
01372     h->SetBinContent(bin,val);
01373     h->SetBinError(bin,valErr);
01374   }
01375   else {
01376     h->Reset();
01377     h->GetXaxis()->SetTimeOffset(da.Convert(kTRUE));
01378   }
01379 }
01380 
01381 //--------------------------------------------------------
01382 // Method to check whether to chane histogram time offset (forward only)
01383 bool BeamMonitor::testScroll(time_t & tmpTime_, time_t & refTime_){
01384   bool scroll_ = false;
01385   if (tmpTime_ - refTime_ >= intervalInSec_) {
01386     scroll_ = true;
01387     edm::LogInfo("BeamMonitor") << "testScroll::  Reset Time Offset" << std::endl;
01388     lastNZbin = intervalInSec_;
01389     for (int bin = intervalInSec_; bin >= 1; bin--) {
01390       if (hs["x0_time"]->getBinContent(bin) > 0) {
01391         lastNZbin = bin;
01392         break;
01393       }
01394     }
01395     edm::LogInfo("BeamMonitor") << "testScroll::  Last non zero bin = " << lastNZbin << std::endl;
01396     if (tmpTime_ - refTime_ >= intervalInSec_ + lastNZbin) {
01397       edm::LogInfo("BeamMonitor") << "testScroll::  Time difference too large since last readout" << std::endl;
01398       lastNZbin = 0;
01399       refTime_ = tmpTime_ - buffTime;
01400     }
01401     else{
01402       edm::LogInfo("BeamMonitor") << "testScroll::  Offset to last record" << std::endl;
01403       int offset = ((lastNZbin > buffTime) ? (lastNZbin - buffTime) : (lastNZbin - 1));
01404       refTime_ += offset;
01405     }
01406   }
01407   return scroll_;
01408 }
01409 
01410 DEFINE_FWK_MODULE(BeamMonitor);