CMS 3D CMS Logo

/data/refman/pasoursint/CMSSW_4_1_8_patch13/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: 2010/10/28 08:47:16 $
00006  * $Revision: 1.59 $
00007  *
00008  */
00009 
00010 #include "DQM/BeamMonitor/plugins/BeamMonitor.h"
00011 #include "DQMServices/Core/interface/QReport.h"
00012 #include "FWCore/ServiceRegistry/interface/Service.h"
00013 #include "DataFormats/BeamSpot/interface/BeamSpot.h"
00014 #include "DataFormats/VertexReco/interface/Vertex.h"
00015 #include "DataFormats/VertexReco/interface/VertexFwd.h"
00016 #include "DataFormats/TrackCandidate/interface/TrackCandidate.h"
00017 #include "DataFormats/TrackCandidate/interface/TrackCandidateCollection.h"
00018 #include "DataFormats/TrackReco/interface/Track.h"
00019 #include "DataFormats/TrackReco/interface/TrackFwd.h"
00020 #include "DataFormats/Common/interface/View.h"
00021 #include "RecoVertex/BeamSpotProducer/interface/BSFitter.h"
00022 #include "FWCore/Framework/interface/MakerMacros.h"
00023 #include "FWCore/Framework/interface/LuminosityBlock.h"
00024 #include "FWCore/Framework/interface/Run.h"
00025 #include "FWCore/MessageLogger/interface/MessageLogger.h"
00026 #include <numeric>
00027 #include <math.h>
00028 #include <TMath.h>
00029 #include <iostream>
00030 #include <TStyle.h>
00031 
00032 using namespace std;
00033 using namespace edm;
00034 
00035 const char * BeamMonitor::formatFitTime( const time_t & t )  {
00036 #define CET (+1)
00037 #define CEST (+2)
00038 
00039   static char ts[] = "yyyy-Mm-dd hh:mm:ss";
00040   tm * ptm;
00041   ptm = gmtime ( &t );
00042   int year = ptm->tm_year;
00043   if (year < 1995) {
00044     edm::LogError("BadTimeStamp") << "year reported is " << year << "!! resetting to 2010..." << std::endl;
00045     year = 2010;
00046   }
00047   sprintf( ts, "%4d-%02d-%02d %02d:%02d:%02d", 2010,ptm->tm_mon+1,ptm->tm_mday,(ptm->tm_hour+CEST)%24, ptm->tm_min, ptm->tm_sec);
00048 
00049 #ifdef STRIP_TRAILING_BLANKS_IN_TIMEZONE
00050   unsigned int b = strlen(ts);
00051   while (ts[--b] == ' ') {ts[b] = 0;}
00052 #endif
00053   return ts;
00054 
00055 }
00056 
00057 #define buffTime (23)
00058 
00059 //
00060 // constructors and destructor
00061 //
00062 BeamMonitor::BeamMonitor( const ParameterSet& ps ) :
00063   countEvt_(0),countLumi_(0),nthBSTrk_(0),nFitElements_(3),resetHistos_(false) {
00064 
00065   parameters_     = ps;
00066   monitorName_    = parameters_.getUntrackedParameter<string>("monitorName","YourSubsystemName");
00067   bsSrc_          = parameters_.getUntrackedParameter<InputTag>("beamSpot");
00068   pvSrc_          = parameters_.getUntrackedParameter<InputTag>("primaryVertex");
00069   intervalInSec_  = parameters_.getUntrackedParameter<int>("timeInterval",920);//40 LS X 23"
00070   fitNLumi_       = parameters_.getUntrackedParameter<int>("fitEveryNLumi",-1);
00071   resetFitNLumi_  = parameters_.getUntrackedParameter<int>("resetEveryNLumi",-1);
00072   fitPVNLumi_     = parameters_.getUntrackedParameter<int>("fitPVEveryNLumi",-1);
00073   resetPVNLumi_   = parameters_.getUntrackedParameter<int>("resetPVEveryNLumi",-1);
00074   deltaSigCut_    = parameters_.getUntrackedParameter<double>("deltaSignificanceCut",15);
00075   debug_          = parameters_.getUntrackedParameter<bool>("Debug");
00076   onlineMode_     = parameters_.getUntrackedParameter<bool>("OnlineMode");
00077   tracksLabel_    = parameters_.getParameter<ParameterSet>("BeamFitter").getUntrackedParameter<InputTag>("TrackCollection");
00078   min_Ntrks_      = parameters_.getParameter<ParameterSet>("BeamFitter").getUntrackedParameter<int>("MinimumInputTracks");
00079   maxZ_           = parameters_.getParameter<ParameterSet>("BeamFitter").getUntrackedParameter<double>("MaximumZ");
00080   minNrVertices_  = parameters_.getParameter<ParameterSet>("PVFitter").getUntrackedParameter<unsigned int>("minNrVerticesForFit");
00081   minVtxNdf_      = parameters_.getParameter<ParameterSet>("PVFitter").getUntrackedParameter<double>("minVertexNdf");
00082   minVtxWgt_      = parameters_.getParameter<ParameterSet>("PVFitter").getUntrackedParameter<double>("minVertexMeanWeight");
00083 
00084   dbe_            = Service<DQMStore>().operator->();
00085 
00086   if (monitorName_ != "" ) monitorName_ = monitorName_+"/" ;
00087 
00088   theBeamFitter = new BeamFitter(parameters_);
00089   theBeamFitter->resetTrkVector();
00090   theBeamFitter->resetLSRange();
00091   theBeamFitter->resetRefTime();
00092   theBeamFitter->resetPVFitter();
00093 
00094   if (fitNLumi_ <= 0) fitNLumi_ = 1;
00095   nFits_ = beginLumiOfBSFit_ = endLumiOfBSFit_ = beginLumiOfPVFit_ = endLumiOfPVFit_ = 0;
00096   refBStime[0] = refBStime[1] = refPVtime[0] = refPVtime[1] = 0;
00097   maxZ_ = std::fabs(maxZ_);
00098   lastlumi_ = 0;
00099   nextlumi_ = 0;
00100   processed_ = false;
00101 }
00102 
00103 
00104 BeamMonitor::~BeamMonitor() {
00105   delete theBeamFitter;
00106 }
00107 
00108 
00109 //--------------------------------------------------------
00110 void BeamMonitor::beginJob() {
00111 
00112   // book some histograms here
00113   const int    dxBin = parameters_.getParameter<int>("dxBin");
00114   const double dxMin  = parameters_.getParameter<double>("dxMin");
00115   const double dxMax  = parameters_.getParameter<double>("dxMax");
00116 
00117   const int    vxBin = parameters_.getParameter<int>("vxBin");
00118   const double vxMin  = parameters_.getParameter<double>("vxMin");
00119   const double vxMax  = parameters_.getParameter<double>("vxMax");
00120 
00121   const int    phiBin = parameters_.getParameter<int>("phiBin");
00122   const double phiMin  = parameters_.getParameter<double>("phiMin");
00123   const double phiMax  = parameters_.getParameter<double>("phiMax");
00124 
00125   const int    dzBin = parameters_.getParameter<int>("dzBin");
00126   const double dzMin  = parameters_.getParameter<double>("dzMin");
00127   const double dzMax  = parameters_.getParameter<double>("dzMax");
00128 
00129   // create and cd into new folder
00130   dbe_->setCurrentFolder(monitorName_+"Fit");
00131 
00132   h_nTrk_lumi=dbe_->book1D("nTrk_lumi","Num. of selected tracks vs lumi",20,0.5,20.5);
00133   h_nTrk_lumi->setAxisTitle("Lumisection",1);
00134   h_nTrk_lumi->setAxisTitle("Num of Tracks",2);
00135 
00136   h_d0_phi0 = dbe_->bookProfile("d0_phi0","d_{0} vs. #phi_{0} (Selected Tracks)",phiBin,phiMin,phiMax,dxBin,dxMin,dxMax,"");
00137   h_d0_phi0->setAxisTitle("#phi_{0} (rad)",1);
00138   h_d0_phi0->setAxisTitle("d_{0} (cm)",2);
00139 
00140   h_vx_vy = dbe_->book2D("trk_vx_vy","Vertex (PCA) position of selected tracks",vxBin,vxMin,vxMax,vxBin,vxMin,vxMax);
00141   h_vx_vy->getTH2F()->SetOption("COLZ");
00142   //   h_vx_vy->getTH1()->SetBit(TH1::kCanRebin);
00143   h_vx_vy->setAxisTitle("x coordinate of input track at PCA (cm)",1);
00144   h_vx_vy->setAxisTitle("y coordinate of input track at PCA (cm)",2);
00145 
00146   TDatime *da = new TDatime();
00147   gStyle->SetTimeOffset(da->Convert(kTRUE));
00148 
00149   const int nvar_ = 6;
00150   string coord[nvar_] = {"x","y","z","sigmaX","sigmaY","sigmaZ"};
00151   string label[nvar_] = {"x_{0} (cm)","y_{0} (cm)","z_{0} (cm)",
00152                          "#sigma_{X_{0}} (cm)","#sigma_{Y_{0}} (cm)","#sigma_{Z_{0}} (cm)"};
00153   for (int i = 0; i < 4; i++) {
00154     dbe_->setCurrentFolder(monitorName_+"Fit");
00155     for (int ic=0; ic<nvar_; ++ic) {
00156       TString histName(coord[ic]);
00157       TString histTitle(coord[ic]);
00158       string ytitle(label[ic]);
00159       string xtitle("");
00160       string options("E1");
00161       bool createHisto = true;
00162       switch(i) {
00163       case 1: // BS vs time
00164         histName += "0_time";
00165         xtitle = "Time [UTC]";
00166         if (ic < 3)
00167           histTitle += " coordinate of beam spot vs time (Fit)";
00168         else
00169           histTitle = histTitle.Insert(5," ") + " of beam spot vs time (Fit)";
00170         break;
00171       case 2: // PV vs lumi
00172         if (ic < 3) {
00173           dbe_->setCurrentFolder(monitorName_+"PrimaryVertex");
00174           histName.Insert(0,"PV");
00175           histName += "_lumi";
00176           histTitle.Insert(0,"Avg. ");
00177           histTitle += " position of primary vtx vs lumi";
00178           xtitle = "Lumisection";
00179           ytitle.insert(0,"PV");
00180           ytitle += " #pm #sigma_{PV";
00181           ytitle += coord[ic];
00182           ytitle += "} (cm)";
00183         }
00184         else createHisto = false;
00185         break;
00186       case 3: // PV vs time
00187         if (ic < 3) {
00188           dbe_->setCurrentFolder(monitorName_+"PrimaryVertex");
00189           histName.Insert(0,"PV");
00190           histName += "_time";
00191           histTitle.Insert(0,"Avg. ");
00192           histTitle += " position of primary vtx vs time";
00193           xtitle = "Time [UTC]";
00194           ytitle.insert(0,"PV");
00195           ytitle += " #pm #sigma_{PV";
00196           ytitle += coord[ic];
00197           ytitle += "} (cm)";
00198         }
00199         else createHisto = false;
00200         break;
00201       default: // BS vs lumi
00202         histName += "0_lumi";
00203         xtitle = "Lumisection";
00204         if (ic < 3)
00205           histTitle += " coordinate of beam spot vs lumi (Fit)";
00206         else
00207           histTitle = histTitle.Insert(5," ") + " of beam spot vs lumi (Fit)";
00208         break;
00209       }
00210       if (createHisto) {
00211         edm::LogInfo("BeamMonitor") << "hitsName = " << histName << "; histTitle = " << histTitle << std::endl;
00212         hs[histName] = dbe_->book1D(histName,histTitle,40,0.5,40.5);
00213         hs[histName]->setAxisTitle(xtitle,1);
00214         hs[histName]->setAxisTitle(ytitle,2);
00215         hs[histName]->getTH1()->SetOption("E1");
00216         if (histName.Contains("time")) {
00217           //int nbins = (intervalInSec_/23 > 0 ? intervalInSec_/23 : 40);
00218           hs[histName]->getTH1()->SetBins(intervalInSec_,0.5,intervalInSec_+0.5);
00219           hs[histName]->setAxisTimeDisplay(1);
00220           hs[histName]->setAxisTimeFormat("%H:%M:%S",1);
00221         }
00222         histName += "_all";
00223         histTitle += " all";
00224         hs[histName] = dbe_->book1D(histName,histTitle,40,0.5,40.5);
00225         hs[histName]->getTH1()->SetBit(TH1::kCanRebin);
00226         hs[histName]->setAxisTitle(xtitle,1);
00227         hs[histName]->setAxisTitle(ytitle,2);
00228         hs[histName]->getTH1()->SetOption("E1");
00229         if (histName.Contains("time")) {
00230           //int nbins = (intervalInSec_/23 > 0 ? intervalInSec_/23 : 40);
00231           hs[histName]->getTH1()->SetBins(intervalInSec_,0.5,intervalInSec_+0.5);
00232           hs[histName]->setAxisTimeDisplay(1);
00233           hs[histName]->setAxisTimeFormat("%H:%M:%S",1);
00234         }
00235       }
00236     }
00237   }
00238   dbe_->setCurrentFolder(monitorName_+"Fit");
00239 
00240   h_trk_z0 = dbe_->book1D("trk_z0","z_{0} of selected tracks",dzBin,dzMin,dzMax);
00241   h_trk_z0->setAxisTitle("z_{0} of selected tracks (cm)",1);
00242 
00243   h_vx_dz = dbe_->bookProfile("vx_dz","v_{x} vs. dz of selected tracks",dzBin,dzMin,dzMax,dxBin,dxMin,dxMax,"");
00244   h_vx_dz->setAxisTitle("dz (cm)",1);
00245   h_vx_dz->setAxisTitle("x coordinate of input track at PCA (cm)",2);
00246 
00247   h_vy_dz = dbe_->bookProfile("vy_dz","v_{y} vs. dz of selected tracks",dzBin,dzMin,dzMax,dxBin,dxMin,dxMax,"");
00248   h_vy_dz->setAxisTitle("dz (cm)",1);
00249   h_vy_dz->setAxisTitle("x coordinate of input track at PCA (cm)",2);
00250 
00251   h_x0 = dbe_->book1D("BeamMonitorFeedBack_x0","x coordinate of beam spot (Fit)",100,-0.01,0.01);
00252   h_x0->setAxisTitle("x_{0} (cm)",1);
00253   h_x0->getTH1()->SetBit(TH1::kCanRebin);
00254 
00255   h_y0 = dbe_->book1D("BeamMonitorFeedBack_y0","y coordinate of beam spot (Fit)",100,-0.01,0.01);
00256   h_y0->setAxisTitle("y_{0} (cm)",1);
00257   h_y0->getTH1()->SetBit(TH1::kCanRebin);
00258 
00259   h_z0 = dbe_->book1D("BeamMonitorFeedBack_z0","z coordinate of beam spot (Fit)",dzBin,dzMin,dzMax);
00260   h_z0->setAxisTitle("z_{0} (cm)",1);
00261   h_z0->getTH1()->SetBit(TH1::kCanRebin);
00262 
00263   h_sigmaX0 = dbe_->book1D("BeamMonitorFeedBack_sigmaX0","sigma x0 of beam spot (Fit)",100,0,0.05);
00264   h_sigmaX0->setAxisTitle("#sigma_{X_{0}} (cm)",1);
00265   h_sigmaX0->getTH1()->SetBit(TH1::kCanRebin);
00266 
00267   h_sigmaY0 = dbe_->book1D("BeamMonitorFeedBack_sigmaY0","sigma y0 of beam spot (Fit)",100,0,0.05);
00268   h_sigmaY0->setAxisTitle("#sigma_{Y_{0}} (cm)",1);
00269   h_sigmaY0->getTH1()->SetBit(TH1::kCanRebin);
00270 
00271   h_sigmaZ0 = dbe_->book1D("BeamMonitorFeedBack_sigmaZ0","sigma z0 of beam spot (Fit)",100,0,10);
00272   h_sigmaZ0->setAxisTitle("#sigma_{Z_{0}} (cm)",1);
00273   h_sigmaZ0->getTH1()->SetBit(TH1::kCanRebin);
00274 
00275   // Histograms of all reco tracks (without cuts):
00276   h_trkPt=dbe_->book1D("trkPt","p_{T} of all reco'd tracks (no selection)",200,0.,50.);
00277   h_trkPt->setAxisTitle("p_{T} (GeV/c)",1);
00278 
00279   h_trkVz=dbe_->book1D("trkVz","Z coordinate of PCA of all reco'd tracks (no selection)",dzBin,dzMin,dzMax);
00280   h_trkVz->setAxisTitle("V_{Z} (cm)",1);
00281 
00282   cutFlowTable = dbe_->book1D("cutFlowTable","Cut flow table of track selection", 9, 0, 9 );
00283 
00284   // Results of previous good fit:
00285   fitResults=dbe_->book2D("fitResults","Results of previous good beam fit",2,0,2,8,0,8);
00286   fitResults->setAxisTitle("Fitted Beam Spot (cm)",1);
00287   fitResults->setBinLabel(8,"x_{0}",2);
00288   fitResults->setBinLabel(7,"y_{0}",2);
00289   fitResults->setBinLabel(6,"z_{0}",2);
00290   fitResults->setBinLabel(5,"#sigma_{Z}",2);
00291   fitResults->setBinLabel(4,"#frac{dx}{dz} (rad)",2);
00292   fitResults->setBinLabel(3,"#frac{dy}{dz} (rad)",2);
00293   fitResults->setBinLabel(2,"#sigma_{X}",2);
00294   fitResults->setBinLabel(1,"#sigma_{Y}",2);
00295   fitResults->setBinLabel(1,"Mean",1);
00296   fitResults->setBinLabel(2,"Stat. Error",1);
00297   fitResults->getTH1()->SetOption("text");
00298 
00299   // Histos of PrimaryVertices:
00300   dbe_->setCurrentFolder(monitorName_+"PrimaryVertex");
00301 
00302   h_nVtx = dbe_->book1D("vtxNbr","Reconstructed Vertices in Event",20,-0.5,19.5);
00303   h_nVtx->setAxisTitle("Num. of reco. vertices",1);
00304 
00305   // Monitor only the PV with highest sum pt of assoc. trks:
00306   h_PVx[0] = dbe_->book1D("PVX","x coordinate of Primary Vtx",50,-0.01,0.01);
00307   h_PVx[0]->setAxisTitle("PVx (cm)",1);
00308   h_PVx[0]->getTH1()->SetBit(TH1::kCanRebin);
00309 
00310   h_PVy[0] = dbe_->book1D("PVY","y coordinate of Primary Vtx",50,-0.01,0.01);
00311   h_PVy[0]->setAxisTitle("PVy (cm)",1);
00312   h_PVy[0]->getTH1()->SetBit(TH1::kCanRebin);
00313 
00314   h_PVz[0] = dbe_->book1D("PVZ","z coordinate of Primary Vtx",dzBin,dzMin,dzMax);
00315   h_PVz[0]->setAxisTitle("PVz (cm)",1);
00316 
00317   h_PVx[1] = dbe_->book1D("PVXFit","x coordinate of Primary Vtx (Last Fit)",50,-0.01,0.01);
00318   h_PVx[1]->setAxisTitle("PVx (cm)",1);
00319   h_PVx[1]->getTH1()->SetBit(TH1::kCanRebin);
00320 
00321   h_PVy[1] = dbe_->book1D("PVYFit","y coordinate of Primary Vtx (Last Fit)",50,-0.01,0.01);
00322   h_PVy[1]->setAxisTitle("PVy (cm)",1);
00323   h_PVy[1]->getTH1()->SetBit(TH1::kCanRebin);
00324 
00325   h_PVz[1] = dbe_->book1D("PVZFit","z coordinate of Primary Vtx (Last Fit)",dzBin,dzMin,dzMax);
00326   h_PVz[1]->setAxisTitle("PVz (cm)",1);
00327 
00328   h_PVxz = dbe_->bookProfile("PVxz","PVx vs. PVz",dzBin/2,dzMin,dzMax,dxBin/2,dxMin,dxMax,"");
00329   h_PVxz->setAxisTitle("PVz (cm)",1);
00330   h_PVxz->setAxisTitle("PVx (cm)",2);
00331 
00332   h_PVyz = dbe_->bookProfile("PVyz","PVy vs. PVz",dzBin/2,dzMin,dzMax,dxBin/2,dxMin,dxMax,"");
00333   h_PVyz->setAxisTitle("PVz (cm)",1);
00334   h_PVyz->setAxisTitle("PVy (cm)",2);
00335 
00336   // Results of previous good fit:
00337   pvResults=dbe_->book2D("pvResults","Results of fitting Primary Vertices",2,0,2,6,0,6);
00338   pvResults->setAxisTitle("Fitted Primary Vertex (cm)",1);
00339   pvResults->setBinLabel(6,"PVx",2);
00340   pvResults->setBinLabel(5,"PVy",2);
00341   pvResults->setBinLabel(4,"PVz",2);
00342   pvResults->setBinLabel(3,"#sigma_{X}",2);
00343   pvResults->setBinLabel(2,"#sigma_{Y}",2);
00344   pvResults->setBinLabel(1,"#sigma_{Z}",2);
00345   pvResults->setBinLabel(1,"Mean",1);
00346   pvResults->setBinLabel(2,"Stat. Error",1);
00347   pvResults->getTH1()->SetOption("text");
00348 
00349   // Summary plots:
00350   dbe_->setCurrentFolder(monitorName_+"EventInfo");
00351   reportSummary = dbe_->get(monitorName_+"EventInfo/reportSummary");
00352   if (reportSummary) dbe_->removeElement(reportSummary->getName());
00353 
00354   reportSummary = dbe_->bookFloat("reportSummary");
00355   if(reportSummary) reportSummary->Fill(0./0.);
00356 
00357   char histo[20];
00358   dbe_->setCurrentFolder(monitorName_+"EventInfo/reportSummaryContents");
00359   for (int n = 0; n < nFitElements_; n++) {
00360     switch(n){
00361     case 0 : sprintf(histo,"x0_status"); break;
00362     case 1 : sprintf(histo,"y0_status"); break;
00363     case 2 : sprintf(histo,"z0_status"); break;
00364     }
00365     reportSummaryContents[n] = dbe_->bookFloat(histo);
00366   }
00367 
00368   for (int i = 0; i < nFitElements_; i++) {
00369     summaryContent_[i] = 0.;
00370     reportSummaryContents[i]->Fill(0./0.);
00371   }
00372 
00373   dbe_->setCurrentFolder(monitorName_+"EventInfo");
00374 
00375   reportSummaryMap = dbe_->get(monitorName_+"EventInfo/reportSummaryMap");
00376   if (reportSummaryMap) dbe_->removeElement(reportSummaryMap->getName());
00377 
00378   reportSummaryMap = dbe_->book2D("reportSummaryMap", "Beam Spot Summary Map", 1, 0, 1, 3, 0, 3);
00379   reportSummaryMap->setAxisTitle("",1);
00380   reportSummaryMap->setAxisTitle("Fitted Beam Spot",2);
00381   reportSummaryMap->setBinLabel(1," ",1);
00382   reportSummaryMap->setBinLabel(1,"x_{0}",2);
00383   reportSummaryMap->setBinLabel(2,"y_{0}",2);
00384   reportSummaryMap->setBinLabel(3,"z_{0}",2);
00385   for (int i = 0; i < nFitElements_; i++) {
00386     reportSummaryMap->setBinContent(1,i+1,-1.);
00387   }
00388 }
00389 
00390 //--------------------------------------------------------
00391 void BeamMonitor::beginRun(const edm::Run& r, const EventSetup& context) {
00392 
00393   ftimestamp = r.beginTime().value();
00394   tmpTime = ftimestamp >> 32;
00395   startTime = refTime =  tmpTime;
00396   const char* eventTime = formatFitTime(tmpTime);
00397   std::cout << "TimeOffset = " << eventTime << std::endl;
00398   TDatime da(eventTime);
00399   if (debug_) {
00400     edm::LogInfo("BeamMonitor") << "TimeOffset = ";
00401     da.Print();
00402   }
00403   for (std::map<TString,MonitorElement*>::iterator it = hs.begin();
00404        it != hs.end(); ++it) {
00405     if ((*it).first.Contains("time"))
00406       (*it).second->getTH1()->GetXaxis()->SetTimeOffset(da.Convert(kTRUE));
00407   }
00408 }
00409 
00410 //--------------------------------------------------------
00411 void BeamMonitor::beginLuminosityBlock(const LuminosityBlock& lumiSeg,
00412                                        const EventSetup& context) {
00413   int nthlumi = lumiSeg.luminosityBlock();
00414   const edm::TimeValue_t fbegintimestamp = lumiSeg.beginTime().value();
00415   const std::time_t ftmptime = fbegintimestamp >> 32;
00416 
00417   if (countLumi_ == 0) {
00418     beginLumiOfBSFit_ = beginLumiOfPVFit_ = nthlumi;
00419     refBStime[0] = refPVtime[0] = ftmptime;
00420   }
00421   if (beginLumiOfPVFit_ == 0) beginLumiOfPVFit_ = nextlumi_;
00422   if (beginLumiOfBSFit_ == 0) beginLumiOfBSFit_ = nextlumi_;
00423 
00424   if (onlineMode_ && (nthlumi < nextlumi_)) return;
00425 
00426   if (onlineMode_) {
00427     if (nthlumi > nextlumi_) {
00428       if (countLumi_ != 0 && processed_) FitAndFill(lumiSeg,lastlumi_,nextlumi_,nthlumi);
00429       nextlumi_ = nthlumi;
00430       edm::LogInfo("BeamMonitor") << "Next Lumi to Fit: " << nextlumi_ << endl;
00431       if (refBStime[0] == 0) refBStime[0] = ftmptime;
00432       if (refPVtime[0] == 0) refPVtime[0] = ftmptime;
00433     }
00434   }
00435   else{
00436     if (processed_) FitAndFill(lumiSeg,lastlumi_,nextlumi_,nthlumi);
00437     nextlumi_ = nthlumi;
00438     edm::LogInfo("BeamMonitor") << "Next Lumi to Fit: " << nextlumi_ << endl;
00439     if (refBStime[0] == 0) refBStime[0] = ftmptime;
00440     if (refPVtime[0] == 0) refPVtime[0] = ftmptime;
00441   }
00442   countLumi_++;
00443   if (processed_) processed_ = false;
00444   edm::LogInfo("BeamMonitor") << "Begin of Lumi: " << nthlumi << endl;
00445 }
00446 
00447 // ----------------------------------------------------------
00448 void BeamMonitor::analyze(const Event& iEvent,
00449                           const EventSetup& iSetup ) {
00450   bool readEvent_ = true;
00451   const int nthlumi = iEvent.luminosityBlock();
00452   if (onlineMode_ && (nthlumi < nextlumi_)) {
00453     readEvent_ = false;
00454     edm::LogInfo("BeamMonitor") << "Spilt event from previous lumi section!" << std::endl;
00455   }
00456   if (onlineMode_ && (nthlumi > nextlumi_)) {
00457     readEvent_ = false;
00458     edm::LogInfo("BeamMonitor") << "Spilt event from next lumi section!!!" << std::endl;
00459   }
00460 
00461   if (readEvent_) {
00462     countEvt_++;
00463     theBeamFitter->readEvent(iEvent);
00464     Handle<reco::BeamSpot> recoBeamSpotHandle;
00465     iEvent.getByLabel(bsSrc_,recoBeamSpotHandle);
00466     refBS = *recoBeamSpotHandle;
00467 
00468     dbe_->setCurrentFolder(monitorName_+"Fit/");
00469     const char* tmpfile;
00470     TH1F * tmphisto;
00471     tmpfile = (cutFlowTable->getName()).c_str();
00472     tmphisto = static_cast<TH1F *>((theBeamFitter->getCutFlow())->Clone("tmphisto"));
00473     cutFlowTable->getTH1()->SetBins(tmphisto->GetNbinsX(),tmphisto->GetXaxis()->GetXmin(),tmphisto->GetXaxis()->GetXmax());
00474     if (countEvt_ == 1) // SetLabel just once
00475       for(int n=0; n < tmphisto->GetNbinsX(); n++)
00476         cutFlowTable->setBinLabel(n+1,tmphisto->GetXaxis()->GetBinLabel(n+1),1);
00477 
00478     cutFlowTable = dbe_->book1D(tmpfile,tmphisto);
00479 
00480     Handle<reco::TrackCollection> TrackCollection;
00481     iEvent.getByLabel(tracksLabel_, TrackCollection);
00482     const reco::TrackCollection *tracks = TrackCollection.product();
00483     for ( reco::TrackCollection::const_iterator track = tracks->begin();
00484           track != tracks->end(); ++track ) {
00485       h_trkPt->Fill(track->pt());
00486       h_trkVz->Fill(track->vz());
00487     }
00488 
00489     //------ Primary Vertices
00490     edm::Handle< reco::VertexCollection > PVCollection;
00491 
00492     if (iEvent.getByLabel(pvSrc_, PVCollection )) {
00493       int nPVcount = 0;
00494       for (reco::VertexCollection::const_iterator pv = PVCollection->begin(); pv != PVCollection->end(); ++pv) {
00495         //--- vertex selection
00496         if (pv->isFake() || pv->tracksSize()==0)  continue;
00497         nPVcount++; // count non fake pv
00498         if (pv->ndof() < minVtxNdf_ || (pv->ndof()+3.)/pv->tracksSize() < 2*minVtxWgt_)  continue;
00499         h_PVx[0]->Fill(pv->x());
00500         h_PVy[0]->Fill(pv->y());
00501         h_PVz[0]->Fill(pv->z());
00502         h_PVxz->Fill(pv->z(),pv->x());
00503         h_PVyz->Fill(pv->z(),pv->y());
00504       }
00505       if (nPVcount>0) h_nVtx->Fill(nPVcount*1.);
00506     }
00507     processed_ = true;
00508   }//end of read event
00509 
00510 }
00511 
00512 
00513 //--------------------------------------------------------
00514 void BeamMonitor::endLuminosityBlock(const LuminosityBlock& lumiSeg,
00515                                      const EventSetup& iSetup) {
00516   int nthlumi = lumiSeg.id().luminosityBlock();
00517   edm::LogInfo("BeamMonitor") << "Lumi of the last event before endLuminosityBlock: " << nthlumi << endl;
00518 
00519   if (onlineMode_ && nthlumi < nextlumi_) return;
00520   const edm::TimeValue_t fendtimestamp = lumiSeg.endTime().value();
00521   const std::time_t fendtime = fendtimestamp >> 32;
00522   tmpTime = refBStime[1] = refPVtime[1] = fendtime;
00523 }
00524 
00525 //--------------------------------------------------------
00526 void BeamMonitor::FitAndFill(const LuminosityBlock& lumiSeg,int &lastlumi,int &nextlumi,int &nthlumi){
00527   if (onlineMode_ && (nthlumi <= nextlumi)) return;
00528 
00529   int currentlumi = nextlumi;
00530   edm::LogInfo("BeamMonitor") << "Lumi of the current fit: " << currentlumi << endl;
00531   lastlumi = currentlumi;
00532   endLumiOfBSFit_ = currentlumi;
00533   endLumiOfPVFit_ = currentlumi;
00534 
00535   if (onlineMode_) { // filling LS gap
00536     // FIXME: need to add protection for the case if the gap is at the resetting LS!
00537     const int countLS_bs = hs["x0_lumi"]->getTH1()->GetEntries();
00538     const int countLS_pv = hs["PVx_lumi"]->getTH1()->GetEntries();
00539     edm::LogInfo("BeamMonitor") << "countLS_bs = " << countLS_bs << " ; countLS_pv = " << countLS_pv << std::endl;
00540     int LSgap_bs = currentlumi/fitNLumi_ - countLS_bs;
00541     int LSgap_pv = currentlumi/fitPVNLumi_ - countLS_pv;
00542     if (currentlumi%fitNLumi_ == 0)
00543       LSgap_bs--;
00544     if (currentlumi%fitPVNLumi_ == 0)
00545       LSgap_pv--;
00546     edm::LogInfo("BeamMonitor") << "LSgap_bs = " << LSgap_bs << " ; LSgap_pv = " << LSgap_pv << std::endl;
00547     // filling previous fits if LS gap ever exists
00548     for (int ig = 0; ig < LSgap_bs; ig++) {
00549       hs["x0_lumi"]->ShiftFillLast( 0., 0., fitNLumi_ );
00550       hs["y0_lumi"]->ShiftFillLast( 0., 0., fitNLumi_ );
00551       hs["z0_lumi"]->ShiftFillLast( 0., 0., fitNLumi_ );
00552       hs["sigmaX0_lumi"]->ShiftFillLast( 0., 0., fitNLumi_ );
00553       hs["sigmaY0_lumi"]->ShiftFillLast( 0., 0., fitNLumi_ );
00554       hs["sigmaZ0_lumi"]->ShiftFillLast( 0., 0., fitNLumi_ );
00555     }
00556     for (int ig = 0; ig < LSgap_pv; ig++) {
00557       hs["PVx_lumi"]->ShiftFillLast( 0., 0., fitPVNLumi_ );
00558       hs["PVy_lumi"]->ShiftFillLast( 0., 0., fitPVNLumi_ );
00559       hs["PVz_lumi"]->ShiftFillLast( 0., 0., fitPVNLumi_ );
00560     }
00561     const int previousLS = h_nTrk_lumi->getTH1()->GetEntries();
00562     for (int i=1;i < (currentlumi - previousLS);i++)
00563       h_nTrk_lumi->ShiftFillLast(nthBSTrk_);
00564   }
00565 
00566   edm::LogInfo("BeamMonitor") << "Time lapsed since last scroll = " << tmpTime - refTime << std:: endl;
00567 
00568   if (testScroll(tmpTime,refTime)) {
00569     scrollTH1(hs["x0_time"]->getTH1(),refTime);
00570     scrollTH1(hs["y0_time"]->getTH1(),refTime);
00571     scrollTH1(hs["z0_time"]->getTH1(),refTime);
00572     scrollTH1(hs["sigmaX0_time"]->getTH1(),refTime);
00573     scrollTH1(hs["sigmaY0_time"]->getTH1(),refTime);
00574     scrollTH1(hs["sigmaZ0_time"]->getTH1(),refTime);
00575     scrollTH1(hs["PVx_time"]->getTH1(),refTime);
00576     scrollTH1(hs["PVy_time"]->getTH1(),refTime);
00577     scrollTH1(hs["PVz_time"]->getTH1(),refTime);
00578   }
00579 
00580   bool doPVFit = false;
00581 
00582   if (fitPVNLumi_ > 0) {
00583     if (onlineMode_) {
00584       if (currentlumi%fitPVNLumi_ == 0)
00585         doPVFit = true;
00586     }
00587     else
00588       if (countLumi_%fitPVNLumi_ == 0)
00589         doPVFit = true;
00590   }
00591   else
00592     doPVFit = true;
00593 
00594   if (doPVFit) {
00595 
00596     edm::LogInfo("BeamMonitor") << "Do PV Fitting for LS = " << beginLumiOfPVFit_ << " to " << endLumiOfPVFit_ << std::endl;
00597     // Primary Vertex Fit:
00598     if (h_PVx[0]->getTH1()->GetEntries() > minNrVertices_) {
00599       pvResults->Reset();
00600       char tmpTitle[50];
00601       sprintf(tmpTitle,"%s %i %s %i","Fitted Primary Vertex (cm) of LS: ",beginLumiOfPVFit_," to ",endLumiOfPVFit_);
00602       pvResults->setAxisTitle(tmpTitle,1);
00603 
00604       TF1 *fgaus = new TF1("fgaus","gaus");
00605       double mean,width,meanErr,widthErr;
00606       fgaus->SetLineColor(4);
00607       h_PVx[0]->getTH1()->Fit("fgaus","QLM0");
00608       mean = fgaus->GetParameter(1);
00609       width = fgaus->GetParameter(2);
00610       meanErr = fgaus->GetParError(1);
00611       widthErr = fgaus->GetParError(2);
00612       hs["PVx_lumi"]->ShiftFillLast(mean,width,fitPVNLumi_);
00613       hs["PVx_lumi_all"]->setBinContent(currentlumi,mean);
00614       hs["PVx_lumi_all"]->setBinError(currentlumi,width);
00615       int nthBin = tmpTime - refTime;
00616       if (nthBin < 0)
00617         edm::LogInfo("BeamMonitor") << "Event time outside current range of time histograms!" << std::endl;
00618       if (nthBin > 0) {
00619         hs["PVx_time"]->setBinContent(nthBin,mean);
00620         hs["PVx_time"]->setBinError(nthBin,width);
00621       }
00622       int jthBin = tmpTime - startTime;
00623       if (jthBin > 0) {
00624         hs["PVx_time_all"]->setBinContent(jthBin,mean);
00625         hs["PVx_time_all"]->setBinError(jthBin,width);
00626       }
00627       pvResults->setBinContent(1,6,mean);
00628       pvResults->setBinContent(1,3,width);
00629       pvResults->setBinContent(2,6,meanErr);
00630       pvResults->setBinContent(2,3,widthErr);
00631 
00632       dbe_->setCurrentFolder(monitorName_+"PrimaryVertex/");
00633       const char* tmpfile;
00634       TH1D * tmphisto;
00635       // snap shot of the fit
00636       tmpfile= (h_PVx[1]->getName()).c_str();
00637       tmphisto = static_cast<TH1D *>((h_PVx[0]->getTH1())->Clone("tmphisto"));
00638       h_PVx[1]->getTH1()->SetBins(tmphisto->GetNbinsX(),tmphisto->GetXaxis()->GetXmin(),tmphisto->GetXaxis()->GetXmax());
00639       h_PVx[1] = dbe_->book1D(tmpfile,h_PVx[0]->getTH1F());
00640       h_PVx[1]->getTH1()->Fit("fgaus","QLM");
00641 
00642 
00643       h_PVy[0]->getTH1()->Fit("fgaus","QLM0");
00644       mean = fgaus->GetParameter(1);
00645       width = fgaus->GetParameter(2);
00646       meanErr = fgaus->GetParError(1);
00647       widthErr = fgaus->GetParError(2);
00648       hs["PVy_lumi"]->ShiftFillLast(mean,width,fitPVNLumi_);
00649       hs["PVy_lumi_all"]->setBinContent(currentlumi,mean);
00650       hs["PVy_lumi_all"]->setBinError(currentlumi,width);
00651       if (nthBin > 0) {
00652         hs["PVy_time"]->setBinContent(nthBin,mean);
00653         hs["PVy_time"]->setBinError(nthBin,width);
00654       }
00655       if (jthBin > 0) {
00656         hs["PVy_time_all"]->setBinContent(jthBin,mean);
00657         hs["PVy_time_all"]->setBinError(jthBin,width);
00658       }
00659       pvResults->setBinContent(1,5,mean);
00660       pvResults->setBinContent(1,2,width);
00661       pvResults->setBinContent(2,5,meanErr);
00662       pvResults->setBinContent(2,2,widthErr);
00663       // snap shot of the fit
00664       tmpfile= (h_PVy[1]->getName()).c_str();
00665       tmphisto = static_cast<TH1D *>((h_PVy[0]->getTH1())->Clone("tmphisto"));
00666       h_PVy[1]->getTH1()->SetBins(tmphisto->GetNbinsX(),tmphisto->GetXaxis()->GetXmin(),tmphisto->GetXaxis()->GetXmax());
00667       h_PVy[1]->update();
00668       h_PVy[1] = dbe_->book1D(tmpfile,h_PVy[0]->getTH1F());
00669       h_PVy[1]->getTH1()->Fit("fgaus","QLM");
00670 
00671 
00672       h_PVz[0]->getTH1()->Fit("fgaus","QLM0");
00673       mean = fgaus->GetParameter(1);
00674       width = fgaus->GetParameter(2);
00675       meanErr = fgaus->GetParError(1);
00676       widthErr = fgaus->GetParError(2);
00677       hs["PVz_lumi"]->ShiftFillLast(mean,width,fitPVNLumi_);
00678       hs["PVz_lumi_all"]->setBinContent(currentlumi,mean);
00679       hs["PVz_lumi_all"]->setBinError(currentlumi,width);
00680       if (nthBin > 0) {
00681         hs["PVz_time"]->setBinContent(nthBin,mean);
00682         hs["PVz_time"]->setBinError(nthBin,width);
00683       }
00684       if (jthBin > 0) {
00685         hs["PVz_time_all"]->setBinContent(jthBin,mean);
00686         hs["PVz_time_all"]->setBinError(jthBin,width);
00687       }
00688       pvResults->setBinContent(1,4,mean);
00689       pvResults->setBinContent(1,1,width);
00690       pvResults->setBinContent(2,4,meanErr);
00691       pvResults->setBinContent(2,1,widthErr);
00692       // snap shot of the fit
00693       tmpfile= (h_PVz[1]->getName()).c_str();
00694       tmphisto = static_cast<TH1D *>((h_PVz[0]->getTH1())->Clone("tmphisto"));
00695       h_PVz[1]->getTH1()->SetBins(tmphisto->GetNbinsX(),tmphisto->GetXaxis()->GetXmin(),tmphisto->GetXaxis()->GetXmax());
00696       h_PVz[1]->update();
00697       h_PVz[1] = dbe_->book1D(tmpfile,h_PVz[0]->getTH1F());
00698       h_PVz[1]->getTH1()->Fit("fgaus","QLM");
00699 
00700     }
00701   }
00702 
00703   if (resetPVNLumi_ > 0 &&
00704       ((onlineMode_ && currentlumi%resetPVNLumi_ == 0) ||
00705        (!onlineMode_ && countLumi_%resetPVNLumi_ == 0))) {
00706     h_PVx[0]->Reset();
00707     h_PVy[0]->Reset();
00708     h_PVz[0]->Reset();
00709     beginLumiOfPVFit_ = 0;
00710     refPVtime[0] = 0;
00711   }
00712 
00713   // Beam Spot Fit:
00714   vector<BSTrkParameters> theBSvector = theBeamFitter->getBSvector();
00715   h_nTrk_lumi->ShiftFillLast( theBSvector.size() );
00716 
00717   bool countFitting = false;
00718   if (theBSvector.size() > nthBSTrk_ && theBSvector.size() >= min_Ntrks_) {
00719     countFitting = true;
00720   }
00721 
00722   if (resetHistos_) {
00723     edm::LogInfo("BeamMonitor") << "Resetting Histograms" << endl;
00724     h_d0_phi0->Reset();
00725     h_vx_vy->Reset();
00726     h_vx_dz->Reset();
00727     h_vy_dz->Reset();
00728     h_trk_z0->Reset();
00729     theBeamFitter->resetCutFlow();
00730     resetHistos_ = false;
00731   }
00732 
00733   edm::LogInfo("BeamMonitor") << "Fill histos, start from " << nthBSTrk_ + 1 << "th record of selected tracks" << endl;
00734   unsigned int itrk = 0;
00735   for (vector<BSTrkParameters>::const_iterator BSTrk = theBSvector.begin();
00736        BSTrk != theBSvector.end();
00737        ++BSTrk, ++itrk){
00738     if (itrk >= nthBSTrk_){
00739       h_d0_phi0->Fill( BSTrk->phi0(), BSTrk->d0() );
00740       double vx = BSTrk->vx();
00741       double vy = BSTrk->vy();
00742       double z0 = BSTrk->z0();
00743       h_vx_vy->Fill( vx, vy );
00744       h_vx_dz->Fill( z0, vx );
00745       h_vy_dz->Fill( z0, vy );
00746       h_trk_z0->Fill( z0 );
00747     }
00748   }
00749   nthBSTrk_ = theBSvector.size(); // keep track of num of tracks filled so far
00750   if (countFitting) edm::LogInfo("BeamMonitor") << "Num of tracks collected = " << nthBSTrk_ << endl;
00751 
00752   if (fitNLumi_ > 0) {
00753     if (onlineMode_){
00754       if (currentlumi%fitNLumi_!=0) {
00755 //      for (std::map<TString,MonitorElement*>::iterator itAll = hs.begin();
00756 //           itAll != hs.end(); ++itAll) {
00757 //        if ((*itAll).first.Contains("all")) {
00758 //          (*itAll).second->setBinContent(currentlumi,0.);
00759 //          (*itAll).second->setBinError(currentlumi,0.);
00760 //        }
00761 //      }
00762         return;
00763       }
00764     }
00765     else
00766       if (countLumi_%fitNLumi_!=0) return;
00767   }
00768 
00769   edm::LogInfo("BeamMonitor") << " [DebugTime] refBStime[0] = " << refBStime[0]
00770                               << "; address =  " << &refBStime[0] << std::endl;
00771   edm::LogInfo("BeamMonitor") << " [DebugTime] refBStime[1] = " << refBStime[1]
00772                               << "; address =  " << &refBStime[1] << std::endl;
00773 
00774   if (countFitting) {
00775     nFits_++;
00776     int * fitLS = theBeamFitter->getFitLSRange();
00777     edm::LogInfo("BeamMonitor") << "[BeamFitter] Do BeamSpot Fit for LS = " << fitLS[0] << " to " << fitLS[1] << std::endl;
00778     edm::LogInfo("BeamMonitor") << "[BeamMonitor] Do BeamSpot Fit for LS = " << beginLumiOfBSFit_ << " to " << endLumiOfBSFit_ << std::endl;
00779     if (theBeamFitter->runPVandTrkFitter()) {
00780       reco::BeamSpot bs = theBeamFitter->getBeamSpot();
00781       if (bs.type() > 0) // with good beamwidth fit
00782         preBS = bs; // cache good fit results
00783       edm::LogInfo("BeamMonitor") << "\n RESULTS OF DEFAULT FIT:" << endl;
00784       edm::LogInfo("BeamMonitor") << bs << endl;
00785       edm::LogInfo("BeamMonitor") << "[BeamFitter] fitting done \n" << endl;
00786 
00787       hs["x0_lumi"]->ShiftFillLast( bs.x0(), bs.x0Error(), fitNLumi_ );
00788       hs["y0_lumi"]->ShiftFillLast( bs.y0(), bs.y0Error(), fitNLumi_ );
00789       hs["z0_lumi"]->ShiftFillLast( bs.z0(), bs.z0Error(), fitNLumi_ );
00790       hs["sigmaX0_lumi"]->ShiftFillLast( bs.BeamWidthX(), bs.BeamWidthXError(), fitNLumi_ );
00791       hs["sigmaY0_lumi"]->ShiftFillLast( bs.BeamWidthY(), bs.BeamWidthYError(), fitNLumi_ );
00792       hs["sigmaZ0_lumi"]->ShiftFillLast( bs.sigmaZ(), bs.sigmaZ0Error(), fitNLumi_ );
00793       hs["x0_lumi_all"]->setBinContent(currentlumi,bs.x0());
00794       hs["x0_lumi_all"]->setBinError(currentlumi,bs.x0Error());
00795       hs["y0_lumi_all"]->setBinContent(currentlumi,bs.y0());
00796       hs["y0_lumi_all"]->setBinError(currentlumi,bs.y0Error());
00797       hs["z0_lumi_all"]->setBinContent(currentlumi,bs.z0());
00798       hs["z0_lumi_all"]->setBinError(currentlumi,bs.z0Error());
00799       hs["sigmaX0_lumi_all"]->setBinContent(currentlumi, bs.BeamWidthX());
00800       hs["sigmaX0_lumi_all"]->setBinError(currentlumi, bs.BeamWidthXError());
00801       hs["sigmaY0_lumi_all"]->setBinContent(currentlumi, bs.BeamWidthY());
00802       hs["sigmaY0_lumi_all"]->setBinError(currentlumi, bs.BeamWidthYError());
00803       hs["sigmaZ0_lumi_all"]->setBinContent(currentlumi, bs.sigmaZ());
00804       hs["sigmaZ0_lumi_all"]->setBinError(currentlumi, bs.sigmaZ0Error());
00805 
00806       int nthBin = tmpTime - refTime;
00807       if (nthBin > 0) {
00808         hs["x0_time"]->setBinContent(nthBin, bs.x0());
00809         hs["y0_time"]->setBinContent(nthBin, bs.y0());
00810         hs["z0_time"]->setBinContent(nthBin, bs.z0());
00811         hs["sigmaX0_time"]->setBinContent(nthBin, bs.BeamWidthX());
00812         hs["sigmaY0_time"]->setBinContent(nthBin, bs.BeamWidthY());
00813         hs["sigmaZ0_time"]->setBinContent(nthBin, bs.sigmaZ());
00814         hs["x0_time"]->setBinError(nthBin, bs.x0Error());
00815         hs["y0_time"]->setBinError(nthBin, bs.y0Error());
00816         hs["z0_time"]->setBinError(nthBin, bs.z0Error());
00817         hs["sigmaX0_time"]->setBinError(nthBin, bs.BeamWidthXError());
00818         hs["sigmaY0_time"]->setBinError(nthBin, bs.BeamWidthYError());
00819         hs["sigmaZ0_time"]->setBinError(nthBin, bs.sigmaZ0Error());
00820       }
00821 
00822       int jthBin = tmpTime - startTime;
00823       if (jthBin > 0) {
00824         hs["x0_time_all"]->setBinContent(jthBin, bs.x0());
00825         hs["y0_time_all"]->setBinContent(jthBin, bs.y0());
00826         hs["z0_time_all"]->setBinContent(jthBin, bs.z0());
00827         hs["sigmaX0_time_all"]->setBinContent(jthBin, bs.BeamWidthX());
00828         hs["sigmaY0_time_all"]->setBinContent(jthBin, bs.BeamWidthY());
00829         hs["sigmaZ0_time_all"]->setBinContent(jthBin, bs.sigmaZ());
00830         hs["x0_time_all"]->setBinError(jthBin, bs.x0Error());
00831         hs["y0_time_all"]->setBinError(jthBin, bs.y0Error());
00832         hs["z0_time_all"]->setBinError(jthBin, bs.z0Error());
00833         hs["sigmaX0_time_all"]->setBinError(jthBin, bs.BeamWidthXError());
00834         hs["sigmaY0_time_all"]->setBinError(jthBin, bs.BeamWidthYError());
00835         hs["sigmaZ0_time_all"]->setBinError(jthBin, bs.sigmaZ0Error());
00836       }
00837 
00838       h_x0->Fill( bs.x0());
00839       h_y0->Fill( bs.y0());
00840       h_z0->Fill( bs.z0());
00841       if (bs.type() > 0) { // with good beamwidth fit
00842         h_sigmaX0->Fill( bs.BeamWidthX());
00843         h_sigmaY0->Fill( bs.BeamWidthY());
00844       }
00845       h_sigmaZ0->Fill( bs.sigmaZ());
00846 
00847       if (nthBSTrk_ >= 2*min_Ntrks_) {
00848         double amp = std::sqrt(bs.x0()*bs.x0()+bs.y0()*bs.y0());
00849         double alpha = std::atan2(bs.y0(),bs.x0());
00850         TF1 *f1 = new TF1("f1","[0]*sin(x-[1])",-3.14,3.14);
00851         f1->SetParameters(amp,alpha);
00852         f1->SetParLimits(1,amp-0.1,amp+0.1);
00853         f1->SetParLimits(2,alpha-0.577,alpha+0.577);
00854         f1->SetLineColor(4);
00855         h_d0_phi0->getTProfile()->Fit("f1","QR");
00856 
00857         double mean = bs.z0();
00858         double width = bs.sigmaZ();
00859         TF1 *fgaus = new TF1("fgaus","gaus");
00860         fgaus->SetParameters(mean,width);
00861         fgaus->SetLineColor(4);
00862         h_trk_z0->getTH1()->Fit("fgaus","QLRM","",mean-3*width,mean+3*width);
00863       }
00864 
00865       fitResults->Reset();
00866       int * LSRange = theBeamFitter->getFitLSRange();
00867       char tmpTitle[50];
00868       sprintf(tmpTitle,"%s %i %s %i","Fitted Beam Spot (cm) of LS: ",LSRange[0]," to ",LSRange[1]);
00869       fitResults->setAxisTitle(tmpTitle,1);
00870       fitResults->setBinContent(1,8,bs.x0());
00871       fitResults->setBinContent(1,7,bs.y0());
00872       fitResults->setBinContent(1,6,bs.z0());
00873       fitResults->setBinContent(1,5,bs.sigmaZ());
00874       fitResults->setBinContent(1,4,bs.dxdz());
00875       fitResults->setBinContent(1,3,bs.dydz());
00876       if (bs.type() > 0) { // with good beamwidth fit
00877         fitResults->setBinContent(1,2,bs.BeamWidthX());
00878         fitResults->setBinContent(1,1,bs.BeamWidthY());
00879       }
00880       else { // fill cached widths
00881         fitResults->setBinContent(1,2,preBS.BeamWidthX());
00882         fitResults->setBinContent(1,1,preBS.BeamWidthY());
00883       }
00884 
00885       fitResults->setBinContent(2,8,bs.x0Error());
00886       fitResults->setBinContent(2,7,bs.y0Error());
00887       fitResults->setBinContent(2,6,bs.z0Error());
00888       fitResults->setBinContent(2,5,bs.sigmaZ0Error());
00889       fitResults->setBinContent(2,4,bs.dxdzError());
00890       fitResults->setBinContent(2,3,bs.dydzError());
00891       if (bs.type() > 0) { // with good beamwidth fit
00892         fitResults->setBinContent(2,2,bs.BeamWidthXError());
00893         fitResults->setBinContent(2,1,bs.BeamWidthYError());
00894       }
00895       else { // fill cached width errors
00896         fitResults->setBinContent(2,2,preBS.BeamWidthXError());
00897         fitResults->setBinContent(2,1,preBS.BeamWidthYError());
00898       }
00899 
00900       // count good fit
00901       //     if (std::fabs(refBS.x0()-bs.x0())/bs.x0Error() < deltaSigCut_) { // disabled temporarily
00902       summaryContent_[0] += 1.;
00903       //     }
00904       //     if (std::fabs(refBS.y0()-bs.y0())/bs.y0Error() < deltaSigCut_) { // disabled temporarily
00905       summaryContent_[1] += 1.;
00906       //     }
00907       //     if (std::fabs(refBS.z0()-bs.z0())/bs.z0Error() < deltaSigCut_) { // disabled temporarily
00908       summaryContent_[2] += 1.;
00909       //     }
00910     } // beam fit is good
00911     else { // beam fit fails
00912       reco::BeamSpot bs = theBeamFitter->getBeamSpot();
00913       edm::LogInfo("BeamMonitor") << "[BeamMonitor] Beam fit fails!!! \n" << endl;
00914       edm::LogInfo("BeamMonitor") << "[BeamMonitor] Output beam spot for DIP \n" << endl;
00915       edm::LogInfo("BeamMonitor") << bs << endl;
00916 
00917       hs["sigmaX0_lumi"]->ShiftFillLast( bs.BeamWidthX(), bs.BeamWidthXError(), fitNLumi_ );
00918       hs["sigmaY0_lumi"]->ShiftFillLast( bs.BeamWidthY(), bs.BeamWidthYError(), fitNLumi_ );
00919       hs["sigmaZ0_lumi"]->ShiftFillLast( bs.sigmaZ(), bs.sigmaZ0Error(), fitNLumi_ );
00920       hs["x0_lumi"]->ShiftFillLast( bs.x0(), bs.x0Error(), fitNLumi_ );
00921       hs["y0_lumi"]->ShiftFillLast( bs.y0(), bs.y0Error(), fitNLumi_ );
00922       hs["z0_lumi"]->ShiftFillLast( bs.z0(), bs.z0Error(), fitNLumi_ );
00923     } // end of beam fit fails
00924   } // end of countFitting
00925   else { // no fit
00926     // Overwrite Fit LS and fit time when no event processed or no track selected
00927     theBeamFitter->setFitLSRange(beginLumiOfBSFit_,endLumiOfBSFit_);
00928     theBeamFitter->setRefTime(refBStime[0],refBStime[1]);
00929     if (theBeamFitter->runPVandTrkFitter()) {} // Dump fake beam spot for DIP
00930     reco::BeamSpot bs = theBeamFitter->getBeamSpot();
00931     edm::LogInfo("BeamMonitor") << "[BeamMonitor] No fitting \n" << endl;
00932     edm::LogInfo("BeamMonitor") << "[BeamMonitor] Output fake beam spot for DIP \n" << endl;
00933     edm::LogInfo("BeamMonitor") << bs << endl;
00934 
00935     hs["sigmaX0_lumi"]->ShiftFillLast( bs.BeamWidthX(), bs.BeamWidthXError(), fitNLumi_ );
00936     hs["sigmaY0_lumi"]->ShiftFillLast( bs.BeamWidthY(), bs.BeamWidthYError(), fitNLumi_ );
00937     hs["sigmaZ0_lumi"]->ShiftFillLast( bs.sigmaZ(), bs.sigmaZ0Error(), fitNLumi_ );
00938     hs["x0_lumi"]->ShiftFillLast( bs.x0(), bs.x0Error(), fitNLumi_ );
00939     hs["y0_lumi"]->ShiftFillLast( bs.y0(), bs.y0Error(), fitNLumi_ );
00940     hs["z0_lumi"]->ShiftFillLast( bs.z0(), bs.z0Error(), fitNLumi_ );
00941   }
00942 
00943   // Fill summary report
00944   if (countFitting) {
00945     for (int n = 0; n < nFitElements_; n++) {
00946       reportSummaryContents[n]->Fill( summaryContent_[n] / (float)nFits_ );
00947     }
00948 
00949     summarySum_ = 0;
00950     for (int ii = 0; ii < nFitElements_; ii++) {
00951       summarySum_ += summaryContent_[ii];
00952     }
00953     reportSummary_ = summarySum_ / (nFitElements_ * nFits_);
00954     if (reportSummary) reportSummary->Fill(reportSummary_);
00955 
00956     for ( int bi = 0; bi < nFitElements_ ; bi++) {
00957       reportSummaryMap->setBinContent(1,bi+1,summaryContent_[bi] / (float)nFits_);
00958     }
00959   }
00960 
00961   if (resetFitNLumi_ > 0 &&
00962       ((onlineMode_ && currentlumi%resetFitNLumi_ == 0) ||
00963        (!onlineMode_ && countLumi_%resetFitNLumi_ == 0))) {
00964     edm::LogInfo("BeamMonitor") << "Reset track collection for beam fit!!!" <<endl;
00965     resetHistos_ = true;
00966     nthBSTrk_ = 0;
00967     theBeamFitter->resetTrkVector();
00968     theBeamFitter->resetLSRange();
00969     theBeamFitter->resetRefTime();
00970     theBeamFitter->resetPVFitter();
00971     beginLumiOfBSFit_ = 0;
00972     refBStime[0] = 0;
00973   }
00974 }
00975 
00976 //--------------------------------------------------------
00977 void BeamMonitor::endRun(const Run& r, const EventSetup& context){
00978 
00979 }
00980 
00981 //--------------------------------------------------------
00982 void BeamMonitor::endJob(const LuminosityBlock& lumiSeg,
00983                          const EventSetup& iSetup){
00984   if (!onlineMode_) endLuminosityBlock(lumiSeg, iSetup);
00985 }
00986 
00987 //--------------------------------------------------------
00988 void BeamMonitor::scrollTH1(TH1 * h, time_t ref) {
00989   const char* offsetTime = formatFitTime(ref);
00990   TDatime da(offsetTime);
00991   if (lastNZbin > 0) {
00992     double val = h->GetBinContent(lastNZbin);
00993     double valErr = h->GetBinError(lastNZbin);
00994     h->Reset();
00995     h->GetXaxis()->SetTimeOffset(da.Convert(kTRUE));
00996     int bin = (lastNZbin > buffTime ? buffTime : 1);
00997     h->SetBinContent(bin,val);
00998     h->SetBinError(bin,valErr);
00999   }
01000   else {
01001     h->Reset();
01002     h->GetXaxis()->SetTimeOffset(da.Convert(kTRUE));
01003   }
01004 }
01005 
01006 //--------------------------------------------------------
01007 // Method to check whether to chane histogram time offset (forward only)
01008 bool BeamMonitor::testScroll(time_t & tmpTime_, time_t & refTime_){
01009   bool scroll_ = false;
01010   if (tmpTime_ - refTime_ >= intervalInSec_) {
01011     scroll_ = true;
01012     edm::LogInfo("BeamMonitor") << "Reset Time Offset" << std::endl;
01013     lastNZbin = intervalInSec_;
01014     for (int bin = intervalInSec_; bin >= 1; bin--) {
01015       if (hs["x0_time"]->getBinContent(bin) > 0) {
01016         lastNZbin = bin;
01017         break;
01018       }
01019     }
01020     edm::LogInfo("BeamMonitor") << "Last non zero bin = " << lastNZbin << std::endl;
01021     if (tmpTime_ - refTime_ >= intervalInSec_ + lastNZbin) {
01022       edm::LogInfo("BeamMonitor") << "Time difference too large since last readout" << std::endl;
01023       lastNZbin = 0;
01024       refTime_ = tmpTime_ - buffTime;
01025     }
01026     else{
01027       edm::LogInfo("BeamMonitor") << "Offset to last record" << std::endl;
01028       int offset = ((lastNZbin > buffTime) ? (lastNZbin - buffTime) : (lastNZbin - 1));
01029       refTime_ += offset;
01030     }
01031   }
01032   return scroll_;
01033 }
01034 
01035 DEFINE_FWK_MODULE(BeamMonitor);