コード例 #1
0
void DileptonAnalyzer::storeSignalEfficiencies( TFile & outputFile ) {
  // Store in a TProfile
  TProfile *sigEffOne = new TProfile("SignalEfficOneDecay","Signal efficiencies when one exotic decays in this channel",10,0.5,10.5,-9.9e9,9.9e9);
  TAxis *sigEffOneAxis = sigEffOne->GetXaxis();

  TProfile *sigEffTwo = new TProfile("SignalEfficTwoDecay","Signal efficiencies when two exotic decays in this channel",10,0.5,10.5,-9.9e9,9.9e9);
  TAxis *sigEffTwoAxis = sigEffTwo->GetXaxis();

  // Fill set of 3 bins in each TProfile for each exotic
  for ( int iExotic = 0; iExotic < nSignalParticles_; iExotic++ ) {

    TString axisTitle;

    sigEffOne->Fill( iExotic*nSignalParticles_+1, numEvents_oneSensitiveDecay_[iExotic] );
    axisTitle.Form("Number of events coming into macro for exotic %d",signalPdgId_[iExotic]);
    sigEffOneAxis->SetBinLabel( iExotic*nSignalParticles_+1, axisTitle.Data());

    sigEffOne->Fill( iExotic*nSignalParticles_+2, numExoticsRECO_oneSensitiveDecay_[iExotic] );
    axisTitle.Form("Number of candidates RECO'd for exotic %d",signalPdgId_[iExotic]);
    sigEffOneAxis->SetBinLabel( iExotic*nSignalParticles_+2, axisTitle.Data());

    sigEffOne->Fill( iExotic*nSignalParticles_+3, numExoticsCorrectRECO_oneSensitiveDecay_[iExotic] );
    axisTitle.Form("Number of exotics correctly RECO'd for exotic %d",signalPdgId_[iExotic]);
    sigEffOneAxis->SetBinLabel( iExotic*nSignalParticles_+3, axisTitle.Data());

    sigEffTwo->Fill( iExotic*nSignalParticles_+1, numEvents_twoSensitiveDecay_[iExotic] );
    axisTitle.Form("Number of events coming into macro for exotic %d",signalPdgId_[iExotic]);
    sigEffTwoAxis->SetBinLabel( iExotic*nSignalParticles_+1, axisTitle.Data());

    sigEffTwo->Fill( iExotic*nSignalParticles_+2, numExoticsRECO_twoSensitiveDecay_[iExotic] );
    axisTitle.Form("Number of candidates RECO'd for exotic %d",signalPdgId_[iExotic]);
    sigEffTwoAxis->SetBinLabel( iExotic*nSignalParticles_+2, axisTitle.Data());

    sigEffTwo->Fill( iExotic*nSignalParticles_+3, numExoticsCorrectRECO_twoSensitiveDecay_[iExotic] );
    axisTitle.Form("Number of exotics correctly RECO'd for exotic %d",signalPdgId_[iExotic]);
    sigEffTwoAxis->SetBinLabel( iExotic*nSignalParticles_+3, axisTitle.Data());
  }
  outputFile.cd();
  sigEffOne->Write();
  sigEffTwo->Write();
}
コード例 #2
0
// Report cut flow findings to screen
void DileptonAnalyzer::reportCutFlow( TFile & outputFile ) {

  // Store in a TProfile
  TProfile *cutFlow = new TProfile("cutFlow","Cut flow for final set of analysis cuts",20,0.5,20.5,-9.9e9,9.9e9);
  TAxis *cutFlowAxis = cutFlow->GetXaxis();

  for ( unsigned int iCut = 0; iCut < cutNamesInOrder_.size(); iCut++ ) {
    cutFlow->Fill( iCut+1, cutFlowMap_[cutNamesInOrder_[iCut]]);
    cutFlowAxis->SetBinLabel( iCut+1, cutNamesInOrder_[iCut]);
  }

  outputFile.cd();
  cutFlow->Write();
}
コード例 #3
0
Float_t doCoinc(const char *fileIn="coincCERN_0102n.root",TCanvas *cout=NULL,Float_t &rate,Float_t &rateErr){

  // Print settings
  printf("SETTINGS\nAnalyze output from new Analyzer\n");
  printf("Input file = %s\n",fileIn);
  printf("School distance = %f m, angle = %f deg\n",distance,angle);
  printf("School orientation: tel1=%f deg, tel2=%f deg\n",phi1Corr,phi2Corr);
  printf("Max Chi2 = %f\n",maxchisquare);
  printf("Theta Rel Range = %f - %f deg\n",minthetarel,maxthetarel);
  printf("Range for N sattellite in each run = (tel1) %f - %f, (tel2) %f - %f \n",minAvSat[0],maxAvSat[0],minAvSat[1],maxAvSat[1]);
  printf("Min N satellite in a single event = %i\n",satEventThr);

  Int_t adayMin = (yearRange[0]-2014) * 1000 + monthRange[0]*50 + dayRange[0];
  Int_t adayMax = (yearRange[1]-2014) * 1000 + monthRange[1]*50 + dayRange[1];

  Float_t nsigPeak=0;
  Float_t nbackPeak=0;

  angle *= TMath::DegToRad();

  // define some histos
  TH1F *hDeltaTheta = new TH1F("hDeltaTheta","#Delta#theta below the peak (500 ns);#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhi = new TH1F("hDeltaPhi","#Delta#phi below the peak (500 ns);#Delta#phi (#circ)",200,-360,360);
  TH1F *hDeltaThetaBack = new TH1F("hDeltaThetaBack","#Delta#theta out of the peak (> 1000 ns) - normalized;#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhiBack = new TH1F("hDeltaPhiBack","#Delta#phi out of the peak (> 1000 ns)  - normalized;#Delta#phi (#circ)",200,-360,360);
  TH1F *hThetaRel = new TH1F("hThetaRel","#theta_{rel} below the peak (500 ns);#theta_{rel} (#circ)",100,0,120);
  TH1F *hThetaRelBack = new TH1F("hThetaRelBack","#theta_{rel} out of the peak (> 1000 ns)  - normalized;#theta_{rel} (#circ)",100,0,120);

  TH2F *hAngle = new TH2F("hAngle",";#Delta#theta (#circ);#Delta#phi (#circ}",20,-60,60,20,-360,360);
  TH2F *hAngleBack = new TH2F("hAngleBack",";#Delta#theta (#circ);#Delta#phi (#circ}",20,-60,60,20,-360,360);

  TProfile *hModulation = new  TProfile("hModulation","#theta^{rel} < 10#circ;#phi - #alpha;dist (m)",50,0,360);
  TProfile *hModulation2 = new  TProfile("hModulation2","#theta^{rel} < 10#circ;#phi - #alpha;dist (m)",50,0,360);
  TProfile *hModulationAv = new  TProfile("hModulationAv","#theta^{rel} < 10#circ;#phi - #alpha;dist (m)",50,0,360);
  TProfile *hModulationAvCorr = new  TProfile("hModulationAvCorr","#theta^{rel} < 10#circ;#phi - #alpha;diff (ns)",50,0,360);

  TH1F *hnsigpeak = new TH1F("hnsigpeak","",50,0,360);
  TH1F *hnbackpeak = new TH1F("hnbackpeak","",50,0,360);

  TProfile *hSinTheta = new  TProfile("hSinTheta",";#phi - #alpha;sin(#theta)",50,0,360);
  TProfile *hSinTheta2 = new  TProfile("hSinTheta2",";#phi - #alpha;sin(#theta)",50,0,360);

  TH1F *hRunCut[2];
  hRunCut[0] = new TH1F("hRunCut1","Reason for Run Rejection Tel-1;Reason;runs rejected",11,0,11);
  hRunCut[1] = new TH1F("hRunCut2","Reason for Run Rejection Tel-2;Reason;runs rejected",11,0,11);

  for(Int_t i=0;i<2;i++){
    hRunCut[i]->Fill("DateRange",0);
    hRunCut[i]->Fill("LowFractionGT",0);
    hRunCut[i]->Fill("TimeDuration",0);
    hRunCut[i]->Fill("rateGT",0);
    hRunCut[i]->Fill("RunNumber",0);
    hRunCut[i]->Fill("MissingHitFrac",0);
    hRunCut[i]->Fill("DeadStripBot",0);
    hRunCut[i]->Fill("DeadStripMid",0);
    hRunCut[i]->Fill("DeadStripTop",0);
    hRunCut[i]->Fill("NSatellites",0);
    hRunCut[i]->Fill("NoGoodWeather",0);  
  }

  TFile *f = new TFile(fileIn);
  TTree *t = (TTree *) f->Get("tree");
  
  TTree *tel[2];
  tel[0] = (TTree *) f->Get("treeTel1");
  tel[1] = (TTree *) f->Get("treeTel2");

  TTree *telC = (TTree *) f->Get("treeTimeCommon");
  
  // quality info of runs
  const Int_t nyearmax = 5;
  Bool_t runstatus[2][nyearmax][12][31][500]; //#telescope, year-2014, month, day, run
  Float_t effTel[2][nyearmax][12][31][500];
  Int_t nStripDeadBot[2][nyearmax][12][31][500];
  Int_t nStripDeadMid[2][nyearmax][12][31][500];
  Int_t nStripDeadTop[2][nyearmax][12][31][500];

  Float_t nstripDeadB[2]={0,0},nstripDeadM[2]={0,0},nstripDeadT[2]={0,0};

  // sat info
  Float_t NsatAv[2][nyearmax][12][31][500];

  // weather info
  Float_t pressureTel[2][nyearmax][12][31][500];
  Float_t TempInTel[2][nyearmax][12][31][500];
  Float_t TempOutTel[2][nyearmax][12][31][500];
  Float_t timeWeath[2][nyearmax][12][31][500];

  Float_t rateGT;

  Float_t phirelative;
  Float_t phirelative2;
  Float_t phirelativeAv;

  printf("Check Run quality\n");

  if(tel[0] && tel[1]){
    for(Int_t i=0;i < 2;i++){ // loop on telescopes
      printf("Tel-%i\n",i+1);
      for(Int_t j=0;j < tel[i]->GetEntries();j++){ // loop on runs
	tel[i]->GetEvent(j);
	rateGT = tel[i]->GetLeaf("FractionGoodTrack")->GetValue()*tel[i]->GetLeaf("rateHitPerRun")->GetValue();

	Int_t aday = (tel[i]->GetLeaf("year")->GetValue()-2014) * 1000 + tel[i]->GetLeaf("month")->GetValue()*50 + tel[i]->GetLeaf("day")->GetValue();

        if(i==1) printf("%f %f\n",rateGT , rateMin[i]);

	if(aday < adayMin || aday > adayMax){
	  hRunCut[i]->Fill("DateRange",1); continue;}
	if(tel[i]->GetLeaf("FractionGoodTrack")->GetValue() < fracGT[i]){
	  hRunCut[i]->Fill("LowFractionGT",1); continue;} // cut on fraction of good track
	if(tel[i]->GetLeaf("timeduration")->GetValue()*tel[i]->GetLeaf("rateHitPerRun")->GetValue() < hitevents[i]){
	  hRunCut[i]->Fill("TimeDuration",1); continue;} // cut on the number of event
	if(rateGT < rateMin[i] || rateGT > rateMax[i]){
	  hRunCut[i]->Fill("rateGT",1); continue;} // cut on the rate
	if(tel[i]->GetLeaf("run")->GetValue() > 499){
	  hRunCut[i]->Fill("RunNumber",1); continue;} // run < 500

        if(i==1) printf("GR\n");

	Float_t missinghitfrac = (tel[i]->GetLeaf("ratePerRun")->GetValue()-tel[i]->GetLeaf("rateHitPerRun")->GetValue()-2)/(tel[i]->GetLeaf("ratePerRun")->GetValue()-2);
	if(missinghitfrac < minmissingHitFrac[i] || missinghitfrac > maxmissingHitFrac[i]){
	  hRunCut[i]->Fill("MissingHitFrac",1); continue;}
		
	// active strip maps
	if(tel[i]->GetLeaf("maskB")) nStripDeadBot[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = countBits(Int_t(tel[i]->GetLeaf("maskB")->GetValue()));
	if(tel[i]->GetLeaf("maskM")) nStripDeadMid[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = countBits(Int_t(tel[i]->GetLeaf("maskM")->GetValue()));
	if(tel[i]->GetLeaf("maskT")) nStripDeadTop[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = countBits(Int_t(tel[i]->GetLeaf("maskT")->GetValue()));

	if(nStripDeadBot[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > ndeadBotMax[i] || nStripDeadBot[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < ndeadBotMin[i]) {
	  hRunCut[i]->Fill("DeadStripBot",1); continue;}
	if(nStripDeadMid[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > ndeadMidMax[i] || nStripDeadMid[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < ndeadMidMin[i]){
	  hRunCut[i]->Fill("DeadStripMid",1); continue;}
	if(nStripDeadTop[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > ndeadTopMax[i] || nStripDeadTop[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < ndeadTopMin[i]){
	  hRunCut[i]->Fill("DeadStripTop",1); continue;}
     
	// nsat averaged  per run
	if(tel[i]->GetLeaf("nSat")) NsatAv[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("nSat")->GetValue();


	if(NsatAv[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < minAvSat[i] || NsatAv[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > maxAvSat[i]){
	 hRunCut[i]->Fill("NSatellites",1); continue;}

	// weather info
	if(tel[i]->GetLeaf("Pressure")) pressureTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("Pressure")->GetValue();
	if(tel[i]->GetLeaf("IndoorTemperature")) TempInTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("IndoorTemperature")->GetValue();
	if(tel[i]->GetLeaf("OutdoorTemperature")) TempOutTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("OutdoorTemperature")->GetValue();
	if(tel[i]->GetLeaf("TimeWeatherUpdate")) timeWeath[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("TimeWeatherUpdate")->GetValue();

	if(timeWeath[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < minWeathTimeDelay[i] ||  timeWeath[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > maxWeathTimeDelay[i]){ hRunCut[i]->Fill("NoGoodWeather",1); continue;	}

	// Set good runs
	runstatus[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = kTRUE;
	effTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = 1;//rateGT/refRate[i];

      }
    }
  }
  else{
    telC = NULL;
  }

  printf("Start to process correlations\n");
  Int_t n = t->GetEntries();
  // counter for seconds
  Int_t nsec = 0;
  Int_t nsecGR = 0; // for good runs
  Int_t isec = -1; // used only in case the tree with time info is not available

  Float_t neventsGR = 0;
  Float_t neventsGRandSat = 0;

  if(telC){
    for(Int_t i=0; i < telC->GetEntries();i++){
      telC->GetEvent(i);
      nsec += telC->GetLeaf("timeduration")->GetValue(); 
      
      
      
      if(telC->GetLeaf("run")->GetValue() > 499 || telC->GetLeaf("run2")->GetValue() > 499) continue;
      
      if(!runstatus[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())]) continue;
      
      if(!runstatus[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run2")->GetValue())]) continue;
      
      nsecGR += telC->GetLeaf("timeduration")->GetValue(); 
      nstripDeadB[0] += countBits(nStripDeadBot[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadM[0] += countBits(nStripDeadMid[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadT[0] += countBits(nStripDeadTop[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();

      nstripDeadB[1] += countBits(nStripDeadBot[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadM[1] += countBits(nStripDeadMid[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadT[1] += countBits(nStripDeadTop[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
    }
    nstripDeadB[0] /= nsecGR;
    nstripDeadM[0] /= nsecGR;
    nstripDeadT[0] /= nsecGR;

    nstripDeadB[1] /= nsecGR;
    nstripDeadM[1] /= nsecGR;
    nstripDeadT[1] /= nsecGR;

    printf("Dead channel tel1 = %f - %f - %f\n",nstripDeadB[0],nstripDeadM[0],nstripDeadT[0]);
    printf("Dead channel tel2 = %f - %f - %f\n",nstripDeadB[1],nstripDeadM[1],nstripDeadT[1]);
  }
  
  char title[300];
  TH1F *h;
  
  sprintf(title,"correction assuming #Delta#phi = %4.2f, #DeltaL = %.1f m;#Deltat (ns);entries",angle,distance);
  
  h = new TH1F("hCoinc",title,nbint,tmin,tmax);
  
  Float_t DeltaT;
  Float_t phiAv,thetaAv,corr;
  
  Float_t Theta1,Theta2;
  Float_t Phi1,Phi2;
  Int_t nsatel1cur,nsatel2cur,ntrack1,ntrack2;

  Float_t v1[3],v2[3],vSP; // variable to recompute ThetaRel on the fly
  Float_t eff = 1; 
  
  for(Int_t i=0;i<n;i++){
    t->GetEvent(i);
    
    if(t->GetLeaf("RunNumber1") && (t->GetLeaf("RunNumber1")->GetValue() > 499 || t->GetLeaf("RunNumber2")->GetValue() > 499)) continue;
  
    if(tel[0] && !runstatus[0][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber1")->GetValue())]) continue;
    
    if(tel[1] && !runstatus[1][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber2")->GetValue())]) continue;


    eff = effTel[0][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber1")->GetValue())];
    eff *= effTel[1][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber2")->GetValue())];
    
    Int_t timec = t->GetLeaf("ctime1")->GetValue();
    
    if(! telC){
      if(isec == -1) isec = timec;
      
      if(timec != isec){
	if(timec - isec < 20){
	  //	printf("diff = %i\n",timec-isec);
	  nsec +=(timec - isec);
	  nsecGR +=(timec - isec);
	}
	isec = timec;
    }
    }

    Float_t thetarel = t->GetLeaf("ThetaRel")->GetValue();
    Theta1 = (t->GetLeaf("Theta1")->GetValue())*TMath::DegToRad();
    Theta2 = t->GetLeaf("Theta2")->GetValue()*TMath::DegToRad();
    Phi1 = t->GetLeaf("Phi1")->GetValue()*TMath::DegToRad();
    Phi2 = t->GetLeaf("Phi2")->GetValue()*TMath::DegToRad();
    
    nsatel1cur = t->GetLeaf("Nsatellite1")->GetValue();
    nsatel2cur = t->GetLeaf("Nsatellite2")->GetValue();
    ntrack1 = t->GetLeaf("Ntracks1")->GetValue();
    ntrack2 = t->GetLeaf("Ntracks2")->GetValue();

    if(recomputeThetaRel){ // recompute ThetaRel applying corrections
      Phi1 += phi1Corr*TMath::DegToRad();
      Phi2 += phi2Corr*TMath::DegToRad();
      if(Phi1 > 2*TMath::Pi()) Phi1 -= 2*TMath::Pi();
      if(Phi1 < 0) Phi1 += 2*TMath::Pi();
      if(Phi2 > 2*TMath::Pi()) Phi2 -= 2*TMath::Pi();
      if(Phi2 < 0) Phi2 += 2*TMath::Pi();
      
      v1[0] = TMath::Sin(Theta1)*TMath::Cos(Phi1);
      v1[1] = TMath::Sin(Theta1)*TMath::Sin(Phi1);
      v1[2] = TMath::Cos(Theta1);
      v2[0] = TMath::Sin(Theta2)*TMath::Cos(Phi2);
      v2[1] = TMath::Sin(Theta2)*TMath::Sin(Phi2);
      v2[2] = TMath::Cos(Theta2);
      
      v1[0] *= v2[0];
      v1[1] *= v2[1];
      v1[2] *= v2[2];
      
      vSP = v1[0] + v1[1] + v1[2];
      
      thetarel = TMath::ACos(vSP)*TMath::RadToDeg();
    }
    
    // cuts
    if(thetarel < minthetarel) continue;
    if(thetarel > maxthetarel) continue;
    if(t->GetLeaf("ChiSquare1")->GetValue() > maxchisquare) continue;
    if(t->GetLeaf("ChiSquare2")->GetValue() > maxchisquare) continue;
    

    neventsGR++;

    // reject events with not enough satellites
    if(nsatel1cur < satEventThr || nsatel1cur < satEventThr) continue;

    neventsGRandSat++;
    
    DeltaT = t->GetLeaf("DiffTime")->GetValue();
    
    // get primary direction
    if(TMath::Abs(Phi1-Phi2) < TMath::Pi()) phiAv = (Phi1+Phi2)*0.5;
    else phiAv = (Phi1+Phi2)*0.5 + TMath::Pi();

    thetaAv = (Theta1+Theta2)*0.5;
    
    // extra cuts if needed
    //    if(TMath::Cos(Phi1-Phi2) < 0.) continue;
    
    Float_t resFactor = 1;
    if(thetarel > 10 ) resFactor *= 0.5;
    if(thetarel > 20 ) resFactor *= 0.5;
    if(thetarel > 30 ) resFactor *= 0.5;

    corr = distance * TMath::Sin(thetaAv)*TMath::Cos(phiAv-angle)/2.99792458000000039e-01 + deltatCorr;

    phirelative = (Phi1-angle)*TMath::RadToDeg();
    if(phirelative < 0) phirelative += 360;
    if(phirelative < 0) phirelative += 360;
    if(phirelative > 360) phirelative -= 360;
    if(phirelative > 360) phirelative -= 360;

    phirelative2 = (Phi2-angle)*TMath::RadToDeg();
    if(phirelative2 < 0) phirelative2 += 360;
    if(phirelative2 < 0) phirelative2 += 360;
    if(phirelative2 > 360) phirelative2 -= 360;
    if(phirelative2 > 360) phirelative2 -= 360;

    phirelativeAv = (phiAv-angle)*TMath::RadToDeg();
    if(phirelativeAv < 0) phirelativeAv += 360;
    if(phirelativeAv < 0) phirelativeAv += 360;
    if(phirelativeAv > 360) phirelativeAv -= 360;
    if(phirelativeAv > 360) phirelativeAv -= 360;


    // if(TMath::Abs(DeltaT- deltatCorr) < windowAlignment){
      
    // }

    if(thetarel < 10){//cos(thetarel*TMath::DegToRad())>0.98 && sin(thetaAv)>0.1){
      if(TMath::Abs(DeltaT- corr) < windowAlignment)
	hModulationAvCorr->Fill(phirelativeAv,DeltaT-corr);
      if(TMath::Abs(DeltaT- deltatCorr) < windowAlignment){
	hModulation->Fill(phirelative,(DeltaT-deltatCorr)/sin(thetaAv)*2.99792458000000039e-01);
	hModulation2->Fill(phirelative2,(DeltaT-deltatCorr)/sin(thetaAv)*2.99792458000000039e-01);
	hModulationAv->Fill(phirelativeAv,(DeltaT-deltatCorr)/sin(thetaAv)*2.99792458000000039e-01);
	hSinTheta->Fill(phirelative,sin(thetaAv));
	hSinTheta2->Fill(phirelative2,sin(thetaAv));
	nsigPeak++;
	hnsigpeak->Fill(phirelativeAv);
      }
      else if(TMath::Abs(DeltaT- deltatCorr) < windowAlignment*10){
	nbackPeak++;
	hnbackpeak->Fill(phirelativeAv);
      }
    }

    h->Fill(DeltaT-corr,1./eff);
    if(TMath::Abs(DeltaT-corr) < windowAlignment){
      hDeltaTheta->Fill((Theta1-Theta2)*TMath::RadToDeg());
      hDeltaPhi->Fill((Phi1-Phi2)*TMath::RadToDeg());
      hThetaRel->Fill(thetarel);
      hAngle->Fill((Theta1-Theta2)*TMath::RadToDeg(),(Phi1-Phi2)*TMath::RadToDeg());
    }
    else if(TMath::Abs(DeltaT-corr) > windowAlignment*2 && TMath::Abs(DeltaT-corr) < windowAlignment*12){
      hDeltaThetaBack->Fill((Theta1-Theta2)*TMath::RadToDeg());
      hDeltaPhiBack->Fill((Phi1-Phi2)*TMath::RadToDeg());
      hThetaRelBack->Fill(thetarel);
      hAngleBack->Fill((Theta1-Theta2)*TMath::RadToDeg(),(Phi1-Phi2)*TMath::RadToDeg());
    }
  }
  
  // compute (S+B)/S
  for(Int_t i=1;i<=50;i++){
    Float_t corrfactorPeak = 1;
    if(nsigPeak-nbackPeak*0.1 > 0)
      corrfactorPeak = hnsigpeak->GetBinContent(i)/(hnsigpeak->GetBinContent(i)-hnbackpeak->GetBinContent(i)*0.1);
    else
      printf("bin %i) not enough statistics\n",i);
    hnsigpeak->SetBinContent(i,corrfactorPeak);
  }

  TF1 *fpol0 = new TF1("fpol0","pol0");
  hnsigpeak->Fit(fpol0);

  hModulation->Scale(fpol0->GetParameter(0));
  hModulation2->Scale(fpol0->GetParameter(0));
  hModulationAv->Scale(fpol0->GetParameter(0));
  hModulationAvCorr->Scale(fpol0->GetParameter(0));
  
  TF1 *fmod = new TF1("fmod","[0] + [1]*cos((x-[2])*TMath::DegToRad())"); 
  hModulationAv->Fit(fmod); 

  printf("Estimates from time delay: Distance = %f +/- %f m -- Angle = %f +/- %f deg\n",fmod->GetParameter(1),fmod->GetParError(1),fmod->GetParameter(2),fmod->GetParError(2));

  h->SetStats(0);

  hDeltaThetaBack->Sumw2();
  hDeltaPhiBack->Sumw2();
  hThetaRelBack->Sumw2();
  hDeltaThetaBack->Scale(0.1);
  hDeltaPhiBack->Scale(0.1);
  hThetaRelBack->Scale(0.1);
  hAngleBack->Scale(0.1);
  hAngle->Add(hAngleBack,-1);

  printf("bin counting: SIGNAL = %f +/- %f\n",hDeltaPhi->Integral()-hDeltaPhiBack->Integral(),sqrt(hDeltaPhi->Integral()));
  rate = (hDeltaPhi->Integral()-hDeltaPhiBack->Integral())/nsecGR*86400;
  rateErr = sqrt(hDeltaPhi->Integral())/nsecGR*86400;


  Float_t val,eval;
  TCanvas *c1=new TCanvas();
  TF1 *ff = new TF1("ff","[0]*[4]/[2]/sqrt(2*TMath::Pi())*TMath::Exp(-(x-[1])*(x-[1])*0.5/[2]/[2]) + [3]*[4]/6/[2]");
  ff->SetParName(0,"signal");
  ff->SetParName(1,"mean");
  ff->SetParName(2,"sigma");
  ff->SetParName(3,"background");
  ff->SetParName(4,"bin width");
  ff->SetParameter(0,42369);
  ff->SetParameter(1,0);
  ff->SetParLimits(2,10,maxwidth);
  ff->SetParameter(2,350); // fix witdh if needed
  ff->SetParameter(3,319);
  ff->FixParameter(4,(tmax-tmin)/nbint); // bin width

  ff->SetNpx(1000);
  
  if(cout) cout->cd();
  h->Fit(ff,"EI","",-10000,10000);
  
  val = ff->GetParameter(2);
  eval = ff->GetParError(2);
  
  printf("significance = %f\n",ff->GetParameter(0)/sqrt(ff->GetParameter(0) + ff->GetParameter(3)));

  h->Draw();
  
  new TCanvas;

  TF1 *func1 = (TF1 *)  h->GetListOfFunctions()->At(0);
  
  func1->SetLineColor(2);
  h->SetLineColor(4);
  
  TPaveText *text = new TPaveText(1500,(h->GetMinimum()+(h->GetMaximum()-h->GetMinimum())*0.6),9500,h->GetMaximum());
  text->SetFillColor(0);
  sprintf(title,"width = %5.1f #pm %5.1f",func1->GetParameter(2),func1->GetParError(2));
  text->AddText(title);
  sprintf(title,"signal (S) = %5.1f #pm %5.1f",func1->GetParameter(0),func1->GetParError(0));
  text->AddText(title);
  sprintf(title,"background (B) (3#sigma) = %5.1f #pm %5.1f",func1->GetParameter(3),func1->GetParError(3));
  text->AddText(title);
  sprintf(title,"significance (S/#sqrt{S+B}) = %5.1f",func1->GetParameter(0)/sqrt(func1->GetParameter(0)+func1->GetParameter(3)));
  text->AddText(title);
  
  text->SetFillStyle(0);
  text->SetBorderSize(0);
  
  text->Draw("SAME");
  
  // correct nsecGR for the event rejected because of the number of satellites (event by event cut)
  nsecGR *= neventsGRandSat/neventsGR;

  printf("n_day = %f\nn_dayGR = %f\n",nsec*1./86400,nsecGR*1./86400);

  text->AddText(Form("rate = %f #pm %f per day",func1->GetParameter(0)*86400/nsecGR,func1->GetParError(0)*86400/nsecGR));

  TFile *fo = new TFile("outputCERN-01-02.root","RECREATE");
  h->Write();
  hDeltaTheta->Write();
  hDeltaPhi->Write();
  hThetaRel->Write();
  hDeltaThetaBack->Write();
  hDeltaPhiBack->Write();
  hThetaRelBack->Write();
  hAngle->Write();
  hModulation->Write();
  hModulation2->Write();
  hModulationAv->Write();
  hModulationAvCorr->Write();
  hSinTheta->Write();
  hSinTheta2->Write();
  hnsigpeak->Write();
  hRunCut[0]->Write();
  hRunCut[1]->Write();
  fo->Close();

  return nsecGR*1./86400;
  
}
コード例 #4
0
ファイル: coeffCompareEE.cpp プロジェクト: HeinerTholen/cmssw
int main (int argc, char* argv[]) 
{
   
    int EEradStart = 15 ;
    int EEradEnd = 50 ;
    int EEphiStart = 0 ;
    int EEphiEnd = 360 ;

    std::string filename = "coeffcompareEE.root" ;
     
//     std::string NameDBOracle1 = "oracle://cms_orcoff_int2r/CMS_COND_ECAL";
//     std::string TagDBOracle1 = "EcalIntercalibConstants_startup_csa08_mc";  
//     
//     std::string NameDBOracle2 = "oracle://cms_orcoff_int2r/CMS_COND_ECAL";
//     std::string TagDBOracle2 = "EcalIntercalibConstants_inv_startup_csa08_mc";  

    std::string NameDBOracle1 = "oracle://cms_orcoff_prod/CMS_COND_20X_ECAL";
    std::string TagDBOracle1 = "EcalIntercalibConstants_phi_Zee_csa08_s156_mc";  
    
    std::string NameDBOracle2 = "oracle://cms_orcoff_prod/CMS_COND_20X_ECAL";
    std::string TagDBOracle2 = "EcalIntercalibConstants_startup_csa08_mc";  
    
    
    
    //---- location of the xml file ----
    std::string calibFile = "/afs/cern.ch/user/a/amassiro/scratch0/CMSSW_2_1_2/src/CalibCalorimetry/CaloMiscalibTools/data/miscalib_endcap_startup_csa08.xml";
 
    
    
    
    if (argc == 1) {
        std::cout << "Help:"<<std::endl;
        std::cout << " 0-> Help"<< std::endl;
        std::cout << " 1-> Name of 1st Database. e.g. oracle://cms_orcoff_int2r/CMS_COND_ECAL"<< std::endl;
        std::cout << " 2-> Name of 1st Database Tag. e.g. EcalIntercalibConstants_startup_csa08_mc"<< std::endl;
        std::cout << " 3-> Location of the xml file, e.g. /afs/cern.ch/user/.../CMSSW_2_1_2/src/CalibCalorimetry/CaloMiscalibTools/data/miscalib_endcap_startup_csa08.xml. Make sure it is on your afs."<< std::endl;
        std::cout << " 4-> Name of 2nd Database. e.g. oracle://cms_orcoff_int2r/CMS_COND_ECAL"<< std::endl;
        std::cout << " 5-> Name of 2nd Database Tag. e.g. EcalIntercalibConstants_startup_csa08_mc"<< std::endl;
        std::cout << " 6-> EEradStart"<< std::endl;
        std::cout << " 7-> EEradEnd"<< std::endl;
        std::cout << " 8-> EEphiStart"<< std::endl;
        std::cout << " 9-> EEphiEnd"<< std::endl;
        std::cout << " 10-> filename output"<< std::endl;
        
        std::cout << std::endl << std::endl << "Now working with default values" << std::endl;
    }
      
    if (argc == 2) {
        //---- Help option ----
        std::string testName = "--help";
        std::string testNameLoad = argv[1];
        if (argv[1] == testName){
        std::cout << "Help:"<<std::endl;
        std::cout << " 0-> Help. --help option"<< std::endl;
        std::cout << " 1-> Name of 1st Database. e.g. oracle://cms_orcoff_int2r/CMS_COND_ECAL"<< std::endl;
        std::cout << " 2-> Name of 1st Database Tag. e.g. EcalIntercalibConstants_startup_csa08_mc"<< std::endl;
        std::cout << " 3-> Location of the xml file, e.g. /afs/cern.ch/user/.../CMSSW_2_1_2/src/CalibCalorimetry/CaloMiscalibTools/data/miscalib_endcap_startup_csa08.xml. Make sure it is on your afs."<< std::endl;
        std::cout << " 4-> Name of 2nd Database. e.g. oracle://cms_orcoff_int2r/CMS_COND_ECAL"<< std::endl;
        std::cout << " 5-> Name of 2nd Database Tag. e.g. EcalIntercalibConstants_startup_csa08_mc"<< std::endl;
        std::cout << " 6-> EEradStart"<< std::endl;
        std::cout << " 7-> EEradEnd"<< std::endl;
        std::cout << " 8-> EEphiStart"<< std::endl;
        std::cout << " 9-> EEphiEnd"<< std::endl;
        std::cout << " 10-> filename output"<< std::endl;
        exit (1);
        }
    }
    if (argc > 1){
        NameDBOracle1 = argv[1];
        TagDBOracle1 = argv[2];
        std::cout << "NameDBOracle1 = " << NameDBOracle1 << std::endl;
        std::cout << "TagDBOracle1 = " << TagDBOracle1 << std::endl;
        if (argc > 3){
            calibFile = argv[3];
            std::cout << "calibFile = " << calibFile << std::endl;
            if (argc > 4){
                NameDBOracle2 = argv[4];
                TagDBOracle2 = argv[5];
                std::cout << "NameDBOracle2 = " << NameDBOracle2 << std::endl;
                std::cout << "TagDBOracle2 = " << TagDBOracle2 << std::endl;
            }
        }
    }
  
    
    if (argc > 6)
    {
        if (argc < 10)
        {
            std::cerr << "Too few (or too many) arguments passed" << std::endl ;
            exit (1) ;
        }
        EEradStart = atoi (argv[6]) ;
        EEradEnd = atoi (argv[7]) ;
        EEphiStart = atoi (argv[8]) ;
        EEphiEnd = atoi (argv[9]) ;
    }
    if (argc == 11) filename = argv[10] ;

    
    
    
    //---- export of the DB from oracle to sqlite db ----
  
    
    std::string Command2LineStr1 = "cmscond_export_iov -s " + NameDBOracle1 + " -d sqlite_file:Uno.db -D CondFormatsEcalObjects -t " + TagDBOracle1 + " -P /afs/cern.ch/cms/DB/conddb/";
   
    std::string Command2LineStr2 = "cmscond_export_iov -s " + NameDBOracle2 + " -d sqlite_file:Due.db -D CondFormatsEcalObjects -t " + TagDBOracle2 + " -P /afs/cern.ch/cms/DB/conddb/";
            

    gSystem->Exec(Command2LineStr1.c_str());

    //---- now the second set analysed through xml file ----
        gSystem->Exec(Command2LineStr2.c_str());
   
    
    
   
  
  std::string NameDB;
  std::string FileData;

  //----------------------------------
  //---- First Database Analyzed -----
  //----------------------------------

  NameDB = "sqlite_file:Uno.db";
  FileData = TagDBOracle1;
  CondIter<EcalIntercalibConstants> Iterator1;
  Iterator1.create(NameDB,FileData);
  
  
  
  //-----------------------------------
  //---- Second Database Analyzed -----
  //-----------------------------------
  
  NameDB = "sqlite_file:Due.db";
  FileData = TagDBOracle2;
  CondIter<EcalIntercalibConstants> Iterator2;
  Iterator2.create(NameDB,FileData);

  //---------------------------------------------------------------------
  
  
      
  
  
  //-------------------------------------------------
  //---- Ottengo Mappe da entrambi gli Iterators ----
  //-------------------------------------------------
  
  const EcalIntercalibConstants* EEconstants1;
  EEconstants1 = Iterator1.next();
  EcalIntercalibConstantMap iEEcalibMap = EEconstants1->getMap () ;
 
  
  
  const EcalIntercalibConstants* EEconstants2;
  EEconstants2 = Iterator2.next();
  EcalIntercalibConstantMap iEEscalibMap = EEconstants2->getMap () ;

  
  
  
  
  
  
  
  
  
  //---- load form xml file ----
  //---- name of the xml file defined at the beginning ----
  
//   CaloMiscalibMapEcal EEscalibMap ;
//   EEscalibMap.prefillMap () ;
//   MiscalibReaderFromXMLEcalEndcap endcapreader (EEscalibMap) ;
//   if (!calibFile.empty ()) endcapreader.parseXMLMiscalibFile (calibFile) ;
//   EcalIntercalibConstants* EEconstants = new EcalIntercalibConstants (EEscalibMap.get ()) ;
//   EcalIntercalibConstantMap iEEscalibMap = EEconstants->getMap () ;  //MF prende i vecchi coeff
    
  
  
  
  
  
  
  //---- Xml way ----  

  
  
//   CaloMiscalibMapEcal EEscalibMap ;
//   EEscalibMap.prefillMap () ;
//   MiscalibReaderFromXMLEcalEndcap endcapreader (EEscalibMap) ;
//   if (!endcapfile.empty ()) endcapreader.parseXMLMiscalibFile (endcapfile) ;
//   EcalIntercalibConstants* EEconstants = 
//           new EcalIntercalibConstants (EEscalibMap.get ()) ;
//   EcalIntercalibConstantMap iEEscalibMap = EEconstants->getMap () ;  //MF prende i vecchi coeff
// 
//   //PG get the recalibration files for EB and EE
//   //PG -----------------------------------------
// 
//   CaloMiscalibMapEcal EEcalibMap ;
//   EEcalibMap.prefillMap () ;
//   MiscalibReaderFromXMLEcalEndcap calibEndcapreader (EEcalibMap) ;
//   if (!calibEndcapfile.empty ()) calibEndcapreader.parseXMLMiscalibFile (calibEndcapfile) ;
//   EcalIntercalibConstants* EECconstants = 
//           new EcalIntercalibConstants (EEcalibMap.get ()) ;
//   EcalIntercalibConstantMap iEEcalibMap = EECconstants->getMap () ;  //MF prende i vecchi coeff
  
  
  
  
  
  
  
  
  //PG fill the histograms
  //PG -------------------
  
  TH1F EEPCompareCoeffDistr ("EEPCompareCoeffDistr","EEPCompareCoeffDistr",5000,0,2) ;
  TH2F EEPCompareCoeffMap ("EEPCompareCoeffMap","EEPCompareCoeffMap",101,0,101,101,0,101) ;
  TH2F EEPCompareCoeffEtaTrend ("EEPCompareCoeffEtaTrend",
                                "EEPCompareCoeffEtaTrend",
                                51,0,50,500,0,2) ;
  TProfile EEPCompareCoeffEtaProfile ("EEPCompareCoeffEtaProfile",
                                      "EEPCompareCoeffEtaProfile",
                                      51,0,50,0,2) ;
   
  TH1F EEPCompareCoeffDistr_R1 ("EEPCompareCoeff_R1","EEPCompareCoeff_R1",1000,0,2) ;
  TH1F EEPCompareCoeffDistr_R2 ("EEPCompareCoeff_R2","EEPCompareCoeff_R2",1000,0,2) ;
  TH1F EEPCompareCoeffDistr_R3 ("EEPCompareCoeff_R3","EEPCompareCoeff_R3",1000,0,2) ;
  TH1F EEPCompareCoeffDistr_R4 ("EEPCompareCoeff_R4","EEPCompareCoeff_R4",1000,0,2) ;
  TH1F EEPCompareCoeffDistr_R5 ("EEPCompareCoeff_R5","EEPCompareCoeff_R5",1000,0,2) ;

  // ECAL endcap +
  for (int ix = 1 ; ix <= 100 ; ++ix)
      for (int iy = 1 ; iy <= 100 ; ++iy)
  {
      int rad = static_cast<int> (sqrt ((ix - 50) * (ix - 50) +
              (iy - 50) * (iy - 50))) ;
      if (rad < EEradStart || rad > EEradEnd) continue ;
      double phiTemp = atan2 (iy - 50, ix - 50) ;
      if (phiTemp < 0) phiTemp += 2 * PI_GRECO ;
      int phi = static_cast<int> ( phiTemp * 180 / PI_GRECO) ;
      if (phi < EEphiStart || phi > EEphiEnd) continue ;
      if (!EEDetId::validDetId (ix,iy,1)) continue ;
      EEDetId det = EEDetId (ix, iy, 1, EEDetId::XYMODE) ;
      double factor = *(iEEcalibMap.find (det.rawId ())) / 
                  *(iEEscalibMap.find (det.rawId ())) ;
      
//       std::cout << " iEEcalibMap rad = " << rad << " --> " << *(iEEcalibMap.find (det.rawId ()));
//       std::cout << " iEEscalibMap --> " << *(iEEscalibMap.find (det.rawId ())) << std::endl;  
      
      EEPCompareCoeffDistr.Fill (factor) ;
      EEPCompareCoeffMap.Fill (ix,iy,factor) ;
      EEPCompareCoeffEtaTrend.Fill (rad,factor) ;
      EEPCompareCoeffEtaProfile.Fill (rad,factor) ;
      if (abs(rad) < 22) continue ;
      else if (abs(rad) < 27) EEPCompareCoeffDistr_R1.Fill (factor) ;
      else if (abs(rad) < 32) EEPCompareCoeffDistr_R2.Fill (factor) ;
      else if (abs(rad) < 37) EEPCompareCoeffDistr_R3.Fill (factor) ;
      else if (abs(rad) < 42) EEPCompareCoeffDistr_R4.Fill (factor) ;
      else EEPCompareCoeffDistr_R5.Fill (factor) ;

  } // ECAL endcap +

  // ECAL endcap-
  TH1F EEMCompareCoeffDistr ("EEMCompareCoeffDistr","EEMCompareCoeffDistr",200,0,2) ;
  TH2F EEMCompareCoeffMap ("EEMCompareCoeffMap","EEMCompareCoeffMap",100,0,100,100,0,100) ;
  TH2F EEMCompareCoeffEtaTrend ("EEMCompareCoeffEtaTrend",
                                "EEMCompareCoeffEtaTrend",
                                51,0,50,500,0,2) ;
  TProfile EEMCompareCoeffEtaProfile ("EEMCompareCoeffEtaProfile",
                                      "EEMCompareCoeffEtaProfile",
                                      51,0,50,0,2) ;
   
  // ECAL endcap -
  for (int ix = 1 ; ix <= 100 ; ++ix)
      for (int iy = 1 ; iy <= 100 ; ++iy)
  {
      int rad = static_cast<int> (sqrt ((ix - 50) * (ix - 50) +
              (iy - 50) * (iy - 50))) ;
      if (rad < EEradStart || rad > EEradEnd) continue ;
      double phiTemp = atan2 (iy - 50, ix - 50) ;
      if (phiTemp < 0) phiTemp += 2 * PI_GRECO ;
      if (!EEDetId::validDetId (ix,iy,-1)) continue ;
      EEDetId det = EEDetId (ix, iy, -1, EEDetId::XYMODE) ;
      double factor = *(iEEcalibMap.find (det.rawId ())) *
                  *(iEEscalibMap.find (det.rawId ())) ;
      EEMCompareCoeffDistr.Fill (factor) ;
      EEMCompareCoeffMap.Fill (ix,iy,factor) ;
      EEMCompareCoeffEtaTrend.Fill (rad,factor) ;
      EEMCompareCoeffEtaProfile.Fill (rad,factor) ;
  } // ECAL endcap -
    
  TFile out (filename.c_str (),"recreate") ;
  EEMCompareCoeffMap.Write() ;
  EEMCompareCoeffDistr.Write() ;
  EEMCompareCoeffEtaTrend.Write () ;
  EEMCompareCoeffEtaProfile.Write () ;
  EEPCompareCoeffMap.Write() ;
  EEPCompareCoeffDistr.Write() ;
  EEPCompareCoeffEtaTrend.Write () ;
  EEPCompareCoeffEtaProfile.Write () ;
  EEPCompareCoeffDistr_R1.Write () ;
  EEPCompareCoeffDistr_R2.Write () ;
  EEPCompareCoeffDistr_R3.Write () ;
  EEPCompareCoeffDistr_R4.Write () ;
  EEPCompareCoeffDistr_R5.Write () ;
  out.Close() ;
  
  
  
  
  
  
  
  
  //---- remove local database ----
  
  gSystem->Exec("rm Uno.db");
  gSystem->Exec("rm Due.db");

  
   
}
コード例 #5
0
ファイル: Analyze.C プロジェクト: XuQiao/HI
void
Analyze(const TString mode="CLOSED",
        UShort_t       maxH=6,
        Bool_t         /*doLoops*/=false,
        Int_t ifile=0   )
{
#ifdef __CINT__
  gROOT->LoadMacro("correlations/Types.hh++");
  gROOT->LoadMacro("correlations/Result.hh++");
  gROOT->LoadMacro("correlations/QVector.hh++");
  gROOT->LoadMacro("correlations/recursive/FromQVector.hh++");
  gROOT->LoadMacro("correlations/recurrence/FromQVector.hh++");
  gROOT->LoadMacro("correlations/closed/FromQVector.hh++");
  gROOT->LoadMacro("correlations/test/ReadData.hh++");
#endif
  // --- Setup of harmonics, etc -------------------------------------
  gRandom->SetSeed(54321);
  UShort_t emode = 0;
  if      (mode.EqualTo("closed",     TString::kIgnoreCase)) emode = 0;
  else if (mode.EqualTo("recurrence", TString::kIgnoreCase)) emode = 1;
  else if (mode.EqualTo("recursive",  TString::kIgnoreCase)) emode = 2;
  else
    Warning("Analyze", "Mode %s unknown, assuming CLOSED", mode.Data());

  correlations::QVector        q[nbin];
  correlations::FromQVector*   c[nbin];
  correlations::HarmonicVector h(maxH);
  for (UShort_t i = 0; i < maxH; i++) {
    // Generate random harmonicx
   // h[i] = -6 + gRandom->Integer(12);
   h[0] = 2;
   h[1] = -2;
   h[2] = 2;
   h[3] = -2;
   h[4] = 2;
   h[5] = -2;
   h[6] = -2;
   h[7] = 2;
   // Printf("h_%d:\t%d", i, h[i]);
  }

  // Resize the Q-vector to fit the harmonics
    for(int ibin=0;ibin<nbin;ibin++){
    q[ibin] = correlations::QVector(0,0,false);
    q[ibin].resize(h);
  switch (emode) {
  case 0: c[ibin] = new correlations::closed::FromQVector(q[ibin]); break;
  case 1: c[ibin] = new correlations::recurrence::FromQVector(q[ibin]); break;
  case 2: c[ibin] = new correlations::recursive::FromQVector(q[ibin]); break;
    }
  }
  //Printf("Correlator: %s", c->name());


  // --- Some histograms ---------------------------------------------
  TH1* sumreals[nbin];
  TH1* sumimags[nbin];
  TH1* weights[nbin];
  TVectorD tottrk;
  TVectorD Nevent;
  tottrk.ResizeTo(nbin);
  tottrk.Zero();
  Nevent.ResizeTo(nbin);
  Nevent.Zero();

  //TH1*      reals  = new TH1D("reals", "Re(C{n})", maxH-2+1, 2+.5, maxH+1+.5);
  //TH1*      imags  = static_cast<TH1*>(reals->Clone("imags"));
    for(int ibin=0;ibin<nbin;ibin++){
  sumreals[ibin]  = new TH1D(Form("sumreals_%d",ibin), "Re(C{n})", maxH-2+1, 2+.5, maxH+1+.5);
  sumimags[ibin]  = static_cast<TH1*>(sumreals[ibin]->Clone(Form("sumimags_%d",ibin)));
  weights[ibin]  = static_cast<TH1*>(sumreals[ibin]->Clone(Form("weights_%d",ibin)));
    }
  TProfile* timing = new TProfile("timing", "Timing", maxH-2+1, 2+.5,maxH+1+.5);
  TH1*      hs     = new TH1I("harmonics", "Harmonics", maxH, 1.5, maxH+1.5);
  /*reals->SetFillColor(kGreen+1);
  reals->SetFillStyle(3001);
  reals->SetStats(0);
  imags->SetTitle("Im(C{n})");
  imags->SetFillColor(kBlue+1);
  imags->SetFillStyle(3001);
  imags->SetStats(0);
  timing->SetFillColor(kRed+1);
  timing->SetFillStyle(3001);
  timing->SetStats(0);
  hs->SetFillColor(kMagenta+1);
  hs->SetFillStyle(3001);
  hs->SetStats(0);*/
  for (UShort_t i = 0; i < maxH-1; i++) {
    TString label = TString::Format("C{%d}", i+2);
//    reals->GetXaxis()->SetBinLabel(i+1, label);
//    imags->GetXaxis()->SetBinLabel(i+1, label);
    timing->GetXaxis()->SetBinLabel(i+1, label);
    hs->GetXaxis()->SetBinLabel(i+1,Form("h_{%d}", i+1));
    hs->SetBinContent(i+1, h[i]);
  }
  hs->GetXaxis()->SetBinLabel(maxH,Form("h_{%d}", maxH));
  hs->SetBinContent(maxH, h[maxH-1]);

  TStopwatch timer;
 
  // --- Setup input ------------------------------------------------
  TFile*   file = TFile::Open(Form("%s/vndata_50k_%d.root",dir.Data(),ifile), "READ");
  TTree*   tree = static_cast<TTree*>(file->Get("tree"));
//  TArrayD  phis(0);
  Int_t M;
  Float_t phi[10000],pt[10000],eta[10000];
//  TArrayD  weights(0);
//  Double_t phiR = 0;
//  TArrayD* pPhis = &phis;
//  TArrayD* pWeights = &weights;
  tree->SetBranchAddress("phig", phi);
  tree->SetBranchAddress("ptg",pt);
  tree->SetBranchAddress("etag",eta);
  tree->SetBranchAddress("n", &M);
//  tree->SetBranchAddress("weight", &pWeights);
//  tree->SetBranchAddress("event", &phiR);


  // --- The results -------------------------------------------------
  const UShort_t             nQ = maxH - 1;
  correlations::ResultVector qs[nbin];
    for(int ibin=0;ibin<nbin;ibin++)
        qs[ibin] = correlations::ResultVector(nQ);

  // --- Event loop --------------------------------------------------
  Int_t nEvents = tree->GetEntries();
  for (Int_t event = 0; event < nEvents; event++) {
    tree->GetEntry(event);
    int ntrk = M; int xbin=-1;
    for(int j=0;j<nbin;j++)
        if(ntrk<trkbin[j]&&ntrk>=trkbin[j+1])
            xbin=j;
        if(xbin<0 || xbin==nbin) continue;
    tottrk[xbin]+=ntrk;
    q[xbin].reset();
 //   printf("Event # %4u  %4d particles ", event++, phis.GetSize());
    for (UShort_t pa = 0; pa < M; pa++){
	if(fabs(eta[pa])>etamax) continue;
        if(pt[pa]<ptmin||pt[pa]>ptmax) continue; //event selection
  //  phis.Set(n,pPhis);
      q[xbin].fill(phi[pa], 1.);
    }
    for (UShort_t i = 0; i < nQ; i++) {
      UShort_t n = i + 2;
   //   printf("%s%d", i == 0 ? "" : "..", n);
      timer.Reset();
      timer.Start();
      qs[xbin][i] += c[xbin]->calculate(n, h);
      timer.Stop();
      timing->Fill(n+.5, timer.RealTime());
    }

  //  printf(" done\n");
  Nevent[xbin]++;
  }
  file->Close();

    for(int ibin=0;ibin<nbin;ibin++){
  for (UShort_t i = 0; i < nQ; i++) {
 //   UShort_t iq = i+2;
 //   Double_t              t  = timing->GetBinContent(i+1);
 //   correlations::Complex rc = qs[i].eval();
   // Printf("QC{%2d}: %12g + %12gi  <t>: %10gs",
//	   iq, rc.real(), rc.imag(), t);
   // if(i==0)Printf("v2{%2d}: %3g\n",2,sqrt(qs[0].eval().real()));
   // if(i==2)Printf("v2{%2d}: %3g\n",4,TMath::Power(fabs(qs[2].eval().real()),1./4));
   // if(i==4)Printf("v2{%2d}: %3g\n",6,TMath::Power(fabs(qs[4].eval().real()),1./6));
    sumreals[ibin]->SetBinContent(i+1,qs[ibin][i]._sum.real());
    sumimags[ibin]->SetBinContent(i+1,qs[ibin][i]._sum.imag());
    weights[ibin]->SetBinContent(i+1,qs[ibin][i]._weights);
    //reals->SetBinContent(i+1, rc.real());
    //imags->SetBinContent(i+1, rc.imag());
  }
    }

/*
  TCanvas* can = new TCanvas("C", "C");
  can->SetTopMargin(0.15);
  can->SetBottomMargin(0.15);
  can->SetRightMargin(0.03);
  can->Divide(1,3, 0, 0);

  DrawInPad(can, 3, timing, true);
  DrawInPad(can, 1, reals);
  DrawInPad(can, 2, imags);

  can->cd(0);
  TLatex* ltx = new TLatex(0.5,0.995,c->name());
  ltx->SetNDC(true);
  ltx->SetTextAlign(23);
  ltx->SetTextSize(0.04);
  ltx->Draw();

  can->Modified();
  can->Update();
  can->cd();
*/
  TString out(mode);
  out.ToLower();
  file = TFile::Open(Form("%s/%s_%d.root",outdir.Data(),out.Data(),ifile), "RECREATE");
    for(int ibin=0;ibin<nbin;ibin++){
  sumimags[ibin]->Write();
  sumreals[ibin]->Write();
  weights[ibin]->Write();
    }
  Nevent.Write("Nevent");
  tottrk.Write("tottrk");
  timing->Write();
  hs->Write();
  file->Write();
  file->Close();
    for(int ibin=0;ibin<nbin;ibin++){
  delete sumimags[ibin];
  delete sumreals[ibin];
  delete weights[ibin];
    }
  delete timing;
  delete hs;
}
コード例 #6
0
void ecaltree::Loop(const char* outputfilename)
{
//   In a ROOT session, you can do:
//      Root > .L ecaltree.C
//      Root > ecaltree t
//      Root > t.GetEntry(12); // Fill t data members with entry number 12
//      Root > t.Show();       // Show values of entry 12
//      Root > t.Show(16);     // Read and show values of entry 16
//      Root > t.Loop();       // Loop on all entries
//

//     This is the loop skeleton where:
//    jentry is the global entry number in the chain
//    ientry is the entry number in the current Tree
//  Note that the argument to GetEntry must be:
//    jentry for TChain::GetEntry
//    ientry for TTree::GetEntry and TBranch::GetEntry
//
//       To read only selected branches, Insert statements like:
// METHOD1:
//    fChain->SetBranchStatus("*",0);  // disable all branches
//    fChain->SetBranchStatus("branchname",1);  // activate branchname
// METHOD2: replace line
//    fChain->GetEntry(jentry);       //read all branches
//by  b_branchname->GetEntry(ientry); //read only this branch
   if (fChain == 0) return;

   std::cout << "Output file is " << outputfilename << std::endl;

#if ANALYSIS == 1

   TFile *fileo = TFile::Open(outputfilename,"recreate");

   // correlation plots
  TH2D *timesCorr_EB = new TH2D("timesCorr_EB","",1000,-10,10,1000,-10,10);
  TH2D *timesCorr_EE = new TH2D("timesCorr_EE","",1000,-25,25,1000,-25,25);

  TH2D *time1EnergyCorr_EB = new TH2D("time1EnergyCorr_EB","",1000,-10,10,1000,0,200);
  TH2D *time1EnergyCorr_EE = new TH2D("time1EnergyCorr_EE","",1000,-50,50,1000,0,200);
  TH2D *time2EnergyCorr_EB = new TH2D("time2EnergyCorr_EB","",1000,-10,10,1000,0,200);
  TH2D *time2EnergyCorr_EE = new TH2D("time2EnergyCorr_EE","",1000,-50,50,1000,0,200);

  // time ratio vs eta, ET, chi2
  TProfile *timeRatioVsEta = new TProfile("timeRatioVsEta","",100,0,3.0); 
  TProfile *timeRatioVsE_EB = new TProfile("timeRatioVsE_EB","",20,0.0,200.); 
  TProfile *timeRatioVsE_EE = (TProfile*)timeRatioVsE_EB->Clone("timeRatioVsE_EE");
  TProfile *timeRatioVsChi2_EB = new TProfile("timeRatioVsChi2_EB","",50,0.0,30.); 
  TProfile *timeRatioVsChi2_EE = (TProfile*)timeRatioVsChi2_EB->Clone("timeRatioVsChi2_EE");

  // time with weights for different slices of times with ratio
  double t_window=5.0; // ns
  TH1F *time_0_EB = new TH1F("time_0_EB","",1000,-75,75);
  TH1F *time_p1_EB = new TH1F("time_p1_EB","",1000,-50,100);
  TH1F *time_p2_EB = new TH1F("time_p2_EB","",1000,-25,125);
  TH1F *time_m1_EB = new TH1F("time_m1_EB","",1000,-100,50);
  TH1F *time_m2_EB = new TH1F("time_m2_EB","",1000,-125,25);
  TH1F *time_0_EE = new TH1F("time_0_EE","",1000,-75,75);
  TH1F *time_p1_EE = new TH1F("time_p1_EE","",1000,-50,100);
  TH1F *time_p2_EE = new TH1F("time_p2_EE","",1000,-25,125);
  TH1F *time_m1_EE = new TH1F("time_m1_EE","",1000,-100,50);
  TH1F *time_m2_EE = new TH1F("time_m2_EE","",1000,-125,25);

  std::vector<TH1F*> time1Dplots;
  time1Dplots.push_back(time_0_EB);
  time1Dplots.push_back(time_p1_EB);
  time1Dplots.push_back(time_p2_EB);
  time1Dplots.push_back(time_m1_EB);
  time1Dplots.push_back(time_m2_EB);
  time1Dplots.push_back(time_0_EE);
  time1Dplots.push_back(time_p1_EE);
  time1Dplots.push_back(time_p2_EE);
  time1Dplots.push_back(time_m1_EE);
  time1Dplots.push_back(time_m2_EE);

   Long64_t nentries = fChain->GetEntries();

   std::cout << "Total entries = " << nentries << std::endl;
   
   Long64_t nbytes = 0, nb = 0;
   for (Long64_t jentry=0; jentry<nentries;jentry++) {
      Long64_t ientry = LoadTree(jentry);
      if (ientry < 0) break;
      nb = fChain->GetEntry(jentry);   nbytes += nb;
      // if (Cut(ientry) < 0) continue;

      if(jentry % 1000 == 0) std::cout << "Processing entry " << jentry << std::endl;

      // barrel
      for(int h=0;h<std::min(nEBRecHits,10000);++h) {
        double r=timeEBRecHits2[h]-timeEBRecHits[h];
          if(energyEBRecHits[h]>10) {
            timesCorr_EB->Fill(timeEBRecHits[h],timeEBRecHits2[h]);
            timeRatioVsEta->Fill(etaEBRecHits[h],r);
            timeRatioVsChi2_EB->Fill(chi2EBRecHits[h],r);
            if(abs(timeEBRecHits[h])<t_window) time_0_EB->Fill(timeEBRecHits2[h]);
            if(abs(timeEBRecHits[h]-25.)<t_window) time_p1_EB->Fill(timeEBRecHits2[h]);
            if(abs(timeEBRecHits[h]-50.)<t_window) time_p2_EB->Fill(timeEBRecHits2[h]);
            if(abs(timeEBRecHits[h]+25.)<t_window) time_m1_EB->Fill(timeEBRecHits2[h]);
            if(abs(timeEBRecHits[h]+50.)<t_window) time_m2_EB->Fill(timeEBRecHits2[h]);
          }
          time1EnergyCorr_EB->Fill(timeEBRecHits[h],energyEBRecHits[h]);
          time2EnergyCorr_EB->Fill(timeEBRecHits2[h],energyEBRecHits[h]);
          timeRatioVsE_EB->Fill(energyEBRecHits[h],r);
      }
      // endcap
      for(int h=0;h<std::min(nEERecHits,10000);++h) {
        double r=timeEERecHits2[h]-timeEERecHits[h];
        if(energyEERecHits[h]>10) {
          timesCorr_EE->Fill(timeEERecHits[h],timeEERecHits2[h]);
          timeRatioVsEta->Fill(etaEERecHits[h],r);
          timeRatioVsChi2_EE->Fill(chi2EERecHits[h],r);
          if(abs(timeEERecHits[h])<t_window) time_0_EE->Fill(timeEERecHits2[h]);
          if(abs(timeEERecHits[h]-25.)<t_window) time_p1_EE->Fill(timeEERecHits2[h]);
          if(abs(timeEERecHits[h]-50.)<t_window) time_p2_EE->Fill(timeEERecHits2[h]);
          if(abs(timeEERecHits[h]+25.)<t_window) time_m1_EE->Fill(timeEERecHits2[h]);
          if(abs(timeEERecHits[h]+50.)<t_window) time_m2_EE->Fill(timeEERecHits2[h]);
        }
        time1EnergyCorr_EE->Fill(timeEERecHits[h],energyEERecHits[h]);
        time2EnergyCorr_EE->Fill(timeEERecHits2[h],energyEERecHits[h]);
        timeRatioVsE_EE->Fill(energyEERecHits[h],r);
      }

   } // event loop

   timeRatioVsEta->Write();

   timesCorr_EB->Write();
   time1EnergyCorr_EB->Write();
   time2EnergyCorr_EB->Write();
   timeRatioVsChi2_EB->Write();
   timeRatioVsE_EB->Write();

   timesCorr_EE->Write();
   time1EnergyCorr_EE->Write();
   time2EnergyCorr_EE->Write();
   timeRatioVsChi2_EE->Write();
   timeRatioVsE_EE->Write();
   
   for(int i=0; i<(int) time1Dplots.size(); ++i)  time1Dplots[i]->Write();

   fileo->Close();

#endif

#if ANALYSIS == 2

   ofstream txtfile;
   txtfile.open(outputfilename,std::ios::trunc);

   Long64_t nentries = fChain->GetEntries();

   std::cout << "Total entries = " << nentries << std::endl;

   Long64_t nbytes = 0, nb = 0;
   for (Long64_t jentry=0; jentry<nentries;jentry++) {
     Long64_t ientry = LoadTree(jentry);
     if (ientry < 0) break;
     nb = fChain->GetEntry(jentry);   nbytes += nb;
     if(jentry%1000==0) std::cout << "Processing entry " << jentry << "..." << std::endl;
     for(int h=0; h<std::min(nEERecHits,10000); ++h) {
       if(energyEERecHits[h]>5.0)
         txtfile << eventNumber << "\t"
                 << ixEERecHits[h] << "\t"
                 << iyEERecHits[h] << "\t"
                 << nTruePU[12] << "\t" // the bx = 0
                 << energyEERecHits[h] << "\t"
                 << timeEERecHits[h] << "\t"
                 << chi2EERecHits[h] << "\t"
                 << ootenergyEERecHits[h] << std::endl;
     }
     // if (Cut(ientry) < 0) continue;
   }
   txtfile.close();

#endif


}
コード例 #7
0
ファイル: analisi_tree_1hit.C プロジェクト: noferini/ALICE
void analisi_tree_1hit(){ //faccio gli istogrammi dal Tree T creato nel file CheckESD.C
  gROOT->Reset();
  gStyle->SetOptStat(0012);
  gStyle->SetOptFit(0111);

  Bool_t kCal=kFALSE;

  TFile *fcal = TFile::Open("calibration.root");
  TProfile *hCalX;
  TProfile *hCalZ;
  if(fcal){
    kCal=kTRUE;
    hCalX = (TProfile *) fcal->Get("hCalX");
    hCalZ = (TProfile *) fcal->Get("hCalZ");
  }
  else{
    hCalX= new TProfile("hCalX","x alignement per strip;# strip;#DeltaX (cm)",1700,0,1700);
    hCalZ= new TProfile("hCalZ","z alignement per strip;# strip;#DeltaX (cm)",1700,0,1700);
  }

  // check alignment
  TProfile *hx = new TProfile("hx","x alignement per strip;# strip;#DeltaX (cm)",1700,0,1700);
  TProfile *hz = new TProfile("hz","z alignement per strip;# strip;#DeltaZ (cm)",1700,0,1700);
  
  // definire istogrammi (ricordarsi di fare il write nel file successivamente)
  //TH1F *hdeltat = new TH1F("hdeltat","inside the pad (cl_{1}) - cluster along x;t_{1} - t_{2} (ps)",400,-500,500);
  //TH1F *hdeltax = new TH1F("hdeltax","inside the pad (cl_{1}) - cluster along x;#Deltax_{1} - #Deltax_{2} (cm)",100,-10,10);
  TH1F *hch = new TH1F("hch","inside the pad (cl_{1}) - cluster along x;ch_{1} - ch_{2}",500,0,500);
  //TH2F *pxt = new TH2F("pxt","inside the pad (cl_{1}) - cluster along x ;t_{1} - t_{2} (ps);cl_{1} #Deltax (cm)",41,-20.5*24.4,20.5*24.4,100,-4,4); // 24.4 ps quantizzazione TDC
  //TH2F *pzt = new TH2F("pzt","inside the pad (cl_{1}) - cluster along z ;t_{1} - t_{2} (ps);cl_{1} #Deltaz (cm)",41,-20.5*24.4,20.5*24.4,100,-4,4); // 24.4 ps quantizzazione TDC
  //CFC:Istogramma numero cluster(qua coincidono con le hit)
  //TH1F *hnc = new TH1F("hnc","Number of Hits",12,0.,12.);
  //Istogramma  tempi TOF
  TH1F *ht1 = new TH1F("ht1","TOF's Time ",41,0.,30000.);
  
  //Istogramma 1D per i residui
  TH1F *hresx1 = new TH1F("hresx1","Residui x1",100,-10.,10.);
  TH1F *hresz1 = new TH1F("hresz1","Residui z1",100,-10.,10.);
  TH1F *hresdist1 = new TH1F("hresdist1","Residui sqrt(x1^2+z1^2)",100,-10.,10.);
  
  //Istogramma 2D per i residui
  TH2F *h2resxz1 = new TH2F("h2resxz1" , "Residui dx1 e dz1", 100, -4. , 4. , 100 , -4. , 4.);
  
  //Istogramma tempi meno tempi attesi
  TH1F *ht1_texp = new TH1F("ht1_texp","",100,-2000.,2000.);
  TH1F *ht1_texptot = new TH1F("ht1_texptot","",100,-2000.,2000.);
  
  //TH1F *hexp_time_pi = new TH1F("hexp_time_pi","hexp_time_pi",1000,0.,30000.);
  
  TProfile *hprofx  = new TProfile("hprofx","Profile t1-t_exp_pi vs dx1",26, -2.,2.);
  TProfile *hprofxcorr  = new TProfile("hprofxcorr","Profile t1-t_exp_pi corr vs dx1",26, -2.,2.);
  
  TProfile *hprofz  = new TProfile("hprofz","Profile t1-t_exp_pi vs dz1",26, -3.,3.);
  
  TProfile *hprofd=new TProfile("hprofd","Profile t1-t_exp_pi vs d",26, 0.,4.);
  
  TH1F *htbest = new TH1F("htbest","htbest",100,-2000.,2000.);
  
  TH1F *htcorrtw= new TH1F("htcorrtw","htcorrtw",100,-2000.,2000.);
  
  //TH2F *h2dxdzt1_texp=new TH2F("h2dxdzt1_texp","h2dxdzt1_texp",30,-10.25.,10.25,50,-10.75.,10.75.);
  //TH2F *h2dxdzt1_texp_dummy=new TH2F("h2dxdzt1_texp_dummy","h2dxdzt1_texp_dummy",30,-10.25.,10.25,50,-10.75.,10.75.);
  TH2F *h2dxdzt1_texp=new TH2F("h2dxdzt1_texp","h2dxdzt1_texp",20,-1.25,1.25,10,-1.75,1.75);
  TH2F *h2dxdzt1_texp_dummy=new TH2F("h2dxdzt1_texp_dummy","h2dxdzt1_texp_dummy",20,-1.25,1.25,10,-1.75,1.75);
  
  //Istogramma 2D distanza eff vs delay time
  TH2F *h2t1_texp_deff= new TH2F("h2t1_texp_deff" , "Delay time 0 vs deff", 50, 0. , 10.,100,-400.,400.);
  TH2F *h2t1_texp_deff_tw= new TH2F("h2t1_texp_deff_tw" , "Delay time 0 corr tw vs deff", 50, 0. , 10.,100,-400.,400.);
  
  TProfile *hprofdeff=new TProfile("hprofdeff","Profile t1-t_exp_pi vs deff",50, -3.,10.);
  
  // Utilizzo TOT.
  TH2F *h2t1_texp_TOT= new TH2F("h2t1_texp_TOT" , "Delay time vs TOT", 50, 0. , 100.,100,-400.,400.);
  TProfile *hproft1_texp_TOT = new TProfile("hproft1_texp_TOT","Profile t1-t_exp_pi vs TOT",50, 0. , 100.);
  TH2F *h2t1_deff_TOT= new TH2F("h2t1_deff_TOT" , "deff vs TOT", 50, 0. , 100.,50, 0. , 10.);
  TH2F *h2t1_TOT_deff= new TH2F("h2t1_TOT_deff" , "TOT vs deff",50, 0. , 10., 50, 0. , 100.);
  
  
  TFile *f = new TFile("AnalysisResults.root");
  TTree *T = (TTree*)f->Get("T"); //in generale . (e non freccia) se Tfile è un oggetto e NON un puntatore(*)
  
  
  //Varibili tree "T"
  //Int_t nevento;
  //Int_t ntracks;
  Int_t ncluster;
  Float_t tempo[100];//con start time sottratto
  Float_t DeltaX[100];
  Float_t DeltaZ[100];

  Int_t ChannelTOF[100];
  Float_t impulso_trasv;
  Float_t exp_time_pi[100];
  Float_t L[100];
  Float_t TOT[100];
  Float_t res[3];
  Int_t charge;
  Float_t phi,eta;
  Float_t secAngle;
  Float_t cval[5];
  Float_t thetay;
  Float_t StartTime,StartTimeRes;
  Float_t z;
  
  //T->Branch("nevento",&nevento,"nevento/I");
  //T->SetBranchAddress("ntracks",&ntracks);
  T->SetBranchAddress("ncluster",&ncluster);
  T->SetBranchAddress("tempo",tempo);
  T->SetBranchAddress("DeltaX",DeltaX);
  T->SetBranchAddress("DeltaZ",DeltaZ);
  T->SetBranchAddress("ChannelTOF",ChannelTOF);
  T->SetBranchAddress("impulso_trasv",&impulso_trasv);
  T->SetBranchAddress("exp_time_pi",exp_time_pi);
  T->SetBranchAddress("L",L);
  T->SetBranchAddress("TOT",TOT);
  T->SetBranchAddress("res",res);
  T->SetBranchAddress("charge",&charge);
  T->SetBranchAddress("phi",&phi);
  T->SetBranchAddress("eta",&eta);
  T->SetBranchAddress("secPhi",&secAngle);
  T->SetBranchAddress("cval",cval);
  T->SetBranchAddress("thetay",&thetay);
  T->SetBranchAddress("StartTime",&StartTime);
  T->SetBranchAddress("StartTimeRes",&StartTimeRes);
  
  
  Int_t nentries = (Int_t)T->GetEntries();
  
  for(Int_t i=0;i<nentries;i++) {
    T->GetEntry(i);
    
    for(Int_t ip=0;ip<ncluster;ip++){
      tempo[ip] -= StartTime;
      Int_t strip=ChannelTOF[0]/96;
      if(kCal){
	DeltaX[ip] -= hCalX->GetBinContent(strip+1);
	DeltaZ[ip] -= hCalZ->GetBinContent(strip+1);

      }
    }
    
    if(ncluster == 1){
      
      if(impulso_trasv>1.3){
	hx->Fill(int(ChannelTOF[0]/96),DeltaX[0]);
	hz->Fill(int(ChannelTOF[0]/96),DeltaZ[0]);

	if(!kCal){
	  hCalX->Fill(int(ChannelTOF[0]/96),DeltaX[0]);
	  hCalZ->Fill(int(ChannelTOF[0]/96),DeltaZ[0]);	  
	}

	h2resxz1->Fill(DeltaX[0],DeltaZ[0]);
	h2resxz1->GetXaxis()->SetTitle("Dx1 (cm)");
	h2resxz1->GetYaxis()->SetTitle("Dz1 (cm)");
	
	hresx1->Fill(DeltaX[0]);
	hresx1->GetXaxis()->SetTitle("Dx1 (cm)");
	
	hresz1->Fill(DeltaZ[0]);
	hresz1->GetXaxis()->SetTitle("Dz1 (cm)");
	
	hresdist1->Fill(sqrt(DeltaX[0]*DeltaX[0]+DeltaZ[0]*DeltaZ[0]));
	hresdist1->GetXaxis()->SetTitle("sqrt(Dx^2+Dz^2) (cm)");
      }

      if(impulso_trasv>0.8 && impulso_trasv<1.){ // serve per gli exp time
	//if( TMath::Abs(DeltaZ[0])<1.75){
	
	
	if(TMath::Abs(tempo[0]-exp_time_pi[0])<800./* per avere circa 3 sigma che sia un pi*/ ){
	  if(TMath::Abs(DeltaX[0])<1.5){
	    //if((ChannelTOF[0]/48)%2==0){z=1.75+DeltaZ[0];}
	    //if((ChannelTOF[0]/48)%2 == 1){z=1.75-DeltaZ[0];}
	    if((ChannelTOF[0]/48)%2==0){z=DeltaZ[0];}
	    if((ChannelTOF[0]/48)%2 == 1){z= -DeltaZ[0];}
	    Float_t w=tempo[0]- exp_time_pi[0];
	    h2dxdzt1_texp->Fill(DeltaX[0],z, w);
	    h2dxdzt1_texp_dummy->Fill(DeltaX[0],z);
	    
	    if( TMath::Abs(DeltaZ[0])<1.75 && TMath::Abs(DeltaX[0])<1.25){ //sto selezionando che il pad matchato sia dove passa la traccia, poichè altrimenti nel grafico con d e delay time vi sarebbero degli effetti di bordo
			  
	      Float_t t1=tempo[0];
	      ht1->Fill(t1);
	      ht1->GetXaxis()->SetTitle("t1(ps)");
	      
	      //cout<<(ChannelTOF[0]/48)%2<<endl;
	      
	      
	      Float_t d;
	      
	      if((ChannelTOF[0]/48)%2 == 0){
		d=sqrt(DeltaX[0]*DeltaX[0]+(1.75+DeltaZ[0])*(1.75+DeltaZ[0])); //da quello che ho capito il pad 0 è quello in alto quindi ha punto d raccolta in alto
		/*
		  if((ChannelTOF[0]/96)==((ChannelTOF[0]+48)/96)) //if fatto per capire quale sia quallo in alto e quale quello in basso poichè hanno una raccolta di carica differente
		  {
		  cout<<"ciao, io ,pad 0, sono quello sopra"<<endl;
		  }
		*/
	      }
	      if((ChannelTOF[0]/48)%2 == 1) {
		d=sqrt(DeltaX[0]*DeltaX[0]+(1.75-DeltaZ[0])*(1.75-DeltaZ[0])); //da quello che ho capito il pad 1 è quello in basso quindi ha punto d raccolta in basso
		/*//if fatto per capire quale sia quallo in alto e quale quello in basso poichè hanno una raccolta di carica differente
		  
		if((ChannelTOF[0]/96)==((ChannelTOF[0]+48)/96))
		{
		cout<<"ciao, io ,pad 1, sono quello sopra"<<endl;
		}
		*/
	      }
	      	      
              Float_t res1 = DeltaX[0]*DeltaX[0] + DeltaZ[0]*DeltaZ[0];
	      
              //Float_t posx = (DeltaX[0])*(ChannelTOF[0]-ChannelTOF[1]);
              
	      // hdeltax->Fill(posx);
              //hdeltax->GetXaxis()->SetTitle("posx (cm)");
	      //
	      //              pxt->Fill(tempo[0], DeltaX[0]);
	      //              pxt->GetXaxis()->SetTitle("t (cm)");
	      //              pxt->GetYaxis()->SetTitle("dx (cm)");
	      
              
	      //              pzt->Fill(tempo[0], DeltaZ[0]);
	      //              pzt->GetXaxis()->SetTitle("t(cm)");
	      //              pzt->GetYaxis()->SetTitle("Dz1 (cm)");
	      
              hch->Fill(ChannelTOF[0]);
              hch->GetXaxis()->SetTitle("ch");
	      
              Float_t tw1=tempo[0]- exp_time_pi[0];
	      
              ht1_texp->Fill(tw1);
              ht1_texp->GetXaxis()->SetTitle("t_{1} - t_{exp #pi} (ps)");
	      
	      //cerco correlazione tra TOT e delay time
              h2t1_texp_TOT->Fill(TOT[0],tw1);
              h2t1_texp_TOT->GetXaxis()->SetTitle("TOT ");
              h2t1_texp_TOT->GetYaxis()->SetTitle("t_{1}-t_{exp #pi} (ps)");
              hproft1_texp_TOT->Fill(TOT[0],tw1 ,1);
              hproft1_texp_TOT->GetXaxis()->SetTitle("TOT");
              hproft1_texp_TOT->GetYaxis()->SetTitle("t_{0}-t_{exp #pi} (ps)");
	      
	      /////////////////////PROFILE  1
	      
              //riempio istogrammma, poi lo fitto fuori dal loop
	      
	      //               hprofx->Fill(DeltaX[0],tw1 ,1);
	      //               hprofx->GetXaxis()->SetTitle("dx (cm)");
	      //               hprofx->GetYaxis()->SetTitle("t_{1}-t_{exp #pi} (ps)");
	      //        
	      //               hprofz->Fill(DeltaZ[0],tw1 ,1);
	      //               hprofz->GetXaxis()->SetTitle("dz (cm)");
	      //               hprofz->GetYaxis()->SetTitle("t_{1}-t_{exp #pi} (ps)");
	      
	      
	      hprofd->Fill(d,tw1 ,1);
	      hprofd->GetXaxis()->SetTitle("d (cm)");
	      hprofd->GetYaxis()->SetTitle("t_{1}-t_{exp #pi} (ps)");
	      
	      
	      
	      //}
	    }
	  }
	}
      }
    }
  }
    
  
  h2dxdzt1_texp->Divide(h2dxdzt1_texp_dummy);
  h2dxdzt1_texp->SetOption("LEGO2");
  h2dxdzt1_texp->GetXaxis()->SetTitle("dx (cm)");
  h2dxdzt1_texp->GetYaxis()->SetTitle("dz (cm)");
  
  //Double_t par[0]=0;
  //Double_t par[1]=0;
  
  TF2 *myfunc=new TF2("myfunc"," [0] * sqrt(x*x+[1]*[1]*(1.75+y)*(1.75+y))+[2]", -1.25,1.25,-1.75,1.75);
  myfunc->SetParameter(1,0.5);
  h2dxdzt1_texp->Fit(myfunc,"R");
  Double_t vel1, alfa;
  vel1= pow(myfunc->GetParameter(0),-1);
  alfa= myfunc->GetParameter(1);
  cout<<"Ciao, io sono la velocità in 3d "<<vel1<<endl;
  
  for(Int_t i=0;i<nentries;i++){
    T->GetEntry(i);
    
    for(Int_t ip=0;ip<ncluster;ip++){
      tempo[ip] -= StartTime;
      Int_t strip=ChannelTOF[0]/96;
      if(kCal){
	DeltaX[ip] -= hCalX->GetBinContent(strip+1);
	DeltaZ[ip] -= hCalZ->GetBinContent(strip+1);

      }
    }

    if(ncluster == 1) {
      if(impulso_trasv>0.8 && impulso_trasv<1.){ // serve per gli exp time
	if(TMath::Abs(tempo[0]-exp_time_pi[0])<800./* per avere circa 3 sigma che sia un pi*/ ){
	  
	  if(TMath::Abs(DeltaX[0])<1.5){
	    if((ChannelTOF[0]/48)%2==0){z=DeltaZ[0];}
	    if((ChannelTOF[0]/48)%2==1){z= -DeltaZ[0];}
	    Float_t deff=sqrt(DeltaX[0]*DeltaX[0]+ alfa*alfa * (1.75+z)*(1.75+z)*(z>-1.75));
	    Float_t tw1tot=tempo[0]- exp_time_pi[0];
	    h2t1_texp_deff->Fill(deff,tw1tot);
	    h2t1_texp_deff->GetXaxis()->SetTitle("deff (cm)");
	    h2t1_texp_deff->GetYaxis()->SetTitle("delay time (ps)");
            
	    hprofdeff ->Fill(deff,tw1tot ,1);
	    hprofdeff->GetXaxis()->SetTitle("deff (cm)");
	    hprofdeff->GetYaxis()->SetTitle("t_{1}-t_{exp #pi} (ps)");
            
	    h2t1_deff_TOT->Fill(TOT[0],deff);
	    h2t1_deff_TOT->GetXaxis()->SetTitle("TOT (ps)");
	    h2t1_deff_TOT->GetYaxis()->SetTitle("deff (cm)");
            
	    h2t1_TOT_deff->Fill(deff, TOT[0]);
	    h2t1_TOT_deff->GetXaxis()->SetTitle("deff (cm)");
	    h2t1_TOT_deff->GetYaxis()->SetTitle("TOT (ps)");
	           
	  }
	}
      }
    }
  }
  
  TF1 *fs = new TF1("fs","gaus",-400.,400.);
  h2t1_texp_deff->FitSlicesY(fs);
  TH1D *h2t1_texp_deff_1 = (TH1D *) gDirectory->FindObject("h2t1_texp_deff_1");
  h2t1_texp_deff_1->Draw("same");
  //h2t1_texp_deff_2->Draw("same");
  
  //   TF1 *f1 = new TF1("f1","pol1",0., 2.15);
  //    h2t1_texp_deff_1->Fit("f1","R");
  //    Double_t vel2;
  //    vel2 = pow(f1->GetParameter(1),-1);
  //    cout<<"Ciao, io sono la velocità in 2d "<<vel2<<endl;
  
  TF1 *f1 = new TF1("f1","[0]*TMath::Min(x,1.75)+[1]",0., 2.8); //Min(x,1.75) , l'1.75 è stato scelto guardando il fit, come meglio sembrava interploare. Per ora, per quanto ne so, è solo una coincidenza che coincida con pad z
  h2t1_texp_deff_1->Fit(f1,"R");
  Double_t p0,vel2, offset_tw;
  p0=f1->GetParameter(0);
  vel2= pow(p0,-1);
  offset_tw=f1->GetParameter(1);
  cout<<"Ciao, io sono la velocità in 2d "<<vel2<<endl;
  
  for(Int_t i=0;i<nentries;i++){
    T->GetEntry(i);
    
    for(Int_t ip=0;ip<ncluster;ip++){
      tempo[ip] -= StartTime;
      Int_t strip=ChannelTOF[0]/96;
      if(kCal){
	DeltaX[ip] -= hCalX->GetBinContent(strip+1);
	DeltaZ[ip] -= hCalZ->GetBinContent(strip+1);

      }
    }
    
    if(ncluster == 1){
      if(impulso_trasv>0.8 && impulso_trasv<1.){ // serve per gli exp time
	if(TMath::Abs(tempo[0]-exp_time_pi[0])<800./* per avere circa 3 sigma che sia un pi*/ ){                   
	  if(TMath::Abs(DeltaX[0])<1.5){
	    if((ChannelTOF[0]/48)%2==0){z=DeltaZ[0];}
	    if((ChannelTOF[0]/48)%2==1){z= -DeltaZ[0];}
            
	    Float_t deff=sqrt(DeltaX[0]*DeltaX[0]+ alfa*alfa * (1.75+z)*(1.75+z)*(z>-1.75));
            
	    if(deff<2.8){
	      Float_t tw1tot=tempo[0]- exp_time_pi[0];
	      ht1_texptot->Fill(tw1tot);
	      ht1_texptot->GetXaxis()->SetTitle("t_{1} - t_{exp #pi} (ps)");
	      
	      Float_t tw1corrtw=tw1tot-(offset_tw + p0 *TMath::Min(deff,Float_t(1.75)));//Min(x,1.75) , l'1.75 è stato scelto guardando il fit, come meglio sembrava interploare. Per ora, per quanto ne so, è solo una coincidenza che coincida con pad z
	      htcorrtw->Fill(tw1corrtw);
	      htcorrtw->GetXaxis()->SetTitle("t_corr_tw (ps)");
              
	      h2t1_texp_deff_tw->Fill(deff,tw1corrtw);
	      h2t1_texp_deff_tw->GetXaxis()->SetTitle("deff (cm)");
	      h2t1_texp_deff_tw->GetYaxis()->SetTitle("delay time corr_tw (ps)");
	      
	    }
	  }
	}
      }
    }
  }

    
  TF1 *fstw = new TF1("fstw","gaus",-400.,400.);
  h2t1_texp_deff_tw->FitSlicesY(fstw);
  TH1D *h2t1_texp_deff_tw_1 = (TH1D *) gDirectory->FindObject("h2t1_texp_deff_tw_1");
  TH1D *h2t1_texp_deff_tw_2 = (TH1D *) gDirectory->FindObject("h2t1_texp_deff_tw_2");
  
  h2t1_texp_deff_tw_1->Draw("same");
  h2t1_texp_deff_tw_2->Draw("same");
  
  //    TF1 *f1 = new TF1("f1","pol1",-1.25,0.5);
  //    //hprofx->GetYaxis()->SetRangeUser(-40.,100.);
  //    hprofx->Fit("f1","R");
  //    Double_t offset_p1,x1_p1;
  //    offset_p1= f1->GetParameter(0);
  //    x1_p1= f1->GetParameter(1);
  
  
  //    for(Int_t i=0;i<nentries;i++)
  //    {
  //        T->GetEntry(i);
  //    for(Int_t ip=0;ip<ncluster;ip++)
  //      tempo[ip] -= StartTime;
  //        if(ncluster == 1)
  //        {
  //        if(impulso_trasv>0.8 && impulso_trasv<1.2) // serve per gli exp time
  //        {
  //                //if( TMath::Abs(DeltaZ[0])<1.75)
  //                //{
  //        if(TMath::Abs(tempo[0]-exp_time_pi[0])<800./* per avere circa 3 sigmca che sia un pi*/ )
  //        {
  //
  //            //Float_t posx = (DeltaX[0])* dch;
  //            Float_t tw1=tempo[0]- exp_time_pi[0];
  //            
  //            Float_t tw1corr=tw1-(offset_p1 + x1_p1 *DeltaX[0]);
  //            
  //            hprofxcorr->Fill(DeltaX[0],tw1corr,1);
  //            hprofxcorr->GetXaxis()->SetTitle("Dx1 (cm)");
  //            hprofxcorr->GetYaxis()->SetTitle("t1_corr=t1-t_exp_pi corr(ps)");
  //            
  //            htbest->Fill(tw1corr);
  //            htbest->GetXaxis()->SetTitle("t_best=t1_corr(ps)");
  //        
  //        //}
  //        }
  //        }
  //        }
  //    }
  //    
  //    TF1 *f1c = new TF1("f1c","pol1",-1.25,0.5);
  //    hprofxcorr->Fit("f1c","R");
  
  TFile *fo2 = new TFile("output_ist_tree_1hit.root","RECREATE");
  
  hch->Write();
  ht1->Write();
  h2resxz1->Write();
  hresx1->Write();
  hresz1->Write();
  hresdist1->Write();
  //hdeltax->Write();
  //pxt->Write();
  //pzt->Write();
  //hdeltach->Write();
  ht1_texp->Write();
  ht1_texptot->Write();
  //hprofx->Write();
  //hprofz->Write();
  //hprofxcorr->Write();
  //htbest->Write();
  hprofd->Write();
  h2dxdzt1_texp->Write();
  //h2dxdzt1_texp_dummy->Write();
  h2t1_texp_deff->Write();
  h2t1_texp_deff_1->Write();
  //h2t1_texp_deff_2->Write();
  hprofdeff->Write();
  
  htcorrtw->Write();
  
  h2t1_texp_deff_tw->Write();
  h2t1_texp_deff_tw_1->Write();
  h2t1_texp_deff_tw_2->Write();
  h2t1_texp_TOT->Write();
  hproft1_texp_TOT->Write();
  h2t1_deff_TOT->Write();
  h2t1_TOT_deff->Write();
  hx->Write();
  hz->Write();
  fo2->Close();
  
  if(!kCal){
    printf("write calibration\n");
    fcal = new TFile("calibration.root","RECREATE");
    hCalX->Write();
    hCalZ->Write();
    fcal->Close();
  }

  system("say Ehi you, I have done");
}
コード例 #8
0
ファイル: coeffCompareEE.cpp プロジェクト: Bicocca/UserCode
int main (int argc, char* argv[]) 
{

  int EEradStart = 15 ;
  int EEradEnd = 50 ;
  int EEphiStart = 15 ;
  int EEphiEnd = 45 ;

  std::string endcapfile = argv[1] ; 
  std::string calibEndcapfile = argv[2] ; 
  std::string filename = "coeffcompareEE.root" ;

  if (argc > 3)
    {
      if (argc < 7)
        {
          std::cerr << "Too few (or too many) arguments passed" << std::endl ;
          exit (1) ;
        }
      EEradStart = atoi (argv[3]) ;
      EEradEnd = atoi (argv[4]) ;
      EEphiStart = atoi (argv[5]) ;
      EEphiEnd = atoi (argv[6]) ;
    }

  if (argc == 8) filename = argv[7] ;

//  std::string endcapfile = "/afs/cern.ch/user/g/govoni/scratch1/CMSSW/CALIB/CMSSW_1_6_0/src/CalibCalorimetry/CaloMiscalibTools/data/ecal_endcap_startup.xml" ;
//  std::string calibEndcapfile = "/afs/cern.ch/user/g/govoni/scratch1/CMSSW/CALIB/CMSSW_1_6_0/src/CalibCalorimetry/CaloMiscalibTools/data/inv_ecal_endcap_startup.xml" ;
  
  //PG get the miscalibration files for EB and EE
  //PG ------------------------------------------

  CaloMiscalibMapEcal EEscalibMap ;
  EEscalibMap.prefillMap () ;
  MiscalibReaderFromXMLEcalEndcap endcapreader (EEscalibMap) ;
  if (!endcapfile.empty ()) endcapreader.parseXMLMiscalibFile (endcapfile) ;
  EcalIntercalibConstants* EEconstants = 
         new EcalIntercalibConstants (EEscalibMap.get ()) ;
  EcalIntercalibConstants::EcalIntercalibConstantMap iEEscalibMap = EEconstants->getMap () ;  //MF prende i vecchi coeff

  //PG get the recalibration files for EB and EE
  //PG -----------------------------------------

  CaloMiscalibMapEcal EEcalibMap ;
  EEcalibMap.prefillMap () ;
  MiscalibReaderFromXMLEcalEndcap calibEndcapreader (EEcalibMap) ;
  if (!calibEndcapfile.empty ()) calibEndcapreader.parseXMLMiscalibFile (calibEndcapfile) ;
  EcalIntercalibConstants* EECconstants = 
         new EcalIntercalibConstants (EEcalibMap.get ()) ;
  EcalIntercalibConstants::EcalIntercalibConstantMap iEEcalibMap = EECconstants->getMap () ;  //MF prende i vecchi coeff
  
  //PG fill the histograms
  //PG -------------------
  
  TH1F EEPCompareCoeffDistr ("EEPCompareCoeffDistr","EEPCompareCoeffDistr",5000,0,2) ;
  TH2F EEPCompareCoeffMap ("EEPCompareCoeffMap","EEPCompareCoeffMap",101,0,101,101,0,101) ;
  TH2F EEPCompareCoeffEtaTrend ("EEPCompareCoeffEtaTrend",
                               "EEPCompareCoeffEtaTrend",
                               51,0,50,500,0,2) ;
  TProfile EEPCompareCoeffEtaProfile ("EEPCompareCoeffEtaProfile",
                                      "EEPCompareCoeffEtaProfile",
                                      51,0,50,0,2) ;
   
  TH1F EEPCompareCoeffDistr_R1 ("EEPCompareCoeff_R1","EEPCompareCoeff_R1",1000,0,2) ;
  TH1F EEPCompareCoeffDistr_R2 ("EEPCompareCoeff_R2","EEPCompareCoeff_R2",1000,0,2) ;
  TH1F EEPCompareCoeffDistr_R3 ("EEPCompareCoeff_R3","EEPCompareCoeff_R3",1000,0,2) ;
  TH1F EEPCompareCoeffDistr_R4 ("EEPCompareCoeff_R4","EEPCompareCoeff_R4",1000,0,2) ;
  TH1F EEPCompareCoeffDistr_R5 ("EEPCompareCoeff_R5","EEPCompareCoeff_R5",1000,0,2) ;

  // ECAL endcap +
  for (int ix = 1 ; ix <= 100 ; ++ix)
   for (int iy = 1 ; iy <= 100 ; ++iy)
    {
      int rad = static_cast<int> (sqrt ((ix - 50) * (ix - 50) +
                                        (iy - 50) * (iy - 50))) ;
      if (rad < EEradStart || rad > EEradEnd) continue ;
      double phiTemp = atan2 (iy - 50, ix - 50) ;
      if (phiTemp < 0) phiTemp += 2 * PI_GRECO ;
      int phi = static_cast<int> ( phiTemp * 180 / PI_GRECO) ;
      if (phi < EEphiStart || phi > EEphiEnd) continue ;
      if (!EEDetId::validDetId (ix,iy,1)) continue ;
      EEDetId det = EEDetId (ix, iy, 1, EEDetId::XYMODE) ;
      double factor = (iEEcalibMap.find (det.rawId ()))->second * 
                      (iEEscalibMap.find (det.rawId ()))->second ;
      EEPCompareCoeffDistr.Fill (factor) ;
      EEPCompareCoeffMap.Fill (ix,iy,factor) ;
      EEPCompareCoeffEtaTrend.Fill (rad,factor) ;
      EEPCompareCoeffEtaProfile.Fill (rad,factor) ;
      if (abs(rad) < 22) continue ;
      else if (abs(rad) < 27) EEPCompareCoeffDistr_R1.Fill (factor) ;
      else if (abs(rad) < 32) EEPCompareCoeffDistr_R2.Fill (factor) ;
      else if (abs(rad) < 37) EEPCompareCoeffDistr_R3.Fill (factor) ;
      else if (abs(rad) < 42) EEPCompareCoeffDistr_R4.Fill (factor) ;
      else EEPCompareCoeffDistr_R5.Fill (factor) ;

    } // ECAL endcap +

  // ECAL endcap-
  TH1F EEMCompareCoeffDistr ("EEMCompareCoeffDistr","EEMCompareCoeffDistr",200,0,2) ;
  TH2F EEMCompareCoeffMap ("EEMCompareCoeffMap","EEMCompareCoeffMap",100,0,100,100,0,100) ;
  TH2F EEMCompareCoeffEtaTrend ("EEMCompareCoeffEtaTrend",
                               "EEMCompareCoeffEtaTrend",
                               51,0,50,500,0,2) ;
  TProfile EEMCompareCoeffEtaProfile ("EEMCompareCoeffEtaProfile",
                                     "EEMCompareCoeffEtaProfile",
                                     51,0,50,0,2) ;
   
  // ECAL endcap -
  for (int ix = 1 ; ix <= 100 ; ++ix)
   for (int iy = 1 ; iy <= 100 ; ++iy)
    {
      int rad = static_cast<int> (sqrt ((ix - 50) * (ix - 50) +
                                        (iy - 50) * (iy - 50))) ;
      if (rad < EEradStart || rad > EEradEnd) continue ;
      double phiTemp = atan2 (iy - 50, ix - 50) ;
      if (phiTemp < 0) phiTemp += 2 * PI_GRECO ;
      int phi = static_cast<int> ( phiTemp * 180 / PI_GRECO) ;
      if (!EEDetId::validDetId (ix,iy,-1)) continue ;
      EEDetId det = EEDetId (ix, iy, -1, EEDetId::XYMODE) ;
      double factor = (iEEcalibMap.find (det.rawId ()))->second * 
                      (iEEscalibMap.find (det.rawId ()))->second ;
      EEMCompareCoeffDistr.Fill (factor) ;
      EEMCompareCoeffMap.Fill (ix,iy,factor) ;
      EEMCompareCoeffEtaTrend.Fill (rad,factor) ;
      EEMCompareCoeffEtaProfile.Fill (rad,factor) ;
    } // ECAL endcap -
    
  TFile out (filename.c_str (),"recreate") ;
  EEMCompareCoeffMap.Write() ;
  EEMCompareCoeffDistr.Write() ;
  EEMCompareCoeffEtaTrend.Write () ;
  EEMCompareCoeffEtaProfile.Write () ;
  EEPCompareCoeffMap.Write() ;
  EEPCompareCoeffDistr.Write() ;
  EEPCompareCoeffEtaTrend.Write () ;
  EEPCompareCoeffEtaProfile.Write () ;
  EEPCompareCoeffDistr_R1.Write () ;
  EEPCompareCoeffDistr_R2.Write () ;
  EEPCompareCoeffDistr_R3.Write () ;
  EEPCompareCoeffDistr_R4.Write () ;
  EEPCompareCoeffDistr_R5.Write () ;
  out.Close() ;
  
}
コード例 #9
0
int main(int argc, char* argv[])
{
  TApplication theApp(srcName.Data(), &argc, argv);
//=============================================================================

  if (argc<5) return -1;
  TString sPath = argv[1]; if (sPath.IsNull()) return -1;
  TString sFile = argv[2]; if (sFile.IsNull()) return -1;
  TString sJetR = argv[3]; if (sJetR.IsNull()) return -1;
  TString sSjeR = argv[4]; if (sSjeR.IsNull()) return -1;
//=============================================================================

  sPath.ReplaceAll("#", "/");
//=============================================================================

  double dJetR = -1.;
  if (sJetR=="JetR02") dJetR = 0.2;
  if (sJetR=="JetR03") dJetR = 0.3;
  if (sJetR=="JetR04") dJetR = 0.4;
  if (sJetR=="JetR05") dJetR = 0.5;

  if (dJetR<0.) return -1;
  cout << "Jet R = " << dJetR << endl;
//=============================================================================

  double dSjeR = -1.;
  if (sSjeR=="SjeR01") dSjeR = 0.1;
  if (sSjeR=="SjeR02") dSjeR = 0.2;
  if (sSjeR=="SjeR03") dSjeR = 0.3;
  if (sSjeR=="SjeR04") dSjeR = 0.4;

  if (dSjeR<0.) return -1;
  cout << "Sub-jet R = " << dSjeR << endl;
//=============================================================================

  const double dJetsPtMin  = 0.001;
  const double dCutEtaMax  = 1.6;
  const double dJetEtaMax  = 1.;
  const double dJetAreaRef = TMath::Pi() * dJetR * dJetR;

  fastjet::GhostedAreaSpec areaSpc(dCutEtaMax);
  fastjet::JetDefinition   jetsDef(fastjet::antikt_algorithm, dJetR, fastjet::BIpt_scheme, fastjet::Best);
  fastjet::AreaDefinition  areaDef(fastjet::active_area_explicit_ghosts,areaSpc);

  fastjet::Selector selectJet = fastjet::SelectorAbsEtaMax(dJetEtaMax);
  fastjet::JetDefinition subjDef(fastjet::kt_algorithm, dSjeR, fastjet::BIpt_scheme, fastjet::Best);
//=============================================================================

  std::vector<fastjet::PseudoJet> fjInput;
  const Double_t dCut = TMath::TwoPi() / 3.;
//=============================================================================

  enum { kWgt, kXsc, kLje, kLjr, kLtk, kLtr, kJet, kAje, kMje, k1sz, k1sA, k1sm, k1sr, k2sz, k2sA, k2sm, k2sr, kDsm, kDsr, kVar };

  TFile *file = TFile::Open(Form("%s.root",sFile.Data()), "NEW");
  TNtuple *nt = new TNtuple("nt", "", "fWgt:fXsc:fLje:fLjr:fLtk:fLtr:fJet:fAje:fMje:f1sj:f1sA:f1sm:f1sr:f2sj:f2sA:f2sm:f2sr:fDsm:fDsr");
//=============================================================================

  HepMC::IO_GenEvent ascii_in(Form("%s/%s.hepmc",sPath.Data(),sFile.Data()), std::ios::in);
  HepMC::GenEvent *evt = ascii_in.read_next_event();

  while (evt) {
    fjInput.resize(0);

    double dLtk = -1.;
    TVector3 vPar, vLtk;
    for (HepMC::GenEvent::particle_const_iterator p=evt->particles_begin(); p!=evt->particles_end(); ++p) if ((*p)->status()==1) {
      double dEta = (*p)->momentum().eta(); if (TMath::Abs(dEta)>dCutEtaMax) continue;

      double dTrk = (*p)->momentum().perp();
      double dPhi = (*p)->momentum().phi();
      vPar.SetPtEtaPhi(dTrk, dEta, dPhi);
      fjInput.push_back(fastjet::PseudoJet(vPar.Px(), vPar.Py(), vPar.Pz(), vPar.Mag()));
      if (dTrk>dLtk) { dLtk = dTrk; vLtk.SetPtEtaPhi(dTrk, dEta, dPhi); }
    }
//=============================================================================

    fastjet::ClusterSequenceArea clustSeq(fjInput, jetsDef, areaDef);
    std::vector<fastjet::PseudoJet> includJets = clustSeq.inclusive_jets(dJetsPtMin);
    std::vector<fastjet::PseudoJet> selectJets = selectJet(includJets);
//=============================================================================

    if (selectJets.size()>0) {
      std::vector<fastjet::PseudoJet> sortedJets = fastjet::sorted_by_pt(selectJets);
      TVector3 vLje; vLje.SetPtEtaPhi(sortedJets[0].pt(), sortedJets[0].eta(), sortedJets[0].phi());

      TVector3 vJet;
      int kJrl = -1; double dJrl = -1.;
      int kTrl = -1; double dTrl = -1.;
      for (int j=0; j<sortedJets.size(); j++) {
        double dJet = sortedJets[j].pt();
        sortedJets[j].set_user_index(-1);
        vJet.SetPtEtaPhi(dJet, sortedJets[j].eta(), sortedJets[j].phi());
        if (TMath::Abs(vJet.DeltaPhi(vLje))>dCut) { sortedJets[j].set_user_index(1); if (dJet>dJrl) { dJrl = dJet; kJrl = j; } }
        if (TMath::Abs(vJet.DeltaPhi(vLtk))>dCut) { sortedJets[j].set_user_index(2); if (dJet>dTrl) { dTrl = dJet; kTrl = j; } }
      }
//=============================================================================

      TVector3 v1sj, v2sj;
      for (int j=0; j<sortedJets.size(); j++) {
        Float_t dVar[kVar]; for (Int_t i=0; i<kVar; i++) dVar[i] = -1.;
        dVar[kWgt] = 1.; dVar[kXsc] = 1.;
        vJet.SetPtEtaPhi(sortedJets[j].pt(), sortedJets[j].eta(), sortedJets[j].phi());
//=============================================================================

        dVar[kLje] = vLje.Pt(); if (sortedJets[j].user_index()==1) { dVar[kLjr] = ((kJrl==j) ? 1.5 : 0.5); }
        dVar[kLtk] = vLtk.Pt(); if (sortedJets[j].user_index()==2) { dVar[kLtr] = ((kTrl==j) ? 1.5 : 0.5); }
//=============================================================================

        dVar[kJet] = sortedJets[j].pt();
        dVar[kAje] = sortedJets[j].area();
        dVar[kMje] = sortedJets[j].m();
//=============================================================================

        fastjet::Filter trimmer(subjDef, fastjet::SelectorPtFractionMin(0.));
        fastjet::PseudoJet trimmdJet = trimmer(sortedJets[j]);
        std::vector<fastjet::PseudoJet> trimmdSj = trimmdJet.pieces();

        double d1sj = -1.; int k1sj = -1;
        double d2sj = -1.; int k2sj = -1;
        for (int i=0; i<trimmdSj.size(); i++) {
          double dIsj = trimmdSj[i].pt(); if (dIsj<0.001) continue;

          if (dIsj>d1sj) {
            d2sj = d1sj; k2sj = k1sj;
            d1sj = dIsj; k1sj = i;
          } else if (dIsj>d2sj) {
            d2sj = dIsj; k2sj = i;
          }
        }
//=============================================================================

        if (d1sj>0.) {
          v1sj.SetPtEtaPhi(d1sj, trimmdSj[k1sj].eta(), trimmdSj[k1sj].phi());
          dVar[k1sz] = d1sj;
          dVar[k1sA] = trimmdSj[k1sj].area();
          dVar[k1sm] = trimmdSj[k1sj].m();
          dVar[k1sr] = v1sj.DeltaR(vJet);
        }

        if (d2sj>0.) {
          v2sj.SetPtEtaPhi(d2sj, trimmdSj[k2sj].eta(), trimmdSj[k2sj].phi());
          dVar[k2sz] = d2sj;
          dVar[k2sA] = trimmdSj[k2sj].area();
          dVar[k2sm] = trimmdSj[k2sj].m();
          dVar[k2sr] = v2sj.DeltaR(vJet);
        }

        if ((d1sj>0.) && (d2sj>0.)) dVar[kDsr] = v2sj.DeltaR(v1sj);

        nt->Fill(dVar);
      }
    }
//=============================================================================

    delete evt;
    ascii_in >> evt;
  }
//=============================================================================

  file->cd(); nt->Write(); file->Close();
//=============================================================================

  TString sXsec = sFile; sXsec.ReplaceAll("out", "xsecs");
  file = TFile::Open(Form("%s/xsecs/%s.root",sPath.Data(),sXsec.Data()), "READ");
  TH1D *hPtHat        = (TH1D*)file->Get("hPtHat");        hPtHat->SetDirectory(0);
  TH1D *hWeightSum    = (TH1D*)file->Get("hWeightSum");    hWeightSum->SetDirectory(0);
  TProfile *hSigmaGen = (TProfile*)file->Get("hSigmaGen"); hSigmaGen->SetDirectory(0);
  file->Close();
//=============================================================================

  sFile.ReplaceAll("out", "wgt");
  file = TFile::Open(Form("%s.root",sFile.Data()), "NEW");
  hPtHat->Write();
  hWeightSum->Write();
  hSigmaGen->Write();
  file->Close();
//=============================================================================

  cout << "DONE" << endl;
//=============================================================================

  return 0;
}
コード例 #10
0
ファイル: AnaSjePy8Mass.C プロジェクト: xcheung/AnaSubjetsMC
int main(int argc, char* argv[])
{
  TApplication theApp(srcName.Data(), &argc, argv);
//=============================================================================

  if (argc<5) return -1;
  TString sPath = argv[1]; if (sPath.IsNull()) return -1;
  TString sFile = argv[2]; if (sFile.IsNull()) return -1;
  TString sJetR = argv[3]; if (sJetR.IsNull()) return -1;
  TString sSjeR = argv[4]; if (sSjeR.IsNull()) return -1;
//=============================================================================

  sPath.ReplaceAll("#", "/");
//=============================================================================

  double dJetR = -1.;
  if (sJetR=="JetR02") dJetR = 0.2;
  if (sJetR=="JetR03") dJetR = 0.3;
  if (sJetR=="JetR04") dJetR = 0.4;
  if (sJetR=="JetR05") dJetR = 0.5;

  if (dJetR<0.) return -1;
  cout << "Jet R = " << dJetR << endl;
//=============================================================================

  double dSjeR = -1.;
  if (sSjeR=="SjeR01") dSjeR = 0.1;
  if (sSjeR=="SjeR02") dSjeR = 0.2;
  if (sSjeR=="SjeR03") dSjeR = 0.3;
  if (sSjeR=="SjeR04") dSjeR = 0.4;

  if (dSjeR<0.) return -1;
  cout << "Sub-jet R = " << dSjeR << endl;
//=============================================================================

  const double dJetsPtMin  = 0.001;
  const double dCutEtaMax  = 1.6;
  const double dJetEtaMax  = 1.;
  const double dJetAreaRef = TMath::Pi() * dJetR * dJetR;

  fastjet::GhostedAreaSpec areaSpc(dCutEtaMax);
  fastjet::JetDefinition   jetsDef(fastjet::antikt_algorithm, dJetR, fastjet::E_scheme, fastjet::Best);
  fastjet::AreaDefinition  areaDef(fastjet::active_area_explicit_ghosts,areaSpc);


  fastjet::Selector selectJet = fastjet::SelectorAbsEtaMax(dJetEtaMax);
  fastjet::JetDefinition subjDef(fastjet::kt_algorithm, dSjeR, fastjet::E_scheme, fastjet::Best);
//=============================================================================

  std::vector<fastjet::PseudoJet> fjInput;
  const double dMass = TDatabasePDG::Instance()->GetParticle(211)->Mass();
//=============================================================================

  enum { kWgt, kJet, kAje, kMje, k1sz, k1sA, k1sr, k1sm, k2sz, k2sA, k2sr, k2sm, kDsr, kIsm, kVar };

  TFile *file = TFile::Open(Form("%s.root",sFile.Data()), "NEW");
  TNtuple *nt = new TNtuple("nt", "", "fWgt:fJet:fAje:fMje:f1sj:f1sA:f1sr:f1sm:f2sj:f2sA:f2sr:f2sm:fDsr:fIsm");
//=============================================================================

  HepMC::IO_GenEvent ascii_in(Form("%s/%s.hepmc",sPath.Data(),sFile.Data()), std::ios::in);
  HepMC::GenEvent *evt = ascii_in.read_next_event();

  while (evt) {
    fjInput.resize(0);

    TLorentzVector vPar;
    for (HepMC::GenEvent::particle_const_iterator p=evt->particles_begin(); p!=evt->particles_end(); ++p) if ((*p)->status()==1) {
      vPar.SetPtEtaPhiM((*p)->momentum().perp(), (*p)->momentum().eta(), (*p)->momentum().phi(), dMass);

      if ((TMath::Abs(vPar.Eta())<dCutEtaMax)) {
        fjInput.push_back(fastjet::PseudoJet(vPar.Px(), vPar.Py(), vPar.Pz(), vPar.E()));
      }
    }
//=============================================================================

    fastjet::ClusterSequenceArea clustSeq(fjInput, jetsDef, areaDef);
    std::vector<fastjet::PseudoJet> includJets = clustSeq.inclusive_jets(dJetsPtMin);
    std::vector<fastjet::PseudoJet> selectJets = selectJet(includJets);

    TLorentzVector vJet, v1sj, v2sj, vIsj;
    for (int j=0; j<selectJets.size(); j++) {
      double dJet = selectJets[j].pt();
      vJet.SetPtEtaPhiM(dJet, selectJets[j].eta(), selectJets[j].phi(), selectJets[j].m());

      fastjet::Filter trimmer(subjDef, fastjet::SelectorPtFractionMin(0.));
      fastjet::PseudoJet trimmdJet = trimmer(selectJets[j]);
      std::vector<fastjet::PseudoJet> trimmdSj = trimmdJet.pieces();

      double d1sj = -1.; int k1sj = -1;
      double d2sj = -1.; int k2sj = -1;
      for (int i=0; i<trimmdSj.size(); i++) {
        double dIsj = trimmdSj[i].pt(); if (dIsj<0.001) continue;

        if (dIsj>d1sj) {
          d2sj = d1sj; k2sj = k1sj;
          d1sj = dIsj; k1sj = i;
        } else if (dIsj>d2sj) {
          d2sj = dIsj; k2sj = i;
        }
      }
//=============================================================================

      Float_t dVar[] = { 1., dJet, selectJets[j].area(), selectJets[j].m(), d1sj, -1., -1., -1., d2sj, -1., -1., -1., -1., -1. };

      if (d1sj>0.) {
        v1sj.SetPtEtaPhiM(d1sj, trimmdSj[k1sj].eta(), trimmdSj[k1sj].phi(), trimmdSj[k1sj].m());
        dVar[k1sr] = v1sj.DeltaR(vJet);
        dVar[k1sm] = trimmdSj[k1sj].m();
        dVar[k1sA] = trimmdSj[k1sj].area();
      }

      if (d2sj>0.) {
        v2sj.SetPtEtaPhiM(d2sj, trimmdSj[k2sj].eta(), trimmdSj[k2sj].phi(), trimmdSj[k2sj].m());
        dVar[k2sr] = v2sj.DeltaR(vJet);
        dVar[k2sm] = trimmdSj[k2sj].m();
        dVar[k2sA] = trimmdSj[k2sj].area();
      }

      if ((d1sj>0.) && (d2sj>0.)) {
        vIsj = v1sj + v2sj;
        dVar[kIsm] = vIsj.M();
        dVar[kDsr] = v2sj.DeltaR(v1sj);
      }

      nt->Fill(dVar);
    }
//=============================================================================

    delete evt;
    ascii_in >> evt;
  }
//=============================================================================

  file->cd(); nt->Write(); file->Close();
//=============================================================================

  TString sXsec = sFile; sXsec.ReplaceAll("out", "xsecs");
  file = TFile::Open(Form("%s/xsecs/%s.root",sPath.Data(),sXsec.Data()), "READ");
  TH1D *hPtHat        = (TH1D*)file->Get("hPtHat");        hPtHat->SetDirectory(0);
  TH1D *hWeightSum    = (TH1D*)file->Get("hWeightSum");    hWeightSum->SetDirectory(0);
  TProfile *hSigmaGen = (TProfile*)file->Get("hSigmaGen"); hSigmaGen->SetDirectory(0);
  file->Close();
//=============================================================================

  sFile.ReplaceAll("out", "wgt");
  file = TFile::Open(Form("%s.root",sFile.Data()), "NEW");
  hPtHat->Write();
  hWeightSum->Write();
  hSigmaGen->Write();
  file->Close();
//=============================================================================

  cout << "DONE" << endl;
  return 0;
}
void ClusterWidthAnalysisTreeMaker::FitProfiles(std::map<ULong64_t , std::vector<TProfile*> > &ProfVsAngle, string output_file){

  TFile * myFile = new TFile(output_file.c_str(), "recreate");

  ULong64_t detid;
  double voltage;
  double errvoltage;
  double Slope;
  double errSlope;
  double Origin;
  double errOrigin;
  double Chi2;
  int index;
  TTree *tree = new TTree("T", "summary information");

  tree->Branch("DetID",&detid, "DetID/l");
  tree->Branch("Voltage",&voltage,"Voltage/D");
  tree->Branch("Index",&index,"Index/I");
  tree->Branch("errVoltage",&errvoltage,"errVoltage/D");
  tree->Branch("Slope",&Slope,"Slope/D");
  tree->Branch("errSlope",&errSlope,"errSlope/D");
  tree->Branch("Origin",&Origin,"Origin/D");
  tree->Branch("errOrigin",&errOrigin,"errOrigin/D");
  tree->Branch("Chi2",&Chi2,"Chi2/D");


  //TCanvas* c1 = new TCanvas();
  TH1F* hChi2 = new TH1F("hChi2", "hChi2", 100, 0, 100);
  
  unsigned int nfitrm=0;

  for(std::map<ULong64_t , std::vector<TProfile*> >::iterator iter = ProfVsAngle.begin(); iter != ProfVsAngle.end(); ++iter){
    
	unsigned int i=0; // voltage index    
    std::set< int >::iterator itVolt;
	std::set< int > Voltage = VSmaker.getVoltageList();
    for( itVolt=Voltage.begin(); itVolt!=Voltage.end(); itVolt++){
      
      //std::cout<<"going through the measurement: " << i << std::endl;
            
      TString thestring;
      thestring.Form("DetID_%llu_prof_%u",iter->first,i);
 	  	  
	  if(i>=iter->second.size()) 
       { std::cout<<" Wrong number of voltage steps. "<<std::endl; i++; continue;}
 	  TProfile*  Prof = iter->second[i];
	  
	  if(!Prof) 
       { std::cout<<" Profile "<<thestring.Data()<<"_"<<i<<" not found."<<std::endl; i++; continue;}
 
      //if(Histo->GetEntries()) hNhits->Fill(Histo->Integral());
	  
	  /*if(Histo->Integral()<20) //0.1
	   { //std::cout<<" Not enought entries for histo "<<thestring.Data()<<std::endl;
	    i++; continue;}*/
 
	  
	  detid = iter->first;

	  bool rmfit=false;
	  
	  TF1* pol = new TF1("pol", "pol1", -3, 3);
	  pol->SetRange(-1,0);
	  Prof->Fit("pol", "qr");
	  double chi2 = pol->GetChisquare()/pol->GetNDF();
	  hChi2->Fill(chi2);
	  if(chi2>10) rmfit=true;
	  

      if( rmfit || 
      // TIB modules
          // TIB - 1.4.2.5
      detid==369121605 || detid==369121606 || detid==369121614 || 
      detid==369121613 || detid==369121610 || detid==369121609 ||
          // TIB - 1.2.2.1
      detid==369121390 || detid==369121382 || detid==369121386 || 
      detid==369121385 || detid==369121389 || detid==369121381 ||
          // others in TIB  
      detid==369121437 || detid==369142077 || detid==369121722 || 
      detid==369125534 || detid==369137018 || detid==369121689 ||
      detid==369121765 || detid==369137045 || detid==369169740 ||
      detid==369121689 ||
      // TOB modules 
	      // TOB + 4.3.3.8
      detid/10==436281512 || detid/10==436281528 || detid/10==436281508 ||
      detid/10==436281524 || detid/10==436281520 || detid/10==436281516 ||
          // others in TOB  
      detid/10==436228249 || detid/10==436232694 || detid/10==436228805 ||
      detid/10==436244722 || detid/10==436245110 || detid/10==436249546 ||
      detid/10==436310808 || detid/10==436312136 || detid/10==436315600 ||
	      // without 'sensors' option 
      detid==436281512 || detid==436281528 || detid==436281508 ||
      detid==436281524 || detid==436281520 || detid==436281516 ||
      detid==436228249 || detid==436232694 || detid==436228805 ||
      detid==436244722 || detid==436245110 || detid==436249546 ||
      detid==436310808 || detid==436312136 || detid==436315600 || 
      // TID modules
      detid==402664070 || detid==402664110 ||
	  // TEC modules in small scans
      detid==470148196 || detid==470148200 || detid==470148204 ||
      detid==470148228 || detid==470148232 || detid==470148236 ||
      detid==470148240 || detid==470148261 || detid==470148262 ||
	  detid==470148265 || detid==470148266 || detid==470148292 ||
	  detid==470148296 || detid==470148300 || detid==470148304 ||
	  detid==470148324 || detid==470148328 || detid==470148332 ||
	  detid==470148336 || detid==470148340 )  { 
	    Prof->Write();
        std::cout << " Saving histo : " << thestring.Data() << std::endl;
      }  


	  if(rmfit) {nfitrm++; i++; continue;}

          int subdet = ((detid>>25)&0x7);
          int TECgeom=0;
          if(subdet==6) TECgeom = ((detid>>5)&0x7);

      // save values
	  detid = iter->first;
	  voltage  = *itVolt;
	  index = i;
	  errvoltage = 2 ;
	  Slope = pol->GetParameter(1);
	  errSlope = pol->GetParError(1);
	  Origin = pol->GetParameter(0);
	  errOrigin = pol->GetParError(0);
	  Chi2 = chi2;
	  tree->Fill();
	    
	  i++;

    }  

  }
  
  tree->Write();
  //hNhits->Write();

  
  //// If you want to store all the individual detId histograms uncomments this line !!!!
  //myFile->Write();
  myFile->Close();

}
コード例 #12
0
int main(int argc, char* argv[])
{
  TApplication theApp(srcName.Data(), &argc, argv);
//=============================================================================

  for (int i=0; i<argc; i++) cout << i << ", " << argv[i] << endl;
//=============================================================================

  if (argc<5) return -1;
  TString sPath = argv[1]; if (sPath.IsNull()) return -1;
  TString sFile = argv[2]; if (sFile.IsNull()) return -1;
  TString sJetR = argv[3]; if (sJetR.IsNull()) return -1;
  TString sSjeR = argv[4]; if (sSjeR.IsNull()) return -1;
//=============================================================================

  sPath.ReplaceAll("#", "/");
//=============================================================================

  double dJetR = -1.;
  if (sJetR=="JetR02") dJetR = 0.2;
  if (sJetR=="JetR03") dJetR = 0.3;
  if (sJetR=="JetR04") dJetR = 0.4;
  if (sJetR=="JetR05") dJetR = 0.5;

  if (dJetR<0.) return -1;
  cout << "Jet R = " << dJetR << endl;
//=============================================================================

  double dSjeR = -1.;
  if (sSjeR=="SjeR01") dSjeR = 0.1;
  if (sSjeR=="SjeR02") dSjeR = 0.2;
  if (sSjeR=="SjeR03") dSjeR = 0.3;
  if (sSjeR=="SjeR04") dSjeR = 0.4;

  if (dSjeR<0.) return -1;
  cout << "Sub-jet R = " << dSjeR << endl;
//=============================================================================

  const double dJetsPtMin  = 0.001;
  const double dCutEtaMax  = 1.6;
  const double dJetEtaMax  = 1.;
  const double dJetAreaRef = TMath::Pi() * dJetR * dJetR;

  fastjet::GhostedAreaSpec areaSpc(dCutEtaMax);
  fastjet::JetDefinition   jetsDef(fastjet::antikt_algorithm, dJetR, fastjet::BIpt_scheme, fastjet::Best);

//fastjet::AreaDefinition  areaDef(fastjet::active_area,areaSpc);
  fastjet::AreaDefinition  areaDef(fastjet::active_area_explicit_ghosts,areaSpc);

//fastjet::JetDefinition   bkgsDef(fastjet::kt_algorithm, 0.2, fastjet::BIpt_scheme, fastjet::Best);
//fastjet::AreaDefinition  aBkgDef(fastjet::active_area_explicit_ghosts, areaSpc);

  fastjet::Selector selectJet = fastjet::SelectorAbsEtaMax(dJetEtaMax);
//fastjet::Selector selectRho = fastjet::SelectorAbsEtaMax(dCutEtaMax-0.2);
//fastjet::Selector selecHard = fastjet::SelectorNHardest(2);
//fastjet::Selector selectBkg = selectRho * (!(selecHard));
//fastjet::JetMedianBackgroundEstimator bkgsEstimator(selectBkg, bkgsDef, aBkgDef);
//fastjet::Subtractor                   bkgSubtractor(&bkgsEstimator);

  fastjet::JetDefinition subjDef(fastjet::antikt_algorithm, dSjeR, fastjet::BIpt_scheme, fastjet::Best);
//=============================================================================

  std::vector<fastjet::PseudoJet> fjInput;
//=============================================================================

  TList *list = new TList();
  TH1D *hPtHat = new TH1D("hPtHat", "", 1000, 0., 1000.);

  TH1D *hJet = new TH1D("hJet", "", 1000, 0., 1000.); hJet->Sumw2(); list->Add(hJet);
  TH2D *hJetNsj = new TH2D("hJetNsj", "", 1000, 0., 1000., 101, -0.5, 100.5); hJetNsj->Sumw2(); list->Add(hJetNsj);

  TH2D *hJetIsj = new TH2D("hJetIsj", "", 1000, 0., 1000., 1000, 0., 1000.); hJetIsj->Sumw2(); list->Add(hJetIsj);
  TH2D *hJet1sj = new TH2D("hJet1sj", "", 1000, 0., 1000., 1000, 0., 1000.); hJet1sj->Sumw2(); list->Add(hJet1sj);
  TH2D *hJet2sj = new TH2D("hJet2sj", "", 1000, 0., 1000., 1000, 0., 1000.); hJet2sj->Sumw2(); list->Add(hJet2sj);
  TH2D *hJetDsj = new TH2D("hJetDsj", "", 1000, 0., 1000., 1000, 0., 1000.); hJetDsj->Sumw2(); list->Add(hJetDsj);

  TH2D *hJetIsz = new TH2D("hJetIsz", "", 1000, 0., 1000., 120, 0., 1.2); hJetIsz->Sumw2(); list->Add(hJetIsz);
  TH2D *hJet1sz = new TH2D("hJet1sz", "", 1000, 0., 1000., 120, 0., 1.2); hJet1sz->Sumw2(); list->Add(hJet1sz);
  TH2D *hJet2sz = new TH2D("hJet2sz", "", 1000, 0., 1000., 120, 0., 1.2); hJet2sz->Sumw2(); list->Add(hJet2sz);
  TH2D *hJetDsz = new TH2D("hJetDsz", "", 1000, 0., 1000., 120, 0., 1.2); hJetDsz->Sumw2(); list->Add(hJetDsz);
//=============================================================================

  AliRunLoader *rl = AliRunLoader::Open(Form("%s/galice.root",sPath.Data())); if (!rl) return -1;

  if (rl->LoadHeader()) return -1;
  if (rl->LoadKinematics("READ")) return -1;
//=============================================================================

  for (Int_t iEvent=0; iEvent<rl->GetNumberOfEvents(); iEvent++) {
    fjInput.resize(0);
    if (rl->GetEvent(iEvent)) continue;
//=============================================================================

    AliStack  *pStack  = rl->Stack();     if (!pStack)  continue;
    AliHeader *pHeader = rl->GetHeader(); if (!pHeader) continue;
//=============================================================================

    AliGenPythiaEventHeader *pHeadPy = (AliGenPythiaEventHeader*)pHeader->GenEventHeader();

    if (!pHeadPy) continue;
    hPtHat->Fill(pHeadPy->GetPtHard());
//=============================================================================

    for (Int_t i=0; i<pStack->GetNtrack(); i++) if (pStack->IsPhysicalPrimary(i)) {
      TParticle *pTrk = pStack->Particle(i); if (!pTrk) continue;
      if (TMath::Abs(pTrk->Eta())>dCutEtaMax) { pTrk = 0; continue; }
//    TParticlePDG *pPDG = pTrk->GetPDG(); if (!pPDG) { pTrk = 0; continue; }

      fjInput.push_back(fastjet::PseudoJet(pTrk->Px(), pTrk->Py(), pTrk->Pz(), pTrk->P()));

//    pPDG = 0;
      pTrk = 0;
    }
//=============================================================================

    fastjet::ClusterSequenceArea clustSeq(fjInput, jetsDef, areaDef);
    std::vector<fastjet::PseudoJet> includJets = clustSeq.inclusive_jets(dJetsPtMin);
//  std::vector<fastjet::PseudoJet> subtedJets = bkgSubtractor(includJets);
    std::vector<fastjet::PseudoJet> selectJets = selectJet(includJets);
//  std::vector<fastjet::PseudoJet> sortedJets = fastjet::sorted_by_pt(selectJets);

    for (int j=0; j<selectJets.size(); j++) {
      double dJet = selectJets[j].pt();

      hJet->Fill(dJet);
//=============================================================================

      fastjet::Filter trimmer(subjDef, fastjet::SelectorPtFractionMin(0.));
      fastjet::PseudoJet trimmdJet = trimmer(selectJets[j]);
      std::vector<fastjet::PseudoJet> trimmdSj = trimmdJet.pieces();

      double nIsj = 0.;
      double d1sj = -1.; int k1sj = -1;
      double d2sj = -1.; int k2sj = -1;
      for (int i=0; i<trimmdSj.size(); i++) {
        double dIsj = trimmdSj[i].pt(); if (dIsj<0.001) continue;

        hJetIsj->Fill(dJet, dIsj);
        hJetIsz->Fill(dJet, dIsj/dJet);

        if (dIsj>d1sj) {
          d2sj = d1sj; k2sj = k1sj;
          d1sj = dIsj; k1sj = i;
        } else if (dIsj>d2sj) {
          d2sj = dIsj; k2sj = i;
        } nIsj += 1.;
      }

      hJetNsj->Fill(dJet, nIsj);
      if (d1sj>0.) { hJet1sj->Fill(dJet, d1sj); hJet1sz->Fill(dJet, d1sj/dJet); }
      if (d2sj>0.) { hJet2sj->Fill(dJet, d2sj); hJet2sz->Fill(dJet, d2sj/dJet); }

      if ((d1sj>0.) && (d2sj>0.)) {
        double dsj = d1sj - d2sj;
        double dsz = dsj / dJet;

        hJetDsj->Fill(dJet, dsj);
        hJetDsz->Fill(dJet, dsz);
      }
    }
//=============================================================================

    pStack  = 0;
    pHeadPy = 0;
    pHeader = 0;
  }
//=============================================================================

  rl->UnloadgAlice();
  rl->UnloadHeader();
  rl->UnloadKinematics();
  rl->RemoveEventFolder();
//=============================================================================

  TFile *file = TFile::Open(Form("%s/pyxsec_hists.root",sPath.Data()), "READ");
  TList *lXsc = (TList*)file->Get("cFilterList");
  file->Close();

  TH1D     *hWeightSum = (TH1D*)lXsc->FindObject("h1Trials");   hWeightSum->SetName("hWeightSum");
  TProfile *hSigmaGen  = (TProfile*)lXsc->FindObject("h1Xsec"); hSigmaGen->SetName("hSigmaGen");
//=============================================================================

  file = TFile::Open(Form("%s.root",sFile.Data()), "NEW");
  hPtHat->Write();
  hWeightSum->Write();
  hSigmaGen->Write();
  list->Write();
  file->Close();
//=============================================================================

  cout << "DONE" << endl;
//=============================================================================

  return 0;
}
コード例 #13
0
int recoil_analysis(TString inputz, TString rootoutput, char* psoutput, int binz) {

  ifstream inputResp(inputz);
  ifstream inputSET(inputz);
  TFile* ROOTout = new TFile(rootoutput, "update");

  int theBin = -1;
  theBin = binz;


 int ptnbins = 46;
 double ptbins[] = {0.0, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25, 3.5, 3.75, 4.0, 4.5, 5.0, 5.5, 6.0, 7.0, 8.0, 9.0, 
		   10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 
		    30.0, 33.0, 36.0, 39.0, 42.0, 45.0, 49.0, 55.0, 70.0, 100.0, 500.0};


  // Defines the variables  
  RooRealVar resp("resp", "u_{T}/q_{T}", 0., 30.);
  RooRealVar ZBset("ZBset", "ZB SET", 0., 40.);//was 20
  RooRealVar dphi_norm("dphi_norm", "#Delta#phi / #pi", -1., 1.);
  RooRealVar lumi("lumi", "lumi", 0., 20.);
  RooRealVar zphi("zphi", "Z #phi", 0., 2*TMath::Pi());
  RooRealVar set_ut("set_ut", "SET - u_{T}", 0., 100.);
  RooRealVar ut("ut", "u_{T}", 0., 200.); //was 200
 
  double resp_bdr[] = {20., 15., 15., 10.,10.,10., 5., 5.,5., 5.,5.,5.,3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5};
  double dphi_bdr[] = { 1.,  1.,  1., 1., 1., 1., 1., 1., 1., 1.,  1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., .5, .5, .5, .5, .5, .5, .5, .5, .3, .3, .3, .3,.3,.3,.3,.3, .2, .2, .2, .2, .2, .2, .1, .1};


 int ptnbinszphi = 16;
 double ptbinszphi[] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 15.0, 20.0, 30., 500.0};


 int ptnbinsset = 15;
 double ptbinsset[] = {0.0, 1.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 15.0, 20.0, 25.0, 30., 40.0, 50.0, 70.0, 500.0};
 double set_ut_bdr[]= {20., 30., 40., 40., 50., 50., 60., 60., 60., 60., 70.,70.,70., 70., 90.};
 double ut_bdr[]=    {10., 10., 15., 15.,15., 20., 20., 25., 30., 40.,40., 60.,60.,90., 200.}; //250

  // Import the recoil (response x delta phi) from dump file 
  RooDataSet** RecoilRespData;
  RooDataSet** SETData;

  cout<<"importing data response"<<endl;
  if (theBin == -1 || theBin == -3) RecoilRespData = importRecoilRespData(inputResp, resp, ZBset, dphi_norm, lumi, zphi, ptnbins, ptbins);

  if (theBin == -2) SETData = importSETData(inputSET, set_ut, ut, ptnbinsset, ptbinsset);
  if (theBin == -4) RecoilRespData = importRecoilRespData(inputResp, resp, ZBset, dphi_norm, lumi, zphi, ptnbinszphi, ptbinszphi);
  
  inputResp.close();
  inputSET.close();
  
  gROOT->SetStyle("Plain");
  gStyle->SetOptStat(0000);
  gStyle->SetPalette(1,0);
  TCanvas* c1 = new TCanvas("c1","c1");
  c1->Print(TString::Format("%s[", psoutput));



   for (int i=0; i<ptnbins; i++) {
     //this is dphi and response in bins of true phi
    if (i!=theBin && theBin != -1) continue;

    if (RecoilRespData[i]->numEntries() < 5) continue;
     cout<<"RESP bin "<<i<<endl;

    RecoilRespData[i]->printMultiline(cout, 1);
    TH2D* genHist0(0);
    TH2D* genHist1(0);
    TH2D* genHist2(0);
    TH2D* genHist3(0);
    TH2D* genHist4(0);
    TH2D* genHist5(0);

    //slightly different binning than 0-1, etc on 0 to 2pi scale to be more even on the sides (2 larger bins, rather than one)
    RooDataSet* RecoilRespData_phi0 = (RooDataSet*) RecoilRespData[i]->reduce("zphi>=0.&&zphi<1.");
    RooDataSet* RecoilRespData_phi1 = (RooDataSet*) RecoilRespData[i]->reduce("zphi>=1.&&zphi<2.");
    RooDataSet* RecoilRespData_phi2 = (RooDataSet*) RecoilRespData[i]->reduce("zphi>=2.&&zphi<3.");
    RooDataSet* RecoilRespData_phi3 = (RooDataSet*) RecoilRespData[i]->reduce("zphi>=3.&&zphi<4.");
    RooDataSet* RecoilRespData_phi4 = (RooDataSet*) RecoilRespData[i]->reduce("zphi>=4.&&zphi<5.");
    RooDataSet* RecoilRespData_phi5 = (RooDataSet*) RecoilRespData[i]->reduce("zphi>=5.");

    RecoilRespData_phi0->printMultiline(cout, 1);
    RecoilRespData_phi1->printMultiline(cout, 1);
    RecoilRespData_phi2->printMultiline(cout, 1);
    RecoilRespData_phi3->printMultiline(cout, 1);
    RecoilRespData_phi4->printMultiline(cout, 1);
    RecoilRespData_phi5->printMultiline(cout, 1);


    cout<<"RESP bin start HIST "<<i<<endl;
    genHist0 = (TH2D*) RecoilRespData_phi0->createHistogram(TString::Format("recoil_resp_hist_truephi0_bin_%d", i).Data(), 
							 resp, Binning(250, 0., resp_bdr[i]),
							 YVar(dphi_norm, Binning(128, -1*dphi_bdr[i], dphi_bdr[i])));
    genHist1 = (TH2D*) RecoilRespData_phi1->createHistogram(TString::Format("recoil_resp_hist_truephi1_bin_%d", i).Data(), 
							 resp, Binning(250, 0., resp_bdr[i]),
							 YVar(dphi_norm, Binning(128, -1*dphi_bdr[i], dphi_bdr[i])));
    genHist2 = (TH2D*) RecoilRespData_phi2->createHistogram(TString::Format("recoil_resp_hist_truephi2_bin_%d", i).Data(), 
							 resp, Binning(250, 0., resp_bdr[i]),
							 YVar(dphi_norm, Binning(128, -1*dphi_bdr[i], dphi_bdr[i])));
    genHist3 = (TH2D*) RecoilRespData_phi3->createHistogram(TString::Format("recoil_resp_hist_truephi3_bin_%d", i).Data(), 
							 resp, Binning(250, 0., resp_bdr[i]),
							 YVar(dphi_norm, Binning(128, -1*dphi_bdr[i], dphi_bdr[i])));
    genHist4 = (TH2D*) RecoilRespData_phi4->createHistogram(TString::Format("recoil_resp_hist_truephi4_bin_%d", i).Data(), 
							 resp, Binning(250, 0., resp_bdr[i]),
							 YVar(dphi_norm, Binning(128, -1*dphi_bdr[i], dphi_bdr[i])));
    genHist5 = (TH2D*) RecoilRespData_phi5->createHistogram(TString::Format("recoil_resp_hist_truephi5_bin_%d", i).Data(), 
							 resp, Binning(250, 0., resp_bdr[i]),
							 YVar(dphi_norm, Binning(128, -1*dphi_bdr[i], dphi_bdr[i])));
      
  
    cout<<"RESP bin start Write "<<i<<endl;
 
     genHist0->Smooth(1);
    genHist0->SetName(TString::Format("recoil_resp_hist_truephi0_bin_%d", i));
    genHist0->SetTitle(TString::Format("recoil_resp_hist_truephi0_bin_%d", i));      
    double integral0 = genHist0->Integral();
    genHist0->Scale(1/integral0);

     genHist1->Smooth(1);
    genHist1->SetName(TString::Format("recoil_resp_hist_truephi1_bin_%d", i));
    genHist1->SetTitle(TString::Format("recoil_resp_hist_truephi1_bin_%d", i));      
    double integral1 = genHist1->Integral();
    genHist1->Scale(1/integral1);

     genHist2->Smooth(1);
    genHist2->SetName(TString::Format("recoil_resp_hist_truephi2_bin_%d", i));
    genHist2->SetTitle(TString::Format("recoil_resp_hist_truephi2_bin_%d", i));      
    double integral2 = genHist2->Integral();
    genHist2->Scale(1/integral2);

     genHist3->Smooth(1);
    genHist3->SetName(TString::Format("recoil_resp_hist_truephi3_bin_%d", i));
    genHist3->SetTitle(TString::Format("recoil_resp_hist_truephi3_bin_%d", i));      
    double integral3 = genHist3->Integral();
    genHist3->Scale(1/integral3);

     genHist4->Smooth(1);
    genHist4->SetName(TString::Format("recoil_resp_hist_truephi4_bin_%d", i));
    genHist4->SetTitle(TString::Format("recoil_resp_hist_truephi4_bin_%d", i));      
    double integral4 = genHist4->Integral();
    genHist4->Scale(1/integral4);

     genHist5->Smooth(1);
    genHist5->SetName(TString::Format("recoil_resp_hist_truephi5_bin_%d", i));
    genHist5->SetTitle(TString::Format("recoil_resp_hist_truephi5_bin_%d", i));      
    double integral5 = genHist5->Integral();
    genHist5->Scale(1/integral5);



    ROOTout->cd();
    genHist0->Write(TString::Format("recoil_resp_hist_truephi0_bin_%d", i),TObject::kOverwrite);
    genHist0->Draw("colz");      
    c1->Print(psoutput);

    genHist1->Write(TString::Format("recoil_resp_hist_truephi1_bin_%d", i),TObject::kOverwrite);
    genHist1->Draw("colz");      
    c1->Print(psoutput);

    genHist2->Write(TString::Format("recoil_resp_hist_truephi2_bin_%d", i),TObject::kOverwrite);
    genHist2->Draw("colz");      
    c1->Print(psoutput);

    genHist3->Write(TString::Format("recoil_resp_hist_truephi3_bin_%d", i),TObject::kOverwrite);
    genHist3->Draw("colz");      
    c1->Print(psoutput);

    genHist4->Write(TString::Format("recoil_resp_hist_truephi4_bin_%d", i),TObject::kOverwrite);
    genHist4->Draw("colz");      
    c1->Print(psoutput);

    genHist5->Write(TString::Format("recoil_resp_hist_truephi5_bin_%d", i),TObject::kOverwrite);
    genHist5->Draw("colz");      
    c1->Print(psoutput);
  }

   for (int i=0; i<ptnbins; i++) {
     //this is zbset and response, in bins of luminosity
     if (i!=theBin && theBin != -3) continue;

    if (RecoilRespData[i]->numEntries() < 5) continue;
     cout<<"RESP bin "<<i<<endl;

    RecoilRespData[i]->printMultiline(cout, 1);
    TH2D* genHist0(0);
    TH2D* genHist1(0);
    TH2D* genHist2(0);
    TH2D* genHist3(0);
    TH2D* genHist4(0);
    TH2D* genHist5(0);
    RooDataSet* RecoilRespData_lumi0 = (RooDataSet*) RecoilRespData[i]->reduce("lumi>=0.&&lumi<2.");
    RooDataSet* RecoilRespData_lumi1 = (RooDataSet*) RecoilRespData[i]->reduce("lumi>=2.&&lumi<3.");
    RooDataSet* RecoilRespData_lumi2 = (RooDataSet*) RecoilRespData[i]->reduce("lumi>=3.&&lumi<4.");
    RooDataSet* RecoilRespData_lumi3 = (RooDataSet*) RecoilRespData[i]->reduce("lumi>=4.&&lumi<5.");
    RooDataSet* RecoilRespData_lumi4 = (RooDataSet*) RecoilRespData[i]->reduce("lumi>=5.&&lumi<6.");
    RooDataSet* RecoilRespData_lumi5 = (RooDataSet*) RecoilRespData[i]->reduce("lumi>=6.");

    RecoilRespData_lumi0->printMultiline(cout, 1);
    RecoilRespData_lumi1->printMultiline(cout, 1);
    RecoilRespData_lumi2->printMultiline(cout, 1);
    RecoilRespData_lumi3->printMultiline(cout, 1);
    RecoilRespData_lumi4->printMultiline(cout, 1);
    RecoilRespData_lumi5->printMultiline(cout, 1);


    cout<<"RESP bin start HIST "<<i<<endl;
    genHist0 = (TH2D*) RecoilRespData_lumi0->createHistogram(TString::Format("recoil_resp_zbset_hist_lumibin0_bin_%d", i).Data(), 
							 resp, Binning(500, 0., resp_bdr[i]),
							 YVar(ZBset, Binning(25, 0.,25.)));//was 40 0 20    
    genHist1 = (TH2D*) RecoilRespData_lumi1->createHistogram(TString::Format("recoil_resp_zbset_hist_lumibin1_bin_%d", i).Data(), 
							 resp, Binning(500, 0., resp_bdr[i]),
							 YVar(ZBset, Binning(25, 0.,25.)));//was 40 0 20    
    genHist2 = (TH2D*) RecoilRespData_lumi2->createHistogram(TString::Format("recoil_resp_zbset_hist_lumibin2_bin_%d", i).Data(), 
							 resp, Binning(500, 0., resp_bdr[i]),
							 YVar(ZBset, Binning(25, 0.,25.)));//was 40 0 20    
    genHist3 = (TH2D*) RecoilRespData_lumi3->createHistogram(TString::Format("recoil_resp_zbset_hist_lumibin3_bin_%d", i).Data(), 
							 resp, Binning(500, 0., resp_bdr[i]),
							 YVar(ZBset, Binning(25, 0.,25.)));//was 40 0 20    
    genHist4 = (TH2D*) RecoilRespData_lumi4->createHistogram(TString::Format("recoil_resp_zbset_hist_lumibin4_bin_%d", i).Data(), 
							 resp, Binning(500, 0., resp_bdr[i]),
							 YVar(ZBset, Binning(25, 0.,25.)));//was 40 0 20    
    genHist5 = (TH2D*) RecoilRespData_lumi5->createHistogram(TString::Format("recoil_resp_zbset_hist_lumibin5_bin_%d", i).Data(), 
							 resp, Binning(500, 0., resp_bdr[i]),
							 YVar(ZBset, Binning(25, 0.,25.)));//was 40 0 20
    
   
    cout<<"RESP bin start Write "<<i<<endl;

     genHist0->Smooth(1);
    genHist0->SetName(TString::Format("recoil_resp_zbset_hist_lumibin0_bin_%d", i));
    genHist0->SetTitle(TString::Format("recoil_resp_zbset_hist_lumibin0_bin_%d", i));      
    double integral0 = genHist0->Integral();
    genHist0->Scale(1/integral0);

    genHist1->Smooth(1);
    genHist1->SetName(TString::Format("recoil_resp_zbset_hist_lumibin1_bin_%d", i));
    genHist1->SetTitle(TString::Format("recoil_resp_zbset_hist_lumibin1_bin_%d", i));      
    double integral1 = genHist1->Integral();
    genHist1->Scale(1/integral1);

    genHist2->Smooth(1);
    genHist2->SetName(TString::Format("recoil_resp_zbset_hist_lumibin2_bin_%d", i));
    genHist2->SetTitle(TString::Format("recoil_resp_zbset_hist_lumibin2_bin_%d", i));      
    double integral2 = genHist2->Integral();
    genHist2->Scale(1/integral2);

    genHist3->Smooth(1);
    genHist3->SetName(TString::Format("recoil_resp_zbset_hist_lumibin3_bin_%d", i));
    genHist3->SetTitle(TString::Format("recoil_resp_zbset_hist_lumibin3_bin_%d", i));      
    double integral3 = genHist3->Integral();
    genHist3->Scale(1/integral3);

     genHist4->Smooth(1);
    genHist4->SetName(TString::Format("recoil_resp_zbset_hist_lumibin4_bin_%d", i));
    genHist4->SetTitle(TString::Format("recoil_resp_zbset_hist_lumibin4_bin_%d", i));      
    double integral4 = genHist4->Integral();
    genHist4->Scale(1/integral4);

     genHist5->Smooth(1);
    genHist5->SetName(TString::Format("recoil_resp_zbset_hist_lumibin5_bin_%d", i));
    genHist5->SetTitle(TString::Format("recoil_resp_zbset_hist_lumibin5_bin_%d", i));      
    double integral5 = genHist5->Integral();
    genHist5->Scale(1/integral5);

    ROOTout->cd();
    genHist0->Write(TString::Format("recoil_resp_zbset_hist_lumibin0_bin_%d", i),TObject::kOverwrite);
    genHist0->Draw("colz");      
    c1->Print(psoutput);

    genHist1->Write(TString::Format("recoil_resp_zbset_hist_lumibin1_bin_%d", i),TObject::kOverwrite);
    genHist1->Draw("colz");      
    c1->Print(psoutput);

    genHist2->Write(TString::Format("recoil_resp_zbset_hist_lumibin2_bin_%d", i),TObject::kOverwrite);
    genHist2->Draw("colz");      
    c1->Print(psoutput);

    genHist3->Write(TString::Format("recoil_resp_zbset_hist_lumibin3_bin_%d", i),TObject::kOverwrite);
    genHist3->Draw("colz");      
    c1->Print(psoutput);

    genHist4->Write(TString::Format("recoil_resp_zbset_hist_lumibin4_bin_%d", i),TObject::kOverwrite);
    genHist4->Draw("colz");      
    c1->Print(psoutput);

    genHist5->Write(TString::Format("recoil_resp_zbset_hist_lumibin5_bin_%d", i),TObject::kOverwrite);
    genHist5->Draw("colz");      
    c1->Print(psoutput);

  }
   std::vector <double>  parmMean;
   std::vector <double>  parmA;
   std::vector <double>  parmB;
   std::vector <double>  parmC;
   std::vector <double>  parmD;
   
   parmMean.clear();
   parmA.clear();
   parmB.clear();
   parmC.clear();
   parmD.clear();

  for (int i=0; i<ptnbinszphi; i++) {
     //this is zbset and response, in bins of luminosity
     if (i!=theBin && theBin != -4) continue;

    if (RecoilRespData[i]->numEntries() < 5) continue;
     cout<<"RESP bin "<<i<<endl;

    RecoilRespData[i]->printMultiline(cout, 1);
    TH2D* genHist(0);
  
    double twopi = 2*TMath::Pi();
    cout<<"RESP bin start HIST "<<i<<endl;
    genHist = (TH2D*) RecoilRespData[i]->createHistogram(TString::Format("recoil_resp_zphi_hist_bin_%d", i).Data(), 
							 resp, Binning(500, 0., resp_bdr[i]),
							    YVar(zphi, Binning(64, 0., twopi)));//was 40 0 20    
  
   
    cout<<"RESP bin start Write "<<i<<endl;
   
    genHist->SetName(TString::Format("recoil_resp_zphi_hist_bin_%d", i));
    genHist->SetTitle(TString::Format("recoil_resp_zphi_hist_bin_%d", i));      
    TProfile *myhisty = genHist->ProfileY();

    ROOTout->cd();
    myhisty->Write(TString::Format("recoil_resp_zphi_hist_bin_%d", i),TObject::kOverwrite);
    TF1 *pol3 = new TF1("pol3", "pol3");
    myhisty->Fit("pol3");
    double stats[7];
    myhisty->GetStats(stats); 
    parmMean.push_back(myhisty->GetMean(2));
    parmA.push_back(pol3->GetParameter(0));
    parmB.push_back(pol3->GetParameter(1));
    parmC.push_back(pol3->GetParameter(2));
    parmD.push_back(pol3->GetParameter(3));

    myhisty->Draw();  
    c1->Print(psoutput); 
  }

  if (theBin == -4){
    
      cout<<"HardRecoil_zphiresp_Mean:       ";
    for (int i=0; i<ptnbinszphi-1; i++) {
      cout<<parmMean[i]<<" ";
    }
    cout<<parmMean[ptnbinszphi-1]<<endl;;

      cout<<"HardRecoil_zphiresp_ParameterA: ";
    for (int i=0; i<ptnbinszphi-1; i++) {
      cout<<parmA[i]<<" ";
    }
    cout<<parmA[ptnbinszphi-1]<<endl;;

      cout<<"HardRecoil_zphiresp_ParameterB: ";
    for (int i=0; i<ptnbinszphi-1; i++) {
      cout<<parmB[i]<<" ";
    }
    cout<<parmB[ptnbinszphi-1]<<endl;;

      cout<<"HardRecoil_zphiresp_ParameterC: ";
    for (int i=0; i<ptnbinszphi-1; i++) {
      cout<<parmC[i]<<" ";
    }
    cout<<parmC[ptnbinszphi-1]<<endl;;

      cout<<"HardRecoil_zphiresp_ParameterD: ";
    for (int i=0; i<ptnbinszphi-1; i++) {
      cout<<parmD[i]<<" ";
    }
    cout<<parmD[ptnbinszphi-1]<<endl;;
  }



  for (int i=0; i<ptnbinsset; i++) {      

    if (theBin != -2) continue;      
    if (SETData[i]->numEntries() < 5) continue;
    cout<<"SET bin "<<i<<endl;
    SETData[i]->printMultiline(cout, 1);
    TH2D* genHist(0);
  
    cout<<"SET bin start HIST "<<i<<endl;
    genHist = (TH2D*) SETData[i]->createHistogram(TString::Format("set_ut_kde_bin_%d", i).Data(), 
						  set_ut, Binning(500, 0., set_ut_bdr[i]),
						  YVar(ut, Binning(500, 0., ut_bdr[i]))); 
    genHist->Smooth(1);
    genHist->SetName(TString::Format("set_ut_hist_bin_%d", i));
    genHist->SetTitle(TString::Format("set_ut_hist_bin_%d", i));      
    double integral = genHist->Integral();
    genHist->Scale(1/integral);
    ROOTout->cd();
    genHist->Write(TString::Format("set_ut_hist_bin_%d", i),TObject::kOverwrite);
    genHist->Draw("colz");      
    c1->Print(psoutput);
    
  }

  c1->Print(TString::Format("%s]", psoutput));

  ROOTout->Close();

  return(0);
}
コード例 #14
0
ファイル: AnaSjePy8Mass.C プロジェクト: xcheung/AnaSubjetsMC
int main(int argc, char* argv[])
{
  TApplication theApp(srcName.Data(), &argc, argv);
//=============================================================================

  if (argc<5) return -1;
  TString sPath = argv[1]; if (sPath.IsNull()) return -1;
  TString sFile = argv[2]; if (sFile.IsNull()) return -1;
  TString sJetR = argv[3]; if (sJetR.IsNull()) return -1;
  TString sSjeR = argv[4]; if (sSjeR.IsNull()) return -1;
//=============================================================================

  sPath.ReplaceAll("#", "/");
//=============================================================================

  double dJetR = -1.;
  if (sJetR=="JetR02") dJetR = 0.2;
  if (sJetR=="JetR03") dJetR = 0.3;
  if (sJetR=="JetR04") dJetR = 0.4;
  if (sJetR=="JetR05") dJetR = 0.5;

  if (dJetR<0.) return -1;
  cout << "Jet R = " << dJetR << endl;
//=============================================================================

  double dSjeR = -1.;
  if (sSjeR=="SjeR01") dSjeR = 0.1;
  if (sSjeR=="SjeR02") dSjeR = 0.2;
  if (sSjeR=="SjeR03") dSjeR = 0.3;
  if (sSjeR=="SjeR04") dSjeR = 0.4;

  if (dSjeR<0.) return -1;
  cout << "Sub-jet R = " << dSjeR << endl;
//=============================================================================

  const double dJetsPtMin  = 0.001;
  const double dCutEtaMax  = 1.6;
  const double dJetEtaMax  = 1.;
  const double dJetAreaRef = TMath::Pi() * dJetR * dJetR;

  fastjet::GhostedAreaSpec areaSpc(dCutEtaMax);
  fastjet::JetDefinition   jetsDef(fastjet::antikt_algorithm, dJetR, fastjet::E_scheme, fastjet::Best);

//fastjet::AreaDefinition  areaDef(fastjet::active_area,areaSpc);
  fastjet::AreaDefinition  areaDef(fastjet::active_area_explicit_ghosts,areaSpc);

//fastjet::JetDefinition   bkgsDef(fastjet::kt_algorithm, 0.2, fastjet::BIpt_scheme, fastjet::Best);
//fastjet::AreaDefinition  aBkgDef(fastjet::active_area_explicit_ghosts, areaSpc);

  fastjet::Selector selectJet = fastjet::SelectorAbsEtaMax(dJetEtaMax);
//fastjet::Selector selectRho = fastjet::SelectorAbsEtaMax(dCutEtaMax-0.2);
//fastjet::Selector selecHard = fastjet::SelectorNHardest(2);
//fastjet::Selector selectBkg = selectRho * (!(selecHard));
//fastjet::JetMedianBackgroundEstimator bkgsEstimator(selectBkg, bkgsDef, aBkgDef);
//fastjet::Subtractor                   bkgSubtractor(&bkgsEstimator);

  fastjet::JetDefinition subjDef(fastjet::kt_algorithm, dSjeR, fastjet::E_scheme, fastjet::Best);
//=============================================================================

  std::vector<fastjet::PseudoJet> fjInput;
  const double dMass = TDatabasePDG::Instance()->GetParticle(211)->Mass();
//=============================================================================

  TList *list = new TList();
  TH1D *hJet = new TH1D("hJet", "", 1000, 0., 1000.); hJet->Sumw2(); list->Add(hJet);

  enum                    {  kJet,   kMje,   kDsz,   kIsm,   kZsm,   kDsr, kVar };
  const TString sHist[] = { "aJet", "aMje", "aDsz", "aIsm", "aZsm", "aDsr" };
  const Int_t      nv[] = {   1000,    150,  120,      150,    150,    500 };
  const Double_t dMin[] = {     0.,     0.,   0.,       0.,     0.,     0. };
  const Double_t dMax[] = {  1000.,   150.,  1.2,     150.,    1.5,     5. };

  THnSparseD *hs = new THnSparseD("hs", "", kVar, nv, dMin, dMax); hs->Sumw2();
  for (Int_t i=0; i<kVar; i++) hs->GetAxis(i)->SetName(sHist[i].Data()); list->Add(hs);
//=============================================================================

  HepMC::IO_GenEvent ascii_in(Form("%s/%s.hepmc",sPath.Data(),sFile.Data()), std::ios::in);
  HepMC::GenEvent *evt = ascii_in.read_next_event();

  while (evt) {
    fjInput.resize(0);

    TLorentzVector vPar;
    for (HepMC::GenEvent::particle_const_iterator p=evt->particles_begin(); p!=evt->particles_end(); ++p) if ((*p)->status()==1) {
      vPar.SetPtEtaPhiM((*p)->momentum().perp(), (*p)->momentum().eta(), (*p)->momentum().phi(), dMass);

      if ((TMath::Abs(vPar.Eta())<dCutEtaMax)) {
        fjInput.push_back(fastjet::PseudoJet(vPar.Px(), vPar.Py(), vPar.Pz(), vPar.E()));
      }
    }
//=============================================================================

    fastjet::ClusterSequenceArea clustSeq(fjInput, jetsDef, areaDef);
    std::vector<fastjet::PseudoJet> includJets = clustSeq.inclusive_jets(dJetsPtMin);
//  std::vector<fastjet::PseudoJet> subtedJets = bkgSubtractor(includJets);
    std::vector<fastjet::PseudoJet> selectJets = selectJet(includJets);
//  std::vector<fastjet::PseudoJet> sortedJets = fastjet::sorted_by_pt(selectJets);

    for (int j=0; j<selectJets.size(); j++) {
      double dJet = selectJets[j].pt();

      hJet->Fill(dJet);
//=============================================================================

      fastjet::Filter trimmer(subjDef, fastjet::SelectorPtFractionMin(0.));
      fastjet::PseudoJet trimmdJet = trimmer(selectJets[j]);
      std::vector<fastjet::PseudoJet> trimmdSj = trimmdJet.pieces();

      double d1sj = -1.; int k1sj = -1;
      double d2sj = -1.; int k2sj = -1;
      for (int i=0; i<trimmdSj.size(); i++) {
        double dIsj = trimmdSj[i].pt(); if (dIsj<0.001) continue;

        if (dIsj>d1sj) {
          d2sj = d1sj; k2sj = k1sj;
          d1sj = dIsj; k1sj = i;
        } else if (dIsj>d2sj) {
          d2sj = dIsj; k2sj = i;
        }
      }

      if ((d1sj>0.) && (d2sj>0.)) {
        TLorentzVector v1sj; v1sj.SetPtEtaPhiM(d1sj, trimmdSj[k1sj].eta(), trimmdSj[k1sj].phi(), trimmdSj[k1sj].m());
        TLorentzVector v2sj; v2sj.SetPtEtaPhiM(d2sj, trimmdSj[k2sj].eta(), trimmdSj[k2sj].phi(), trimmdSj[k2sj].m());
        TLorentzVector vIsj = v1sj + v2sj;

        Double_t dIsm = vIsj.M();
        Double_t dMje = selectJets[j].m();
        Double_t dVar[] = { dJet, dMje, (d1sj-d2sj)/dJet, dIsm, dIsm/dMje, v1sj.DeltaR(v2sj)/2./dJetR };

        hs->Fill(dVar);
      }
    }
//=============================================================================

    delete evt;
    ascii_in >> evt;
  }
//=============================================================================

  TString sXsec = sFile; sXsec.ReplaceAll("out", "xsecs");
  TFile *file = TFile::Open(Form("%s/xsecs/%s.root",sPath.Data(),sXsec.Data()), "READ");
  TH1D *hPtHat        = (TH1D*)file->Get("hPtHat");        hPtHat->SetDirectory(0);
  TH1D *hWeightSum    = (TH1D*)file->Get("hWeightSum");    hWeightSum->SetDirectory(0);
  TProfile *hSigmaGen = (TProfile*)file->Get("hSigmaGen"); hSigmaGen->SetDirectory(0);
  file->Close();
//=============================================================================

  file = TFile::Open(Form("%s.root",sFile.Data()), "NEW");
  hPtHat->Write();
  hWeightSum->Write();
  hSigmaGen->Write();
  list->Write();
  file->Close();
//=============================================================================

  cout << "DONE" << endl;
  return 0;
}
コード例 #15
0
ファイル: extractFlowVZERO.C プロジェクト: ktf/AliPhysics
void extractFlowVZERO(Int_t icentr,const char *type,Int_t arm,Float_t pTh,Bool_t isMC,Int_t addbin){
  LoadLib();

  char name[100];
  snprintf(name,100,"AnalysisResults%s.root",type);
  if(!fo) fo = new TFile(name);

  new TCanvas();

  Int_t cMin[] = {0,5,10,20,30,40,50,60,70};
  Int_t cMax[] = {5,10,20,30,40,50,60,70,80};

  if(kNUOcorr){ // Compute correction for NUO in TOF
    compareTPCTOF(icentr,0,arm,pTh,addbin);
//     compareTPCTOF(icentr,1,arm,pTh,addbin);
//     compareTPCTOF(icentr,2,arm,pTh,addbin);
//     compareTPCTOF(icentr,3,arm,pTh,addbin);
//     compareTPCTOF(icentr,4,arm,pTh,addbin);
  }

  TProfile *pAll;
  pAll=extractFlowVZEROsingle(icentr,0,arm,0,pTh,addbin,"all",0,1);
  pAll->SetMarkerStyle(24);
  TProfile *pPiTOF,*pPiTPC,*pPiTPC2;
  pPiTOF=extractFlowVZEROsingle(icentr,1,arm,0,pTh,addbin,"piTOF",1,1);
  pPiTPC=extractFlowVZEROsingle(icentr,1,arm,0,pTh,addbin,"piTPC",0,0);
  pPiTPC2=extractFlowVZEROsingle(icentr,1,arm,0,pTh,addbin,"piTPC2",2,2);
  pPiTPC->Add(pPiTPC2);

  TH1D *hPi = pPiTOF->ProjectionX("hPi");
  hPi->SetLineColor(4);
  hPi->SetMarkerColor(4);
  hPi->SetMarkerStyle(20);
  for(Int_t i=1;i <=hPi->GetNbinsX();i++){
    Float_t x = hPi->GetBinCenter(i);
    if(x < 0.2){
      hPi->SetBinContent(i,0);
      hPi->SetBinError(i,0);
    }
    else if(x < 0.5){
      hPi->SetBinContent(i,pPiTPC->GetBinContent(i));
      hPi->SetBinError(i,pPiTPC->GetBinError(i));      
    }
    else{
      if(kNUOcorr){
	hPi->SetBinContent(i,pPiTOF->GetBinContent(i) + hNUO[0]->GetBinContent(i));
	hPi->SetBinError(i,pPiTOF->GetBinError(i));      
      }
      else{
	hPi->SetBinContent(i,pPiTOF->GetBinContent(i));
	hPi->SetBinError(i,pPiTOF->GetBinError(i));      
      }
    }
  }

  TProfile *pElTOF,*pElTPC,*pElTPC2;
  pElTOF=extractFlowVZEROsingle(icentr,4,arm,0,pTh,addbin,"piTOF",1,1);
  pElTPC=extractFlowVZEROsingle(icentr,4,arm,0,pTh,addbin,"piTPC",0,0);
  pElTPC2=extractFlowVZEROsingle(icentr,4,arm,0,pTh,addbin,"piTPC2",2,2);
  pElTPC->Add(pElTPC2);

  TH1D *hEl = pElTOF->ProjectionX("hEl");
  hEl->SetLineColor(6);
  hEl->SetMarkerColor(6);
  hEl->SetMarkerStyle(20);
  for(Int_t i=1;i <=hEl->GetNbinsX();i++){
    Float_t x = hEl->GetBinCenter(i);
    if(x < 0.2){
      hEl->SetBinContent(i,0);
      hEl->SetBinError(i,0);
    }
    else if(x < 0.3){
      hEl->SetBinContent(i,pElTPC->GetBinContent(i));
      hEl->SetBinError(i,pElTPC->GetBinError(i));      
    }
    else{
      if(kNUOcorr){
	hEl->SetBinContent(i,pElTOF->GetBinContent(i) + hNUO[0]->GetBinContent(i));
	hEl->SetBinError(i,pElTOF->GetBinError(i));      
      }
      else{
	hEl->SetBinContent(i,pElTOF->GetBinContent(i));
	hEl->SetBinError(i,pElTOF->GetBinError(i));      
      }
    }
  }

  TProfile *pKTOF,*pKTPC,*pKTPC2;
  pKTOF=extractFlowVZEROsingle(icentr,2,arm,0,pTh,addbin,"kaTOF",1,1);
  pKTPC=extractFlowVZEROsingle(icentr,2,arm,0,pTh,addbin,"kaTPC",0,0);
  pKTPC2=extractFlowVZEROsingle(icentr,2,arm,0,pTh,addbin,"kaTPC2",2,2);
  pKTPC->Add(pKTPC2);

  TH1D *hK = pKTOF->ProjectionX("hKa");
  hK->SetLineColor(1);
  hK->SetMarkerColor(1);
  hK->SetMarkerStyle(21);
  for(Int_t i=1;i <=hK->GetNbinsX();i++){
    Float_t x = hK->GetBinCenter(i);
    if(x < 0.25){
      hK->SetBinContent(i,0);
      hK->SetBinError(i,0);
    }
    else if(x < 0.45){
      hK->SetBinContent(i,pKTPC->GetBinContent(i));
      hK->SetBinError(i,pKTPC->GetBinError(i));      
    }
    else{
      if(kNUOcorr){
	hK->SetBinContent(i,pKTOF->GetBinContent(i) + hNUO[0]->GetBinContent(i));
	hK->SetBinError(i,pKTOF->GetBinError(i));      
      }
      else{
	hK->SetBinContent(i,pKTOF->GetBinContent(i));
	hK->SetBinError(i,pKTOF->GetBinError(i));      
      }
    }
  }

  TProfile *pPrTOF,*pPrTOF2,*pPrTPC,*pPrTPC2;
  pPrTOF=extractFlowVZEROsingle(icentr,3,arm,0,pTh,addbin,"prTOF",1,1,-1,-1);
  pPrTOF2=extractFlowVZEROsingle(icentr,3,arm,0,pTh,addbin,"prTOF2",1,1,-1,1);
  pPrTPC=extractFlowVZEROsingle(icentr,3,arm,0,pTh,addbin,"prTPC",0,0,-1,-1);
  pPrTPC2=extractFlowVZEROsingle(icentr,3,arm,0,pTh,addbin,"prTPC2",2,2,-1,-1);
  pPrTPC->Add(pPrTPC2);

  TH1D *hPr = pPrTOF->ProjectionX("hPr");
  hPr->SetLineColor(2);
  hPr->SetMarkerColor(2);
  hPr->SetMarkerStyle(22);
  for(Int_t i=1;i <=hPr->GetNbinsX();i++){
    Float_t x = hPr->GetBinCenter(i);
    if(x < 0.3){
      hPr->SetBinContent(i,0);
      hPr->SetBinError(i,0);
    }
    else if(x < 1.0){
      hPr->SetBinContent(i,pPrTPC->GetBinContent(i));
      hPr->SetBinError(i,pPrTPC->GetBinError(i));      
    }
    else{
      if(x < 3){
	if(kNUOcorr){
	  hPr->SetBinContent(i,pPrTOF->GetBinContent(i) + hNUO[0]->GetBinContent(i));
	  hPr->SetBinError(i,pPrTOF->GetBinError(i));      
	}
	else{
	  hPr->SetBinContent(i,pPrTOF->GetBinContent(i));
	  hPr->SetBinError(i,pPrTOF->GetBinError(i));      
	}
      }
      else{
	if(kNUOcorr){
	  hPr->SetBinContent(i,pPrTOF2->GetBinContent(i) + hNUO[0]->GetBinContent(i));
	  hPr->SetBinError(i,pPrTOF2->GetBinError(i));      
	}
	else{
	  hPr->SetBinContent(i,pPrTOF2->GetBinContent(i));
	  hPr->SetBinError(i,pPrTOF2->GetBinError(i));      
	}
      }
    }
  }
  
  pAll->Draw();
  hPi->Draw("SAME");
  hK->Draw("SAME");
  hPr->Draw("SAME");


  char name[100];


  // PID correction
  if(kPIDcorr){
    TFile *fPidTOF = new TFile("$ALICE_ROOT/PWGCF/FLOW/other/BayesianPIDcontTPCTOF.root");
    TFile *fPidTPC = new TFile("$ALICE_ROOT/PWGCF/FLOW/other/BayesianPIDcontTPC.root");
    // pi histos
    sprintf(name,"Pi_IDas_Picentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPiPi=(TH1D *) fPidTOF->Get(name);
    sprintf(name,"Pi_IDas_Elcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPiEl=(TH1D *) fPidTOF->Get(name);
    sprintf(name,"Pi_IDas_Kacentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPiKa=(TH1D *) fPidTOF->Get(name);
    sprintf(name,"Pi_IDas_Prcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPiPr=(TH1D *) fPidTOF->Get(name);
    TH1D *hPidAll = new TH1D(*hPidPiPi);
    hPidAll->Add(hPidPiKa);
    hPidAll->Add(hPidPiPr);
    hPidAll->Add(hPidPiEl);
    hPidPiPi->Divide(hPidAll);
    hPidPiKa->Divide(hPidAll);
    hPidPiPr->Divide(hPidAll);
    hPidPiEl->Divide(hPidAll);

    sprintf(name,"Pi_IDas_Picentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPiPiTPC=(TH1D *) fPidTPC->Get(name);
    sprintf(name,"Pi_IDas_Elcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPiElTPC=(TH1D *) fPidTPC->Get(name);
    sprintf(name,"Pi_IDas_Kacentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPiKaTPC=(TH1D *) fPidTPC->Get(name);
    sprintf(name,"Pi_IDas_Prcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPiPrTPC=(TH1D *) fPidTPC->Get(name);
    hPidAll->Reset();
    hPidAll->Add(hPidPiPiTPC);
    hPidAll->Add(hPidPiKaTPC);
    hPidAll->Add(hPidPiPrTPC);
    hPidAll->Add(hPidPiElTPC);
    hPidPiPiTPC->Divide(hPidAll);
    hPidPiKaTPC->Divide(hPidAll);
    hPidPiPrTPC->Divide(hPidAll);
    hPidPiElTPC->Divide(hPidAll);

    // K histos
    sprintf(name,"Ka_IDas_Picentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidKaPi=(TH1D *) fPidTOF->Get(name);
    sprintf(name,"Ka_IDas_Elcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidKaEl=(TH1D *) fPidTOF->Get(name);
    sprintf(name,"Ka_IDas_Kacentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidKaKa=(TH1D *) fPidTOF->Get(name);
    sprintf(name,"Ka_IDas_Prcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidKaPr=(TH1D *) fPidTOF->Get(name);
    hPidAll->Reset();
    hPidAll->Add(hPidKaPi);
    hPidAll->Add(hPidKaKa);
    hPidAll->Add(hPidKaPr);
    hPidAll->Add(hPidKaEl);
    hPidKaPi->Divide(hPidAll);
    hPidKaKa->Divide(hPidAll);
    hPidKaPr->Divide(hPidAll);
    hPidKaEl->Divide(hPidAll);

    sprintf(name,"Ka_IDas_Picentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidKaPiTPC=(TH1D *) fPidTPC->Get(name);
    sprintf(name,"Ka_IDas_Elcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidKaElTPC=(TH1D *) fPidTPC->Get(name);
    sprintf(name,"Ka_IDas_Kacentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidKaKaTPC=(TH1D *) fPidTPC->Get(name);
    sprintf(name,"Ka_IDas_Prcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidKaPrTPC=(TH1D *) fPidTPC->Get(name);
    hPidAll->Reset();
    hPidAll->Add(hPidKaPiTPC);
    hPidAll->Add(hPidKaKaTPC);
    hPidAll->Add(hPidKaPrTPC);
    hPidAll->Add(hPidKaElTPC);
    hPidKaPiTPC->Divide(hPidAll);
    hPidKaKaTPC->Divide(hPidAll);
    hPidKaPrTPC->Divide(hPidAll);
    hPidKaElTPC->Divide(hPidAll);

    // pr histos
    sprintf(name,"Pr_IDas_Picentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPrPi=(TH1D *) fPidTOF->Get(name);
    sprintf(name,"Pr_IDas_Elcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPrEl=(TH1D *) fPidTOF->Get(name);
    sprintf(name,"Pr_IDas_Kacentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPrKa=(TH1D *) fPidTOF->Get(name);
    sprintf(name,"Pr_IDas_Prcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPrPr=(TH1D *) fPidTOF->Get(name);
    hPidAll->Reset();
    hPidAll->Add(hPidPrPi);
    hPidAll->Add(hPidPrKa);
    hPidAll->Add(hPidPrPr);
    hPidAll->Add(hPidPrEl);
    hPidPrPi->Divide(hPidAll);
    hPidPrKa->Divide(hPidAll);
    hPidPrPr->Divide(hPidAll);
    hPidPrEl->Divide(hPidAll);

    sprintf(name,"Pr_IDas_Picentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPrPiTPC=(TH1D *) fPidTPC->Get(name);
    sprintf(name,"Pr_IDas_Elcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPrElTPC=(TH1D *) fPidTPC->Get(name);
    sprintf(name,"Pr_IDas_Kacentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPrKaTPC=(TH1D *) fPidTPC->Get(name);
    sprintf(name,"Pr_IDas_Prcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPrPrTPC=(TH1D *) fPidTPC->Get(name);
    hPidAll->Reset();
    hPidAll->Add(hPidPrPiTPC);
    hPidAll->Add(hPidPrKaTPC);
    hPidAll->Add(hPidPrPrTPC);
    hPidAll->Add(hPidPrElTPC);
    hPidPrPiTPC->Divide(hPidAll);
    hPidPrKaTPC->Divide(hPidAll);
    hPidPrPrTPC->Divide(hPidAll);
    hPidPrElTPC->Divide(hPidAll);
 
    for(Int_t k=1;k <=hPi->GetNbinsX();k++){
      Float_t pt = hPi->GetBinCenter(k);
      Float_t xPi=hPi->GetBinContent(k)*hPidPiPi->Interpolate(pt) + hK->GetBinContent(k)*hPidPiKa->Interpolate(pt) + hPr->GetBinContent(k)*hPidPiPr->Interpolate(pt) + hEl->GetBinContent(k)*hPidPiEl->Interpolate(pt);
      if(pt < 0.5)
	xPi=hPi->GetBinContent(k)*hPidPiPiTPC->Interpolate(pt) + hK->GetBinContent(k)*hPidPiKaTPC->Interpolate(pt) + hPr->GetBinContent(k)*hPidPiPrTPC->Interpolate(pt) + hEl->GetBinContent(k)*hPidPiElTPC->Interpolate(pt);
      Float_t xKa=hPi->GetBinContent(k)*hPidKaPi->Interpolate(pt) + hK->GetBinContent(k)*hPidKaKa->Interpolate(pt) + hPr->GetBinContent(k)*hPidKaPr->Interpolate(pt) + hEl->GetBinContent(k)*hPidKaEl->Interpolate(pt);
      if(pt < 0.45)
	xKa=hPi->GetBinContent(k)*hPidKaPiTPC->Interpolate(pt) + hK->GetBinContent(k)*hPidKaKaTPC->Interpolate(pt) + hPr->GetBinContent(k)*hPidKaPrTPC->Interpolate(pt) + hEl->GetBinContent(k)*hPidKaElTPC->Interpolate(pt);
      Float_t xPr=hPi->GetBinContent(k)*hPidPrPi->Interpolate(pt) + hK->GetBinContent(k)*hPidPrKa->Interpolate(pt) + hPr->GetBinContent(k)*hPidPrPr->Interpolate(pt) + hEl->GetBinContent(k)*hPidPrEl->Interpolate(pt);
      if(pt < 1)
	xPr=hPi->GetBinContent(k)*hPidPrPiTPC->Interpolate(pt) + hK->GetBinContent(k)*hPidPrKaTPC->Interpolate(pt) + hPr->GetBinContent(k)*hPidPrPrTPC->Interpolate(pt) + hEl->GetBinContent(k)*hPidPrElTPC->Interpolate(pt);

      hPi->SetBinContent(k,hPi->GetBinContent(k)*2 - xPi);
      hK->SetBinContent(k,hK->GetBinContent(k)*2 - xKa);
      hPr->SetBinContent(k,hPr->GetBinContent(k)*2 - xPr);    
    }
  }


  // antiproton Feed down
  TProfile *pFromLambda = extractFlowVZEROsingle(icentr,11,arm,0,pTh,addbin,"pFromLambda",1,1);
  TProfile *piFromK = extractFlowVZEROsingle(icentr,12,arm,0,pTh,addbin,"piFromK",1,1,1,1);
  TProfile *pFromLambda2 = extractFlowVZEROsingle(icentr,11,arm,0,0.6,addbin,"pFromLambdanoPID",0,1);
  TProfile *piFromK2 = extractFlowVZEROsingle(icentr,12,arm,0,0.6,addbin,"piFromKnoPID",0,1);
  TProfile *piFromK3 = extractFlowVZEROsingle(icentr,12,arm,0,0.6,addbin,"piFromKnoPIDtof",1,1);

  TH1D *hFeedSyst = NULL;

  if(kFEEDcorr){
    hFeedSyst = new TH1D(*hPr);
    hFeedSyst->SetName("hFeedSyst");
    hFeedSyst->Reset();
    for(Int_t k=1;k <=hPr->GetNbinsX();k++){
      Float_t contam = 3.23174e-01 * TMath::Exp(- 9.46743e-01 *  hPr->GetBinCenter(k));
      Float_t corr = contam * pFromLambda->GetBinContent(k)/(1-contam);
      Float_t corrErr = contam * pFromLambda->GetBinError(k)/(1-contam);
      Float_t value = hPr->GetBinContent(k)/(1-contam) - corr;
      Float_t valueErr = hPr->GetBinError(k)/(1-contam);

      hFeedSyst->SetBinContent(k,hPr->GetBinContent(k) - value);
      hFeedSyst->SetBinContent(k,sqrt(corrErr*corrErr + valueErr*valueErr - hPr->GetBinError(k)*hPr->GetBinError(k)));

      hPr->SetBinContent(k,value);
      hPr->SetBinError(k,sqrt(corrErr*corrErr + valueErr*valueErr));

    }
    hFeedSyst->Divide(hPr);
  }
    
  // write output
  snprintf(name,100,"results%03i-%03iv%i_pTh%3.1f%s.root",cMin[icentr],cMax[icentr+addbin],arm,pTh,type);
  TFile *fout = new TFile(name,"RECREATE");
  pAll->ProjectionX()->Write();
  hPi->Write();
  hK->Write();
  hPr->Write();
  if(isMC){
    TH1D *pTmp = extractFlowVZEROsingle(icentr,0,arm,1,pTh,addbin,"allMC",1,1,-1,1)->ProjectionX();
    pTmp->SetLineColor(6);
    pTmp->SetMarkerColor(6);
    pTmp->SetMarkerStyle(24);
    pTmp->Write();
    pTmp = extractFlowVZEROsingle(icentr,1,arm,1,pTh,addbin,"piMC",1,1,-1,1)->ProjectionX();
    pTmp->SetLineColor(4);
    pTmp->SetMarkerColor(4);
    pTmp->SetMarkerStyle(24);
    pTmp->Write();
    pTmp = extractFlowVZEROsingle(icentr,2,arm,1,pTh,addbin,"kaMC",1,1,-1,1)->ProjectionX();
    pTmp->SetLineColor(1);
    pTmp->SetMarkerColor(1);
    pTmp->SetMarkerStyle(25);
    pTmp->Write();
    pTmp = extractFlowVZEROsingle(icentr,3,arm,1,pTh,addbin,"prMC",1,1,-1,-1)->ProjectionX();
    pTmp->SetLineColor(2);
    pTmp->SetMarkerColor(2);
    pTmp->SetMarkerStyle(26);
    pTmp->Write();
  }
  extractFlowVZEROsingle(icentr,2,arm,0,pTh,addbin,"kProf")->Write();
  extractFlowVZEROsingle(icentr,9,arm,0,pTh,addbin,"ks",0,1,1,1)->Write();
  extractFlowVZEROsingle(icentr,9,arm,0,pTh,addbin,"ksMy",0,1,-1,-1)->Write();
  extractFlowVZEROsingle(icentr,10,arm,0,pTh,addbin,"lambda")->Write();
  pFromLambda->Write();
  piFromK->Write();
  pFromLambda2->Write();
  piFromK2->Write();
  piFromK3->Write();
  if(hFeedSyst) hFeedSyst->Write();
  fout->Close();
}
コード例 #16
0
// ****************************************************************
//XXX: main
int main(int argc, char* argv[])
{
  //
  // **** May 20 2010 update ****
  // Usage: CreateEcalTimingCalibsEE fileWithTree options...
  //

  using namespace std;
  // Ao dependent timing corrections
  timeCorrectionEE_ = new TF1("timeCorrectionEE_","pol4(0)",0,1.2);
  //coefficients obtained in the interval (0, 1.5) from Low eta region < 2.2, run 144011
  timeCorrectionEE_->SetParameters(-0.461192,0.0876435,-0.234752,0.143774,-0.051990);

  // For selection cuts
  string inBxs, inOrbits, inTrig, inTTrig, inLumi, inRuns;
  float avgTimeMin, avgTimeMax;
  float minAmpEB, minAmpEE;
  float maxE1E9, maxSwissCrossNoise;  // EB only, no spikes seen in EE
  float maxHitTimeEE, minHitTimeEE;
  // init to sensible defaults
  avgTimeMin = -1; // in ns
  avgTimeMax = 1; // in ns
  minAmpEB = 5; // GeV
  minAmpEE = 5; // GeV
  maxHitTimeEE = 15; // ns
  minHitTimeEE = -15; // ns
  maxE1E9 = 0.95; // EB only
  maxSwissCrossNoise = 0.95; // EB only
  inBxs = "-1";
  inOrbits = "-1";
  inTrig = "-1";
  inTTrig = "-1";
  inLumi = "-1";
  inRuns = "-1";

  char* infile = argv[1];
  if (!infile)
  {
    cout << " No input file specified !" << endl;
    return -1;
  }

  //TODO: Replace this with the parseArguments function from the pi0 binary
  std::string stringGenericOption    = "--";
  for (int i=1 ; i<argc ; i++) {
    if (argv[i] == std::string("-bxs") && argc>i+1) inBxs = std::string(argv[i+1]);
    if (argv[i] == std::string("-orbits") && argc>i+1) inOrbits = std::string(argv[i+1]);
    if (argv[i] == std::string("-trig") && argc>i+1) inTrig = std::string(argv[i+1]);
    if (argv[i] == std::string("-ttrig") && argc>i+1) inTTrig = std::string(argv[i+1]);
    if (argv[i] == std::string("-lumi") && argc>i+1) inLumi = std::string(argv[i+1]);
    if (argv[i] == std::string("-runs") && argc>i+1) inRuns = std::string(argv[i+1]);
    if (argv[i] == std::string("-ebampmin") && argc>i+1) minAmpEB = atof(argv[i+1]);
    if (argv[i] == std::string("-eeampmin") && argc>i+1) minAmpEE = atof(argv[i+1]);
    if (argv[i] == std::string("-e1e9max") && argc>i+1) maxE1E9 = atof(argv[i+1]);
    if (argv[i] == std::string("-swisskmax") && argc>i+1) maxSwissCrossNoise = atof(argv[i+1]);
    if (argv[i] == std::string("-avgtimemin") && argc>i+1) avgTimeMin = atof(argv[i+1]);
    if (argv[i] == std::string("-avgtimemax") && argc>i+1) avgTimeMax = atof(argv[i+1]);
    if (argv[i] == std::string("-eehittimemax") && argc>i+1) maxHitTimeEE = atof(argv[i+1]);
    if (argv[i] == std::string("-eehittimemin") && argc>i+1) minHitTimeEE = atof(argv[i+1]);
    // handle here the case of multiple arguments for input files
    if (argv[i] == std::string("--i"))// && argc>i+1)
    {
      for (int u=i+1; u<argc; u++)
      {
        if ( 0==std::string(argv[u]).find( stringGenericOption ) )
        {
          if ( 0==listOfFiles_.size())  {std::cout << "no input files listed" << std::cout;}
          else  {std::cout << "no more files listed, found: " << argv[u] << std::cout;}
          break;
        }
        else
        {
          listOfFiles_.push_back(argv[u]);
          i++;
        }
      }// loop on arguments following --i
      continue;
    }//end 'if input files'

  }
  // Open the input files
  if (listOfFiles_.size()==0){
    std::cout << "\tno input file found" << std::endl;
    return(1);
  }
  else{
    std::cout << "\tfound " << listOfFiles_.size() << " input files: " << std::endl;
    for(std::vector<std::string>::const_iterator  file_itr=listOfFiles_.begin(); file_itr!=listOfFiles_.end(); file_itr++){
      std::cout << "\t" << (*file_itr) << std::endl;
    }
  }
  // Tree construction
  TChain* chain = new TChain ("EcalTimeAnalysis") ;
  std::vector<std::string>::const_iterator file_itr;
  for(file_itr=listOfFiles_.begin(); file_itr!=listOfFiles_.end(); file_itr++){
    chain->Add( (*file_itr).c_str() );
  }


  cout << "Running with options: "
    << "avgTimeMin: " << avgTimeMin << " avgTimeMax: " << avgTimeMax
    << " minAmpEB: " << minAmpEB << " minAmpEE: " << minAmpEE
    << " maxHitTimeEE: " << maxHitTimeEE << " minHitTimeEE: " << minHitTimeEE
    << " inTrig: " << inTrig << " inTTrig: " << inTTrig << " inLumi: " << inLumi 
    << " inBxs: " << inBxs << " inRuns: " << inRuns << " inOrbits: " << inOrbits
    << endl;

  // Ignore warnings
  gErrorIgnoreLevel = 2001;

  setBranchAddresses(chain,treeVars_);

  // Generate all the vectors for skipping selections
  std::vector<std::vector<double> > bxIncludeVector;
  std::vector<std::vector<double> > bxExcludeVector;
  std::vector<std::vector<double> > orbitIncludeVector;
  std::vector<std::vector<double> > orbitExcludeVector;
  std::vector<std::vector<double> > trigIncludeVector;
  std::vector<std::vector<double> > trigExcludeVector;
  std::vector<std::vector<double> > ttrigIncludeVector;
  std::vector<std::vector<double> > ttrigExcludeVector;
  std::vector<std::vector<double> > lumiIncludeVector;
  std::vector<std::vector<double> > lumiExcludeVector;
  std::vector<std::vector<double> > runIncludeVector;
  std::vector<std::vector<double> > runExcludeVector;
  //recall: string inBxs, inOrbits, inTrig, inTTrig, inLumi, inRuns;
  genIncludeExcludeVectors(inBxs,bxIncludeVector,bxExcludeVector);
  genIncludeExcludeVectors(inOrbits,orbitIncludeVector,orbitExcludeVector);
  genIncludeExcludeVectors(inTrig,trigIncludeVector,trigExcludeVector);
  genIncludeExcludeVectors(inTTrig,ttrigIncludeVector,ttrigExcludeVector);
  genIncludeExcludeVectors(inLumi,lumiIncludeVector,lumiExcludeVector);
  genIncludeExcludeVectors(inRuns,runIncludeVector,runExcludeVector);

  // Open output file and book hists
  string fileNameBeg = "timingCalibsEE";
  string rootFilename = fileNameBeg+".root";
  TFile* outfile = new TFile(rootFilename.c_str(),"RECREATE");
  outfile->cd();

  TH1F* calibHistEE = new TH1F("timingCalibsEE","timingCalibs EE [ns]",2000,-100,100);
  TH1F* calibErrorHistEE = new TH1F("timingCalibErrorEE","timingCalibError EE [ns]",500,0,5);
  calibHistEE->Sumw2();
  calibErrorHistEE->Sumw2();

  TH2F* calibsVsErrors = new TH2F("timingCalibsAndErrors","TimingCalibs vs. errors [ns]",500,0,5,100,0,10);
  calibsVsErrors->Sumw2();

  //TH2F* calibMapEE = new TH2F("calibMapEE","time calib map EE",360,1,361,170,-86,86);
  //TH2F* calibMapEEFlip = new TH2F("calibMapEEFlip","time calib map EE",170,-86,86,360,1,361);
  //TH2F* calibMapEEPhase = new TH2F("calibMapEEPhase","time calib map EE (phase of Tmax)",360,1,361,170,-86,86);
  
  //TH2F* calibMapEtaAvgEE = new TH2F("calibMapEtaAvgEE","time calibs raw eta avg map EE",360,1,361,170,-86,86);
  //TH1F* calibHistEtaAvgEE = new TH1F("timingCalibsEtaAvgEE","EtaAvgTimingCalibs EE [ns]",2000,-100,100);

  TH2F* hitsPerCryMapEEM = new TH2F("hitsPerCryMapEEM","Hits per cry EEM;ix;iy",100,1,101,100,1,101);
  TH2F* hitsPerCryMapEEP = new TH2F("hitsPerCryMapEEP","Hits per cry EEP;ix;iy",100,1,101,100,1,101);
  TH1F* hitsPerCryHistEEM = new TH1F("hitsPerCryHistEEM","Hits per cry EEM;hashedIndex",14648,0,14648);
  TH1F* hitsPerCryHistEEP = new TH1F("hitsPerCryHistEEP","Hits per cry EEP;hashedIndex",14648,0,14648);
  //TH1C* eventsEEMHist = new TH1C("numEventsEEM","Number of events, EEM",100,0,100);
  //TH1C* eventsEEPHist = new TH1C("numEventsEEP","Number of events, EEP",100,0,100);
  TProfile* ampProfileEEM = new TProfile("ampProfileEEM","Amp. profile EEM;hashedIndex",14648,0,14648);
  TProfile* ampProfileEEP = new TProfile("ampProfileEEP","Amp. profile EEP;hashedIndex",14648,0,14648);
  TProfile2D* ampProfileMapEEP = new TProfile2D("ampProfileMapEEP","Amp. profile EEP;ix;iy",100,1,101,100,1,101);
  TProfile2D* ampProfileMapEEM = new TProfile2D("ampProfileMapEEM","Amp. profile EEM;ix;iy",100,1,101,100,1,101);

  //TH1F* eventsEEHist = new TH1F("numEventsEE","Number of events, EE",100,0,100);
  //TH1F* calibSigmaHist = new TH1F("timingSpreadEE","Crystal timing spread [ns]",1000,-5,5);

  TH1F* sigmaHistEE = new TH1F("sigmaCalibsEE"," Sigma of calib distributions EE [ns]",100,0,1);

  //TH1F* chiSquaredEachEventHist = new TH1F("chi2eachEvent","Chi2 of each event",500,0,500);
  //TH2F* chiSquaredVsAmpEachEventHist = new TH2F("chi2VsAmpEachEvent","Chi2 vs. amplitude of each event",500,0,500,750,0,750);
  //TH2F* chiSquaredHighMap = new TH2F("chi2HighMap","Channels with event #Chi^{2} > 100",360,1,361,170,-86,86);
  //TH1F* chiSquaredTotalHist = new TH1F("chi2Total","Total chi2 of all events in each crystal",500,0,500);
  //TH1F* chiSquaredSingleOverTotalHist = new TH1F("chi2SingleOverTotal","Chi2 of each event over total chi2",100,0,1);
  //TH1F* ampEachEventHist = new TH1F("energyEachEvent","Energy of all events [GeV]",1000,0,10);
  //TH1F* numPointsErasedHist = new TH1F("numPointsErased","Number of points erased per crystal",25,0,25);
  
  //TProfile2D* myAmpProfile = (TProfile2D*)EBampProfile->Clone();
  //myAmpProfile->Write();
  TH1F* expectedStatPresHistEEM = new TH1F("expectedStatPresEEM","Avg. expected statistical precision EEM [ns], all crys",200,0,2);
  TH2F* expectedStatPresVsObservedMeanErrHistEEM = new TH2F("expectedStatPresVsObsEEM","Expected stat. pres. vs. obs. error on mean each event EEM [ns]",200,0,2,200,0,2);
  TH1F* expectedStatPresEachEventHistEEM = new TH1F("expectedStatPresSingleEventEEM","Expected stat. pres. each event EEM [ns]",200,0,2);
  TH1F* expectedStatPresHistEEP = new TH1F("expectedStatPresEEP","Avg. expected statistical precision EEP [ns], all crys",200,0,2);
  TH2F* expectedStatPresVsObservedMeanErrHistEEP = new TH2F("expectedStatPresVsObsEEP","Expected stat. pres. vs. obs. error on mean each event [ns] EEP",200,0,2,200,0,2);
  TH1F* expectedStatPresEachEventHistEEP = new TH1F("expectedStatPresSingleEventEEP","Expected stat. pres. each event EEP [ns]",200,0,2);
  
  TH2F* errorOnMeanVsNumEvtsHist = new TH2F("errorOnMeanVsNumEvts","Error_on_mean vs. number of events",50,0,50,200,0,2);
  errorOnMeanVsNumEvtsHist->Sumw2();
  
  TH1F* calibHistEEM = new TH1F("timingCalibsEEM","timingCalibs EEM [ns]",500,-25,25);
  TH1F* calibHistEEP = new TH1F("timingCalibsEEP","timingCalibs EEP [ns]",500,-25,25);
  TH1F* calibErrorHistEEM = new TH1F("calibErrorEEM","timingCalibError EEM [ns]",250,0,5);
  TH1F* calibErrorHistEEP = new TH1F("calibErrorEEP","timingCalibError EEP [ns]",250,0,5);
  calibHistEEM->Sumw2();
  calibHistEEP->Sumw2();
  calibErrorHistEEM->Sumw2();
  calibErrorHistEEP->Sumw2();

  TH2F* calibMapEEM = new TH2F("calibMapEEM","time calib map EEM",100,1,101,100,1,101);
  TH2F* calibMapEEP = new TH2F("calibMapEEP","time calib map EEP",100,1,101,100,1,101);
  calibMapEEM->Sumw2();
  calibMapEEP->Sumw2();

  TH2F* sigmaMapEEM = new TH2F("sigmaMapEEM","Sigma of time calib map EEM [ns];ix;iy",100,1.,101.,100,1,101);
  TH2F* sigmaMapEEP = new TH2F("sigmaMapEEP","Sigma of time calib map EEP [ns];ix;iy",100,1.,101.,100,1,101);
  TH2F* calibErrorMapEEM = new TH2F("calibErrorMapEEM","Error of time calib map EEM [ns];ix;iy",100,1.,101.,100,1,101);
  TH2F* calibErrorMapEEP = new TH2F("calibErrorMapEEP","Error of time calib map EEP [ns];ix;iy",100,1.,101.,100,1,101);

  TDirectory* cryDirEEP = gDirectory->mkdir("crystalTimingHistsEEP");
  cryDirEEP->cd();
  TH1C* cryTimingHistsEEP[100][100]; // [0][0] = ix 1, iy 1
  for(int x=0; x < 100; ++x)
  {
    for(int y=0; y < 100; ++y)
    {
      if(!EEDetId::validDetId(x+1,y+1,1))
        continue;
      string histname = "EEP_cryTiming_ix";
      histname+=intToString(x+1);
      histname+="_iy";
      histname+=intToString(y+1);
      cryTimingHistsEEP[x][y] = new TH1C(histname.c_str(),histname.c_str(),660,-33,33);
      cryTimingHistsEEP[x][y]->Sumw2();
    }
  }
  outfile->cd();
  TDirectory* cryDirEEM = gDirectory->mkdir("crystalTimingHistsEEM");
  cryDirEEM->cd();
  TH1C* cryTimingHistsEEM[100][100]; // [0][0] = ix 1, iy 1
  for(int x=0; x < 100; ++x)
  {
    for(int y=0; y < 100; ++y)
    {
      if(!EEDetId::validDetId(x+1,y+1,-1))
        continue;
      string histname = "EEM_cryTiming_ix";
      histname+=intToString(x+1);
      histname+="_iy";
      histname+=intToString(y+1);
      cryTimingHistsEEM[x][y] = new TH1C(histname.c_str(),histname.c_str(),660,-33,33);
      cryTimingHistsEEM[x][y]->Sumw2();
    }
  }
  outfile->cd();
  
  cout << "Making calibs..." << endl;

  CrystalCalibration* eeCryCalibs[14648];
  //XXX: Making calibs with weighted/unweighted mean
  for(int i=0; i < 14648; ++i)
    eeCryCalibs[i] = new CrystalCalibration(); //use weighted mean!
    //eeCryCalibs[i] = new CrystalCalibration(false); //don't use weighted mean!

  cout << "Looping over TTree...";

  // Loop over the TTree
  int numEventsUsed = 0;
  int nEntries = chain->GetEntries();
  cout << "Begin loop over TTree." << endl;

  for(int entry = 0; entry < nEntries; ++entry)
  {
    chain->GetEntry(entry);

    // Loop once to calculate average event time
    float sumTime = 0;
    int numCrysEE = 0;
    for(int bCluster=0; bCluster < treeVars_.nClusters; bCluster++)
    {
      if(treeVars_.xtalInBCIEta[bCluster][0] != -999999) continue; // skip EB clusters
      for(int cryInBC=0; cryInBC < treeVars_.nXtalsInCluster[bCluster]; cryInBC++)
      {
        sumTime += treeVars_.xtalInBCTime[bCluster][cryInBC];
        numCrysEE++;
      }
    }
    //debug
    //cout << "Number of EE crys in event: " << numEEcrys << endl;

    //XXX: Event cuts
    if(sumTime/numCrysEE > avgTimeMax || sumTime/numCrysEE < avgTimeMin)
    {
      //cout << "Average event time: " << sumTime/numCrysEE  << " so event rejected." << endl;
      continue;
    }
    // check BX, orbit, lumi, run, L1 tech/phys triggers
    bool keepEvent = includeEvent(treeVars_.bx,bxIncludeVector,bxExcludeVector)
      && includeEvent(treeVars_.orbit,orbitIncludeVector,orbitExcludeVector)
      && includeEvent(treeVars_.lumiSection,lumiIncludeVector,lumiExcludeVector)
      && includeEvent(treeVars_.runId,runIncludeVector,runExcludeVector)
      && includeEvent(treeVars_.l1ActiveTriggers,
          treeVars_.l1NActiveTriggers,trigIncludeVector,trigExcludeVector)
      && includeEvent(treeVars_.l1ActiveTechTriggers,
          treeVars_.l1NActiveTechTriggers,ttrigIncludeVector,ttrigExcludeVector);
    if(!keepEvent)
      continue;
      
    numEventsUsed++;

    // Loop over the EE crys and fill the map
    for(int bCluster=0; bCluster < treeVars_.nClusters; bCluster++)
    {
      if(treeVars_.xtalInBCIEta[bCluster][0] != -999999) continue; // skip EB clusters
      for(int cryInBC=0; cryInBC < treeVars_.nXtalsInCluster[bCluster]; cryInBC++)
      {
        int hashedIndex = treeVars_.xtalInBCHashedIndex[bCluster][cryInBC];
        float cryTime = treeVars_.xtalInBCTime[bCluster][cryInBC];
        float cryTimeError = treeVars_.xtalInBCTimeErr[bCluster][cryInBC];
        float cryAmp = treeVars_.xtalInBCAmplitudeADC[bCluster][cryInBC];
	float Ao = cryAmp/sigmaNoiseEE;
	float AoLog = log10(Ao/25);

        EEDetId det = EEDetId::unhashIndex(hashedIndex);
        if(det==EEDetId()) // make sure DetId is valid
          continue;

        int ix = det.ix();
        int iy = det.iy();

        //XXX: RecHit cuts
        bool keepHit = cryAmp >= minAmpEE
          && cryTime > minHitTimeEE
          && cryTime < maxHitTimeEE
	  && AoLog > 0
          && AoLog < 1.2;
        if(!keepHit)
          continue;

        //cout << "STUPID DEBUG: " << hashedIndex << " cryTime: " << cryTime << " cryTimeError: " << cryTimeError << " cryAmp: " << cryAmp << endl;

	// Timing correction to take out the energy dependence if log10(ampliOverSigOfThis/25)
        // is between 0 and 1.2 (about 1 and 13 GeV)
	// amplitude dependent timing corrections
        float timing = cryTime - timeCorrectionEE_->Eval(AoLog);
        //FIXME
        cryTimeError = 1;
        eeCryCalibs[hashedIndex]->insertEvent(cryAmp,timing,cryTimeError,false);

        //SIC Use when we don't have time_error available
        //eeCryCalibs[hashedIndex]->insertEvent(cryAmp,cryTime,35/(cryAmp/1.2),false);
        if(det.zside() < 0)
        {
          ampProfileEEM->Fill(hashedIndex,cryAmp);
          ampProfileMapEEM->Fill(ix,iy,cryAmp);
        }
        else
        {
          ampProfileEEP->Fill(hashedIndex,cryAmp);
          ampProfileMapEEP->Fill(ix,iy,cryAmp);
        }
      }
    }
  }

  //create output text file
  ofstream fileStream;
  string fileName = fileNameBeg+".calibs.txt";
  fileStream.open(fileName.c_str());
  if(!fileStream.good() || !fileStream.is_open())
  {
    cout << "Couldn't open text file." << endl;
    return -1;
  }
  //create problem channels text file
  ofstream fileStreamProb;
  string fileName2 = fileNameBeg+".problems.txt";
  fileStreamProb.open(fileName2.c_str());
  if(!fileStreamProb.good() || !fileStreamProb.is_open())
  {
    cout << "Couldn't open text file." << endl;
    return -1;
  }

  // Create calibration container objects
  EcalTimeCalibConstants timeCalibConstants;
  EcalTimeCalibErrors timeCalibErrors;

  cout << "Using " << numEventsUsed << " out of " << nEntries << " in the tree." << endl;
  cout << "Creating calibs..." << endl;
  float cryCalibAvg = 0;
  int numCrysCalibrated = 0;
  vector<int> hashesToCalibrateToAvg;
  //Loop over all the crys
  for(int hashedIndex=0; hashedIndex < 14648; ++hashedIndex)
  {
    EEDetId det = EEDetId::unhashIndex(hashedIndex);
    if(det==EEDetId())
      continue;
    CrystalCalibration cryCalib = *(eeCryCalibs[hashedIndex]);
    int x = det.ix();
    int y = det.iy();

    //chiSquaredTotalHist->Fill(cryCalib.totalChi2);
    //expectedStatPresHistEB->Fill(sqrt(1/expectedPresSumEB));
    //expectedStatPresVsObservedMeanErrHistEB->Fill(sigmaM,sqrt(1/expectedPresSumEB));

    //XXX: Filter events at default 0.5*meanE threshold
    cryCalib.filterOutliers();
    
    //numPointsErasedHist->Fill(numPointsErased);
    
    //Write cryTimingHists
    vector<TimingEvent> times = cryCalib.timingEvents;
    for(vector<TimingEvent>::const_iterator timeItr = times.begin();
        timeItr != times.end(); ++timeItr)
    {
      if(det.zside() < 0)
      {
        float weight = 1/((timeItr->sigmaTime)*(timeItr->sigmaTime));
        cryTimingHistsEEM[x-1][y-1]->Fill(timeItr->time,weight);
      }
      else
      {
        float weight = 1/((timeItr->sigmaTime)*(timeItr->sigmaTime));
        cryTimingHistsEEP[x-1][y-1]->Fill(timeItr->time,weight);
      }
    }
    if(det.zside() < 0)
    {
      cryDirEEM->cd();
      cryTimingHistsEEM[x-1][y-1]->Write();
    }
    else
    {
      cryDirEEP->cd();
      cryTimingHistsEEP[x-1][y-1]->Write();
    }
    outfile->cd();

    if(det.zside() < 0)
    {
      hitsPerCryHistEEM->SetBinContent(hashedIndex+1,cryCalib.timingEvents.size());
      hitsPerCryMapEEM->Fill(x,y,cryCalib.timingEvents.size());
    }
    else
    {
      hitsPerCryHistEEP->SetBinContent(hashedIndex+1,cryCalib.timingEvents.size());
      hitsPerCryMapEEP->Fill(x,y,cryCalib.timingEvents.size());
    }
    
    // Make timing calibs
    double p1 = cryCalib.mean;
    double p1err = cryCalib.meanE;
    //cout << "cry ieta: " << ieta << " cry iphi: " << iphi << " p1: " << p1 << " p1err: " << p1err << endl;
    if(cryCalib.timingEvents.size() < 10)
    {
      fileStreamProb << "Cry (only " << cryCalib.timingEvents.size() << " events) was calibrated to avg: " << det.zside() << ", "
                                                                                        << x <<", " << y << ", hash: "
                                                                        << hashedIndex
                                                                          << "\t Calib: " << p1 << "\t Error: " << p1err << std::endl;
      hashesToCalibrateToAvg.push_back(hashedIndex);
      continue;
    }
    // Make it so we can add calib to reco time
    p1*=-1;
    if(p1err < 0.5 && p1err > 0)
    {
      fileStream << "EE\t" << hashedIndex << "\t" << p1 << "\t\t" << p1err << endl;
      if(det.zside() < 0)
      {
        calibHistEEM->Fill(p1);
        //calibMapEEMFlip->Fill(y-85,x+1,p1);
        calibMapEEM->Fill(x,y,p1);
        //calibMapEEMPhase->Fill(x+1,y-85,p1/25-floor(p1/25));
        //errorOnMeanVsNumEvtsHist->Fill(times.size(),p1err);
      }
      else
      {
        calibHistEEP->Fill(p1);
        //calibMapEEPFlip->Fill(y-85,x+1,p1);
        calibMapEEP->Fill(x,y,p1);
        //calibMapEEPPhase->Fill(x+1,y-85,p1/25-floor(p1/25));
        //errorOnMeanVsNumEvtsHist->Fill(times.size(),p1err);
      }
      cryCalibAvg+=p1;
      ++numCrysCalibrated;
      //Store in timeCalibration container
      EcalTimeCalibConstant tcConstant = p1;
      EcalTimeCalibError tcError = p1err;
      uint32_t rawId = EEDetId::unhashIndex(hashedIndex);
      timeCalibConstants[rawId] = tcConstant;
      timeCalibErrors[rawId] = tcError;
    }
    else
    {
      //std::cout << "Cry: " << y <<", " << x << ", hash: " << itr->first
      //  << "\t Calib: " << p1 << "\t Error: " << p1err << std::endl;
      fileStreamProb << "Cry was calibrated to avg: " << x <<", " << y << ", hash: " << hashedIndex
        << "\t Calib: " << p1 << "\t Error: " << p1err << std::endl;
    }

    sigmaHistEE->Fill(cryCalib.stdDev);
    if(det.zside() < 0)
    {
      //calibsVsErrorsEEM->Fill(p1err, p1 > 0 ? p1 : -1*p1);
      calibErrorHistEEM->Fill(p1err);
      calibErrorMapEEM->Fill(x,y,p1err);
      sigmaMapEEM->Fill(x,y,cryCalib.stdDev);
    }
    else
    {
      //calibsVsErrorsEEP->Fill(p1err, p1 > 0 ? p1 : -1*p1);
      calibErrorHistEEP->Fill(p1err);
      calibErrorMapEEP->Fill(x,y,p1err);
      sigmaMapEEP->Fill(x,y,cryCalib.stdDev);
    }
  }
  
  fileStream.close();
  fileStreamProb.close();
  // Calc average
  if(numCrysCalibrated > 0)
    cryCalibAvg/=numCrysCalibrated;
  cryCalibAvg-= 2.0833; // Global phase shift
  // calibrate uncalibratable crys
  for(vector<int>::const_iterator hashItr = hashesToCalibrateToAvg.begin();
      hashItr != hashesToCalibrateToAvg.end(); ++hashItr)
  {
    //Store in timeCalibration container
    EcalTimeCalibConstant tcConstant = cryCalibAvg;
    EcalTimeCalibError tcError = 999;
    uint32_t rawId = EEDetId::unhashIndex(*hashItr);
    timeCalibConstants[rawId] = tcConstant;
    timeCalibErrors[rawId] = tcError;
  }

  //Write XML files
  cout << "Writing XML files." << endl;
  EcalCondHeader header;
  header.method_="testmethod";
  header.version_="testversion";
  header.datasource_="testdata";
  header.since_=123;
  header.tag_="testtag";
  header.date_="Mar 24 1973";
  string timeCalibFile = "EcalTimeCalibsEE.xml";
  string timeCalibErrFile = "EcalTimeCalibErrorsEE.xml";
  // Hack to prevent seg fault
  EcalTimeCalibConstant tcConstant = 0;
  EcalTimeCalibError tcError = 0;
  uint32_t rawId = EBDetId::unhashIndex(0);
  timeCalibConstants[rawId] = tcConstant;
  timeCalibErrors[rawId] = tcError;
  // End hack
  EcalTimeCalibConstantsXMLTranslator::writeXML(timeCalibFile,header,timeCalibConstants);
  EcalTimeCalibErrorsXMLTranslator::writeXML(timeCalibErrFile,header,timeCalibErrors);

  cout << "Writing histograms." << endl;
  outfile->cd();
  calibHistEEM->SetXTitle("timingCalib [ns]");
  calibHistEEM->Write();
  calibHistEEP->SetXTitle("timingCalib [ns]");
  calibHistEEP->Write();
  calibErrorHistEEP->SetXTitle("uncertainty on mean [ns]");
  calibErrorHistEEP->Write();
  calibErrorHistEEM->SetXTitle("uncertainty on mean [ns]");
  calibErrorHistEEM->Write();
  calibErrorMapEEP->Write();
  calibErrorMapEEM->Write();
  sigmaHistEE->Write();
  sigmaMapEEM->Write();
  sigmaMapEEP->Write();

  //can->Print("calibs1D.png");
  //cout << "Writing calibVsErrors" << endl;
  //calibsVsErrors->SetYTitle("AbsCalibConst");
  //calibsVsErrors->SetXTitle("calibConstError");
  //calibsVsErrors->Write();

  //Move empty bins out of the way
  int nxbins = calibMapEEM->GetNbinsX();
  int nybins = calibMapEEM->GetNbinsY();
  for(int i=0;i<=(nxbins+2)*(nybins+2); ++i)
  {
    double binentsM = calibMapEEM->GetBinContent(i);
    if(binentsM==0)
    {
      calibMapEEM->SetBinContent(i,-1000);
    }
    double binentsP = calibMapEEP->GetBinContent(i);
    if(binentsP==0)
    {
      calibMapEEP->SetBinContent(i,-1000);
    }
  }
  calibMapEEM->SetXTitle("ix");
  calibMapEEM->SetYTitle("iy");
  calibMapEEM->Write();
  calibMapEEP->SetXTitle("ix");
  calibMapEEP->SetYTitle("iy");
  calibMapEEP->Write();

  //calibSigmaHist->SetXTitle("#sigma_{cryTime} [ns]");
  //calibSigmaHist->Write();
  
  // Old hist, commented Jun 15 2009
  //avgAmpVsSigmaTHist->SetXTitle("#sigma_{cryTime} [ns]");
  //avgAmpVsSigmaTHist->SetYTitle("Avg. amp. [adc]");
  //avgAmpVsSigmaTHist->Write();
 
  //errorOnMeanVsNumEvtsHist->SetXTitle("Events");
  //errorOnMeanVsNumEvtsHist->SetYTitle("Error_on_mean [ns]");
  //TProfile* theProf = (TProfile*) errorOnMeanVsNumEvtsHist->ProfileX();
  //TF1* myFit = new TF1("myFit","[0]/sqrt(x)+[1]",0,50);
  //myFit->SetRange(0,50);
  ////theProf->Fit("myFit");
  //theProf->Write();
  //errorOnMeanVsNumEvtsHist->Write();
  //
  //chiSquaredEachEventHist->Write();
  //chiSquaredVsAmpEachEventHist->SetXTitle("amplitude [ADC]");
  //chiSquaredVsAmpEachEventHist->SetYTitle("#Chi^{2}");
  //chiSquaredVsAmpEachEventHist->Write();
  //chiSquaredHighMap->SetXTitle("iphi");
  //chiSquaredHighMap->SetYTitle("ieta");
  //chiSquaredHighMap->Write();
  //chiSquaredTotalHist->Write();
  //chiSquaredSingleOverTotalHist->Write();

  expectedStatPresHistEEM->Write();
  expectedStatPresVsObservedMeanErrHistEEM->Write();
  expectedStatPresEachEventHistEEM->Write();
  expectedStatPresHistEEP->Write();
  expectedStatPresVsObservedMeanErrHistEEP->Write();
  expectedStatPresEachEventHistEEP->Write();
  //ampEachEventHist->Write();
  //numPointsErasedHist->Write();
  hitsPerCryHistEEP->Write();
  hitsPerCryMapEEP->Write();
  hitsPerCryHistEEM->Write();
  hitsPerCryMapEEM->Write();
  ampProfileEEP->Write();
  ampProfileMapEEP->Write();
  ampProfileEEM->Write();
  ampProfileMapEEM->Write();
  
  //cout << "All done!  Close input." << endl;
  //f->Close();
  //cout << "Close output and quit!" << endl;
  outfile->Close();
  cout << "done." << endl;
}
コード例 #17
0
ファイル: CalibTree.C プロジェクト: mkiani/cmssw
Double_t CalibTree::Loop(int loop, TFile *fout, bool useweight, int nMin,
			 bool inverse, double rmin, double rmax, int ietaMax,
			 int applyL1Cut, double l1Cut, bool last, 
			 double fraction, bool writeHisto, bool debug) {

  if (fChain == 0) return 0;
  Long64_t nbytes(0), nb(0), kprint(0);
  Long64_t nentryTot = fChain->GetEntriesFast();
  Long64_t nentries = (fraction > 0.01 && fraction < 0.99) ? 
    (Long64_t)(fraction*nentryTot) : nentryTot;
  if (detIds.size() == 0) {
    for (Long64_t jentry=0; jentry<nentries; jentry++) {
      Long64_t ientry = LoadTree(jentry);
      if (ientry < 0) break;
      nb = fChain->GetEntry(jentry);   nbytes += nb;
      // Find DetIds contributing to the track
      bool selRun = (includeRun_ ? ((t_Run >= runlo_) && (t_Run <= runhi_)) :
		     ((t_Run < runlo_) || (t_Run > runhi_)));
      if (selRun && (t_nVtx >= nvxlo_) && (t_nVtx <= nvxhi_)) {
	bool isItRBX = (cSelect_ && exclude_ && cSelect_->isItRBX(t_DetIds));
	++kprint;
	if (!isItRBX) {
	  for (unsigned int idet=0; idet<(*t_DetIds).size(); idet++) { 
	    if (selectPhi((*t_DetIds)[idet])) {
	      unsigned int detid = truncateId((*t_DetIds)[idet],
					      truncateFlag_,debug);
	      if (debug && (kprint<=10)) {
		std::cout << "DetId[" << idet << "] Original " << std::hex 
			  << (*t_DetIds)[idet] << " truncated " << detid 
			  << std::dec;
	      }
	      if (std::find(detIds.begin(),detIds.end(),detid) == detIds.end()){
		detIds.push_back(detid);
		if (debug && (kprint<=10)) std::cout << " new";
	      }
	      if (debug && (kprint<=10)) std::cout << std::endl;
	    }
	  }
	  // Also look at the neighbouring cells if available
	  if (t_DetIds3 != 0) {
	    for (unsigned int idet=0; idet<(*t_DetIds3).size(); idet++) { 
	      if (selectPhi((*t_DetIds3)[idet])) {
		unsigned int detid = truncateId((*t_DetIds3)[idet],
						truncateFlag_,debug);
		if (std::find(detIds.begin(),detIds.end(),detid)==detIds.end()){
		  detIds.push_back(detid);
		}
	      }
	    }
	  }
	}
      }
    }
  }
  if (debug) {
    std::cout << "Total of " << detIds.size() << " detIds and " 
	      << histos.size() << " histos found" << std::endl;
    // The masks are defined in DataFormats/HcalDetId/interface/HcalDetId.h
    for (unsigned int k=0; k<detIds.size(); ++k) {
      int subdet, depth, zside, ieta, iphi;
      unpackDetId(detIds[k], subdet, zside, ieta, iphi, depth);
      std::cout << "DetId[" << k << "] " << subdet << ":" << zside*ieta << ":"
		<< depth << ":" << iphi << "  " << std::hex << detIds[k] 
		<< std::dec << std::endl;
    }
  }
  unsigned int k(0);
  for (std::map<unsigned int, TH1D*>::const_iterator itr = histos.begin();
       itr != histos.end(); ++itr,++k) {
    if (debug) {
      std::cout << "histos[" << k << "] " << std::hex << itr->first 
		<< std::dec << " " << itr->second;
      if (itr->second != 0) std::cout << " " << itr->second->GetTitle();
      std::cout << std::endl;
    }
    if (itr->second != 0) itr->second->Delete();
  }

  for (unsigned int k=0; k<detIds.size(); ++k) {
    char name[20], title[100];
    sprintf (name, "Hist%d_%d", detIds[k], loop);
    int subdet, depth, zside, ieta, iphi;
    unpackDetId(detIds[k], subdet, zside, ieta, iphi, depth);
    sprintf (title, "Correction for Subdet %d #eta %d depth %d (Loop %d)", subdet, zside*ieta, depth, loop);
    TH1D* hist = new TH1D(name,title,100, 0.0, 5.0);
    hist->Sumw2();
    if (debug) {
      std::cout << "Book Histo " << k << " " << title << std::endl;
    }
    histos[detIds[k]] = hist;
  }
  std::cout << "Total of " << detIds.size() << " detIds and " << histos.size() 
	    << " found in " << nentries << std::endl;

  nbytes = nb = 0;
  std::map<unsigned int, myEntry > SumW;
  std::map<unsigned int, double  > nTrks;

  int ntkgood(0);
  for (Long64_t jentry=0; jentry<nentries; jentry++) {
    Long64_t ientry = LoadTree(jentry);
    if (ientry < 0)                               break;
    nb = fChain->GetEntry(jentry);   nbytes += nb;
    if (std::find(entries.begin(),entries.end(),jentry) !=
	entries.end())                            continue;
    bool selRun = (includeRun_ ? ((t_Run >= runlo_) && (t_Run <= runhi_)) :
		   ((t_Run < runlo_) || (t_Run > runhi_)));
    if (!selRun)                                  continue;
    if ((t_nVtx < nvxlo_) || (t_nVtx > nvxhi_))   continue;
    if (cSelect_ != nullptr) {
      if (exclude_) {
	if (cSelect_->isItRBX(t_DetIds))          continue;
      } else {
	if (!(cSelect_->isItRBX(t_ieta,t_iphi)))  continue;
      }
    }

    if (debug) {
      std::cout << "***Entry (Track) Number : " << ientry << std::endl;
      std::cout << "p/eHCal/eMipDR/nDets : " << t_p << "/" << t_eHcal << "/"
		<< t_eMipDR << "/" << (*t_DetIds).size() << std::endl;
    }
    double pmom = (useGen_ && (t_gentrackP > 0)) ? t_gentrackP : t_p;
    if (goodTrack()) {
      ++ntkgood;
      double Etot(0), Etot2(0);
      for (unsigned int idet=0; idet<(*t_DetIds).size(); idet++) { 
	if (selectPhi((*t_DetIds)[idet])) {
	  unsigned int id = (*t_DetIds)[idet];
	  double hitEn(0);
	  unsigned int detid = truncateId(id,truncateFlag_,false);
	  if (Cprev.find(detid) != Cprev.end()) 
	    hitEn = Cprev[detid].first * (*t_HitEnergies)[idet];
	  else 
	    hitEn = (*t_HitEnergies)[idet];
	  if (cFactor_) hitEn *= cFactor_->getCorr(t_Run,id);
	  Etot  += hitEn;
	  Etot2 += ((*t_HitEnergies)[idet]);
	}
      }
      // Now the outer cone 
      double Etot1(0), Etot3(0);
      if (t_DetIds1 != 0 && t_DetIds3 != 0) {
	for (unsigned int idet=0; idet<(*t_DetIds1).size(); idet++) { 
	  if (selectPhi((*t_DetIds1)[idet])) {
	    unsigned int id    = (*t_DetIds1)[idet];
	    unsigned int detid = truncateId(id,truncateFlag_,false);
	    double hitEn(0);
	    if (Cprev.find(detid) != Cprev.end()) 
	      hitEn = Cprev[detid].first * (*t_HitEnergies1)[idet];
	    else 
	      hitEn = (*t_HitEnergies1)[idet];
	    if (cFactor_) hitEn *= cFactor_->getCorr(t_Run,id);
	    Etot1  += hitEn;
	  }
	}
	for (unsigned int idet=0; idet<(*t_DetIds3).size(); idet++) { 
	  if (selectPhi((*t_DetIds3)[idet])) {
	    unsigned int id    = (*t_DetIds3)[idet];
	    unsigned int detid = truncateId(id,truncateFlag_,false);
	    double hitEn(0);
	    if (Cprev.find(detid) != Cprev.end()) 
	      hitEn = Cprev[detid].first * (*t_HitEnergies3)[idet];
	    else 
	      hitEn = (*t_HitEnergies3)[idet];
	    if (cFactor_) hitEn *= cFactor_->getCorr(t_Run,id);
	    Etot3  += hitEn;
	  }
	}
      }
      eHcalDelta_ = Etot3-Etot1;
      double evWt = (useweight) ? t_EventWeight : 1.0; 
      // PU correction only for loose isolation cut
      double ehcal = ((puCorr_ == 0) ? Etot : 
		      ((puCorr_ < 0) ? (Etot*puFactor(-puCorr_,t_ieta,pmom,Etot,eHcalDelta_)) :
		       puFactorRho(puCorr_,t_ieta,t_rhoh,Etot)));
      double pufac = (Etot > 0) ? (ehcal/Etot) : 1.0;
      double ratio = ehcal/(pmom-t_eMipDR);
      if (debug) std::cout << " Weights " << evWt << ":" << pufac << " Energy "
			   << Etot2 << ":" << Etot << ":" << pmom << ":" 
			   << t_eMipDR << ":" << t_eHcal << ":" << ehcal 
			   << " ratio " << ratio  << std::endl;
      if (loop==0) {
	h_pbyE->Fill(ratio, evWt);
        h_Ebyp_bfr->Fill(t_ieta, ratio, evWt);
      }
      if (last){
        h_Ebyp_aftr->Fill(t_ieta, ratio, evWt);
      }
      bool l1c(true);
      if (applyL1Cut != 0) l1c = ((t_mindR1 >= l1Cut) || 
				  ((applyL1Cut == 1) && (t_DataType == 1)));
      if ((rmin >=0 && ratio > rmin) && (rmax >= 0 && ratio < rmax) && l1c) {
	for (unsigned int idet=0; idet<(*t_DetIds).size(); idet++) {
	  if (selectPhi((*t_DetIds)[idet])) {
	    unsigned int id    = (*t_DetIds)[idet];
	    unsigned int detid = truncateId(id,truncateFlag_,false);
	    double hitEn=0.0;
	    if (debug) {
	      std::cout << "idet " << idet << " detid/hitenergy : " 
			<< std::hex << (*t_DetIds)[idet] << ":" << detid 
			<< "/" << (*t_HitEnergies)[idet] << std::endl;
	    }
	    if (Cprev.find(detid) != Cprev.end()) 
	      hitEn = Cprev[detid].first * (*t_HitEnergies)[idet];
	    else 
	      hitEn = (*t_HitEnergies)[idet];
	    if (cFactor_) hitEn *= cFactor_->getCorr(t_Run,id);
	    double Wi  = evWt * hitEn/Etot;
	    double Fac = (inverse) ? (ehcal/(pmom-t_eMipDR)) : 
	      ((pmom-t_eMipDR)/ehcal);
	    double Fac2= Wi*Fac*Fac;
	    TH1D* hist(0);
	    std::map<unsigned int,TH1D*>::const_iterator itr = histos.find(detid);
	    if (itr != histos.end()) hist = itr->second;
	    if (debug) {
	      std::cout << "Det Id " << std::hex << detid << std::dec 
			<< " " << hist << std::endl;
	    }
	    if (hist != 0) hist->Fill(Fac, Wi);//////histola
	    Fac       *= Wi;
	    if (SumW.find(detid) != SumW.end() ) {
	      Wi  += SumW[detid].fact0;
	      Fac += SumW[detid].fact1;
	      Fac2+= SumW[detid].fact2;
	      int kount = SumW[detid].kount + 1;
	      SumW[detid]   = myEntry(kount,Wi,Fac,Fac2); 
	      nTrks[detid] += evWt;
	    } else {
	      SumW.insert(std::pair<unsigned int,myEntry>(detid,myEntry(1,Wi,Fac,Fac2)));
	      nTrks.insert(std::pair<unsigned int,unsigned int>(detid, evWt));
	    }
	  }
	}
      }
    }
  }
  if (debug) {
    std::cout << "# of Good Tracks " << ntkgood << " out of " << nentries 
	      << std::endl;
  }
  if (loop==0) {
    h_pbyE->Write("h_pbyE");
    h_Ebyp_bfr->Write("h_Ebyp_bfr");
  }
  if (last) {
    h_Ebyp_aftr->Write("h_Ebyp_aftr");
  }

  std::map<unsigned int, std::pair<double,double> > cfactors;
  unsigned int kount(0), kountus(0);
  double       sumfactor(0);
  for (std::map<unsigned int,TH1D*>::const_iterator itr = histos.begin();
       itr != histos.end(); ++itr) {
    if (writeHisto) {
      std::pair<double,double> result_write = fitMean(itr->second, 0);
      (itr->second)->Write();
    }
    // The masks are defined in DataFormats/HcalDetId/interface/HcalDetId.h
    int subdet, depth, zside, ieta, iphi;
    unpackDetId(itr->first, subdet, zside, ieta, iphi, depth);
    if (debug) {
      std::cout << "DETID :" << subdet << "  IETA :" << ieta 
		<< " HIST ENTRIES :" << (itr->second)->GetEntries()
		<< std::endl;
    }
  }

  for (std::map<unsigned int,TH1D*>::const_iterator itr = histos.begin();
       itr != histos.end(); ++itr,++kount) {
    std::pair<double,double> result = fitMean(itr->second, 0);
    double factor = (inverse) ? (2.-result.first) : result.first;
    if (debug) {
      int subdet, depth, zside, ieta, iphi;
      unpackDetId(itr->first, subdet, zside, ieta, iphi, depth);
      std::cout << "DetId[" << kount << "] " << subdet << ":" << zside*ieta 
		<< ":" << depth << " Factor " << factor << " +- " 
		<< result.second << std::endl;
    }
    if (!useMean_) {
      cfactors[itr->first] = std::pair<double,double>(factor,result.second);
      if (itr->second->GetEntries() > nMin) {
	kountus++;
	if (factor > 1) sumfactor += (1-1/factor);
	else            sumfactor += (1-factor);
      }
    }
  }
  
  std::map<unsigned int, myEntry>::const_iterator SumWItr = SumW.begin();
  for (; SumWItr != SumW.end(); SumWItr++) {
    unsigned int detid = SumWItr->first;
    int subdet, depth, zside, ieta, iphi;
    unpackDetId(detid, subdet, zside, ieta, iphi, depth);
    if (debug) {
      std::cout << "Detid|kount|SumWi|SumFac|myId : " << subdet << ":" 
		<< zside*ieta << ":" << depth << " | " 
		<< (SumWItr->second).kount << " | " << (SumWItr->second).fact0
		<< "|" << (SumWItr->second).fact1 << "|" 
		<< (SumWItr->second).fact2 << std::endl;
    }
    double factor = (SumWItr->second).fact1/(SumWItr->second).fact0;
    double dfac1  = ((SumWItr->second).fact2/(SumWItr->second).fact0-factor*factor);
    if (dfac1 < 0) dfac1 = 0;
    double dfac   = sqrt(dfac1/(SumWItr->second).kount);
    if (debug) {
      std::cout << "Factor " << factor << " " << dfac1 << " " << dfac
		<< std::endl;
    }
    if (inverse) factor = 2.-factor;
    if (useMean_) {
      cfactors[detid] = std::pair<double,double>(factor,dfac);
      if ((SumWItr->second).kount > nMin) {
	kountus++;
	if (factor > 1) sumfactor += (1-1/factor);
	else            sumfactor += (1-factor);
      }
    }
  }

  double dets[150], cfacs[150], wfacs[150], myId[150], nTrk[150];
  kount = 0;
  std::map<unsigned int,std::pair<double,double> >::const_iterator itr=cfactors.begin();
  for (; itr !=cfactors.end(); ++itr,++kount) {
    unsigned int detid = itr->first;
    int subdet, depth, zside, ieta, iphi;
    unpackDetId(detid, subdet, zside, ieta, iphi, depth);
    double id  = ieta*zside + 0.25*(depth-1);
    double factor = (itr->second).first;
    double dfac   = (itr->second).second;
    if (ieta > ietaMax) {
      factor = 1;
      dfac   = 0;
    }
    std::pair<double,double> cfac(factor,dfac);
    if (Cprev.find(detid) != Cprev.end()) {
      dfac        /= factor;
      factor      *= Cprev[detid].first;
      dfac        *= factor;
      Cprev[detid] = std::pair<double,double>(factor,dfac);
      cfacs[kount] = factor;
    } else {
      Cprev[detid] = std::pair<double,double>(factor,dfac);
      cfacs[kount] = factor;
    }
    wfacs[kount]= factor;
    dets[kount] = detid;
    myId[kount] = id;
    nTrk[kount] = nTrks[detid];
  }
  if (higheta_ > 0) highEtaFactors(ietaMax, debug);

  std::cout << kountus << " detids out of " << kount << " have tracks > "
	    << nMin << std::endl;

  char fname[50];
  fout->cd();
  TGraph *g_fac1 = new TGraph(kount, dets, cfacs); 
  sprintf (fname, "Cfacs%d", loop);
  g_fac1->SetMarkerStyle(7);
  g_fac1->SetMarkerSize(5.0);
  g_fac1->Draw("AP");
  g_fac1->Write(fname);
  TGraph *g_fac2 = new TGraph(kount, dets, wfacs); 
  sprintf (fname, "Wfacs%d", loop);
  g_fac2->SetMarkerStyle(7);
  g_fac2->SetMarkerSize(5.0);
  g_fac2->Draw("AP");
  g_fac2->Write(fname);
  TGraph *g_fac3 = new TGraph(kount, myId, cfacs); 
  sprintf (fname, "CfacsVsMyId%d", loop);
  g_fac3->SetMarkerStyle(7);
  g_fac3->SetMarkerSize(5.0);
  g_fac3->Draw("AP");
  g_fac3->Write(fname);
  TGraph *g_fac4 = new TGraph(kount, myId, wfacs); 
  sprintf (fname, "WfacsVsMyId%d", loop);
  g_fac4->SetMarkerStyle(7);
  g_fac4->SetMarkerSize(5.0);
  g_fac4->Draw("AP");
  g_fac4->Write(fname);
  TGraph *g_nTrk = new TGraph(kount, myId, nTrk); 
  sprintf (fname, "nTrk");
  if(loop==0){
    g_nTrk->SetMarkerStyle(7);
    g_nTrk->SetMarkerSize(5.0);
    g_nTrk->Draw("AP");
    g_nTrk->Write(fname);
  }
  std::cout << "The new factors are :" << std::endl;
  std::map<unsigned int, std::pair<double,double> >::const_iterator CprevItr = Cprev.begin();
  unsigned int indx(0);
  for (; CprevItr != Cprev.end(); CprevItr++, indx++){
    unsigned int detid = CprevItr->first;
    int subdet, depth, zside, ieta, iphi;
    unpackDetId(detid, subdet, zside, ieta, iphi, depth);
    std::cout << "DetId[" << indx << "] " << std::hex << detid << std::dec
	      << "(" << ieta*zside << "," << depth << ") (nTrks:" 
	      << nTrks[detid] << ") : " << CprevItr->second.first << " +- "
	      << CprevItr->second.second << std::endl;
  }
  double mean = (kountus > 0) ? (sumfactor/kountus) : 0;
  std::cout << "Mean deviation " << mean << " from 1 for " << kountus 
	    << " DetIds" << std::endl;
  h_cvg->SetBinContent(loop+1,mean);
  if (last) h_cvg->Write("Cvg0");
  return mean;
}
コード例 #18
0
// ****************************************************************
//XXX: main
int main(int argc, char* argv[])
{
  //
  // **** May 20 2010 update ****
  // Usage: CreateEcalTimingCalibsEB fileWithTree options...
  //

  using namespace std;
  // Ao dependent timing corrections
  // By the definition of these corrections, the timing should be zero for the hits in
  // Module 1 or Low eta EE within the valid A/sigma ranges.
  // Earlier data will have positive time due to the gradual timing shifts in the positive direction.
  timeCorrectionEB_ = new TF1("timeCorrectionEB_","pol4(0)",0,1.2);
  //coefficients obtained in the interval (0, 1.5) from Module 1 of run 144011 EB data; 
  timeCorrectionEB_->SetParameters(0.0399144,-1.32993,2.00013,-1.51769,0.407406);
  //coefficients obtained in the interval (-0.5, 2.0)
  //timeCorrectionEB_->SetParameters(0.0544539,-1.51924,2.57379,-2.11848,0.606632);

  // For selection cuts
  string inBxs, inOrbits, inTrig, inTTrig, inLumi, inRuns;
  float avgTimeMin, avgTimeMax;
  float minAmpEB, minAmpEE;
  float maxSwissCrossNoise;  // EB only, no spikes seen in EE
  float maxHitTimeEB, minHitTimeEB;
  // init to sensible defaults
  avgTimeMin = -1; // in ns
  avgTimeMax = 1; // in ns
  minAmpEB = 5; // GeV
  minAmpEE = 5; // GeV
  maxHitTimeEB = 15; // ns
  minHitTimeEB = -15; // ns
  maxSwissCrossNoise = 0.95; // EB only
  inBxs = "-1";
  inOrbits = "-1";
  inTrig = "-1";
  inTTrig = "-1";
  inLumi = "-1";
  inRuns = "-1";

  char* infile = argv[1];
  if (!infile)
  {
    cout << " No input file specified !" << endl;
    return -1;
  }

  //TODO: Replace this with the parseArguments function from the pi0 binary
  std::string stringGenericOption    = "--";
  for (int i=1 ; i<argc ; i++) {
    if (argv[i] == std::string("-bxs") && argc>i+1) inBxs = std::string(argv[i+1]);
    if (argv[i] == std::string("-orbits") && argc>i+1) inOrbits = std::string(argv[i+1]);
    if (argv[i] == std::string("-trig") && argc>i+1) inTrig = std::string(argv[i+1]);
    if (argv[i] == std::string("-ttrig") && argc>i+1) inTTrig = std::string(argv[i+1]);
    if (argv[i] == std::string("-lumi") && argc>i+1) inLumi = std::string(argv[i+1]);
    if (argv[i] == std::string("-runs") && argc>i+1) inRuns = std::string(argv[i+1]);
    if (argv[i] == std::string("-ebampmin") && argc>i+1) minAmpEB = atof(argv[i+1]);
    if (argv[i] == std::string("-eeampmin") && argc>i+1) minAmpEE = atof(argv[i+1]);
    if (argv[i] == std::string("-swisskmax") && argc>i+1) maxSwissCrossNoise = atof(argv[i+1]);
    if (argv[i] == std::string("-avgtimemin") && argc>i+1) avgTimeMin = atof(argv[i+1]);
    if (argv[i] == std::string("-avgtimemax") && argc>i+1) avgTimeMax = atof(argv[i+1]);
    if (argv[i] == std::string("-ebhittimemax") && argc>i+1) maxHitTimeEB = atof(argv[i+1]);
    if (argv[i] == std::string("-ebhittimemin") && argc>i+1) minHitTimeEB = atof(argv[i+1]);
    // handle here the case of multiple arguments for input files
    if (argv[i] == std::string("--i"))// && argc>i+1)
    {
      for (int u=i+1; u<argc; u++)
      {
        if ( 0==std::string(argv[u]).find( stringGenericOption ) )
        {
          if ( 0==listOfFiles_.size())  {std::cout << "no input files listed" << std::cout;}
          else  {std::cout << "no more files listed, found: " << argv[u] << std::cout;}
          break;
        }
        else
        {
          listOfFiles_.push_back(argv[u]);
          i++;
        }
      }// loop on arguments following --i
      continue;
    }//end 'if input files'

  }
  // Open the input files
  if (listOfFiles_.size()==0){
    std::cout << "\tno input file found" << std::endl;
    return(1);
  }
  else{
    std::cout << "\tfound " << listOfFiles_.size() << " input files: " << std::endl;
    for(std::vector<std::string>::const_iterator  file_itr=listOfFiles_.begin(); file_itr!=listOfFiles_.end(); file_itr++){
      std::cout << "\t" << (*file_itr) << std::endl;
    }
  }
  // Tree construction
  TChain* chain = new TChain ("EcalTimeAnalysis") ;
  std::vector<std::string>::const_iterator file_itr;
  for(file_itr=listOfFiles_.begin(); file_itr!=listOfFiles_.end(); file_itr++){
    chain->Add( (*file_itr).c_str() );
  }


  cout << "Running with options: "
    << "avgTimeMin: " << avgTimeMin << " avgTimeMax: " << avgTimeMax
    << " minAmpEB: " << minAmpEB << " minAmpEE: " << minAmpEE
    << " maxSwissCrossNoise (EB): " << maxSwissCrossNoise
    << " maxHitTimeEB: " << maxHitTimeEB << " minHitTimeEB: " << minHitTimeEB                                                                   
    << " inTrig: " << inTrig << " inTTrig: " << inTTrig << " inLumi: " << inLumi 
    << " inBxs: " << inBxs << " inRuns: " << inRuns << " inOrbits: " << inOrbits
    << endl;

  // Ignore warnings
  gErrorIgnoreLevel = 2001;

  setBranchAddresses(chain,treeVars_);

  // Generate all the vectors for skipping selections
  std::vector<std::vector<double> > bxIncludeVector;
  std::vector<std::vector<double> > bxExcludeVector;
  std::vector<std::vector<double> > orbitIncludeVector;
  std::vector<std::vector<double> > orbitExcludeVector;
  std::vector<std::vector<double> > trigIncludeVector;
  std::vector<std::vector<double> > trigExcludeVector;
  std::vector<std::vector<double> > ttrigIncludeVector;
  std::vector<std::vector<double> > ttrigExcludeVector;
  std::vector<std::vector<double> > lumiIncludeVector;
  std::vector<std::vector<double> > lumiExcludeVector;
  std::vector<std::vector<double> > runIncludeVector;
  std::vector<std::vector<double> > runExcludeVector;
  //recall: string inBxs, inOrbits, inTrig, inTTrig, inLumi, inRuns;
  genIncludeExcludeVectors(inBxs,bxIncludeVector,bxExcludeVector);
  genIncludeExcludeVectors(inOrbits,orbitIncludeVector,orbitExcludeVector);
  genIncludeExcludeVectors(inTrig,trigIncludeVector,trigExcludeVector);
  genIncludeExcludeVectors(inTTrig,ttrigIncludeVector,ttrigExcludeVector);
  genIncludeExcludeVectors(inLumi,lumiIncludeVector,lumiExcludeVector);
  genIncludeExcludeVectors(inRuns,runIncludeVector,runExcludeVector);

  // Open output file and book hists
  string fileNameBeg = "timingCalibsEB";
  string rootFilename = fileNameBeg+".root";
  TFile* outfile = new TFile(rootFilename.c_str(),"RECREATE");
  outfile->cd();

  TH1F* calibHistEB = new TH1F("timingCalibsEB","timingCalibs EB [ns]",2000,-100,100);
  TH1F* calibErrorHistEB = new TH1F("calibErrorEB","timingCalibError EB [ns]",500,0,5);
  calibHistEB->Sumw2();
  calibErrorHistEB->Sumw2();

  TH2F* calibsVsErrors = new TH2F("timingCalibsAndErrors","TimingCalibs vs. errors [ns]",500,0,5,100,0,10);
  calibsVsErrors->Sumw2();

  TH1F* expectedStatPresHistEB = new TH1F("expectedStatPresEB","Avg. expected statistical precision EB [ns], all crys",200,0,2);
  TH2F* expectedStatPresVsObservedMeanErrHistEB = new TH2F("expectedStatPresVsObsEB","Expected stat. pres. vs. obs. error on mean each event EB [ns]",200,0,2,200,0,2);
  TH1F* expectedStatPresEachEventHistEB = new TH1F("expectedStatPresSingleEventEB","Expected stat. pres. each event EB [ns]",200,0,2);
  
  TH2F* errorOnMeanVsNumEvtsHist = new TH2F("errorOnMeanVsNumEvts","Error_on_mean vs. number of events",50,0,50,200,0,2);
  errorOnMeanVsNumEvtsHist->Sumw2();

  TH1F* hitsPerCryHistEB = new TH1F("hitsPerCryEB","Hits used in each crystal;hashedIndex",61200,0,61200);
  TH2F* hitsPerCryMapEB = new TH2F("hitsPerCryMapEB","Hits used in each crystal;i#phi;i#eta",360,1.,361.,172,-86,86);

  TProfile2D* ampProfileMapEB = new TProfile2D("ampProfileMapEB","amp profile map [ADC];i#phi;i#eta",360,1.,361.,172,-86,86);
  TProfile* ampProfileEB = new TProfile("ampProfileEB","Average amplitude in cry [ADC];hashedIndex",61200,0,61200);

  TH1F* sigmaHistEB = new TH1F("sigmaCalibsEB"," Sigma of calib distributions EB [ns]",100,0,1);

  //=============Special Bins for TT and Modules borders=============================
  double ttEtaBins[36] = {-85, -80, -75, -70, -65, -60, -55, -50, -45, -40, -35, -30, -25, -20, -15, -10, -5, 0, 1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71, 76, 81, 86 };
  // double modEtaBins[10]={-85, -65, -45, -25, 0, 1, 26, 46, 66, 86};
  double ttPhiBins[73];
  double modPhiBins[19];
  double timingBins[79];
  double highEBins[11];
  for (int i = 0; i < 79; ++i)
  {
    timingBins[i]=-7.+double(i)*14./78.;
    if (i<73)
    {
      ttPhiBins[i]=1+5*i;
      if ( i < 19) 
      {
        modPhiBins[i]=1+20*i;
        if (i < 11)
        {
          highEBins[i]=10.+double(i)*20.;
        }
      }
    }

  } 
  TH2F* calibMapEB = new TH2F("calibMapEB","time calib map EB [ns];i#phi;i#eta",360,1.,361.,172,-86,86);
  calibMapEB->Sumw2();
  TH2F* sigmaMapEB = new TH2F("sigmaMapEB","Sigma of time calib map EB [ns];i#phi;i#eta",360,1.,361.,172,-86,86);
  TH2F* calibErrorMapEB = new TH2F("calibErrorMapEB","Error of time calib map EB [ns];i#phi;i#eta",360,1.,361.,172,-86,86);
  TProfile2D* calibTTMapEB = new TProfile2D("calibTTMapEB","time calib map EB (TT) [ns];i#phi;i#eta",360/5,ttPhiBins,35, ttEtaBins);

  TDirectory* cryDirEB = gDirectory->mkdir("crystalTimingHistsEB");
  cryDirEB->cd();
  TH1C* cryTimingHistsEB[61200];
  EBDetId det;
  for(int hi=0; hi < 61200; ++hi)
  {
    det = EBDetId::unhashIndex(hi);
    if(det==EBDetId())
      continue;
    string histname = "EB_cryTiming_ieta";
    histname+=intToString(det.ieta());
    histname+="_iphi";
    histname+=intToString(det.iphi());
    cryTimingHistsEB[hi] = new TH1C(histname.c_str(),histname.c_str(),660,-33,33);
    cryTimingHistsEB[hi]->Sumw2();
  }
  outfile->cd();
  
  cout << "Making calibs...";

  CrystalCalibration* ebCryCalibs[61200];
  //XXX: Making calibs with weighted/unweighted mean
  for(int i=0; i < 61200; ++i)
    ebCryCalibs[i] = new CrystalCalibration(); //use weighted mean!
    //ebCryCalibs[i] = new CrystalCalibration(false); //don't use weighted mean!

  // Loop over the TTree
  int numEventsUsed = 0;
  int nEntries = chain->GetEntries();
  cout << "Begin loop over TTree." << endl;

  for(int entry = 0; entry < nEntries; ++entry)
  {
    chain->GetEntry(entry);

    // Loop once to calculate average event time
    float sumTime = 0;
    int numCrysEB = 0;
    for(int bCluster=0; bCluster < treeVars_.nClusters; bCluster++)
    {
      if(treeVars_.xtalInBCIEta[bCluster][0] == -999999) continue; // skip EE clusters
      for(int cryInBC=0; cryInBC < treeVars_.nXtalsInCluster[bCluster]; cryInBC++)
      {
        sumTime += treeVars_.xtalInBCTime[bCluster][cryInBC];
        numCrysEB++;
      }
    }
    //debug
    //cout << "Number of EB crys in event: " << numEBcrys << endl;

    //XXX: Event cuts
    if(sumTime/numCrysEB > avgTimeMax || sumTime/numCrysEB < avgTimeMin)
    {
      //cout << "Average event time: " << sumTime/numCrysEB  << " so event rejected." << endl;
      continue;
    }
    // check BX, orbit, lumi, run, L1 tech/phys triggers
    bool keepEvent = includeEvent(treeVars_.bx,bxIncludeVector,bxExcludeVector)
      && includeEvent(treeVars_.orbit,orbitIncludeVector,orbitExcludeVector)
      && includeEvent(treeVars_.lumiSection,lumiIncludeVector,lumiExcludeVector)
      && includeEvent(treeVars_.runId,runIncludeVector,runExcludeVector)
      && includeEvent(treeVars_.l1ActiveTriggers,
          treeVars_.l1NActiveTriggers,trigIncludeVector,trigExcludeVector)
      && includeEvent(treeVars_.l1ActiveTechTriggers,
          treeVars_.l1NActiveTechTriggers,ttrigIncludeVector,ttrigExcludeVector);
    if(!keepEvent)
      continue;
      
    numEventsUsed++;

    // Loop over the EB crys and fill the map
    for(int bCluster=0; bCluster < treeVars_.nClusters; bCluster++)
    {
      if(treeVars_.xtalInBCIEta[bCluster][0] == -999999) continue; // skip EE clusters
      for(int cryInBC=0; cryInBC < treeVars_.nXtalsInCluster[bCluster]; cryInBC++)
      {
        int hashedIndex = treeVars_.xtalInBCHashedIndex[bCluster][cryInBC];
        float cryTime = treeVars_.xtalInBCTime[bCluster][cryInBC];
        float cryTimeError = treeVars_.xtalInBCTimeErr[bCluster][cryInBC];
        float cryAmp = treeVars_.xtalInBCAmplitudeADC[bCluster][cryInBC];
        //float cryEt = treeVars_.cryETEB_[cryIndex]; // not in the tree
        //SIC FEB 14,16 2011 - removed E/E9
        //                - spike cleaning done higher up
        float crySwissCrossNoise = treeVars_.xtalInBCSwissCross[bCluster][cryInBC];
	float Ao = cryAmp/sigmaNoiseEB;
	float AoLog = log10(Ao/25);

        EBDetId det = EBDetId::unhashIndex(hashedIndex);
        if(det==EBDetId()) // make sure DetId is valid
          continue;

        int ieta = det.ieta();
        int iphi = det.iphi();

        //XXX: RecHit cuts
        bool keepHit = cryAmp >= minAmpEB
          && crySwissCrossNoise < maxSwissCrossNoise
          && cryTime > minHitTimeEB
          && cryTime < maxHitTimeEB
          && AoLog > 0
          && AoLog < 1.2;
        if(!keepHit)
          continue;

        //cout << "STUPID DEBUG: " << hashedIndex << " cryTime: " << cryTime << " cryTimeError: " << cryTimeError << " cryAmp: " << cryAmp << endl;

        // Timing correction to take out the energy dependence if log10(ampliOverSigOfThis/25)
        // is between 0 and 1.2 (about 1 and 13 GeV)
	// amplitude dependent timing corrections
        float timing = cryTime - timeCorrectionEB_->Eval(AoLog);
        //FIXME
        cryTimeError = 1;
        ebCryCalibs[hashedIndex]->insertEvent(cryAmp,timing,cryTimeError,false);
        //SIC Use when we don't have time_error available
        //ebCryCalibs[hashedIndex]->insertEvent(cryAmp,cryTime,35/(cryAmp/1.2),false);
        ampProfileEB->Fill(hashedIndex,cryAmp);
        ampProfileMapEB->Fill(iphi,ieta,cryAmp);
        //if(cryTime > 33 || cryTime < -33)
        //  cout << "Crystal: " << det << " event time is over/underflow: " << cryTime << endl;
      }
    }
  }

  //create output text file
  ofstream fileStream;
  string fileName = fileNameBeg+".calibs.txt";
  fileStream.open(fileName.c_str());
  if(!fileStream.good() || !fileStream.is_open())
  {
    cout << "Couldn't open text file." << endl;
    return -1;
  }
  //create problem channels text file
  ofstream fileStreamProb;
  string fileName2 = fileNameBeg+".problems.txt";
  fileStreamProb.open(fileName2.c_str());
  if(!fileStreamProb.good() || !fileStreamProb.is_open())
  {
    cout << "Couldn't open text file." << endl;
    return -1;
  }

  // Create calibration container objects
  EcalTimeCalibConstants timeCalibConstants;
  EcalTimeCalibErrors timeCalibErrors;

  cout << "Using " << numEventsUsed << " out of " << nEntries << " in the tree." << endl;
  cout << "Creating calibs..." << endl;
  float cryCalibAvg = 0;
  int numCrysCalibrated = 0;
  vector<int> hashesToCalibrateToAvg;
  //Loop over all the crys
  for(int hashedIndex=0; hashedIndex < 61200; ++hashedIndex)
  {
    EBDetId det = EBDetId::unhashIndex(hashedIndex);
    if(det==EBDetId())
      continue;
    CrystalCalibration cryCalib = *(ebCryCalibs[hashedIndex]);
    int ieta = det.ieta();
    int iphi = det.iphi();

    //chiSquaredTotalHist->Fill(cryCalib.totalChi2);
    //expectedStatPresHistEB->Fill(sqrt(1/expectedPresSumEB));
    //expectedStatPresVsObservedMeanErrHistEB->Fill(sigmaM,sqrt(1/expectedPresSumEB));

    //XXX: Filter events at default 0.5*meanE threshold
    cryCalib.filterOutliers();
    
    //numPointsErasedHist->Fill(numPointsErased);
    
    //Write cryTimingHists
    vector<TimingEvent> times = cryCalib.timingEvents;
    for(vector<TimingEvent>::const_iterator timeItr = times.begin();
        timeItr != times.end(); ++timeItr)
    {
      float weight = 1/((timeItr->sigmaTime)*(timeItr->sigmaTime));
      cryTimingHistsEB[hashedIndex]->Fill(timeItr->time,weight);
    }
    cryDirEB->cd();
    cryTimingHistsEB[hashedIndex]->Write();
    outfile->cd();
    hitsPerCryHistEB->SetBinContent(hashedIndex+1,cryCalib.timingEvents.size());
    hitsPerCryMapEB->Fill(iphi,ieta,cryCalib.timingEvents.size());
    
    // Make timing calibs
    double p1 = cryCalib.mean;
    double p1err = cryCalib.meanE;
    //cout << "cry ieta: " << ieta << " cry iphi: " << iphi << " p1: " << p1 << " p1err: " << p1err << endl;
    if(cryCalib.timingEvents.size() < 10)
    {
      fileStreamProb << "Cry (only " << cryCalib.timingEvents.size() << " events) was calibrated to avg: " << ieta <<", " << iphi << ", hash: "
                                                                        << hashedIndex
                                                                        << "\t Calib: " << p1 << "\t Error: " << p1err << std::endl;
      hashesToCalibrateToAvg.push_back(hashedIndex);
      continue;
    }
    // Make it so we can add calib to reco time
    p1*=-1;
    if(p1err < 0.5 && p1err > 0)
    {
      fileStream << "EB\t" << hashedIndex << "\t" << p1 << "\t\t" << p1err << endl;
      calibHistEB->Fill(p1);
      //calibMapEEMFlip->Fill(y-85,x+1,p1);
      calibMapEB->Fill(iphi,ieta,p1);
      calibTTMapEB->Fill(iphi,ieta,p1);
      //calibMapEEMPhase->Fill(x+1,y-85,p1/25-floor(p1/25));
      //errorOnMeanVsNumEvtsHist->Fill(times.size(),p1err);
      cryCalibAvg+=p1;
      ++numCrysCalibrated;
      
      //Store in timeCalibration container
      EcalTimeCalibConstant tcConstant = p1;
      EcalTimeCalibError tcError = p1err;
      uint32_t rawId = EBDetId::unhashIndex(hashedIndex);
      timeCalibConstants[rawId] = tcConstant;
      timeCalibErrors[rawId] = tcError;
    }
    else
    {
      //std::cout << "Cry: " << ieta <<", " << iphi << ", hash: " << itr->first
      //  << "\t Calib: " << p1 << "\t Error: " << p1err << std::endl;
      fileStreamProb << "Cry was calibrated to avg: " << ieta <<", " << iphi << ", hash: " << hashedIndex
        << "\t Calib: " << p1 << "\t Error: " << p1err << std::endl;
      hashesToCalibrateToAvg.push_back(hashedIndex);
    }
    //calibsVsErrorsEB->Fill(p1err, p1 > 0 ? p1 : -1*p1);
    calibErrorHistEB->Fill(p1err);
    calibErrorMapEB->Fill(iphi,ieta,p1err);
    sigmaHistEB->Fill(cryCalib.stdDev);
    sigmaMapEB->Fill(iphi,ieta,cryCalib.stdDev);
  }
  
  fileStream.close();
  fileStreamProb.close();
  // Calc average
  if(numCrysCalibrated > 0)
    cryCalibAvg/=numCrysCalibrated;
  cryCalibAvg-= 2.0833; // Global phase shift
  // calibrate uncalibratable crys
  for(vector<int>::const_iterator hashItr = hashesToCalibrateToAvg.begin();
      hashItr != hashesToCalibrateToAvg.end(); ++hashItr)
  {
    //Store in timeCalibration container
    EcalTimeCalibConstant tcConstant = cryCalibAvg;
    EcalTimeCalibError tcError = 999;
    uint32_t rawId = EBDetId::unhashIndex(*hashItr);
    timeCalibConstants[rawId] = tcConstant;
    timeCalibErrors[rawId] = tcError;
  }

  //Write XML files
  cout << "Writing XML files." << endl;
  EcalCondHeader header;
  header.method_="testmethod";
  header.version_="testversion";
  header.datasource_="testdata";
  header.since_=123;
  header.tag_="testtag";
  header.date_="Mar 24 1973";
  string timeCalibFile = "EcalTimeCalibsEB.xml";
  string timeCalibErrFile = "EcalTimeCalibErrorsEB.xml";
  // Hack to prevent seg fault
  EcalTimeCalibConstant tcConstant = 0;
  EcalTimeCalibError tcError = 0;
  uint32_t rawId = EEDetId::unhashIndex(0);
  timeCalibConstants[rawId] = tcConstant;
  timeCalibErrors[rawId] = tcError;
  // End hack
  EcalTimeCalibConstantsXMLTranslator::writeXML(timeCalibFile,header,timeCalibConstants);
  EcalTimeCalibErrorsXMLTranslator::writeXML(timeCalibErrFile,header,timeCalibErrors);

  cout << "Writing histograms." << endl;
  outfile->cd();
  calibHistEB->SetXTitle("timingCalib [ns]");
  calibHistEB->Write();
  sigmaHistEB->Write();
  calibErrorHistEB->SetXTitle("uncertainty on mean [ns]");
  calibErrorHistEB->Write();
  //eventsEBHist->Write();

  //can->Print("calibs1D.png");
  //cout << "Writing calibVsErrors" << endl;
  //calibsVsErrors->SetYTitle("AbsCalibConst");
  //calibsVsErrors->SetXTitle("calibConstError");
  //calibsVsErrors->Write();

  //cout << "Writing calibErrorHists" << endl;
  //calibErrorHistEB->Write();

  //cout << "Writing calib maps" << endl;
  sigmaMapEB->Write();
  calibMapEB->Write();
  calibErrorMapEB->Write();
  calibTTMapEB->Write();
  //calibMapEBFlip->SetXTitle("ieta");
  //calibMapEBFlip->SetYTitle("iphi");
  //calibMapEBFlip->Write();
  //calibMapEBPhase->SetXTitle("iphi");
  //calibMapEBPhase->SetYTitle("ieta");
  //calibMapEBPhase->Write();
  
  //Move empty bins out of the way
  //int nxbins = calibMapEEM->GetNbinsX();
  //int nybins = calibMapEEM->GetNbinsY();
  //for(int i=0;i<=(nxbins+2)*(nybins+2); ++i)
  //{
  //  double binentsM = calibMapEEM->GetBinContent(i);
  //  if(binentsM==0)
  //  {
  //    calibMapEEM->SetBinContent(i,-1000);
  //  }
  //  double binentsP = calibMapEEP->GetBinContent(i);
  //  if(binentsP==0)
  //  {
  //    calibMapEEP->SetBinContent(i,-1000);
  //  }
  //}
  //calibMapEEM->SetXTitle("ix");
  //calibMapEEM->SetYTitle("iy");
  //calibMapEEM->Write();
  //calibMapEEP->SetXTitle("ix");
  //calibMapEEP->SetYTitle("iy");
  //calibMapEEP->Write();

  //calibSigmaHist->SetXTitle("#sigma_{cryTime} [ns]");
  //calibSigmaHist->Write();
  
  // Old hist, commented Jun 15 2009
  //avgAmpVsSigmaTHist->SetXTitle("#sigma_{cryTime} [ns]");
  //avgAmpVsSigmaTHist->SetYTitle("Avg. amp. [adc]");
  //avgAmpVsSigmaTHist->Write();
 
  //errorOnMeanVsNumEvtsHist->SetXTitle("Events");
  //errorOnMeanVsNumEvtsHist->SetYTitle("Error_on_mean [ns]");
  //TProfile* theProf = (TProfile*) errorOnMeanVsNumEvtsHist->ProfileX();
  //TF1* myFit = new TF1("myFit","[0]/sqrt(x)+[1]",0,50);
  //myFit->SetRange(0,50);
  ////theProf->Fit("myFit");
  //theProf->Write();
  //errorOnMeanVsNumEvtsHist->Write();
  //
  //chiSquaredEachEventHist->Write();
  //chiSquaredVsAmpEachEventHist->SetXTitle("amplitude [ADC]");
  //chiSquaredVsAmpEachEventHist->SetYTitle("#Chi^{2}");
  //chiSquaredVsAmpEachEventHist->Write();
  //chiSquaredHighMap->SetXTitle("iphi");
  //chiSquaredHighMap->SetYTitle("ieta");
  //chiSquaredHighMap->Write();
  //chiSquaredTotalHist->Write();
  //chiSquaredSingleOverTotalHist->Write();

  expectedStatPresHistEB->Write();
  expectedStatPresVsObservedMeanErrHistEB->Write();
  expectedStatPresEachEventHistEB->Write();
  //ampEachEventHist->Write();
  //numPointsErasedHist->Write();

  //calibMapEtaAvgEB->SetXTitle("i#phi");
  //calibMapEtaAvgEB->SetYTitle("i#eta");
  //calibMapEtaAvgEB->Write();
  //calibHistEtaAvgEB->Write();
  
  hitsPerCryHistEB->Write();
  hitsPerCryMapEB->Write();
  ampProfileMapEB->Write();
  ampProfileEB->Write();
  
  //cout << "All done!  Close input." << endl;
  //f->Close();
  //cout << "Close output and quit!" << endl;
  outfile->Close();
  cout << "done." << endl;
}
コード例 #19
0
ファイル: AnaSjePy.C プロジェクト: xcheung/AnaSubjetsMC
int main(int argc, char* argv[])
{
  TApplication theApp(srcName.Data(), &argc, argv);
//=============================================================================

  if (argc<5) return -1;
  TString sPath = argv[1]; if (sPath.IsNull()) return -1;
  TString sFile = argv[2]; if (sFile.IsNull()) return -1;
  TString sJetR = argv[3]; if (sJetR.IsNull()) return -1;
  TString sSjeR = argv[4]; if (sSjeR.IsNull()) return -1;
//=============================================================================

  sPath.ReplaceAll("#", "/");
//=============================================================================

  double dJetR = -1.;
  if (sJetR=="JetR02") dJetR = 0.2;
  if (sJetR=="JetR03") dJetR = 0.3;
  if (sJetR=="JetR04") dJetR = 0.4;
  if (sJetR=="JetR05") dJetR = 0.5;

  if (dJetR<0.) return -1;
//=============================================================================

  double dSjeR = -1.;
  if (sSjeR=="SjeR01") dSjeR = 0.1;
  if (sSjeR=="SjeR02") dSjeR = 0.2;
  if (sSjeR=="SjeR03") dSjeR = 0.3;
  if (dSjeR<0.) return -1;
//=============================================================================

  const double dJetsRange  = dJetR;
  const double dJetsPtMin  = 0.10;
  const double dPseuPtMin  = 0.15;
  const double dCutEtaMax  = 0.9;
  const double dJetEtaMax  = 0.45;
  const double dJetAreaRef = TMath::Pi() * dJetsRange * dJetsRange;

  fastjet::GhostedAreaSpec areaSpc(dCutEtaMax);
  fastjet::JetDefinition   jetsDef(fastjet::antikt_algorithm, dJetsRange, fastjet::BIpt_scheme, fastjet::Best);

//fastjet::AreaDefinition  areaDef(fastjet::active_area,areaSpc);
  fastjet::AreaDefinition  areaDef(fastjet::active_area_explicit_ghosts,areaSpc);

//fastjet::JetDefinition   bkgsDef(fastjet::kt_algorithm, 0.2, fastjet::BIpt_scheme, fastjet::Best);
//fastjet::AreaDefinition  aBkgDef(fastjet::active_area_explicit_ghosts, areaSpc);

  fastjet::Selector selectJet = fastjet::SelectorAbsEtaMax(dJetEtaMax);
//fastjet::Selector selectRho = fastjet::SelectorAbsEtaMax(dCutEtaMax-0.2);
//fastjet::Selector selecHard = fastjet::SelectorNHardest(2);
//fastjet::Selector selectBkg = selectRho * (!(selecHard));
//fastjet::JetMedianBackgroundEstimator bkgsEstimator(selectBkg, bkgsDef, aBkgDef);
//fastjet::Subtractor                   bkgSubtractor(&bkgsEstimator);

  fastjet::JetDefinition subjDef(fastjet::kt_algorithm, dSjeR, fastjet::BIpt_scheme, fastjet::Best);
//=============================================================================

  std::vector<fastjet::PseudoJet> fjInput;
//=============================================================================

  TList *list = new TList();
  TH1D *hJet = new TH1D("hJet", "", 1000, 0., 1000.); hJet->Sumw2(); list->Add(hJet);
  TH1D *hL1j = new TH1D("hL1j", "", 1000, 0., 1000.); hL1j->Sumw2(); list->Add(hL1j);
  TH1D *hL2j = new TH1D("hL2j", "", 1000, 0., 1000.); hL2j->Sumw2(); list->Add(hL2j);

  TH2D *hL1jNsj = new TH2D("hL1jNsj", "", 1000, 0., 1000., 101, -0.5, 100.5); hL1jNsj->Sumw2(); list->Add(hL1jNsj);
  TH2D *hL2jNsj = new TH2D("hL2jNsj", "", 1000, 0., 1000., 101, -0.5, 100.5); hL2jNsj->Sumw2(); list->Add(hL2jNsj);

  TH2D *hL1jIsj = new TH2D("hL1jIsj", "", 1000, 0., 1000., 1000, 0., 1000.); hL1jIsj->Sumw2(); list->Add(hL1jIsj);
  TH2D *hL1j1sj = new TH2D("hL1j1sj", "", 1000, 0., 1000., 1000, 0., 1000.); hL1j1sj->Sumw2(); list->Add(hL1j1sj);
  TH2D *hL1j2sj = new TH2D("hL1j2sj", "", 1000, 0., 1000., 1000, 0., 1000.); hL1j2sj->Sumw2(); list->Add(hL1j2sj);
  TH2D *hL1jDsj = new TH2D("hL1jDsj", "", 1000, 0., 1000., 1000, 0., 1000.); hL1jDsj->Sumw2(); list->Add(hL1jDsj);

  TH2D *hL2jIsj = new TH2D("hL2jIsj", "", 1000, 0., 1000., 1000, 0., 1000.); hL2jIsj->Sumw2(); list->Add(hL2jIsj);
  TH2D *hL2j1sj = new TH2D("hL2j1sj", "", 1000, 0., 1000., 1000, 0., 1000.); hL2j1sj->Sumw2(); list->Add(hL2j1sj);
  TH2D *hL2j2sj = new TH2D("hL2j2sj", "", 1000, 0., 1000., 1000, 0., 1000.); hL2j2sj->Sumw2(); list->Add(hL2j2sj);
  TH2D *hL2jDsj = new TH2D("hL2jDsj", "", 1000, 0., 1000., 1000, 0., 1000.); hL2jDsj->Sumw2(); list->Add(hL2jDsj);

  TH2D *hL1jIsz = new TH2D("hL1jIsz", "", 2000, 0., 1000., 120, 0., 1.2); hL1jIsz->Sumw2(); list->Add(hL1jIsz);
  TH2D *hL1j1sz = new TH2D("hL1j1sz", "", 2000, 0., 1000., 120, 0., 1.2); hL1j1sz->Sumw2(); list->Add(hL1j1sz);
  TH2D *hL1j2sz = new TH2D("hL1j2sz", "", 2000, 0., 1000., 120, 0., 1.2); hL1j2sz->Sumw2(); list->Add(hL1j2sz);
  TH2D *hL1jDsz = new TH2D("hL1jDsz", "", 2000, 0., 1000., 120, 0., 1.2); hL1jDsz->Sumw2(); list->Add(hL1jDsz);

  TH2D *hL2jIsz = new TH2D("hL2jIsz", "", 2000, 0., 1000., 120, 0., 1.2); hL2jIsz->Sumw2(); list->Add(hL2jIsz);
  TH2D *hL2j1sz = new TH2D("hL2j1sz", "", 2000, 0., 1000., 120, 0., 1.2); hL2j1sz->Sumw2(); list->Add(hL2j1sz);
  TH2D *hL2j2sz = new TH2D("hL2j2sz", "", 2000, 0., 1000., 120, 0., 1.2); hL2j2sz->Sumw2(); list->Add(hL2j2sz);
  TH2D *hL2jDsz = new TH2D("hL2jDsz", "", 2000, 0., 1000., 120, 0., 1.2); hL2jDsz->Sumw2(); list->Add(hL2jDsz);
//=============================================================================

  HepMC::IO_GenEvent ascii_in(Form("%s/%s.hepmc",sPath.Data(),sFile.Data()), std::ios::in);
  HepMC::GenEvent *evt = ascii_in.read_next_event();

  while (evt) {
    fjInput.resize(0);

    TVector3 vPar;
    for (HepMC::GenEvent::particle_const_iterator p=evt->particles_begin(); p!=evt->particles_end(); ++p) if ((*p)->status()==1) {
      vPar.SetXYZ((*p)->momentum().px(), (*p)->momentum().py(), (*p)->momentum().pz());

      if ((TMath::Abs(vPar.Eta())<dCutEtaMax)) {
        fjInput.push_back(fastjet::PseudoJet(vPar.Px(), vPar.Py(), vPar.Pz(), vPar.Mag()));
      }
    }
//=============================================================================

    fastjet::ClusterSequenceArea clustSeq(fjInput, jetsDef, areaDef);
    std::vector<fastjet::PseudoJet> includJets = clustSeq.inclusive_jets(dJetsPtMin);
//  std::vector<fastjet::PseudoJet> subtedJets = bkgSubtractor(includJets);
    std::vector<fastjet::PseudoJet> selectJets = selectJet(includJets);
    std::vector<fastjet::PseudoJet> sortedJets = fastjet::sorted_by_pt(selectJets);

    for (int j=0; j<sortedJets.size(); j++) {
      double dJet = sortedJets[j].pt();

      hJet->Fill(dJet);
      if (j==0) hL1j->Fill(dJet);
      if (j==1) hL2j->Fill(dJet); if (j>1) continue;
//=============================================================================

      fastjet::Filter trimmer(subjDef, fastjet::SelectorPtFractionMin(0.));
      fastjet::PseudoJet trimmdJet = trimmer(sortedJets[j]);
      std::vector<fastjet::PseudoJet> trimmdSj = trimmdJet.pieces();

      double nIsj = 0.;
      double d1sj = -1., d2sj = -1.;
      for (int i=0; i<trimmdSj.size(); i++) {
        double dIsj = trimmdSj[i].pt(); if (dIsj<0.001) continue;

        if (j==0) { hL1jIsj->Fill(dJet, dIsj); hL1jIsz->Fill(dJet, dIsj/dJet); }
        if (j==1) { hL2jIsj->Fill(dJet, dIsj); hL2jIsz->Fill(dJet, dIsj/dJet); }
        if (dIsj>d1sj) { d2sj = d1sj; d1sj = dIsj; } else if (dIsj>d2sj) { d2sj = dIsj; }

        nIsj += 1.;
      }

      if (j==0) hL1jNsj->Fill(dJet, nIsj);
      if (j==1) hL2jNsj->Fill(dJet, nIsj);

      if (d1sj>0.) {
        if (j==0) { hL1j1sj->Fill(dJet, d1sj); hL1j1sz->Fill(dJet, d1sj/dJet); }
        if (j==1) { hL2j1sj->Fill(dJet, d1sj); hL2j1sz->Fill(dJet, d1sj/dJet); }
      }

      if (d2sj>0.) {
        if (j==0) { hL1j2sj->Fill(dJet, d2sj); hL1j2sz->Fill(dJet, d2sj/dJet); }
        if (j==1) { hL2j2sj->Fill(dJet, d2sj); hL2j2sz->Fill(dJet, d2sj/dJet); }
      }

      if ((d1sj>0.) && (d2sj>0.)) {
        double dsj = d1sj - d2sj;
        if (j==0) { hL1jDsj->Fill(dJet, dsj); hL1jDsz->Fill(dJet, dsj/dJet); }
        if (j==1) { hL2jDsj->Fill(dJet, dsj); hL2jDsz->Fill(dJet, dsj/dJet); }
      }
    }
//=============================================================================

    delete evt;
    ascii_in >> evt;
  }
//=============================================================================

  TString sXsec = sFile; sXsec.ReplaceAll("out", "xsecs");
  TFile *file = TFile::Open(Form("%s/xsecs/%s.root",sPath.Data(),sXsec.Data()), "READ");
  TH1D *hPtHat        = (TH1D*)file->Get("hPtHat");        hPtHat->SetDirectory(0);
  TH1D *hWeightSum    = (TH1D*)file->Get("hWeightSum");    hWeightSum->SetDirectory(0);
  TProfile *hSigmaGen = (TProfile*)file->Get("hSigmaGen"); hSigmaGen->SetDirectory(0);
  file->Close();
//=============================================================================

  file = TFile::Open(Form("%s.root",sFile.Data()), "NEW");
  hPtHat->Write();
  hWeightSum->Write();
  hSigmaGen->Write();
  list->Write();
  file->Close();
//=============================================================================

  cout << "DONE" << endl;
  return 0;
}