示例#1
0
void HistPdfTest(void)
{
	using namespace RooFit;

	TFile *fin = TFile::Open("./stobg_high.root");
	TTree *tin = (TTree*)fin->Get("stobg_data");

	TCut Cut_SC   = "eta < 0 && charge < 0";
	TCut Cut_DCA  = "Rpc1dca < 100 && Rpc3dca < 100";
	TCut Cut_FVTX = "((fvtx_dr * fvtx_dtheta) < 150) && (TMath::Abs(fvtx_dphi) < 1.5)";
	TCut Cut_Comb = (Cut_SC + Cut_DCA + Cut_FVTX);

	TH2F *TestH = new TH2F("DCA_r_chi2", "", 100, 0, 30, 100, 0, 20);
	tin->Project(TestH->GetName(), "chi2:DCA_r", Cut_Comb);

	RooRealVar DCA_r("DCA_r", "DCA_r", 0, 30.0);
	RooRealVar chi2 ("chi2",  "chi2",  0, 20.0);

	RooArgSet *ASX  = new RooArgSet(DCA_r);
	RooArgSet *ASY  = new RooArgSet(chi2);
	RooArgSet *ASXY = new RooArgSet(DCA_r, chi2);

	//Projected into each direction
	RooDataHist *D1x = new RooDataHist("D1x", "", *ASX, TestH->ProjectionX());
	RooDataHist *D1y = new RooDataHist("D1y", "", *ASY, TestH->ProjectionY());
	RooHistPdf  *P1x = new RooHistPdf ("P1x", "", *ASX, *D1x);
	RooHistPdf  *P1y = new RooHistPdf ("P1y", "", *ASY, *D1y);
	RooAbsPdf	*AP1 = new RooProdPdf ("AP1", "", RooArgSet(*P1x, *P1y));

	//Whole 2D histogram
	RooDataHist *D2  = new RooDataHist("D2",  "", *ASXY, TestH);
	RooHistPdf  *P2  = new RooHistPdf ("P2",  "", *ASXY, *D2);
	RooAbsPdf	*AP2 = new RooProdPdf ("AP2", "", RooArgSet(*P2));


	//! ------------------------------------------------------------------

	//Draw
	RooPlot *f1_x = DCA_r.frame();
	RooPlot *f1_y =  chi2.frame();
	AP1->plotOn(f1_x);
	AP1->plotOn(f1_y);

	RooPlot *f2_x = DCA_r.frame();
	RooPlot *f2_y =  chi2.frame();
	//D2 ->plotOn(f2_x, LineColor(2), LineWidth(2));
	//D2 ->plotOn(f2_y, LineColor(2), LineWidth(2));
	AP2->plotOn(f2_x, LineColor(4), LineWidth(2));
	AP2->plotOn(f2_y, LineColor(4), LineWidth(2));

	//! ------------------------------------------------------------------

	TCanvas *c1 = new TCanvas("c1", "", 1280, 800);
	c1->Divide(2, 2);
	c1->cd(1);
	f1_x->Draw();
	c1->cd(2);
	f1_y->Draw();
	c1->cd(3);
	f2_x->Draw();
	c1->cd(4);
	f2_y->Draw();

	DCA_r = 4.10000;

	double Val1 = AP1->getVal(DCA_r);
	double Val2 = AP2->getVal(DCA_r);

	cout <<endl <<Val1 <<" " <<Val2 <<endl;

	return;
}
示例#2
0
TH2F* mergeBackground(TFile* fa,const char* pattern,const char * theSbtag,const char* newname,const string scenario) {
  std::cout << "mergeBackground: newname = " << newname << std::endl;
  const int nTrig=3;
  const int nfc=3;
  const int ncateg=3;
  string sfc[nfc] = { "q", "c", "b" };
  TH2F* theData[nTrig][nfc][ncateg];
  if (fa == NULL) {
    std::cout << "mergeBackground: no hfile opened" << std::endl;
    return NULL;
  }

  // no weights
  for (int iTrig=0; iTrig<nTrig; ++iTrig) {
    for (int ifc=0; ifc<nfc; ++ifc) {
      for (int icateg=0; icateg<ncateg; ++icateg) {
	//string sname( Form(Form("%sTrig%d",pattern,iTrig),sfc[ifc].c_str(),theSbtag,icateg,icateg) );
	string sname( Form("bgPredict/MassBTagPred_%s_%s_Cat%dTpat%dTrig%d",
			   sfc[ifc].c_str(),theSbtag,icateg,icateg,iTrig) );
	theData[iTrig][ifc][icateg] = (TH2F*) fa->Get( sname.c_str());
	if (theData[iTrig][ifc][icateg] == NULL) {
	  std::cout << "mergeBackground: histogram " << sname << " not found" << std::endl;
	  return 0;
	}
    //theData[ii]->Draw();
      }
    }
  }

  TH2F* mergedData = new TH2F( *theData[0][0][0] );
  mergedData->SetName( newname );
  mergedData->SetTitle( newname );
  for (int iTrig=0; iTrig<nTrig; ++iTrig) {
    for (int ifc=0; ifc<nfc; ++ifc) {
      for (int icateg=0; icateg<ncateg; ++icateg) {
	if (! ((iTrig == 0) && (ifc == 0) && (icateg == 0) )) {
	  mergedData->Add( theData[iTrig][ifc][icateg] );
	  std::cout << "mergeBackground: adding " << theData[iTrig][ifc][icateg]->GetName() << std::endl;
	}
      }
    }
  }  
  std::cout << "mergeBackground: newname(4) = " << newname << std::endl;

  // cross check total weight
  double tw = 0;
  for (int iTrig=0; iTrig<nTrig; ++iTrig) {
    for (int ifc=0; ifc<nfc; ++ifc) {
      for (int icateg=0; icateg<ncateg; ++icateg) {
	tw += theData[iTrig][ifc][icateg]->GetSumOfWeights();
      }
    }
  }
  std::cout << newname << " Sum = " << tw << "  mergedData = " << mergedData->GetSumOfWeights() << std::endl;
  std::cout << mergedData->GetName() << std::endl;
  
  // final normalization (from control region)
  double wScale = 1;
  string sb( theSbtag );
  if (scenario == "LowMass2011") {
    {
      if ( sb == "CSVT" ) {
	wScale = 1.07817;
      } else if ( sb == "TCHPT" ) {
	wScale = 0.970401;
      }
    }
  } else if (scenario == "MediumMass2011") {
    {
      if ( sb == "CSVT" ) {
	wScale = 0.9505;
      } else if ( sb == "TCHPT" ) {
	wScale = 0.874897;
      }
    }
  

   } else if (scenario == "MediumMass2012") {

	       if ( sb == "CSVT" ) 
           wScale = 0.9505;
        if ( sb == "TCHPT" ) 
          wScale = 0.874897;

}

else {
    std::cout << "merge background: bad scenario " << scenario << std::endl;
    return 0;
  }
  std::cout << "Use expected background scale factor of " << wScale << " for " << theSbtag 
	    << " scenario " << scenario << std::endl;
  mergedData->Scale( wScale );
  std::cout << newname << " After final normalization: " << mergedData->GetSumOfWeights() << std::endl;

  return mergedData;
}
示例#3
0
void packTemplatesMass(const int iMass) {
  // This Root macro is for the purpose of providing input for expected limit computation
  // It packs predicted background and a set of signal samples into a root file per Higgs mass
  // 
  TH1::SetDefaultSumw2();
  TH2::SetDefaultSumw2();
  canvas = new TCanvas ("cg1","PadX",10,10,800,600);
  gStyle->SetPadColor(0);
  canvas->SetFillColor(0);

//   const int nbtag = 4;
  const int nbtag = 1;
  //const std::string sbtag[nbtag] = { "TCHPT", "TCHP6", "CSVT", "SSVHPT" };
  const std::string sbtag[nbtag] = { "CSVT" };

  const int nfc=3;
  const int ncateg=3;
  string sfc[nfc] = { "q", "c", "b" };

  // this is for the combination of triggers in real data
  const int nTCombData = 4;
  std::string tCombData[nTCombData] = {"Trig0", "Trig1", "Trig2", "Trig3"};

  std::string L1L2Mode("Weight");
  std::string signalMode("PU_WEIGHTED-NEW");
//   std::string L1L2Mode("Cut");
//   std::string signalMode("CUT_BASED");
  std::string scenario("LowMass2011");


  const int nSignal=7;
  int signalMass[nSignal] = { 90, 100, 120, 140, 180, 250, 350 };
//   double efficiency[nSignal] = { 0.0022081, 0.00324694, 0.00600146, 0.00918135,
// 				0.0138382, 0.0189684, 0.0206572 };
  double efficiency[nSignal][nbtag];
  double intLumi = 0;
  string IgorScen("");
  string spacer("");
  string SashaPath("");

  if (scenario == "LowMass2011") {
    //intLumi = 2.66794; // in fb-1
    intLumi = 2.692643;  // with new method
    IgorScen.assign("low");
    spacer.assign("");
    SashaPath.assign("Data-Run2011AB");
  } else if (scenario == "MediumMass2011") {
    //intLumi = 3.99983; // in fb-1
    intLumi = 4.040802;
    IgorScen.assign("medium");
    spacer.assign("/MEDIUM");
    SashaPath.assign("Data-Run2011AB-Medium");
  } else {
    std::cout << "Bad scenario" << std::endl;
    return;
  }
  string signalHistPattern("massEvBtag/mjjEvBTag_%s");
  if (L1L2Mode == "Weight") {
    signalHistPattern.assign("massEvBtagTW/mjjEvBTagTW_%s");
  }

  double fScal[nSignal][nbtag];
  
  // signal templates
  const int nSyst = 3;
  const int nUpDown = 2;
  std::string signalFile( Form("/data/user/marfin/CMSSW_5_0_1/src/Analysis/HbbMSSMAnalysis/test/Systematics-test-3/%s/theMergeList-SUSYBBHToBB_M-%d_7TeV-pythia6-tauola%s/SF/job_1/TripleBtagAnalysisM-%d_%s.root",signalMode.c_str(),signalMass[iMass],spacer.c_str(),signalMass[iMass],IgorScen.c_str() ) );
  std::string signalSystFiles[nSyst][nUpDown];
  std::string systName[nSyst] = { "JES", "SFbc", "SFudsg" };
  std::string upDownName[nUpDown] = { "Up", "Down" };
  TH2F* hSignalSyst[nSyst][nUpDown][nbtag];

  

  // output file
  TFile* hout = new TFile(Form("packedTemplates-M-%d.root",signalMass[iMass]),"recreate");
  hout->cd();
  TH2::AddDirectory(true);

  TFile* fSig = new TFile( signalFile.c_str() );
  if ( fSig == NULL ) {
    std::cout << "Could not open signal central file " << signalFile.c_str() << std::endl;
    return;
  } else {
    std::cout << "Open signal file " << signalFile.c_str() << std::endl;
  }

  TH2F* hSignalCentral[nbtag];

  for (int ibtag=0; ibtag<nbtag; ++ibtag) {
    hSignalCentral[ibtag] = mergeSignal(fSig,Form(signalHistPattern.c_str(),sbtag[ibtag].c_str()),
					Form("bbH_%s",sbtag[ibtag].c_str()));
    // read the efficiency
    TH1F* histEffMerged = (TH1F*) fSig->Get(Form("TrigEff/EffMerged%s",sbtag[ibtag].c_str()));
    if ( histEffMerged == NULL) {
      std::cout << "Efficiency histo not found" << std::endl;
      return;
    }
    double newEff = histEffMerged->GetBinContent(1);
    std::cout << "Mass= " << signalMass[iMass] 
	      << " btag= " << sbtag[ibtag]
	      << " Efficiency = " << newEff << std::endl;
    efficiency[iMass][ibtag] = newEff;

    double normShould = 1000 * intLumi * efficiency[iMass][ibtag];
    double normIs = hSignalCentral[ibtag]->GetSumOfWeights();
    std::cout << hSignalCentral[ibtag]->GetName() << " TotalContents=" << hSignalCentral[ibtag]->GetSumOfWeights()
	      << std::endl;
    fScal[iMass][ibtag] = normShould / normIs;
    std::cout << "normShould = " << normShould << " normIs " << normIs
	      << " rescale by " << fScal[iMass][ibtag] << std::endl;
    hSignalCentral[ibtag]->Scale( fScal[iMass][ibtag] );
    hout->cd();
    hSignalCentral[ibtag]->Write();
    histEffMerged->Write();

    // create empty file just as marker
    ofstream markerFile;
    markerFile.open(Form("pack-%s-%s.txt",sbtag[ibtag].c_str(),scenario.c_str()),ios::app);
    markerFile << "Template for mass " << signalMass[iMass] << std::endl;
    markerFile.close();
  }

  // read the nominal cross section
  TH1F* histXSect = (TH1F*) fSig->Get("xsection/xsect");
  if ( histXSect == NULL) {
    std::cout << "xsection/xsect" << " not found" << std::endl;
    return;
  }
  histXSect->Write();

  for (int iSyst=0; iSyst<nSyst; ++iSyst) {
    for (int iUpDown=0; iUpDown<nUpDown; ++iUpDown) {
      signalSystFiles[iSyst][iUpDown] = Form( "/data/user/marfin/CMSSW_5_0_1/src/Analysis/HbbMSSMAnalysis/test/Systematics-test-3/%s/theMergeList-SUSYBBHToBB_M-%d_7TeV-pythia6-tauola%s/%s_Sys%s/job_1/TripleBtagAnalysisM-%d_%s.root",
					      signalMode.c_str(),signalMass[iMass],spacer.c_str(),systName[iSyst].c_str(),
					      upDownName[iUpDown].c_str(),signalMass[iMass],IgorScen.c_str());
      std::cout << "Signal systematics file " << signalSystFiles[iSyst][iUpDown] << std::endl;
      TFile* fSigSys = new TFile( signalSystFiles[iSyst][iUpDown].c_str() );
      if ( fSigSys == NULL ) {
	std::cout << "Could not open signal syst file " << signalSystFiles[iSyst][iUpDown].c_str() << std::endl;
	return;
      }
      for (int ibtag=0; ibtag<nbtag; ++ibtag) {
	hSignalSyst[iSyst][iUpDown][ibtag] 
	  = mergeSignal(fSigSys,Form(signalHistPattern.c_str(),sbtag[ibtag].c_str()),
			Form("bbH_%s_%s_%s",systName[iSyst].c_str(),
			     upDownName[iUpDown].c_str(),sbtag[ibtag].c_str()));
	std::cout << "The merged hist has name " << hSignalSyst[iSyst][iUpDown][ibtag]->GetName() << std::endl;
	std::cout << hSignalSyst[iSyst][iUpDown][ibtag]->GetName() << " TotalContents=" << hSignalSyst[iSyst][iUpDown][ibtag]->GetSumOfWeights()
	      << std::endl;

	hSignalSyst[iSyst][iUpDown][ibtag]->Scale( fScal[iMass][ibtag] );
	hout->cd();
	hSignalSyst[iSyst][iUpDown][ibtag]->Write();
      }
      fSigSys->Close();
    }
  }

  // real data
  std::string backgroundFile( Form("/afs/naf.desy.de/user/r/rmankel/scratch/HbbPat/CMSSW_4_2_4_patch1/src/Analysis/HbbMSSMAnalysis/test/results/v1/%s/TripleBtagAnalysis_CR3_SF7/TripleBtagAnalysis_SF/TripleBtagAnalysis.root",SashaPath.c_str()) );
  std::cout << "Background central file : " << backgroundFile << std::endl;
  TFile* fBac = new TFile( backgroundFile.c_str() );
  if ( fBac == NULL ) {
    std::cout << "Could not open background central file " << signalFile.c_str() << std::endl;
    return;
  }

  // hist-to-be-fitted
  TH2F* mjjEbtdata[nbtag];
  for (int ibtag=0; ibtag<nbtag; ++ibtag) {
    mjjEbtdata[ibtag] = getTrigsAndMerge(fBac,Form("massEvBtag/mjjEvBTag_%s",sbtag[ibtag].c_str()),nTCombData,tCombData);

    if (mjjEbtdata[ibtag] == NULL) {
      std::cout << "Histogram not found: " << Form("massEvBtag/mjjEvBTag_%s",sbtag[ibtag].c_str()) << std::endl;
      return;
    }
    // rename
    mjjEbtdata[ibtag]->SetName( Form("Data_%s",sbtag[ibtag].c_str() ) );
    hout->cd();
    mjjEbtdata[ibtag]->Write();
  }

  TH2F* hBackgroundCentral[nbtag][ncateg][nfc];
  TH2F* hBackgroundCentralError[nbtag][ncateg][nfc];
  for (int ibtag=0; ibtag<nbtag; ++ibtag) {
    for (int icateg=0; icateg<ncateg; ++icateg) {
      for (int ifc=0; ifc<nfc; ++ifc) {
	string templateCore("massBTagTemplatesCld/MassBTagTemplateCld");
	string hbSystName( Form("%s_%s_%s_Cat%dTpat%d",templateCore.c_str(),
				sfc[ifc].c_str(),sbtag[ibtag].c_str(),icateg,3) );
	hBackgroundCentral[ibtag][icateg][ifc] = getTrigsAndMerge(fBac,Form("%s_%s_%s_Cat%dTpat%d",
									   templateCore.c_str(),
									   sfc[ifc].c_str(),
									   sbtag[ibtag].c_str(),icateg,3),nTCombData,tCombData);

	if ( hBackgroundCentral[ibtag][icateg][ifc] == NULL ) {
	  std::cout << "Hist not found: " << hbSystName << std::endl;
	  return;
	}
	// rename
	templateId tName(ifc,icateg);
	hBackgroundCentral[ibtag][icateg][ifc]->SetName( Form("%s_%s",tName.name().c_str(),sbtag[ibtag].c_str()) );
	// read the template errors
	templateCore.assign("errorMassBTagTemplates/ErrorMassBTagTemplate");
	string hbSystNameError( Form("%s_%s_%s_Cat%dTpat%d",templateCore.c_str(),
				sfc[ifc].c_str(),sbtag[ibtag].c_str(),icateg,3) );
	hBackgroundCentralError[ibtag][icateg][ifc] 
	  = getTrigsAndMerge(fBac,Form("%s_%s_%s_Cat%dTpat%d",
				       templateCore.c_str(),
				       sfc[ifc].c_str(),
				       sbtag[ibtag].c_str(),icateg,3),nTCombData,tCombData);
	if ( hBackgroundCentralError[ibtag][icateg][ifc] == NULL ) {
	  std::cout << "Hist not found: " << hbSystNameError << std::endl;
	  return;
	}
	// add the template error
	std::cout << " ==== Adding Btag Errors ==== " << hBackgroundCentral[ibtag][icateg][ifc]->GetName() << std::endl;
	for (int ibinx=1; ibinx<= (hBackgroundCentral[ibtag][icateg][ifc]->GetXaxis()->GetNbins()); ++ibinx) {
	  for (int ibiny=1; ibiny<= (hBackgroundCentral[ibtag][icateg][ifc]->GetYaxis()->GetNbins()); ++ibiny) {
	    float oldError = hBackgroundCentral[ibtag][icateg][ifc]->GetBinError(ibinx,ibiny);
	    float addError = hBackgroundCentralError[ibtag][icateg][ifc]->GetBinContent(ibinx,ibiny);
	    float newError = sqrt( oldError * oldError + addError * addError );
	    hBackgroundCentral[ibtag][icateg][ifc]->SetBinError(ibinx,ibiny,newError);
	  }
	}
	hout->cd();
	hBackgroundCentral[ibtag][icateg][ifc]->Write();
      }
    }
  }

  std::string backgroundSystFiles[nSyst][nUpDown];
  std::string systNameSasha[nSyst] = { "JES", "SFbc", "SFq" };
  std::string upDownNameSasha[nUpDown] = { "plus2", "minus2" };
  TH2F* hBackgroundSyst[nSyst][nUpDown][nbtag][ncateg][nfc];
  TH2F* hBackgroundSystError[nSyst][nUpDown][nbtag][ncateg][nfc];

  // for JEC, the up/down templates are just copies of the central templates
  for (int iSyst=0; iSyst<1; ++iSyst) {
    for (int iUpDown=0; iUpDown<nUpDown; ++iUpDown) {
      for (int ibtag=0; ibtag<nbtag; ++ibtag) {
	for (int icateg=0; icateg<ncateg; ++icateg) {
	  for (int ifc=0; ifc<nfc; ++ifc) {
	    hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]
	      = new TH2F( *hBackgroundCentral[ibtag][icateg][ifc] );
	    // rename
	    templateId tName(ifc,icateg);
	    hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]
	      ->SetName( Form("%s_%s_%s_%s",
			      tName.name().c_str(),systName[iSyst].c_str(),
			      upDownName[iUpDown].c_str(),sbtag[ibtag].c_str()) );
	    hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]->Write();
	  }
	}
      }
    }
  }
  fBac->Close();


  for (int iSyst=1; iSyst<nSyst; ++iSyst) {
    for (int iUpDown=0; iUpDown<nUpDown; ++iUpDown) {
      backgroundSystFiles[iSyst][iUpDown] = Form( "/afs/naf.desy.de/user/r/rmankel/scratch/HbbPat/CMSSW_4_2_4_patch1/src/Analysis/HbbMSSMAnalysis/test/results/v1/%s/TripleBtagAnalysis_CR3_SF7/TripleBtagAnalysis_%s%s/TripleBtagAnalysis.root",SashaPath.c_str(),systNameSasha[iSyst].c_str(),upDownNameSasha[iUpDown].c_str() );
      TFile* fBacSys = new TFile( backgroundSystFiles[iSyst][iUpDown].c_str() );
      std::cout << "Background systematics file " << backgroundSystFiles[iSyst][iUpDown] << std::endl;
      if ( fBacSys == NULL ) {
	std::cout << "Could not open background syst file " << backgroundSystFiles[iSyst][iUpDown] << std::endl;
	return;
      }
      for (int ibtag=0; ibtag<nbtag; ++ibtag) {
	for (int icateg=0; icateg<ncateg; ++icateg) {
	  for (int ifc=0; ifc<nfc; ++ifc) {
	    string templateCore("massBTagTemplatesCld/MassBTagTemplateCld");
	    string hbSystName( Form("%s_%s_%s_Cat%dTpat%d",templateCore.c_str(),
				   sfc[ifc].c_str(),sbtag[ibtag].c_str(),icateg,3) );
	    hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc] 
	      = getTrigsAndMerge(fBacSys,Form("%s_%s_%s_Cat%dTpat%d",
					   templateCore.c_str(),
					   sfc[ifc].c_str(),
					   sbtag[ibtag].c_str(),icateg,3),nTCombData,tCombData);
	    if ( hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc] == NULL ) {
	      std::cout << "Hist not found: " << hbSystName << std::endl;
	      return;
	    }
	    // rename
	    templateId tName(ifc,icateg);
	    hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]
	      ->SetName( Form("%s_%s_%s_%s",
			      tName.name().c_str(),systName[iSyst].c_str(),
			      upDownName[iUpDown].c_str(),sbtag[ibtag].c_str()) );

	    // read template errors
	    templateCore.assign("errorMassBTagTemplates/ErrorMassBTagTemplate");
	    string hbSystNameError( Form("%s_%s_%s_Cat%dTpat%d",templateCore.c_str(),
					 sfc[ifc].c_str(),sbtag[ibtag].c_str(),icateg,3) );
	    hBackgroundSystError[iSyst][iUpDown][ibtag][icateg][ifc] 
	      = getTrigsAndMerge(fBacSys,Form("%s_%s_%s_Cat%dTpat%d",
					      templateCore.c_str(),
					      sfc[ifc].c_str(),
					      sbtag[ibtag].c_str(),icateg,3),nTCombData,tCombData);
	    if ( hBackgroundSystError[iSyst][iUpDown][ibtag][icateg][ifc] == NULL ) {
	      std::cout << "Hist not found: " << hbSystNameError << std::endl;
	      return;
	    }
	    // add the template error
	    std::cout << " ==== ErrorAdd ==== " << hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]->GetName() << std::endl;
	    for (int ibinx=1; ibinx<= (hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]->GetXaxis()->GetNbins()); ++ibinx) {
	      for (int ibiny=1; ibiny<= (hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]->GetYaxis()->GetNbins()); ++ibiny) {
		float oldError = hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]->GetBinError(ibinx,ibiny);
		float addError = hBackgroundSystError[iSyst][iUpDown][ibtag][icateg][ifc]->GetBinContent(ibinx,ibiny);
		float newError = sqrt( oldError * oldError + addError * addError );
		hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]->SetBinError(ibinx,ibiny,newError);
	      }
	    }
	    hout->cd();
	    hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]->Write();
	  }
	}
      }
      fBacSys->Close();
    }
  }

  std::cout << "Everything done " << std::endl;

#ifdef PROJECTIONS
  // loop over background templates
  //TH1D* bgProX[nbtag][ncateg][nfc];
  TH1D* bgSystProX[nSyst][nUpDown][nbtag][ncateg][nfc];
  for (int ibtag=0; ibtag<nbtag; ++ibtag) {
    for (int icateg=0; icateg<ncateg; ++icateg) {
      for (int ifc=0; ifc<nfc; ++ifc) {
	TH2F* theTemp = hBackgroundCentral[ibtag][icateg][ifc];
	TH1D* theTempProX = theTemp->ProjectionX(Form("%sProX",theTemp->GetName()),0,-1,"e");
	theTempProX->SetName( Form("%sProX",theTemp->GetName()) );
	TH1D* theTempProY = theTemp->ProjectionY(Form("%sProY",theTemp->GetName()),0,-1,"e");
	std::cout << "Made projection " << theTempProX->GetName() << std::endl;

	if ( (icateg == 0) && (ifc == 0) ) {
	  for (int ibinx=1; ibinx<= theTempProX->GetXaxis()->GetNbins(); ++ibinx) {
	    std::cout << ibinx << " content " << theTempProX->GetBinContent(ibinx)
		      << " error " << theTempProX->GetBinError(ibinx) << std::endl;
	  }
	}
	theTempProX->SetMarkerStyle(20);
	theTempProX->SetMarkerColor(1);
	theTempProX->SetLineColor(1);
	theTempProX->SetMarkerSize(1);
	std::cout << "Draw" << std::endl;
	theTempProX->Draw("EP");
	//theTempProX->Draw("LP,SAME");
	// draw the SFbc systematics
	int colSyst[3] = {1, 2, 4};
	int lstyleUpDown[2] = {1, 1};
	for (int iSyst=1; iSyst<nSyst; ++iSyst) {
	  for (int iUpDown=0; iUpDown<nUpDown; ++iUpDown) {
	    bgSystProX[iSyst][iUpDown][ibtag][icateg][ifc] =  hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]->ProjectionX(Form("%sProXX",hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]->GetName()),0,-1,"e");
	    bgSystProX[iSyst][iUpDown][ibtag][icateg][ifc]->SetName( Form("%sProXX",hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc]->GetName()) );
	    std::cout << "Made projection " << bgSystProX[iSyst][iUpDown][ibtag][icateg][ifc]->GetName() << std::endl;
	     bgSystProX[iSyst][iUpDown][ibtag][icateg][ifc]->SetLineColor( colSyst[iSyst] );
	     bgSystProX[iSyst][iUpDown][ibtag][icateg][ifc]->Draw("HIST,SAME");


// 	    TH2F* theTemp = hBackgroundSyst[iSyst][iUpDown][ibtag][icateg][ifc];
// 	    TH1D* theTempProX = theTemp->ProjectionX(Form("%sProX",theTemp->GetName()),0,-1,"e");
// 	    theTempProX->SetLineColor( colSyst[iSyst] );
// 	    TH1D* theTempProY = theTemp->ProjectionY(Form("%sProY",theTemp->GetName()),0,-1,"e");
// 	    theTempProY->SetLineColor( colSyst[iSyst] );
// 	    //theTempProX->Draw("HIST");
	  }
	}

	canvas->Print(Form("Template_%s_%s_Cat%d_ProX.png",sbtag[ibtag].c_str(),sfc[ifc].c_str(),icateg));
      }
    }
  }
#endif

  //hout->Write();
  hout->Close();

  // close the signal central file
  fSig->Close();

  return;
}
int main (int argc, char *argv[])
{

  printBoxedMessage("Starting plot generation");

  // ####################
  // ##   Init tools   ##
  // ####################
 
     string signalCategory = "T2bw-025";

     // Create a sonic Screwdriver
      SonicScrewdriver screwdriver;

  // ##########################
  // ##   Create Variables   ##
  // ##########################

     screwdriver.AddVariable("METoverSqrtHT",  "MET / #sqrt{H_{T}}",      "",       32,0,32,         &(myEvent.METoverSqrtHT),       "");
     screwdriver.AddVariable("MET",            "MET",                     "GeV",    15,50,500,       &(myEvent.MET),                 "logY=true");
     screwdriver.AddVariable("MT",             "MT",                      "GeV",    20,0,400,        &(myEvent.MT),                  "logY=true");
     screwdriver.AddVariable("leadingBPt",     "p_{T}(leading b jet)",    "GeV",    20,0,200,        &(myEvent.leadingBPt),          "logY=true");
     
     screwdriver.AddVariable("mStop",          "m_{#tilde{t}}",           "GeV",    28,112.5,812.5,  &(myEvent.mStop),               "");
     screwdriver.AddVariable("mNeutralino",    "m_{#chi^{0}}",            "GeV",    16,-12.5,387.5,  &(myEvent.mNeutralino),         "noOverflowInLastBin");
     
     // #########################################################
     // ##   Create ProcessClasses (and associated datasets)   ##
     // #########################################################

     screwdriver.AddProcessClass("1ltop",                        "1l top", "background",kRed-7);
         #ifdef USING_TTBAR_POWHEG
             screwdriver.AddDataset("ttbar_powheg",              "1ltop",  0, 0);
         #endif
         #ifdef USING_TTBAR_MADGRAPH
             screwdriver.AddDataset("ttbar_madgraph_1l",         "1ltop",  0, 0);
         #endif
         screwdriver.AddDataset("singleTop_st",                  "1ltop",  0, 0);


     screwdriver.AddProcessClass("ttbar_2l", "t#bar{t} #rightarrow l^{+}l^{-}", "background",kCyan-3);
         #ifdef USING_TTBAR_MADGRAPH
             screwdriver.AddDataset("ttbar_madgraph_2l",   "ttbar_2l",  0, 0);
         #endif

     screwdriver.AddProcessClass("W+jets",         "W+jets",                    "background", kOrange-2);
             screwdriver.AddDataset("W+jets",      "W+jets", 0, 0);
                                                   
     screwdriver.AddProcessClass("rare",           "rare",                      "background", kMagenta-5);
             screwdriver.AddDataset("rare",        "rare", 0, 0);
                                                   
     screwdriver.AddProcessClass(signalCategory,    signalCategory,             "signal",     kViolet-1);
             screwdriver.AddDataset(signalCategory, signalCategory,   0, 0);

     screwdriver.AddProcessClass("signal_250_100",  signalCategory+" (250/100)",      "signal",COLORPLOT_BLUE   );
     screwdriver.AddProcessClass("signal_450_100",  signalCategory+" (450/100)",      "signal",COLORPLOT_GREEN2 ); 
     screwdriver.AddProcessClass("signal_400_175",  signalCategory+" (400/175)",      "signal",COLORPLOT_GREEN2 ); 
     screwdriver.AddProcessClass("signal_650_100",  signalCategory+" (650/100)",      "signal",COLORPLOT_GREEN  );

  // ##########################
  // ##    Create Regions    ##
  // ##########################

     screwdriver.AddRegion("presel",             "Preselection",                          &goesInPreselectionMTtail);
/*
     screwdriver.AddRegion("veryOffShell_loose", "Cut-and-count;Very off-shell (loose)",  &Selector_veryOffShell_loose);
     screwdriver.AddRegion("offShell_loose",     "Cut-and-count;Off-shell (loose)",       &Selector_offShell_loose );
     screwdriver.AddRegion("lowDeltaM_tight",    "Cut-and-count;Low #DeltaM (tight)",     &Selector_lowDeltaM_tight );
     screwdriver.AddRegion("highDeltaM",         "Cut-and-count;High #DeltaM",            &Selector_highDeltaM );
*/
     
     screwdriver.AddRegion("offshell",           "Cut-and-count;Off-shell",              &Selector_offShell);
     screwdriver.AddRegion("lowMasses",          "Cut-and-count;Low masses",             &Selector_lowMasses);
     screwdriver.AddRegion("highMasses",         "Cut-and-count;High masses",            &Selector_highMasses);
     

  // ##########################
  // ##   Create Channels    ##
  // ##########################
      
     screwdriver.AddChannel("singleLepton", "e/#mu-channels",  &goesInSingleLeptonChannel);

  // ########################################
  // ##       Create histograms and        ##
  // ##  schedule type of plots to produce ##
  // ########################################

     screwdriver.SetLumi(20000);

     // Create histograms
     screwdriver.Create1DHistos();
     screwdriver.Add2DHisto("mStop","mNeutralino");

     screwdriver.SetGlobalBoolOption  ("1DSuperimposed",   "includeSignal",                   true   );

     screwdriver.SetGlobalStringOption("1DStack",          "includeSignal",                   "stack");
     screwdriver.SetGlobalFloatOption ("1DStack",          "factorSignal",                    1.0    );

     screwdriver.SetGlobalStringOption("DataMCComparison", "includeSignal",                   "stack");
     screwdriver.SetGlobalFloatOption ("DataMCComparison", "factorSignal",                    1.0    );

     // Schedule plots
     screwdriver.SchedulePlots("1DSuperimposed");
     screwdriver.SchedulePlots("1DStack");
     screwdriver.SchedulePlots("2D");
     screwdriver.SchedulePlots("2DSuperimposed");

     // Config plots

     screwdriver.SetGlobalStringOption("Plot", "infoTopRight", "CMS Internal");
     screwdriver.SetGlobalStringOption("Plot", "infoTopLeft",  "#sqrt{s} = 8 TeV, L = 20 fb^{-1}");

     screwdriver.SetGlobalBoolOption("Plot", "exportPdf", true);
     screwdriver.SetGlobalBoolOption("Plot", "exportEps", false);
     screwdriver.SetGlobalBoolOption("Plot", "exportPng", false);

  // ########################################
  // ##       Run over the datasets        ##
  // ########################################

  vector<string> datasetsList;
  screwdriver.GetDatasetList(&datasetsList);

  cout << "   > Reading datasets... " << endl;
  cout << endl;

  for (unsigned int d = 0 ; d < datasetsList.size() ; d++)
  {
     string currentDataset = datasetsList[d];
     string currentProcessClass = screwdriver.GetProcessClass(currentDataset); 
     // Open the tree
     TFile f((string(FOLDER_BABYTUPLES)+currentDataset+".root").c_str());
     TTree* theTree = (TTree*) f.Get("babyTuple"); 

     intermediatePointers pointers;
     InitializeBranchesForReading(theTree,&myEvent,&pointers);

     sampleName = currentDataset;
     sampleType = screwdriver.GetProcessClassType(currentProcessClass);
    
     if (currentDataset == signalCategory)
     {
         theTree->SetBranchAddress("mStop",       &(myEvent.mStop));
         theTree->SetBranchAddress("mNeutralino", &(myEvent.mNeutralino));
     }
     else
     {
         myEvent.mStop       = -1;
         myEvent.mNeutralino = -1;
     }

  // ########################################
  // ##        Run over the events         ##
  // ########################################

      int nEntries = theTree->GetEntries();
      for (int i = 0 ; i < nEntries ; i++)
      //for (int i = 0 ; i < min(200000, (int) theTree->GetEntries()); i++)
      {
          if (i % (theTree->GetEntries() / 50) == 0) 
              printProgressBar(i,nEntries,currentDataset);

          // Get the i-th entry
          ReadEvent(theTree,i,&pointers,&myEvent);

          // Split 1-lepton ttbar and 2-lepton ttbar
          string currentProcessClass_ = currentProcessClass;
          if ((currentDataset == "ttbar_powheg") && (myEvent.numberOfGenLepton == 2)) 
              currentProcessClass_ = "ttbar_2l";

          screwdriver.AutoFillProcessClass(currentProcessClass_,getWeight());

          if ((myEvent.mStop == 250) && (myEvent.mNeutralino == 100))
              screwdriver.AutoFillProcessClass("signal_250_100",getWeight());
          if ((myEvent.mStop == 450) && (myEvent.mNeutralino == 100))
              screwdriver.AutoFillProcessClass("signal_450_100",getWeight());
          if ((myEvent.mStop == 400) && (myEvent.mNeutralino == 175))
              screwdriver.AutoFillProcessClass("signal_400_175",getWeight());
          if ((myEvent.mStop == 650) && (myEvent.mNeutralino == 100))
              screwdriver.AutoFillProcessClass("signal_650_100",getWeight());
      }

      printProgressBar(nEntries,nEntries,currentDataset);
      cout << endl;
      f.Close();

  }

  // ###################################
  // ##   Make plots and write them   ##
  // ###################################
 
  cout << endl;
  cout << "   > Making plots..." << endl;
  screwdriver.MakePlots();
  cout << "   > Saving plots..." << endl;
  screwdriver.WritePlots("../plots/cutAndCount_performances/"+signalCategory+"/");

  printBoxedMessage("Plot generation completed");

  // #############################
  // ##   Post-plotting tests   ##
  // #############################
  
  printBoxedMessage("Now computing misc tests ... ");
  
  /*
  vector<string> cutAndCountRegions =
  {
      "veryOffShell_loose",
      "offShell_loose",    
      "lowDeltaM_tight",   
      "highDeltaM"     
  };

  float SF_1ltop_and_Wjets = 2;
  float SF_allOthers       = 1.3;

  vector<float> globalBackgroundUncertainty =
  {
      0.2,
      0.2,
      0.2,
      0.4
  };
  */
  
  vector<string> cutAndCountRegions =
  {
    "presel",
    "offshell",
    "lowMasses",
    "highMasses"
  };

  float SF_1ltop_and_Wjets = 2;
  float SF_allOthers       = 1.3;

  vector<float> globalBackgroundUncertainty =
  {
      0.2,
      0.2,
      0.2
  };
  
  TableBackgroundSignal(&screwdriver,cutAndCountRegions,"singleLepton").Print();
  TableBackgroundSignal(&screwdriver,cutAndCountRegions,"singleLepton").PrintLatex();

  // ##########################
  // ##   Compute FOM maps   ##
  // ##########################

  vector<TH2F*> signalMaps;
  vector<TH2F*> FOMdiscoveryMaps;
  vector<TH2F*> FOMexclusionMaps;
  vector<TH2F*> efficiencies;

  int nBinsX = -1;
  int nBinsY = -1;

  TH2F* signalMapPresel  = screwdriver.get2DHistoClone("mStop","mNeutralino",signalCategory,"presel","singleLepton");
  TH2F* backgroundPresel = screwdriver.get2DCompositeHistoClone("mStop","mNeutralino","2DSumBackground","presel","singleLepton","");

  if (nBinsX == -1) nBinsX = signalMapPresel->GetNbinsX();
  if (nBinsY == -1) nBinsY = signalMapPresel->GetNbinsY();

  // Store background eff in (mStop,mLSP) = (200,300)
  int backgroundBin = signalMapPresel->FindBin(200,300);
  float backgroundYieldPresel = backgroundPresel->Integral(0,nBinsX+1,0,nBinsY+1);

  for (unsigned int i = 0 ; i < cutAndCountRegions.size() ; i++)
  {
      signalMaps.push_back(screwdriver.get2DHistoClone("mStop","mNeutralino",signalCategory,cutAndCountRegions[i],"singleLepton"));
      signalMaps[i]->SetName((string("signalMap_")+cutAndCountRegions[i]).c_str());

      float B =   screwdriver.GetYieldAndError("1ltop",    cutAndCountRegions[i],"singleLepton").value()  * SF_1ltop_and_Wjets
                + screwdriver.GetYieldAndError("ttbar_2l", cutAndCountRegions[i],"singleLepton").value()  * SF_allOthers
                + screwdriver.GetYieldAndError("W+jets",   cutAndCountRegions[i],"singleLepton").value()  * SF_1ltop_and_Wjets
                + screwdriver.GetYieldAndError("rare",     cutAndCountRegions[i],"singleLepton").value()  * SF_allOthers;

      // Apply scale factor from background prediction
      float f_B = globalBackgroundUncertainty[i];
      //float f_B = 0.15;

      if (B < 1.0) B = 1.0;
 
      efficiencies.push_back((TH2F*) signalMaps[i]->Clone());
      efficiencies[i]->SetName((string("eff_")+cutAndCountRegions[i]).c_str());
      efficiencies[i]->Divide(signalMapPresel);
      efficiencies[i]->SetBinContent(backgroundBin,B/backgroundYieldPresel);
      
      FOMdiscoveryMaps.push_back((TH2F*) signalMaps[i]->Clone());
      FOMdiscoveryMaps[i]->SetName((string("FOMdisco_")+cutAndCountRegions[i]).c_str());

      FOMexclusionMaps.push_back((TH2F*) signalMaps[i]->Clone());
      FOMexclusionMaps[i]->SetName((string("FOMexclu_")+cutAndCountRegions[i]).c_str());

      for (int x = 1 ; x <= nBinsX ; x++)
      for (int y = 1 ; y <= nBinsY ; y++)
      {
          float S = signalMaps[i]->GetBinContent(x,y);

          float FOMdiscovery = figureOfMerit(S,B,"discovery",false,f_B);
          FOMdiscoveryMaps[i]->SetBinContent(x,y,FOMdiscovery);
          
          float FOMexclusion = figureOfMerit(S,B,"exclusion",false,f_B);
          FOMexclusionMaps[i]->SetBinContent(x,y,FOMexclusion);
      }

  }

  // ################################
  // ##   Compute "best" FOM map   ##
  // ################################

  TH2F* bestDiscoFOMMap = (TH2F*) signalMaps[0]->Clone();  bestDiscoFOMMap->SetName("bestDiscoFOM");
  TH2F* bestDiscoSetMap = (TH2F*) signalMaps[0]->Clone();  bestDiscoSetMap->SetName("bestDiscoSet");
  TH2F* bestDiscoSigEff = (TH2F*) signalMaps[0]->Clone();  bestDiscoSigEff->SetName("bestDiscoSigEff");
  TH2F* bestDiscoBkgEff = (TH2F*) signalMaps[0]->Clone();  bestDiscoBkgEff->SetName("bestDiscoBkgEff");
  
  TH2F* bestExcluFOMMap = (TH2F*) signalMaps[0]->Clone();  bestExcluFOMMap->SetName("bestExcluFOM");
  TH2F* bestExcluSetMap = (TH2F*) signalMaps[0]->Clone();  bestExcluSetMap->SetName("bestExcluSet");
  TH2F* bestExcluSigEff = (TH2F*) signalMaps[0]->Clone();  bestExcluSigEff->SetName("bestExcluSigEff");
  TH2F* bestExcluBkgEff = (TH2F*) signalMaps[0]->Clone();  bestExcluBkgEff->SetName("bestExcluBkgEff");
  
  for (int x = 1 ; x <= nBinsX ; x++)
  for (int y = 1 ; y <= nBinsY ; y++)
  {
      float bestDiscoFOM = -1.0;
      int   bestDiscoSet = 0;
      float bestDiscoSigEff_ = -1.0;
      float bestDiscoBkgEff_ = -1.0;
      for (unsigned int i = 0 ; i < cutAndCountRegions.size() ; i++)
      {
          float DiscoFOM = FOMdiscoveryMaps[i]->GetBinContent(x,y);
          if (bestDiscoFOM < DiscoFOM)
          {
              bestDiscoFOM = DiscoFOM;
              if (bestDiscoFOM > 0) bestDiscoSet = i+1;
              bestDiscoSigEff_ = efficiencies[i]->GetBinContent(x,y);
              bestDiscoBkgEff_ = efficiencies[i]->GetBinContent(backgroundBin);
          }
      }
      bestDiscoFOMMap->SetBinContent(x,y,bestDiscoFOM);
      bestDiscoSetMap->SetBinContent(x,y,bestDiscoSet);
      bestDiscoSigEff->SetBinContent(x,y,bestDiscoSigEff_);
      bestDiscoBkgEff->SetBinContent(x,y,bestDiscoBkgEff_);

      float bestExcluFOM = -1.0;
      int   bestExcluSet = 0;
      float bestExcluSigEff_ = -1.0;
      float bestExcluBkgEff_ = -1.0;
      for (unsigned int i = 0 ; i < cutAndCountRegions.size() ; i++)
      {
          float ExcluFOM = FOMexclusionMaps[i]->GetBinContent(x,y);
          if (bestExcluFOM < ExcluFOM)
          {
              bestExcluFOM = ExcluFOM;
              if (bestExcluFOM > 0) bestExcluSet = i+1;
              bestExcluSigEff_ = efficiencies[i]->GetBinContent(x,y);
              bestExcluBkgEff_ = efficiencies[i]->GetBinContent(backgroundBin);
          }
      }
      bestExcluFOMMap->SetBinContent(x,y,bestExcluFOM);
      bestExcluSetMap->SetBinContent(x,y,bestExcluSet);
      bestExcluSigEff->SetBinContent(x,y,bestExcluSigEff_);
      bestExcluBkgEff->SetBinContent(x,y,bestExcluBkgEff_);

  }

  // #########################
  // ##   Save those maps   ##
  // #########################

  float lineOffset = 0.0;
  string label;
  if (signalCategory == "T2tt"    ) { lineOffset = 172; label = "T2tt;";            }
  if (signalCategory == "T2bw-025") { lineOffset = 320; label = "T2bw (x = 0.25);"; }
  if (signalCategory == "T2bw-050") { lineOffset = 160; label = "T2bw (x = 0.50);"; }
  if (signalCategory == "T2bw-075") { lineOffset = 105; label = "T2bw (x = 0.75);"; }

  TFile fOutput(("../plots/cutAndCount_performances/"+signalCategory+"/custom.root").c_str(),"RECREATE");
  string pathExport = "../plots/cutAndCount_performances/"+signalCategory+"/";
  gStyle->SetPaintTextFormat("4.0f");
  formatAndWriteMapPlot(&screwdriver,bestDiscoSetMap,bestDiscoSetMap->GetName(),label+"Best set of cuts;(for discovery)",pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestExcluSetMap,bestExcluSetMap->GetName(),label+"Best set of cuts;(for exclusion)",pathExport,lineOffset);
  gStyle->SetPaintTextFormat("4.1f");
  for (unsigned int i = 0 ; i < cutAndCountRegions.size() ; i++)
  {
      FOMdiscoveryMaps[i]->SetMaximum(5.0);
      formatAndWriteMapPlot(&screwdriver,FOMdiscoveryMaps[i],FOMdiscoveryMaps[i]->GetName(),string("Discovery FOM for ")+cutAndCountRegions[i], pathExport,lineOffset);
      formatAndWriteMapPlot(&screwdriver,    efficiencies[i],    efficiencies[i]->GetName(),string("Efficiencies for " )+cutAndCountRegions[i], pathExport,lineOffset);
  }
  bestDiscoFOMMap->SetMaximum(5.0);
  bestExcluFOMMap->SetMaximum(5.0);
  formatAndWriteMapPlot(&screwdriver,bestDiscoFOMMap,bestDiscoFOMMap->GetName(),label+"Best FOM;(for discovery)"              ,pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestDiscoSigEff,bestDiscoSigEff->GetName(),label+"Best signal efficiency;(for discovery)",pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestDiscoBkgEff,bestDiscoBkgEff->GetName(),label+"Best backgr efficiency;(for discovery)",pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestExcluFOMMap,bestExcluFOMMap->GetName(),label+"Best FOM;(for exclusion)"              ,pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestExcluSigEff,bestExcluSigEff->GetName(),label+"Best signal efficiency;(for exclusion)",pathExport,lineOffset);
  formatAndWriteMapPlot(&screwdriver,bestExcluBkgEff,bestExcluBkgEff->GetName(),label+"Best backgr efficiency;(for exclusion)",pathExport,lineOffset);
  fOutput.Close();

  printBoxedMessage("Program done.");
  return (0);
}
示例#5
0
void rulevisHists( TDirectory *rfdir, TDirectory *vardir, TDirectory *corrdir, TMVAGlob::TypeOfPlot type) {
   //
   if (rfdir==0)   return;
   if (vardir==0)  return;
   if (corrdir==0) return;
   //
   const TString rfName    = rfdir->GetName();
   const TString maintitle = rfName + " : Rule Importance";
   const TString rfNameOpt = "_RF2D_";
   const TString outfname[TMVAGlob::kNumOfMethods] = { "rulevisHists",
                                                       "rulevisHists_decorr",
                                                       "rulevisCorr_pca",
                                                       "rulevisCorr_gaussdecorr" };

   const TString outputName = outfname[type]+"_"+rfdir->GetName();
   //
   TIter rfnext(rfdir->GetListOfKeys());
   TKey *rfkey;
   Double_t rfmax;
   Double_t rfmin;
   Bool_t allEmpty=kTRUE;
   Bool_t first=kTRUE;
   while ((rfkey = (TKey*)rfnext())) {
      // make sure, that we only look at histograms
      TClass *cl = gROOT->GetClass(rfkey->GetClassName());
      if (!cl->InheritsFrom("TH2F")) continue;
      TH2F *hrf = (TH2F*)rfkey->ReadObj();
      TString hname= hrf->GetName();
      if (hname.Contains("__RF_")){ // found a new RF plot
         Double_t valmin = hrf->GetMinimum();
         Double_t valmax = hrf->GetMaximum();
         if (first) {
            rfmin=valmin;
            rfmax=valmax;
            first = kFALSE;
         } else {
            if (valmax>rfmax) rfmax=valmax;
            if (valmin<rfmin) rfmin=valmin;
         }
         if (hrf->GetEntries()>0) allEmpty=kFALSE;
      }
   }
   if (first) {
      cout << "ERROR: no RF plots found..." << endl;
      return;
   }

   const Int_t nContours = 100;
   Double_t contourLevels[nContours];
   Double_t dcl = (rfmax-rfmin)/Double_t(nContours-1);
   //
   for (Int_t i=0; i<nContours; i++) {
      contourLevels[i] = rfmin+dcl*Double_t(i);
   }

   ///////////////////////////
   vardir->cd();
 
   // how many plots are in the directory?
   Int_t noPlots = ((vardir->GetListOfKeys())->GetEntries()) / 2;
 
   // define Canvas layout here!
   // default setting
   Int_t xPad;  // no of plots in x
   Int_t yPad;  // no of plots in y
   Int_t width; // size of canvas
   Int_t height;
   switch (noPlots) {
   case 1:
      xPad = 1; yPad = 1; width = 500; height = 0.7*width; break;
   case 2:
      xPad = 2; yPad = 1; width = 600; height = 0.7*width; break;
   case 3:
      xPad = 3; yPad = 1; width = 900; height = 0.4*width; break;
   case 4:
      xPad = 2; yPad = 2; width = 600; height = width; break;
   default:
      xPad = 3; yPad = 2; width = 800; height = 0.7*width; break;
   }
   Int_t noPad = xPad * yPad ;   

   // this defines how many canvases we need
   const Int_t noCanvas = 1 + (Int_t)((noPlots - 0.001)/noPad);
   TCanvas **c = new TCanvas*[noCanvas];
   for (Int_t ic=0; ic<noCanvas; ic++) c[ic] = 0;

   // counter variables
   Int_t countCanvas = 0;
   Int_t countPad    = 1;

   // loop over all objects in directory
   TIter next(vardir->GetListOfKeys());
   TKey *key;
   TH1F *sigCpy=0;
   TH1F *bgdCpy=0;
   //
   Bool_t first = kTRUE;

   while ((key = (TKey*)next())) {

      // make sure, that we only look at histograms
      TClass *cl = gROOT->GetClass(key->GetClassName());
      if (!cl->InheritsFrom("TH1")) continue;
      sig = (TH1F*)key->ReadObj();
      TString hname= sig->GetName();

      // check for all signal histograms
      if (hname.Contains("__S")){ // found a new signal plot
         //         sigCpy = new TH1F(*sig);
         // create new canvas
         if ((c[countCanvas]==NULL) || (countPad>noPad)) {
            char cn[20];
            sprintf( cn, "rulehist%d_", countCanvas+1 );
            TString cname(cn);
            cname += rfdir->GetName();
            c[countCanvas] = new TCanvas( cname, maintitle,
                                          countCanvas*50+200, countCanvas*20, width, height ); 
            // style
            c[countCanvas]->Divide(xPad,yPad);
            countPad = 1;
         }       

         // save canvas to file
         TPad *cPad = (TPad *)(c[countCanvas]->GetPad(countPad));
         c[countCanvas]->cd(countPad);
         countPad++;

         // find the corredponding background histo
         TString bgname = hname;
         bgname.ReplaceAll("__S","__B");
         hkey = vardir->GetKey(bgname);
         bgd = (TH1F*)hkey->ReadObj();
         if (bgd == NULL) {
            cout << "ERROR!!! couldn't find backgroung histo for" << hname << endl;
            exit;
         }

         TString rfname = hname;
         rfname.ReplaceAll("__S","__RF");
         TKey *hrfkey = rfdir->GetKey(rfname);
         TH2F *hrf = (TH2F*)hrfkey->ReadObj();
         Double_t wv = hrf->GetMaximum();
         //         if (rfmax>0.0)
         //            hrf->Scale(1.0/rfmax);
         hrf->SetMinimum(rfmin); // make sure it's zero  -> for palette axis
         hrf->SetMaximum(rfmax); // make sure max is 1.0 -> idem
         hrf->SetContour(nContours,&contourLevels[0]);

         // this is set but not stored during plot creation in MVA_Factory
         //         TMVAGlob::SetSignalAndBackgroundStyle( sigK, bgd );
         sig->SetFillStyle(3002);
         sig->SetFillColor(1);
         sig->SetLineColor(1);
         sig->SetLineWidth(2);

         bgd->SetFillStyle(3554);
         bgd->SetFillColor(1);
         bgd->SetLineColor(1);
         bgd->SetLineWidth(2);

         // chop off "signal" 
         TString title(hrf->GetTitle());
         title.ReplaceAll("signal","");

         // finally plot and overlay       
         Float_t sc = 1.1;
         if (countPad==2) sc = 1.3;
         sig->SetMaximum( TMath::Max( sig->GetMaximum(), bgd->GetMaximum() )*sc );
         Double_t smax = sig->GetMaximum();

         if (first) {
            hrf->SetTitle( maintitle );
            first = kFALSE;
         } else {
            hrf->SetTitle( "" );
         }
         hrf->Draw("colz ah");
         TMVAGlob::SetFrameStyle( hrf, 1.2 );

         sig->Draw("same ah");
         bgd->Draw("same ah");
         // draw axis using range [0,smax]
         hrf->GetXaxis()->SetTitle( title );
         hrf->GetYaxis()->SetTitleOffset( 1.30 );
         hrf->GetYaxis()->SetTitle("Events");
         hrf->GetYaxis()->SetLimits(0,smax);
         hrf->Draw("same axis");

         cPad->SetRightMargin(0.13);
         cPad->Update();

         // Draw legend
         if (countPad==2){
            TLegend *legend= new TLegend( cPad->GetLeftMargin(), 
                                          1-cPad->GetTopMargin()-.18, 
                                          cPad->GetLeftMargin()+.4, 
                                          1-cPad->GetTopMargin() );
            legend->AddEntry(sig,"Signal","F");
            legend->AddEntry(bgd,"Background","F");
            legend->Draw("same");
            legend->SetBorderSize(1);
            legend->SetMargin( 0.3 );
            legend->SetFillColor(19);
            legend->SetFillStyle(1);
         } 

         // save canvas to file
         if (countPad > noPad) {
            c[countCanvas]->Update();
            TString fname = Form( "plots/%s_c%i", outputName.Data(), countCanvas+1 );
            TMVAGlob::imgconv( c[countCanvas], fname );
            //        TMVAGlob::plot_logo(); // don't understand why this doesn't work ... :-(
            countCanvas++;
         }
      }
   }

   if (countPad <= noPad) {
      c[countCanvas]->Update();
      TString fname = Form( "plots/%s_c%i", outputName.Data(), countCanvas+1 );
      TMVAGlob::imgconv( c[countCanvas], fname );
   }
}
示例#6
0
void DoEvolutions( const TString &sim, Int_t time, Int_t Nbins=1, const TString &options="") { 
  
#ifdef __CINT__  
  gSystem->Load("libptools.so");
#endif

  PGlobals::Initialize();
    
  // Palettes!
  gROOT->Macro("PPalettes.C");

  TString opt = options;
  // cout << "options = " << opt << endl;

  // Load PData
  PData *pData = PData::Get(sim.Data());
  pData->LoadFileNames(time);
  if(!pData->IsInit()) return;

  Bool_t CYL = kFALSE;
  if(sim.Contains("cyl")) { CYL = kTRUE; opt += "cyl"; } 
    
  Bool_t ThreeD = kFALSE;
  if(sim.Contains("3D")) ThreeD = kTRUE; 
  
  // Some plasma constants
  Double_t n0 = pData->GetPlasmaDensity();
  Double_t kp = pData->GetPlasmaK();
  Double_t skindepth = 1.0;
  if(kp!=0.0) skindepth = 1/kp;
  Double_t E0 = pData->GetPlasmaE0();

  // Some initial beam properties:
  Float_t Ebeam = pData->GetBeamEnergy() * PUnits::MeV;
  Float_t gamma = pData->GetBeamGamma();
  Float_t vbeam = pData->GetBeamVelocity();
  
  Double_t rms0 = pData->GetBeamRmsY() * kp;
  if(CYL)  rms0 = pData->GetBeamRmsR() * kp;
  
  // Time in OU
  Float_t Time = pData->GetRealTime();
  // z start of the plasma in normalized units.
  Float_t zStartPlasma = pData->GetPlasmaStart() * kp;
  // z start of the beam in normalized units.
  Float_t zStartBeam = pData->GetBeamStart() * kp;
  
  if(opt.Contains("center")) {
    Time -= zStartPlasma;
    if(opt.Contains("comov"))      // Centers on the head of the beam.
      Time += zStartBeam;
  }

  // Beam charge 2D and 1D histogram (on-axis)
  // ------------------------------------------------------------------
  TH2F *hDen2D = NULL;
  if(pData->GetChargeFileName(1)) {
    char hName[24];
    sprintf(hName,"hDen2D");
    hDen2D = (TH2F*) gROOT->FindObject(hName);
    if(hDen2D) { delete hDen2D; hDen2D = NULL; }

    if(!ThreeD)
      hDen2D = pData->GetCharge(1,opt);
    else
      hDen2D = pData->GetCharge2DSliceZY(1,-1,1,opt+"avg");

    hDen2D->SetName(hName);
    hDen2D->GetXaxis()->CenterTitle();
    hDen2D->GetYaxis()->CenterTitle();
    hDen2D->GetZaxis()->CenterTitle();
    
    if(opt.Contains("comov"))
      hDen2D->GetXaxis()->SetTitle("k_{p}#zeta");
    else
      hDen2D->GetXaxis()->SetTitle("k_{p}z");
    
    if(CYL) 
      hDen2D->GetYaxis()->SetTitle("k_{p}r");
    else
      hDen2D->GetYaxis()->SetTitle("k_{p}y");

    hDen2D->GetZaxis()->SetTitle("n_{b}/n_{0}");

 
  }
  
  // Define ranges from the charge 2D histogram:
  // Binning for 2D histograms:
  // We get this values from the 2D density histogram.
  Int_t   x1Nbin    = hDen2D->GetNbinsX();
  Float_t x1Range   = (hDen2D->GetXaxis()->GetXmax() - hDen2D->GetXaxis()->GetXmin());
  Float_t x1Mid     = (hDen2D->GetXaxis()->GetXmax() + hDen2D->GetXaxis()->GetXmin())/2.;
  Float_t x1Min     = hDen2D->GetXaxis()->GetXmin();
  Float_t x1Max     = hDen2D->GetXaxis()->GetXmax();
  
  Int_t   x2Nbin    = hDen2D->GetNbinsY();      
  Float_t x2Range   = (hDen2D->GetYaxis()->GetXmax() - hDen2D->GetYaxis()->GetXmin());
  Float_t x2Mid     = (hDen2D->GetYaxis()->GetXmax() + hDen2D->GetYaxis()->GetXmin())/2.;
  Float_t x2Min     = x2Mid - x2Range/2;
  Float_t x2Max     = x2Mid + x2Range/2;
  
  if(Nbins==0) {
    Nbins = TMath::Nint(rms0 / hDen2D->GetYaxis()->GetBinWidth(1)) ;
    // cout << Form(" Rms0 = %6.2f  Dx = %6.2f  Nbins = %4i .", 
    // 	   rms0, hDen2D->GetYaxis()->GetBinWidth(1), Nbins) << endl;
  }
  
  // Slice width limits.
  Int_t FirstyBin = 0;
  Int_t LastyBin  = 0;
  if(!CYL) {
    FirstyBin = hDen2D->GetNbinsY()/2 + 1 - Nbins;
    LastyBin =  hDen2D->GetNbinsY()/2 + Nbins;
  } else {
    FirstyBin = 1; 
    LastyBin  = Nbins;
  }  


  // OUTPUT ROOT FILE WITH THE PLOTS:
  TString filename = Form("./%s/Plots/Evolutions/Evolutions-%s.root",sim.Data(),sim.Data());
  TFile * ifile = (TFile*) gROOT->GetListOfFiles()->FindObject(filename);
  // if doesn't exist the directory should be created
  if (!ifile) {
    TString f = filename;
    TString dir2 = f.Remove( f.Last( '/' ), f.Length() - f.Last( '/' ) );
    TString dir1 = f.Remove( f.Last( '/' ), f.Length() - f.Last( '/' ) );
    gSystem->mkdir( dir1 );
    gSystem->mkdir( dir2 );
    ifile = new TFile(filename,"UPDATE");
  }  

  
  // Charge 1D histogram on axis
  TH1F *hDen1D = NULL;
  if(pData->GetChargeFileName(1)) {
    TString opth1 = opt;
    opth1 += "avg";
    
    char hName[24];
    sprintf(hName,"hDen1D");
    hDen1D = (TH1F*) gROOT->FindObject(hName);
    if(hDen1D) delete hDen1D;
    
    if(ThreeD) {
      hDen1D = pData->GetH1SliceZ3D(pData->GetChargeFileName(1)->c_str(),"charge",-1,Nbins,-1,Nbins,opth1.Data());
    } else if(CYL) { // Cylindrical: The first bin with r>0 is actually the number 1 (not the 0).
      hDen1D = pData->GetH1SliceZ(pData->GetChargeFileName(1)->c_str(),"charge",1,Nbins,opth1.Data());
    } else { // 2D cartesian
      hDen1D = pData->GetH1SliceZ(pData->GetChargeFileName(1)->c_str(),"charge",-1,Nbins,opth1.Data());
    }
    hDen1D->SetName(hName); 
    
    if(opt.Contains("comov"))
      hDen1D->GetXaxis()->SetTitle("k_{p}#zeta");
    else
      hDen1D->GetXaxis()->SetTitle("k_{p}z");
  
    hDen1D->GetYaxis()->SetTitle("n_{b}/n_{0}");
  }

  // On-axis beam density vs \zeta vs time! _________________________________
  TH2F *hDen1DvsTime = NULL; 
  if(hDen1D) {
    char hName[24];
    sprintf(hName,"hDen1DvsTime");
    TH2F *hDen1DvsTimeOld = (TH2F*) ifile->Get(hName);

    Int_t nBins   = 1;
    Float_t edge0 = Time-0.5;
    Float_t edge1 = Time+0.5;
    if(hDen1DvsTimeOld!=NULL) {
      nBins = hDen1DvsTimeOld->GetNbinsX()+1;
      Float_t binwidth =  (Time - hDen1DvsTimeOld->GetXaxis()->GetBinCenter(1))/(nBins-1);
      edge0 = hDen1DvsTimeOld->GetXaxis()->GetBinCenter(1) - binwidth/2.;
      edge1 = Time + binwidth/2.;
    }
    hDen1DvsTime = new TH2F("temp","",nBins,edge0,edge1,
		       	hDen1D->GetNbinsX(),
			hDen1D->GetBinLowEdge(1),
			hDen1D->GetBinLowEdge(hDen1D->GetNbinsX()+1));
    
    for(Int_t ix=1;ix<hDen1DvsTime->GetNbinsX();ix++) {
      for(Int_t iy=1;iy<hDen1DvsTime->GetNbinsY();iy++) {
	hDen1DvsTime->SetBinContent(ix,iy,hDen1DvsTimeOld->GetBinContent(ix,iy));
      }
    }  
    delete hDen1DvsTimeOld;
  
    // Fill last bin with the newest values.
    for(Int_t iy=1;iy<=hDen1D->GetNbinsX();iy++) {
      hDen1DvsTime->SetBinContent(nBins,iy,hDen1D->GetBinContent(iy));
    }   

    hDen1DvsTime->GetZaxis()->SetTitle("n_{b}/n_{0}");
    hDen1DvsTime->GetYaxis()->SetTitle("k_{p}#zeta");
    hDen1DvsTime->GetXaxis()->SetTitle("k_{p}z");
    hDen1DvsTime->GetZaxis()->CenterTitle();
    hDen1DvsTime->GetYaxis()->CenterTitle();
    hDen1DvsTime->GetXaxis()->CenterTitle();
    hDen1DvsTime->SetName(hName);

    // Change the range of z axis 
    Float_t Denmax = hDen1DvsTime->GetMaximum();
    hDen1DvsTime->GetZaxis()->SetRangeUser(0,Denmax); 
    hDen1DvsTime->Write(hName,TObject::kOverwrite);

  }

  // RMS (vs z) of the beam's charge distribution: 
  TProfile *hDen2Dprof = NULL;
  TH1F *hRms = NULL;
  Double_t axisPos = x2Mid;
  if(hDen2D) {
    TString pname = hDen2D->GetName();
    pname += "_pfx";
    
    hDen2Dprof =  (TProfile*) gROOT->FindObject(pname.Data());
    if(hDen2Dprof) { delete hDen2Dprof; hDen2Dprof = NULL; }
    hDen2Dprof = hDen2D->ProfileX("_pfx",1,-1,"s");
    
    hRms = (TH1F*) gROOT->FindObject("hRms");
    if(hRms) delete hRms;
    
    hRms = new TH1F("hRms","",x1Nbin,x1Min,x1Max);
    
    if(CYL) axisPos = 0.0;
    
    for(Int_t j=0;j<hRms->GetNbinsX();j++) {
      Double_t rms = 0;
      Double_t total = 0;
      for(Int_t k=1;k<=x2Nbin;k++) {
	Double_t value  = hDen2D->GetBinContent(j,k);
	Double_t radius = hDen2D->GetYaxis()->GetBinCenter(k) - axisPos;
	if(CYL) {
	  rms += radius*radius*radius*value;
	  total += radius*value;
	} else {
	  rms += radius*radius*value;
	  total += value;
	}
	// cout << Form(" (%i,%i) -> radius = %7.4f ,  density = %7.4f",j,k,radius,value) << endl;
      }
      
      rms /= total;
      rms = sqrt(rms);
      
      hRms->SetBinContent(j,rms); 
      
    }
    
    hRms->GetXaxis()->SetTitle("k_{p}z");
    if(opt.Contains("comov"))
      hRms->GetXaxis()->SetTitle("k_{p}#zeta");
    
    hRms->GetYaxis()->SetTitle("k_{p}#LTr#GT_{rms}");
  }
  
  // Transverse charge RMS vs \zeta vs time! _________________________________
  TH2F *hRmsvsTime = NULL; 
  if(hRms) {
    char hName[24];
    sprintf(hName,"hRmsvsTime");
    TH2F *hRmsvsTimeOld = (TH2F*) ifile->Get(hName);

    Int_t nBins   = 1;
    Float_t edge0 = Time-0.5;
    Float_t edge1 = Time+0.5;
    if(hRmsvsTimeOld!=NULL) {
      nBins = hRmsvsTimeOld->GetNbinsX()+1;
      Float_t binwidth =  (Time - hRmsvsTimeOld->GetXaxis()->GetBinCenter(1))/(nBins-1);
      edge0 = hRmsvsTimeOld->GetXaxis()->GetBinCenter(1) - binwidth/2.;
      edge1 = Time + binwidth/2.;
    }
    hRmsvsTime = new TH2F("temp","",nBins,edge0,edge1,
		       	hRms->GetNbinsX(),
			hRms->GetBinLowEdge(1),
			hRms->GetBinLowEdge(hRms->GetNbinsX()+1));
    
    for(Int_t ix=1;ix<hRmsvsTime->GetNbinsX();ix++) {
      for(Int_t iy=1;iy<hRmsvsTime->GetNbinsY();iy++) {
	hRmsvsTime->SetBinContent(ix,iy,hRmsvsTimeOld->GetBinContent(ix,iy));
      }
    }  
    delete hRmsvsTimeOld;
  
    // Fill last bin with the newest values.
    for(Int_t iy=1;iy<=hRms->GetNbinsX();iy++) {
      hRmsvsTime->SetBinContent(nBins,iy,hRms->GetBinContent(iy));
    }   

    hRmsvsTime->GetZaxis()->SetTitle("#LTr#GT_{rms}");
    hRmsvsTime->GetYaxis()->SetTitle("k_{p}#zeta");
    hRmsvsTime->GetXaxis()->SetTitle("k_{p}z");
    hRmsvsTime->GetZaxis()->CenterTitle();
    hRmsvsTime->GetYaxis()->CenterTitle();
    hRmsvsTime->GetXaxis()->CenterTitle();
    hRmsvsTime->SetName(hName);

    // Change the range of z axis
    Float_t Rmsmax = hRmsvsTime->GetMaximum();
    hRmsvsTime->GetZaxis()->SetRangeUser(0,Rmsmax); 
    hRmsvsTime->Write(hName,TObject::kOverwrite);

  }

  // INTEGRATED Beam's Charge:
  // Total charge vs time :
  TGraph *gQvsTime = NULL;
  if(hDen2D) {
    Double_t Q = 0;
    for(Int_t i=1;i<=x1Nbin;i++) {
      for(Int_t j=1;j<=x2Nbin;j++) {
	Double_t value  = hDen2D->GetBinContent(i,j);
	if(CYL) {
	  Double_t radius = hDen2D->GetYaxis()->GetBinCenter(j);
	  Q += radius * value;
	  // cout << Form(" (%i,%i) -> radius = %7.4f , value = %7.4f",i,j,radius,value) << endl;
	} else {
	  Q += value;
	}
      }    
    }
    Double_t xbinsize = hDen2D->GetXaxis()->GetBinWidth(1);
    Double_t ybinsize = hDen2D->GetYaxis()->GetBinWidth(1); 
    Q *= xbinsize * ybinsize;
    
    if(!CYL && !ThreeD) {
      Q *= TMath::Sqrt(2*TMath::Pi()) * rms0; 
    } else if(CYL) {
      Q *= 2*TMath::Pi();
    }
    
    if(opt.Contains("units")) {
      Double_t dV = skindepth * skindepth * skindepth;
      Q *= n0 * dV;
      Q *= (PConst::ElectronCharge/PUnits::picocoulomb); 
      cout << Form(" Integrated charge     = %8i pC", TMath::Nint(Q)) << endl;
    } else {
      cout << Form(" Integrated charge     = %8.4f n0 * kp^-3",Q) << endl;
    }
    
    Int_t nPoints = 0;
    char gName[32];
    sprintf(gName,"gQvsTime");     
    gQvsTime = (TGraph*) ifile->Get(gName);
    if(gQvsTime==NULL) {
      gQvsTime = new TGraph();
      gQvsTime->SetName(gName);
      nPoints = 0;
      // Some cosmetics at creation time:
      gQvsTime->SetLineWidth(3);
      gQvsTime->SetLineColor(PGlobals::fieldLine);
      gQvsTime->SetMarkerStyle(20);
      gQvsTime->SetMarkerSize(0.4);
      gQvsTime->SetMarkerColor(PGlobals::fieldLine);	
      gQvsTime->GetYaxis()->SetTitle("charge [n_{0}/k_{p}^{3}]");
      gQvsTime->GetXaxis()->SetTitle("k_{p}z");
    } else {
      nPoints = gQvsTime->GetN(); 
    }  
    
    gQvsTime->Set(nPoints+1);
    gQvsTime->SetPoint(nPoints,Time,Q);
    gQvsTime->Write(gName,TObject::kOverwrite);
  }
  
  // ------------------------------------------------------------------------------------
  

  // Longitudinal phasespace 
  Int_t  gNbin = 100;
  // Float_t gMin = 80;
  // Float_t gMax = 120;
  Float_t gMin = 43.07 - 1.2;
  Float_t gMax = 43.07 + 1.2;
  TH2F *hGvsZ = NULL;
  if(pData->GetRawFileName(1)) {
    char hName[24];
    sprintf(hName,"hGvsZ");
    hGvsZ = (TH2F*) gROOT->FindObject(hName);
    if(hGvsZ) { delete hGvsZ; hGvsZ = NULL; }
    hGvsZ = new TH2F(hName,"",x1Nbin,x1Min,x1Max,gNbin,gMin,gMax);
    pData->GetH2Raw(pData->GetRawFileName(1)->c_str(),"x1","gamma",hGvsZ,opt);
    
    hGvsZ->GetXaxis()->CenterTitle();
    hGvsZ->GetYaxis()->CenterTitle();
    hGvsZ->GetZaxis()->CenterTitle();
    hGvsZ->GetYaxis()->SetTitle("#gamma");
    if(opt.Contains("comov")) {
      hGvsZ->GetXaxis()->SetTitle("k_{p}#zeta");
      hGvsZ->GetZaxis()->SetTitle("dN/d#zetad#gamma [a.u.]");
    }  else {
      hGvsZ->GetXaxis()->SetTitle("k_{p}z");
      hGvsZ->GetZaxis()->SetTitle("dN/dzd#gamma [a.u.]");
    }    
  } else {
    cout << Form("--> No RAW data file is present for species 1") << endl;
  }

  TH2F *hGvsTime = NULL; 
  TProfile *hGvsZprof = NULL;
  TGraphErrors *gGvsZ = NULL;
  if(hGvsZ) {
    TString pname = hGvsZ->GetName();
    pname += "_pfx";
    hGvsZprof =  (TProfile*) gROOT->FindObject(pname.Data());
    if(hGvsZprof) delete hGvsZprof;

    hGvsZprof = hGvsZ->ProfileX("_pfx",1,-1,"s");

    gGvsZ = (TGraphErrors*) gROOT->FindObject("gGvsZ");
    if(gGvsZ) delete gGvsZ;

    Int_t Npoints = hGvsZprof->GetNbinsX();
    Double_t *x = new Double_t[Npoints];
    Double_t *y = new Double_t[Npoints];
    Double_t *ex = new Double_t[Npoints];
    Double_t *ey = new Double_t[Npoints];
    
    for(Int_t j=0;j<Npoints;j++) {
      x[j] = hGvsZprof->GetBinCenter(j);
      y[j] = hGvsZprof->GetBinContent(j);
      ex[j] = 0;
      ey[j] = hGvsZprof->GetBinError(j);   
    }
    
    gGvsZ = new TGraphErrors(Npoints,x,y,ex,ey);
    gGvsZ->SetName("gGvsZ");
        
    // PGlobals::SetH1Style((TH1*)gGvsZ,1);
    PGlobals::SetGraphStyle(gGvsZ,1);

   
    if(opt.Contains("comov")) 
      gGvsZ->GetXaxis()->SetTitle("k_{p}#zeta");
    else
      gGvsZ->GetXaxis()->SetTitle("k_{p}z");
    
    gGvsZ->GetYaxis()->SetTitle("#LT#gamma#GT [MeV]");

    char hName[24];
    sprintf(hName,"hGvsTime");
    TH2F *hGvsTimeOld = (TH2F*) ifile->Get(hName);

    Int_t nBins   = 1;
    Float_t edge0 = Time-0.5;
    Float_t edge1 = Time+0.5;
    if(hGvsTimeOld!=NULL) {
      nBins = hGvsTimeOld->GetNbinsX()+1;
      Float_t binwidth =  (Time - hGvsTimeOld->GetXaxis()->GetBinCenter(1))/(nBins-1);
      edge0 = hGvsTimeOld->GetXaxis()->GetBinCenter(1) - binwidth/2.;
      edge1 = Time + binwidth/2.;
    }
    hGvsTime = new TH2F("temp","",nBins,edge0,edge1,
		       	hGvsZprof->GetNbinsX(),
			hGvsZprof->GetBinLowEdge(1),
			hGvsZprof->GetBinLowEdge(hGvsZprof->GetNbinsX()+1));
    
    for(Int_t ix=1;ix<hGvsTime->GetNbinsX();ix++) {
      for(Int_t iy=1;iy<hGvsTime->GetNbinsY();iy++) {
	hGvsTime->SetBinContent(ix,iy,hGvsTimeOld->GetBinContent(ix,iy));
      }
    }  
    delete hGvsTimeOld;
  
    // Fill last bin with the newest values.
    for(Int_t iy=1;iy<=hGvsZprof->GetNbinsX();iy++) {
      hGvsTime->SetBinContent(nBins,iy,hGvsZprof->GetBinContent(iy));
    }   

    hGvsTime->GetZaxis()->SetTitle("#LT#gamma#GT");
    hGvsTime->GetYaxis()->SetTitle("k_{p}#zeta");
    hGvsTime->GetXaxis()->SetTitle("k_{p}z");
    hGvsTime->GetZaxis()->CenterTitle();
    hGvsTime->GetYaxis()->CenterTitle();
    hGvsTime->GetXaxis()->CenterTitle();
    hGvsTime->SetName(hName);

    // Change the range of z axis
    Float_t Gmax = hGvsTime->GetMaximum();
    Float_t Gmin = hGvsTime->GetMinimum();    
    hGvsTime->GetZaxis()->SetRangeUser(Gmin,Gmax); 
    hGvsTime->Write(hName,TObject::kOverwrite);
    
  }

  // ---------------------------------------------------------------------------------


  // EM fields on - axis :

  TString opth1 = opt;
  opth1 += "avg";
  // Get electric fields
  const Int_t Nfields = 2;
  TH1F **hE1D = new TH1F*[Nfields];
  for(Int_t i=0;i<Nfields;i++) {
    hE1D[i] = NULL;
    if(!pData->GetEfieldFileName(i))
      continue;
    
    char nam[3]; sprintf(nam,"e%i",i+1);
    if(ThreeD) {
      if(i==0) 
	hE1D[i] = pData->GetH1SliceZ3D(pData->GetEfieldFileName(i)->c_str(),nam,-1,Nbins,-1,Nbins,opth1.Data());
      else  
	hE1D[i] = pData->GetH1SliceZ3D(pData->GetEfieldFileName(i)->c_str(),nam,-Nbins,Nbins,-Nbins,Nbins,opth1.Data());
    } else if(CYL) { // Cylindrical: The first bin with r>0 is actually the number 1 (not the 0).
      if(i==0) 
	hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,1,Nbins,opth1.Data());
      else
	hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,1,Nbins,opth1.Data());
    } else { // 2D cartesian
      if(i==0) 
	hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,-1,Nbins,opth1.Data());
      else 
	hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,-Nbins,Nbins,opth1.Data());
    }
    
    char hName[24];
    sprintf(hName,"hE_%i_%i",i,time);
    hE1D[i]->SetName(hName);
    if(opt.Contains("comov"))
      hE1D[i]->GetXaxis()->SetTitle("k_{p}#zeta");
    else
      hE1D[i]->GetXaxis()->SetTitle("k_{p}z");
   
    if(i==0)
      hE1D[i]->GetYaxis()->SetTitle("E_{z}/E_{0}");
    else if(i==1)
      hE1D[i]->GetYaxis()->SetTitle("E_{y}/E_{0}");
    else if(i==2)
      hE1D[i]->GetYaxis()->SetTitle("E_{x}/E_{0}");
    
    hE1D[i]->GetYaxis()->CenterTitle();
    hE1D[i]->GetXaxis()->CenterTitle();
    
  }  
  
  // Calculate wave positions:
  // ----------------------------------------------------------------
    
  // Calculate the crossings and the extremes of the Electric fields
  Float_t Ecross[Nfields][100] = {{0.0}};
  Float_t Eextr[Nfields][100] = {{0.0}};
  Int_t Ncross[Nfields] = {0};

  for(Int_t i=0;i<Nfields;i++) {
    Ncross[i] = 0;
    
    if(!hE1D[i]) continue;
    
    // Only smooths the focusing if flag activated..
    if(i>0 && opt.Contains("smooth")) {
      // cout << " Smoothing fields on axis..." << endl;
      hE1D[i]->Smooth(10);
    } 

    Float_t maxZeta = zStartBeam;
    if(opt.Contains("center")) 
      maxZeta -= zStartBeam;
          
    for(Int_t ip=hE1D[i]->GetNbinsX();ip>1;ip--) {

      Float_t Z2 = hE1D[i]->GetBinCenter(ip-1);
      if(Z2 > maxZeta) continue;
      Float_t E1 = hE1D[i]->GetBinContent(ip);
      Float_t E2 = hE1D[i]->GetBinContent(ip-1);
      Float_t Z1 = hE1D[i]->GetBinCenter(ip);
      
      // cout << Form("Z1 = %6.4f  Z2 = %6.4f   E1 = %6.4f   E2 = %6.4f", Z1, Z2, E1, E2) << endl; 

      if(E1*E2 >= 0) { // No change of sign means we are in a side of the zero axis.
	if(fabs(E2)>fabs(Eextr[i][Ncross[i]])) {
	  Eextr[i][Ncross[i]] = E2;
	} 
      }
      
      if(E1*E2 < 0) { // change of sign means a crossing!
	
	// The next crossing has to be far enough from the previous one:
	Float_t zcross =  -E1 * ( (Z2-Z1)/(E2-E1) ) + Z1;
        if(Ncross[i]>0 && fabs(Ecross[i][Ncross[i]-1]-zcross)<TMath::PiOver2() ) continue;	
	// cout << " CROSS! " << endl;

	// add the point
	Ecross[i][Ncross[i]] = zcross;
	Ncross[i]++;
      }
    }
    
    cout << "  -> Number of crossings for field " << i << " : " << Ncross[i] << endl;
    for(Int_t ic=0;ic<Ncross[i];ic++) {
      //  cout << Form(" %2i:  zeta = %6.4f  E = %6.4f", ic, Ecross[i][ic], Eextr[i][ic]) << endl; 
    }  
    
    
    hE1D[i]->SetLineColor(kRed);
    hE1D[i]->Write(hE1D[i]->GetName(),TObject::kOverwrite);

  }
  
  // Get the Graphs and histos from file
  Int_t nPoints = 0;
  TGraph ***gEcross = new TGraph**[Nfields]; 
  TGraph ***gEextr  = new TGraph**[Nfields]; 
  TH2F **hEvsTime = new TH2F*[Nfields]; 
  for(Int_t i=0;i<Nfields;i++) {
    char hName[24];
    sprintf(hName,"hEvsTime_%i",i);
    TH2F *hEvsTimeOld = (TH2F*) ifile->Get(hName);
    Int_t nBins   = 1;
    Float_t edge0 = Time-0.5;
    Float_t edge1 = Time+0.5;
    if(hEvsTimeOld!=NULL) {
      nBins = hEvsTimeOld->GetNbinsX()+1;
      Float_t binwidth =  (Time - hEvsTimeOld->GetXaxis()->GetBinCenter(1))/(nBins-1);
      edge0 = hEvsTimeOld->GetXaxis()->GetBinCenter(1) - binwidth/2.;
      edge1 = Time + binwidth/2.;
    }
    hEvsTime[i] = new TH2F("temp","",nBins,edge0,edge1,
			hE1D[i]->GetNbinsX(),
			hE1D[i]->GetBinLowEdge(1),
			hE1D[i]->GetBinLowEdge(hE1D[i]->GetNbinsX()+1));
    
    for(Int_t ix=1;ix<hEvsTime[i]->GetNbinsX();ix++) {
      for(Int_t iy=1;iy<hEvsTime[i]->GetNbinsY();iy++) {
	hEvsTime[i]->SetBinContent(ix,iy,hEvsTimeOld->GetBinContent(ix,iy));
      }
    }  
    delete hEvsTimeOld;
  
    // Fill last bin with the newest values.
    for(Int_t iy=1;iy<=hE1D[i]->GetNbinsX();iy++) {
      hEvsTime[i]->SetBinContent(nBins,iy,hE1D[i]->GetBinContent(iy));
    }   

    if(i==0) 
      hEvsTime[i]->GetZaxis()->SetTitle("E_{z}/E_{0}");
    else if(i==1)
      hEvsTime[i]->GetZaxis()->SetTitle("E_{y}/E_{0}");
    else if(i==2)
      hEvsTime[i]->GetZaxis()->SetTitle("E_{x}/E_{0}");
  
    hEvsTime[i]->GetYaxis()->SetTitle("k_{p}#zeta");
    hEvsTime[i]->GetXaxis()->SetTitle("k_{p}z");
    hEvsTime[i]->GetZaxis()->CenterTitle();
    hEvsTime[i]->GetYaxis()->CenterTitle();
    hEvsTime[i]->GetXaxis()->CenterTitle();
    hEvsTime[i]->SetName(hName);

    // Change the range of z axis for the fields to be symmetric.
    Float_t Emax = hEvsTime[i]->GetMaximum();
    Float_t Emin = hEvsTime[i]->GetMinimum();
    if(Emax > TMath::Abs(Emin))
      Emin = -Emax;
    else
      Emax = -Emin;
    hEvsTime[i]->GetZaxis()->SetRangeUser(Emin,Emax); 
    
    hEvsTime[i]->Write(hName,TObject::kOverwrite);

    // ---

    gEcross[i] = new TGraph*[Ncross[i]];
    gEextr[i] = new TGraph*[Ncross[i]];
    char gName[24];
    Int_t ifail = 0;
    for(Int_t ic=0;ic<Ncross[i];ic++) {
      sprintf(gName,"gEcross_%i_%i",i,ic);     
      gEcross[i][ic] = (TGraph*) ifile->Get(gName);
      if(gEcross[i][ic]==NULL) {
	gEcross[i][ic] = new TGraph();
	gEcross[i][ic]->SetName(gName);
	nPoints = 0;
	// Some cosmetics at creation time:
	if(i==1) gEcross[i][ic]->SetLineStyle(2);
	else gEcross[i][ic]->SetLineStyle(1);
	gEcross[i][ic]->SetLineWidth(1);
	gEcross[i][ic]->SetLineColor(kGray+1);
	gEcross[i][ic]->SetMarkerStyle(20);
	gEcross[i][ic]->SetMarkerSize(0.4);
	gEcross[i][ic]->SetMarkerColor(kGray+1);	
	gEcross[i][ic]->GetYaxis()->SetTitle("k_{p}#zeta]");
	gEcross[i][ic]->GetXaxis()->SetTitle("k_{p}z");
      } else {
	nPoints = gEcross[i][ic]->GetN(); 
      }  
      
      // Check the new crossings respect the previous ones:
      // Double_t t,zeta;
      // if(nPoints>0) {
      // 	gEcross[i][ic]->GetPoint(nPoints-1,t,zeta);
      // 	if(fabs(zeta-Ecross[i][ic+ifail])>TMath::Pi()) {
      // 	  ic--;
      // 	  ifail++;
      // 	  continue;
      // 	}
      // }
      
      gEcross[i][ic]->Set(nPoints+1);
      gEcross[i][ic]->SetPoint(nPoints,Time,Ecross[i][ic+ifail]);
      gEcross[i][ic]->Write(gName,TObject::kOverwrite);
      
      // if(ic==Ncross[i]-1) continue;
      
      sprintf(gName,"gEextr_%i_%i",i,ic);     
      gEextr[i][ic] = (TGraph*) ifile->Get(gName);
      if(gEextr[i][ic]==NULL) {
	gEextr[i][ic] = new TGraph();
	gEextr[i][ic]->SetName(gName);
	nPoints = 0;
	// Some cosmetics at creation time:
	if(i==0) {
	  gEextr[i][ic]->SetLineWidth(3);
	  gEextr[i][ic]->SetLineColor(PGlobals::fieldLine);
	  gEextr[i][ic]->SetMarkerStyle(20);
	  gEextr[i][ic]->SetMarkerSize(0.4);
	  gEextr[i][ic]->SetMarkerColor(PGlobals::fieldLine);	
	  gEextr[i][ic]->GetYaxis()->SetTitle("E_{z}/E_{0}");
	  gEextr[i][ic]->GetXaxis()->SetTitle("k_{p}z");
	} else if(i==1) {
	  gEextr[i][ic]->SetLineWidth(1);
	  gEextr[i][ic]->SetLineColor(kGray+2);
	  gEextr[i][ic]->SetMarkerStyle(20);
	  gEextr[i][ic]->SetMarkerSize(0.4);
	  gEextr[i][ic]->SetMarkerColor(kGray+2);	
	  gEextr[i][ic]->GetYaxis()->SetTitle("E_{y}/E_{0}");
	  gEextr[i][ic]->GetXaxis()->SetTitle("k_{p}z");	  
	}
      } else {
	nPoints = gEextr[i][ic]->GetN(); 
      }  
      
      gEextr[i][ic]->Set(nPoints+1);
      gEextr[i][ic]->SetPoint(nPoints,Time,Eextr[i][ic]);
      gEextr[i][ic]->Write(gName,TObject::kOverwrite);
    }
  }

  
  ifile->Close();
  
}
void TSelectionClass::saveHistos()
{
	cout<<"save Histo: "<<hFiducialCutSilicon->GetTitle()<<endl;
	TString name = hFiducialCutSilicon->GetName();
	name.Insert(0,"c");
	TCanvas *c1= fiducialCuts->getAllFiducialCutsCanvas(hFiducialCutSilicon);
	c1->SetName(name);
	histSaver->SaveCanvas(c1);
	delete c1;
	c1 = 0;
    delete hFiducialCutSilicon;

	name = hFiducialCutSiliconDiamondHit->GetName();
	name.Insert(0,"c");
	c1 = fiducialCuts->getAllFiducialCutsCanvas(hFiducialCutSiliconDiamondHit,true);
	c1->SetName(name);
	histSaver->SaveCanvas(c1);
	delete c1;
	c1=0;
    delete hFiducialCutSiliconDiamondHit;

	name = "c";
	name.Append(hFiducialCutSiliconOneAndOnlyOneDiamondHit->GetName());
	c1= fiducialCuts->getAllFiducialCutsCanvas(hFiducialCutSiliconOneAndOnlyOneDiamondHit,true);
	c1->SetName(name);
	histSaver->SaveCanvas(c1);
    delete c1;
    c1=0;
    delete hFiducialCutSiliconOneAndOnlyOneDiamondHit;

	name = "c";
	name.Append(hSelectedEvents->GetName());
	c1 = fiducialCuts->getAllFiducialCutsCanvas(hSelectedEvents,true);
	c1->SetName(name);
	histSaver->SaveCanvas(c1);
    delete c1;
    c1=0;
    delete hSelectedEvents;

    map<Int_t,TH2F*>::iterator it;
    for (it = mapFiducialCutSiliconDiamondHitSamePattern.begin(); it!=mapFiducialCutSiliconDiamondHitSamePattern.end(); it++){
        TH2F* histo = (*it).second;
        name = histo->GetName();
        name.Replace(0,1,"c");
        c1 = fiducialCuts->getAllFiducialCutsCanvas(histo,true);
        c1->SetName(name);
        histSaver->SaveCanvas(c1);
        delete c1;
        c1=0;
        delete histo;
    }
	hAnalysisFraction->Scale(.1);
	hAnalysisFraction->SetStats(false);
	//	hAnalysisFraction->GetYaxis()->SetRangeUser(0,100);
	histSaver->SaveHistogram(hAnalysisFraction);
	delete hAnalysisFraction;


    histSaver->SaveHistogram(hDiamondPatternFiducialPattern);

    histSaver->SaveHistogram(hDiamondPatternFiducialPatternNoMapping);
    name = "stackPatternMapping";
    hDiamondPatternFiducialPattern->SetLineColor(kGreen);
    hDiamondPatternFiducialPatternNoMapping->SetLineColor(kRed);
    THStack *stack = new THStack(name,name);
    stack->Add(hDiamondPatternFiducialPattern);
    stack->Add(hDiamondPatternFiducialPatternNoMapping);
    stack->Draw();
    if(stack->GetXaxis()) stack->GetXaxis()->SetTitle("pattern no.");
    if(stack->GetYaxis()) stack->GetYaxis()->SetTitle("number of entries #");
    histSaver->SaveStack(stack,"hist",true);
    if(stack) delete stack;
    histSaver->SaveHistogram(pDiamondPatternFiducialPatternProfile);
    if(hDiamondPatternFiducialPatternNoMapping) delete hDiamondPatternFiducialPatternNoMapping;
    if(hDiamondPatternFiducialPattern) delete hDiamondPatternFiducialPattern;
    if (pDiamondPatternFiducialPatternProfile) delete pDiamondPatternFiducialPatternProfile;
}
void createCorrectedBackgroundModel(std::string fileName, int nsidebands=6, bool makePlots=false, std::string defaultPrepend="CMS-HGG" ){

     if (makePlots){
       system("mkdir -p BMplots/ada");
       system("mkdir -p BMplots/grad");
       gStyle->SetPalette(1);
       gStyle->SetOptStat(0);
     }

     global_nMassBins=nsidebands;

     double massMin = 120;
     double massMax = 130;
     double dM  = 0.1;
	
     // Open the original Workspace
     TFile *in = TFile::Open(fileName.c_str(),"UPDATE");
     RooWorkspace *work = (RooWorkspace*)in->Get("cms_hgg_workspace");
 
     std::string types[2]={"grad","ada"};

     for (int ty=0;ty<2;ty++){

	std::string type = types[ty];
	// Create An output file for the TF1 Sideband Fits
  	std::string pathToFile=fileName.substr(0,fileName.find(defaultPrepend.c_str()));
 	std::string fName=fileName.substr(fileName.find(defaultPrepend.c_str()),fileName.size());
	TFile *out = new TFile(Form("%sbdtSidebandFits_%s_%s",pathToFile.c_str(),type.c_str(),fName.c_str()),"RECREATE");
	for (double mH=massMin;mH<=massMax;mH+=dM){

		//TH1F *originalHist      = (TH1F*) in->Get(Form("th1f_bkg_%s_%3.1f_cat0",type.c_str(),mH)); // This histogram is normalized to the inclusive fit (will not include VBF cat)
		RooRealVar *nSignalVar = (RooRealVar*)work->var(Form("NBkgInSignal_mH%3.1f",mH));
		TH1F *dataHist  = (TH1F*) in->Get(Form("th1f_data_%s_%3.1f_cat0",type.c_str(),mH)); // Data Histogram, includes VBF category
		int nBins = dataHist->GetNbinsX();

		// Want to make a "corrected" histogram 
		TH1F *correctedHist = new TH1F(Form("th1f_bkg_%s_%3.1f_cat0_fitsb_biascorr",type.c_str(),mH),Form("th1f_bkg_%s_%3.1f_cat0_fitsb_biascorr",type.c_str(),mH),nBins,0,nBins);		     
		TH1F *correctedHistFR = new TH1F(Form("th1f_bkg_%s_%3.1f_cat0_fitsb_biascorr_frac",type.c_str(),mH),Form("th1f_bkg_%s_%3.1f_cat0_fitsb_biascorr_frac",type.c_str(),mH),nBins,0,nBins);		     
      	        TH2F *hFCovar=new TH2F(Form("fCovar_%3.1f",mH),
			 Form("Fraction covariance matrix m %3.1f",mH),
			 nBins,0.0,nBins,nBins,0.0,nBins);
		TH2F *uCorrErr = new TH2F(Form("fUncorrErr_%s_%3.1f",type.c_str(),mH),
			 Form("Uncorrelated Errors m %3.1f",mH),
			 nBins,0.0,nBins,nBins,0.0,nBins);
	
		TDirectory *mass_dir = out->mkdir(Form("mH_%3.1f",mH));

		// For a given mass point, need to set up globals
		global_nBdtBins=nBins;		
		global_mH=mH;
		global_nSignalRegion=nSignalVar->getVal();

		fillData(mH,in,type);
		paulFit(mass_dir,correctedHistFR,correctedHist,hFCovar,makePlots,type);
		
		// Finally Get the uncorrleated errors from the covariance matrix
		diagonalizeMatrix(hFCovar,uCorrErr);

		std::cout << "Final Check of Normalizations at mH="<<mH <<std::endl;
		std::cout << "Original - "<< global_nSignalRegion <<  ", After - " <<correctedHist->Integral() <<std::endl;
		
		// Write out the Hists into the original File
		in->cd();
		correctedHist->Write(correctedHist->GetName(),TObject::kOverwrite);
		correctedHistFR->Write(correctedHistFR->GetName(),TObject::kOverwrite);
		//hFCovar->Write();
		uCorrErr->Write(uCorrErr->GetName(),TObject::kOverwrite);
    out->cd();
    mass_dir->cd();
    uCorrErr->Write(uCorrErr->GetName(),TObject::kOverwrite);

    if (makePlots){
      TCanvas *canv = new TCanvas();
      uCorrErr->SetMarkerColor(kGray);
      gPad->SetRightMargin(2.);
      uCorrErr->Draw("colz text");
      canv->Print(Form("BMplots/%s/uncorrErr_m%3.1f.png",type.c_str(),mH));
      canv->Print(Form("BMplots/%s/uncorrErr_m%3.1f.pdf",type.c_str(),mH));
    }
	}
	std::cout << "Saving Fits to file -> " << out->GetName() << std::endl;
        out->Close();
     }
    
    std::cout << "Updated (with corrected background model) -> " << in->GetName() << std::endl;
    in->Close();
}
示例#9
0
void RunPlots(const char* data_dir, int first_run, const int n_runs) {

  gROOT->Reset();
  gROOT->SetStyle("Plain");
  gStyle->SetCanvasBorderMode(0); // turn off canvas borders

  TCanvas* c1 = new TCanvas("c1", "c1");

  // Go through the runs and create a PDF for each one
  for (int iRun = 0; iRun < n_runs; ++iRun) {

    // Open up the file for this run
    std::stringstream filename;
    filename << data_dir << "/hist/hist0" << first_run + iRun << ".root";
    TFile* file = new TFile(filename.str().c_str(), "READ");

    // Create the output PDF file to save all the plots to
    std::stringstream basepdfname;
    basepdfname << "DQ_LowLevel_RunPlots_Run0" << first_run + iRun << ".pdf";
    
    std::string openpdfname = basepdfname.str() + "[";
    std::string closepdfname = basepdfname.str() + "]";
    c1->Print(openpdfname.c_str());

    TIter nextFileKey(file->GetListOfKeys()); // get the list of keys in this file
    TKey *fileKey;
        
    while (fileKey = (TKey*)nextFileKey()) {

      // Get the directory for low-level data quality plots
      if (strcmp(fileKey->ReadObj()->ClassName(), "TDirectoryFile") == 0) {
	// Check that the directory has the correct name
	if (strcmp(fileKey->ReadObj()->GetName(), "DataQuality_LowLevel") == 0) {

	  TDirectoryFile* dir = (TDirectoryFile*) fileKey->ReadObj();

	  TIter nextDirKey(dir->GetListOfKeys()); // get the list of keys in the directory (all histograms should be in this folder)
	  TKey *dirKey;
        
	  while (dirKey = (TKey*)nextDirKey()) {
	    
	    if (strcmp(dirKey->ReadObj()->ClassName(), "TH1F") == 0) {

	      // Get histogram and print
	      TH1F* hist = (TH1F*) dirKey->ReadObj();
	      hist->Draw();
	      c1->Update();
	      c1->Print(basepdfname.str().c_str());
	    }
	    else if (strcmp(dirKey->ReadObj()->ClassName(), "TH2F") == 0) {

	      TH2F* hist = (TH2F*) dirKey->ReadObj();
	      
	      // Search through the histogram name
	      if (strstr(hist->GetName(), "PulseShapes") != NULL) {
		c1->SetLogz();
	      }

	      hist->Draw("COLZ");
	      c1->Update();
	      c1->Print(basepdfname.str().c_str());
	    } // end if statements

	    // Undo any c1 log scales
	    c1->SetLogz(0);
	  } // end while loop through histograms in directory
	} // end if correctly name directory
      } // end if the key is a directory
    } // end while loop through keys in file

    // Close the PDF file
    c1->Print(closepdfname.c_str());

  } // end loop through each run file
}