int main(int argc, char ** argv) {
	TStopwatch comulativeWatch;
	comulativeWatch.Start(true);
	readInputs(argc,argv);
	cout<<"Currrent Subversion Revision: "<<SVN_REV<<endl;
	cout << "starting main loop.." << endl;
	RunListOK = ReadRunList();
	if(!RunListOK)exit(-1);
	TSystem* sys = gSystem;
	std::string currentDir = sys->pwd();
	for (unsigned int i = 0; i < RunParameters.size(); i++) {
		cout << RunParameters[i].getRunNumber();
		if (i+1 < RunParameters.size()) cout << ", ";
	}
	cout << " will be analysed.." << endl;

	if (!RunListOK) return 0;

	/**Start with Analyising, read RunParameteres of the Run and start analysis with that parameters
	 */
	for (unsigned int i = 0; i < RunParameters.size(); i++) {
		TStopwatch runWatch;
		runWatch.Start(true);
		RunParameters[i].Print();
		bool DO_ALIGNMENT = RunParameters[i].doAlignment();
		bool DO_ALIGNMENTANALYSIS = RunParameters[i].doAlignmentAnalysis();
		bool DO_TRANSPARENT_ANALYSIS = RunParameters[i].doTransparentAnalysis();

		time_t rawtime;
		tm *timestamp;
		time (&rawtime);
		timestamp = gmtime(&rawtime);

		ostringstream logfilename;
		logfilename << "analyse_log_" << RunParameters[i].getRunNumber() << "_" << timestamp->tm_year << "-" << timestamp->tm_mon << "-" << timestamp->tm_mday << "." << timestamp->tm_hour << "." << timestamp->tm_min << "." << timestamp->tm_sec << ".log";
		//
		//		FILE *log;
		//		log = freopen(logfilename.str().c_str(), "w", stdout);


		TSettings *settings = 0;
		cout<<"settings"<<endl;
		settings = new TSettings((TRunInfo*)&RunParameters[i]);

		TResults *currentResults =new TResults(settings);
		currentResults->Print();


		TRawEventSaver *eventSaver;
		eventSaver = new TRawEventSaver(settings);
		eventSaver->saveEvents(RunParameters[i].getEvents());
		delete eventSaver;

		//Calculate Pedestal
		sys->cd(currentDir.c_str());
		TPedestalCalculation* pedestalCalculation;
		pedestalCalculation = new TPedestalCalculation(settings);
		pedestalCalculation->calculateSlidingPedestals(RunParameters[i].getEvents());
		delete pedestalCalculation;

		if(RunParameters[i].doPedestalAnalysis()){
			sys->cd(currentDir.c_str());
			TAnalysisOfPedestal *analysisOfPedestal;
			analysisOfPedestal = new TAnalysisOfPedestal(settings);
			analysisOfPedestal->setResults(currentResults);
			analysisOfPedestal->doAnalysis(RunParameters[i].getEvents());
			delete analysisOfPedestal;
		}

		THTMLGenerator *htmlGen = new THTMLGenerator(settings);
		htmlGen->setFileGeneratingPath(settings->getAbsoluteOuputPath(true));
		htmlGen->setMainPath("./");
		htmlGen->setSubdirPath("");
		htmlGen->setFileName("overview.html");
		htmlGen->addSection("Pedestal","<a href=\"./pedestalAnalysis/pedestal.html\">PEDESTAL</a>");
		htmlGen->addSection("Clustering","<a href=\"./clustering/clustering.html\">CLUSTERING</a>");
		htmlGen->addSection("Selection","<a href=\"./selections/selection.html\">SELECTION</a>");
		htmlGen->addSection("Alignment","<a href=\"./alignment/alignment.html\">ALIGNMENT</a>");
		htmlGen->addSection("Landau","<a href=\"./selectionAnalysis/landaus.html\">LANDAU-DISTRIBUTIONS</a>");
		htmlGen->generateHTMLFile();
		delete htmlGen;

		sys->cd(currentDir.c_str());
		TClustering* clustering;
		clustering=new TClustering(settings);//int seedDetSigma=10,int hitDetSigma=7,int seedDiaSigma=5, int hitDiaSigma=3);
		clustering->ClusterEvents(RunParameters[i].getEvents());
		delete clustering;

		if(RunParameters[i].doClusterAnalysis()){
			sys->cd(currentDir.c_str());
			TAnalysisOfClustering* analysisClustering;
			analysisClustering = new TAnalysisOfClustering(settings);
			analysisClustering->setResults(currentResults);
			analysisClustering->doAnalysis(RunParameters[i].getEvents());
			delete analysisClustering;
		}

		sys->cd(currentDir.c_str());
		TSelectionClass* selectionClass = new TSelectionClass(settings);
		selectionClass->SetResults(currentResults);
		selectionClass->MakeSelection(RunParameters[i].getEvents());
		delete selectionClass;

		if(RunParameters[i].doSelectionAnalysis()){
			sys->cd(currentDir.c_str());
			TAnalysisOfSelection *analysisSelection=new TAnalysisOfSelection(settings);
			analysisSelection->doAnalysis(RunParameters[i].getEvents());
			delete analysisSelection;
		}

		if (DO_ALIGNMENT){
			sys->cd(currentDir.c_str());
			TAlignment *alignment = new TAlignment(settings);
			//			alignment->setSettings(settings);
			//alignment->PrintEvents(1511,1501);
			alignment->Align(RunParameters[i].getEvents());
			delete alignment;
		}

		if(DO_ALIGNMENTANALYSIS){
			sys->cd(currentDir.c_str());
			TAnalysisOfAlignment *anaAlignment;
			anaAlignment=new TAnalysisOfAlignment(settings);
			anaAlignment->doAnalysis(RunParameters[i].getEvents());
			delete anaAlignment;
		}

		if (DO_TRANSPARENT_ANALYSIS) {
			TTransparentAnalysis *transpAna;
			transpAna = new TTransparentAnalysis(settings);
			transpAna->setResults(currentResults);
			transpAna->analyze(RunParameters[i].getEvents(),RunParameters.at(i).getStartEvent());
			delete transpAna;
		}

		if (settings && settings->doTransparentAlignmnet()){
			sys->cd(currentDir.c_str());
			TAlignment *alignment = new TAlignment(settings,TSettings::transparentMode);
			alignment->createTransparentEventVectors(RunParameters[i].getEvents());
			//			alignment->setSettings(settings);
			//alignment->PrintEvents(1511,1501);
			alignment->Align(RunParameters[i].getEvents(),0,TAlignment::diaAlignment);
			delete alignment;

			TTransparentAnalysis *transpAna;
			transpAna = new TTransparentAnalysis(settings,TSettings::transparentMode);
			transpAna->setResults(currentResults);
			transpAna->analyze(RunParameters[i].getEvents(),RunParameters.at(i).getStartEvent());
			delete transpAna;
		}
		cout<<"PRINT RESULTS"<<endl;
		currentResults->Print();
		cout<<"SAVE RESULTS"<<endl;
//		currentResults->saveResults(settings->getResultsRootFilePath());
		TFile* file = new TFile (settings->getResultsRootFilePath().c_str(),"RECREATE");
		file->Print();
		file->ls();
		file->SetName("fileName");
		file->cd();
		cout<<"KEYS: "<<file->GetNkeys()<<endl;
		file->GetListOfKeys()->Print();
		cout<<"Write"<<endl;

		currentResults->Write("test");
		cout<<"CLOSE FILE"<<endl;
		file->Close();
//		if (currentResults){
//			cout<<"DELETE RESULTS"<<endl;
//			delete currentResults;
//			cout<<"#"<<endl;;
//		}
		cout<<"saved results..."<<endl;


		runWatch.Stop();
		cout<<"needed Time for Run "<<RunParameters[i].getRunNumber()<<":"<<endl;
		runWatch.Print();
   
        cout<<"needed Time for Run "<<RunParameters[i].getRunNumber()<<":\n\t"<<flush;
        runWatch.Print();
        if (settings!=NULL){
            cout<<"delete Settings..."<<endl;
            delete settings;
            cout<<"DONE_SETTINGS"<<endl;
                                                           
        }
        cout<<"DONE with Analysis of Run "<< RunParameters[i].getRunNumber();
        cout<<": "<<i+1<<"/"<<RunParameters.size()<<endl;
   }
   cout<<"DONE with Analysis of all "<<RunParameters.size()<<" Runs from RunList.ini"<<endl;
   cout<<"total time for all analysis:\n\t"<<flush;

	cout<<"time for all analysis:"<<endl;
	comulativeWatch.Print();
	cout<<"DONE_ALL"<<endl;

	return 0;
}
Example #2
0
int main ( int argc, char ** argv )
{

  // load framework libraries
  gSystem->Load( "libFWCoreFWLite" );
  AutoLibraryLoader::enable();

  if ( argc < 2 ) {
    std::cout << "Usage : " << argv[0] << " [parameters.py]" << std::endl;
    return 0;
  }

  // Get the python configuration
  PythonProcessDesc builder(argv[1], argc, argv);
  edm::ParameterSet const& shyftParameters = builder.processDesc()->getProcessPSet()->getParameter<edm::ParameterSet>("shyftAnalysis");
  edm::ParameterSet const& inputs = builder.processDesc()->getProcessPSet()->getParameter<edm::ParameterSet>("inputs");
  edm::ParameterSet const& outputs = builder.processDesc()->getProcessPSet()->getParameter<edm::ParameterSet>("outputs");

  // book a set of histograms
  fwlite::TFileService fs = fwlite::TFileService( outputs.getParameter<std::string>("outputName") );
  TFileDirectory theDir = fs.mkdir( "histos" ); 
    
  // This object 'event' is used both to get all information from the
  // event as well as to store histograms, etc.
  fwlite::ChainEvent ev ( inputs.getParameter<std::vector<std::string> > ("fileNames") );

  //cout << "Making event selector" << endl;
  WPlusJetsEventSelector wPlusJets( shyftParameters );
  pat::strbitset ret = wPlusJets.getBitTemplate();
  

  unsigned int nEventsAnalyzed(0);

  // some timing
  TStopwatch timer;
  timer.Start();

  std::cout << "About to loop" << std::endl;
  //loop through each event
  for( ev.toBegin();
       ! ev.atEnd();
       ++ev) {
    ret.set(false);
    //bool passed = wPlusJets(ev, ret);

    ++nEventsAnalyzed;

  } //end event loop

  timer.Stop();

  // print some timing statistics
  Double_t rtime = timer.RealTime();
  Double_t ctime = timer.CpuTime();
  printf("Analyzed events: %d \n",nEventsAnalyzed);
  printf("RealTime=%f seconds, CpuTime=%f seconds\n",rtime,ctime);
  printf("%4.2f events / RealTime second .\n", nEventsAnalyzed/rtime);
  printf("%4.2f events / CpuTime second .\n", nEventsAnalyzed/ctime);


  
  //cout << "Printing" << endl;
  wPlusJets.print(std::cout);
  //cout << "We're done!" << endl;

  
  return 0;
}
Example #3
0
void compute_p0(const char* inFileName,
	    const char* wsName = "combined",
	    const char* modelConfigName = "ModelConfig",
	    const char* dataName = "obsData",
	    const char* asimov1DataName = "asimovData_1",
	    const char* conditional1Snapshot = "conditionalGlobs_1",
	    const char* nominalSnapshot = "nominalGlobs",
	    string smass = "130",
	    string folder = "test")
{
  double mass;
  stringstream massStr;
  massStr << smass;
  massStr >> mass;

  double mu_profile_value = 1; // mu value to profile the obs data at wbefore generating the expected
  bool doConditional      = 1; // do conditional expected data
  bool remakeData         = 0; // handle unphysical pdf cases in H->ZZ->4l
  bool doUncap            = 1; // uncap p0
  bool doInj              = 0; // setup the poi for injection study (zero is faster if you're not)
  bool doObs              = 1; // compute median significance
  bool doMedian           = 1; // compute observed significance

  TStopwatch timer;
  timer.Start();

  TFile f(inFileName);
  RooWorkspace* ws = (RooWorkspace*)f.Get(wsName);
  if (!ws)
  {
    cout << "ERROR::Workspace: " << wsName << " doesn't exist!" << endl;
    return;
  }
  ModelConfig* mc = (ModelConfig*)ws->obj(modelConfigName);
  if (!mc)
  {
    cout << "ERROR::ModelConfig: " << modelConfigName << " doesn't exist!" << endl;
    return;
  }
  RooDataSet* data = (RooDataSet*)ws->data(dataName);
  if (!data)
  {
    cout << "ERROR::Dataset: " << dataName << " doesn't exist!" << endl;
    return;
  }

  mc->GetNuisanceParameters()->Print("v");

  ROOT::Math::MinimizerOptions::SetDefaultMinimizer("Minuit2");
  ROOT::Math::MinimizerOptions::SetDefaultStrategy(0);
  ROOT::Math::MinimizerOptions::SetDefaultPrintLevel(1);
  cout << "Setting max function calls" << endl;

  ws->loadSnapshot("conditionalNuis_0");
  RooArgSet nuis(*mc->GetNuisanceParameters());

  RooRealVar* mu = (RooRealVar*)mc->GetParametersOfInterest()->first();

  RooAbsPdf* pdf = mc->GetPdf();

  string condSnapshot(conditional1Snapshot);
  RooArgSet nuis_tmp2 = *mc->GetNuisanceParameters();
  RooNLLVar* obs_nll = doObs ? (RooNLLVar*)pdf->createNLL(*data, Constrain(nuis_tmp2)) : NULL;

  RooDataSet* asimovData1 = (RooDataSet*)ws->data(asimov1DataName);
  RooRealVar* emb = (RooRealVar*)mc->GetNuisanceParameters()->find("ATLAS_EMB");
  if (!asimovData1 || (string(inFileName).find("ic10") != string::npos && emb))
  {
    if (emb) emb->setVal(0.7);
    cout << "Asimov data doesn't exist! Please, allow me to build one for you..." << endl;
    string mu_str, mu_prof_str;
    asimovData1 = makeAsimovData(mc, doConditional, ws, obs_nll, 1, &mu_str, &mu_prof_str, mu_profile_value, true);
    condSnapshot="conditionalGlobs"+mu_prof_str;
  }
  
  if (!doUncap) mu->setRange(0, 40);
  else mu->setRange(-40, 40);

  RooAbsPdf* pdf = mc->GetPdf();

  RooArgSet nuis_tmp1 = *mc->GetNuisanceParameters();
  RooNLLVar* asimov_nll = (RooNLLVar*)pdf->createNLL(*asimovData1, Constrain(nuis_tmp1));

  //do asimov
  mu->setVal(1);
  mu->setConstant(0);
  if (!doInj) mu->setConstant(1);

  int status,sign;
  double med_sig=0,obs_sig=0,asimov_q0=0,obs_q0=0;

  if (doMedian)
  {
    ws->loadSnapshot(condSnapshot.c_str());
    if (doInj) ws->loadSnapshot("conditionalNuis_inj");
    else ws->loadSnapshot("conditionalNuis_1");
    mc->GetGlobalObservables()->Print("v");
    mu->setVal(0);
    mu->setConstant(1);
    status = minimize(asimov_nll, ws);
    if (status < 0) 
    {
      cout << "Retrying with conditional snapshot at mu=1" << endl;
      ws->loadSnapshot("conditionalNuis_0");
      status = minimize(asimov_nll, ws);
      if (status >= 0) cout << "Success!" << endl;
    }
    double asimov_nll_cond = asimov_nll->getVal();

    mu->setVal(1);
    if (doInj) ws->loadSnapshot("conditionalNuis_inj");
    else ws->loadSnapshot("conditionalNuis_1");
    if (doInj) mu->setConstant(0);
    status = minimize(asimov_nll, ws);
    if (status < 0) 
    {
      cout << "Retrying with conditional snapshot at mu=1" << endl;
      ws->loadSnapshot("conditionalNuis_0");
      status = minimize(asimov_nll, ws);
      if (status >= 0) cout << "Success!" << endl;
    }

    double asimov_nll_min = asimov_nll->getVal();
    asimov_q0 = 2*(asimov_nll_cond - asimov_nll_min);
    if (doUncap && mu->getVal() < 0) asimov_q0 = -asimov_q0;

    sign = int(asimov_q0 != 0 ? asimov_q0/fabs(asimov_q0) : 0);
    med_sig = sign*sqrt(fabs(asimov_q0));

    ws->loadSnapshot(nominalSnapshot);
  }

  if (doObs)
  {

    ws->loadSnapshot("conditionalNuis_0");
    mu->setVal(0);
    mu->setConstant(1);
    status = minimize(obs_nll, ws);
    if (status < 0) 
    {
      cout << "Retrying with conditional snapshot at mu=1" << endl;
      ws->loadSnapshot("conditionalNuis_0");
      status = minimize(obs_nll, ws);
      if (status >= 0) cout << "Success!" << endl;
    }
    double obs_nll_cond = obs_nll->getVal();

    mu->setConstant(0);
    status = minimize(obs_nll, ws);
    if (status < 0) 
    {
      cout << "Retrying with conditional snapshot at mu=1" << endl;
      ws->loadSnapshot("conditionalNuis_0");
      status = minimize(obs_nll, ws);
      if (status >= 0) cout << "Success!" << endl;
    }

    double obs_nll_min = obs_nll->getVal();



    obs_q0 = 2*(obs_nll_cond - obs_nll_min);
    if (doUncap && mu->getVal() < 0) obs_q0 = -obs_q0;

    sign = int(obs_q0 == 0 ? 0 : obs_q0 / fabs(obs_q0));
    if (!doUncap && (obs_q0 < 0 && obs_q0 > -0.1 || mu->getVal() < 0.001)) obs_sig = 0; 
    else obs_sig = sign*sqrt(fabs(obs_q0));
  }

  // Report results
  cout << "obs: " << obs_sig << endl;

  cout << "Observed significance: " << obs_sig << endl;
  cout << "Corresponding to a p-value of " << (1-ROOT::Math::gaussian_cdf( obs_sig )) << endl;
  if (med_sig)
  {
    cout << "Median test stat val: " << asimov_q0 << endl;
    cout << "Median significance:   " << med_sig << endl;
  }


  f.Close();

  stringstream fileName;
  fileName << "root-files/" << folder << "/" << mass << ".root";
  system(("mkdir -vp root-files/" + folder).c_str());
  TFile f2(fileName.str().c_str(),"recreate");

  TH1D* h_hypo = new TH1D("hypo","hypo",2,0,2);
  h_hypo->SetBinContent(1, obs_sig);
  h_hypo->SetBinContent(2, med_sig);

  f2.Write();
  f2.Close();

  timer.Stop();
  timer.Print();
  
}
void DrawFakeEtaBins_reduced(std::string kSpecies="PbPb"){
  timer.Start();

  bool printDebug=false;
   TDatime date;

  std::string kAlgName="ak";
  std::string kSpeciesLong = "pp (PYTHIA)";
  if( kSpecies == "PbPb" ) { kAlgName="akPu";  kSpeciesLong = "PbPb (PYTHIA+HYDJET)"; }
  std::string kjetType="PF";
  
  LoadStyle();
  TH1::SetDefaultSumw2();
  TH2::SetDefaultSumw2();
  TH2F * hBlankRatio = new TH2F("hBlankRatio","",20,-2.1,2.1,50,0,1.0);
  TH2F * hBlankPhiRatio = new TH2F("hBlankPhiRatio","",20,-pi,pi,50,0,1.0);
  TH2F * hBlankPt= new TH2F("hBlankPt","",50,20,350,50,0,1.0);
  TH2F * hBlankPtEff= new TH2F("hBlankPtEff","",50,20,350,50,0.6,1.1);


    TH1F *hPtAll [2][ncen], *hPtEff [2][ncen];
    TH1F *hPtFakeAll[ncen], *hPtFake[2][ncen];
    TH1F *hPtFakeRatio[2][ncen];
    TH1F *hPtAll_etabin[2][ncen][neta], *hPtEff_etabin[2][ncen][neta];    
    TH1F *hPtFakeAll_etabin[ncen][neta], *hPtFake_etabin[2][ncen][neta];
    TH1F *hPtFakeRatio_etabin[2][ncen][neta];   
    TH1F *hPtEffRatio_etabin[2][ncen][neta];     
    TH1F *hPtEffRatio[2][ncen];     
    TH1F *hEtaFakeAll_20[ncen],*hEtaFakeAll_30[ncen], *hEtaFakeAll_40[ncen],*hEtaFakeAll_45[ncen], *hEtaFakeAll_50[ncen], *hEtaFakeAll_60[ncen];
    TH1F *hPhiFakeAll_20[ncen],*hPhiFakeAll_30[ncen], *hPhiFakeAll_40[ncen],*hPhiFakeAll_45[ncen], *hPhiFakeAll_50[ncen], *hPhiFakeAll_60[ncen];
    TH1F *hEtaFake_20[2][ncen],*hEtaFake_30[2][ncen], *hEtaFake_40[2][ncen],*hEtaFake_45[2][ncen], *hEtaFake_50[2][ncen], *hEtaFake_60[2][ncen];
    TH1F *hPhiFake_20[2][ncen],*hPhiFake_30[2][ncen], *hPhiFake_40[2][ncen],*hPhiFake_45[2][ncen], *hPhiFake_50[2][ncen], *hPhiFake_60[2][ncen];  
    TH1F *hEtaFakeRatio_20[2][ncen],*hEtaFakeRatio_30[2][ncen], *hEtaFakeRatio_40[2][ncen],*hEtaFakeRatio_45[2][ncen], *hEtaFakeRatio_50[2][ncen], *hEtaFakeRatio_60[2][ncen];
    TH1F *hPhiFakeRatio_20[2][ncen],*hPhiFakeRatio_30[2][ncen], *hPhiFakeRatio_40[2][ncen],*hPhiFakeRatio_45[2][ncen], *hPhiFakeRatio_50[2][ncen], *hPhiFakeRatio_60[2][ncen];

    TH1F *hEtaFakeRatio_70[2][ncen], *hEtaFakeRatio_80[2][ncen];
    TH1F *hPhiFakeRatio_70[2][ncen], *hPhiFakeRatio_80[2][ncen];
    TH1F *hEtaFakeAll_70[ncen], *hEtaFakeAll_80[ncen];
    TH1F *hPhiFakeAll_70[ncen], *hPhiFakeAll_80[ncen];
    TH1F *hEtaFake_70[2][ncen], *hEtaFake_80[2][ncen];
    TH1F *hPhiFake_70[2][ncen], *hPhiFake_80[2][ncen];
    
  TFile *fin = new TFile(Form("Histos/OutputHist_ntuples_reduced_eta_lt1pt8_%s.root",kSpecies.c_str()),"r");
// radius loop
    for(int nj=0; nj<knj; nj++){
    // i is the with or without jetID loop, NOT the nj loop! 0 == no JetID, 1== JetID
     for(int i=0; i<2; i++){
 // centrality loop    
      for(int ic=0; ic<ncen; ic++){
    	if(i==0){
     	  hPtFakeAll[ic] = (TH1F*)fin->Get(Form("hPtFakeAll_%s_%d",(kAlgName+srad[nj]+kjetType).c_str(),ic)); 
     	  hPtFakeAll[ic]->Print("base");  	  
    	  hEtaFakeAll_20[ic] = (TH1F*)fin->Get(Form("hEtaFakeAll_20_%s_%d",(kAlgName+srad[nj]+kjetType).c_str(),ic)); 
    	  hEtaFakeAll_20[ic]->Print("base");
    	  hPhiFakeAll_20[ic] = (TH1F*)fin->Get(Form("hPhiFakeAll_20_%s_%d",(kAlgName+srad[nj]+kjetType).c_str(),ic)); 
          hPhiFakeAll_20[ic]->Print("base");
    	  hEtaFakeAll_30[ic] = (TH1F*)fin->Get(Form("hEtaFakeAll_30_%s_%d",(kAlgName+srad[nj]+kjetType).c_str(),ic)); 
    	  hEtaFakeAll_30[ic]->Print("base");
    	  hPhiFakeAll_30[ic] = (TH1F*)fin->Get(Form("hPhiFakeAll_30_%s_%d",(kAlgName+srad[nj]+kjetType).c_str(),ic)); 
          hPhiFakeAll_30[ic]->Print("base");
    	  hEtaFakeAll_40[ic] = (TH1F*)fin->Get(Form("hEtaFakeAll_40_%s_%d",(kAlgName+srad[nj]+kjetType).c_str(),ic)); 
    	  hEtaFakeAll_40[ic]->Print("base");
    	  hPhiFakeAll_40[ic] = (TH1F*)fin->Get(Form("hPhiFakeAll_40_%s_%d",(kAlgName+srad[nj]+kjetType).c_str(),ic)); 
          hPhiFakeAll_40[ic]->Print("base");
    	  hEtaFakeAll_45[ic] = (TH1F*)fin->Get(Form("hEtaFakeAll_45_%s_%d",(kAlgName+srad[nj]+kjetType).c_str(),ic)); 
    	  hEtaFakeAll_45[ic] ->Print("base");
    	  hPhiFakeAll_45[ic] = (TH1F*)fin->Get(Form("hPhiFakeAll_45_%s_%d",(kAlgName+srad[nj]+kjetType).c_str(),ic)); 
          hPhiFakeAll_45[ic]->Print("base");
    	  hEtaFakeAll_50[ic] = (TH1F*)fin->Get(Form("hEtaFakeAll_50_%s_%d",(kAlgName+srad[nj]+kjetType).c_str(),ic));
    	  hEtaFakeAll_50[ic]->Print("base"); 
    	  hPhiFakeAll_50[ic] = (TH1F*)fin->Get(Form("hPhiFakeAll_50_%s_%d",(kAlgName+srad[nj]+kjetType).c_str(),ic)); 
    	  hPhiFakeAll_50[ic]->Print("base"); 
    	  hEtaFakeAll_60[ic] = (TH1F*)fin->Get(Form("hEtaFakeAll_60_%s_%d",(kAlgName+srad[nj]+kjetType).c_str(),ic)); 
    	  hEtaFakeAll_60[ic]->Print("base");
    	  hPhiFakeAll_60[ic] = (TH1F*)fin->Get(Form("hPhiFakeAll_60_%s_%d",(kAlgName+srad[nj]+kjetType).c_str(),ic)); 
          hPhiFakeAll_60[ic]->Print("base");
    	  hEtaFakeAll_70[ic] = (TH1F*)fin->Get(Form("hEtaFakeAll_70_%s_%d",(kAlgName+srad[nj]+kjetType).c_str(),ic)); 
    	  hEtaFakeAll_70[ic]->Print("base");
    	  hPhiFakeAll_70[ic] = (TH1F*)fin->Get(Form("hPhiFakeAll_70_%s_%d",(kAlgName+srad[nj]+kjetType).c_str(),ic)); 
          hPhiFakeAll_70[ic]->Print("base");
    	  hEtaFakeAll_80[ic] = (TH1F*)fin->Get(Form("hEtaFakeAll_80_%s_%d",(kAlgName+srad[nj]+kjetType).c_str(),ic)); 
    	  hEtaFakeAll_80[ic]->Print("base");
    	  hPhiFakeAll_80[ic] = (TH1F*)fin->Get(Form("hPhiFakeAll_80_%s_%d",(kAlgName+srad[nj]+kjetType).c_str(),ic)); 
          hPhiFakeAll_80[ic]->Print("base");
           for(int in=0; in<neta; in++){    
              hPtFakeAll_etabin[ic][in] = (TH1F*)fin->Get(Form("hPtFakeAll_etabin_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),ic,in)); 
     	      hPtFakeAll_etabin[ic][in]->Print("base");  
      	  }
   	  
    	}
     	  hPtAll[i][ic] = (TH1F*)fin->Get(Form("hPtAll_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic));
     	  hPtAll[i][ic]->Print("base");    	
    	// end if i=0 (no jetID)
     	hPtEff[i][ic] = (TH1F*)fin->Get(Form("hPtEff_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic)); 
     	hPtEff[i][ic]->Print("base");
    	hPtFake[i][ic] = (TH1F*)fin->Get(Form("hPtFake_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic)); 
        hPtFake[i][ic]->Print("base");
    	hEtaFake_20[i][ic] = (TH1F*)fin->Get(Form("hEtaFake_20_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic)); 
    	hEtaFake_20[i][ic]->Print("base");
    	hPhiFake_20[i][ic] = (TH1F*)fin->Get(Form("hPhiFake_20_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic)); 
        hPhiFake_20[i][ic]->Print("base");
    	hEtaFake_30[i][ic] = (TH1F*)fin->Get(Form("hEtaFake_30_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic)); 
    	hEtaFake_30[i][ic]->Print("base");
    	hPhiFake_30[i][ic] = (TH1F*)fin->Get(Form("hPhiFake_30_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic)); 
        hPhiFake_30[i][ic]->Print("base");
    	hEtaFake_40[i][ic] = (TH1F*)fin->Get(Form("hEtaFake_40_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic)); 
    	hEtaFake_40[i][ic]->Print("base");
    	hPhiFake_40[i][ic] = (TH1F*)fin->Get(Form("hPhiFake_40_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic)); 
        hPhiFake_40[i][ic]->Print("base");
    	hEtaFake_45[i][ic] = (TH1F*)fin->Get(Form("hEtaFake_45_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic)); 
    	hEtaFake_45[i][ic]->Print("base");
    	hPhiFake_45[i][ic] = (TH1F*)fin->Get(Form("hPhiFake_45_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic)); 
        hPhiFake_45[i][ic]->Print("base");
    	hEtaFake_50[i][ic] = (TH1F*)fin->Get(Form("hEtaFake_50_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic)); 
    	hEtaFake_50[i][ic]->Print("base");
    	hPhiFake_50[i][ic] = (TH1F*)fin->Get(Form("hPhiFake_50_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic)); 
   	    hPhiFake_50[i][ic]->Print("base");
    	hEtaFake_60[i][ic] = (TH1F*)fin->Get(Form("hEtaFake_60_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic)); 
    	hEtaFake_60[i][ic]->Print("base");
     	hEtaFake_60[i][ic]->Draw();   	
    	hPhiFake_60[i][ic] = (TH1F*)fin->Get(Form("hPhiFake_60_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic)); 
    	hPhiFake_60[i][ic]->Print("base");
    	hEtaFake_70[i][ic] = (TH1F*)fin->Get(Form("hEtaFake_70_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic)); 
    	hEtaFake_70[i][ic]->Print("base");
     	hEtaFake_70[i][ic]->Draw();   	
    	hPhiFake_70[i][ic] = (TH1F*)fin->Get(Form("hPhiFake_70_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic)); 
    	hPhiFake_70[i][ic]->Print("base");
    	hEtaFake_80[i][ic] = (TH1F*)fin->Get(Form("hEtaFake_80_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic)); 
    	hEtaFake_80[i][ic]->Print("base");
     	hEtaFake_80[i][ic]->Draw();   	
    	hPhiFake_80[i][ic] = (TH1F*)fin->Get(Form("hPhiFake_80_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic)); 
    	hPhiFake_80[i][ic]->Print("base");
    	hEtaFakeRatio_20[i][ic]=(TH1F*)hEtaFake_20[i][ic]->Clone(Form("hEtaFakeRatio_20_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic));
    	hEtaFakeRatio_20[i][ic]->Divide(hEtaFakeAll_20[ic]);
    	hEtaFakeRatio_30[i][ic]=(TH1F*)hEtaFake_30[i][ic]->Clone(Form("hEtaFakeRatio_30_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic));
    	hEtaFakeRatio_30[i][ic]->Divide(hEtaFakeAll_30[ic]);
    	hEtaFakeRatio_30[i][ic]->SetMarkerSize(2.5);
    	hEtaFakeRatio_40[i][ic]=(TH1F*)hEtaFake_40[i][ic]->Clone(Form("hEtaFakeRatio_40_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic));
    	hEtaFakeRatio_40[i][ic]->Divide(hEtaFakeAll_40[ic]);
    	hEtaFakeRatio_40[i][ic]->SetMarkerSize(2.5);
    	hEtaFakeRatio_45[i][ic]=(TH1F*)hEtaFake_45[i][ic]->Clone(Form("hEtaFakeRatio_45_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic));
    	hEtaFakeRatio_45[i][ic]->Divide(hEtaFakeAll_45[ic]);
    	hEtaFakeRatio_50[i][ic]=(TH1F*)hEtaFake_50[i][ic]->Clone(Form("hEtaFakeRatio_50_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic));
    	hEtaFakeRatio_50[i][ic]->Divide(hEtaFakeAll_50[ic]);
    	hEtaFakeRatio_50[i][ic]->SetMarkerSize(2.5);
    	hEtaFakeRatio_60[i][ic]=(TH1F*)hEtaFake_60[i][ic]->Clone(Form("hEtaFakeRatio_60_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic));
    	hEtaFakeRatio_60[i][ic]->Divide(hEtaFakeAll_60[ic]);
    	hEtaFakeRatio_60[i][ic]->SetMarkerSize(2.5);
     	hPhiFakeRatio_20[i][ic]=(TH1F*)hPhiFake_20[i][ic]->Clone(Form("hPhiFakeRatio_20_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic));
    	hPhiFakeRatio_20[i][ic]->Divide(hPhiFakeAll_20[ic]);
    	hPhiFakeRatio_30[i][ic]=(TH1F*)hPhiFake_30[i][ic]->Clone(Form("hPhiFakeRatio_30_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic));
    	hPhiFakeRatio_30[i][ic]->Divide(hPhiFakeAll_30[ic]);
    	hPhiFakeRatio_30[i][ic]->SetMarkerSize(2.5);
    	hPhiFakeRatio_40[i][ic]=(TH1F*)hPhiFake_40[i][ic]->Clone(Form("hPhiFakeRatio_40_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic));
    	hPhiFakeRatio_40[i][ic]->Divide(hPhiFakeAll_40[ic]);
    	hPhiFakeRatio_40[i][ic]->SetMarkerSize(2.5);
    	hPhiFakeRatio_45[i][ic]=(TH1F*)hPhiFake_45[i][ic]->Clone(Form("hPhiFakeRatio_45_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic));
    	hPhiFakeRatio_45[i][ic]->Divide(hPhiFakeAll_45[ic]);
    	hPhiFakeRatio_50[i][ic]=(TH1F*)hPhiFake_50[i][ic]->Clone(Form("hPhiFakeRatio_50_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic));
    	hPhiFakeRatio_50[i][ic]->Divide(hPhiFakeAll_50[ic]);
    	hPhiFakeRatio_50[i][ic]->SetMarkerSize(2.5);
    	hPhiFakeRatio_60[i][ic]=(TH1F*)hPhiFake_60[i][ic]->Clone(Form("hPhiFakeRatio_60_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic));
    	hPhiFakeRatio_60[i][ic]->Divide(hPhiFakeAll_60[ic]);
    	hPhiFakeRatio_60[i][ic]->SetMarkerSize(2.5);
    	hEtaFakeRatio_70[i][ic]=(TH1F*)hEtaFake_70[i][ic]->Clone(Form("hEtaFakeRatio_70_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic));
    	hEtaFakeRatio_70[i][ic]->Divide(hEtaFakeAll_70[ic]);
    	hEtaFakeRatio_70[i][ic]->SetMarkerSize(2.5);
    	hPhiFakeRatio_70[i][ic]=(TH1F*)hPhiFake_70[i][ic]->Clone(Form("hPhiFakeRatio_70_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic));
    	hPhiFakeRatio_70[i][ic]->Divide(hPhiFakeAll_70[ic]);
    	hPhiFakeRatio_70[i][ic]->SetMarkerSize(2.5);
    	hEtaFakeRatio_80[i][ic]=(TH1F*)hEtaFake_80[i][ic]->Clone(Form("hEtaFakeRatio_80_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic));
    	hEtaFakeRatio_80[i][ic]->Divide(hEtaFakeAll_80[ic]);
    	hEtaFakeRatio_80[i][ic]->SetMarkerSize(2.5);
    	hPhiFakeRatio_80[i][ic]=(TH1F*)hPhiFake_80[i][ic]->Clone(Form("hPhiFakeRatio_80_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic));
    	hPhiFakeRatio_80[i][ic]->Divide(hPhiFakeAll_80[ic]);
    	hPhiFakeRatio_80[i][ic]->SetMarkerSize(2.5);
    	    	
    	hPtFakeRatio[i][ic]=(TH1F*)hPtFake[i][ic]->Clone(Form("hPtFakeRatio_%s_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic));
    	hPtFakeRatio[i][ic]->Divide(hPtFakeAll[ic]);    
    	hPtFakeRatio[i][ic]->SetMarkerSize(2.5);	
        for(int in=0; in<neta; in++){
            hPtAll_etabin[i][ic][in] = (TH1F*)fin->Get(Form("hPtAll_etabin_%s_%d_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic,in)); 
     	   hPtAll_etabin[i][ic][in]->Print("base");       
     	   hPtEff_etabin[i][ic][in] = (TH1F*)fin->Get(Form("hPtEff_etabin_%s_%d_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic,in)); 
     	   hPtEff_etabin[i][ic][in]->Print("base");
    	   hPtFake_etabin[i][ic][in] = (TH1F*)fin->Get(Form("hPtFake_etabin_%s_%d_%d_%d",(kAlgName+srad[nj]+kjetType).c_str(),i,ic,in)); 
           hPtFake_etabin[i][ic][in]->Print("base");    	
    	   hPtFakeRatio_etabin[i][ic][in]=(TH1F*)hPtFake_etabin[i][ic][in]->Clone(Form("hPtFakeRatio_etabin%d_%s_%d_%d",in,(kAlgName+srad[nj]+kjetType).c_str(),i,ic));
    	   hPtFakeRatio_etabin[i][ic][in]->Divide(hPtFakeAll_etabin[ic][in]);    
    	   hPtFakeRatio_etabin[i][ic][in]->SetMarkerSize(2.5);	
    	   hPtEffRatio_etabin[i][ic][in]=(TH1F*)hPtEff_etabin[i][ic][in]->Clone(Form("hPtEffRatio_etabin%d_%s_%d",in,(kAlgName+srad[nj]+kjetType).c_str(),ic));
    	   hPtEffRatio_etabin[i][ic][in]->Divide(hPtAll_etabin[i][ic][in]);    
    	   hPtEffRatio_etabin[i][ic][in]->SetMarkerSize(2.5);	
    	}
    	   hPtEffRatio[i][ic]=(TH1F*)hPtEff[i][ic]->Clone(Form("hPtEffRatio_%s_%d",(kAlgName+srad[nj]+kjetType).c_str(),ic));
    	   hPtEffRatio[i][ic]->Divide(hPtAll[i][ic]);    
    	   hPtEffRatio[i][ic]->SetMarkerSize(2.5);	
    	
       }
//  end centrality loop
    	
     } // end i loop (JetID)   
//     if(nj==0){   
//         TCanvas *c0 = new TCanvas();
//         c0.cd();
//     } else {
//     if(nj==1){
//         TCanvas *c1 = new TCanvas();
//         c1.cd();
//     } else {
//     if(nj==2){
//         TCanvas *c2 = new TCanvas();
//         c2.cd();
//     }
    TCanvas * c30 = new TCanvas("c30","",1200,1000);
    TLegend *leg30 = getLegend(0.5,0.5,0.7,0.9);
    leg30->SetHeader("");   
    for(int ic=0; ic<ncen-2; ic++){
       hEtaFakeRatio_30[1][ic]->SetMarkerStyle(24+ic);
       if(ic==0){ hEtaFakeRatio_30[1][ic]->SetMarkerColor(kViolet); hEtaFakeRatio_30[1][ic]->SetLineColor(kViolet);}
       if(ic==1){ hEtaFakeRatio_30[1][ic]->SetMarkerColor(kGreen+1); hEtaFakeRatio_30[1][ic]->SetLineColor(kGreen+1);}
       if(ic==2){ hEtaFakeRatio_30[1][ic]->SetMarkerColor(kRed); hEtaFakeRatio_30[1][ic]->SetLineColor(kRed);}
       if(ic==3){ hEtaFakeRatio_30[1][ic]->SetMarkerColor(kBlue); hEtaFakeRatio_30[1][ic]->SetLineColor(kBlue);}
       if(ic==4){ hEtaFakeRatio_30[1][ic]->SetMarkerColor(kPink);  hEtaFakeRatio_30[1][ic]->SetLineColor(kPink);}
       if(ic==5){ hEtaFakeRatio_30[1][ic]->SetMarkerColor(kYellow); hEtaFakeRatio_30[1][ic]->SetLineColor(kYellow);}
       if(ic==0){
         hBlankRatio->SetTitle(Form(" %s, %s, jetID, pT>30 GeV/c",(kAlgName+srad[nj]+kjetType).c_str(),kSpeciesLong.c_str()));
         hBlankRatio->GetXaxis()->SetTitle("Reco jet eta");
         hBlankRatio->GetYaxis()->SetTitle("Fake rate");
         hBlankRatio->Draw();
       }
       leg30->AddEntry(hEtaFakeRatio_30[1][ic],Form("%s",ccent[ic]),"p");
       hEtaFakeRatio_30[1][ic]->Draw("same");
    }
    leg30->Draw();    
     c30->SaveAs(Form("ANPlots/FakeEtaRate_30_%sMC_JetID_%s_%d.pdf",kSpecies.c_str(),(kAlgName+srad[nj]+kjetType).c_str(),date.GetDate()),"RECREATE");
//          hBlankRatio->SetTitle(Form(" %s, pp (PYTHIA), jetID, pT>30 GeV/c ",(kAlgName+srad[nj]+kjetType).c_str()));
//          hBlankRatio->GetXaxis()->SetTitle("Reco jet eta");
//          hBlankRatio->GetYaxis()->SetTitle("Fake rate");
//          hBlankRatio->Draw(); 
//          leg30->AddEntry(hEtaFakeRatio_30[1][7],Form("%s",ccent[7]),"p"); 
//          hEtaFakeRatio_30[1][7]->Draw("same"); 
//     c30->SaveAs(Form("ANPlots/FakeEtaRate_30_ppMC_JetID_%s_%d.pdf",(kAlgName+srad[nj]+kjetType).c_str(),date.GetDate()),"RECREATE");
    
    TCanvas * c40 = new TCanvas("c40","",1200,1000);
    TLegend *leg40 = getLegend(0.5,0.5,0.7,0.9);
    leg40->SetHeader("");    
    for(int ic=0; ic<ncen-2; ic++){
       hEtaFakeRatio_40[1][ic]->SetMarkerStyle(24+ic);
       if(ic==0){ hEtaFakeRatio_40[1][ic]->SetMarkerColor(kViolet); hEtaFakeRatio_40[1][ic]->SetLineColor(kViolet);}
       if(ic==1){ hEtaFakeRatio_40[1][ic]->SetMarkerColor(kGreen+1); hEtaFakeRatio_40[1][ic]->SetLineColor(kGreen+1);}
       if(ic==2){ hEtaFakeRatio_40[1][ic]->SetMarkerColor(kRed); hEtaFakeRatio_40[1][ic]->SetLineColor(kRed);}
       if(ic==3){ hEtaFakeRatio_40[1][ic]->SetMarkerColor(kBlue); hEtaFakeRatio_40[1][ic]->SetLineColor(kBlue);}
       if(ic==4){ hEtaFakeRatio_40[1][ic]->SetMarkerColor(kPink);  hEtaFakeRatio_40[1][ic]->SetLineColor(kPink);}
       if(ic==5){ hEtaFakeRatio_40[1][ic]->SetMarkerColor(kYellow); hEtaFakeRatio_40[1][ic]->SetLineColor(kYellow);}
       if(ic==0){
         hBlankRatio->SetTitle(Form(" %s, %s, jetID, pT>40 GeV/c",(kAlgName+srad[nj]+kjetType).c_str(),kSpeciesLong.c_str()));
         hBlankRatio->GetXaxis()->SetTitle("Reco jet eta");
         hBlankRatio->GetYaxis()->SetTitle("Fake rate");
         hBlankRatio->Draw();
       }
       leg40->AddEntry(hEtaFakeRatio_40[1][ic],Form("%s",ccent[ic]),"p");
      hEtaFakeRatio_40[1][ic]->Draw("same");
    }
    leg40->Draw();
    c40->SaveAs(Form("ANPlots/FakeEtaRate_40_%sMC_JetID_%s_%d.pdf",kSpecies.c_str(),(kAlgName+srad[nj]+kjetType).c_str(),date.GetDate()),"RECREATE");
//          hBlankRatio->SetTitle(Form(" %s, pp (PYTHIA), jetID, pT>40 GeV/c ",(kAlgName+srad[nj]+kjetType).c_str()));
//          hBlankRatio->GetXaxis()->SetTitle("Reco jet eta");
//          hBlankRatio->GetYaxis()->SetTitle("Fake rate");
//          hBlankRatio->Draw(); 
//          leg40->AddEntry(hEtaFakeRatio_40[1][7],Form("%s",ccent[7]),"p"); 
//          hEtaFakeRatio_40[1][7]->Draw("same"); 
//     c40->SaveAs(Form("ANPlots/FakeEtaRate_40_ppMC_JetID_%s_%d.pdf",(kAlgName+srad[nj]+kjetType).c_str(),date.GetDate()),"RECREATE");
    
    TCanvas * c50 = new TCanvas("c50","",1200,1000);
    TLegend *leg50 = getLegend(0.5,0.5,0.7,0.9);
    leg50->SetHeader("");   
    for(int ic=0; ic<ncen-2; ic++){
       hEtaFakeRatio_50[1][ic]->SetMarkerStyle(24+ic);
       if(ic==0){ hEtaFakeRatio_50[1][ic]->SetMarkerColor(kViolet); hEtaFakeRatio_50[1][ic]->SetLineColor(kViolet);}
       if(ic==1){ hEtaFakeRatio_50[1][ic]->SetMarkerColor(kGreen+1); hEtaFakeRatio_50[1][ic]->SetLineColor(kGreen+1);}
       if(ic==2){ hEtaFakeRatio_50[1][ic]->SetMarkerColor(kRed); hEtaFakeRatio_50[1][ic]->SetLineColor(kRed);}
       if(ic==3){ hEtaFakeRatio_50[1][ic]->SetMarkerColor(kBlue); hEtaFakeRatio_50[1][ic]->SetLineColor(kBlue);}
       if(ic==4){ hEtaFakeRatio_50[1][ic]->SetMarkerColor(kPink);  hEtaFakeRatio_50[1][ic]->SetLineColor(kPink);}
       if(ic==5){ hEtaFakeRatio_50[1][ic]->SetMarkerColor(kYellow); hEtaFakeRatio_50[1][ic]->SetLineColor(kYellow);}
       if(ic==0){
         hBlankRatio->SetTitle(Form(" %s, %s, jetID, pT>50 GeV/c",(kAlgName+srad[nj]+kjetType).c_str(),kSpeciesLong.c_str()));
         hBlankRatio->GetXaxis()->SetTitle("Reco jet eta");
         hBlankRatio->GetYaxis()->SetTitle("Fake rate");
         hBlankRatio->Draw();
       }
       leg50->AddEntry(hEtaFakeRatio_50[1][ic],Form("%s",ccent[ic]),"p");
       hEtaFakeRatio_50[1][ic]->Draw("same");
    }
    leg50->Draw();
    c50->SaveAs(Form("ANPlots/FakeEtaRate_50_%sMC_JetID_%s_%d.pdf",kSpecies.c_str(),(kAlgName+srad[nj]+kjetType).c_str(),date.GetDate()),"RECREATE");
//          hBlankRatio->SetTitle(Form(" %s, pp (PYTHIA), jetID, pT>50 GeV/c ",(kAlgName+srad[nj]+kjetType).c_str()));
//          hBlankRatio->GetXaxis()->SetTitle("Reco jet eta");
//          hBlankRatio->GetYaxis()->SetTitle("Fake rate");
//          hBlankRatio->Draw(); 
//          leg50->AddEntry(hEtaFakeRatio_50[1][7],Form("%s",ccent[7]),"p"); 
//          hEtaFakeRatio_50[1][7]->Draw("same"); 
//     c50->SaveAs(Form("ANPlots/FakeEtaRate_50_ppMC_JetID_%s_%d.pdf",(kAlgName+srad[nj]+kjetType).c_str(),date.GetDate()),"RECREATE");

    TCanvas * c60 = new TCanvas("c60","",1200,1000);
    TLegend *leg60 = getLegend(0.5,0.5,0.7,0.9);
    leg60->SetHeader("");      
    for(int ic=0; ic<ncen-2; ic++){
       hEtaFakeRatio_60[1][ic]->SetMarkerStyle(24+ic);
       if(ic==0){ hEtaFakeRatio_60[1][ic]->SetMarkerColor(kViolet); hEtaFakeRatio_60[1][ic]->SetLineColor(kViolet);}
       if(ic==1){ hEtaFakeRatio_60[1][ic]->SetMarkerColor(kGreen+1); hEtaFakeRatio_60[1][ic]->SetLineColor(kGreen+1);}
       if(ic==2){ hEtaFakeRatio_60[1][ic]->SetMarkerColor(kRed); hEtaFakeRatio_60[1][ic]->SetLineColor(kRed);}
       if(ic==3){ hEtaFakeRatio_60[1][ic]->SetMarkerColor(kBlue); hEtaFakeRatio_60[1][ic]->SetLineColor(kBlue);}
       if(ic==4){ hEtaFakeRatio_60[1][ic]->SetMarkerColor(kPink);  hEtaFakeRatio_60[1][ic]->SetLineColor(kPink);}
       if(ic==5){ hEtaFakeRatio_60[1][ic]->SetMarkerColor(kYellow); hEtaFakeRatio_60[1][ic]->SetLineColor(kYellow);}
       if(ic==0){
         hBlankRatio->SetTitle(Form(" %s, %s, jetID, pT>60 GeV/c",(kAlgName+srad[nj]+kjetType).c_str(),kSpeciesLong.c_str()));
         hBlankRatio->GetXaxis()->SetTitle("Reco jet eta");
         hBlankRatio->GetYaxis()->SetTitle("Fake rate");
         hBlankRatio->Draw();
       }
       leg60->AddEntry(hEtaFakeRatio_60[1][ic],Form("%s",ccent[ic]),"p");
       hEtaFakeRatio_60[1][ic]->Draw("same");  
    }
    leg60->Draw();    
    c60->SaveAs(Form("ANPlots/FakeEtaRate_60_%sMC_JetID_%s_%d.pdf",kSpecies.c_str(),(kAlgName+srad[nj]+kjetType).c_str(),date.GetDate()),"RECREATE");    

    TCanvas * c70 = new TCanvas("c70","",1200,1000);
    TLegend *leg70 = getLegend(0.5,0.5,0.7,0.9);
    leg70->SetHeader("");      
    for(int ic=0; ic<ncen-2; ic++){
       hEtaFakeRatio_70[1][ic]->SetMarkerStyle(24+ic);
       if(ic==0){ hEtaFakeRatio_70[1][ic]->SetMarkerColor(kViolet); hEtaFakeRatio_70[1][ic]->SetLineColor(kViolet);}
       if(ic==1){ hEtaFakeRatio_70[1][ic]->SetMarkerColor(kGreen+1); hEtaFakeRatio_70[1][ic]->SetLineColor(kGreen+1);}
       if(ic==2){ hEtaFakeRatio_70[1][ic]->SetMarkerColor(kRed); hEtaFakeRatio_70[1][ic]->SetLineColor(kRed);}
       if(ic==3){ hEtaFakeRatio_70[1][ic]->SetMarkerColor(kBlue); hEtaFakeRatio_70[1][ic]->SetLineColor(kBlue);}
       if(ic==4){ hEtaFakeRatio_70[1][ic]->SetMarkerColor(kPink);  hEtaFakeRatio_70[1][ic]->SetLineColor(kPink);}
       if(ic==5){ hEtaFakeRatio_70[1][ic]->SetMarkerColor(kYellow); hEtaFakeRatio_70[1][ic]->SetLineColor(kYellow);}
       if(ic==0){
         hBlankRatio->SetTitle(Form(" %s, %s, jetID, pT>70 GeV/c",(kAlgName+srad[nj]+kjetType).c_str(),kSpeciesLong.c_str()));
         hBlankRatio->GetXaxis()->SetTitle("Reco jet eta");
         hBlankRatio->GetYaxis()->SetTitle("Fake rate");
         hBlankRatio->Draw();
       }
       leg70->AddEntry(hEtaFakeRatio_70[1][ic],Form("%s",ccent[ic]),"p");
       hEtaFakeRatio_70[1][ic]->Draw("same");  
    }
    leg70->Draw();    
    c70->SaveAs(Form("ANPlots/FakeEtaRate_70_%sMC_JetID_%s_%d.pdf",kSpecies.c_str(),(kAlgName+srad[nj]+kjetType).c_str(),date.GetDate()),"RECREATE");    

    TCanvas * c80 = new TCanvas("c80","",1200,1000);
    TLegend *leg80 = getLegend(0.5,0.5,0.7,0.9);
    leg80->SetHeader("");      
    for(int ic=0; ic<ncen-2; ic++){
       hEtaFakeRatio_80[1][ic]->SetMarkerStyle(24+ic);
       if(ic==0){ hEtaFakeRatio_80[1][ic]->SetMarkerColor(kViolet); hEtaFakeRatio_80[1][ic]->SetLineColor(kViolet);}
       if(ic==1){ hEtaFakeRatio_80[1][ic]->SetMarkerColor(kGreen+1); hEtaFakeRatio_80[1][ic]->SetLineColor(kGreen+1);}
       if(ic==2){ hEtaFakeRatio_80[1][ic]->SetMarkerColor(kRed); hEtaFakeRatio_80[1][ic]->SetLineColor(kRed);}
       if(ic==3){ hEtaFakeRatio_80[1][ic]->SetMarkerColor(kBlue); hEtaFakeRatio_80[1][ic]->SetLineColor(kBlue);}
       if(ic==4){ hEtaFakeRatio_80[1][ic]->SetMarkerColor(kPink);  hEtaFakeRatio_80[1][ic]->SetLineColor(kPink);}
       if(ic==5){ hEtaFakeRatio_80[1][ic]->SetMarkerColor(kYellow); hEtaFakeRatio_80[1][ic]->SetLineColor(kYellow);}
       if(ic==0){
         hBlankRatio->SetTitle(Form(" %s, %s, jetID, pT>80 GeV/c",(kAlgName+srad[nj]+kjetType).c_str(),kSpeciesLong.c_str()));
         hBlankRatio->GetXaxis()->SetTitle("Reco jet eta");
         hBlankRatio->GetYaxis()->SetTitle("Fake rate");
         hBlankRatio->Draw();
       }
       leg80->AddEntry(hEtaFakeRatio_80[1][ic],Form("%s",ccent[ic]),"p");
       hEtaFakeRatio_80[1][ic]->Draw("same");  
    }
    leg80->Draw();    
    c80->SaveAs(Form("ANPlots/FakeEtaRate_80_%sMC_JetID_%s_%d.pdf",kSpecies.c_str(),(kAlgName+srad[nj]+kjetType).c_str(),date.GetDate()),"RECREATE");    

//          hBlankRatio->SetTitle(Form(" %s, pp (PYTHIA), jetID, pT>60 GeV/c ",(kAlgName+srad[nj]+kjetType).c_str()));
//          hBlankRatio->GetXaxis()->SetTitle("Reco jet eta");
//          hBlankRatio->GetYaxis()->SetTitle("Fake rate");
//          hBlankRatio->Draw(); 
//          leg60->AddEntry(hEtaFakeRatio_60[1][7],Form("%s",ccent[7]),"p"); 
//          hEtaFakeRatio_60[1][7]->Draw("same"); 
//     c60->SaveAs(Form("ANPlots/FakeEtaRate_60_ppMC_JetID_%s_%d.pdf",(kAlgName+srad[nj]+kjetType).c_str(),date.GetDate()),"RECREATE");

// phi plots
    TCanvas * cPhi30 = new TCanvas("cPhi30","",1200,1000);
    TLegend *legPhi30 = getLegend(0.5,0.5,0.7,0.9);
    legPhi30->SetHeader("");   
    for(int ic=0; ic<ncen-2; ic++){
       hPhiFakeRatio_30[1][ic]->SetMarkerStyle(24+ic);
       if(ic==0){ hPhiFakeRatio_30[1][ic]->SetMarkerColor(kViolet); hPhiFakeRatio_30[1][ic]->SetLineColor(kViolet);}
       if(ic==1){ hPhiFakeRatio_30[1][ic]->SetMarkerColor(kGreen+1); hPhiFakeRatio_30[1][ic]->SetLineColor(kGreen+1);}
       if(ic==2){ hPhiFakeRatio_30[1][ic]->SetMarkerColor(kRed); hPhiFakeRatio_30[1][ic]->SetLineColor(kRed);}
       if(ic==3){ hPhiFakeRatio_30[1][ic]->SetMarkerColor(kBlue); hPhiFakeRatio_30[1][ic]->SetLineColor(kBlue);}
       if(ic==4){ hPhiFakeRatio_30[1][ic]->SetMarkerColor(kPink);  hPhiFakeRatio_30[1][ic]->SetLineColor(kPink);}
       if(ic==5){ hPhiFakeRatio_30[1][ic]->SetMarkerColor(kYellow); hPhiFakeRatio_30[1][ic]->SetLineColor(kYellow);}
       if(ic==0){
         hBlankPhiRatio->SetTitle(Form(" %s, %s, jetID, pT>30 GeV/c |eta|<%.2f",(kAlgName+srad[nj]+kjetType).c_str(),kSpeciesLong.c_str(),ketacut));
         hBlankPhiRatio->GetXaxis()->SetTitle("Reco jet Phi");
         hBlankPhiRatio->GetYaxis()->SetTitle("Fake rate");
         hBlankPhiRatio->Draw();
       }
       legPhi30->AddEntry(hPhiFakeRatio_30[1][ic],Form("%s",ccent[ic]),"p");
       hPhiFakeRatio_30[1][ic]->Draw("same");
    }
    legPhi30->Draw();    
    cPhi30->SaveAs(Form("ANPlots/FakePhiRate_30_%sMC_JetID_%s_%d.pdf",kSpecies.c_str(),(kAlgName+srad[nj]+kjetType).c_str(),date.GetDate()),"RECREATE");
    TCanvas * cPhi40 = new TCanvas("cPhi40","",1200,1000);
    TLegend *legPhi40 = getLegend(0.5,0.5,0.7,0.9);
    legPhi40->SetHeader("");    
    for(int ic=0; ic<ncen-2; ic++){
       hPhiFakeRatio_40[1][ic]->SetMarkerStyle(24+ic);
       if(ic==0){ hPhiFakeRatio_40[1][ic]->SetMarkerColor(kViolet); hPhiFakeRatio_40[1][ic]->SetLineColor(kViolet);}
       if(ic==1){ hPhiFakeRatio_40[1][ic]->SetMarkerColor(kGreen+1); hPhiFakeRatio_40[1][ic]->SetLineColor(kGreen+1);}
       if(ic==2){ hPhiFakeRatio_40[1][ic]->SetMarkerColor(kRed); hPhiFakeRatio_40[1][ic]->SetLineColor(kRed);}
       if(ic==3){ hPhiFakeRatio_40[1][ic]->SetMarkerColor(kBlue); hPhiFakeRatio_40[1][ic]->SetLineColor(kBlue);}
       if(ic==4){ hPhiFakeRatio_40[1][ic]->SetMarkerColor(kPink);  hPhiFakeRatio_40[1][ic]->SetLineColor(kPink);}
       if(ic==5){ hPhiFakeRatio_40[1][ic]->SetMarkerColor(kYellow); hPhiFakeRatio_40[1][ic]->SetLineColor(kYellow);}
       if(ic==0){
         hBlankPhiRatio->SetTitle(Form(" %s, %s, jetID, pT>40 GeV/c |eta|<%.2f",(kAlgName+srad[nj]+kjetType).c_str(),kSpeciesLong.c_str(),ketacut));
         hBlankPhiRatio->GetXaxis()->SetTitle("Reco jet Phi");
         hBlankPhiRatio->GetYaxis()->SetTitle("Fake rate");
         hBlankPhiRatio->Draw();
       }
       legPhi40->AddEntry(hPhiFakeRatio_40[1][ic],Form("%s",ccent[ic]),"p");
      hPhiFakeRatio_40[1][ic]->Draw("same");
    }
    legPhi40->Draw();
    cPhi40->SaveAs(Form("ANPlots/FakePhiRate_40_%sMC_JetID_%s_%d.pdf",kSpecies.c_str(),(kAlgName+srad[nj]+kjetType).c_str(),date.GetDate()),"RECREATE");
    TCanvas * cPhi50 = new TCanvas("cPhi50","",1200,1000);
    TLegend *legPhi50 = getLegend(0.5,0.5,0.7,0.9);
    legPhi50->SetHeader("");   
    for(int ic=0; ic<ncen-2; ic++){
       hPhiFakeRatio_50[1][ic]->SetMarkerStyle(24+ic);
       if(ic==0){ hPhiFakeRatio_50[1][ic]->SetMarkerColor(kViolet); hPhiFakeRatio_50[1][ic]->SetLineColor(kViolet);}
       if(ic==1){ hPhiFakeRatio_50[1][ic]->SetMarkerColor(kGreen+1); hPhiFakeRatio_50[1][ic]->SetLineColor(kGreen+1);}
       if(ic==2){ hPhiFakeRatio_50[1][ic]->SetMarkerColor(kRed); hPhiFakeRatio_50[1][ic]->SetLineColor(kRed);}
       if(ic==3){ hPhiFakeRatio_50[1][ic]->SetMarkerColor(kBlue); hPhiFakeRatio_50[1][ic]->SetLineColor(kBlue);}
       if(ic==4){ hPhiFakeRatio_50[1][ic]->SetMarkerColor(kPink);  hPhiFakeRatio_50[1][ic]->SetLineColor(kPink);}
       if(ic==5){ hPhiFakeRatio_50[1][ic]->SetMarkerColor(kYellow); hPhiFakeRatio_50[1][ic]->SetLineColor(kYellow);}
       if(ic==0){
         hBlankPhiRatio->SetTitle(Form(" %s, %s, jetID, pT>50 GeV/c |eta|<%.2f",(kAlgName+srad[nj]+kjetType).c_str(),kSpeciesLong.c_str(),ketacut));
         hBlankPhiRatio->GetXaxis()->SetTitle("Reco jet Phi");
         hBlankPhiRatio->GetYaxis()->SetTitle("Fake rate");
         hBlankPhiRatio->Draw();
       }
       legPhi50->AddEntry(hPhiFakeRatio_50[1][ic],Form("%s",ccent[ic]),"p");
       hPhiFakeRatio_50[1][ic]->Draw("same");
    }
    legPhi50->Draw();
    cPhi50->SaveAs(Form("ANPlots/FakePhiRate_50_%sMC_JetID_%s_%d.pdf",kSpecies.c_str(),(kAlgName+srad[nj]+kjetType).c_str(),date.GetDate()),"RECREATE");
    TCanvas * cPhi60 = new TCanvas("cPhi60","",1200,1000);
    TLegend *legPhi60 = getLegend(0.5,0.5,0.7,0.9);
    legPhi60->SetHeader("");      
    for(int ic=0; ic<ncen-2; ic++){
       hPhiFakeRatio_60[1][ic]->SetMarkerStyle(24+ic);
       if(ic==0){ hPhiFakeRatio_60[1][ic]->SetMarkerColor(kViolet); hPhiFakeRatio_60[1][ic]->SetLineColor(kViolet);}
       if(ic==1){ hPhiFakeRatio_60[1][ic]->SetMarkerColor(kGreen+1); hPhiFakeRatio_60[1][ic]->SetLineColor(kGreen+1);}
       if(ic==2){ hPhiFakeRatio_60[1][ic]->SetMarkerColor(kRed); hPhiFakeRatio_60[1][ic]->SetLineColor(kRed);}
       if(ic==3){ hPhiFakeRatio_60[1][ic]->SetMarkerColor(kBlue); hPhiFakeRatio_60[1][ic]->SetLineColor(kBlue);}
       if(ic==4){ hPhiFakeRatio_60[1][ic]->SetMarkerColor(kPink);  hPhiFakeRatio_60[1][ic]->SetLineColor(kPink);}
       if(ic==5){ hPhiFakeRatio_60[1][ic]->SetMarkerColor(kYellow); hPhiFakeRatio_60[1][ic]->SetLineColor(kYellow);}
       if(ic==0){
         hBlankPhiRatio->SetTitle(Form(" %s, %s, jetID, pT>60 GeV/c |eta|<%.2f",(kAlgName+srad[nj]+kjetType).c_str(),kSpeciesLong.c_str(),ketacut));
         hBlankPhiRatio->GetXaxis()->SetTitle("Reco jet Phi");
         hBlankPhiRatio->GetYaxis()->SetTitle("Fake rate");
         hBlankPhiRatio->Draw();
       }
       legPhi60->AddEntry(hPhiFakeRatio_60[1][ic],Form("%s",ccent[ic]),"p");
       hPhiFakeRatio_60[1][ic]->Draw("same");  
    }
    legPhi60->Draw();    
    cPhi60->SaveAs(Form("ANPlots/FakePhiRate_60_%sMC_JetID_%s_%d.pdf",kSpecies.c_str(),(kAlgName+srad[nj]+kjetType).c_str(),date.GetDate()),"RECREATE"); 
    TCanvas * cPhi70 = new TCanvas("cPhi70","",1200,1000);
    TLegend *legPhi70 = getLegend(0.5,0.5,0.7,0.9);
    legPhi70->SetHeader("");      
    for(int ic=0; ic<ncen-2; ic++){
       hPhiFakeRatio_70[1][ic]->SetMarkerStyle(24+ic);
       if(ic==0){ hPhiFakeRatio_70[1][ic]->SetMarkerColor(kViolet); hPhiFakeRatio_70[1][ic]->SetLineColor(kViolet);}
       if(ic==1){ hPhiFakeRatio_70[1][ic]->SetMarkerColor(kGreen+1); hPhiFakeRatio_70[1][ic]->SetLineColor(kGreen+1);}
       if(ic==2){ hPhiFakeRatio_70[1][ic]->SetMarkerColor(kRed); hPhiFakeRatio_70[1][ic]->SetLineColor(kRed);}
       if(ic==3){ hPhiFakeRatio_70[1][ic]->SetMarkerColor(kBlue); hPhiFakeRatio_70[1][ic]->SetLineColor(kBlue);}
       if(ic==4){ hPhiFakeRatio_70[1][ic]->SetMarkerColor(kPink);  hPhiFakeRatio_70[1][ic]->SetLineColor(kPink);}
       if(ic==5){ hPhiFakeRatio_70[1][ic]->SetMarkerColor(kYellow); hPhiFakeRatio_70[1][ic]->SetLineColor(kYellow);}
       if(ic==0){
         hBlankPhiRatio->SetTitle(Form(" %s, %s, jetID, pT>70 GeV/c |eta|<%.2f",(kAlgName+srad[nj]+kjetType).c_str(),kSpeciesLong.c_str(),ketacut));
         hBlankPhiRatio->GetXaxis()->SetTitle("Reco jet Phi");
         hBlankPhiRatio->GetYaxis()->SetTitle("Fake rate");
         hBlankPhiRatio->Draw();
       }
       legPhi70->AddEntry(hPhiFakeRatio_70[1][ic],Form("%s",ccent[ic]),"p");
       hPhiFakeRatio_70[1][ic]->Draw("same");  
    }
    legPhi70->Draw();    
    cPhi70->SaveAs(Form("ANPlots/FakePhiRate_70_%sMC_JetID_%s_%d.pdf",kSpecies.c_str(),(kAlgName+srad[nj]+kjetType).c_str(),date.GetDate()),"RECREATE"); 
     TCanvas * cPhi80 = new TCanvas("cPhi80","",1200,1000);
    TLegend *legPhi80 = getLegend(0.5,0.5,0.7,0.9);
    legPhi80->SetHeader("");      
    for(int ic=0; ic<ncen-2; ic++){
       hPhiFakeRatio_80[1][ic]->SetMarkerStyle(24+ic);
       if(ic==0){ hPhiFakeRatio_80[1][ic]->SetMarkerColor(kViolet); hPhiFakeRatio_80[1][ic]->SetLineColor(kViolet);}
       if(ic==1){ hPhiFakeRatio_80[1][ic]->SetMarkerColor(kGreen+1); hPhiFakeRatio_80[1][ic]->SetLineColor(kGreen+1);}
       if(ic==2){ hPhiFakeRatio_80[1][ic]->SetMarkerColor(kRed); hPhiFakeRatio_80[1][ic]->SetLineColor(kRed);}
       if(ic==3){ hPhiFakeRatio_80[1][ic]->SetMarkerColor(kBlue); hPhiFakeRatio_80[1][ic]->SetLineColor(kBlue);}
       if(ic==4){ hPhiFakeRatio_80[1][ic]->SetMarkerColor(kPink);  hPhiFakeRatio_80[1][ic]->SetLineColor(kPink);}
       if(ic==5){ hPhiFakeRatio_80[1][ic]->SetMarkerColor(kYellow); hPhiFakeRatio_80[1][ic]->SetLineColor(kYellow);}
       if(ic==0){
         hBlankPhiRatio->SetTitle(Form(" %s, %s, jetID, pT>80 GeV/c |eta|<%.2f",(kAlgName+srad[nj]+kjetType).c_str(),kSpeciesLong.c_str(),ketacut));
         hBlankPhiRatio->GetXaxis()->SetTitle("Reco jet Phi");
         hBlankPhiRatio->GetYaxis()->SetTitle("Fake rate");
         hBlankPhiRatio->Draw();
       }
       legPhi80->AddEntry(hPhiFakeRatio_80[1][ic],Form("%s",ccent[ic]),"p");
       hPhiFakeRatio_80[1][ic]->Draw("same");  
    }
    legPhi80->Draw();    
    cPhi80->SaveAs(Form("ANPlots/FakePhiRate_80_%sMC_JetID_%s_%d.pdf",kSpecies.c_str(),(kAlgName+srad[nj]+kjetType).c_str(),date.GetDate()),"RECREATE"); 
            
    TCanvas * cpT = new TCanvas("cpT","",1200,1000);
    TLegend *legpT = getLegend(0.5,0.5,0.7,0.9);
    legpT->SetHeader("");   
    for(int ic=0; ic<ncen-2; ic++){
       hPtFakeRatio[1][ic]->SetMarkerStyle(24+ic);
       if(ic==0){ hPtFakeRatio[1][ic]->SetMarkerColor(kViolet); hPtFakeRatio[1][ic]->SetLineColor(kViolet);}
       if(ic==1){ hPtFakeRatio[1][ic]->SetMarkerColor(kGreen+1); hPtFakeRatio[1][ic]->SetLineColor(kGreen+1);}
       if(ic==2){ hPtFakeRatio[1][ic]->SetMarkerColor(kRed); hPtFakeRatio[1][ic]->SetLineColor(kRed);}
       if(ic==3){ hPtFakeRatio[1][ic]->SetMarkerColor(kBlue); hPtFakeRatio[1][ic]->SetLineColor(kBlue);}
       if(ic==4){ hPtFakeRatio[1][ic]->SetMarkerColor(kPink);  hPtFakeRatio[1][ic]->SetLineColor(kPink);}
       if(ic==5){ hPtFakeRatio[1][ic]->SetMarkerColor(kYellow); hPtFakeRatio[1][ic]->SetLineColor(kYellow);}
       if(ic==0){
         hBlankPt->SetTitle(Form(" %s, %s, jetID",(kAlgName+srad[nj]+kjetType).c_str(),kSpeciesLong.c_str()));
         hBlankPt->GetXaxis()->SetTitle(Form("Reco jet pT (GeV/c) |eta|<%.2f",ketacut));
         hBlankPt->GetYaxis()->SetTitle("Fake rate");
         hBlankPt->Draw();
       }
       legpT->AddEntry(hPtFakeRatio[1][ic],Form("%s",ccent[ic]),"p");
       hPtFakeRatio[1][ic]->Draw("same");
    }
    legpT->Draw();    
     cpT->SaveAs(Form("ANPlots/FakeRatepT_%sMC_JetID_%s_%d.pdf",kSpecies.c_str(),(kAlgName+srad[nj]+kjetType).c_str(),date.GetDate()),"RECREATE");
     
    TCanvas * cpT_etabin = new TCanvas("cpT_etabin","",1200,1000);
    TLegend *legpT_etabin = getLegend(0.5,0.5,0.7,0.9);
    legpT_etabin->SetHeader("");   
    for(int ic=0; ic<ncen-2; ic++){
       hPtFakeRatio_etabin[1][ic][0]->SetMarkerStyle(24+ic);
       if(ic==0){ hPtFakeRatio_etabin[1][ic][0]->SetMarkerColor(kViolet); hPtFakeRatio_etabin[1][ic][0]->SetLineColor(kViolet);}
       if(ic==1){ hPtFakeRatio_etabin[1][ic][0]->SetMarkerColor(kGreen+1); hPtFakeRatio_etabin[1][ic][0]->SetLineColor(kGreen+1);}
       if(ic==2){ hPtFakeRatio_etabin[1][ic][0]->SetMarkerColor(kRed); hPtFakeRatio_etabin[1][ic][0]->SetLineColor(kRed);}
       if(ic==3){ hPtFakeRatio_etabin[1][ic][0]->SetMarkerColor(kBlue); hPtFakeRatio_etabin[1][ic][0]->SetLineColor(kBlue);}
       if(ic==4){ hPtFakeRatio_etabin[1][ic][0]->SetMarkerColor(kPink);  hPtFakeRatio_etabin[1][ic][0]->SetLineColor(kPink);}
       if(ic==5){ hPtFakeRatio_etabin[1][ic][0]->SetMarkerColor(kYellow); hPtFakeRatio_etabin[1][ic][0]->SetLineColor(kYellow);}
       if(ic==0){
         hBlankPt->SetTitle(Form(" %s, %s, jetID",(kAlgName+srad[nj]+kjetType).c_str(),kSpeciesLong.c_str()));
         hBlankPt->GetXaxis()->SetTitle(Form("Reco jet pT (GeV/c) %s",seta[0]));
         hBlankPt->GetYaxis()->SetTitle("Fake rate");
         hBlankPt->Draw();
       }
       legpT_etabin->AddEntry(hPtFakeRatio_etabin[1][ic][0],Form("%s",ccent[ic]),"p");
       hPtFakeRatio_etabin[1][ic][0]->Draw("same");
    }
    legpT_etabin->Draw();    
     cpT_etabin->SaveAs(Form("ANPlots/FakeRatepT_etabin%d_%sMC_JetID_%s_%d.pdf",0,kSpecies.c_str(),(kAlgName+srad[nj]+kjetType).c_str(),date.GetDate()),"RECREATE");
     
    TCanvas * cpT_eff_etabin = new TCanvas("cpT_eff_etabin","",1200,1000);
    TLegend *legpT_eff_etabin = getLegend(0.5,0.5,0.3,0.7);
    legpT_eff_etabin->SetHeader("");   
    for(int ic=0; ic<ncen-2; ic++){
       hPtEffRatio_etabin[0][ic][0]->SetMarkerStyle(24+ic);
       if(ic==0){ hPtEffRatio_etabin[0][ic][0]->SetMarkerColor(kViolet); hPtEffRatio_etabin[0][ic][0]->SetLineColor(kViolet);}
       if(ic==1){ hPtEffRatio_etabin[0][ic][0]->SetMarkerColor(kGreen+1); hPtEffRatio_etabin[0][ic][0]->SetLineColor(kGreen+1);}
       if(ic==2){ hPtEffRatio_etabin[0][ic][0]->SetMarkerColor(kRed); hPtEffRatio_etabin[0][ic][0]->SetLineColor(kRed);}
       if(ic==3){ hPtEffRatio_etabin[0][ic][0]->SetMarkerColor(kBlue); hPtEffRatio_etabin[0][ic][0]->SetLineColor(kBlue);}
       if(ic==4){ hPtEffRatio_etabin[0][ic][0]->SetMarkerColor(kPink);  hPtEffRatio_etabin[0][ic][0]->SetLineColor(kPink);}
       if(ic==5){ hPtEffRatio_etabin[0][ic][0]->SetMarkerColor(kYellow); hPtEffRatio_etabin[0][ic][0]->SetLineColor(kYellow);}
       if(ic==0){
         hBlankPtEff->SetTitle(Form(" %s, %s",(kAlgName+srad[nj]+kjetType).c_str(),kSpeciesLong.c_str()));
         hBlankPtEff->GetXaxis()->SetTitle(Form("Reco jet pT (GeV/c) %s",seta[0]));
         hBlankPtEff->GetYaxis()->SetTitle("Efficiency");
         hBlankPtEff->Draw();
       }
       legpT_eff_etabin->AddEntry(hPtEffRatio_etabin[0][ic][0],Form("%s",ccent[ic]),"p");
       hPtEffRatio_etabin[0][ic][0]->Draw("same");
    }
    legpT_eff_etabin->Draw();    
     cpT_eff_etabin->SaveAs(Form("ANPlots/EfficiencypT_eff_etabin%d_%sMC_noJetID_%s_%d.pdf",0,kSpecies.c_str(),(kAlgName+srad[nj]+kjetType).c_str(),date.GetDate()),"RECREATE");

    TCanvas * cpT_eff = new TCanvas("cpT_eff","",1200,1000);
    TLegend *legpT_eff = getLegend(0.5,0.5,0.3,0.7);
    legpT_eff->SetHeader("");   
    for(int ic=0; ic<ncen-2; ic++){
       hPtEffRatio[0][ic]->SetMarkerStyle(24+ic);
       if(ic==0){ hPtEffRatio[0][ic]->SetMarkerColor(kViolet); hPtEffRatio[0][ic]->SetLineColor(kViolet);}
       if(ic==1){ hPtEffRatio[0][ic]->SetMarkerColor(kGreen+1); hPtEffRatio[0][ic]->SetLineColor(kGreen+1);}
       if(ic==2){ hPtEffRatio[0][ic]->SetMarkerColor(kRed); hPtEffRatio[0][ic]->SetLineColor(kRed);}
       if(ic==3){ hPtEffRatio[0][ic]->SetMarkerColor(kBlue); hPtEffRatio[0][ic]->SetLineColor(kBlue);}
       if(ic==4){ hPtEffRatio[0][ic]->SetMarkerColor(kPink);  hPtEffRatio[0][ic]->SetLineColor(kPink);}
       if(ic==5){ hPtEffRatio[0][ic]->SetMarkerColor(kYellow); hPtEffRatio[0][ic]->SetLineColor(kYellow);}
       if(ic==0){
         hBlankPtEff->SetTitle(Form(" %s, %s",(kAlgName+srad[nj]+kjetType).c_str(),kSpeciesLong.c_str()));
         hBlankPtEff->GetXaxis()->SetTitle(Form("Reco jet pT (GeV/c) |eta|<%.2f",ketacut));
         hBlankPtEff->GetYaxis()->SetTitle("Efficiency");
         hBlankPtEff->Draw();
       }
       legpT_eff->AddEntry(hPtEffRatio[0][ic],Form("%s",ccent[ic]),"p");
       hPtEffRatio[0][ic]->Draw("same");
    }
    legpT_eff->Draw();    
     cpT_eff->SaveAs(Form("ANPlots/EfficiencypT_etaLt2_%sMC_noJetID_%s_%d.pdf",kSpecies.c_str(),(kAlgName+srad[nj]+kjetType).c_str(),date.GetDate()),"RECREATE");

    } // end nj loop (radius)
    
} // end program
Example #5
0
void global_reco(Int_t nEvents = 100, Int_t seed = 555)
{
	gRandom->SetSeed(seed);

   TTree::SetMaxTreeSize(90000000000);
   TString script = TString(gSystem->Getenv("LIT_SCRIPT"));
   TString parDir = TString(gSystem->Getenv("VMCWORKDIR")) + TString("/parameters");

   // Input and output data
   TString dir = "events/much_anna_omega_8gev_10k/"; // Output directory
   TString mcFile = dir + "mc.0000.root"; // MC transport file
   TString parFile = dir + "param.0000.root"; // Parameters file
   TString globalRecoFile = dir + "global.reco.0000.root"; // Output file with reconstructed tracks and hits

   // Digi files
   TList* parFileList = new TList();
   TObjString stsDigiFile = parDir + "/sts/sts_v12b_std.digi.par"; // STS digi file
   TObjString trdDigiFile = parDir + "/trd/trd_v13g.digi.par"; // TRD digi file
   TString muchDigiFile = parDir + "/much/much_v12c.digi.root"; // MUCH digi file
   TString stsMatBudgetFile = parDir + "/sts/sts_matbudget_v12b.root";
   TObjString tofDigiFile = parDir + "/tof/tof_v13b.digi.par";// TOF digi file

   // Reconstruction parameters
   TString globalTrackingType = "nn"; // Global tracking type
   TString trdHitProducerType = "smearing"; // TRD hit producer type: smearing, digi, clustering
   TString muchHitProducerType = "advanced"; // MUCH hit producer type: simple, advanced

   if (script == "yes") {
      mcFile = TString(gSystem->Getenv("LIT_MC_FILE"));
      parFile = TString(gSystem->Getenv("LIT_PAR_FILE"));
      globalRecoFile = TString(gSystem->Getenv("LIT_GLOBAL_RECO_FILE"));

      stsDigiFile = TString(gSystem->Getenv("LIT_STS_DIGI"));
      trdDigiFile = TString(gSystem->Getenv("LIT_TRD_DIGI"));
      muchDigiFile = TString(gSystem->Getenv("LIT_MUCH_DIGI"));
      tofDigiFile = TString(gSystem->Getenv("LIT_TOF_DIGI"));
      stsMatBudgetFile = TString(gSystem->Getenv("LIT_STS_MAT_BUDGET_FILE"));
   }

   parFileList->Add(&stsDigiFile);
   parFileList->Add(&trdDigiFile);
   parFileList->Add(&tofDigiFile);

	Int_t iVerbose = 1;
	TStopwatch timer;
	timer.Start();

	gROOT->LoadMacro("$VMCWORKDIR/macro/littrack/loadlibs.C");
	loadlibs();

	FairRunAna *run = new FairRunAna();
   run->SetInputFile(mcFile);
	run->SetOutputFile(globalRecoFile);


   // -----   STS  -------------------------------------------------
   Double_t threshold = 4;
   Double_t noiseWidth = 0.01;
   Int_t nofBits = 12;
   Double_t ElectronsPerAdc =  10.;
   Double_t StripDeadTime = 0.1;
   CbmStsDigitize* stsDigitize = new CbmStsDigitize("STS Digitiser", iVerbose);
   stsDigitize->SetRealisticResponse();
   stsDigitize->SetFrontThreshold(threshold);
   stsDigitize->SetBackThreshold(threshold);
   stsDigitize->SetFrontNoiseWidth(noiseWidth);
   stsDigitize->SetBackNoiseWidth(noiseWidth);
   stsDigitize->SetFrontNofBits(nofBits);
   stsDigitize->SetBackNofBits(nofBits);
   stsDigitize->SetFrontNofElPerAdc(ElectronsPerAdc);
   stsDigitize->SetBackNofElPerAdc(ElectronsPerAdc);
   stsDigitize->SetStripDeadTime(StripDeadTime);
   run->AddTask(stsDigitize);

   FairTask* stsClusterFinder = new CbmStsClusterFinder("STS Cluster Finder",iVerbose);
   run->AddTask(stsClusterFinder);

   FairTask* stsFindHits = new CbmStsFindHits("STS Hit Finder", iVerbose);
   run->AddTask(stsFindHits);

   FairTask* stsMatchHits = new CbmStsMatchHits("STS Hit Matcher", iVerbose);
   run->AddTask(stsMatchHits);

   FairTask* kalman = new CbmKF();
   run->AddTask(kalman);
   CbmL1* l1 = new CbmL1();
   //l1->SetExtrapolateToTheEndOfSTS(true);
   l1->SetMaterialBudgetFileName(stsMatBudgetFile);
   run->AddTask(l1);
   CbmStsTrackFinder* trackFinder = new CbmL1StsTrackFinder();
   FairTask* findTracks = new CbmStsFindTracks(iVerbose, trackFinder);
   run->AddTask(findTracks);

   FairTask* stsMatchTracks = new CbmStsMatchTracks("STSMatchTracks", iVerbose);
   run->AddTask(stsMatchTracks);
	// ------------------------------------------------------------------------

   if (IsMuch(parFile)) {
      // -------- MUCH digitization ------------
      CbmMuchDigitizeGem* digitize = new CbmMuchDigitizeGem(muchDigiFile.Data());
      if (muchHitProducerType == "simple") {
         digitize->SetAlgorithm(0);
      } else if (muchHitProducerType == "advanced") {
         digitize->SetAlgorithm(1);
      }
      run->AddTask(digitize);
      CbmMuchFindHitsGem* findHits = new CbmMuchFindHitsGem(muchDigiFile.Data());
      run->AddTask(findHits);

      CbmMuchDigitizeStraws* strawDigitize = new CbmMuchDigitizeStraws("MuchDigitizeStraws", muchDigiFile.Data(), iVerbose);
      run->AddTask(strawDigitize);
      CbmMuchFindHitsStraws* strawFindHits = new CbmMuchFindHitsStraws("MuchFindHitsStraws", muchDigiFile.Data(), iVerbose);
      strawFindHits->SetMerge(1);
      run->AddTask(strawFindHits);
      // -----------------------------------------------------------------
   }

   if (IsTrd(parFile)) {
      // ----- TRD reconstruction-----------------------------------------
      // Update of the values for the radiator F.U. 17.08.07
      Int_t trdNFoils = 130; // number of polyetylene foils
      Float_t trdDFoils = 0.0013; // thickness of 1 foil [cm]
      Float_t trdDGap = 0.02; // thickness of gap between foils [cm]
      Bool_t simpleTR = kTRUE; // use fast and simple version for TR production

      CbmTrdRadiator *radiator = new CbmTrdRadiator(simpleTR, trdNFoils, trdDFoils, trdDGap);

      if (trdHitProducerType == "smearing") {
         CbmTrdHitProducerSmearing* trdHitProd = new CbmTrdHitProducerSmearing(radiator);
         trdHitProd->SetUseDigiPar(false);
         run->AddTask(trdHitProd);
      } else if (trdHitProducerType == "digi") {
         CbmTrdDigitizer* trdDigitizer = new CbmTrdDigitizer(radiator);
         run->AddTask(trdDigitizer);

         CbmTrdHitProducerDigi* trdHitProd = new CbmTrdHitProducerDigi();
         run->AddTask(trdHitProd);
      } else if (trdHitProducerType == "clustering") {
         // ----- TRD clustering -----
         CbmTrdDigitizerPRF* trdClustering = new CbmTrdDigitizerPRF("TRD Clusterizer", "TRD task", radiator, false, true);
         run->AddTask(trdClustering);

         CbmTrdClusterFinderFast* trdClusterfindingfast = new CbmTrdClusterFinderFast(true, true, false, 5.0e-7);
         run->AddTask(trdClusterfindingfast);

         CbmTrdHitProducerCluster* trdClusterHitProducer = new CbmTrdHitProducerCluster();
         run->AddTask(trdClusterHitProducer);
         // ----- End TRD Clustering -----
      }
      // ------------------------------------------------------------------------
   }

   if (IsTof(parFile)) {
      // ------ TOF hits --------------------------------------------------------
      CbmTofHitProducerNew* tofHitProd = new CbmTofHitProducerNew("TOF HitProducerNew",iVerbose);
      tofHitProd->SetInitFromAscii(kFALSE);
      run->AddTask(tofHitProd);
      // ------------------------------------------------------------------------
   }

   // ------ Global track reconstruction -------------------------------------
   CbmLitFindGlobalTracks* finder = new CbmLitFindGlobalTracks();
   //CbmLitFindGlobalTracksParallel* finder = new CbmLitFindGlobalTracksParallel();
   // Tracking method to be used
   // "branch" - branching tracking
   // "nn" - nearest neighbor tracking
   // "nn_parallel" - nearest neighbor parallel tracking
   finder->SetTrackingType(std::string(globalTrackingType));

   // Hit-to-track merger method to be used
   // "nearest_hit" - assigns nearest hit to the track
   finder->SetMergerType("nearest_hit");

   run->AddTask(finder);

   if (IsTrd(parFile)) {
      CbmTrdMatchTracks* trdMatchTracks = new CbmTrdMatchTracks();
      run->AddTask(trdMatchTracks);
   }

   if (IsMuch(parFile)) {
      CbmMuchMatchTracks* muchMatchTracks = new CbmMuchMatchTracks();
      run->AddTask(muchMatchTracks);
   }

   // -----   Primary vertex finding   --------------------------------------
   CbmPrimaryVertexFinder* pvFinder = new CbmPVFinderKF();
   CbmFindPrimaryVertex* findVertex = new CbmFindPrimaryVertex(pvFinder);
   run->AddTask(findVertex);
   // -----------------------------------------------------------------------

	// -----  Parameter database   --------------------------------------------
	FairRuntimeDb* rtdb = run->GetRuntimeDb();
	FairParRootFileIo* parIo1 = new FairParRootFileIo();
	FairParAsciiFileIo* parIo2 = new FairParAsciiFileIo();
	parIo1->open(parFile.Data());
	parIo2->open(parFileList, "in");
	rtdb->setFirstInput(parIo1);
	rtdb->setSecondInput(parIo2);
	rtdb->setOutput(parIo1);
	rtdb->saveOutput();
	// ------------------------------------------------------------------------

	// -----   Initialize and run   --------------------------------------------
	run->Init();
	run->Run(0, nEvents);
	// ------------------------------------------------------------------------

	// -----   Finish   -------------------------------------------------------
	timer.Stop();
 	cout << "Macro finished successfully." << endl;
   cout << "Test passed"<< endl;
   cout << " All ok " << endl;
	cout << "Output file is " << globalRecoFile << endl;
	cout << "Parameter file is " << parFile << endl;
	cout << "Real time " << timer.RealTime() << " s, CPU time "	<< timer.CpuTime() << " s" << endl;
	// ------------------------------------------------------------------------
}
void chi2_lambda_stack_mumue(){
  TStopwatch totaltime;
  totaltime.Start();
  int sample, isPU, ischi2;
  
  TChain *chain_mu[N_chain];
  TChain *chain_el[N_chain];
  TChain *chain_jet[N_chain];
  TChain *chain_event[N_chain];
  
  cout << "==========================" << endl
  << "40, 50, 60, 100(no gen lvl info) : signal" << endl
  << "==========================" << endl
  << "Run : ";
  cin >> sample;
  cout << endl;
  
  cout << "==========================" << endl
  << "PileUP? (0 = no, 1 = yes) : ";
  cin >> isPU;
  cout << "==========================" << endl
  << "chi2 fit? (0 = no, 1 = yes) :";
  cin >> ischi2;
  cout << endl;

  /*
  /// [0] = Signal ///
  chain_mu[0] = new TChain("Muon");
  chain_el[0] = new TChain("Electron");
  chain_event[0] = new TChain("Event");
  chain_mu[0]->Add("./files/signal/trilepton_mumue_SKHN"+TString::Itoa(sample, 10)+"_lep_5_3_14.root");
  chain_el[0]->Add("./files/signal/trilepton_mumue_SKHN"+TString::Itoa(sample, 10)+"_lep_5_3_14.root");
  chain_event[0]->Add("./files/signal/trilepton_mumue_SKHN"+TString::Itoa(sample, 10)+"_lep_5_3_14.root");
  */
  
  /// [1] = Data ///
  chain_mu[1] = new TChain("Muon");
  chain_el[1] = new TChain("Electron");
  chain_event[1] = new TChain("Event");
  chain_jet[1] = new TChain("Jet");
  chain_mu[1]->Add("./files/data/*.root");
  chain_el[1]->Add("./files/data/*.root");
  chain_event[1]->Add("./files/data/*.root");
  chain_jet[1]->Add("./files/data/*.root");
  
  /// [2]~ = Bkg ///
  TString chainlist[N_chain] = {"signal", "data",
                                "DY10to50", "DY50plus", "Zbb",  // DY
                                "WZtollln_mg", "WZtollqq_mg", "WZtoqqln_mg", "ZZtollll_mg", "ZZtollnn_mg", "ZZtollqq_mg", "WW_mg",  // VV
                                "Wbb", // Wjets
                                "topDIL", // Top
                                "TTG", "TTWW", "WWG", "WWW", "WWZ", "WZZ", "ZZZ", "ttZ", "HtoWW", "Wtollln"}; // others
  for(int i=2; i<N_chain; i++){
    chain_mu[i] = new TChain("Muon");
    chain_el[i] = new TChain("Electron");
    chain_event[i] = new TChain("Event");
    chain_jet[i] = new TChain("Jet");
    chain_mu[i]->Add("./files/bkg/trilepton_mumue_SK"+chainlist[i]+"_5_3_14.root");
    chain_el[i]->Add("./files/bkg/trilepton_mumue_SK"+chainlist[i]+"_5_3_14.root");
    chain_event[i]->Add("./files/bkg/trilepton_mumue_SK"+chainlist[i]+"_5_3_14.root");
    chain_jet[i]->Add("./files/bkg/trilepton_mumue_SK"+chainlist[i]+"_5_3_14.root");
  }
  
  Muon *mu[N_chain];
  Electron *el[N_chain];
  Event *evt[N_chain];
  Jet *jet[N_chain];
           
  double MET, METphi, nu_Pz, W_mass_fit, MET_fit, weight, PUweight_sum;
  int N_entry, HN_x_min=0, HN_x_max=100, HN_dx=10, W_x_min=70, W_x_max=120, W_dx=5, solution_selection, smaller;
  struct Fit fitresult[2];
  Color_t fillcolors[N_chain] = {0, kRed-5, // signal and data. data random color
    kAzure-5, kAzure-5, kAzure-5,
    kGreen-5, kGreen-5, kGreen-5, kGreen-5, kGreen-5, kGreen-5, kGreen-5,
    kYellow-5,
    kRed-5,
    kGreen-10, kGreen-10, kGreen-10, kGreen-10, kGreen-10, kGreen-10, kGreen-10, kGreen-10, kGreen-10, kOrange-4};
  double gamma_star_bin[16];
  TString gamma_star_bin_label[15];
  for(int i=0; i<15; i++){
    gamma_star_bin[i] = 0.5*i;
    if(i%2==0) gamma_star_bin_label[i] = "";
    else      gamma_star_bin_label[i] = "            "+TString::Itoa(i/2+1, 10)+".0";
    //cout << gamma_star_bin[i] << '\t' << gamma_star_bin_label[i] << endl;
  }
  gamma_star_bin[15] = 8;
  gamma_star_bin_label[14] = "        > 7.0 GeV";
  
  TH1D *hist_dimuon[N_chain];
  
  TH1D *hist_dimuon_err = new TH1D("hist_dimuon_err", "", (50.-0.)/1., 0., 50.);
  
  THStack *bkgstack_dimuon = new THStack("bkgstack_dimuon", "");
  
  TLorentzVector mu_4vec[2], el_4vec, W_real, HN, nu, gen_nu, gamma_star, z_candidate, selection_nu[2];

  for(int k=1; k<N_chain; k++){
    N_entry = 0;
    PUweight_sum=0;
    
    mu[k] = new Muon(chain_mu[k], 2);
    el[k] = new Electron(chain_el[k], 1);
    jet[k] = new Jet(chain_jet[k], 4);
    evt[k] = new Event(chain_event[k]);
 
    hist_dimuon[k] = new TH1D("hist_dimuon"+TString::Itoa(k,10), "", (50.-0.)/1., 0., 50.);

    
    cout << endl << "Running Sample : " << chainlist[k] << endl;
    
  
    for(int i=0; i<chain_mu[k]->GetEntries(); i++){
      
      printeventnumber(i, chain_mu[k]->GetEntries());
      
      chain_mu[k]->GetEntry(i);
      chain_el[k]->GetEntry(i);
      chain_jet[k]->GetEntry(i);
      chain_event[k]->GetEntry(i);
      
      if( mu[k]->isHNLooseMuon(0) && mu[k]->isHNLooseMuon(1)){
      //if( mu[k]->PassID("TightMuon", 0) && mu[k]->PassID("TightMuon", 1) && mu[k]->PassID("TightMuon", 2) ){
      //if( mu[k]->isHNTightMuon(0) && mu[k]->isHNTightMuon(1) && mu[k]->isHNTightMuon(2) ){
      //if( 1 ){ // NoHNLoose cut
        mu_4vec[0].SetPxPyPzE(mu[k]->Px[0],mu[k]->Py[0],mu[k]->Pz[0],mu[k]->E[0]);
        mu_4vec[1].SetPxPyPzE(mu[k]->Px[1],mu[k]->Py[1],mu[k]->Pz[1],mu[k]->E[1]);
        el_4vec.SetPxPyPzE(el[k]->Px[0],el[k]->Py[0],el[k]->Pz[0],el[k]->E[0]);

        MET = evt[k]->MET;
        METphi = evt[k]->METphi;
        nu.SetPxPyPzE(MET*TMath::Cos(METphi), MET*TMath::Sin(METphi), 0, 0);
        
        if(ischi2){
          fit(&fitresult[0], 3, 1000, mu_4vec[0]+mu_4vec[1]+el_4vec[0], MET, METphi, "m");
          fit(&fitresult[1], 3, 1000, mu_4vec[0]+mu_4vec[1]+el_4vec[0], MET, METphi, "p"); // 0 = minus, 1 = plus
          PutNuPz(&selection_nu[0], fitresult[0].Pz_fit);
          PutNuPz(&selection_nu[1], fitresult[1].Pz_fit);
        }
        else{
          PutNuPz(&selection_nu[0], solveqdeq(80.4, mu_4vec[0]+mu_4vec[1]+el_4vec[0], MET, METphi, "m"));
          PutNuPz(&selection_nu[1], solveqdeq(80.4, mu_4vec[0]+mu_4vec[1]+el_4vec[0], MET, METphi, "p")); // 0 = minus, 1 = plus
        }
        
        if( selection_nu[0].Pz() == selection_nu[1].Pz() ){
          solution_selection = 0; // 0, 1 상관 없으므로
        }
        else{
          if(fabs(selection_nu[0].Pz()) > fabs(selection_nu[1].Pz())){
            smaller = 1;
          }
          else{
            smaller = 0;
          }
          
          solution_selection = smaller;
        }
        
        if(!isPU) weight = evt[k]->weight;
        else      weight = evt[k]->weight * evt[k]->PU_reweight; // pileup weight
        
        if(mu[k]->Charge[0] != mu[k]->Charge[1] && evt[k]->n_bjet>=1 && jet[k]->n_Jet>=1){
        //if(mu[k]->Charge[0] != mu[k]->Charge[1] && mu[0].DeltaR(mu[1]) < 1.0){
          N_entry++;
          PUweight_sum+=evt[k]->PU_reweight;
          hist_dimuon[k]->Fill( (mu_4vec[0]+mu_4vec[1]).M(), weight );
          
        } // additional cuts
      } // Object Selection
    } // event loop
    
    cout << "weight = " << evt[k]->weight << endl
    << "entry = " << N_entry << endl
    << "PUweight = " << PUweight_sum/(double)N_entry << endl;
    
    /// apply weight after filling histogram ///
    //hist_HN[k]->Scale(weight);
    //hist_W_real[k]->Scale(weight);
    //hist_dR[k]->Scale(weight);
    //hist_gamma_star[k]->Scale(weight);
    
    /*
     if(k==4){ // Add two DY process
     hist_HN[4]->Add(hist_HN[3]);
     hist_W_real[4]->Add(hist_W_real[3]);
     }
     */
    
    hist_dimuon[k]->SetFillColor(fillcolors[k]);
    
    /// merging same-type histograms
    if(k>=15 && k<=22){
      hist_dimuon[14]->Add(hist_dimuon[k]);
    }
    if(k>=6 && k<=11){
      hist_dimuon[5]->Add(hist_dimuon[k]);
    }
    if(k==3 || k==4){
      hist_dimuon[2]->Add(hist_dimuon[k]);
    }
    if(k==14 || k==23 || k==5 || k==12 || k==13 || k==2){
      bkgstack_dimuon->Add(hist_dimuon[k]);
    }
    if(k>=2){
      hist_dimuon_err->Add(hist_dimuon[k]);
    }
  } // chain loop
  
  Double_t totalRuntime = totaltime.CpuTime();
  cout << "\n----------Total Runtime: " << totalRuntime << " seconds----------\n" << endl;
  
  gStyle->SetOptStat(0);
  
  /// dimuon ///
  TCanvas *c1 = new TCanvas("c1", "", 800, 600);
  c1->cd();
  ///bkg///
  bkgstack_dimuon->Draw("hist");
  bkgstack_dimuon->SetMaximum(100); // 100 for dR_W, 70 for chi2_lambda
  bkgstack_dimuon->SetTitle("Dimuon(OS) Invariant Mass");
  //bkgstack_dimuon->GetXaxis()->SetTitle("m(#mu_{2}#mu_{3}#nu) [GeV]");
  bkgstack_dimuon->GetYaxis()->SetTitle("Event / 1 GeV");
  ///data///
  hist_dimuon[1]->SetMarkerStyle(3);
  hist_dimuon[1]->SetMarkerSize(1);
  hist_dimuon[1]->Draw("APsameE1");
  ///signal///
  //hist_dimuon[0]->SetLineColor(kRed);
  //hist_dimuon[0]->Draw("histsame");
  ///err///
  //hist_dimuon_err->SetFillStyle(3004);
  //hist_dimuon_err->SetFillColor(kBlue);
  //hist_dimuon_err->Draw("sameE2");
  ///legend///
  TLegend *lg1 = new TLegend(0.65, 0.6, 0.9, 0.9);
  lg1->AddEntry(hist_dimuon[1], "data", "p");
  //lg1->AddEntry(hist_dimuon[0], "HN"+TString::Itoa(sample, 10)+", |V_{N#mu}|^{2}=10^{"+TString::Itoa(TMath::Log10(coupling_const), 10)+"}", "l");
  lg1->AddEntry(hist_dimuon[2], "DY", "f");
  lg1->AddEntry(hist_dimuon[13], "top", "f");
  lg1->AddEntry(hist_dimuon[5], "VV", "f");
  lg1->AddEntry(hist_dimuon[23], "Wtollln", "f");
  lg1->AddEntry(hist_dimuon[12], "Wjets", "f");
  lg1->AddEntry(hist_dimuon[14], "other", "f");
  lg1->Draw();
}
Example #7
0
void jeteta2() 
{   
  TString sysname ="JETETA.root";
  TFile *sysinput(0);
  sysinput = TFile::Open( sysname ); // if not: download from ROOT server
  std::vector<string> variables_;
  TString name;
  variables_.push_back("BDT__zjethist");
//  variables_.push_back("BDT__phjethist");
  variables_.push_back("BDT__tbartchhist");
  variables_.push_back("BDT__tt3hist");
  variables_.push_back("BDT__ttphhist");
  variables_.push_back("BDT__wwphhist");
  variables_.push_back("BDT__zzhist");
  variables_.push_back("BDT__zgammahist");
  variables_.push_back("BDT__singleantitopphotonhist");

std::vector<TH1F*> addhists;
std::vector<TH1F*> wjetandwphjet;

wjetandwphjet.push_back((TH1F*) sysinput->Get((std::string("BDT__wjet").c_str())));
wjetandwphjet.push_back((TH1F*) sysinput->Get((std::string("BDT__wphjethist").c_str())));

std::vector<TH1F*> jesuphists;
for(unsigned int i=0; i<variables_.size(); ++i){
name=variables_[i]+"__JES__plus";
jesuphists.push_back((TH1F*) sysinput->Get(name));
}
//jesuphists.push_back((TH1F*) sysinput->Get((std::string("BDT__wjet").c_str())));
//jesuphists.push_back((TH1F*) sysinput->Get((std::string("BDT__wphjethist").c_str())));
for(unsigned int idx=1; idx<variables_.size(); ++idx){
jesuphists[idx]->Add(jesuphists[idx-1]);
}
addhists.push_back(jesuphists[variables_.size()-1]);

std::vector<TH1F*> jesdownhists;
for(unsigned int i=0; i<variables_.size(); ++i){
name=variables_[i]+"__JES__minus";
jesdownhists.push_back((TH1F*) sysinput->Get(name));}
for(unsigned int idx=1; idx<variables_.size(); ++idx){
jesdownhists[idx]->Add(jesdownhists[idx-1]);}
addhists.push_back(jesdownhists[variables_.size()-1]);

std::vector<TH1F*> jeruphists;
for(unsigned int i=0; i<variables_.size(); ++i){
name=variables_[i]+"__JER__plus";
jeruphists.push_back((TH1F*) sysinput->Get(name));}
for(unsigned int idx=1; idx<variables_.size(); ++idx){
jeruphists[idx]->Add(jeruphists[idx-1]);}
addhists.push_back(jeruphists[variables_.size()-1]);

std::vector<TH1F*> jerdownhists;
for(unsigned int i=0; i<variables_.size(); ++i){
name=variables_[i]+"__JER__minus";
jerdownhists.push_back((TH1F*) sysinput->Get(name));}
for(unsigned int idx=1; idx<variables_.size(); ++idx){
jerdownhists[idx]->Add(jerdownhists[idx-1]);}
addhists.push_back(jerdownhists[variables_.size()-1]);

std::vector<TH1F*> phesuphists;
for(unsigned int i=0; i<variables_.size(); ++i){
name=variables_[i]+"__PhES__plus";
phesuphists.push_back((TH1F*) sysinput->Get(name));}
for(unsigned int idx=1; idx<variables_.size(); ++idx){
phesuphists[idx]->Add(phesuphists[idx-1]);}
addhists.push_back(phesuphists[variables_.size()-1]);

std::vector<TH1F*> phesdownhists;
for(unsigned int i=0; i<variables_.size(); ++i){
name=variables_[i]+"__PhES__minus";
phesdownhists.push_back((TH1F*) sysinput->Get(name));}
for(unsigned int idx=1; idx<variables_.size(); ++idx){
phesdownhists[idx]->Add(phesdownhists[idx-1]);}
addhists.push_back(phesdownhists[variables_.size()-1]);

std::vector<TH1F*> puuphists;
for(unsigned int i=0; i<variables_.size(); ++i){
name=variables_[i]+"__PU__plus";
puuphists.push_back((TH1F*) sysinput->Get(name));}
for(unsigned int idx=1; idx<variables_.size(); ++idx){
puuphists[idx]->Add(puuphists[idx-1]);}
addhists.push_back(puuphists[variables_.size()-1]);

std::vector<TH1F*> pudownhists;
for(unsigned int i=0; i<variables_.size(); ++i){
name=variables_[i]+"__PU__minus";
pudownhists.push_back((TH1F*) sysinput->Get(name));}
for(unsigned int idx=1; idx<variables_.size(); ++idx){
pudownhists[idx]->Add(pudownhists[idx-1]);}
addhists.push_back(pudownhists[variables_.size()-1]);

std::vector<TH1F*> triguphists;
for(unsigned int i=0; i<variables_.size(); ++i){
name=variables_[i]+"__TRIG__plus";
triguphists.push_back((TH1F*) sysinput->Get(name));}
for(unsigned int idx=1; idx<variables_.size(); ++idx){
triguphists[idx]->Add(triguphists[idx-1]);}
addhists.push_back(triguphists[variables_.size()-1]);

std::vector<TH1F*> trigdownhists;
for(unsigned int i=0; i<variables_.size(); ++i){
name=variables_[i]+"__TRIG__minus";
trigdownhists.push_back((TH1F*) sysinput->Get(name));}
for(unsigned int idx=1; idx<variables_.size(); ++idx){
trigdownhists[idx]->Add(trigdownhists[idx-1]);}
addhists.push_back(trigdownhists[variables_.size()-1]);

std::vector<TH1F*> btaguphists;
for(unsigned int i=0; i<variables_.size(); ++i){
name=variables_[i]+"__BTAG__plus";
btaguphists.push_back((TH1F*) sysinput->Get(name));}
for(unsigned int idx=1; idx<variables_.size(); ++idx){
btaguphists[idx]->Add(btaguphists[idx-1]);}
addhists.push_back(btaguphists[variables_.size()-1]);

std::vector<TH1F*> btagdownhists;
for(unsigned int i=0; i<variables_.size(); ++i){
name=variables_[i]+"__BTAG__minus";
btagdownhists.push_back((TH1F*) sysinput->Get(name));}
for(unsigned int idx=1; idx<variables_.size(); ++idx){
btagdownhists[idx]->Add(btagdownhists[idx-1]);}
addhists.push_back(btagdownhists[variables_.size()-1]);

std::vector<TH1F*> misstaguphists;
for(unsigned int i=0; i<variables_.size(); ++i){
name=variables_[i]+"__MISSTAG__plus";
misstaguphists.push_back((TH1F*) sysinput->Get(name));}
for(unsigned int idx=1; idx<variables_.size(); ++idx){
misstaguphists[idx]->Add(misstaguphists[idx-1]);}
addhists.push_back(misstaguphists[variables_.size()-1]);

std::vector<TH1F*> misstagdownhists;
for(unsigned int i=0; i<variables_.size(); ++i){
name=variables_[i]+"__MISSTAG__minus";
misstagdownhists.push_back((TH1F*) sysinput->Get(name));}
for(unsigned int idx=1; idx<variables_.size(); ++idx){
misstagdownhists[idx]->Add(misstagdownhists[idx-1]);}
addhists.push_back(misstagdownhists[variables_.size()-1]);

std::vector<TH1F*> muonuphists;
for(unsigned int i=0; i<variables_.size(); ++i){
name=variables_[i]+"__MUON__plus";
muonuphists.push_back((TH1F*) sysinput->Get(name));}
for(unsigned int idx=1; idx<variables_.size(); ++idx){
muonuphists[idx]->Add(muonuphists[idx-1]);}
addhists.push_back(muonuphists[variables_.size()-1]);

std::vector<TH1F*> muondownhists;
for(unsigned int i=0; i<variables_.size(); ++i){
name=variables_[i]+"__MUON__minus";
muondownhists.push_back((TH1F*) sysinput->Get(name));}
for(unsigned int idx=1; idx<variables_.size(); ++idx){
muondownhists[idx]->Add(muondownhists[idx-1]);}
addhists.push_back(muondownhists[variables_.size()-1]);

std::vector<TH1F*> photonuphists;
for(unsigned int i=0; i<variables_.size(); ++i){
name=variables_[i]+"__PHOTON__plus";
photonuphists.push_back((TH1F*) sysinput->Get(name));}
for(unsigned int idx=1; idx<variables_.size(); ++idx){
photonuphists[idx]->Add(photonuphists[idx-1]);}
addhists.push_back(photonuphists[variables_.size()-1]);

std::vector<TH1F*> photondownhists;
for(unsigned int i=0; i<variables_.size(); ++i){
name=variables_[i]+"__PHOTON__minus";
photondownhists.push_back((TH1F*) sysinput->Get(name));}
for(unsigned int idx=1; idx<variables_.size(); ++idx){
photondownhists[idx]->Add(photondownhists[idx-1]);}
addhists.push_back(photondownhists[variables_.size()-1]);

std::vector<std::vector<double_t> > vec(photondownhists[0]->GetNbinsX(), vector<double>(18));
  for(int p = 0; p <photondownhists[0]->GetNbinsX(); p++){ //loop over bins
    for(int m = 0; m < 18; m++){ //loop over systematics
vec[p][m]=addhists[m]->GetBinContent(p+1)+wjetandwphjet[0]->GetBinContent(p+1)+wjetandwphjet[1]->GetBinContent(p+1);
cout<<vec[p][m]<<endl;
}}


   // Book output histograms
   UInt_t nbin = 15;
   double min=-3;
   double max=3;

   // Prepare input tree (this must be replaced by your data source)
   // in this example, there is a toy tree with signal and one with background events
   // we'll later on use only the "signal" events for the test in this example.
   //   
   TFile *input(0);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::vector<string> samples_;
std::vector<string> datasamples_;
std::vector<TH1F*> hists;
std::vector<TH1F*> datahists;
std::vector<TH1F*> revDATAhists;

float scales[] = {0.628,0.0978,34.01,6.133,1.04,0.32,0.02,0.002,0.0961,0.0253,0.0224,0.0145,0.0125,0.0160,0.0158,0.0341,0.0341,0.0341,0.020,0.0017,0.0055,0.0032,0.00084,0.02,0.01139,0.01139,0.049094905/19.145};
samples_.push_back("WJET.root");
samples_.push_back("ZJET.root");
samples_.push_back("G_Pt_50to80.root");
samples_.push_back("G_Pt_80to120.root");
samples_.push_back("G_Pt_120to170.root");
samples_.push_back("G_Pt_170to300.root");
samples_.push_back("G_Pt_300to470.root");
samples_.push_back("G_Pt_470to800.root");
samples_.push_back("WPHJET.root");
samples_.push_back("T-W-CH.root");
samples_.push_back("TBAR-W-CH.root");
samples_.push_back("T-S-CH.root");
samples_.push_back("TBAR-S-CH.root");
samples_.push_back("T-T-CH.root");
samples_.push_back("TBAR-T-CH.root");
samples_.push_back("TTBAR1.root");
samples_.push_back("TTBAR2.root");
samples_.push_back("TTBAR3.root");
samples_.push_back("TTG.root");
samples_.push_back("WWG.root");
samples_.push_back("WW.root");
samples_.push_back("WZ.root");
samples_.push_back("ZZ.root");
samples_.push_back("ZGAMMA.root");
samples_.push_back("SINGLE-TOP-PH.root");
samples_.push_back("SINGLE-ANTITOP-PH.root");
samples_.push_back("SIGNALtGu.root");
datasamples_.push_back("REALDATA1.root");
datasamples_.push_back("REALDATA2.root");
datasamples_.push_back("REALDATA3.root");

std::vector<string> datasamplesreverse_;
datasamplesreverse_.push_back("etarev/REALDATA1.root");
datasamplesreverse_.push_back("etarev/REALDATA2.root");
datasamplesreverse_.push_back("etarev/REALDATA3.root");

TH1F   *wphjethist(0), *zjethist(0) , *phjethist(0), *wjethist(0), *twchhist(0), *tbarwhist(0),  *tschhist(0), *tbarschhist(0), *ttchhist(0), *tbartchhist(0), *tt1hist(0) ,*tt2hist(0), *tt3hist(0), *ttphhist(0), *wwphhist(0), *wwhist(0), *wzhist(0), *zzhist(0), *zgammahist(0),*singletopphotonhist(0), *singleantitopphotonhist(0), *signalhist(0), *G_Pt_50to80(0),*G_Pt_80to120(0), *G_Pt_120to170(0), *G_Pt_170to300(0) ,*G_Pt_300to470(0),*G_Pt_470to800(0)  ;

TH1F   *wphjethistSB(0), *zjethistSB(0) , *phjethistSB(0), *wjethistSB(0), *twchhistSB(0), *tbarwhistSB(0),  *tschhistSB(0), *tbarschhistSB(0), *ttchhistSB(0), *tbartchhistSB(0), *tt1histSB(0) ,*tt2histSB(0), *tt3histSB(0), *ttphhistSB(0), *wwphhistSB(0), *wwhistSB(0), *wzhistSB(0), *zzhistSB(0), *zgammahistSB(0),*singletopphotonhistSB(0), *singleantitopphotonhistSB(0), *signalhistSB(0), *G_Pt_50to80SB(0),*G_Pt_80to120SB(0), *G_Pt_120to170SB(0), *G_Pt_170to300SB(0) ,*G_Pt_300to470SB(0),*G_Pt_470to800SB(0)  ;

TH1F *data1hist(0), *data2hist(0) ,*data3hist(0) ,*datahistsideband(0);
TH1F *data1histrev(0), *data2histrev(0) ,*data3histrev(0), *datahistrevsideband(0);

wphjethist = new TH1F( "mu_BDT__wphjethist",           "mu_BDT__wphjethist",           nbin, min, max );
zjethist = new TH1F( "mu_BDT__zjethist",           "mu_BDT__zjethist",           nbin, min, max );
G_Pt_50to80= new TH1F( "mu_BDT__G_Pt_50to80",           "mu_BDT__G_Pt_50to80",           nbin, min, max );
G_Pt_80to120= new TH1F( "mu_BDT__G_Pt_80to120",           "mu_BDT__G_Pt_80to120",           nbin, min, max );
G_Pt_120to170= new TH1F( "mu_BDT__G_Pt_120to170",           "mu_BDT__G_Pt_120to170",           nbin, min, max );
G_Pt_170to300= new TH1F( "mu_BDT__G_Pt_170to300",           "mu_BDT__G_Pt_170to300",           nbin, min, max );
G_Pt_300to470= new TH1F( "mu_BDT__G_Pt_300to470",           "mu_BDT__G_Pt_300to470",           nbin, min, max );
G_Pt_470to800= new TH1F( "mu_BDT__G_Pt_470to800",           "mu_BDT__G_Pt_470to800",           nbin, min, max );
wjethist = new TH1F( "mu_BDT__wjethist",           "mu_BDT__wjethist",           nbin, min, max);
twchhist = new TH1F( "mu_BDT__twchhist",           "mu_BDT__twchhist",           nbin, min, max );
tbarwhist = new TH1F( "mu_BDT__tbarwhist",           "mu_BDT__tbarwhist",           nbin, min, max );
tschhist = new TH1F( "mu_BDT__tschhist",           "mu_BDT__tschhist",           nbin, min, max );
tbarschhist = new TH1F( "mu_BDT__tbarschhist",           "mu_BDT__tbarschhist",           nbin, min, max );
ttchhist = new TH1F( "mu_BDT__ttchhist",           "mu_BDT__ttchhist",           nbin, min, max );
tbartchhist = new TH1F( "mu_BDT__tbartchhist",           "mu_BDT__tbartchhist",           nbin, min, max);
tt1hist = new TH1F( "mu_BDT__tt1hist",           "mu_BDT__tt1hist",           nbin,min, max );
tt2hist = new TH1F( "mu_BDT__tt2hist",           "mu_BDT__tt2hist",           nbin, min, max);
tt3hist = new TH1F( "mu_BDT__tt3hist",           "mu_BDT__tt3hist",           nbin, min, max);
ttphhist = new TH1F( "mu_BDT__ttphhist",           "mu_BDT__ttphhist",           nbin, min, max);
wwphhist = new TH1F( "mu_BDT__wwphhist",           "BDT__wwphhist",           nbin,min, max );
wwhist = new TH1F( "mu_BDT__wwhist",           "mu_BDT__wwhist",           nbin,min, max );
wzhist = new TH1F( "mu_BDT__wzhist",           "mu_BDT__wzhist",           nbin, min, max );
zzhist = new TH1F( "mu_BDT__zzhist",           "mu_BDT__zzhist",           nbin, min, max );
zgammahist = new TH1F( "mu_BDT__zgammahist",           "mu_BDT__zgammahist",           nbin,min, max );
singletopphotonhist = new TH1F( "mu_BDT__singletopphotonhist",           "mu_BDT__singletopphotonhist",           nbin, min, max);
singleantitopphotonhist = new TH1F( "mu_BDT__singleantitopphotonhist",           "mu_BDT__singleantitopphotonhist",           nbin,min, max );
signalhist = new TH1F( "mu_BDT__signal100",           "mu_BDT__signal100",           nbin, min, max );


data1hist = new TH1F( "mu_BDT__data1hist",           "mu_BDT__data1hist",           nbin, min, max );
data2hist = new TH1F( "mu_BDT__data2hist",           "mu_BDT__data2hist",           nbin, min, max );
data3hist = new TH1F( "mu_BDT__DATA",           "mu_BDT__DATA",           nbin, min, max );
datahistsideband = new TH1F( "mu_BDT__DATA_sideband",           "mu_BDT__DATA_sideband",           nbin, min, max);


data1histrev = new TH1F( "mu_BDT__data1histrev",           "mu_BDT__data1histrev",           nbin, min, max );
data2histrev = new TH1F( "mu_BDT__data2histrev",           "mu_BDT__data2histrev",           nbin,min, max );
data3histrev = new TH1F( "mu_BDT__DATArev",           "mu_BDT__DATArev",           nbin, min, max );
datahistrevsideband = new TH1F( "mu_BDT__DATArevsideband",           "mu_BDT__DATArevsideband",           nbin, min, max );

wphjethistSB = new TH1F( "mu_BDT__wphjethist__JES__SB",           "mu_BDT__wphjethist__JES__SB",           nbin,min, max );
zjethistSB = new TH1F( "mu_BDT__zjethist__JES__SB",           "mu_BDT__zjethist__JES__SB",           nbin, min, max );
G_Pt_50to80SB= new TH1F( "mu_BDT__G_Pt_50to80SB",           "mu_BDT__G_Pt_50to80SB",           nbin, min, max );
G_Pt_80to120SB= new TH1F( "mu_BDT__G_Pt_80to120SB",           "mu_BDT__G_Pt_80to120SB",           nbin, min, max );
G_Pt_120to170SB= new TH1F( "mu_BDT__G_Pt_120to170SB",           "mu_BDT__G_Pt_120to170SB",           nbin, min, max );
G_Pt_170to300SB= new TH1F( "mu_BDT__G_Pt_170to300SB",           "mu_BDT__G_Pt_170to300SB",           nbin, min, max );
G_Pt_300to470SB= new TH1F( "mu_BDT__G_Pt_300to470SB",           "mu_BDT__G_Pt_300to470SB",           nbin, min, max );
G_Pt_470to800SB= new TH1F( "mu_BDT__G_Pt_470to800SB",           "mu_BDT__G_Pt_470to800SB",           nbin, min, max );
wjethistSB = new TH1F( "mu_BDT__wjethist__JES__SB",           "mu_BDT__wjethist__JES__SB",           nbin, min, max );
twchhistSB = new TH1F( "mu_BDT__twchhist__JES__SB",           "mu_BDT__twchhist__JES__SB",           nbin,min, max);
tbarwhistSB = new TH1F( "mu_BDT__tbarwhist__JES__SB",           "mu_BDT__tbarwhist__JES__SB",           nbin,min, max );
tschhistSB = new TH1F( "mu_BDT__tschhist__JES__SB",           "mu_BDT__tschhist__JES__SB",           nbin, min, max );
tbarschhistSB = new TH1F( "mu_BDT__tbarschhist__JES__SB",           "mu_BDT__tbarschhist__JES__SB",           nbin, min, max );
ttchhistSB = new TH1F( "mu_BDT__ttchhist__JES__SB",           "mu_BDT__ttchhist__JES__SB",           nbin, min, max );
tbartchhistSB = new TH1F( "mu_BDT__tbartchhist__JES__SB",           "mu_BDT__tbartchhist__JES__SB",           nbin, min, max);
tt1histSB = new TH1F( "mu_BDT__tt1hist__JES__SB",           "mu_BDT__tt1hist__JES__SB",           nbin, min, max );
tt2histSB = new TH1F( "mu_BDT__tt2hist__JES__SB",           "mu_BDT__tt2hist__JES__SB",           nbin, min, max );
tt3histSB = new TH1F( "mu_BDT__tt3hist__JES__SB",           "mu_BDT__tt3hist__JES__SB",           nbin, min, max );
ttphhistSB = new TH1F( "mu_BDT__ttphhist__JES__SB",           "mu_BDT__ttphhist__JES__SB",           nbin,min, max );
wwphhistSB = new TH1F( "mu_BDT__wwphhist__JES__SB",           "BDT__wwphhist__JES__SB",           nbin,min, max );
wwhistSB = new TH1F( "mu_BDT__wwhist__JES__SB",           "mu_BDT__wwhist__JES__SB",           nbin, min, max );
wzhistSB = new TH1F( "mu_BDT__wzhist__JES__SB",           "mu_BDT__wzhist__JES__SB",           nbin, min, max );
zzhistSB = new TH1F( "mu_BDT__zzhist__JES__SB",           "mu_BDT__zzhist__JES__SB",           nbin, min, max);
zgammahistSB = new TH1F( "mu_BDT__zgammahist__JES__SB",           "mu_BDT__zgammahist__JES__SB",           nbin, min, max );
singletopphotonhistSB = new TH1F( "mu_BDT__singletopphotonhistSB",           "mu_BDT__singletopphotonhistSB",           nbin,min, max );
singleantitopphotonhistSB = new TH1F( "mu_BDT__singleantitopphotonhistSB",           "mu_BDT__singleantitopphotonhistSB",           nbin, min, max);
signalhistSB = new TH1F( "mu_BDT__signal100__JES__SB",           "mu_BDT__signal100__JES__SB",           nbin,min, max );

std::vector<TH1F*> SBhists;
SBhists.push_back(wjethistSB);
SBhists.push_back(zjethistSB);
SBhists.push_back(G_Pt_50to80SB);
SBhists.push_back(G_Pt_80to120SB);
SBhists.push_back(G_Pt_120to170SB);
SBhists.push_back(G_Pt_170to300SB);
SBhists.push_back(G_Pt_300to470SB);
SBhists.push_back(G_Pt_470to800SB);
SBhists.push_back(wphjethistSB);
SBhists.push_back(twchhistSB);
SBhists.push_back(tbarwhistSB);
SBhists.push_back(tschhistSB);
SBhists.push_back(tbarschhistSB);
SBhists.push_back(ttchhistSB);
SBhists.push_back(tbartchhistSB);
SBhists.push_back(tt1histSB);
SBhists.push_back(tt2histSB);
SBhists.push_back(tt3histSB);
SBhists.push_back(ttphhistSB);
SBhists.push_back(wwphhistSB);
SBhists.push_back(wwhistSB);
SBhists.push_back(wzhistSB);
SBhists.push_back(zzhistSB);
SBhists.push_back(zgammahistSB);
SBhists.push_back(singletopphotonhistSB);
SBhists.push_back(singleantitopphotonhistSB);
SBhists.push_back(signalhistSB);

hists.push_back(wjethist);
hists.push_back(zjethist);
hists.push_back(G_Pt_50to80);
hists.push_back(G_Pt_80to120);
hists.push_back(G_Pt_120to170);
hists.push_back(G_Pt_170to300);
hists.push_back(G_Pt_300to470);
hists.push_back(G_Pt_470to800);
hists.push_back(wphjethist);
hists.push_back(twchhist);
hists.push_back(tbarwhist);
hists.push_back(tschhist);
hists.push_back(tbarschhist);
hists.push_back(ttchhist);
hists.push_back(tbartchhist);
hists.push_back(tt1hist);
hists.push_back(tt2hist);
hists.push_back(tt3hist);
hists.push_back(ttphhist);
hists.push_back(wwphhist);
hists.push_back(wwhist);
hists.push_back(wzhist);
hists.push_back(zzhist);
hists.push_back(zgammahist);
hists.push_back(singletopphotonhist);
hists.push_back(singleantitopphotonhist);
hists.push_back(signalhist);

for(unsigned int idx=0; idx<samples_.size(); ++idx){
hists[idx]->Sumw2();}

datahists.push_back(data1hist);
datahists.push_back(data2hist);
datahists.push_back(data3hist);
datahists.push_back(datahistsideband);
for(unsigned int idx=0; idx<datasamples_.size(); ++idx){
datahists[idx]->Sumw2();}

revDATAhists.push_back(data1histrev);
revDATAhists.push_back(data2histrev);
revDATAhists.push_back(data3histrev);
revDATAhists.push_back(datahistrevsideband);

double insidewphjet=0;
double outsidewphjet=0;
double insidewjet=0;
double outsidewjet=0;
double nsignalevent=0;
double mtopup=220;
double mtopdown=130;
//bool SR=false;
//bool SB=true;
bool SR=true;
bool SB=false;
for(unsigned int idx=0; idx<samples_.size(); ++idx){
   TString fname =samples_[idx];
   if (!gSystem->AccessPathName( fname )) input = TFile::Open( fname ); // check if file in local directory exists
   else    
      input = TFile::Open( "http://root.cern.ch/files/tmva_class_example.root" ); // if not: download from ROOT server
   
   if (!input) {
      std::cout << "ERROR: could not open data file" << std::endl;
      exit(1);
   }
   std::cout << "--- TMVAClassificationApp    : Using input file: " << input->GetName() << std::endl;
   
   // --- Event loop

   // Prepare the event tree
   // - here the variable names have to corres[1]ponds to your tree
   // - you can use the same variables as above which is slightly faster,
   //   but of course you can use different ones and copy the values inside the event loop
   //
  //Double_t  myptphoton,myetaphoton,myptmuon,myetamuon,myptjet,myetajet,mymasstop,mymtw,mydeltaRphotonjet,mydeltaRphotonmuon,myht,mycostopphoton,mydeltaphiphotonmet,mycvsdiscriminant,myjetmultiplicity,mybjetmultiplicity,myleptoncharge;


std::vector<double> *myptphoton=0;
std::vector<double> *myetaphoton=0;
std::vector<double> *myptmuon=0;
std::vector<double> *myetamuon=0;
std::vector<double> *myptjet=0;
std::vector<double> *myetajet=0;
std::vector<double> *mymasstop=0;
//std::vector<double> *mymtw=0;
std::vector<double> *mydeltaRphotonjet=0;
std::vector<double> *mydeltaRphotonmuon=0;
//std::vector<double> *myht=0;
std::vector<double> *mycostopphoton=0;
std::vector<double> *mydeltaphiphotonmet=0;
std::vector<double> *mycvsdiscriminant=0;
std::vector<double> *myjetmultiplicity=0;
//std::vector<double> *mybjetmultiplicity=0;
//std::vector<double> *myleptoncharge=0;
std::vector<double> *myweight=0;
std::vector<double> *myjetmatchinginfo=0;
std::vector<double> *mycoswphoton=0;

   std::cout << "--- Select signal sample" << std::endl;
   TTree* theTree = (TTree*)input->Get("analyzestep2/atq");
//   Int_t myjetmultiplicity, mybjetmultiplicity , myleptoncharge;
//   Float_t userVar1, userVar2;

   theTree->SetBranchAddress("ptphoton", &myptphoton  );
   theTree->SetBranchAddress( "etaphoton", &myetaphoton );
   theTree->SetBranchAddress( "ptmuon", &myptmuon );
   theTree->SetBranchAddress( "etamuon", &myetamuon );
   theTree->SetBranchAddress( "ptjet", &myptjet );
   theTree->SetBranchAddress( "etajet", &myetajet );
   theTree->SetBranchAddress( "masstop", &mymasstop );
//   theTree->SetBranchAddress( "mtw", &mymtw );
   theTree->SetBranchAddress( "deltaRphotonjet", &mydeltaRphotonjet );
   theTree->SetBranchAddress( "deltaRphotonmuon", &mydeltaRphotonmuon );
//   theTree->SetBranchAddress( "ht", &myht );
   theTree->SetBranchAddress( "costopphoton", &mycostopphoton );
   theTree->SetBranchAddress( "jetmultiplicity", &myjetmultiplicity );
//   theTree->SetBranchAddress( "bjetmultiplicity", &mybjetmultiplicity );
   theTree->SetBranchAddress( "deltaphiphotonmet", &mydeltaphiphotonmet );
   theTree->SetBranchAddress( "cvsdiscriminant", &mycvsdiscriminant );
//   theTree->SetBranchAddress( "leptoncharge", &myleptoncharge );
   theTree->SetBranchAddress( "weight", &myweight);
   theTree->SetBranchAddress( "coswphoton", &mycoswphoton );
	theTree->SetBranchAddress( "jetmatchinginfo", &myjetmatchinginfo );


//   std::cout << "--- Processing: " << theTree->GetEntries() << " events" << std::endl;
   TStopwatch sw;
   sw.Start();
   for (Long64_t ievt=0; ievt<theTree->GetEntries();ievt++) {
//   std::cout << "--- ... Processing event: " << ievt << std::endl;
double finalweight;

      if (ievt%1000 == 0) std::cout << "--- ... Processing event: " << ievt << std::endl;

      theTree->GetEntry(ievt);
//for (int l=0;l<sizeof(myptphoton);l++){
//std::cout << "--- ... reza: " << myptphoton[l] <<std::endl;
//}
//std::cout << "--- ......................."<< (*mycvsdiscriminant)[0]<<std::endl;
      // --- Return the MVA outputs and fill into histograms

finalweight=(*myweight)[0];
//cout<<(*myweight)[0]<<endl;
if((*mymasstop )[0]>mtopdown && (*mymasstop )[0]<mtopup){
hists[idx] ->Fill( (*myetajet)[0],finalweight );
if (samples_[idx]=="WPHJET.root")insidewphjet=insidewphjet+finalweight;
if (samples_[idx]=="SIGNALtGu.root")nsignalevent=nsignalevent+1;
//cout<<insidewphjet<<endl;
}
else {
SBhists[idx] ->Fill( (*myetajet)[0],finalweight );
if (samples_[idx]=="WPHJET.root")outsidewphjet=outsidewphjet+finalweight;}


      // Retrieve also per-event error
}
delete myptphoton;
delete myetaphoton;
delete myptmuon;
delete myetamuon;
delete myptjet;
delete myetajet;
delete mymasstop;
//delete mymtw;
delete mydeltaRphotonjet;
delete mydeltaRphotonmuon;
//delete myht;
delete mycostopphoton;
delete mydeltaphiphotonmet;
delete mycvsdiscriminant;
delete myjetmultiplicity;
//delete mybjetmultiplicity;
//delete myleptoncharge;
//delete myplot;
}
for(unsigned int idx=0; idx<datasamples_.size(); ++idx){
   TString fname =datasamples_[idx];
   if (!gSystem->AccessPathName( fname )) input = TFile::Open( fname ); // check if file in local directory exists
   else    
      input = TFile::Open( "http://root.cern.ch/files/tmva_class_example.root" ); // if not: download from ROOT server
   
   if (!input) {
      std::cout << "ERROR: could not open data file" << std::endl;
      exit(1);
   }
   std::cout << "--- TMVAClassificationApp    : Using input file: " << input->GetName() << std::endl;
   
   // --- Event loop

   // Prepare the event tree
   // - here the variable names have to corres[1]ponds to your tree
   // - you can use the same variables as above which is slightly faster,
   //   but of course you can use different ones and copy the values inside the event loop
   //
  //Double_t  myptphoton,myetaphoton,myptmuon,myetamuon,myptjet,myetajet,mymasstop,mymtw,mydeltaRphotonjet,mydeltaRphotonmuon,myht,mycostopphoton,mydeltaphiphotonmet,mycvsdiscriminant,myjetmultiplicity,mybjetmultiplicity,myleptoncharge;


std::vector<double> *myptphoton=0;
std::vector<double> *myetaphoton=0;
std::vector<double> *myptmuon=0;
std::vector<double> *myetamuon=0;
std::vector<double> *myptjet=0;
std::vector<double> *myetajet=0;
std::vector<double> *mymasstop=0;
//std::vector<double> *mymtw=0;
std::vector<double> *mydeltaRphotonjet=0;
std::vector<double> *mydeltaRphotonmuon=0;
//std::vector<double> *myht=0;
std::vector<double> *mycostopphoton=0;
std::vector<double> *mydeltaphiphotonmet=0;
std::vector<double> *mycvsdiscriminant=0;
std::vector<double> *myjetmultiplicity=0;
//std::vector<double> *mybjetmultiplicity=0;
//std::vector<double> *myleptoncharge=0;
std::vector<double> *mycoswphoton=0;



   std::cout << "--- Select signal sample" << std::endl;
   TTree* theTree = (TTree*)input->Get("analyzestep2/atq");
//   Int_t myjetmultiplicity, mybjetmultiplicity , myleptoncharge;
//   Float_t userVar1, userVar2;

   theTree->SetBranchAddress("ptphoton", &myptphoton  );
   theTree->SetBranchAddress( "etaphoton", &myetaphoton );
   theTree->SetBranchAddress( "ptmuon", &myptmuon );
   theTree->SetBranchAddress( "etamuon", &myetamuon );
   theTree->SetBranchAddress( "ptjet", &myptjet );
   theTree->SetBranchAddress( "etajet", &myetajet );
   theTree->SetBranchAddress( "masstop", &mymasstop );
//   theTree->SetBranchAddress( "mtw", &mymtw );
   theTree->SetBranchAddress( "deltaRphotonjet", &mydeltaRphotonjet );
   theTree->SetBranchAddress( "deltaRphotonmuon", &mydeltaRphotonmuon );
//   theTree->SetBranchAddress( "ht", &myht );
   theTree->SetBranchAddress( "costopphoton", &mycostopphoton );
   theTree->SetBranchAddress( "jetmultiplicity", &myjetmultiplicity );
//   theTree->SetBranchAddress( "bjetmultiplicity", &mybjetmultiplicity );
   theTree->SetBranchAddress( "deltaphiphotonmet", &mydeltaphiphotonmet );
   theTree->SetBranchAddress( "cvsdiscriminant", &mycvsdiscriminant );
   theTree->SetBranchAddress( "coswphoton", &mycoswphoton );
//   theTree->SetBranchAddress( "leptoncharge", &myleptoncharge );


   for (Long64_t ievt=0; ievt<theTree->GetEntries();ievt++) {
//   std::cout << "--- ... Processing event: " << ievt << std::endl;
      theTree->GetEntry(ievt);
      // --- Return the MVA outputs and fill into histograms
//leptoncharge=(float)(*myleptoncharge )[0];

if((*mymasstop )[0]>mtopdown && (*mymasstop )[0]<mtopup) datahists[idx] ->Fill( (*myetajet)[0] );
else datahists[3]->Fill(  (*myetajet)[0] );
}
delete myptphoton;
delete myetaphoton;
delete myptmuon;
delete myetamuon;
delete myptjet;
delete myetajet;
delete mymasstop;
//delete mymtw;
delete mydeltaRphotonjet;
delete mydeltaRphotonmuon;
//delete myht;
delete mycostopphoton;
delete mydeltaphiphotonmet;
delete mycvsdiscriminant;
delete myjetmultiplicity;
//delete mybjetmultiplicity;
//delete myleptoncharge;
//delete myplot;

}

for(unsigned int idx=0; idx<datasamplesreverse_.size(); ++idx){
   TString fname =datasamplesreverse_[idx];
   if (!gSystem->AccessPathName( fname )) input = TFile::Open( fname ); // check if file in local directory exists
   else
      input = TFile::Open( "http://root.cern.ch/files/tmva_class_example.root" ); // if not: download from ROOT server

   if (!input) {
      std::cout << "ERROR: could not open data file" << std::endl;
      exit(1);
   }
   std::cout << "--- TMVAClassificationApp    : Using input file: " << input->GetName() << std::endl;

std::vector<double> *myptphoton=0;
std::vector<double> *myetaphoton=0;
 std::vector<double> *myptmuon=0;
 std::vector<double> *myetamuon=0;
 std::vector<double> *myptjet=0;
 std::vector<double> *myetajet=0;
 std::vector<double> *mymasstop=0;
 //std::vector<double> *mymtw=0;
 std::vector<double> *mydeltaRphotonjet=0;
std::vector<double> *mydeltaRphotonmuon=0;
 //std::vector<double> *myht=0;
 std::vector<double> *mycostopphoton=0;
 std::vector<double> *mydeltaphiphotonmet=0;
 std::vector<double> *mycvsdiscriminant=0;
 std::vector<double> *myjetmultiplicity=0;
std::vector<double> *mycoswphoton=0;
 //std::vector<double> *mybjetmultiplicity=0;
 //std::vector<double> *myleptoncharge=0;
   TTree* theTree = (TTree*)input->Get("analyzestep2/atq");
   theTree->SetBranchAddress("ptphoton", &myptphoton  );
   theTree->SetBranchAddress( "etaphoton", &myetaphoton );
   theTree->SetBranchAddress( "ptmuon", &myptmuon );
   theTree->SetBranchAddress( "etamuon", &myetamuon );
   theTree->SetBranchAddress( "ptjet", &myptjet );
   theTree->SetBranchAddress( "etajet", &myetajet );
   theTree->SetBranchAddress( "masstop", &mymasstop );
//   theTree->SetBranchAddress( "mtw", &mymtw );
   theTree->SetBranchAddress( "deltaRphotonjet", &mydeltaRphotonjet );
   theTree->SetBranchAddress( "deltaRphotonmuon", &mydeltaRphotonmuon );
         //   theTree->SetBranchAddress( "ht", &myht );
   theTree->SetBranchAddress( "costopphoton", &mycostopphoton );
   theTree->SetBranchAddress( "jetmultiplicity", &myjetmultiplicity );
               //   theTree->SetBranchAddress( "bjetmultiplicity", &mybjetmultiplicity );
   theTree->SetBranchAddress( "deltaphiphotonmet", &mydeltaphiphotonmet );
   theTree->SetBranchAddress( "cvsdiscriminant", &mycvsdiscriminant );
   theTree->SetBranchAddress( "coswphoton", &mycoswphoton );
                     //   theTree->SetBranchAddress( "leptoncharge", &myleptoncharge );
 // Efficiency calculator for cut method
 for (Long64_t ievt=0; ievt<theTree->GetEntries();ievt++) {
                       //   std::cout << "--- ... Processing event: " << ievt << std::endl;
   if (ievt%1000 == 0) std::cout << "--- ... Processing event: " << ievt << std::endl;
   theTree->GetEntry(ievt);

 

if((*mymasstop )[0]>mtopdown && (*mymasstop )[0]<mtopup) {
//revDATAhists[idx]->Fill( reader->EvaluateMVA( "BDT method"           ) );
insidewjet=insidewjet+1;
revDATAhists[idx]->Fill(  (*myetajet)[0]);
}
else {
//revDATAhists[3]->Fill( reader->EvaluateMVA( "BDT method"           ) );
outsidewjet=outsidewjet+1;
revDATAhists[3]->Fill( (*myetajet)[0]);
}


//cout<<insidewjet<<endl;
}
delete myptphoton;
delete myetaphoton;
delete myptmuon;
delete myetamuon;
delete myptjet;
delete myetajet;
delete mymasstop;
//delete mymtw;
delete mydeltaRphotonjet;
delete mydeltaRphotonmuon;
//delete myht;
delete mycostopphoton;
delete mydeltaphiphotonmet;
delete mycvsdiscriminant;
delete myjetmultiplicity;
////delete mybjetmultiplicity;
////delete myleptoncharge;
////delete myplot;
//
}

double wphjetscale;
wphjetscale=insidewphjet/(insidewphjet+outsidewphjet);
cout<<"wphjetscale=    "<<wphjetscale<<endl;
double wjetscale;
wjetscale=insidewjet/(insidewjet+outsidewjet);
cout<<"wjetscale=    "<<wjetscale<<endl;
cout<<"nsignalevent=    "<<nsignalevent<<endl;
//cout<<insidewphjet<<"insidewphjet"<<"       "<<wphjetscale<<"       "<<insidewjet/(insidewjet+outsidewjet)<<endl;
float lumi = 1;

if (SR==true){
double ff=0;
for(unsigned int idx=0; idx<samples_.size(); ++idx){
hists[idx]->Scale(lumi*scales[idx]);
if (idx !=0 && idx!=3){
ff=hists[idx]->Integral()+ff;
cout<<samples_[idx]<<"         =        "<<hists[idx]->Integral()<<"     " <<ff<<endl;}
}

for(unsigned int idx=0; idx<samples_.size(); ++idx){
SBhists[idx]->Scale(lumi*scales[idx]);}

THStack *hs1 = new THStack("hs1","BDT output");
for(unsigned int idx=1; idx<datasamplesreverse_.size(); ++idx){
revDATAhists[idx]->Add(revDATAhists[idx-1]);
}
//cout<<"*********************"<< datahists[3]->Integral()<<"       "<<wphjetscale<<endl;
//cout<<"*********************"<< revDATAhists[2]->Integral()<<"       "<<wjetscale<<endl;

revDATAhists[2]->Scale(219.373/revDATAhists[2]->Integral());
for(unsigned int idx=1; idx<revDATAhists[2]->GetNbinsX()+1; ++idx){
//revDATAhists[2]->SetBinError(idx,(revDATAhists[2]->GetBinContent(idx)/revDATAhists[2]->Integral())*74.84);
revDATAhists[2]->SetBinError(idx,0);
//if (revDATAhists[2]->GetBinError(idx)>revDATAhists[2]->GetBinContent(idx)) revDATAhists[2]->SetBinError(idx, revDATAhists[2]->GetBinContent(idx)/2); 
}
//revDATAhists[2]->Scale(wjetscale);
revDATAhists[3]->Scale(219.373/revDATAhists[3]->Integral());
revDATAhists[3]->Scale((1-wjetscale)/wjetscale);


for(unsigned int idx=1; idx<datasamples_.size(); ++idx){
datahists[idx]->Add(datahists[idx-1]);}
cout<<"     " <<datahists[2]->Integral()<<endl;

datahists[3]->Add(revDATAhists[3],-1);
datahists[3]->Add(SBhists[1],-1);
datahists[3]->Add(SBhists[2],-1);
for(unsigned int idx=9; idx<samples_.size()-1; ++idx){
datahists[3]->Add(SBhists[idx],-1);}
for(unsigned int idx=1; idx<nbin; ++idx){
if (datahists[3]->GetBinContent(idx)<0)datahists[3]->SetBinContent(idx,0);
} 
datahists[3]->Scale(1112.2/datahists[3]->Integral());
for(unsigned int idx=1; idx<datahists[3]->GetNbinsX()+1; ++idx){
//datahists[3]->SetBinError(idx,(datahists[3]->GetBinContent(idx)/datahists[3]->Integral())*139.11);}
datahists[3]->SetBinError(idx,0);}

TH1F *datatoMC(0);

//datahists[3]->Scale(wphjetscale);

//hists[1]->Add(revDATAhists[2]);
//hists[2]->Add(hists[1]);
//datahists[3]->Add(hists[2]);
//hists[4]->Add(datahists[3]);

//for(unsigned int idx=5; idx<samples_.size()-1; ++idx){
//   hists[idx]->Add(hists[idx-1]);}
//cout<<"**********real data***********"<< datahists[2]->Integral()<<"       "<<wphjetscale<<endl;
//cout<<"********** mc ***********"<< hists[18]->Integral()<<"       "<<wjetscale<<endl;
// setup the canvas and draw the histograms

TH1F *sum_h= new TH1F ( *hists[1] ) ;
sum_h->Sumw2();
for(unsigned int idx=2; idx<samples_.size()-1; ++idx){
if (idx!=8)sum_h->Add(hists[idx],1);
}
sum_h->Add(revDATAhists[2],1);
sum_h->Add(datahists[3],1);

std::vector<std::vector<double_t> > vecplus(photondownhists[0]->GetNbinsX(), vector<double>(18));
std::vector<std::vector<double_t> > vecminus(photondownhists[0]->GetNbinsX(), vector<double>(18));
 for(int p = 0; p <photondownhists[0]->GetNbinsX(); p++){ //loop over bins
    for(int m = 0; m < 18; m++){ //loop over systematics
vecplus[p][m]=0;
vecminus[p][m]=0;
if (vec[p][m]>sum_h->GetBinContent(p+1)) vecplus[p][m] = vec[p][m]-sum_h->GetBinContent(p+1);
else if (vec[p][m]<sum_h->GetBinContent(p+1)) vecminus[p][m] = sum_h->GetBinContent(p+1)-vec[p][m];

cout<<vecplus[p][m]<<endl;
}}




TCanvas *c1 = new TCanvas("c1","signal region",50,50,865,780);
c1->cd();
TPad *pad1 = new TPad("pad1","pad1",0,0.25,1,1);
pad1->SetFillStyle(0);
pad1->SetFrameFillStyle(0);
pad1->SetBottomMargin(0);
TPad *pad2 = new TPad("pad2","pad2",0,0,1,0.25);
pad2->SetFillStyle(0);
pad2->SetFrameFillStyle(0);
pad2->SetTopMargin(0);
pad2->SetBottomMargin(0.12/0.46);
pad2->Draw();
pad1->Draw();

pad1->cd();

//W+jet
revDATAhists[2]->SetFillColor(kBlue-2);
revDATAhists[2]->SetLineColor(kBlack);
hs1->Add(revDATAhists[2]);
//Z+jet
hists[1]->SetFillColor(kOrange-4);
hists[1]->SetLineColor(kBlack);
hs1->Add(hists[1]);
//photon+jet
hists[3]->Add(hists[2]);
hists[4]->Add(hists[3]);
hists[5]->Add(hists[4]);
hists[6]->Add(hists[5]);
hists[7]->Add(hists[6]);
hists[7]->SetFillColor(19);
//hs1->Add(hists[7]);
//W+photon+jet
datahists[3]->SetFillColor(kGreen-3);
datahists[3]->SetLineColor(kBlack);
hs1->Add(datahists[3]);

//single top+singletop photon
hists[5+5]->Add(hists[4+5]);
hists[6+5]->Add(hists[5+5]);
hists[7+5]->Add(hists[6+5]);
hists[8+5]->Add(hists[7+5]);
hists[9+5]->Add(hists[8+5]);
hists[19+5]->Add(hists[9+5]);
hists[20+5]->Add(hists[19+5]);
hists[20+5]->SetFillColor(kRed+3);
hists[20+5]->SetLineColor(kBlack);
hs1->Add(hists[20+5]);
//hists[9+5]->SetFillColor(kAzure+10);
//hs1->Add(hists[9+5]);

hists[11+5]->Add(hists[10+5]);
hists[12+5]->Add(hists[11+5]);
hists[13+5]->Add(hists[12+5]);
hists[13+5]->SetFillColor(kPink+1);
hists[13+5]->SetLineColor(kBlack);
hs1->Add(hists[13+5]);
//hists[13+5]->SetFillColor(17);
//hs1->Add(hists[13+5]);
//hists[14+5]->SetFillColor(kSpring-9);
//hs1->Add(hists[14+5]);
hists[15+5]->Add(hists[14+5]);
hists[16+5]->Add(hists[15+5]);
hists[17+5]->Add(hists[16+5]);
hists[17+5]->SetFillColor(kViolet-7);
hists[17+5]->SetLineColor(kBlack);
hs1->Add(hists[17+5]);
hists[18+5]->SetFillColor(kAzure+10);
hists[18+5]->SetLineColor(kBlack);
hs1->Add(hists[18+5]);
//hists[20+5]->Add(hists[19+5]);
//hists[20+5]->SetFillColor(kYellow+3);
//hs1->Add(hists[20+5]);

hs1->Draw("hist");
hs1->SetMaximum(1.6*datahists[2]->GetMaximum());
//hs1->GetXaxis()->SetTitle("BDT output");
hs1->GetYaxis()->SetTitle("Events / 0.4");
hs1->GetYaxis()->SetTitleSize(0.045);
hs1->GetYaxis()->SetTitleFont(22);
hs1->GetYaxis()->SetTitleOffset(0.8);
hs1->GetYaxis()->SetLabelSize(0.044);

hists[21+5]->SetLineColor(kRed+3);
hists[21+5]->SetLineWidth(3);
hists[21+5]->Draw("histsame");

datahists[2]->SetLineWidth(3.);
datahists[2]->SetLineColor(kBlack);
datahists[2]->SetMarkerColor(kBlack);
datahists[2]->SetMarkerStyle(20.);
datahists[2]->SetMarkerSize(1.35);
datahists[2]->Draw("esame");
sum_h->SetLineColor(kBlack);
sum_h->SetFillColor(1);
sum_h->SetFillStyle(3001);
sum_h->Draw("e2same");


    TPaveText *pt = new TPaveText(0.1,0.95,0.4,0.95, "NDC"); // NDC sets coords
    pt->SetLineColor(10);                                              // relative to pad dimensions
    pt->SetFillColor(10); // text is black on white
    pt->SetTextSize(0.045);
    pt->SetTextAlign(12);
    pt->AddText("CMS Preliminary, 19.1 fb^{-1}, #sqrt{s} = 8 TeV");
    pt->SetShadowColor(10);
    pt->Draw("same");

std::vector<double_t> errorup(photondownhists[0]->GetNbinsX());
std::vector<double_t> errordown(photondownhists[0]->GetNbinsX());
 for(int p = 0; p <photondownhists[0]->GetNbinsX(); p++){ //loop over bins
    for(int m = 0; m < 18; m++){ //loop over systematics
if (m==0) {errorup[p]=0;
errordown[p]=0;}
errorup[p]=pow(vecplus[p][m],2)+errorup[p];
errordown[p]=pow(vecminus[p][m],2)+errordown[p];
}
errorup[p]=pow(0.024*sum_h->GetBinContent(p+1),2)+errorup[p];
errordown[p]=pow(0.024*sum_h->GetBinContent(p+1),2)+errordown[p];
errorup[p]=pow(0.4*wjetandwphjet[0]->GetBinContent(p+1),2)+errorup[p];
errordown[p]=pow(0.4*wjetandwphjet[0]->GetBinContent(p+1),2)+errordown[p];
errorup[p]=pow(0.3*wjetandwphjet[1]->GetBinContent(p+1),2)+errorup[p];
errordown[p]=pow(0.3*wjetandwphjet[1]->GetBinContent(p+1),2)+errordown[p];
errorup[p]=pow(0.3*hists[1]->GetBinContent(p+1),2)+errorup[p];
errordown[p]=pow(0.3*hists[1]->GetBinContent(p+1),2)+errordown[p];
errorup[p]=pow(0.3*hists[20+5]->GetBinContent(p+1),2)+errorup[p];
errordown[p]=pow(0.3*hists[20+5]->GetBinContent(p+1),2)+errordown[p];
errorup[p]=pow(0.3*hists[13+5]->GetBinContent(p+1),2)+errorup[p];
errordown[p]=pow(0.3*hists[13+5]->GetBinContent(p+1),2)+errordown[p];
errorup[p]=pow(0.3*hists[17+5]->GetBinContent(p+1),2)+errorup[p];
errordown[p]=pow(0.3*hists[17+5]->GetBinContent(p+1),2)+errordown[p];
errorup[p]=pow(0.3*hists[18+5]->GetBinContent(p+1),2)+errorup[p];
errordown[p]=pow(0.3*hists[18+5]->GetBinContent(p+1),2)+errordown[p];

cout<<errorup[p]<<endl;
cout<<errordown[p]<<endl;
}

 double ax[photondownhists[0]->GetNbinsX()];
 double ay[photondownhists[0]->GetNbinsX()];
 double aexl[photondownhists[0]->GetNbinsX()];
 double aexh[photondownhists[0]->GetNbinsX()];
 double aeyl[photondownhists[0]->GetNbinsX()];
 double aeyh[photondownhists[0]->GetNbinsX()];
 for(int p = 0; p <photondownhists[0]->GetNbinsX(); p++){ //loop over bins
ax[p]=min+(max-min)/(2*nbin)+p*((max-min)/nbin);
ay[p]=sum_h->GetBinContent(p+1);
aexl[p]=(max-min)/(2*nbin);
aexh[p]=(max-min)/(2*nbin);
aeyl[p]=sqrt(errordown[p]);
aeyh[p]=sqrt(errorup[p]);
}
TGraphAsymmErrors* gae = new TGraphAsymmErrors(photondownhists[0]->GetNbinsX(), ax, ay, aexl, aexh, aeyl, aeyh);
gae->SetFillColor(1);
gae->SetFillStyle(3003);

   gae->Draw("e2same");
TLegend* leg = new TLegend(0.70,0.58,0.89,0.88);
  leg->SetFillStyle ( 0);
  leg->SetFillColor ( 0);
  leg->SetBorderSize( 0);
  leg->AddEntry( datahists[2], "Data"               , "PL");
//  leg->AddEntry( hists[25], "Single top+#gamma"               , "F");
  leg->AddEntry( hists[23], "Z#gamma"               , "F");
  leg->AddEntry( hists[22], "WW,WZ,ZZ,WW#gamma "               , "F");
//  leg->AddEntry( hists[19], "WW#gamma"               , "F");
  leg->AddEntry( hists[18], "t#bar{t}, t#bar{t}#gamma"               , "F");
//  leg->AddEntry( hists[17], "t#bar{t}"               , "F");
  leg->AddEntry( hists[25], "Single top, Single top+#gamma"               , "F");
//  leg->AddEntry( hists[14], "Single top"               , "F");
  leg->AddEntry( datahists[3], "W#gamma"              , "F");
//  leg->AddEntry( hists[7], "#gamma+jets"                           , "F");
  leg->AddEntry( hists[1], "Z+jets"                           , "F");
  leg->AddEntry(revDATAhists[2], "W+jets"                           , "F");
  leg->AddEntry( hists[26], "Signal(tu#gamma) 1 pb"               , "L");
  leg->AddEntry(sum_h, "Stat uncertainty"               , "F");
  leg->AddEntry(gae, "Syst uncertainty"               , "F");

//  leg->AddEntry( datahists[2], "CMS Data 2012(19.145/fb)"               , "PL");

leg->Draw("same");
   sum_h->Draw("AXISSAMEY+");
   sum_h->Draw("AXISSAMEX+");
pad1->Draw();

TCanvas *c22 = new TCanvas("c22","signal region22",50,50,865,780);
c22->cd();
    gae->Draw("a2");
    gae->Draw("psame");

TH1F *h_ratio = (TH1F*)datahists[2]->Clone("h_copy");
h_ratio->Sumw2();	
pad2->cd();
pad2->SetGridy();
datatoMC = new TH1F( "datatoMC",           "datatoMC",           nbin, min, max );
datatoMC->Sumw2();
datatoMC->Divide(datahists[2],sum_h);
h_ratio->Divide(sum_h);
h_ratio->SetFillStyle(3004);
h_ratio->GetXaxis()->SetTitle("b-jet #eta");
h_ratio->GetYaxis()->SetTitle("DATA/MC");
  h_ratio->GetXaxis()->SetTitleSize(0.12);
  h_ratio->GetYaxis()->SetTitleSize(0.12);
  h_ratio->GetXaxis()->SetTitleFont(22);
  h_ratio->GetYaxis()->SetTitleFont(22);
  h_ratio->GetXaxis()->SetTickLength(0.05);
  h_ratio->GetYaxis()->SetTickLength(0.05);
  h_ratio->GetXaxis()->SetLabelSize(0.14);
  h_ratio->GetYaxis()->SetLabelSize(0.14);
  h_ratio->GetYaxis()->SetTitleOffset(0.25);
  h_ratio->GetYaxis()->SetNdivisions(504);
  h_ratio->SetLineWidth(2);
//h_ratio->SetStats(0);
//h_ratio->SetMarkerStyle(20);
h_ratio->SetMinimum(0);
h_ratio->SetMaximum(2);
h_ratio->Draw("E");


//datatoMC->Draw("");
TLine *l3 = new TLine(h_ratio->GetXaxis()->GetXmin(), 1.00, h_ratio->GetXaxis()->GetXmax(), 1.00);
l3->SetLineWidth(1);
//l3->SetLineStyle(7);
//l3->Draw();
  h_ratio->Draw("AXISSAMEY+");
   h_ratio->Draw("AXISSAMEX+");

 
c1->Update();

for(unsigned int idx=1; idx<nbin+1; ++idx){
cout<<"MC    "<<"nbin= "<<idx<<"  content= "<<sum_h->GetBinContent(idx)<<endl;
cout<<"signal    "<<"nbin= "<<idx<<"  content= "<<hists[21+5]->GetBinContent(idx)<<endl;
cout<<"Data    "<<"nbin= "<<idx<<"  content= "<<datahists[2]->GetBinContent(idx)<<endl;
}
cout<<"signal Integral   "<<hists[21+5]->Integral()<<endl;

}


if (SB==true){
for(unsigned int idx=0; idx<samples_.size(); ++idx){
SBhists[idx]->Scale(lumi*scales[idx]);}
revDATAhists[3]->Scale(620.32/revDATAhists[3]->Integral());
revDATAhists[3]->Scale(1-wjetscale);
SBhists[1]->Add(revDATAhists[3]);
SBhists[2]->Add(SBhists[1]);
SBhists[4]->Add(SBhists[2]);

for(unsigned int idx=5; idx<samples_.size()-1; ++idx){
   SBhists[idx]->Add(SBhists[idx-1]);}
SBhists[20]->SetMaximum(1.5*datahists[3]->GetMaximum());
SBhists[20]->SetFillColor(kMagenta+2);
SBhists[20]->Draw();
SBhists[18]->SetFillColor(kOrange+4);
SBhists[18]->Draw("same");
SBhists[17]->SetFillColor(kOrange-2);
SBhists[17]->Draw("same");

SBhists[16]->SetFillColor(kRed);
SBhists[16]->Draw("same");
SBhists[15]->SetFillColor(kViolet+1);
SBhists[15]->Draw("same");
SBhists[14]->SetFillColor(kSpring-9);
SBhists[14]->Draw("same");
SBhists[13]->SetFillColor(32);
SBhists[13]->Draw("same");
SBhists[12]->SetFillColor(6);
SBhists[12]->Draw("same");
SBhists[9]->SetFillColor(4);
SBhists[9]->Draw("same");
//hists[8]->SetFillColor(4);
//hists[8]->Draw("same");
//hists[7]->SetFillColor(3);
//hists[7]->Draw("same");
//hists[6]->SetFillColor(3);
//hists[6]->Draw("same");
//hists[5]->SetFillColor(2);
//hists[5]->Draw("same");
//hists[4]->SetFillColor(2);
//hists[4]->Draw("same");
//hists[3]->SetFillColor(5);
//hists[3]->Draw("same");
//datahists[3]->SetFillColor(5);
//datahists[3]->Draw("same");
SBhists[2]->SetFillColor(8);
SBhists[2]->Draw("same");
SBhists[1]->SetFillColor(kOrange+7);
SBhists[1]->Draw("same");
revDATAhists[3]->SetFillColor(7);
revDATAhists[3]->Draw("same");
//hists[0]->SetFillColor(7);
//hists[0]->Draw("same");
SBhists[21]->SetFillColor(1);
SBhists[21]->SetFillStyle(3004);
SBhists[21]->Draw("same");


 // plot data points
datahists[3]->SetLineWidth(3.);
datahists[3]->SetLineColor(kBlack);
datahists[3]->SetMarkerColor(kBlack);
datahists[3]->SetMarkerStyle(20.);
datahists[3]->Draw("esame");
//conv->RedrawAxis();


TLegend* leg = new TLegend(0.60,0.40,0.89,0.87);
  leg->SetFillStyle ( 0);
  leg->SetFillColor ( 0);
  leg->SetBorderSize( 0);
  leg->AddEntry( revDATAhists[2], "W JET"                           , "F");
  leg->AddEntry( SBhists[1], "Z JET"                           , "F");
  leg->AddEntry( SBhists[2], "PH JET"                           , "F");
//  leg->AddEntry( datahists[3], "W PH JET"              , "F");
//  leg->AddEntry( hists[5], "TOP-W-CH"               , "F");
//  leg->AddEntry( hists[5], "T-S-CH"               , "F");
//  leg->AddEntry( hists[7], "TOP-S-CH"               , "F");
//  leg->AddEntry( hists[7], "TTBAR-CH"               , "F");
//  leg->AddEntry( hists[8], "TBAR-W-CH"               , "F");
  leg->AddEntry( SBhists[9], "SINGLE TOP  "               , "F");
  leg->AddEntry( SBhists[12], "TTBAR"               , "F");
  leg->AddEntry( SBhists[13], "TTG"               , "F");
  leg->AddEntry( SBhists[14], "WWG"               , "F");
  leg->AddEntry( SBhists[15], "WW"               , "F");
  leg->AddEntry( SBhists[16], "WZ"               , "F");
  leg->AddEntry( SBhists[17], "ZZ"               , "F");
  leg->AddEntry( SBhists[18], "ZGAMMA"               , "F");
  leg->AddEntry( SBhists[20], "SINGLE TOP+PHOTON"               , "F");
  leg->AddEntry( SBhists[21], "SIGNAL"               , "F");
leg->AddEntry( datahists[3], "CMS Data 2012(19.145/fb)"               , "PL");

  leg->Draw("same");
}
} 
// internal routine to run the inverter
HypoTestInverterResult *
RooStats::HypoTestInvTool::RunInverter(RooWorkspace * w,
                                       const char * modelSBName, const char * modelBName, 
                                       const char * dataName, int type,  int testStatType, 
                                       bool useCLs, int npoints, double poimin, double poimax, 
                                       int ntoys,
                                       bool useNumberCounting,
                                       const char * nuisPriorName ){

   std::cout << "Running HypoTestInverter on the workspace " << w->GetName() << std::endl;
  
   w->Print();
  
  
   RooAbsData * data = w->data(dataName); 
   if (!data) { 
      Error("StandardHypoTestDemo","Not existing data %s",dataName);
      return 0;
   }
   else 
      std::cout << "Using data set " << dataName << std::endl;
  
   if (mUseVectorStore) { 
      RooAbsData::setDefaultStorageType(RooAbsData::Vector);
      data->convertToVectorStore() ;
   }
  
  
   // get models from WS
   // get the modelConfig out of the file
   ModelConfig* bModel = (ModelConfig*) w->obj(modelBName);
   ModelConfig* sbModel = (ModelConfig*) w->obj(modelSBName);
  
   if (!sbModel) {
      Error("StandardHypoTestDemo","Not existing ModelConfig %s",modelSBName);
      return 0;
   }
   // check the model 
   if (!sbModel->GetPdf()) { 
      Error("StandardHypoTestDemo","Model %s has no pdf ",modelSBName);
      return 0;
   }
   if (!sbModel->GetParametersOfInterest()) {
      Error("StandardHypoTestDemo","Model %s has no poi ",modelSBName);
      return 0;
   }
   if (!sbModel->GetObservables()) {
      Error("StandardHypoTestInvDemo","Model %s has no observables ",modelSBName);
      return 0;
   }
   if (!sbModel->GetSnapshot() ) { 
      Info("StandardHypoTestInvDemo","Model %s has no snapshot  - make one using model poi",modelSBName);
      sbModel->SetSnapshot( *sbModel->GetParametersOfInterest() );
   }
  
   // case of no systematics
   // remove nuisance parameters from model
   if (noSystematics) { 
      const RooArgSet * nuisPar = sbModel->GetNuisanceParameters();
      if (nuisPar && nuisPar->getSize() > 0) { 
         std::cout << "StandardHypoTestInvDemo" << "  -  Switch off all systematics by setting them constant to their initial values" << std::endl;
         RooStats::SetAllConstant(*nuisPar);
      }
      if (bModel) { 
         const RooArgSet * bnuisPar = bModel->GetNuisanceParameters();
         if (bnuisPar) 
            RooStats::SetAllConstant(*bnuisPar);
      }
   }
  
   if (!bModel || bModel == sbModel) {
      Info("StandardHypoTestInvDemo","The background model %s does not exist",modelBName);
      Info("StandardHypoTestInvDemo","Copy it from ModelConfig %s and set POI to zero",modelSBName);
      bModel = (ModelConfig*) sbModel->Clone();
      bModel->SetName(TString(modelSBName)+TString("_with_poi_0"));      
      RooRealVar * var = dynamic_cast<RooRealVar*>(bModel->GetParametersOfInterest()->first());
      if (!var) return 0;
      double oldval = var->getVal();
      var->setVal(0);
      bModel->SetSnapshot( RooArgSet(*var)  );
      var->setVal(oldval);
   }
   else { 
      if (!bModel->GetSnapshot() ) { 
         Info("StandardHypoTestInvDemo","Model %s has no snapshot  - make one using model poi and 0 values ",modelBName);
         RooRealVar * var = dynamic_cast<RooRealVar*>(bModel->GetParametersOfInterest()->first());
         if (var) { 
            double oldval = var->getVal();
            var->setVal(0);
            bModel->SetSnapshot( RooArgSet(*var)  );
            var->setVal(oldval);
         }
         else { 
            Error("StandardHypoTestInvDemo","Model %s has no valid poi",modelBName);
            return 0;
         }         
      }
   }

   // check model  has global observables when there are nuisance pdf
   // for the hybrid case the globobs are not needed
   if (type != 1 ) { 
      bool hasNuisParam = (sbModel->GetNuisanceParameters() && sbModel->GetNuisanceParameters()->getSize() > 0);
      bool hasGlobalObs = (sbModel->GetGlobalObservables() && sbModel->GetGlobalObservables()->getSize() > 0);
      if (hasNuisParam && !hasGlobalObs ) {  
         // try to see if model has nuisance parameters first 
         RooAbsPdf * constrPdf = RooStats::MakeNuisancePdf(*sbModel,"nuisanceConstraintPdf_sbmodel");
         if (constrPdf) { 
            Warning("StandardHypoTestInvDemo","Model %s has nuisance parameters but no global observables associated",sbModel->GetName());
            Warning("StandardHypoTestInvDemo","\tThe effect of the nuisance parameters will not be treated correctly ");
         }
      }
   }


  
   // run first a data fit 
  
   const RooArgSet * poiSet = sbModel->GetParametersOfInterest();
   RooRealVar *poi = (RooRealVar*)poiSet->first();
  
   std::cout << "StandardHypoTestInvDemo : POI initial value:   " << poi->GetName() << " = " << poi->getVal()   << std::endl;  
  
   // fit the data first (need to use constraint )
   TStopwatch tw; 

   bool doFit = initialFit;
   if (testStatType == 0 && initialFit == -1) doFit = false;  // case of LEP test statistic
   if (type == 3  && initialFit == -1) doFit = false;         // case of Asymptoticcalculator with nominal Asimov
   double poihat = 0;

   if (minimizerType.size()==0) minimizerType = ROOT::Math::MinimizerOptions::DefaultMinimizerType();
   else 
      ROOT::Math::MinimizerOptions::SetDefaultMinimizer(minimizerType.c_str());
    
   Info("StandardHypoTestInvDemo","Using %s as minimizer for computing the test statistic",
        ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str() );
   
   if (doFit)  { 

      // do the fit : By doing a fit the POI snapshot (for S+B)  is set to the fit value
      // and the nuisance parameters nominal values will be set to the fit value. 
      // This is relevant when using LEP test statistics

      Info( "StandardHypoTestInvDemo"," Doing a first fit to the observed data ");
      RooArgSet constrainParams;
      if (sbModel->GetNuisanceParameters() ) constrainParams.add(*sbModel->GetNuisanceParameters());
      RooStats::RemoveConstantParameters(&constrainParams);
      tw.Start(); 
      RooFitResult * fitres = sbModel->GetPdf()->fitTo(*data,InitialHesse(false), Hesse(false),
                                                       Minimizer(minimizerType.c_str(),"Migrad"), Strategy(0), PrintLevel(mPrintLevel), Constrain(constrainParams), Save(true) );
      if (fitres->status() != 0) { 
         Warning("StandardHypoTestInvDemo","Fit to the model failed - try with strategy 1 and perform first an Hesse computation");
         fitres = sbModel->GetPdf()->fitTo(*data,InitialHesse(true), Hesse(false),Minimizer(minimizerType.c_str(),"Migrad"), Strategy(1), PrintLevel(mPrintLevel+1), Constrain(constrainParams), Save(true) );
      }
      if (fitres->status() != 0) 
         Warning("StandardHypoTestInvDemo"," Fit still failed - continue anyway.....");
  
  
      poihat  = poi->getVal();
      std::cout << "StandardHypoTestInvDemo - Best Fit value : " << poi->GetName() << " = "  
                << poihat << " +/- " << poi->getError() << std::endl;
      std::cout << "Time for fitting : "; tw.Print(); 
  
      //save best fit value in the poi snapshot 
      sbModel->SetSnapshot(*sbModel->GetParametersOfInterest());
      std::cout << "StandardHypoTestInvo: snapshot of S+B Model " << sbModel->GetName() 
                << " is set to the best fit value" << std::endl;
  
   }

   // print a message in case of LEP test statistics because it affects result by doing or not doing a fit 
   if (testStatType == 0) {
      if (!doFit) 
         Info("StandardHypoTestInvDemo","Using LEP test statistic - an initial fit is not done and the TS will use the nuisances at the model value");
      else 
         Info("StandardHypoTestInvDemo","Using LEP test statistic - an initial fit has been done and the TS will use the nuisances at the best fit value");
   }


   // build test statistics and hypotest calculators for running the inverter 
  
   SimpleLikelihoodRatioTestStat slrts(*sbModel->GetPdf(),*bModel->GetPdf());

   // null parameters must includes snapshot of poi plus the nuisance values 
   RooArgSet nullParams(*sbModel->GetSnapshot());
   if (sbModel->GetNuisanceParameters()) nullParams.add(*sbModel->GetNuisanceParameters());
   if (sbModel->GetSnapshot()) slrts.SetNullParameters(nullParams);
   RooArgSet altParams(*bModel->GetSnapshot());
   if (bModel->GetNuisanceParameters()) altParams.add(*bModel->GetNuisanceParameters());
   if (bModel->GetSnapshot()) slrts.SetAltParameters(altParams);
  
   // ratio of profile likelihood - need to pass snapshot for the alt
   RatioOfProfiledLikelihoodsTestStat 
      ropl(*sbModel->GetPdf(), *bModel->GetPdf(), bModel->GetSnapshot());
   ropl.SetSubtractMLE(false);
   if (testStatType == 11) ropl.SetSubtractMLE(true);
   ropl.SetPrintLevel(mPrintLevel);
   ropl.SetMinimizer(minimizerType.c_str());
  
   ProfileLikelihoodTestStat profll(*sbModel->GetPdf());
   if (testStatType == 3) profll.SetOneSided(true);
   if (testStatType == 4) profll.SetSigned(true);
   profll.SetMinimizer(minimizerType.c_str());
   profll.SetPrintLevel(mPrintLevel);

   profll.SetReuseNLL(mOptimize);
   slrts.SetReuseNLL(mOptimize);
   ropl.SetReuseNLL(mOptimize);

   if (mOptimize) { 
      profll.SetStrategy(0);
      ropl.SetStrategy(0);
      ROOT::Math::MinimizerOptions::SetDefaultStrategy(0);
   }
  
   if (mMaxPoi > 0) poi->setMax(mMaxPoi);  // increase limit
  
   MaxLikelihoodEstimateTestStat maxll(*sbModel->GetPdf(),*poi); 
   NumEventsTestStat nevtts;

   AsymptoticCalculator::SetPrintLevel(mPrintLevel);
  
   // create the HypoTest calculator class 
   HypoTestCalculatorGeneric *  hc = 0;
   if (type == 0) hc = new FrequentistCalculator(*data, *bModel, *sbModel);
   else if (type == 1) hc = new HybridCalculator(*data, *bModel, *sbModel);
   else if (type == 2 ) hc = new AsymptoticCalculator(*data, *bModel, *sbModel, false, mAsimovBins);
   else if (type == 3 ) hc = new AsymptoticCalculator(*data, *bModel, *sbModel, true, mAsimovBins);  // for using Asimov data generated with nominal values 
   else {
      Error("StandardHypoTestInvDemo","Invalid - calculator type = %d supported values are only :\n\t\t\t 0 (Frequentist) , 1 (Hybrid) , 2 (Asymptotic) ",type);
      return 0;
   }
  
   // set the test statistic 
   TestStatistic * testStat = 0;
   if (testStatType == 0) testStat = &slrts;
   if (testStatType == 1 || testStatType == 11) testStat = &ropl;
   if (testStatType == 2 || testStatType == 3 || testStatType == 4) testStat = &profll;
   if (testStatType == 5) testStat = &maxll;
   if (testStatType == 6) testStat = &nevtts;

   if (testStat == 0) { 
      Error("StandardHypoTestInvDemo","Invalid - test statistic type = %d supported values are only :\n\t\t\t 0 (SLR) , 1 (Tevatron) , 2 (PLR), 3 (PLR1), 4(MLE)",testStatType);
      return 0;
   }
  
  
   ToyMCSampler *toymcs = (ToyMCSampler*)hc->GetTestStatSampler();
   if (toymcs && (type == 0 || type == 1) ) { 
      // look if pdf is number counting or extended
      if (sbModel->GetPdf()->canBeExtended() ) { 
         if (useNumberCounting)   Warning("StandardHypoTestInvDemo","Pdf is extended: but number counting flag is set: ignore it ");
      }
      else { 
         // for not extended pdf
         if (!useNumberCounting  )  { 
            int nEvents = data->numEntries();
            Info("StandardHypoTestInvDemo","Pdf is not extended: number of events to generate taken  from observed data set is %d",nEvents);
            toymcs->SetNEventsPerToy(nEvents);
         }
         else {
            Info("StandardHypoTestInvDemo","using a number counting pdf");
            toymcs->SetNEventsPerToy(1);
         }
      }

      toymcs->SetTestStatistic(testStat);
    
      if (data->isWeighted() && !mGenerateBinned) { 
         Info("StandardHypoTestInvDemo","Data set is weighted, nentries = %d and sum of weights = %8.1f but toy generation is unbinned - it would be faster to set mGenerateBinned to true\n",data->numEntries(), data->sumEntries());
      }
      toymcs->SetGenerateBinned(mGenerateBinned);
  
      toymcs->SetUseMultiGen(mOptimize);
    
      if (mGenerateBinned &&  sbModel->GetObservables()->getSize() > 2) { 
         Warning("StandardHypoTestInvDemo","generate binned is activated but the number of ovservable is %d. Too much memory could be needed for allocating all the bins",sbModel->GetObservables()->getSize() );
      }

      // set the random seed if needed
      if (mRandomSeed >= 0) RooRandom::randomGenerator()->SetSeed(mRandomSeed); 
    
   }
  
   // specify if need to re-use same toys
   if (reuseAltToys) {
      hc->UseSameAltToys();
   }
  
   if (type == 1) { 
      HybridCalculator *hhc = dynamic_cast<HybridCalculator*> (hc);
      assert(hhc);
    
      hhc->SetToys(ntoys,ntoys/mNToysRatio); // can use less ntoys for b hypothesis 
    
      // remove global observables from ModelConfig (this is probably not needed anymore in 5.32)
      bModel->SetGlobalObservables(RooArgSet() );
      sbModel->SetGlobalObservables(RooArgSet() );
    
    
      // check for nuisance prior pdf in case of nuisance parameters 
      if (bModel->GetNuisanceParameters() || sbModel->GetNuisanceParameters() ) {

         // fix for using multigen (does not work in this case)
         toymcs->SetUseMultiGen(false);
         ToyMCSampler::SetAlwaysUseMultiGen(false);

         RooAbsPdf * nuisPdf = 0; 
         if (nuisPriorName) nuisPdf = w->pdf(nuisPriorName);
         // use prior defined first in bModel (then in SbModel)
         if (!nuisPdf)  { 
            Info("StandardHypoTestInvDemo","No nuisance pdf given for the HybridCalculator - try to deduce  pdf from the model");
            if (bModel->GetPdf() && bModel->GetObservables() ) 
               nuisPdf = RooStats::MakeNuisancePdf(*bModel,"nuisancePdf_bmodel");
            else 
               nuisPdf = RooStats::MakeNuisancePdf(*sbModel,"nuisancePdf_sbmodel");
         }   
         if (!nuisPdf ) {
            if (bModel->GetPriorPdf())  { 
               nuisPdf = bModel->GetPriorPdf();
               Info("StandardHypoTestInvDemo","No nuisance pdf given - try to use %s that is defined as a prior pdf in the B model",nuisPdf->GetName());            
            }
            else { 
               Error("StandardHypoTestInvDemo","Cannnot run Hybrid calculator because no prior on the nuisance parameter is specified or can be derived");
               return 0;
            }
         }
         assert(nuisPdf);
         Info("StandardHypoTestInvDemo","Using as nuisance Pdf ... " );
         nuisPdf->Print();
      
         const RooArgSet * nuisParams = (bModel->GetNuisanceParameters() ) ? bModel->GetNuisanceParameters() : sbModel->GetNuisanceParameters();
         RooArgSet * np = nuisPdf->getObservables(*nuisParams);
         if (np->getSize() == 0) { 
            Warning("StandardHypoTestInvDemo","Prior nuisance does not depend on nuisance parameters. They will be smeared in their full range");
         }
         delete np;
      
         hhc->ForcePriorNuisanceAlt(*nuisPdf);
         hhc->ForcePriorNuisanceNull(*nuisPdf);
      
      
      }
   } 
   else if (type == 2 || type == 3) { 
      if (testStatType == 3) ((AsymptoticCalculator*) hc)->SetOneSided(true);  
      if (testStatType != 2 && testStatType != 3)  
         Warning("StandardHypoTestInvDemo","Only the PL test statistic can be used with AsymptoticCalculator - use by default a two-sided PL");
   }
   else if (type == 0 || type == 1) 
      ((FrequentistCalculator*) hc)->SetToys(ntoys,ntoys/mNToysRatio); 

  
   // Get the result
   RooMsgService::instance().getStream(1).removeTopic(RooFit::NumIntegration);
  
  
  
   HypoTestInverter calc(*hc);
   calc.SetConfidenceLevel(0.95);
  
  
   calc.UseCLs(useCLs);
   calc.SetVerbose(true);
  
   // can speed up using proof-lite
   if (mUseProof && mNWorkers > 1) { 
      ProofConfig pc(*w, mNWorkers, "", kFALSE);
      toymcs->SetProofConfig(&pc);    // enable proof
   }
  
  
   if (npoints > 0) {
      if (poimin > poimax) { 
         // if no min/max given scan between MLE and +4 sigma 
         poimin = int(poihat);
         poimax = int(poihat +  4 * poi->getError());
      }
      std::cout << "Doing a fixed scan  in interval : " << poimin << " , " << poimax << std::endl;
      calc.SetFixedScan(npoints,poimin,poimax);
   }
   else { 
      //poi->setMax(10*int( (poihat+ 10 *poi->getError() )/10 ) );
      std::cout << "Doing an  automatic scan  in interval : " << poi->getMin() << " , " << poi->getMax() << std::endl;
   }
  
   tw.Start();
   HypoTestInverterResult * r = calc.GetInterval();
   std::cout << "Time to perform limit scan \n";
   tw.Print();
  
   if (mRebuild) {
      calc.SetCloseProof(1);
      tw.Start();
      SamplingDistribution * limDist = calc.GetUpperLimitDistribution(true,mNToyToRebuild);
      std::cout << "Time to rebuild distributions " << std::endl;
      tw.Print();
    
      if (limDist) { 
         std::cout << "expected up limit " << limDist->InverseCDF(0.5) << " +/- " 
                   << limDist->InverseCDF(0.16) << "  " 
                   << limDist->InverseCDF(0.84) << "\n"; 
      
         //update r to a new updated result object containing the rebuilt expected p-values distributions
         // (it will not recompute the expected limit)
         if (r) delete r;  // need to delete previous object since GetInterval will return a cloned copy
         r = calc.GetInterval();
      
      }
      else 
         std::cout << "ERROR : failed to re-build distributions " << std::endl; 
   }
  
   return r;
}
void ana_standalone_single_photon_MC() {

  gSystem->Load("/afs/cern.ch/user/y/yohay/scratch0/CMSSW_4_2_4_patch2/src/SusyAnalysis/SusyNtuplizer/macro/libSusy.so");

  // // Look ../jec/JetMETObjects/README
  gSystem->Load("/afs/cern.ch/user/y/yohay/scratch0/CMSSW_4_2_4_patch2/src/SusyAnalysis/SusyNtuplizer/jec/lib/libJetMETObjects.so");

  //GMSBTools shared library (contains Categorizer class)
  gSystem->Load("/afs/cern.ch/user/y/yohay/scratch0/CMSSW_4_2_4_patch2/src/GMSBTools/lib/libFilters.so");

  // Printing utility for ntuple variables
  gSystem->Load("/afs/cern.ch/user/y/yohay/scratch0/CMSSW_4_2_4_patch2/src/SusyAnalysis/SusyNtuplizer/macro/SusyEventPrinter_cc.so");

  // Main analysis code
  gSystem->SetIncludePath("-I/afs/cern.ch/user/y/yohay/scratch0/CMSSW_4_2_4_patch2/src");
  gSystem->Load("/afs/cern.ch/user/y/yohay/scratch0/CMSSW_4_2_4_patch2/src/SusyAnalysis/SusyNtuplizer/macro/EventAnalyzer_cc.so");
  gSystem->Load("/afs/cern.ch/user/y/yohay/scratch0/CMSSW_4_2_4_patch2/src/SusyAnalysis/SusyNtuplizer/macro/DongwookCategoryProducer_cc.so");

  /*now, ECAL/HCAL/track isolation cuts are meant to be matched with loose trigger cuts, so don't 
    use them (i.e. track isolation) to distinguish photon from fake!*/

  //configuration
  ParameterSet pars;
  pars.photonTag = "photons";
  pars.photon1ETMin = 40.0;
  pars.photon2ETMin = 30.0;
  pars.photonAbsEtaMax = 1.4442;
  pars.photonECALIsoMaxPTMultiplier = 0.012; /*https://twiki.cern.ch/twiki/bin/viewauth/CMS/
					       EgammaWorkingPointsv3, IsoVL, assuming dR = 0.3 
					       cone*/
  pars.photonECALIsoMaxConstant = 6.0; /*https://twiki.cern.ch/twiki/bin/viewauth/CMS/
					 EgammaWorkingPointsv3, IsoVL, assuming dR = 0.3 cone*/
  pars.photonECALIsoEffArea = 0.1474; /*https://twiki.cern.ch/twiki/bin/view/CMS/
					RA3IsolationConePileupCorrections, dR = 0.3 cone, 
					18-Oct-11*/
  pars.photonHCALIsoMaxPTMultiplier = 0.005; /*https://twiki.cern.ch/twiki/bin/viewauth/CMS/
					       EgammaWorkingPointsv3, IsoVL, assuming dR = 0.3 
					       cone*/
  pars.photonHCALIsoMaxConstant = 4.0; /*https://twiki.cern.ch/twiki/bin/viewauth/CMS/
					 EgammaWorkingPointsv3, IsoVL, assuming dR = 0.3 cone*/
  pars.photonHCALIsoEffArea = 0.0467; /*https://twiki.cern.ch/twiki/bin/view/CMS/
					RA3IsolationConePileupCorrections, dR = 0.3 cone, 
					18-Oct-11*/
  pars.photonHOverEMax = 0.05;
  pars.photonR9Max = 0.98;
  pars.photonTrackIsoMaxPTMultiplier = 0.002; /*https://twiki.cern.ch/twiki/bin/viewauth/CMS/
						EgammaWorkingPointsv3, IsoVL, assuming dR = 0.3 
						cone*/
  pars.photonTrackIsoMaxConstant = 4.0; /*https://twiki.cern.ch/twiki/bin/viewauth/CMS/
					  EgammaWorkingPointsv3, IsoVL, assuming dR = 0.3 cone*/
  pars.photonCombinedIsoMax = 6.0;
  pars.fakeCombinedIsoMax = 12.0;
  pars.isoConeHLT = DR03;
  pars.isoConeOffline = DR03;
  pars.photonSigmaIetaIetaMax = 0.011;
  pars.photonAbsSeedTimeMax = -1.0;
  pars.photonE2OverE9Max = -1.0;
  pars.photonDPhiMin = 0.05;
  pars.photonDRMin = 0.8;
  pars.pixelVetoOnFake = true;
  pars.treeName = "susyTree";
//   pars.input = VSTRING(1, "/data2/yohay/RA3/Data2011A_ToRun167913_Filter-JsonHLTtwo43-30GeVPhosWithR9HoverE_NoPileupCorr_Photon_NEW.root");
  pars.input = VSTRING();
FILES
  pars.HLT = vector<TString>();
  pars.HLT.push_back("HLT_Photon70_CaloIdL_HT300");
  pars.HLT.push_back("HLT_Photon70_CaloIdL_HT400");
  pars.HLT.push_back("HLT_Photon135");
  pars.HLT.push_back("HLT_Photon75_CaloIdVL_IsoL");
  pars.HLT.push_back("HLT_Photon125");
  pars.nEvts = -1;
  pars.JSON = "";
//   pars.JSON = "/afs/cern.ch/user/y/yohay/scratch0/CMSSW_4_2_4_patch2/src/SusyAnalysis/SusyNtuplizer/macro/JSON_160431-177878_May10ReReco_Run2011APromptRecov4v6_Aug5ReReco_Run2011BPromptRecov1.txt";
//   pars.outputFile = "/data2/yohay/RA3/Data2011A_ToRun167913_Filter-JsonHLTtwo43-30GeVPhosWithR9HoverE_NoPileupCorr_Photon_NEW_categorized_OR.root";
//   pars.outputFile = "/data2/yohay/RA3/1140pb-1_ff_categorized_new.root";
  pars.outputFile = "DATASET_JSON_HLT_PV_single_photon_skim.root";

  TStopwatch ts;

  ts.Start();

  DongwookCategoryProducer producer(pars);

  ts.Stop();

  std::cout << "RealTime : " << ts.RealTime()/60.0 << " minutes" << std::endl;
  std::cout << "CPUTime  : " << ts.CpuTime()/60.0 << " minutes" << std::endl;

}
Example #10
0
sim_upto_emc(Int_t nEvents = 20000)
{
  
  //-----User Settings:-----------------------------------------------
  TString  OutputFile     ="sim_complete_20k_upto_emc.root";
  TString  ParOutputfile  ="simparams_20k_upto_emc.root";
  TString  MediaFile      ="media_pnd.geo";
  gDebug                  = 0;
  TString digiFile        = "all.par"; //The emc run the hit producer directly 

  double BeamMomentum   =15.0; // ** change HERE if you run Box generator

  TString  SimEngine ="TGeant4";
  
  //------------------------------------------------------------------
  TStopwatch timer;
  timer.Start();
  gRandom->SetSeed(); 

  // Create the Simulation run manager--------------------------------
  FairRunSim *fRun = new FairRunSim();
  fRun->SetName(SimEngine.Data() );
  fRun->SetOutputFile(OutputFile.Data());
  fRun->SetWriteRunInfoFile(kFALSE);
  fRun->SetBeamMom(BeamMomentum);
  fRun->SetMaterials(MediaFile.Data());

  fRun->SetRadLenRegister(true);
  //fRun->SetRadMapRegister(true);
  //fRun->SetRadGridRegister(true);

  FairRuntimeDb *rtdb=fRun->GetRuntimeDb();
  
  // Set the parameters 
  //-------------------------------
  TString allDigiFile = gSystem->Getenv("VMCWORKDIR");
  allDigiFile += "/macro/params/";
  allDigiFile += digiFile;
 
  //-------Set the parameter output --------------------
  FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo();
  parIo1->open(allDigiFile.Data(),"in");
  rtdb->setFirstInput(parIo1);        

  //---------------------Set Parameter output      ---------- 
  Bool_t kParameterMerged=kTRUE;
  FairParRootFileIo* output=new FairParRootFileIo(kParameterMerged);
  output->open(ParOutputfile.Data());
  rtdb->setOutput(output);

  // Create and add detectors

  //-------------------------  CAVE      -----------------
  FairModule *Cave= new PndCave("CAVE");
  Cave->SetGeometryFileName("pndcave.geo");
  fRun->AddModule(Cave); 
  
  //-------------------------  Magnet   ----------------- 
  FairModule *Magnet= new PndMagnet("MAGNET");
  //Magnet->SetGeometryFileName("FullSolenoid_V842.root");
  Magnet->SetGeometryFileName("FullSuperconductingSolenoid_v831.root");
  fRun->AddModule(Magnet);
  FairModule *Dipole= new PndMagnet("MAGNET");
  Dipole->SetGeometryFileName("dipole.geo");
  fRun->AddModule(Dipole);
  
  //-------------------------  Pipe     -----------------
  FairModule *Pipe= new PndPipe("PIPE");
  Pipe->SetGeometryFileName("beampipe_201309.root");
  fRun->AddModule(Pipe);

  //-------------------------  STT       -----------------
  FairDetector *Stt= new PndStt("STT", kTRUE);
  Stt->SetGeometryFileName("straws_skewed_blocks_35cm_pipe.geo");
  fRun->AddModule(Stt);
  
  //-------------------------  MVD       -----------------
  FairDetector *Mvd = new PndMvdDetector("MVD", kTRUE);
  Mvd->SetGeometryFileName("Mvd-2.1_FullVersion.root");
  fRun->AddModule(Mvd);
  
  //-------------------------  GEM       -----------------
  FairDetector *Gem = new PndGemDetector("GEM", kTRUE);
  Gem->SetGeometryFileName("gem_3Stations.root");
  fRun->AddModule(Gem);
  
  //-------------------------  EMC       -----------------
  PndEmc *Emc = new PndEmc("EMC",kTRUE);
  Emc->SetGeometryVersion(1);
  Emc->SetStorageOfData(kFALSE);
  fRun->AddModule(Emc);
  
  ////-------------------------  SCITIL    -----------------
  //FairDetector *SciT = new PndSciT("SCIT",kTRUE);
  //SciT->SetGeometryFileName("barrel-SciTil_07022013.root");
  //fRun->AddModule(SciT);
  //
  ////-------------------------  DRC       -----------------
  //PndDrc *Drc = new PndDrc("DIRC", kTRUE);
  //Drc->SetGeometryFileName("dirc_l0_p0_updated.root"); 
  //Drc->SetRunCherenkov(kFALSE);
  //fRun->AddModule(Drc); 
  //
  ////-------------------------  DISC      -----------------
  //PndDsk* Dsk = new PndDsk("DSK", kTRUE);
  //Dsk->SetStoreCerenkovs(kFALSE);
  //Dsk->SetStoreTrackPoints(kFALSE);
  //fRun->AddModule(Dsk);
  //
  ////-------------------------  MDT       -----------------
  //PndMdt *Muo = new PndMdt("MDT",kTRUE);
  //Muo->SetBarrel("fast");
  //Muo->SetEndcap("fast");
  //Muo->SetMuonFilter("fast");
  //Muo->SetForward("fast");
  //Muo->SetMdtMagnet(kTRUE);
  //Muo->SetMdtMFIron(kTRUE);
  //fRun->AddModule(Muo);
  //
  ////-------------------------  FTS       -----------------
  //FairDetector *Fts= new PndFts("FTS", kTRUE);
  //Fts->SetGeometryFileName("fts.geo");
  //fRun->AddModule(Fts); 
  //
  ////-------------------------  FTOF      -----------------
  //FairDetector *FTof = new PndFtof("FTOF",kTRUE);
  //FTof->SetGeometryFileName("ftofwall.root");
  //fRun->AddModule(FTof);
  //
  ////-------------------------  RICH       ----------------
  //FairDetector *Rich= new PndRich("RICH",kFALSE);
  //Rich->SetGeometryFileName("rich_v2_shift.geo");
  //fRun->AddModule(Rich);
  
  // Create and Set Event Generator
  //-------------------------------
  FairPrimaryGenerator* primGen = new FairPrimaryGenerator();
  fRun->SetGenerator(primGen);

  FairBoxGenerator* boxGen = new FairBoxGenerator(0, 1);
  boxGen->SetPRange(2.0,2.0); // GeV/c
  boxGen->SetPhiRange(0., 360.); // Azimuth angle range [degree]
  boxGen->SetThetaRange(0., 180.); // Polar angle in lab system range [degree]
  boxGen->SetXYZ(0., 0., 0.); // cm
  primGen->AddGenerator(boxGen);

  //---------------------Create and Set the Field(s)---------- 
  PndMultiField *fField= new PndMultiField("FULL");
  fRun->SetField(fField);

  // EMC Hit producer
  //-------------------------------
  PndEmcHitProducer* emcHitProd = new PndEmcHitProducer();
  fRun->AddTask(emcHitProd);
  
  //-------------------------  Initialize the RUN  -----------------  
  fRun->Init();
  //-------------------------  Run the Simulation  -----------------   
  fRun->Run(nEvents);
  //-------------------------  Save the parameters ----------------- 
  rtdb->saveOutput();
  //------------------------Print some info and exit----------------     
  timer.Stop();
  Double_t rtime = timer.RealTime();
  Double_t ctime = timer.CpuTime();
  printf("RealTime=%f seconds, CpuTime=%f seconds\n",rtime,ctime);
  
  cout << " Test passed" << endl;
  cout << " All ok " << endl;
  
  //exit(0);

}  
void 
Frequentist_calculation(const char * infile = "results/tttt_combined_my_measurement_model.root",
                        const char * wsName = "combined",
                        const char * modelSBName = "ModelConfig",
                        const char * modelBName = "",
                        const char * dataName = "obsData",                 
                        int calculatorType = 0,
                        int testStatType = 3, 
                        bool useCLs = true ,  
                        int npoints = 25,
                        double poimin = 0.,
                        double poimax = 100.,
                        int ntoys=1000,
                        bool useNumberCounting = false,
                        const char * nuisPriorName = 0){
/*

  Other Parameter to pass in tutorial
  apart from standard for filename, ws, modelconfig and data

  (calculator)Type = 0 Freq calculator 
  (calculator)Type = 1 Hybrid calculator
  (calculator)Type = 2 Asymptotic calculator  
  (calculator)Type = 3 Asymptotic calculator using nominal Asimov data sets (not using fitted parameter values but nominal ones)

  testStatType = 0 LEP
  = 1 Tevatron 
  = 2 Profile Likelihood
  = 3 Profile Likelihood one sided (i.e. = 0 if mu < mu_hat)
  = 4 Profiel Likelihood signed ( pll = -pll if mu < mu_hat) 
  = 5 Max Likelihood Estimate as test statistic
  = 6 Number of observed event as test statistic

  useCLs          scan for CLs (otherwise for CLs+b)    

  npoints:        number of points to scan , for autoscan set npoints = -1 

  poimin,poimax:  min/max value to scan in case of fixed scans 
  (if min >  max, try to find automatically)                           

  ntoys:         number of toys to use 

  useNumberCounting:  set to true when using number counting events 

  nuisPriorName:   name of prior for the nnuisance. This is often expressed as constraint term in the global model
  It is needed only when using the HybridCalculator (type=1)
  If not given by default the prior pdf from ModelConfig is used. 

  extra options are available as global paramwters of the macro. They major ones are: 

  plotHypoTestResult   plot result of tests at each point (TS distributions) (defauly is true)
  useProof             use Proof   (default is true) 
  writeResult          write result of scan (default is true)
  rebuild              rebuild scan for expected limits (require extra toys) (default is false)
  generateBinned       generate binned data sets for toys (default is false) - be careful not to activate with 
  a too large (>=3) number of observables 
  nToyRatio            ratio of S+B/B toys (default is 2)
    

*/


  // Time this macro
  TStopwatch t;
  t.Start();
  
  
   TString fileName(infile);
   if (fileName.IsNull()) { 
      fileName = "results/example_combined_GaussExample_model.root";
      std::cout << "Use standard file generated with HistFactory : " << fileName << std::endl;
   }
  
   // open file and check if input file exists
   TFile * file = TFile::Open(fileName); 
  
   // if input file was specified but not found, quit
   if(!file && !TString(infile).IsNull()){
      cout <<"file " << fileName << " not found" << endl;
      return;
   } 
  
/*   // if default file not found, try to create it
   if(!file ){
      // Normally this would be run on the command line
      cout <<"will run standard hist2workspace example"<<endl;
      gROOT->ProcessLine(".! prepareHistFactory .");
      gROOT->ProcessLine(".! hist2workspace config/example.xml");
      cout <<"\n\n---------------------"<<endl;
      cout <<"Done creating example input"<<endl;
      cout <<"---------------------\n\n"<<endl;
    
      // now try to access the file again
      file = TFile::Open(fileName);
    
   }
*/  
   if(!file){
      // if it is still not there, then we can't continue
      cout << "Not able to run hist2workspace to create example input" <<endl;
      return;
   }
  


   HypoTestInvTool calc;

   // set parameters
   calc.SetParameter("PlotHypoTestResult", plotHypoTestResult);
   calc.SetParameter("WriteResult", writeResult);
   calc.SetParameter("Optimize", optimize);
   calc.SetParameter("UseVectorStore", useVectorStore);
   calc.SetParameter("GenerateBinned", generateBinned);
   calc.SetParameter("NToysRatio", nToysRatio);
   calc.SetParameter("MaxPOI", maxPOI);
   calc.SetParameter("UseProof", useProof);
   calc.SetParameter("NWorkers", nworkers);
   calc.SetParameter("Rebuild", rebuild);
   calc.SetParameter("ReuseAltToys", reuseAltToys);
   calc.SetParameter("NToyToRebuild", nToyToRebuild);
   calc.SetParameter("MassValue", massValue.c_str());
   calc.SetParameter("MinimizerType", minimizerType.c_str());
   calc.SetParameter("PrintLevel", printLevel);
   calc.SetParameter("InitialFit",initialFit);
   calc.SetParameter("ResultFileName",resultFileName);
   calc.SetParameter("RandomSeed",randomSeed);
   calc.SetParameter("AsimovBins",nAsimovBins);


   RooWorkspace * w = dynamic_cast<RooWorkspace*>( file->Get(wsName) );
   HypoTestInverterResult * r = 0;  
   std::cout << w << "\t" << fileName << std::endl;
   if (w != NULL) {
      r = calc.RunInverter(w, modelSBName, modelBName,
                           dataName, calculatorType, testStatType, useCLs,
                           npoints, poimin, poimax,  
                           ntoys, useNumberCounting, nuisPriorName );    
      if (!r) { 
         std::cerr << "Error running the HypoTestInverter - Exit " << std::endl;
         return;          
      }
   }
   else { 
      // case workspace is not present look for the inverter result
      std::cout << "Reading an HypoTestInverterResult with name " << wsName << " from file " << fileName << std::endl;
      r = dynamic_cast<HypoTestInverterResult*>( file->Get(wsName) ); //
      if (!r) { 
         std::cerr << "File " << fileName << " does not contain a workspace or an HypoTestInverterResult - Exit " 
                   << std::endl;
         file->ls();
         return; 
      }
   }		
  
   calc.AnalyzeResult( r, calculatorType, testStatType, useCLs, npoints, infile );
  
  t.Stop();
  t.Print();
  
   return;
}
Example #12
0
void r3ball_batch(Int_t nEvents = 1,
	    TObjArray& fDetList,
	    TString Target = "LeadTarget",
		Bool_t fVis=kFALSE,
		TString fMC="TGeant3",
	    TString fGenerator="box",
	    Bool_t fUserPList= kFALSE,
		Bool_t fR3BMagnet= kTRUE,
		Double_t fEnergyP=1.0,
		Int_t fMult=1, 
		Int_t fGeoVer=5, 
		Double_t fNonUni=1.0	
			)
{


  TString dir = getenv("VMCWORKDIR");
  TString r3bdir = dir + "/macros";

  TString r3b_geomdir = dir + "/geometry";
  gSystem->Setenv("GEOMPATH",r3b_geomdir.Data());

  TString r3b_confdir = dir + "gconfig";
  gSystem->Setenv("CONFIG_DIR",r3b_confdir.Data());

// Output files
  TString OutFile = "r3bsim.root";
  TString ParFile = "r3bpar.root";


  // In general, the following parts need not be touched
  // ========================================================================

  // ----    Debug option   -------------------------------------------------
  gDebug = 0;
  // ------------------------------------------------------------------------

  // -----   Timer   --------------------------------------------------------
  TStopwatch timer;
  timer.Start();
  // ------------------------------------------------------------------------

 
  // -----   Create simulation run   ----------------------------------------
  FairRunSim* run = new FairRunSim();
  run->SetName(fMC.Data());                  // Transport engine
  run->SetOutputFile(OutFile.Data());        // Output file
  FairRuntimeDb* rtdb = run->GetRuntimeDb();

  //  R3B Special Physics List in G4 case
  if ( (fUserPList  == kTRUE ) &&
       (fMC.CompareTo("TGeant4")   == 0)
      ){
       run->SetUserConfig("g4R3bConfig.C");
       run->SetUserCuts("SetR3BCuts.C");
   }


  // -----   Create media   -------------------------------------------------
  run->SetMaterials("media_r3b.geo");       // Materials
  

  // Magnetic field map type
   Int_t fFieldMap = 0;


  // Global Transformations
  //- Two ways for a Volume Rotation are supported
  //-- 1) Global Rotation (Euler Angles definition)
  //-- This represent the composition of : first a rotation about Z axis with
  //-- angle phi, then a rotation with theta about the rotated X axis, and
  //-- finally a rotation with psi about the new Z axis.
  Double_t phi,theta,psi;

  //-- 2) Rotation in Ref. Frame of the Volume
  //-- Rotation is Using Local Ref. Frame axis angles
  Double_t thetaX,thetaY,thetaZ;


  //- Global Translation  Lab. frame.
  Double_t tx,ty,tz;

  // - Polar angular limits
  Double_t minTheta=35., maxTheta=55.;


  // -----   Create R3B geometry --------------------------------------------
  //R3B Cave definition
  FairModule* cave= new R3BCave("CAVE");
  cave->SetGeometryFileName("r3b_cave.geo");
  run->AddModule(cave);


  //R3B Target definition
  if (fDetList.FindObject("TARGET") ) {
      R3BModule* target= new R3BTarget(Target.Data());
      // Global Lab. Rotation
      phi    =  0.0; // (deg)
      theta  =  0.0; // (deg)
      psi    =  0.0; // (deg)
      // Rotation in Ref. Frame.
      thetaX =  0.0; // (deg)
      thetaY =  0.0; // (deg)
      thetaZ =  0.0; // (deg)
      // Global translation in Lab
      tx    =  0.0; // (cm)
      ty    =  0.0; // (cm)
      tz    =  0.0; // (cm)
     //target->SetRotAnglesEuler(phi,theta,psi);
     target->SetRotAnglesXYZ(thetaX,thetaY,thetaZ);
     target->SetTranslation(tx,ty,tz);
      run->AddModule(target);
  }

  //R3B Magnet definition
  if (fDetList.FindObject("ALADIN") ) {
    fFieldMap = 0;
    R3BModule* mag = new R3BMagnet("AladinMagnet");
    mag->SetGeometryFileName("aladin_v13a.geo.root");
    run->AddModule(mag);
  }

    //R3B Magnet definition
  if (fDetList.FindObject("GLAD") ) {
      fFieldMap = 1;
      R3BModule* mag = new R3BGladMagnet("GladMagnet");
      // Global position of the Module
      phi   =  0.0; // (deg)
      theta =  0.0; // (deg)
      psi   =  0.0; // (deg)
      // Rotation in Ref. Frame.
      thetaX =  0.0; // (deg)
      thetaY =  0.0; // (deg)
      thetaZ =  0.0; // (deg)
      // Global translation in Lab
      tx    =  0.0; // (cm)
      ty    =  0.0; // (cm)
      tz    =  0.0; // (cm)
      //mag->SetRotAnglesEuler(phi,theta,psi);
      mag->SetRotAnglesXYZ(thetaX,thetaY,thetaZ);
      mag->SetTranslation(tx,ty,tz);
      run->AddModule(mag);
  }

  if (fDetList.FindObject("CRYSTALBALL") ) {
      //R3B Crystal Calorimeter
      R3BDetector* xball = new R3BXBall("XBall", kTRUE);
      xball->SetGeometryFileName("cal_v13a.geo.root");
      run->AddModule(xball);
  }

  if (fDetList.FindObject("CALIFA") ) {
    // CALIFA Calorimeter
    R3BDetector* calo = new R3BCalo("Califa", kTRUE);
    ((R3BCalo *)calo)->SelectGeometryVersion(10);
    //Selecting the Non-uniformity of the crystals (1 means +-1% max deviation)
    ((R3BCalo *)calo)->SetNonUniformity(1.0);
    calo->SetGeometryFileName("califa_v13_811.geo.root");
    run->AddModule(calo);
  }

  // Tracker
  if (fDetList.FindObject("TRACKER")  ) {
      R3BDetector* tra = new R3BTra("Tracker", kTRUE);
      // Global position of the Module
      phi   =  0.0; // (deg)
      theta =  0.0; // (deg)
      psi   =  0.0; // (deg)
      // Rotation in Ref. Frame.
      thetaX =  0.0; // (deg)
      thetaY =  0.0; // (deg)
      thetaZ =  0.0; // (deg)
      // Global translation in Lab
      tx    =  0.0; // (cm)
      ty    =  0.0; // (cm)
      tz    =  0.0; // (cm)
      //tra->SetRotAnglesEuler(phi,theta,psi);
      tra->SetRotAnglesXYZ(thetaX,thetaY,thetaZ);
      tra->SetTranslation(tx,ty,tz);
      // User defined Energy CutOff
      Double_t fCutOffSi = 1.0e-06;  // Cut-Off -> 10KeV only in Si
      ((R3BTra*) tra)->SetEnergyCutOff(fCutOffSi);
      run->AddModule(tra);
  }
  
  // DCH drift chambers
  if (fDetList.FindObject("DCH") ) {
      R3BDetector* dch = new R3BDch("Dch", kTRUE);
      ((R3BDch*) dch )->SetHeliumBag(kTRUE);
      // Global position of the Module
      phi   =  0.0; // (deg)
      theta =  0.0; // (deg)
      psi   =  0.0; // (deg)
      // Rotation in Ref. Frame.
      thetaX =  0.0; // (deg)
      thetaY =  0.0; // (deg)
      thetaZ =  0.0; // (deg)
      // Global translation in Lab
      tx    =  0.0; // (cm)
      ty    =  0.0; // (cm)
      tz    =  0.0; // (cm)
     //dch->SetRotAnglesEuler(phi,theta,psi);
      dch->SetRotAnglesXYZ(thetaX,thetaY,thetaZ);
      dch->SetTranslation(tx,ty,tz);
      run->AddModule(dch);
  }

  // Tof
  if (fDetList.FindObject("TOF") ) {
      R3BDetector* tof = new R3BTof("Tof", kTRUE);
      // Global position of the Module
      thetaX   =  0.0; // (deg)
      thetaY   =  0.0; // (deg)
      thetaZ   =  0.0; // (deg)
      // Rotation in Ref. Frame.
      thetaX =  0.0; // (deg)
      thetaY =  0.0; // (deg)
      thetaZ =  0.0; // (deg)
      // Global translation in Lab
      tx       =  0.0; // (cm)
      ty       =  0.0; // (cm)
      tz       =  0.0; // (cm)
      tof->SetRotAnglesXYZ(thetaX,thetaY,thetaZ);
      tof->SetTranslation(tx,ty,tz);
      // User defined Energy CutOff
      Double_t fCutOffSci = 1.0e-05;  // Cut-Off -> 10.KeV only in Sci.
      ((R3BTof*) tof)->SetEnergyCutOff(fCutOffSci);
      run->AddModule(tof);
  }

  // mTof
  if (fDetList.FindObject("MTOF") ) {
      R3BDetector* mTof = new R3BmTof("mTof", kTRUE);
      // Global position of the Module
      phi   =  0.0; // (deg)
      theta =  0.0; // (deg)
      psi   =  0.0; // (deg)
      // Rotation in Ref. Frame.
      thetaX =  0.0; // (deg)
      thetaY =  0.0; // (deg)
      thetaZ =  0.0; // (deg)
      // Global translation in Lab
      tx    =  0.0; // (cm)
      ty    =  0.0; // (cm)
      tz    =  0.0; // (cm)
      //mTof->SetRotAnglesEuler(phi,theta,psi);
      mTof->SetRotAnglesXYZ(thetaX,thetaY,thetaZ);
      mTof->SetTranslation(tx,ty,tz);
      // User defined Energy CutOff
      Double_t fCutOffSci = 1.0e-05;  // Cut-Off -> 10.KeV only in Sci.
      ((R3BmTof*) mTof)->SetEnergyCutOff(fCutOffSci);
      run->AddModule(mTof);
  }

  // GFI detector
  if (fDetList.FindObject("GFI") ) {
      R3BDetector* gfi = new R3BGfi("Gfi", kTRUE);
      // Global position of the Module
      phi   =  0.0; // (deg)
      theta =  0.0; // (deg)
      psi   =  0.0; // (deg)
      // Rotation in Ref. Frame.
      thetaX =  0.0; // (deg)
      thetaY =  0.0; // (deg)
      thetaZ =  0.0; // (deg)
      // Global translation in Lab
      tx    =  0.0; // (cm)
      ty    =  0.0; // (cm)
      tz    =  0.0; // (cm)
      gfi->SetRotAnglesXYZ(thetaX,thetaY,thetaZ);
      gfi->SetTranslation(tx,ty,tz);
      // User defined Energy CutOff
      Double_t fCutOffSci = 1.0e-05;  // Cut-Off -> 10.KeV only in Sci.
      ((R3BGfi*) gfi)->SetEnergyCutOff(fCutOffSci);
      run->AddModule(gfi);
  }

  // Land Detector
  if (fDetList.FindObject("LAND") ) {
      R3BDetector* land = new R3BLand("Land", kTRUE);
      land->SetGeometryFileName("land_v12a_10m.geo.root");
      run->AddModule(land);
  }

  // Chimera
  if (fDetList.FindObject("CHIMERA") ) {
      R3BDetector* chim = new R3BChimera("Chimera", kTRUE);
      chim->SetGeometryFileName("chimera.root");
      // Global position of the Module
      thetaX   =  0.0; // (deg)
      thetaY   =  0.0; // (deg)
      thetaZ   =  0.0; // (deg)
      // Rotation in Ref. Frame.
      thetaX =  0.0; // (deg)
      thetaY =  0.0; // (deg)
      thetaZ =  0.0; // (deg)
      // Global translation in Lab
      tx       =  0.0; // (cm)
      ty       =  0.0; // (cm)
      tz       =  0.0; // (cm)
      chim->SetRotAnglesXYZ(thetaX,thetaY,thetaZ);
      chim->SetTranslation(tx,ty,tz);
      // User defined Energy CutOff
      //Double_t fCutOffSci = 1.0e-05;  // Cut-Off -> 10.KeV only in Sci.
      //((R3BChimera*) chim)->SetEnergyCutOff(fCutOffSci);
      run->AddModule(chim);
  }

  // Luminosity detector
  if (fDetList.FindObject("LUMON") ) {
      R3BDetector* lumon = new ELILuMon("LuMon", kTRUE);
      //lumon->SetGeometryFileName("lumon.root");
      // Global position of the Module
      thetaX   =  0.0; // (deg)
      thetaY   =  0.0; // (deg)
      thetaZ   =  0.0; // (deg)
      // Rotation in Ref. Frame.
      thetaX =  0.0; // (deg)
      thetaY =  0.0; // (deg)
      thetaZ =  0.0; // (deg)
      // Global translation in Lab
      tx       =  0.0; // (cm)
      ty       =  0.0; // (cm)
      tz       =  200.0; // (cm)
      lumon->SetRotAnglesXYZ(thetaX,thetaY,thetaZ);
      lumon->SetTranslation(tx,ty,tz);
      // User defined Energy CutOff
      //Double_t fCutOffSci = 1.0e-05;  // Cut-Off -> 10.KeV only in Sci.
      //((ELILuMon*) lumon)->SetEnergyCutOff(fCutOffSci);
      run->AddModule(lumon);
  }


  
  // -----   Create R3B  magnetic field ----------------------------------------
  Int_t typeOfMagneticField = 0;
  Int_t fieldScale = 1;
  Bool_t fVerbose = kFALSE;

  //NB: <D.B>
  // If the Global Position of the Magnet is changed
  // the Field Map has to be transformed accordingly

  if (fFieldMap == 0) {
    R3BFieldMap* magField = new R3BFieldMap(typeOfMagneticField,fVerbose);
    magField->SetPosition(0., 0., 0.);
    magField->SetScale(fieldScale);

    if ( fR3BMagnet == kTRUE ) {
	run->SetField(magField);
    } else {
	run->SetField(NULL);
    }
  } else if(fFieldMap == 1){
    R3BGladFieldMap* magField = new R3BGladFieldMap("R3BGladMap");
    magField->SetPosition(0., 0., +350-119.94);
    magField->SetScale(fieldScale);

    if ( fR3BMagnet == kTRUE ) {
	run->SetField(magField);
    } else {
	run->SetField(NULL);
    }
  }  //! end of field map section



  // -----   Create PrimaryGenerator   --------------------------------------

  // 1 - Create the Main API class for the Generator
  FairPrimaryGenerator* primGen = new FairPrimaryGenerator();


  if (fGenerator.CompareTo("box") == 0  ) {
  // 2- Define the BOX generator
  Double_t pdgId=211; // pion beam
  Double_t theta1= 0.;  // polar angle distribution
  Double_t theta2= 7.;
  Double_t momentum=.8; // 10 GeV/c
  FairBoxGenerator* boxGen = new FairBoxGenerator(pdgId, 50);
  boxGen->SetThetaRange (   theta1,   theta2);
  boxGen->SetPRange     (momentum,momentum*2.);
  boxGen->SetPhiRange   (0.,360.);
  boxGen->SetXYZ(0.0,0.0,-1.5);
  // add the box generator
  primGen->AddGenerator(boxGen);
  } 
	
  if (fGenerator.CompareTo("gammas") == 0  ) {
	// 2- Define the CALIFA Test gamma generator
	Double_t pdgId=22; // 22 for gamma emission, 2212 for proton emission 
	Double_t theta1=minTheta;  // polar angle distribution: lower edge
	Double_t theta2=maxTheta;  // polar angle distribution: upper edge	
	Double_t momentum=fEnergyP; // GeV/c 
	//Double_t momentum=0.808065; // 0.808065 GeV/c (300MeV Kin Energy for protons) 
	//Double_t momentum=0.31016124; // 0.31016124 GeV/c (50MeV Kin Energy for protons)
	//Double_t momentum=0.4442972; // 0.4442972 GeV/c (100MeV Kin Energy for protons)
	//Double_t momentum=0.5509999; // 0.5509999 GeV/c (150MeV Kin Energy for protons)
	//Double_t momentum=0.64405; // 0.64405 GeV/c (200MeV Kin Energy for protons) 
	Int_t multiplicity = fMult;
	R3BCALIFATestGenerator* gammasGen = new R3BCALIFATestGenerator(pdgId, multiplicity);
	gammasGen->SetThetaRange(theta1,theta2);
	gammasGen->SetCosTheta();
	gammasGen->SetPRange(momentum,momentum);
        gammasGen->SetPhiRange(0.,360.);

	gammasGen->SetBoxXYZ(-0.1,0.1,-0.1,0.1,-0.1,0.1);
	gammasGen->SetLorentzBoost(0.8197505718204776); //beta=0.81975 for 700 A MeV
	// add the gamma generator
	primGen->AddGenerator(gammasGen);
  } 
	

 if (fGenerator.CompareTo("r3b") == 0  ) {
  R3BSpecificGenerator *pR3bGen = new R3BSpecificGenerator();

  // R3bGen properties
  pR3bGen->SetBeamInteractionFlag("off");
  pR3bGen->SetBeamInteractionFlag("off");
  pR3bGen->SetRndmFlag("off");
  pR3bGen->SetRndmEneFlag("off");
  pR3bGen->SetBoostFlag("off");
  pR3bGen->SetReactionFlag("on");
  pR3bGen->SetGammasFlag("off");
  pR3bGen->SetDecaySchemeFlag("off");
  pR3bGen->SetDissociationFlag("off");
  pR3bGen->SetBackTrackingFlag("off");
  pR3bGen->SetSimEmittanceFlag("off");

  // R3bGen Parameters
  pR3bGen->SetBeamEnergy(1.); // Beam Energy in GeV
  pR3bGen->SetSigmaBeamEnergy(1.e-03); // Sigma(Ebeam) GeV
  pR3bGen->SetParticleDefinition(2212); // Use Particle Pdg Code
  pR3bGen->SetEnergyPrim(0.3); // Particle Energy in MeV
  Int_t fMultiplicity = 50;
  pR3bGen->SetNumberOfParticles(fMultiplicity); // Mult.

  // Reaction type
  //        1: "Elas"
  //        2: "iso"
  //        3: "Trans"
  pR3bGen->SetReactionType("Elas");

  // Target  type
  //        1: "LeadTarget"
  //        2: "Parafin0Deg"
  //        3: "Parafin45Deg"
  //        4: "LiH"

  pR3bGen->SetTargetType(Target.Data());
  Double_t thickness = (0.11/2.)/10.;  // cm
  pR3bGen->SetTargetHalfThicknessPara(thickness); // cm
  pR3bGen->SetTargetThicknessLiH(3.5); // cm
  pR3bGen->SetTargetRadius(1.); // cm

  pR3bGen->SetSigmaXInEmittance(1.); //cm
  pR3bGen->SetSigmaXPrimeInEmittance(0.0001); //cm

  // Dump the User settings
  pR3bGen->PrintParameters();  
  primGen->AddGenerator(pR3bGen);
  }


  run->SetGenerator(primGen);


  //-------Set visualisation flag to true------------------------------------
  if (fVis==kTRUE){
     run->SetStoreTraj(kTRUE);
  }else{
     run->SetStoreTraj(kFALSE);
  }   

  // -----   Initialize simulation run   ------------------------------------
  run->Init();

  // ------  Increase nb of step for CALO
  Int_t nSteps = -15000;
  gMC->SetMaxNStep(nSteps);

  // -----   Runtime database   ---------------------------------------------
  Bool_t kParameterMerged = kTRUE;
  FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged);
  parOut->open(ParFile.Data());
  rtdb->setOutput(parOut);
  rtdb->saveOutput();
  rtdb->print();
   
  // -----   Start run   ----------------------------------------------------
  if (nEvents>0) run->Run(nEvents);
  
  // -----   Finish   -------------------------------------------------------
  timer.Stop();
  Double_t rtime = timer.RealTime();
  Double_t ctime = timer.CpuTime();
  cout << endl << endl;
  cout << "Macro finished succesfully." << endl;
  cout << "Output file is "    << OutFile << endl;
  cout << "Parameter file is " << ParFile << endl;
  cout << "Real time " << rtime << " s, CPU time " << ctime 
       << "s" << endl << endl;
  // ------------------------------------------------------------------------

  cout << " Test passed" << endl;
  cout << " All ok " << endl;

}
Example #13
0
//______________________________________________________________________________
void AODtrainsim(Int_t merge=0)
{
  // Main analysis train macro.
  // merge = 0: production
  // merge = 1: intermediate merging
  // merge = 2: final merging + terminate
  // merge = 3: terminate only

  if (merge) {
    TGrid::Connect("alien://");
    if (!gGrid || !gGrid->IsConnected()) {
      ::Error("AODtrainsim.C", "No grid connection");
      return;
    }
  }
  // Set temporary merging directory to current one
  gSystem->Setenv("TMPDIR", gSystem->pwd());
  // Set temporary compilation directory to current one
  gSystem->SetBuildDir(gSystem->pwd(), kTRUE);
  printf("==================================================================\n");
  printf("===========    RUNNING FILTERING TRAIN   ==========\n");
  printf("==================================================================\n");
  printf("=  Configuring analysis train for:                               =\n");
  if (usePhysicsSelection)   printf("=  Physics selection                                                =\n");
  if (iESDfilter)   printf("=  ESD filter                                                    =\n");
  if (iMUONcopyAOD) printf("=  MUON copy AOD                                                 =\n");

  // Load common libraries and set include path
  gSystem->AddIncludePath("-I$ALICE_ROOT/include -I$ALICE_PHYSICS/include");

  // Make the analysis manager and connect event handlers
  AliAnalysisManager *mgr  = new AliAnalysisManager("Analysis Train", "Production train");
  if (useSysInfo) mgr->SetNSysInfo(100);

  // Load ParFiles
  if (!LoadAnalysisLibraries()) {
    ::Error("AODtrainsim.C", "Could not load analysis libraries");
    return;
  }
  
  // Create input handler (input container created automatically)
  // ESD input handler
  AliESDInputHandler *esdHandler = new AliESDInputHandler();
  mgr->SetInputEventHandler(esdHandler);
  // Monte Carlo handler
  if (useMC) {
    AliMCEventHandler* mcHandler = new AliMCEventHandler();
    mgr->SetMCtruthEventHandler(mcHandler);
    mcHandler->SetReadTR(useTR);
  }
  // AOD output container, created automatically when setting an AOD handler
  if (iAODhandler) {
    // AOD output handler
    AliAODHandler* aodHandler   = new AliAODHandler();
    aodHandler->SetOutputFileName("AliAOD.root");
    mgr->SetOutputEventHandler(aodHandler);
  }
  // Debugging if needed
  if (useDBG) mgr->SetDebugLevel(3);

  AddAnalysisTasks(merge);
  if (merge) {
    if (merge < 3) AODmerge();
    if (merge > 1) {
      mgr->InitAnalysis();
      mgr->SetGridHandler(new AliAnalysisAlien());
      mgr->StartAnalysis("grid terminate",0);
    }
    return;
  }
  // Run the analysis
  //
  TChain *chain = CreateChain();
  if (!chain) return;

  TStopwatch timer;
  timer.Start();
  mgr->SetSkipTerminate(kTRUE);
  if (mgr->InitAnalysis()) {
    mgr->PrintStatus();
    mgr->StartAnalysis("local", chain);
  }
  timer.Print();
}
Example #14
0
void lhsig0810()
{

  TStopwatch timer;
  timer.Start();
  // Define histogarams
  
  gStyle->SetOptFit(1111);
  gStyle->SetOptStat(111111);
  
  TGraphErrors *g1 = new TGraphErrors(20);
  g1->SetName("Dilvsdm");
  g1->SetTitle("Dilution vs. dm");
  
  TGraph *g2 = new TGraph(20);
  g2->SetName("DilErrvsdm");
  g2->SetTitle("Dil Err vs. dm");
  
  for(Int_t i=0.;i<20.;i++){


    oscpar1_init = 1+i;

    cout << "============== dm fixed at "<< oscpar1_init <<" ===================="<<endl;

    //TH1F *h1 = new TH1F("h1","Gaussian Dist",50, 4.8, 5.8);
    TH1F *h2 = new TH1F("h2","Lifetime Dist",nBins, min, max);
    TH1F *h3 = new TH1F("h3","Lifetime Dist tag=1",nBins, min, max);
    TH1F *h4 = new TH1F("h4","Lifetime Dist tag=-1",nBins, min, max);
    
    // Get data
    
    // Generate events
    
    mixmasta_mc();
    
    for (Int_t ja=0; ja<nEvts; ja++){
      h2->Fill(lifetime[ja]);
      if (tag[ja] == 1){
	h3->Fill(lifetime[ja]);
      }else if(tag[ja] == -1){
	h4->Fill(lifetime[ja]);
      }else{
	cout << "Tag value "<<tag[ja]<< " out of range, should be -1 or 1" << endl;
	break;
      }
    }
    
    // Do unbinned likelihood fit
    
    TF1 *f3 = new TF1("f3", lftmosc_plt_d, min, max, 5);
    TF1 *f4 = new TF1("f4", lftmosc_plt_d, min, max, 5);
    
    

    
    unbinFitosc_d();
    
    for (Int_t j=0; j<4; j++){
      f3->SetParameter(j,fitpar[j]);
      f4->SetParameter(j,fitpar[j]);
    }
    f3->SetParameter(4,1);
    f4->SetParameter(4,-1);
    
    g1->SetPoint(i,fitpar[1],-(1-2*fitpar[3])/dilfit);
    g1->SetPointError(i,fiterr[1],2*fiterr[3]/dilfit);
    
    g2->SetPoint(i,fitpar[1],1.65*2*fiterr[3]/dilfit);
    
    delete h2;
    delete h3;
    delete h4;
    delete f3;
    delete f4;
  }
  
  TCanvas *vardm = new TCanvas("vardm","lhsig0810",800,400);
  vardm->Divide(2,1);
  
  vardm->cd(1);
  g1->GetXaxis()->SetTitle("dm");
  g1->GetXaxis()->CenterTitle();
  g1->GetYaxis()->SetTitle("Dilution (1-2alpha)");
  g1->GetYaxis()->CenterTitle();
  //g1->SetMarkerStyle(21);
  //g1->SetMarkerSize(1);
  g1->Draw("AP*"); 
  
  
  vardm->cd(2);
  
  gStyle->SetPadColor(10);
  gStyle->SetCanvasColor(10);
  vardm->SetGrid();
  
  g2->GetXaxis()->SetTitle("dm");
  g2->GetXaxis()->CenterTitle();
  g2->GetYaxis()->SetTitle("Dil. Err");
  g2->GetYaxis()->CenterTitle();
  //g2->SetMarkerStyle(21);
  //g2->SetMarkerSize(1);
  g2->Draw("AP*");  
  
  TObjArray a1(0);
  a1.Add(g1);
  a1.Add(g2);
  a1.Add(vardm);
  
  TFile var_dm("lhsig0810.root", "recreate");
  a1.Write();
  var_dm.Close();
  
  timer.Stop();
  Double_t rtime = timer.RealTime();
  Double_t ctime = timer.CpuTime();
  
  cout << "Real time " << rtime << endl;
  cout << "CPU time  " << ctime << endl;
  
}
Example #15
0
void call_validation()
{
  TStopwatch* myWatch = new TStopwatch();
  myWatch->Start();

//   std::string inFile = "DoubleElectron_Run2012A_filteredtree.root";
  
//   std::string inFile = "GluGluToHToZZTo2L2Q_M-400_8TeV-powheg-pythia6_filteredtree.root";
  std::string inFile = "DoubleMu_Run2012A_filteredtree.root";

  /*
  displayTwoTreesRatio(inFile.data(),"genParM_",100,0,1000,false,"test",
  		       "genParId_==25");
   displayTwoTreesRatio(inFile.data(),"PU_nTrueInt",60,0,60);

  displayTwoTreesRatio(inFile.data(),"EvtInfo_VertexX_[0]",100,0.23,0.26,false,"EvtInfo_VertexX_");
  displayTwoTreesRatio(inFile.data(),"EvtInfo_VertexY_[0]",100,0.38,0.41,false,"EvtInfo_VertexY_");

//   displayTwoTreesRatio(inFile.data(),"EvtInfo_VertexX_[0]",100,0.05,0.10,false,
// 		       "EvtInfo_VertexX_");
//   displayTwoTreesRatio(inFile.data(),"EvtInfo_VertexY_[0]",100,0.04,0.08,false,
// 		       "EvtInfo_VertexY_");
  
  displayTwoTreesRatio(inFile.data(),"EvtInfo_EventNum",100,0,100000000);
  displayTwoTreesRatio(inFile.data(),"EvtInfo_RunNum",100,150000,300000);
  displayTwoTreesRatio(inFile.data(),"EvtInfo_VertexZ_[0]",100,-30,30,false,
  "EvtInfo_VertexZ_");
  */
  displayTwoTreesRatio(inFile.data(),"EvtInfo_NumVtx",30,0,30);

  /*
  displayTwoTreesRatio(inFile.data(),"patJetPfAk05Pt_",50,0, 500);
  displayTwoTreesRatio(inFile.data(),"patJetPfAk05Eta_",50,-3.0,3.0);
  displayTwoTreesRatio(inFile.data(),"patJetPfAk05Phi_",50,0,TMath::Pi());
  displayTwoTreesRatio(inFile.data(),"patJetPfAk05CharMulti_",100,0,100);
  displayTwoTreesRatio(inFile.data(),"eleRho",100,0,70);
  displayTwoTreesRatio(inFile.data(),"muoRho",100,0,10);

  displayTwoTreesRatio(inFile.data(),"higgsM",50,0,1500);
  displayTwoTreesRatio(inFile.data(),"higgsPt",50, 0,500);
  displayTwoTreesRatio(inFile.data(),"higgsEta",50, -6,6);
  displayTwoTreesRatio(inFile.data(),"higgsPhi",50, 0,TMath::Pi());

  displayTwoTreesRatio(inFile.data(),"zllPt",50, 0,500);
  displayTwoTreesRatio(inFile.data(),"zllEta",50, -6,6);
  displayTwoTreesRatio(inFile.data(),"zllPhi",50, 0,TMath::Pi());

  displayTwoTreesRatio(inFile.data(),"zjjPt",50, 0,500);
  displayTwoTreesRatio(inFile.data(),"zjjEta",50, -6,6);
  displayTwoTreesRatio(inFile.data(),"zjjPhi",50, 0,TMath::Pi());

  displayTwoTreesRatio(inFile.data(),"zllM",100,60,120);
  displayTwoTreesRatio(inFile.data(),"zjjM",100, 0,300);

  displayTwoTreesRatio(inFile.data(),"nBTags",3,-0.5,2.5);
  displayTwoTreesRatio(inFile.data(),"lepType",2,-0.5,1.5);
  displayTwoTreesRatio(inFile.data(),"heliLD",100,0.0,1.0);
  */
  displayTwoTreesRatio(inFile.data(),"metSig", 50,0, 50,true);
  /*
  displayTwoTreesRatio(inFile.data(),"patJetPfAk05NeutEmEFr_",100,0,1,true);
  displayTwoTreesRatio(inFile.data(),"patJetPfAk05NeutHadEFr_",100,0,1,true);
  displayTwoTreesRatio(inFile.data(),"patJetPfAk05CharEmEFr_",100,0,1,true);
  displayTwoTreesRatio(inFile.data(),"patJetPfAk05CharHadEFr_",100,0,1,true);

  displayTwoTreesRatio(inFile.data(),"jetPt",50,0, 500);
  displayTwoTreesRatio(inFile.data(),"jetEta",50,-3.0,3.0);
  displayTwoTreesRatio(inFile.data(),"jetPhi",50,0,TMath::Pi());
  */
  myWatch->Stop();
  cout << myWatch->RealTime() << " seconds has passed! " << endl; 

}
Example #16
0
// Macro created 20/09/2006 by S.Spataro
// It creates a geant simulation file for emc
run_sim_tpc_dpm(Int_t nEvents=10, Float_t mom = 3.6772, Int_t mode =1, UInt_t seed=0){

  gRandom->SetSeed(seed);

  TStopwatch timer;
  timer.Start();
  gDebug=0;
  // Load basic libraries
  // If it does not work,  please check the path of the libs and put it by hands
  gROOT->LoadMacro("$VMCWORKDIR/gconfig/rootlogon.C");
  rootlogon();
  
  TString digiFile = "all.par";
  TString parFile = "dpm_params_tpc.root";
  TString mcMode = "TGeant3";
  FairRunSim *fRun = new FairRunSim();

  // set the MC version used
  // ------------------------

  fRun->SetName(mcMode);
  fRun->SetOutputFile("dpm_points_tpc.root");

  // Set the parameters
  //-------------------------------
  TString allDigiFile = gSystem->Getenv("VMCWORKDIR");
  allDigiFile += "/macro/params/";
  allDigiFile += digiFile;
 
  FairRuntimeDb* rtdb = fRun->GetRuntimeDb();
  FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo();
  parIo1->open(allDigiFile.Data(),"in");
  rtdb->setFirstInput(parIo1);        
  Bool_t kParameterMerged=kTRUE;
	
  FairParRootFileIo* output=new FairParRootFileIo(kParameterMerged);
  output->open(parFile);
  rtdb->setOutput(output);
  
  // Set Material file Name
  //-----------------------
  fRun->SetMaterials("media_pnd.geo");

  // Create and add detectors
  //-------------------------
  FairModule *Cave= new PndCave("CAVE");
  Cave->SetGeometryFileName("pndcave.geo");
  fRun->AddModule(Cave); 

  FairModule *Magnet= new PndMagnet("MAGNET");
  //Magnet->SetGeometryFileName("FullSolenoid_V842.root");
  Magnet->SetGeometryFileName("FullSuperconductingSolenoid_v831.root");
  fRun->AddModule(Magnet);
  
  FairModule *Pipe= new PndPipe("PIPE");
  fRun->AddModule(Pipe);

  PndTpcDetector *Tpc = new PndTpcDetector("TPC", kTRUE);
  Tpc->SetGeometryFileName("TPC_V1.1.root");    //new ROOT geometry
  if(mcMode=="TGeant3")  Tpc->SetAliMC();
  fRun->AddModule(Tpc);

  FairDetector *Mvd = new PndMvdDetector("MVD", kTRUE);
  Mvd->SetGeometryFileName("Mvd-2.1_FullVersion.root");
  fRun->AddModule(Mvd);

  PndEmc *Emc = new PndEmc("EMC",kFALSE);
  Emc->SetGeometryVersion(19);
  Emc->SetStorageOfData(kFALSE);
  fRun->AddModule(Emc);

  //PndMdt *Muo = new PndMdt("MDT",kTRUE);
  //Muo->SetMdtMagnet(kTRUE);
//  Muo->SetMdtMFIron(kFALSE);
  //Muo->SetMdtCoil(kTRUE);
  //Muo->SetBarrel("muon_TS_barrel_strip_v1_noGeo.root");
  //Muo->SetEndcap("muon_TS_endcap_strip_v1_noGeo.root");
  //Muo->SetForward("muon_Forward_strip_v1_noGeo.root");
  //Muo->SetMuonFilter("muon_MuonFilter_strip_v1_noGeo.root");
  //fRun->AddModule(Muo);
  
  FairDetector *Gem = new PndGemDetector("GEM", kTRUE);
  Gem->SetGeometryFileName("gem_3Stations.root");
  fRun->AddModule(Gem);

  PndDsk* Dsk = new PndDsk("DSK", kFALSE);
  Dsk->SetGeometryFileName("dsk.root");
  Dsk->SetStoreCerenkovs(kFALSE);
  Dsk->SetStoreTrackPoints(kFALSE);
  fRun->AddModule(Dsk);

  PndDrc *Drc = new PndDrc("DIRC", kFALSE);
  Drc->SetGeometryFileName("dirc_l0_p0.root");
  Drc->SetRunCherenkov(kFALSE); // for fast sim Cherenkov -> kFALSE
  fRun->AddModule(Drc);
  
  // Create and Set Event Generator
  //-------------------------------

  FairPrimaryGenerator* primGen = new FairPrimaryGenerator();
  primGen->SetTarget(0., 0.5/2.355);
  primGen->SmearVertexZ(kTRUE);
  primGen->SmearGausVertexZ(kTRUE);
  primGen->SetBeam(0., 0., 0.1, 0.1);
  primGen->SmearVertexXY(kTRUE);
  fRun->SetGenerator(primGen);

  PndDpmDirect *dpmGen = new PndDpmDirect(mom,mode, gRandom->GetSeed());
  primGen->AddGenerator(dpmGen);

  // Create and Set Magnetic Field
  //-------------------------------
  fRun->SetBeamMom(mom);
  PndMultiField *fField= new PndMultiField("FULL");
  fRun->SetField(fField);

  /**Initialize the session*/
  fRun->Init();
  
  rtdb->setOutput(output);
  rtdb->saveOutput();
  rtdb->print();

  // Transport nEvents
  // -----------------
  fRun->Run(nEvents);

  timer.Stop();

  Double_t rtime = timer.RealTime();
  Double_t ctime = timer.CpuTime();
  printf("RealTime=%f seconds, CpuTime=%f seconds\n",rtime,ctime);

}
Example #17
0
void RAA_plot_finalpaper(bool isATLASCut = true){
    
  TStopwatch timer;
  timer.Start();

  TDatime date;

  gStyle->SetOptStat(0);

  TH1::SetDefaultSumw2();
  TH2::SetDefaultSumw2();

  char * etaLable = (char*) "0.0 < |#eta| < 2.0";
  char * trkMaxCut = (char*)"_";
  if(isATLASCut) trkMaxCut = (char*)"_trkMax7OrNeMax8GeVCut_";
  char * outLocation = (char*) "July20/";
  if(isATLASCut) outLocation = "July20/ATLASCut/";
  
  Float_t etaLow = 0;
  Float_t etaHigh = 2.0;
  
  TFile *fin_R2, *fin_R3, *fin_R4; 
  fin_R2 = TFile::Open(Form("July20/HiForest_JetComb_JetRAA_%disATLASCut_R0p2_MCCloSameSide_1trigcorAfterUnfo_SevilFakeMBnoLJSbJCut_RecopTCut50GeV_matrixRecoCut_%d.root", isATLASCut, date.GetDate()));
  fin_R3 = TFile::Open(Form("July20/HiForest_JetComb_JetRAA_%disATLASCut_R0p3_MCCloSameSide_1trigcorAfterUnfo_SevilFakeMBnoLJSbJCut_RecopTCut50GeV_matrixRecoCut_%d.root", isATLASCut, date.GetDate()));
  fin_R4 = TFile::Open(Form("July20/HiForest_JetComb_JetRAA_%disATLASCut_R0p4_MCCloSameSide_1trigcorAfterUnfo_SevilFakeMBnoLJSbJCut_RecopTCut50GeV_matrixRecoCut_%d.root", isATLASCut, date.GetDate()));
  
  // get the histograms.
  TH1F * uPbPb_R2_Bayes[nbins_cent], * uPP_R2_Bayes, * uPbPb_R3_Bayes[nbins_cent], * uPP_R3_Bayes, * uPbPb_R4_Bayes[nbins_cent], * uPP_R4_Bayes;
  TH1F * mPbPb_R2[nbins_cent], * mPP_R2, * mPbPb_R3[nbins_cent], * mPP_R3, * mPbPb_R4[nbins_cent], * mPP_R4;
  
  TH1F * RAA_R2_Bayes[nbins_cent], * RAA_R3_Bayes[nbins_cent], * RAA_R4_Bayes[nbins_cent];
  TH1F * RAA_R2_BinByBin[nbins_cent], * RAA_R3_BinByBin[nbins_cent], * RAA_R4_BinByBin[nbins_cent];
  TH1F * RAA_R2_Meas[nbins_cent], * RAA_R3_Meas[nbins_cent], * RAA_R4_Meas[nbins_cent];

  uPP_R2_Bayes = (TH1F*)fin_R2->Get("PP_bayesian_unfolded_spectra");
  uPP_R2_Bayes->Print("base");
  uPP_R3_Bayes = (TH1F*)fin_R3->Get("PP_bayesian_unfolded_spectra");
  uPP_R3_Bayes->Print("base");
  uPP_R4_Bayes = (TH1F*)fin_R4->Get("PP_bayesian_unfolded_spectra");
  uPP_R4_Bayes->Print("base");

  mPP_R2 = (TH1F*)fin_R2->Get("PP_Gen_spectra_refpt");
  mPP_R2->Print("base");
  mPP_R3 = (TH1F*)fin_R3->Get("PP_Gen_spectra_refpt");
  mPP_R3->Print("base");
  mPP_R4 = (TH1F*)fin_R4->Get("PP_Gen_spectra_refpt");
  mPP_R4->Print("base");
  
  for(int i = 0; i<nbins_cent; ++i){

    uPbPb_R2_Bayes[i] = (TH1F*)fin_R2->Get(Form("PbPb_bayesian_unfolded_spectra_combined_cent%d",i));
    uPbPb_R2_Bayes[i]->Print("base");
    uPbPb_R3_Bayes[i] = (TH1F*)fin_R3->Get(Form("PbPb_bayesian_unfolded_spectra_combined_cent%d",i));
    uPbPb_R3_Bayes[i]->Print("base");
    uPbPb_R4_Bayes[i] = (TH1F*)fin_R4->Get(Form("PbPb_bayesian_unfolded_spectra_combined_cent%d",i));
    uPbPb_R3_Bayes[i]->Print("base");
 
    mPbPb_R2[i] = (TH1F*)fin_R2->Get(Form("PbPb_Gen_spectra_refpt_cent%d",i));
    mPbPb_R2[i]->Print("base");
    mPbPb_R3[i] = (TH1F*)fin_R3->Get(Form("PbPb_Gen_spectra_refpt_cent%d",i));
    mPbPb_R3[i]->Print("base");
    mPbPb_R4[i] = (TH1F*)fin_R4->Get(Form("PbPb_Gen_spectra_refpt_cent%d",i));
    mPbPb_R4[i]->Print("base");
    
    RAA_R2_Bayes[i]   = (TH1F*)fin_R2->Get(Form("RAA_bayesian_cent%d",i));  
    RAA_R2_Bayes[i]->Print("base");
    RAA_R3_Bayes[i]   = (TH1F*)fin_R3->Get(Form("RAA_bayesian_cent%d",i));  
    RAA_R3_Bayes[i]->Print("base");
    RAA_R4_Bayes[i]   = (TH1F*)fin_R4->Get(Form("RAA_bayesian_cent%d",i));  
    RAA_R4_Bayes[i]->Print("base");
    
    RAA_R2_BinByBin[i]   = (TH1F*)fin_R2->Get(Form("RAA_binbybin_cent%d",i));  
    RAA_R3_BinByBin[i]   = (TH1F*)fin_R3->Get(Form("RAA_binbybin_cent%d",i));  
    RAA_R4_BinByBin[i]   = (TH1F*)fin_R4->Get(Form("RAA_binbybin_cent%d",i));  
    
    RAA_R2_Meas[i]   = (TH1F*)fin_R2->Get(Form("RAA_measured_cent%d",i));  
    RAA_R3_Meas[i]   = (TH1F*)fin_R3->Get(Form("RAA_measured_cent%d",i));  
    RAA_R4_Meas[i]   = (TH1F*)fin_R4->Get(Form("RAA_measured_cent%d",i));  
    
  }
  
  // plot 1 - spectra plot showing pp and 6 different centrality classes PbPb spectra
  //        - have a 3 panel plot for the different radii, with each of them scaled by two orders of magnitude 

  // first we need to scale the MC to the level of Data:
  // PbPb Data scaling:
  //   uPbPb_Bayes[i]->Scale(1./deltaEta);// delta eta
  //   //uPbPb_Bayes[i]->Scale(1./145.156/1e6);// Jet 80 luminosity
  //   //uPbPb_Bayes[i]->Scale(1./1.1153/1e6);// equivalent no of minbias events 
  //   uPbPb_Bayes[i]->Scale(1./(0.025*(boundaries_cent[i+1] - boundaries_cent[i])));
  //   //uPbPb_Bayes[i]->Scale(1./145.156);
  //   //uPbPb_Bayes[i]->Scale(1./161.939);
  //   uPbPb_Bayes[i]->Scale(1./(7.65*1e6));
  //   uPbPb_Bayes[i]->Scale(64.*1e9/(ncoll[i]*1e3));
  //   uPbPb_Bayes[i] = (TH1F*)uPbPb_Bayes[i]->Rebin(nbins_pt,Form("PbPb_bayesian_unfolded_spectra_combined_cent%d",i),boundaries_pt);
  //   divideBinWidth(uPbPb_Bayes[i]);
  //   uPbPb_Bayes[i]->Write();
  //   So finally PbPb is in 

  // PbPb MC scaling: is already in sigma (mb) / (dEta dpT)
  //   mPbPb_Reco[i]->Scale(1./deltaEta);// delta eta
  //   mPbPb_Reco[i] = (TH1F*)mPbPb_Reco[i]->Rebin(nbins_pt,Form("PbPb_Reco_spectra_refpt_cent%d",i),boundaries_pt);
  //   divideBinWidth(mPbPb_Reco[i]);
  //   mPbPb_Reco[i]->Write();

  // take MC to nano barns from milli barns 
  //mPP_R2->Scale(1e6);
  //mPP_R3->Scale(1e6);
  //mPP_R4->Scale(1e6);

  // for(int i = 0; i<nbins_cent; ++i){

  //   mPbPb_R2[i]->Scale(1./(0.025*(boundaries_cent[i+1] - boundaries_cent[i])));
  //   mPbPb_R2[i]->Scale(64.*1e9/(ncoll[i]*1e3));
  //   mPbPb_R2[i]->Scale(1./(7.65));

  //   mPbPb_R3[i]->Scale(1./(0.025*(boundaries_cent[i+1] - boundaries_cent[i])));
  //   mPbPb_R3[i]->Scale(64.*1e9/(ncoll[i]*1e3));
  //   mPbPb_R3[i]->Scale(1./(7.65));

  //   mPbPb_R4[i]->Scale(1./(0.025*(boundaries_cent[i+1] - boundaries_cent[i])));
  //   mPbPb_R4[i]->Scale(64.*1e9/(ncoll[i]*1e3));
  //   mPbPb_R4[i]->Scale(1./(7.65));
  
  // }
  
  Double_t ScaleFactor[nbins_cent+2] = {1, 1e2, 1e4, 1e6, 1e8, 1e10, 1e12, 1e14};  
  
  TCanvas * cSpectra_R2 = new TCanvas("cSpectra_R2","",1200,1000);
  //makeMultiPanelCanvas(cSpectra_R2,3,1,0.0,0.0,0.2,0.15,0.07);
  cSpectra_R2->SetLogy();
  //cSpectra_R2->SetGridy();
  cSpectra_R2->SetLogx();

  uPP_R2_Bayes->Scale(ScaleFactor[0]);
  uPP_R2_Bayes->SetMarkerStyle(20);
  uPP_R2_Bayes->SetMarkerColor(kBlack);
  makeHistTitle(uPP_R2_Bayes," "," Jet p_{T} (GeV/c)","#frac{d#sigma}{dp_{T} d#eta}(nb)                       #frac{d N}{T_{AA} dp_{T} d#eta} (nb)");
  uPP_R2_Bayes->SetAxisRange(60, 299, "X");
  uPP_R2_Bayes->SetAxisRange(1e-4, 1e14, "Y");
  uPP_R2_Bayes->GetYaxis()->SetMoreLogLabels(kFALSE);
  uPP_R2_Bayes->Draw();

  // draw the MC
  mPP_R2->Scale(ScaleFactor[0]);
  mPP_R2->SetLineColor(kBlack);
  mPP_R2->SetAxisRange(64, 299, "X");
  //mPP_R2->Draw("same Lhist");
  
  for(int i = 0; i<nbins_cent; ++i){
    for(int j = 0; j<uPbPb_R2_Bayes[i]->GetNbinsX(); ++j)
      uPbPb_R2_Bayes[i]->SetBinError(j+1, uPbPb_R2_Bayes[i]->GetBinError(j+1)/ScaleFactor[i+1]);
    
    uPbPb_R2_Bayes[i]->Scale(ScaleFactor[i+1]);
    uPbPb_R2_Bayes[i]->SetMarkerStyle(33);
    uPbPb_R2_Bayes[i]->SetMarkerColor(kRed);
    uPbPb_R2_Bayes[i]->SetAxisRange(60, 299, "X");
    uPbPb_R2_Bayes[i]->Draw("same");

    // mPbPb_R2[i]->Scale(ScaleFactor[i+2]);
    // mPbPb_R2[i]->SetLineColor(kRed);
    // mPbPb_R2[i]->SetAxisRange(unfoldingCut, 299, "X");
    // mPbPb_R2[i]->Draw("same Lhist");
  }

  TLegend * leg1_R2 = myLegend(0.25,0.2,0.35,0.3);
  leg1_R2->AddEntry(uPP_R2_Bayes,"PP Data","pl");
  //leg1_R2->AddEntry(mPP_R2,"PYTHIA","pl");
  leg1_R2->SetTextSize(0.02);
  leg1_R2->Draw();

  TLegend * leg2_R2 = myLegend(0.7,0.8,0.8,0.9);
  leg2_R2->AddEntry(uPbPb_R2_Bayes[0],"PbPb Data","pl");
  //leg2_R2->AddEntry(mPbPb_R2[0],"PYTHIA+HYDJET","pl");
  leg2_R2->SetTextSize(0.02);
  leg2_R2->Draw();
  
  drawText("R=0.2, anti k_{T} PF Jets", 0.25,0.2,16);
  drawText("R=0.2, anti k_{T} Pu PF Jets", 0.67,0.8,16);
  drawText(Form("%s", etaLable),0.4,0.23,16);

  putCMSPrel(0.25,0.94,0.025);
  putPbPbLumi(0.65,0.9,0.02);
  putPPLumi(0.25,0.3,0.02);
  
  //drawText("pp", 0.7,0.15,16);
  drawText("0-5% x 10^{2}", 0.7,0.28,16);
  drawText("5-10% x 10^{4}", 0.7,0.36,16);
  drawText("10-30% x 10^{6}", 0.7,0.46,16);
  drawText("30-50% x 10^{8}", 0.7,0.55,16);
  drawText("50-70% x 10^{10}", 0.7,0.64,16);
  drawText("70-90% x 10^{12}", 0.7,0.72,16);

  cSpectra_R2->SaveAs(Form("%sFinal_paper_plots_%disATLASCut_spectra_%s_akR2_%dGeVCut_%s_%d.pdf",outLocation, isATLASCut, ptbins, 50,  etaWidth,date.GetDate()),"RECREATE");

  
  TCanvas * cSpectra_R3 = new TCanvas("cSpectra_R3","",1200,1000);
  //makeMultiPanelCanvas(cSpectra_R3,3,1,0.0,0.0,0.2,0.15,0.07);
  cSpectra_R3->SetLogy();
  //cSpectra_R3->SetGridy();
  cSpectra_R3->SetLogx();

  uPP_R3_Bayes->Scale(ScaleFactor[0]);
  uPP_R3_Bayes->SetMarkerStyle(20);
  uPP_R3_Bayes->SetMarkerColor(kBlack);
  makeHistTitle(uPP_R3_Bayes," "," Jet p_{T} (GeV/c)","#frac{d#sigma}{dp_{T} d#eta}(nb)                       #frac{d N}{T_{AA} dp_{T} d#eta} (nb)");
  uPP_R3_Bayes->SetAxisRange(60, 299, "X");
  uPP_R3_Bayes->SetAxisRange(1e-4, 1e14, "Y");
  uPP_R3_Bayes->GetYaxis()->SetMoreLogLabels(kFALSE);
  uPP_R3_Bayes->Draw();

  // draw the MC
  mPP_R3->Scale(ScaleFactor[0]);
  mPP_R3->SetLineColor(kBlack);
  mPP_R3->SetAxisRange(64, 299, "X");
  //mPP_R3->Draw("same Lhist");
  
  for(int i = 0; i<nbins_cent; ++i){
    for(int j = 0; j<uPbPb_R3_Bayes[i]->GetNbinsX(); ++j)
      uPbPb_R3_Bayes[i]->SetBinError(j+1, uPbPb_R3_Bayes[i]->GetBinError(j+1)/ScaleFactor[i+1]);
    
    uPbPb_R3_Bayes[i]->Scale(ScaleFactor[i+1]);
    uPbPb_R3_Bayes[i]->SetMarkerStyle(33);
    uPbPb_R3_Bayes[i]->SetMarkerColor(kRed);
    uPbPb_R3_Bayes[i]->SetAxisRange(60, 499, "X");
    uPbPb_R3_Bayes[i]->Draw("same");

    // mPbPb_R3[i]->Scale(ScaleFactor[i+2]);
    // mPbPb_R3[i]->SetLineColor(kRed);
    // mPbPb_R3[i]->SetAxisRange(unfoldingCut, 299, "X");
    // mPbPb_R3[i]->Draw("same Lhist");
  }

  TLegend * leg1_R3 = myLegend(0.25,0.2,0.35,0.3);
  leg1_R3->AddEntry(uPP_R3_Bayes,"PP Data","pl");
  //leg1_R3->AddEntry(mPP_R3,"PYTHIA","pl");
  leg1_R3->SetTextSize(0.02);
  leg1_R3->Draw();

  TLegend * leg2_R3 = myLegend(0.7,0.8,0.8,0.9);
  leg2_R3->AddEntry(uPbPb_R3_Bayes[0],"PbPb Data","pl");
  //leg2_R3->AddEntry(mPbPb_R3[0],"PYTHIA+HYDJET","pl");
  leg2_R3->SetTextSize(0.02);
  leg2_R3->Draw();
  
  drawText("R=0.3, anti k_{T} PF Jets", 0.25,0.2,16);
  drawText("R=0.3, anti k_{T} Pu PF Jets", 0.67,0.8,16);
  drawText(Form("%s", etaLable),0.4,0.23,16);

  putCMSPrel(0.25,0.94,0.025);
  putPbPbLumi(0.65,0.9,0.02);
  putPPLumi(0.25,0.3,0.02);
  
  //drawText("pp", 0.7,0.15,16);
  drawText("0-5% x 10^{2}", 0.7,0.28,16);
  drawText("5-10% x 10^{4}", 0.7,0.36,16);
  drawText("10-30% x 10^{6}", 0.7,0.46,16);
  drawText("30-50% x 10^{8}", 0.7,0.55,16);
  drawText("50-70% x 10^{10}", 0.7,0.64,16);
  drawText("70-90% x 10^{12}", 0.7,0.72,16);

  cSpectra_R3->SaveAs(Form("%sFinal_paper_plots_%disATLASCut_spectra_%s_akR3_%dGeVCut_%s_%d.pdf",outLocation, isATLASCut, ptbins, 50, etaWidth, date.GetDate()),"RECREATE");


  
  TCanvas * cSpectra_R4 = new TCanvas("cSpectra_R4","",1200,1000);
  //makeMultiPanelCanvas(cSpectra_R4,3,1,0.0,0.0,0.2,0.15,0.07);
  cSpectra_R4->SetLogy();
  //cSpectra_R4->SetGridy();
  cSpectra_R4->SetLogx();

  uPP_R4_Bayes->Scale(ScaleFactor[0]);
  uPP_R4_Bayes->SetMarkerStyle(20);
  uPP_R4_Bayes->SetMarkerColor(kBlack);
  makeHistTitle(uPP_R4_Bayes," "," Jet p_{T} (GeV/c)","#frac{d#sigma}{dp_{T} d#eta}(nb)                       #frac{d N}{T_{AA} dp_{T} d#eta} (nb)");
  uPP_R4_Bayes->SetAxisRange(60, 299, "X");
  uPP_R4_Bayes->SetAxisRange(1e-4, 1e14, "Y");
  uPP_R4_Bayes->GetYaxis()->SetMoreLogLabels(kFALSE);
  uPP_R4_Bayes->Draw();

  // draw the MC
  mPP_R4->Scale(ScaleFactor[0]);
  mPP_R4->SetLineColor(kBlack);
  mPP_R4->SetAxisRange(64, 299, "X");
  //mPP_R4->Draw("same Lhist");
  
  for(int i = 0; i<nbins_cent; ++i){
    for(int j = 0; j<uPbPb_R4_Bayes[i]->GetNbinsX(); ++j)
      uPbPb_R4_Bayes[i]->SetBinError(j+1, uPbPb_R4_Bayes[i]->GetBinError(j+1)/ScaleFactor[i+1]);
    
    uPbPb_R4_Bayes[i]->Scale(ScaleFactor[i+1]);
    uPbPb_R4_Bayes[i]->SetMarkerStyle(33);
    uPbPb_R4_Bayes[i]->SetMarkerColor(kRed);
    uPbPb_R4_Bayes[i]->SetAxisRange(60, 299, "X");
    uPbPb_R4_Bayes[i]->Draw("same");

    // mPbPb_R4[i]->Scale(ScaleFactor[i+2]);
    // mPbPb_R4[i]->SetLineColor(kRed);
    // mPbPb_R4[i]->SetAxisRange(unfoldingCut, 299, "X");
    // mPbPb_R4[i]->Draw("same Lhist");
  }

  TLegend * leg1_R4 = myLegend(0.25,0.2,0.35,0.3);
  leg1_R4->AddEntry(uPP_R4_Bayes,"PP Data","pl");
  //leg1_R4->AddEntry(mPP_R4,"PYTHIA","pl");
  leg1_R4->SetTextSize(0.02);
  leg1_R4->Draw();

  TLegend * leg2_R4 = myLegend(0.7,0.8,0.8,0.9);
  leg2_R4->AddEntry(uPbPb_R4_Bayes[0],"PbPb Data","pl");
  //leg2_R4->AddEntry(mPbPb_R4[0],"PYTHIA+HYDJET","pl");
  leg2_R4->SetTextSize(0.02);
  leg2_R4->Draw();
  
  drawText("R=0.4, anti k_{T} PF Jets", 0.25,0.2,16);
  drawText("R=0.4, anti k_{T} Pu PF Jets", 0.67,0.8,16);
  drawText(Form("%s", etaLable),0.4,0.23,16);

  putCMSPrel(0.25,0.94,0.025);
  putPbPbLumi(0.65,0.9,0.02);
  putPPLumi(0.25,0.3,0.02);
  
  //drawText("pp", 0.7,0.15,16);
  drawText("0-5% x 10^{2}", 0.7,0.28,16);
  drawText("5-10% x 10^{4}", 0.7,0.36,16);
  drawText("10-30% x 10^{6}", 0.7,0.46,16);
  drawText("30-50% x 10^{8}", 0.7,0.55,16);
  drawText("50-70% x 10^{10}", 0.7,0.64,16);
  drawText("70-90% x 10^{12}", 0.7,0.72,16);

  cSpectra_R4->SaveAs(Form("%sFinal_paper_plots_%disATLASCut_spectra_%s_akR4_%dGeCut_%s_%d.pdf", outLocation, isATLASCut, ptbins, 50, etaWidth, date.GetDate()),"RECREATE");


}
Example #18
0
File: trcls.C Project: krafczyk/AMS
void trcls(const char *fname, const char *oname, const char *tkdbc)
{
  AMSChain ch;
  TString sfn = fname;
  if (!sfn.Contains(".root")) sfn += "*.root";
  if (ch.Add(sfn) <= 0) return;

  Int_t ntr  = ch.GetNtrees();
  Int_t nent = ch.GetEntries();
  if (ntr <= 0 || nent <= 0) return;

  cout << "Ntr,Nent= " << ntr << " " << nent << endl;

  for (Int_t i = 0; i < ntr; i++)
    cout << ch.GetListOfFiles()->At(i)->GetTitle() << endl;

  Int_t   idata[13];
  Float_t fdata[28];

  TFile of(oname, "recreate");
  TTree *tree = new TTree("tree", "trcls");
  tree->Branch("idata", idata, "run/I:event/I:ient/I:time/I:tkml[9]/I");
  tree->Branch("fdata", fdata, "engc/F:enge/F:rgt/F:chrg/F:"
	                       "p0x/F:p0y/F:dzx/F:dzy/F:csqx/F:csqy/F:"
	                       "xcog[9]/F:ycog[9]/F");

  if (tkdbc && tkdbc[0] && tkdbc[0] != '0') {
    ch.GetEvent(0);
    TkDBc::Head->init(3, tkdbc);
  }
  TrExtAlignDB::OverLoadFlag = 0;

  Int_t malg = 2; // kAlcaraz | kMultScat
  Int_t pat0 = 3; // Inner only

  Int_t nevt = 0;
  Int_t nrsl = 0;
  Int_t npsl = 0;
  Int_t nfil = 0;
  Int_t intv = 10000;

  signal(SIGTERM, handler);
  signal(SIGINT,  handler);

  TStopwatch timer;
  timer.Start();

  for (Int_t ient = 0; ient < nent && !SigTERM; ient++) {
    AMSEventR *evt = ch.GetEvent(ient);
    nevt++;

    if (nevt%intv == 0 || nevt == nent) {
      Double_t tm = timer.RealTime();
      timer.Continue();
      cout << Form("%6d %6d %6d %7d (%5.1f%%) %4.0f sec (%4.1f kHz)",
		   nrsl, npsl, nfil, nevt,
		   100.*nevt/nent, tm, nevt/tm*1e-3)
	   << endl;
    }
    if (evt->nTrRecHit() >= 1600) continue;
    if (evt->nTrTrack () !=    1) continue;

    TrTrackR *trk = evt->pTrTrack(0);
    if (!trk) continue;

    Double_t chgp = TrCharge::GetQ(trk, 1);
    Double_t chgn = TrCharge::GetQ(trk, 0);
    if (chgp <= 0 || chgn <= 0) continue;

    Int_t mfp = trk->iTrTrackPar(malg, pat0, 0);
    if (mfp < 0) continue;

    Double_t rgtp = trk->GetRigidity(mfp);
    if (TMath::Abs(rgtp) < 5) continue;


    //////////////////// Recalc and refit ////////////////////
    trk->RecalcHitCoordinates();

    Int_t mf0 = trk->iTrTrackPar(malg, pat0, 2);
    if (mf0 < 0) continue;

    Double_t rgt0 = trk->GetRigidity(mf0);
    if (TMath::Abs(rgt0) < 10) continue;
    nrsl++;


    //////////////////// Pre-selection ////////////////////
    Bool_t psel = kTRUE;
    Int_t  span = (TrTrackSelection::GetSpanFlags(trk) & 0xff);
    if (!(span & TrTrackSelection::kMaxInt) ||
	!(span & TrTrackSelection::kAllPlane)) psel = kFALSE;

    if   (!(span & TrTrackSelection::kHalfL1N)) {
      if (!(span & TrTrackSelection::kHalfL9)) psel = kFALSE;

      AMSPoint pnt = trk->InterpolateLayerJ(9);
      if (TMath::Abs(pnt.x()) > 33) psel = kFALSE;
    }
    if (psel) npsl++;

    TrTrackR::AdvancedFitBits = 0x0f;

    TrRecon trec;
    Int_t nadd = trec.MergeExtHits(trk, mf0);
    if (!psel && nadd <= 0) continue;

    //////////////////// Remerge ////////////////////
    if (nadd > 0) {
      psel = kTRUE;
      span = (TrTrackSelection::GetSpanFlags(trk) & 0xff);
      if (!(span & TrTrackSelection::kMaxInt) ||
	  !(span & TrTrackSelection::kAllPlane)) psel = kFALSE;

      if   (!(span & TrTrackSelection::kHalfL1N)) {
	if (!(span & TrTrackSelection::kHalfL9)) psel = kFALSE;

	AMSPoint pnt = trk->InterpolateLayerJ(9);
	if (TMath::Abs(pnt.x()) > 33) psel = kFALSE;
      }
    }
    if (!psel) continue;

    idata[0] = evt->Run();
    idata[1] = evt->Event();
    idata[2] = ient;
    idata[3] = evt->fHeader.Time[0];

    EcalShowerR *ecal = evt->pEcalShower(0);
    fdata[0] = (ecal) ? ecal->EnergyC : 0;
    fdata[1] = (ecal) ? ecal->EnergyE : 0;
    fdata[2] = rgt0;
    fdata[3] = (chgp+chgn)/2;
    fdata[4] = trk->GetP0x(mf0);
    fdata[5] = trk->GetP0y(mf0);
    fdata[6] = trk->GetThetaXZ(mf0);
    fdata[7] = trk->GetThetaYZ(mf0);
    fdata[8] = trk->GetNormChisqX(mf0);
    fdata[9] = trk->GetNormChisqY(mf0);

    if (evt->nMCEventg() > 0) {
      MCEventgR *mcg = evt->pMCEventg(0);
      if (mcg) fdata[0] = mcg->Momentum;
    }

    Int_t   *tkml = &idata[ 4];
    Float_t *xcog = &fdata[10];
    Float_t *ycog = &fdata[19];
    for (Int_t i = 0; i < 9; i++) { tkml[i] = 0; xcog[i] = ycog[i] = 0; }

    for (Int_t i = 0; i < trk->GetNhits(); i++) {
      TrRecHitR *hit = trk->GetHit(i);
      if (!hit) continue;

      Int_t layer = hit->GetLayer();
      //if (layer != 8 && layer != 9) continue;

      Int_t il   = layer-1;//layer-8;
      Int_t tkid = hit->GetTkId();
      Int_t imlt = hit->GetResolvedMultiplicity();

      TrClusterR *clx = hit->GetXCluster();
      TrClusterR *cly = hit->GetYCluster();
      tkml[il] = TMath::Sign(imlt*1000+TMath::Abs(tkid), tkid);
      xcog[il] = (!clx) ? -(hit->GetDummyX()+640)
	       : clx->GetCofG()+clx->GetSeedAddress();
      ycog[il] = cly->GetCofG()+cly->GetSeedAddress();
    }

    tree->Fill();
    nfil++;
  }

  of.cd();
  tree->Write();
}
Example #19
0
void rec() {

  AliReconstruction reco;

//
// switch off cleanESD, write ESDfriends and Alignment data

  reco.SetCleanESD(kFALSE);
  reco.SetWriteESDfriend();
  reco.SetWriteAlignmentData();

//
// ITS Efficiency and tracking errors

  reco.SetRunPlaneEff(kTRUE);
  reco.SetUseTrackingErrorsForAlignment("ITS");

//
// Residual OCDB

  reco.SetDefaultStorage("alien://Folder=/alice/simulation/2008/v4-15-Release/Residual/");


//
// GRP from local OCDB

 reco.SetSpecificStorage("GRP/GRP/Data",
                          Form("local://%s",gSystem->pwd()));


//
// Vertex from RAW OCDB

  reco.SetSpecificStorage("GRP/Calib/MeanVertexTPC","alien://folder=/alice/data/2010/OCDB");
  reco.SetSpecificStorage("GRP/Calib/MeanVertex","alien://folder=/alice/data/2010/OCDB");
  reco.SetSpecificStorage("GRP/Calib/MeanVertexSPD", "alien://folder=/alice/data/2010/OCDB");

//
// EMCAL from RAW OCDB

  reco.SetSpecificStorage("EMCAL/Calib/Data","alien://Folder=/alice/data/2010/OCDB");
  reco.SetSpecificStorage("EMCAL/Calib/Pedestals","alien://Folder=/alice/data/2010/OCDB");

//
// PHOS from RAW OCDB

  reco.SetSpecificStorage("PHOS/Calib/EmcBadChannels","alien://Folder=/alice/data/2010/OCDB");

//
// SPD and SDD from RAW OCDB

  reco.SetSpecificStorage("ITS/Calib/SPDDead","alien://folder=/alice/data/2010/OCDB");
  reco.SetSpecificStorage("TRIGGER/SPD/PITConditions","alien://folder=/alice/data/2010/OCDB");
  reco.SetSpecificStorage("ITS/Calib/SPDNoise","alien://folder=/alice/data/2010/OCDB");
  reco.SetSpecificStorage("ITS/Calib/CalibSDD","alien://Folder=/alice/data/2010/OCDB");

//
// TRD from RAW OCDB

  reco.SetSpecificStorage("TRD/Calib/ChamberStatus","alien://folder=/alice/data/2010/OCDB");
  reco.SetSpecificStorage("TRD/Calib/PadStatus","alien://folder=/alice/data/2010/OCDB");

//
// TPC from RAW OCDB

  reco.SetSpecificStorage("TPC/Calib/PadGainFactor","alien://folder=/alice/data/2010/OCDB");

//
// V0 from RAW OCDB

  reco.SetSpecificStorage("VZERO/Trigger/Data","alien://folder=/alice/data/2010/OCDB");
  reco.SetSpecificStorage("VZERO/Calib/RecoParam","alien://folder=/alice/data/2010/OCDB");
  reco.SetSpecificStorage("VZERO/Calib/Data","alien://folder=/alice/data/2010/OCDB");
  reco.SetSpecificStorage("VZERO/Calib/TimeSlewing","alien://folder=/alice/data/2010/OCDB");
  reco.SetSpecificStorage("VZERO/Calib/TimeDelays","alien://folder=/alice/data/2010/OCDB");

//
// TOF from RAW OCDB

  reco.SetSpecificStorage("TOF/Calib/Status","alien://folder=/alice/data/2010/OCDB");

//
// FMD from RAW OCDB

  reco.SetSpecificStorage("FMD/Calib/Pedestal", "alien://folder=/alice/data/2010/OCDB");
  reco.SetSpecificStorage("FMD/Calib/PulseGain","alien://folder=/alice/data/2010/OCDB");
  reco.SetSpecificStorage("FMD/Calib/Dead", "alien://folder=/alice/data/2010/OCDB");
  reco.SetSpecificStorage("FMD/Calib/AltroMap","alien://folder=/alice/data/2010/OCDB");



//
  TStopwatch timer;
  timer.Start();
  reco.Run();
  timer.Stop();
  timer.Print();
}
Example #20
0
void run_unpack_alpha
(TString dataFile = "runfiles/NSCL/alphas/alpha_run_0100.txt",TString parameterFile = "ATTPC.alpha.par",
TString mappath="/data/ar46/run_0085/")
{

  // -----   Timer   --------------------------------------------------------
 TStopwatch timer;
 timer.Start();
 // ------------------------------------------------------------------------

  gSystem->Load("libXMLParser.so");
  // -----------------------------------------------------------------
  // Set file names
  TString scriptfile = "Lookup20150611.xml";
  TString dir = getenv("VMCWORKDIR");
  TString scriptdir = dir + "/scripts/"+ scriptfile;
  TString dataDir = dir + "/macro/data/";
  TString geomDir = dir + "/geometry/";
  gSystem -> Setenv("GEOMPATH", geomDir.Data());

  //TString inputFile   = dataDir + name + ".digi.root";
  //TString outputFile  = dataDir + "output.root";
  TString outputFile  = "output.root";
  //TString mcParFile   = dataDir + name + ".params.root";
  TString loggerFile  = dataDir + "ATTPCLog.log";
  TString digiParFile = dir + "/parameters/" + parameterFile;
  TString geoManFile  = dir + "/geometry/ATTPC_v1.2.root";

  TString inimap   = mappath + "inhib.txt";
  TString lowgmap  = mappath + "lowgain.txt";
  TString xtalkmap = mappath + "beampads_e15503b.txt";

  // -----------------------------------------------------------------
  // Logger
  FairLogger *fLogger = FairLogger::GetLogger();
  fLogger -> SetLogFileName(loggerFile);
  fLogger -> SetLogToScreen(kTRUE);
  fLogger -> SetLogToFile(kTRUE);
  fLogger -> SetLogVerbosityLevel("LOW");

  FairRunAna* run = new FairRunAna();
  run -> SetOutputFile(outputFile);
  //run -> SetGeomFile("../geometry/ATTPC_Proto_v1.0.root");
  run -> SetGeomFile(geoManFile);

  FairRuntimeDb* rtdb = run->GetRuntimeDb();
  FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo();
  parIo1 -> open(digiParFile.Data(), "in");
  //FairParRootFileIo* parIo2 = new FairParRootFileIo();
  //parIo2 -> open("param.dummy_proto.root");
 // rtdb -> setFirstInput(parIo2);
  rtdb -> setSecondInput(parIo1);

  // Settings
  Bool_t fUseDecoder = kTRUE;
  if (dataFile.IsNull() == kTRUE)
    fUseDecoder = kFALSE;

  Bool_t fUseSeparatedData = kFALSE;
    if (dataFile.EndsWith(".txt"))
      fUseSeparatedData = kTRUE;

 /*
  *     Unpacking options:
  *         - SetUseSeparatedData:      To be used with 10 CoBo files without merging. Mainly for the ATTPC. Enabled if the input file is a txt.
  *         - SetPseudoTopologyFrame:   Used to force the graw file to have a Topology frame.
  *         - SetPersistance:           Save the unpacked data into the root file.
  *         - SetMap:                   Chose the lookup table.
  *         - SetMapOpt                 Chose the pad plane geometry. In addition forces the unpacker to use Basic Frames for 1 single file (p-ATTPC case) of Layered
  *                                     Frames for Merged Data (10 Cobos merged data).
  */
  ATDecoder2Task *fDecoderTask = new ATDecoder2Task();
  fDecoderTask -> SetUseSeparatedData(fUseSeparatedData);
  if(fUseSeparatedData) fDecoderTask -> SetPseudoTopologyFrame(kTRUE);//! This calls the method 10 times so for less than 10 CoBos ATCore2 must be modified
  //fDecoderTask -> SetPositivePolarity(kTRUE);
  fDecoderTask -> SetPersistence(kFALSE);
  fDecoderTask -> SetMap(scriptdir.Data());
  //fDecoderTask -> SetInhibitMaps(inimap,lowgmap,xtalkmap); // TODO: Only implemented for fUseSeparatedData!!!!!!!!!!!!!!!!!!!1
  fDecoderTask -> SetMapOpt(0); // ATTPC : 0  - Prototype: 1 |||| Default value = 0
  fDecoderTask -> SetNumCobo(9);
  fDecoderTask -> SetEventID(0);


  /*if (!fUseSeparatedData)
    fDecoderTask -> AddData(dataFile);
  else {
    std::ifstream listFile(dataFile.Data());
    TString dataFileWithPath;
    Int_t iCobo = 0;
    while (dataFileWithPath.ReadLine(listFile)) {
        if (dataFileWithPath.Contains(Form("CoBo%i",iCobo)) )
              fDecoderTask -> AddData(dataFileWithPath, iCobo);
        else{
          iCobo++;
          fDecoderTask -> AddData(dataFileWithPath, iCobo);
        }
    }
  }*/

  fDecoderTask -> AddData("/data/ND/2013/buffer/NSCL_Alpha/run_0100/CoBo0_run_0100_11Dec14_22h03m15s.graw",0);
  fDecoderTask -> AddData("/data/ND/2013/buffer/NSCL_Alpha/run_0100/CoBo1_run_0100_11Dec14_22h03m15s.graw",1);
  fDecoderTask -> AddData("/data/ND/2013/buffer/NSCL_Alpha/run_0100/CoBo2_run_0100_11Dec14_22h03m15s.graw",2);
  fDecoderTask -> AddData("/data/ND/2013/buffer/NSCL_Alpha/run_0100/CoBo2_run_0100_11Dec14_22h03m15s.1.graw",2);
  fDecoderTask -> AddData("/data/ND/2013/buffer/NSCL_Alpha/run_0100/CoBo3_run_0100_11Dec14_22h03m16s.graw",3);
  fDecoderTask -> AddData("/data/ND/2013/buffer/NSCL_Alpha/run_0100/CoBo4_run_0100_11Dec14_22h03m16s.graw",4);
  fDecoderTask -> AddData("/data/ND/2013/buffer/NSCL_Alpha/run_0100/CoBo6_run_0100_11Dec14_22h03m16s.graw",5);
  fDecoderTask -> AddData("/data/ND/2013/buffer/NSCL_Alpha/run_0100/CoBo7_run_0100_11Dec14_22h03m16s.graw",6);
  fDecoderTask -> AddData("/data/ND/2013/buffer/NSCL_Alpha/run_0100/CoBo7_run_0100_11Dec14_22h03m16s.1.graw",6);
  fDecoderTask -> AddData("/data/ND/2013/buffer/NSCL_Alpha/run_0100/CoBo8_run_0100_11Dec14_22h03m16s.graw",7);
  fDecoderTask -> AddData("/data/ND/2013/buffer/NSCL_Alpha/run_0100/CoBo9_run_0100_11Dec14_22h03m16s.graw",8);

  run -> AddTask(fDecoderTask);

  ATPSATask *psaTask = new ATPSATask();
  psaTask -> SetPersistence(kTRUE);
  psaTask -> SetThreshold(20);
  psaTask -> SetPSAMode(1); //NB: 1 is ATTPC - 2 is pATTPC
	//psaTask -> SetPeakFinder(); //NB: Use either peak finder of maximum finder but not both at the same time
	psaTask -> SetMaxFinder();
  psaTask -> SetBaseCorrection(kTRUE); //Directly apply the base line correction to the pulse amplitude to correct for the mesh induction. If false the correction is just saved
  psaTask -> SetTimeCorrection(kFALSE); //Interpolation around the maximum of the signal peak
  run -> AddTask(psaTask);

  ATHoughTask *HoughTask = new ATHoughTask();
	HoughTask ->SetPersistence();
	HoughTask ->SetLinearHough();
	//HoughTask ->SetCircularHough();
  HoughTask ->SetHoughThreshold(100.0); // Charge threshold for Hough
  HoughTask ->SetHoughDistance(5.0);//This is the distance to reject points from a given linear Hough Space
	run -> AddTask(HoughTask);


  run -> Init();

  //run -> RunOnTBData();
  run->Run(0,200);

  std::cout << std::endl << std::endl;
  std::cout << "Macro finished succesfully."  << std::endl << std::endl;
  std::cout << "- Output file : " << outputFile << std::endl << std::endl;
  // -----   Finish   -------------------------------------------------------
  timer.Stop();
  Double_t rtime = timer.RealTime();
  Double_t ctime = timer.CpuTime();
  cout << endl << endl;
  cout << "Real time " << rtime << " s, CPU time " << ctime << " s" << endl;
  cout << endl;
  // ------------------------------------------------------------------------

  //gApplication->Terminate();

}
void ana_MC_BTagEff_test(TString ds="relval", TString physics="ttbar") {
{
  gSystem->Load("libSusyEvent.so");

  // Look ../jec/JetMETObjects/README
  gSystem->Load("../jec/lib/libJetMETObjects.so");

  // Printing utility for ntuple variables
  gROOT->LoadMacro("SusyEventPrinter.cc+");

  // Main analysis code
  gROOT->LoadMacro("SusyAna_MC_BTagEff_test.cc+"); //this line causes everything to segfault at the end.

  // chain of inputs
  TChain* chain = new TChain("susyTree");

//////////////// MC files /////////////////
  //MCpoint* thisMCpoint = setupMCpoint(which_MC_to_use); 
//cout<<"try to add "<<thisMCpoint->filepath.c_str()<<endl;
  //chain->Add(thisMCpoint->filepath.c_str()); 
//int which_MC_to_use=0; //already set
/*if(which_MC_to_use==0){
   chain->Add("MC/susyEvents_MC_AB_1M_st350_ho200.root");
}
else if(which_MC_to_use==1){
   chain->Add("MC/susyEvents_MC_AB_1M_st250_ho200.root");
}
else if(which_MC_to_use==2){
   chain->Add("MC/susyEvents_MC_AB_1M_st250_ho150.root");
}
else if(which_MC_to_use==3){
   chain->Add("MC/susyEvents_MC_AB_1M_ho140.root");
}
else if(which_MC_to_use==4){
   chain->Add("MC/susyEvents_MC_AB_1M_ho200.root");
}
*/


   //chain->Add("../susyEvents_AB_1M_ho200_v2.root");
   chain->Add("../susyEvents_newNatural.root");
   //chain->Add("/eos/uscms/store/user/abarker/MC/newNat350_225/MC_AB_2500k_NEWnaturalHiggsinoNLSPout_mst_350_M3_5025_mu_225.root");//same thing as ../susyEvents_newNatural.root
   //chain->Add("/eos/uscms/store/user/abarker/MC/st_250_ho_150/MC_AB_2500k_st_250_ho_150.root");
   //chain->Add("/eos/uscms/store/user/abarker/MC/st_250_ho_200/MC_AB_2500k_st_250_ho_200.root");
   //chain->Add("/eos/uscms/store/user/abarker/MC/st_350_ho_200/MC_AB_2500k_mst_350_mu_200.root");
   //chain->Add("/eos/uscms/store/user/abarker/MC/ho_140/MC_AB_2500k_ho_140.root");
   //chain->Add("/eos/uscms/store/user/abarker/MC/ho_200/MC_AB_2500k_ho_200.root");


   //chain->Add("../susyEvents_newNatural.root");
    //chain->Add("dcache:/pnfs/cms/WAX/resilient/abarker/MC/MC_AB_2500k_NEWnaturalHiggsinoNLSPout_mst_350_M3_5025_mu_225.root");

   //chain->Add("dcache:/pnfs/cms/WAX/resilient/abarker/MC/MC_AB_2500k_st_250_ho_150.root");
   //chain->Add("dcache:/pnfs/cms/WAX/resilient/abarker/MC/MC_AB_2500k_st_250_ho_200.root");
   //chain->Add("dcache:/pnfs/cms/WAX/resilient/abarker/MC/MC_AB_2500k_mst_350_mu_200.root");
   //chain->Add("dcache:/pnfs/cms/WAX/resilient/abarker/MC/MC_AB_2500k_ho_140.root");
   //chain->Add("dcache:/pnfs/cms/WAX/resilient/abarker/MC/MC_AB_2500k_ho_200.root");


  SusyAna_MC_BTagEff_test* sea = new SusyAna_MC_BTagEff_test(chain);

  // configuration parameters
  // any values given here will replace the default values
  sea->SetDataset(physics+"_"+ds);        // dataset name
  sea->SetPrintInterval(1e4);             // print frequency
  sea->SetPrintLevel(0);                  // print level for event contents
  sea->SetUseTrigger(false);
/*
  sea->AddHltName("HLT_Photon36_CaloIdL_Photon22_CaloIdL");  // add HLT trigger path name 
  sea->AddHltName("HLT_Photon32_CaloIdL_Photon26_CaloIdL");  // add HLT trigger path name
  sea->AddHltName("HLT_Photon26_R9Id85_Photon18_R9Id85_Mass60");
  sea->AddHltName("HLT_Photon26_R9Id85_Photon18_CaloId10_Iso50_Mass60");
  sea->AddHltName("HLT_Photon26_CaloId10_Iso50_Photon18_R9Id85_Mass60");
  sea->AddHltName("HLT_Photon26_CaloId10_Iso50_Photon18_CaloId10_Iso50_Mass60");
  sea->AddHltName("HLT_Photon26_R9Id85_OR_CaloId10_Iso50_Photon18_R9Id85_OR_CaloId10_Iso50_Mass60");
  sea->AddHltName("HLT_Photon26_R9Id85_OR_CaloId10_Iso50_Photon18_R9Id85_OR_CaloId10_Iso50_Mass70");
  sea->AddHltName("HLT_Photon36_R9Id85_Photon22_R9Id85");
  sea->AddHltName("HLT_Photon36_R9Id85_Photon22_CaloId10_Iso50");
  sea->AddHltName("HLT_Photon36_CaloId10_Iso50_Photon22_R9Id85");
  sea->AddHltName("HLT_Photon36_CaloId10_Iso50_Photon22_CaloId10_Iso50");
  sea->AddHltName("HLT_Photon36_R9Id85_OR_CaloId10_Iso50_Photon22_R9Id85_OR_CaloId10_Iso50");
*/
  sea->SetFilter(true);                  // filter events passing final cuts
  sea->SetProcessNEvents(-1);             // number of events to be processed

  // as an example -- add your favorite Json here.  More than one can be "Include"ed
  //  sea->IncludeAJson("Cert_161079-161352_7TeV_PromptReco_Collisions11_JSON_noESpbl_v2.txt");
  //sea->IncludeAJson("anotherJSON.txt");

  TStopwatch ts;

  ts.Start();

  sea->Loop();

  ts.Stop();

  std::cout << "RealTime : " << ts.RealTime()/60.0 << " minutes" << std::endl;
  std::cout << "CPUTime  : " << ts.CpuTime()/60.0 << " minutes" << std::endl;
	}
  std::cout << "super end"<<std::endl;
	

}
Example #22
0
void run_unpack_proto_v2(){


    // -----   Timer   --------------------------------------------------------
	TStopwatch timer;
	timer.Start();
  // ------------------------------------------------------------------------


   gSystem->Load("libXMLParser.so");

   TString scriptfile = "LookupProto20150331.xml";
   TString protomapfile = "proto.map";
   TString dir = getenv("VMCWORKDIR");
   TString scriptdir = dir + "/scripts/"+ scriptfile;
   TString protomapdir = dir + "/scripts/"+ protomapfile;
   TString geo = "proto_geo_hires.root";


   FairLogger *logger = FairLogger::GetLogger();
   logger -> SetLogFileName("ATTPCLog.log");
   logger -> SetLogToFile(kTRUE);
   logger -> SetLogToScreen(kTRUE);
   logger -> SetLogVerbosityLevel("MEDIUM");


   FairRunAna* run = new FairRunAna();
   //run -> SetInputFile("mc.dummy_proto.root");
   run -> SetOutputFile("output_proto.root");
   //run -> SetGeomFile("../geometry/ATTPC_Proto_v1.0.root");

   TString file = "../../parameters/AT.parameters.par";

   FairRuntimeDb* rtdb = run->GetRuntimeDb();
   FairParAsciiFileIo* parIo1 = new FairParAsciiFileIo();
   parIo1 -> open(file.Data(), "in");
   //FairParRootFileIo* parIo2 = new FairParRootFileIo();
   //parIo2 -> open("param.dummy_proto.root");
  // rtdb -> setFirstInput(parIo2);
   rtdb -> setSecondInput(parIo1);

   ATDecoderTask *decoderTask = new ATDecoderTask();
   //decoderTask ->SetDebugMode(kTRUE);
   decoderTask ->SetMapOpt(1); // ATTPC : 0  - Prototype: 1 |||| Default value = 0
   //decoderTask -> AddData("/home/ayyadlim/Desktop/Yassid/ATTPC/Data/Notre_Dame_data/CoBo_AsAd0_2015-01-27T15_19_34.962_0000.graw");//12B
   //decoderTask -> AddData("/home/ayyadlim/Desktop/Yassid/ATTPC/Data/Notre_Dame_data/CoBo_AsAd0_2015-01-27T07_16_00.696_0000.graw");
   //decoderTask -> AddData("/Users/yassidayyad/Desktop/ATTPC/Data/Notre_Dame_data/CoBo_AsAd0_2015-01-27T15_19_34.962_0000.graw");
   //decoderTask ->AddData("/home/ayyadlim/Desktop/Yassid/ATTPC/Data/Notre_Dame_data/CoBo_AsAd0_2015-01-26T19_33_23.451_0003.graw"); //12N
   //decoderTask -> AddData("/home/ayyadlim/Desktop/Yassid/ATTPC/Data/Notre_Dame_data/CoBo_AsAd0_2015-01-28T07:02:50.291_0000.graw");//12B High Pressure
   //decoderTask -> AddData("/home/ayyadlim/Desktop/Yassid/ATTPC/Data/Notre_Dame_data/CoBo_AsAd0_2015-01-28T16:56:24.135_0000.graw");//12B Low Pressure
   decoderTask -> AddData("/home/ayyadlim/Desktop/Yassid/ATTPC/Data/TRIUMF/CoBo_AsAd0_2015-12-01T07_35_27.482_0009.graw");//8He TRIUMF
	//  decoderTask -> AddData("/home/ayyadlim/Desktop/Yassid/ATTPC/Data/Notre_Dame_data/10Be/CoBo_2013-02-21_12-52-57_0006.graw"); //10Be
   //decoderTask -> AddData("/home/s1257/fair_install_ROOT6/data/CoBo_AsAd0_2015-12-03T05:47:43.571_0001.graw");//12B Low Pressure
   //decoderTask -> AddData("/home/daq/Desktop/Data/run_0014/CoBo_AsAd0_2015-07-29T15_45_17.971_0000.graw");
   //decoderTask->AddData("/home/daq/Desktop/Data/run_0028/CoBo_AsAd0_2015-07-29T19_02_32.783_0000.graw");
   decoderTask ->SetGeo(geo.Data());
   decoderTask ->SetProtoMap(protomapdir.Data());
   decoderTask ->SetMap((Char_t const*) scriptdir.Data());
   decoderTask -> SetPositivePolarity(kTRUE);
   decoderTask -> SetFPNPedestal(6);
   //decoderTask->SetInternalPedestal();
   decoderTask -> SetNumTbs(512);
   //decoderTask -> SetPersistence();
   decoderTask -> SetGetRawEventMode(1);
   run -> AddTask(decoderTask);

   ATPSATask *psaTask = new ATPSATask();
   psaTask -> SetPersistence();
   psaTask -> SetBackGroundPeakFinder(kFALSE); // Suppress background of each pad for noisy data (Larger computing Time)
   psaTask -> SetThreshold(20);
   psaTask -> SetPeakFinder(); //Note: For the moment not affecting the prototype PSA Task
   run -> AddTask(psaTask);

   ATPhiRecoTask *phirecoTask = new ATPhiRecoTask();
   phirecoTask -> SetPersistence();
   run -> AddTask(phirecoTask);

   /*ATHoughTask *HoughTask = new ATHoughTask();
   HoughTask->SetPhiReco();
   HoughTask->SetPersistence();
   HoughTask->SetLinearHough();
	 HoughTask->SetRadiusThreshold(3.0); // Truncate Hough Space Calculation
   //HoughTask ->SetCircularHough();
   run ->AddTask(HoughTask);*/

   run->Init();

   run->Run(0,100); // Number must be lower than the number of events in dummy

 // -----   Finish   -------------------------------------------------------
	timer.Stop();
	Double_t rtime = timer.RealTime();
	Double_t ctime = timer.CpuTime();
	cout << endl << endl;
	cout << "Macro finished succesfully." << endl;
	cout << "Real time " << rtime << " s, CPU time " << ctime << " s" << endl;
	cout << endl;
  // ------------------------------------------------------------------------


}
Example #23
0
void run_sim(Int_t nEvents = 100, TString mcEngine = "TGeant4")
{
    
  // Output file name
  TString outFile ="test.root";
    
  // Parameter file name
  TString parFile="params.root";
  
  // -----   Timer   --------------------------------------------------------
  TStopwatch timer;
  timer.Start();
  // ------------------------------------------------------------------------

  // -----   Create simulation run   ----------------------------------------
  FairRunSim* run = new FairRunSim();
  run->SetName(mcEngine);              // Transport engine
  run->SetOutputFile(new FairRootFileSink(outFile));          // Output file
  FairRuntimeDb* rtdb = run->GetRuntimeDb();
  // ------------------------------------------------------------------------
  
  // -----   Create media   -------------------------------------------------
  run->SetMaterials("media.geo");       // Materials
  // ------------------------------------------------------------------------
  
  // -----   Create geometry   ----------------------------------------------

  FairModule* cave= new MyCave("CAVE");
  cave->SetGeometryFileName("cave.geo");
  run->AddModule(cave);

  FairModule* magnet = new MyMagnet("Magnet");
  run->AddModule(magnet);

  FairModule* pipe = new MyPipe("Pipe");
  run->AddModule(pipe);
    
  FairDetector* NewDet = new NewDetector("TestDetector", kTRUE);
  run->AddModule(NewDet);

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


    // -----   Magnetic field   -------------------------------------------
    // Constant Field
    MyConstField  *fMagField = new MyConstField();
    fMagField->SetField(0., 20. ,0. ); // values are in kG
    fMagField->SetFieldRegion(-200, 200,-200, 200, -200, 200); // values are in cm
                          //  (xmin,xmax,ymin,ymax,zmin,zmax)
    run->SetField(fMagField);
    // --------------------------------------------------------------------

    
    
  // -----   Create PrimaryGenerator   --------------------------------------
  FairPrimaryGenerator* primGen = new FairPrimaryGenerator();
  
    // Add a box generator also to the run
    FairBoxGenerator* boxGen = new FairBoxGenerator(13, 5); // 13 = muon; 1 = multipl.
    boxGen->SetPRange(20,25); // GeV/c
    boxGen->SetPhiRange(0., 360.); // Azimuth angle range [degree]
    boxGen->SetThetaRange(0., 90.); // Polar angle in lab system range [degree]
    boxGen->SetXYZ(0., 0., 0.); // cm
    primGen->AddGenerator(boxGen);
  
    
    run->SetGenerator(primGen);
// ------------------------------------------------------------------------
 
  //---Store the visualiztion info of the tracks, this make the output file very large!!
  //--- Use it only to display but not for production!
  run->SetStoreTraj(kTRUE);

    
    
  // -----   Initialize simulation run   ------------------------------------
  run->Init();
  // ------------------------------------------------------------------------

  // -----   Runtime database   ---------------------------------------------

  Bool_t kParameterMerged = kTRUE;
  FairParRootFileIo* parOut = new FairParRootFileIo(kParameterMerged);
  parOut->open(parFile.Data());
  rtdb->setOutput(parOut);
  rtdb->saveOutput();
  rtdb->print();
  // ------------------------------------------------------------------------
   
  // -----   Start run   ----------------------------------------------------
   run->Run(nEvents);
    
  //You can export your ROOT geometry ot a separate file
  run->CreateGeometryFile("geofile_full.root");
  // ------------------------------------------------------------------------
  
  // -----   Finish   -------------------------------------------------------
  timer.Stop();
  Double_t rtime = timer.RealTime();
  Double_t ctime = timer.CpuTime();
  cout << endl << endl;
  cout << "Macro finished succesfully." << endl;
  cout << "Output file is "    << outFile << endl;
  cout << "Parameter file is " << parFile << endl;
  cout << "Real time " << rtime << " s, CPU time " << ctime 
       << "s" << endl << endl;
  // ------------------------------------------------------------------------
}
Example #24
0
void AliTRDanalyzeTestBeam(Int_t run, Int_t begin, Int_t end) {
  
  gROOT->SetStyle("Plain");
  //gStyle->SetPadTopMargin(0.02);
  //gStyle->SetPadRightMargin(0.02);
  //gStyle->SetPadLeftMargin(0.1);

  gStyle->SetPalette(1);
  gStyle->SetOptStat(0);
  gStyle->SetOptDate();
  
  TGaxis::SetMaxDigits(3);

  TStopwatch st;
  st.Start();

  const Int_t N = 640;

  // declare histograms
  const int nbins = 100;
  const int nstart = 0;

  TH1D *mSi1L = new TH1D("mSi1L", ";number of Si1 fired pads", 50, nstart-0.5, nstart+nbins-0.5);
  TH1D *mSi2L = new TH1D("mS21L", ";number of Si2 fired pads", 50, nstart-0.5, nstart+nbins-0.5);
 
  TProfile *mSi1ChP = new TProfile("mSi1ChP",";Si1 pad number;signal", 1280, -0.5, 1279.5, 0, 200, "s");
  TProfile *mSi2ChP = new TProfile("mS21ChP",";Si2 pad number;signal", 1280, -0.5, 1279.5, 0, 200, "s");
  
  TH1D *mSi1N = new TH1D("mSi1N", "Noise Dist Si1;ADC", 100, 0, 50);
  TH1D *mSi2N = new TH1D("mSi2N", "Noise Dist Si2;ADC", 100, 0, 50);
  
  TH1D *mSiCh[4];
  mSiCh[0] = new TH1D("mSi1ChX", ";Si1X pad amplitude (ADC)", 250, -0.5, 249.5);
  mSiCh[1] = new TH1D("mSi1ChY", ";Si1Y pad amplitude (ADC)", 250, -0.5, 249.5);
  mSiCh[2] = new TH1D("mSi2ChX", ";Si2X pad amplitude (ADC)", 250, -0.5, 249.5);
  mSiCh[3] = new TH1D("mSi2ChY", ";Si2Y pad amplitude (ADC)", 250, -0.5, 249.5);
  
  TH1D *mSiFullCh[4];
  mSiFullCh[0] = new TH1D("mSi1fChX", "Si1X;max amplitude (ADC)", 300, -0.5, 299.5);
  mSiFullCh[1] = new TH1D("mSi1fChY", "Si1Y;max amplitude (ADC)", 300, -0.5, 299.5);
  mSiFullCh[2] = new TH1D("mSi2fChX", "Si2X;max amplitude (ADC)", 300, -0.5, 299.5);
  mSiFullCh[3] = new TH1D("mSi2fChY", "Si2Y;max amplitude (ADC)", 300, -0.5, 299.5);  

  TH2D *mPos[2];
  mPos[0] = new TH2D("posSi1", ";x Si1 (mm);y Si1 (mm)", 128, 0, 32, 128, 0, 32);
  mPos[1] = new TH2D("posSi2", ";x Si2 (mm);y Si2 (mm)", 128, 0, 32, 128, 0, 32);

  TH2D *mCor[2];
  mCor[0] = new TH2D("corX", ";Si1 X (mm);Si2 X (mm)", 128, 0, 32, 128, 0, 32);
  mCor[1] = new TH2D("corY", ";Si1 Y (mm);Si2 Y (mm)", 128, 0, 32, 128, 0, 32);

  TH2D *mChCor[2];
  mChCor[0] = new TH2D("ChCorSi1", ";Si1 amp X;Si1 amp Y", 100, 0, 200, 100, 0, 200);
  mChCor[1] = new TH2D("ChCorSi2", ";Si2 amp X;Si2 amp Y", 100, 0, 200, 100, 0, 200);
  
  gStyle->SetOptStat(11);
  TH1D *mPb   = new TH1D("mPb", ";Amp Pb (ADC)", 150, -0.5, 4499.5);
  TH1D *mCher = new TH1D("mCher", ";Amp Cherenkov (ADC)", 150, -0.5, 4499.5);
  TH2D *mPbCher = new TH2D("mPbCher", ";amp Cherenkov;amp Pb", 150, -0.5, 4499.5, 150, -0.5, 4599.5);
  // gStyle->SetOptStat(0);

  // needed by the AliTRDRawStreamTB
  AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
  AliTRDcalibDB *calib = AliTRDcalibDB::Instance();
  calib->SetRun(0);

  // TRD data monitoring
  TH1D *mDet = new TH1D("mDet", ";chamber", 20, -0.5, 19.5);
  TH1D *mROB = new TH1D("mROB", ";rob", 20, -0.5, 19.5);
  TH1D *mTRDsig = new TH1D("mTRDsig", ";trdSignal", 100, -0.5, 299.5);
  
  //AliLog::SetClassDebugLevel("AliTRDRawStreamTB", 10);

  int counter = 0;
  // for(Int_t run = 365; run < 386; run++) {
  //for(Int_t run = 369; run < 382; run++) {
  //for(int run = 387; run < 389; run++) {

  // if (run == 389) continue;
    cout << run << endl;

    for(Int_t fn=begin; fn<end; fn++) {
      
      // connect to data 
      //const char *base="/Users/radomski/data/1GeV/";
      const char *base = "./";
      const char *filename = Form("%s/run%d_gdc_daq09.%03d.raw",base,run,fn);
      if (gSystem->AccessPathName(filename)) continue;
      cout << filename << endl;

      AliTRDtestBeam *data = new AliTRDtestBeam(filename);
      
      // process data
      while (data->NextEvent()) {
      
	if (!(counter%1000)) cout << "Event = " << counter << endl;
	counter++;
	
	/*
	AliTRDRawStreamTB *tb = data->GetTRDrawStream();
	while(tb->Next()) {
	  mROB->Fill(tb->GetROB());
	  mDet->Fill(tb->GetDet());
	  int *sig = tb->GetSignals();
	  mTRDsig->Fill(sig[0]);
	  mTRDsig->Fill(sig[1]);
	  mTRDsig->Fill(sig[2]);
	}
	delete tb;
	*/

	mCher->Fill(data->GetCher());
	mPb->Fill(data->GetPb());
	mPbCher->Fill(data->GetCher(), data->GetPb());

	mSi1L->Fill(data->GetNSi1());
	mSi2L->Fill(data->GetNSi2());
	
	for(int i=0; i<data->GetNSi1(); i++) {
	  Int_t q = data->GetSi1Charge(i);
	  Int_t a = data->GetSi1Address(i);
	  if (a == 0) continue; // noisy channels
	  mSi1ChP->Fill(a, q);
	  if (a < N) mSiCh[0]->Fill(q);
	  else mSiCh[1]->Fill(q);	       
	}
	
	for(int i=0; i<data->GetNSi2(); i++) {
	  Int_t q = data->GetSi2Charge(i);
	  Int_t a = data->GetSi2Address(i);
	  if (a == 0 || a == 1279) continue; // noisy channels
	  mSi2ChP->Fill(a, q);
	  if (a < N) mSiCh[2]->Fill(q);
	  else mSiCh[3]->Fill(q);	       
	}
	
	mSiFullCh[0]->Fill(data->GetQx(0));
	mSiFullCh[1]->Fill(data->GetQy(0));
	mSiFullCh[2]->Fill(data->GetQx(1));
	mSiFullCh[3]->Fill(data->GetQy(1));
	
	for(int k=0; k<2; k++)
	  mChCor[k]->Fill(data->GetQx(k), data->GetQy(k));
	
	/*
	  if (data->GetQx(0) < 20) continue;
	  if (data->GetQx(1) < 20) continue;
	  if (data->GetQy(0) < 20) continue;
	  if (data->GetQy(1) < 20) continue;
	*/
	
	for(int k=0; k<2; k++)
	  mPos[k]->Fill(data->GetX(k), data->GetY(k));
      
	mCor[0]->Fill(data->GetX(0), data->GetX(1));
	mCor[1]->Fill(data->GetY(0), data->GetY(1));
      }
      
      delete data;
    }
    //}

  // process histograms
  for(int i=1; i<1281; i++) mSi1N->Fill(mSi1ChP->GetBinError(i));
  for(int i=1; i<1281; i++) mSi2N->Fill(mSi2ChP->GetBinError(i));

  // display
  cout << "Number of Events = " << counter << endl;
  
  /**/
  TCanvas *c = new TCanvas("siliconSignal", "silicon signal");
  c->Divide(2,2, 0.01, 0.01);
  c->cd(1);
  mSi1L->Draw();
  c->cd(2);
  mSi2L->Draw();
  c->cd(3);
  mSi1ChP->Draw();
  c->cd(4);
  mSi2ChP->Draw();
  /* */

  /**/
  c = new TCanvas();
  c->Divide(2,2,0.01,0.01);
  c->cd(1);
  mSi1N->Draw();
  c->cd(2);
  mSi2N->Draw();
  /**/

  /**/
  // pads
  c = new TCanvas("siPads", "Silicon Pads");
  c->Divide(2,2, 0.01, 0.01);
  for(int i=0; i<4; i++) {
    c->cd(i+1);
    gPad->SetLogy();
    mSiCh[i]->Draw();
  }
  
  // clusters
  c = new TCanvas("siCluster", "silicon clusters");
  c->Divide(2,2, 0.01, 0.01);
  for(int i=0; i<4; i++) {
    c->cd(i+1);
    gPad->SetLogy();
    mSiFullCh[i]->Draw();
  }

  // position and correlation
  c = new TCanvas("siPosition", "reconstructed position");
  c->Divide(2,2, 0.01, 0.01);
  for(int i=0; i<2; i++) {
    c->cd(1+i);
    mPos[i]->Draw("col");
    c->cd(3+i);
    mCor[i]->Draw("col");  
  }
  
  c = new TCanvas("siCharge", "si charge correlation");
  c->Divide(2,2, 0.01, 0.01);
  c->cd(1);
  gPad->SetLogz();
  mChCor[0]->Draw("col");
  c->cd(2);
  gPad->SetLogz();
  mChCor[1]->Draw("col");
  /**/

  new TCanvas();
  gPad->SetLogy();
  mCher->Draw();
  
  // electron sample
  int bin = mCher->FindBin(500.);
  double ef = (mCher->Integral(bin, 151)/ mCher->GetSum());
  TLatex *l = new TLatex(2e3, 0.02*mCher->GetSum(), Form("Electron fraction = %.2f ", ef));
  l->Draw();
  
  new TCanvas();
  gPad->SetLogy();
  mPb->Draw();

  new TCanvas();
  gPad->SetLogz();
  mPbCher->Draw("colz");
  
  /*
  c = new TCanvas();
  c->Divide(2,2,0.01, 0.01);
  c->cd(1);
  gPad->SetLogy();
  mTRDsig->Draw();

  c->cd(2);
  mROB->Draw();

  c->cd(3);
  mDet->Draw();
  */
  
  st.Stop();
  st.Print();
}
Example #25
0
void Trasporta(Int_t s,Int_t Rhum, TRandom *GeneratoreEsterno=0,Int_t Noise_Medio = 20) {

	TStopwatch tempo;

	tempo.Start(kTRUE);

	cout<<endl<<"Sto trasportando attraverso i rivelatori: attendere... "<<endl;
	TRandom *smear;
	if(GeneratoreEsterno == 0){
		smear = new TRandom3();
		cout<<"Generatore Interno";
	}else{
		smear = GeneratoreEsterno;
		cout<<"Generatore Esterno";
	}
	
	cout<<" FirstRNDM: "<<smear->Rndm()<<endl;
	
	//////////////////////////////////////////////////////
	//Creo un nuovo file e
	//Definisco Struct per salvare i nuovi dati x y z 
	//////////////////////////////////////////////////////

	//Definisco il nuovo albero per salvare i punti di hit	
	TFile sfile("trasporto_tree.root","RECREATE");
  
	TTree *trasporto = new TTree("Ttrasporto","TTree con 3 branches");
	 //Punti sul layer
	TTree *Rel_Lay1 = new TTree("Layer1","TTree con 1 branch");
	TTree *Rel_Lay2 = new TTree("Layer2","TTree con 1 branch");
	 //rumore
	TTree *Noise = new TTree("Rumore","TTree con 1 branch");

	typedef struct {
		Double_t X,Y,Z;
		Int_t Flag;		
	} HIT; 
	static HIT beam;  	
	static HIT lay1;  
	static HIT lay2;

	typedef struct {
		Int_t event;
		Int_t tipo;
		Int_t Noiselay1;
		Int_t Noiselay2;
	} infoRumore;
	static infoRumore InfoR;


	//Dichiaro i rami dei tree
	trasporto->Branch("BeamPipe",&beam.X,"X/D:Y:Z:Flag/I");  
	trasporto->Branch("Layer1",&lay1.X,"X/D:Y:Z:Flag/I"); 
	trasporto->Branch("Layer2",&lay2.X,"X/D:Y:Z:Flag/I");  

	Rel_Lay1->Branch("RealLayer1",&lay1.X,"X/D:Y:Z:Flag/I"); 
	Rel_Lay2->Branch("RealLayer2",&lay2.X,"X/D:Y:Z:Flag/I"); 
	
	Noise->Branch("Rumore",&InfoR,"event/I:tipo:Noiselay1:Noiselay2"); 
	Double_t temp_phi = 0;
	Int_t Nnoise=0;	

  ////////////////////////////////
  //Acquisizione Vertici
  ///////////////////////////////
  TClonesArray *dir = new TClonesArray("Direction",100);	
  typedef struct {
    Double_t X,Y,Z;
    Int_t N;
  }SINGLE_EVENT;
  static SINGLE_EVENT event;    //struct con molteplicita' e vertice di un singolo evento
	
  TFile hfile("event_tree.root");


  TTree *Born = (TTree*)hfile.Get("T");       
  TBranch *b1=Born->GetBranch("Event"); 
  TBranch *b2=Born->GetBranch("Direzioni");  //acquisisco i due branches


  b1->SetAddress(&event.X); //passo l'indirizzo del primo oggetto della struct e assegno tutto a b1
  b2->SetAddress(&dir); // lo stesso per il vettore 




  /////////////////////////
  //Geometria del rivelatore
  /////////////////////////
  Double_t R1=3;	//raggio 3 cm beam pipe
  Double_t R2=4;	//raggio 4 cm primo layer
  Double_t R3=7;	//raggio 7 cm secondo layer

  Double_t limit = 8.; //lunghezza layer su z-> z in [-8,8]

  //Variabili Varie
	Double_t Xo=0.;Double_t Yo=0.;Double_t Zo=0.;
  	Double_t X1=0.;Double_t Y1=0.;Double_t Z1=0.;
	Double_t X2=0.;Double_t Y2=0.;Double_t Z2=0.;

	Int_t N=0; //molteplicita'

	Int_t yes = 0;
	Int_t no = 0;	       
	
	for(Int_t e=0; e < Born->GetEntries(); e++){
	
		Born->GetEvent(e);
		Xo=event.X;
		Yo=event.Y;
		Zo=event.Z;		
		N=event.N;	    
		
		for(Int_t i=0; i<N; i++){
			
			//Cast dell'elemenento i di TClones a Direction
			Direction *angolacci=(Direction*)dir->At(i);
			angolacci->SetRNDGenerator(smear);//uso lo stesso generatore anche nella classe
			
			//primo hit beam pipe
			angolacci->GeneraHit(Xo,Yo,Zo,R1);//genero il punto di impatto sul beam pipe		
			
			beam.X=angolacci->GetNewX(); //recupero le coordinate del punto d'impatto sul BP
			beam.Y=angolacci->GetNewY();					
			beam.Z=angolacci->GetNewZ();
			beam.Flag=1;
		

			///////////////////////////////////////////////////
			/////////////scattering sul beam pipe//////////////
			///////////////////////////////////////////////////
			if(s==1){
				//dipende dal tipo di materiale
				angolacci->Scattering(0.08,35.28);
			}
					
				
			//secondo hit layer 1			
			angolacci->GeneraHit(beam.X,beam.Y,beam.Z,R2);

			X1 = angolacci->GetNewX();	
			Y1 = angolacci->GetNewY();
			Z1 = angolacci->GetNewZ();
			
			lay1.X=X1;
			lay1.Y=Y1;							
			lay1.Z=Z1;	
			
			//verifico che la particella colpisca il layer
			if(TMath::Abs(Z1) < limit){

				lay1.Flag = e;
				Rel_Lay1->Fill();					       
				
				///////////////////////////////////////////////
				/////////////scattering sul layer//////////////	
				///////////////////////////////////////////////
				if(s==1){
					angolacci->Scattering(0.02,9.37);
				}				
							
				yes++;
				
			}else no++;	      
				

		      //terzo hit layer 2			
		      angolacci->GeneraHit(X1,Y1,Z1,R3);

		      X2 = angolacci->GetNewX();	
		      Y2 = angolacci->GetNewY();
		      Z2 = angolacci->GetNewZ();
		      lay2.X=X2;
		      lay2.Y=Y2;							
		      lay2.Z=Z2;
			

		      //verifico che la particella colpisca il layer
		      if(TMath::Abs(Z2) < limit){

			lay2.Flag = e;	
			Rel_Lay2->Fill();			
	
			yes++;

		      }else{
			no++;	
		      }

			angolacci->RemoveGenerator();
			trasporto->Fill(); //riempie tutto con quello che ho definito sopra

		      // Debug
		      /*printf("Evento %d : part %d \n",e,i+1);
			printf("x beam= %f ; y beam= %f; z beam= %f \n",beam.X,beam.Y,beam.Z);

			if(lay1.Flag){
			printf("x lay1= %f ; y lay1= %f; z lay1= %f \n",lay1.X,lay1.Y,lay1.Z);
			}else{
			printf("Non urta sul layer 1 \n");
			}


			if(lay2.Flag){
			printf("x lay2= %f ; y lay2= %f; z lay2= %f \n",lay2.X,lay2.Y,lay2.Z);
			}else{
			printf("Non urta sul layer 2 \n");
			}*/
		}

		////////////////////////////////////////////////////////////////////////////
		//////////////////////////RUMORE////////////////////////////////////////////
		////////////////////////////////////////////////////////////////////////////
		InfoR.event = e;
		InfoR.tipo = Rhum;
		if(Rhum != 0){
		//genero rumore lay 1
			if(Rhum == 1){
				//Nnoise= TMath::Abs(smear->Gaus(20,5));
				//Nnoise = 1+(Int_t)(20*smear->Rndm());
				Nnoise = 1+(Int_t)(Noise_Medio*smear->Rndm());
			}else{
				Nnoise= Rhum;
			}
		
		
			InfoR.Noiselay1 = Nnoise;
		
			for(Int_t y =0; y < Nnoise; y++){
				temp_phi = smear->Uniform(0,2*TMath::Pi());
				lay1.X = R2*TMath::Cos(temp_phi);
				lay1.Y = R2*TMath::Sin(temp_phi);							
				lay1.Z = smear->Uniform(-limit,limit);
	
				lay1.Flag=e;

				Rel_Lay1->Fill();		
		
			}

		      //genero rumore lay 2					
			if(Rhum == 1){
				//Nnoise= TMath::Abs(smear->Gaus(20,5));
				//Nnoise = 1+(Int_t)(20*smear->Rndm());
				Nnoise = 1+(Int_t)(Noise_Medio*smear->Rndm());
			}else{
				Nnoise= Rhum;
			}

			InfoR.Noiselay2 = Nnoise;

			for(Int_t w =0; w < Nnoise; w++){
				temp_phi = smear->Uniform(0,2*TMath::Pi());

				lay2.X = R3*TMath::Cos(temp_phi);
				lay2.Y = R3*TMath::Sin(temp_phi);							
				lay2.Z = smear->Uniform(-limit,limit);
	
				lay2.Flag=e;

				Rel_Lay2->Fill();	
			}
		}else{
			InfoR.Noiselay1 = 0;
			InfoR.Noiselay2 = 0;
		}
	
	//fill per il rumore
	Noise->Fill();
	}


	sfile.Write(); 
 
	sfile.Close();
	//ho il file con tutti gli eventi

  

 	tempo.Stop();
  
	cout<<endl<<endl<<endl<<"//////////////////////////////////////"<<endl<<endl;
	cout<<"Completato!"<<endl<<endl;
	cout<<"Il trasporto è durato "<<endl;
	tempo.Print();
	cout<<endl<<endl;
	cout<<"PARAMETRI TRASPORTO: "<<endl;
	cout<<"\t"<<"Scattering:     "<<s;
	if(s==1)cout<<"  Scattering attivo"<<endl;
	if(s==0)cout<<"  Scattering non attivo"<<endl;
	cout<<"\t"<<"Rumore:         ";
	if(Rhum==1)cout<<"  Rumore gaussiano  "<<endl;
	if(Rhum==0)cout<<"  Nessun rumore"<<endl;
	if((Rhum!=0) & (Rhum!=1))cout<<"  Rumore con molteplicita' fissa "<<Rhum<<endl;
  	cout<<endl<<"//////////////////////////////////////"<<endl;

}
Example #26
0
// implementation
void TwoBinInstructional( void ){
  
  // let's time this example
  TStopwatch t;
  t.Start();

  // set RooFit random seed for reproducible results
  RooRandom::randomGenerator()->SetSeed(4357);

  // make model
  RooWorkspace * pWs = new RooWorkspace("ws");

  // derived from data
  pWs->factory("xsec[0.2,0,2]"); // POI
  pWs->factory("bg_b[10,0,50]");    // data driven nuisance

  // predefined nuisances
  pWs->factory("lumi[100,0,1000]");
  pWs->factory("eff_a[0.2,0,1]");
  pWs->factory("eff_b[0.05,0,1]");
  pWs->factory("tau[0,1]");
  pWs->factory("xsec_bg_a[0.05]"); // constant
  pWs->var("xsec_bg_a")->setConstant(1);

  // channel a (signal): lumi*xsec*eff_a + lumi*bg_a + tau*bg_b
  pWs->factory("prod::sig_a(lumi,xsec,eff_a)");
  pWs->factory("prod::bg_a(lumi,xsec_bg_a)");
  pWs->factory("prod::tau_bg_b(tau, bg_b)");
  pWs->factory("Poisson::pdf_a(na[14,0,100],sum::mu_a(sig_a,bg_a,tau_bg_b))");

  // channel b (control): lumi*xsec*eff_b + bg_b
  pWs->factory("prod::sig_b(lumi,xsec,eff_b)");
  pWs->factory("Poisson::pdf_b(nb[11,0,100],sum::mu_b(sig_b,bg_b))");

  // nuisance constraint terms (systematics)
  pWs->factory("Lognormal::l_lumi(lumi,nom_lumi[100,0,1000],sum::kappa_lumi(1,d_lumi[0.1]))");
  pWs->factory("Lognormal::l_eff_a(eff_a,nom_eff_a[0.20,0,1],sum::kappa_eff_a(1,d_eff_a[0.05]))");
  pWs->factory("Lognormal::l_eff_b(eff_b,nom_eff_b[0.05,0,1],sum::kappa_eff_b(1,d_eff_b[0.05]))");
  pWs->factory("Lognormal::l_tau(tau,nom_tau[0.50,0,1],sum::kappa_tau(1,d_tau[0.05]))");
  //pWs->factory("Lognormal::l_bg_a(bg_a,nom_bg_a[0.05,0,1],sum::kappa_bg_a(1,d_bg_a[0.10]))");

  // complete model PDF
  pWs->factory("PROD::model(pdf_a,pdf_b,l_lumi,l_eff_a,l_eff_b,l_tau)");

  // Now create sets of variables. Note that we could use the factory to
  // create sets but in that case many of the sets would be duplicated
  // when the ModelConfig objects are imported into the workspace. So,
  // we create the sets outside the workspace, and only the needed ones
  // will be automatically imported by ModelConfigs

  // observables
  RooArgSet obs(*pWs->var("na"), *pWs->var("nb"), "obs");

  // global observables
  RooArgSet globalObs(*pWs->var("nom_lumi"), *pWs->var("nom_eff_a"), *pWs->var("nom_eff_b"), 
		      *pWs->var("nom_tau"),
		      "global_obs");

  // parameters of interest
  RooArgSet poi(*pWs->var("xsec"), "poi");

  // nuisance parameters
  RooArgSet nuis(*pWs->var("lumi"), *pWs->var("eff_a"), *pWs->var("eff_b"), *pWs->var("tau"), "nuis");

  // priors (for Bayesian calculation)
  pWs->factory("Uniform::prior_xsec(xsec)"); // for parameter of interest
  pWs->factory("Uniform::prior_bg_b(bg_b)"); // for data driven nuisance parameter
  pWs->factory("PROD::prior(prior_xsec,prior_bg_b)"); // total prior

  // create data
  pWs->var("na")->setVal(14);
  pWs->var("nb")->setVal(11);
  RooDataSet * pData = new RooDataSet("data","",obs);
  pData->add(obs);
  pWs->import(*pData);
  //pData->Print();

  // signal+background model
  ModelConfig * pSbModel = new ModelConfig("SbModel");
  pSbModel->SetWorkspace(*pWs);
  pSbModel->SetPdf(*pWs->pdf("model"));
  pSbModel->SetPriorPdf(*pWs->pdf("prior"));
  pSbModel->SetParametersOfInterest(poi);
  pSbModel->SetNuisanceParameters(nuis);
  pSbModel->SetObservables(obs);
  pSbModel->SetGlobalObservables(globalObs);

  // set all but obs, poi and nuisance to const
  SetConstants(pWs, pSbModel);
  pWs->import(*pSbModel);


  // background-only model
  // use the same PDF as s+b, with xsec=0
  // POI value under the background hypothesis
  Double_t poiValueForBModel = 0.0;
  ModelConfig* pBModel = new ModelConfig(*(RooStats::ModelConfig *)pWs->obj("SbModel"));
  pBModel->SetName("BModel");
  pBModel->SetWorkspace(*pWs);
  pWs->import(*pBModel);


  // find global maximum with the signal+background model
  // with conditional MLEs for nuisance parameters
  // and save the parameter point snapshot in the Workspace
  //  - safer to keep a default name because some RooStats calculators
  //    will anticipate it
  RooAbsReal * pNll = pSbModel->GetPdf()->createNLL(*pData);
  RooAbsReal * pProfile = pNll->createProfile(RooArgSet());
  pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values
  RooArgSet * pPoiAndNuisance = new RooArgSet();
  if(pSbModel->GetNuisanceParameters())
    pPoiAndNuisance->add(*pSbModel->GetNuisanceParameters());
  pPoiAndNuisance->add(*pSbModel->GetParametersOfInterest());
  cout << "\nWill save these parameter points that correspond to the fit to data" << endl;
  pPoiAndNuisance->Print("v");
  pSbModel->SetSnapshot(*pPoiAndNuisance);
  delete pProfile;
  delete pNll;
  delete pPoiAndNuisance;

  // Find a parameter point for generating pseudo-data
  // with the background-only data.
  // Save the parameter point snapshot in the Workspace
  pNll = pBModel->GetPdf()->createNLL(*pData);
  pProfile = pNll->createProfile(poi);
  ((RooRealVar *)poi.first())->setVal(poiValueForBModel);
  pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values
  pPoiAndNuisance = new RooArgSet();
  if(pBModel->GetNuisanceParameters())
    pPoiAndNuisance->add(*pBModel->GetNuisanceParameters());
  pPoiAndNuisance->add(*pBModel->GetParametersOfInterest());
  cout << "\nShould use these parameter points to generate pseudo data for bkg only" << endl;
  pPoiAndNuisance->Print("v");
  pBModel->SetSnapshot(*pPoiAndNuisance);
  delete pProfile;
  delete pNll;
  delete pPoiAndNuisance;

  // inspect workspace
  pWs->Print();

  // save workspace to file
  pWs->writeToFile("ws_twobin.root");

  // clean up
  delete pWs;
  delete pData;
  delete pSbModel;
  delete pBModel;

} // ----- end of tutorial ----------------------------------------
void runPicoMixedEvent(const Char_t *inputFile="test.list", const Char_t *outputFile="outputBaseName", 
			 const Char_t *badRunListFileName = "picoList_bad_MB.list") { 
  // -- Check STAR Library. Please set SL_version to the original star library used in the production 
  //    from http://www.star.bnl.gov/devcgi/dbProdOptionRetrv.pl
  TStopwatch*   stopWatch = new TStopwatch();
  stopWatch->Start();
  StMemStat mem;
  string SL_version = "SL15c";
  string env_SL = getenv ("STAR");
  if (env_SL.find(SL_version)==string::npos) {
      cout<<"Environment Star Library does not match the requested library in runPicoMixedEventMaker.C. Exiting..."<<endl;
      exit(1);
  }
  // ========================================================================================
  //   Testing 
  // ========================================================================================
  Int_t nEvents = 10000000;
  //Int_t nEvents = 20000;
	
  gROOT->LoadMacro("$STAR/StRoot/StMuDSTMaker/COMMON/macros/loadSharedLibraries.C");
  loadSharedLibraries();

  // gSystem->Load("StBTofUtil");
  gSystem->Load("StPicoDstMaker");
  gSystem->Load("StPicoPrescales");
  // gSystem->Load("StPicoCutsBase");
  // gSystem->Load("StPicoHFMaker");
  gSystem->Load("StRefMultCorr");
  gSystem->Load("StEventPlane");
  gSystem->Load("StPicoMixedEventMaker");
  
  
  chain = new StChain();

  // ========================================================================================
  // Still bone dry
  // ========================================================================================


  TString sInputFile(inputFile);
  TString sInputListHF("");  

  // create list of kfVertex files
  TString command = "sed 's/picodsts/hft\\\/kfVertex/g' " + sInputFile + " >correspondingkfVertex.list";
  gSystem->Exec(command.Data());
  command = "sed -i 's/picoDst/kfVertex/g' correspondingkfVertex.list";
  gSystem->Exec(command.Data());

  // ========================================================================================
  StPicoDstMaker* picoDstMaker = new StPicoDstMaker(0, sInputFile, "picoDstMaker");
  StRefMultCorr* grefmultCorrUtil  = CentralityMaker::instance()->getgRefMultCorr();
  cout<<"here"<<endl;
  grefmultCorrUtil->setVzForWeight(6, -6.0, 6.0);
  grefmultCorrUtil->readScaleForWeight("StRoot/StRefMultCorr/macros/weight_grefmult_vpd30_vpd5_Run14.txt");
  for(Int_t i=0;i<6;i++){
    cout << i << " " << grefmultCorrUtil->get(i, 0) << endl;
  }
  StEventPlane*  eventPlaneMaker = new StEventPlane("eventPlaneMaker",picoDstMaker,grefmultCorrUtil);
  StPicoMixedEventMaker* picoMixedEventMaker = new StPicoMixedEventMaker("picoMixedEventMaker", picoDstMaker, grefmultCorrUtil, eventPlaneMaker, outputFile, sInputListHF, "correspondingkfVertex.list");

  // ---------------------------------------------------
  // -- Set Base cuts for HF analysis

  // -- File name of bad run list
  //hfCuts->setBadRunListFileName(badRunListFileName);

  chain->Init();
  cout << "chain->Init();" << endl;

  int total = picoDstMaker->chain()->GetEntries();
  cout << " Total entries = " << total << endl;
  if(nEvents>total) nEvents = total;
  for (Int_t i=0; i<nEvents; i++) {
    if(i%1000==0)
      cout << "Working on eventNumber " << i << endl;
    
    chain->Clear();

    int iret = chain->Make(i);

    if (iret) { cout << "Bad return code!" << iret << endl; break;}
    
    total++;
  }
  
  cout << "****************************************** " << endl;
  cout << "Work done... now its time to close up shop!"<< endl;
  cout << "****************************************** " << endl;
  chain->Finish();
  cout << "****************************************** " << endl;
  cout << "total number of events  " << nEvents << endl;
  cout << "****************************************** " << endl;
  
  delete chain;
  // delete list of kfEvent list
  command = "rm -f correspondingkfVertex.list";
  gSystem->Exec(command.Data());

  stopWatch->Stop(); 
  stopWatch->Print();
}
Example #28
0
void fitNormSum()
{
    //***************************************************************************************************

    // Tutorial for normalized sum of two functions
    // Here: a background exponential and a crystalball function


    // Parameters can be set:
    // I.   with the TF1 object before adding the function (for 3) and 4))
    // II.  with the TF1NormSum object (first two are the coefficients, then the non constant parameters)
    // III. with the TF1 object after adding the function

    // Sum can be constructed by:
    // 1) by a string containing the names of the functions and/or the coefficient in front
    // 2) by a string containg formulas like expo, gaus...
    // 3) by the list of functions and coefficients (which are 1 by default)
    // 4) by a std::vector for functions and coefficients

    //***************************************************************************************************


    const int nsig = 5.E4;
    const int nbkg = 1.e6;
    Int_t NEvents = nsig+nbkg;
    Int_t NBins   = 1e3;

    double signal_mean = 3;
    TF1 *f_cb    = new TF1("MyCrystalBall","crystalball",-5.,5.);
    TF1 *f_exp   = new TF1("MyExponential","expo",-5.,5.);

    // I.:
    f_exp-> SetParameters(1.,-0.3);
    f_cb -> SetParameters(1,signal_mean,0.3,2,1.5);

    // CONSTRUCTION OF THE TF1NORMSUM OBJECT ........................................
    // 1) :
    TF1NormSum *fnorm_exp_cb = new TF1NormSum(f_cb,f_exp,nsig,nbkg);
    // 4) :

    TF1   * f_sum = new TF1("fsum", *fnorm_exp_cb, -5., 5., fnorm_exp_cb->GetNpar());
    f_sum->Draw();

    // III.:
    f_sum->SetParameters( fnorm_exp_cb->GetParameters().data() );
    f_sum->SetParName(1,"NBackground");
    f_sum->SetParName(0,"NSignal");
    for (int i = 2; i < f_sum->GetNpar(); ++i)
        f_sum->SetParName(i,fnorm_exp_cb->GetParName(i) );

    //GENERATE HISTOGRAM TO FIT ..............................................................
    TStopwatch w;
    w.Start();
    TH1D *h_sum = new TH1D("h_ExpCB", "Exponential Bkg + CrystalBall function", NBins, -5., 5.);
    for (int i=0; i<NEvents; i++)
    {
        h_sum -> Fill(f_sum -> GetRandom());
    }
    printf("Time to generate %d events:  ",NEvents);
    w.Print();
    //TH1F *h_orig = new TH1F(*h_sum);

    // need to scale histogram with width since we are fitting a density
    h_sum -> Sumw2();
    h_sum -> Scale(1., "width");

    //fit - use Minuit2 if available
    ROOT::Math::MinimizerOptions::SetDefaultMinimizer("Minuit2");
    new TCanvas("Fit","Fit",800,1000);
    // do a least-square fit of the spectrum
    auto result = h_sum -> Fit("fsum","SQ");
    result->Print();
    h_sum -> Draw();
    printf("Time to fit using ROOT TF1Normsum: ");
    w.Print();

    // test if parameters are fine
    std::vector<double>  pref = {nsig, nbkg, signal_mean};
    for (unsigned int i = 0; i< pref.size(); ++i)  {
        if (!TMath::AreEqualAbs(pref[i], f_sum->GetParameter(i), f_sum->GetParError(i)*10.) )
            Error("testFitNormSum","Difference found in fitted %s - difference is %g sigma",f_sum->GetParName(i), (f_sum->GetParameter(i)-pref[i])/f_sum->GetParError(i));
    }

    gStyle->SetOptStat(0);
    // add parameters
    auto t1 = new TLatex(-2.5, 300000, TString::Format("%s = %8.0f #pm %4.0f", "NSignal",f_sum->GetParameter(0), f_sum->GetParError(0) ) );
    auto t2 = new TLatex(-2.5, 270000, TString::Format("%s = %8.0f #pm %4.0f", "Nbackgr",f_sum->GetParameter(1), f_sum->GetParError(1) ) );
    t1->Draw();
    t2->Draw();
}
 TimerRAII(const char *meta): fMeta(meta)
 {
    fTimer.Start();
 }
int Analyzeforest_jec_pp2013(const char *ksp="pp")
{

    timer.Start();

    std::string inname="";
    int knj = kAlgos;
    if(strcmp(ksp,"pp")==0)inname="dijet_pp_mergedpthatbins_prod22v18MC.root";
    else {
        inname="dijet_pp_mergedpthatbins_embedpp.root";
        knj = 12;
    }
    TFile *fin = new TFile(inname.c_str(),"r");

    std::string outname="";
    if(strcmp(ksp,"pp")==0)outname="JetResponse_histos_prod22v81_pp.root";
    else outname="JetResponse_histos_JECv14_embeded_pp_cent.root";
    TFile *fout = new TFile(outname.c_str(),"RECREATE");

    std::cout<<"\t"<<std::endl;
    std::cout<<"\t"<<std::endl;
    std::cout<<"**************************************************** "<<std::endl;
    std::cout<<Form("Analyzeforest_jec : %s",ksp)<<std::endl;
    std::cout<<Form("eta cut for %0.3f ",ketacut)<<std::endl;
    std::cout<<"**************************************************** "<<std::endl;
    std::cout<<"\t"<<std::endl;
    std::cout<<"\t"<<std::endl;


    //!
    //! Define histograms here
    //   TH1::SetDefaultSumw2();
    //   TH2::SetDefaultSumw2();
    //   TH3::SetDefaultSumw2();
    //  TProfile::SetDefaultSumw2();

    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    TH1F *hBin    = new TH1F("hBin","Centrality bin",200,-0.5,200-0.5);
    hBin->Sumw2();
    TH1F *hpthat  = new TH1F("hpthat","pt-hat distribution",500,0,1000);
    hpthat->Sumw2();

    TH2F *hrajptrpt [knj][ncent];

    //! Gen matched jets
    TH1F *hgenpt_genm [knj][ncent], *hrecopt_genm[knj][ncent], *hrawpt_genm[knj][ncent];
    TH1F *hjeteta     [knj][ncent], *hjetphi     [knj][ncent];
    TH2F *hjetpteta   [knj][ncent], *hjetptphi   [knj][ncent], *hjetetaphi [knj][ncent];

    //! Ratios of the pt distributions
    TProfile *hrecogen[knj][ncent], *hrecoraw[knj][ncent], *hrawgen[knj][ncent];

    //! Resposnse
    TH2F *hrescrpt_genm [knj][ncent], *hresrrpt_genm [knj][ncent], *hresrcrpt_genm [knj][ncent];
    TH3F *hrescreta_genm[knj][ncent], *hresrreta_genm[knj][ncent], *hresrcreta_genm[knj][ncent];
    TH3F *hrescrphi_genm[knj][ncent], *hresrrphi_genm[knj][ncent], *hresrcrphi_genm[knj][ncent];
    TH2F *hratiorawrefpt_eta[knj][ncent][2], *hratiocorrrefpt_eta[knj][ncent][2];

    TH2F *hratiocorrrefpt_genm[knj][ncent];

    TH2F *hpteta[knj][ncent][maxe] ;
    TH2F *hptphi[knj][ncent][maxph] ;

    TH2F *hgenjrecoj[knj][ncent];
    TH2F *hgenjrawj [knj][ncent];

    //! Background jet pt
    TH2F *hjbkgComb[knj][ncent];


    //! For comparison with data
    TH2F *hJetEnergyScale[knj][ncent];


    //! Efficency histos
    TH1F *hPtAll [knj][ncent], *hPtSel[knj][ncent];
    TH1F *hEtaAll[knj][ncent], *hEtaSel[knj][ncent];
    TH1F *hPhiAll[knj][ncent], *hPhiSel[knj][ncent];


    for(int nj=0; nj<knj; nj++) {
        for(int ic=0; ic<ncent; ic++) {

            hgenpt_genm [nj][ic] = new TH1F(Form("hgenpt_genm%d_%d",nj,ic),Form("Gen matched gen p_{T} distribution jet centb %d %s",ic,calgo[nj]),500,0,1000);
            hgenpt_genm [nj][ic]->Sumw2();
            hrecopt_genm[nj][ic] = new TH1F(Form("hrecopt_genm%d_%d",nj,ic),Form("Gen matched reco p_{T} distribution jet centb %d %s",ic,calgo[nj]),500,0,1000);
            hrecopt_genm[nj][ic]->Sumw2();
            hrawpt_genm [nj][ic] = new TH1F(Form("hrawpt_genm%d_%d",nj,ic),Form("Gen matched raw p_{T} distribution jet centb %d %s",ic,calgo[nj]),500,0,1000);
            hrawpt_genm [nj][ic]->Sumw2();

            hjbkgComb[nj][ic] = new TH2F(Form("hjbkgComb%d_%d",nj,ic),Form("jet background distribution jet centb %d %s",ic,calgo[nj]),500,0,1000,500,0.,250.);
            hjbkgComb[nj][ic]->Sumw2();

            //! Ratios
            hrecogen[nj][ic] = new TProfile(Form("hrecogen%d_%d",nj,ic),Form("reco/gen p_{T} distribution jet centb %d %s",ic,calgo[nj]),500,0,1000);
            hrecogen[nj][ic]->Sumw2();
            hrecoraw[nj][ic] = new TProfile(Form("hrecoraw%d_%d",nj,ic),Form("reco/raw p_{T} distribution jet centb %d %s",ic,calgo[nj]),500,0,1000);
            hrecoraw[nj][ic]->Sumw2();
            hrawgen[nj][ic]  = new TProfile(Form("hrawgen%d_%d",nj,ic),Form("raw/gen p_{T} distribution jet centb %d %s",ic,calgo[nj]),500,0,1000);
            hrawgen[nj][ic]->Sumw2();

            //! Gen matched Response and resolution
            hrescrpt_genm[nj][ic]= new TH2F(Form("hrescrpt_genm%d_%d",nj,ic),Form("Gen jet:(Reco/Gen) jet p_{T} distribution jet centb %d %s",ic,calgo[nj]),500,0,1000,150,rbinl,rbinh);
            hrescrpt_genm[nj][ic]->Sumw2();
            hresrrpt_genm[nj][ic]= new TH2F(Form("hresrrpt_genm%d_%d",nj,ic),Form("Gen jet:(Raw/Gen) jet p_{T}  distribution jet centb %d %s",ic,calgo[nj]),500,0,1000,150,rbinl,rbinh);
            hresrrpt_genm[nj][ic]->Sumw2();
            hresrcrpt_genm[nj][ic]= new TH2F(Form("hresrcrpt_genm%d_%d",nj,ic),Form("Reco jet:(Reco/Raw) jet p_{T} distribution jet centb %d %s",ic,calgo[nj]),500,0,1000,150,rbinl,rbinh);
            hresrcrpt_genm[nj][ic]->Sumw2();

            //! Gen matched response and resolutions in different eta bins
            hrescreta_genm[nj][ic]  = new TH3F(Form("hrescreta_genm%d_%d",nj,ic),Form("Gen jet:(Reco/Gen) jet p_{T} distribution jet centb %d %s",ic,calgo[nj])  ,50,-2.5,2.5,500,0,1000,rbins,rbinl,rbinh);
            hrescreta_genm[nj][ic]->Sumw2();
            hresrreta_genm[nj][ic]  = new TH3F(Form("hresrreta_genm%d_%d",nj,ic),Form("Gen jet:(Raw/Gen) jet p_{T}  distribution jet centb %d %s",ic,calgo[nj])  ,50,-2.5,2.5,500,0,1000,rbins,rbinl,rbinh);
            hresrreta_genm[nj][ic]->Sumw2();
            hresrcreta_genm[nj][ic] = new TH3F(Form("hresrcreta_genm%d_%d",nj,ic),Form("Reco jet:(Reco/Raw) jet p_{T} distribution jet centb %d %s",ic,calgo[nj]),50,-2.5,2.5,500,0,1000,rbins,rbinl,rbinh);
            hresrcreta_genm[nj][ic]->Sumw2();

            //! Gen matched response and resolutions in different phi bins
            hrescrphi_genm[nj][ic]  = new TH3F(Form("hrescrphi_genm%d_%d",nj,ic),Form("Gen jet:(Reco/Gen) jet p_{T} distribution jet centb %d %s",ic,calgo[nj])  ,72,-pi,pi,500,0,1000,rbins,rbinl,rbinh);
            hrescrphi_genm[nj][ic]->Sumw2();
            hresrrphi_genm[nj][ic]  = new TH3F(Form("hresrrphi_genm%d_%d",nj,ic),Form("Gen jet:(Raw/Gen) jet p_{T}  distribution jet centb %d %s",ic,calgo[nj])  ,72,-pi,pi,500,0,1000,rbins,rbinl,rbinh);
            hresrrphi_genm[nj][ic]->Sumw2();
            hresrcrphi_genm[nj][ic] = new TH3F(Form("hresrcrphi_genm%d_%d",nj,ic),Form("Reco jet:(Reco/Raw) jet p_{T} distribution jet centb %d %s",ic,calgo[nj]),72,-pi,pi,500,0,1000,rbins,rbinl,rbinh);
            hresrcrphi_genm[nj][ic]->Sumw2();

            hjeteta[nj][ic] = new TH1F(Form("hjeteta%d_%d",nj,ic),Form("jet eta distribution jet centb %d %s",ic,calgo[nj]),72,-ketacut,ketacut);
            hjeteta[nj][ic]->Sumw2();
            hjetphi[nj][ic] = new TH1F(Form("hjetphi%d_%d",nj,ic),Form("jet phi distribution jet centb %d %s",ic,calgo[nj]),72,-pi,pi);
            hjetphi[nj][ic]->Sumw2();

            hjetetaphi[nj][ic] = new TH2F(Form("hjetetaphi%d_%d",nj,ic),Form("jet eta-phi distribution jet centb %d %s",ic,calgo[nj]),72,-ketacut,ketacut,72,-pi,pi);
            hjetetaphi[nj][ic] ->Sumw2();
            hjetpteta[nj][ic] = new TH2F(Form("hjetpteta%d_%d",nj,ic),Form("jet pt-eta distribution jet centb %d %s",ic,calgo[nj]),500,0,1000,72,-ketacut,ketacut);
            hjetpteta[nj][ic]->Sumw2();
            hjetptphi[nj][ic] = new TH2F(Form("hjetptphi%d_%d",nj,ic),Form("jet pt-phi distribution jet centb %d %s",ic,calgo[nj]),500,0,1000,72,-pi,pi);
            hjetptphi[nj][ic]->Sumw2();

            hratiocorrrefpt_genm[nj][ic]= new TH2F(Form("hratiocorrrefpt_genm%d_%d",nj,ic),Form("Gen matched jet Reco jet / Gen jet p_{T} (corr.) distribution jet centb %d %s",ic,calgo[nj]),
                                                   500,0,1000,rbins,rbinl,rbinh);
            hratiocorrrefpt_genm[nj][ic]->Sumw2();

            for(int ie=0; ie<2; ie++) {
                hratiorawrefpt_eta[nj][ic][ie]= new TH2F(Form("hratiorawrefpt_eta%d_%d_%d",nj,ic,ie),
                        Form("Raw jet / Gen jet p_{T} (raw) distribution jet centb %d %s etabin%d",ic,calgo[nj],ie),
                        500,0,1000,rbins,rbinl,rbinh);
                hratiorawrefpt_eta[nj][ic][ie]->Sumw2();
                hratiocorrrefpt_eta[nj][ic][ie]= new TH2F(Form("hratiocorrrefpt_eta%d_%d_%d",nj,ic,ie),
                        Form("Reco jet / Gen jet p_{T} (raw) distribution jet centb %d %s etabin%d",ic,calgo[nj],ie),
                        500,0,1000,rbins,rbinl,rbinh);
                hratiocorrrefpt_eta[nj][ic][ie]->Sumw2();
            }

            for(int m=0; m<maxe; m++) {
                hpteta[nj][ic][m] = new TH2F(Form("hpteta%d_%d_%d",nj,ic,m),Form("resolution  pt(eta) distribution cent %d jet %s etabin%d",ic,calgo[nj],m),
                                             500,0,1000,rbins,rbinl,rbinh);
                hpteta[nj][ic][m]->Sumw2();
            }

            for(int m=0; m<maxph; m++) {
                hptphi[nj][ic][m] = new TH2F(Form("hptphi%d_%d_%d",nj,ic,m),Form("resolution pt(phi) distribution cent %d jet %s phibin%d",ic,calgo[nj],m),
                                             500,0,1000,rbins,rbinl,rbinh);
                hptphi[nj][ic][m]->Sumw2();
            }

            hgenjrecoj[nj][ic] =new TH2F(Form("hgenjrecoj%d_%d",nj,ic),Form("gen jet2 : reco jet2 %s cent %d",calgo[nj],ic),500,0.,1000.,500,0.,1000.);
            hgenjrecoj[nj][ic]->Sumw2();


            hgenjrawj[nj][ic] =new TH2F(Form("hgenjrawj%d_%d",nj,ic),Form("gen jet2 : raw jet2 %s cent %d",calgo[nj],ic),500,0.,1000.,500,0.,1000.);
            hgenjrawj[nj][ic]->Sumw2();

            hrajptrpt[nj][ic] = new TH2F(Form("hrajptrpt%d_%d",nj,ic),Form("corr pT / jet(raw pt) p_{T} distribution %d jet %s",ic,calgo[nj]),500,0,1000,50,0,10);
            hrajptrpt[nj][ic]->Sumw2();

            hJetEnergyScale[nj][ic] = new TH2F(Form("hJetEnergyScale%d_%d",nj,ic),Form("hJetEnergyScale%d_%d",nj,ic),500,0,1000,50,-1.00,1.00);
            hJetEnergyScale[nj][ic]->Sumw2();

            //! efficcy histograms
            hPtAll [nj][ic] = new TH1F(Form("hPtAll%d_%d",nj,ic),Form("Denominator pT for algorithm %s cent %d",calgo[nj],ic),40,10,110);
            hEtaAll[nj][ic] = new TH1F(Form("hEtaAll%d_%d",nj,ic),Form("Denominator eta  for algorithm %s cent %d",calgo[nj],ic),20,-ketacut,ketacut);
            hPhiAll[nj][ic] = new TH1F(Form("hPhiAll%d_%d",nj,ic),Form("Denominator  phi  for algorithm %s cent %d",calgo[nj],ic),20,-pi,pi);

            hPtSel [nj][ic] = new TH1F(Form("hPtSel%d_%d",nj,ic),Form("Numerator pT for algorithm %s cent %d",calgo[nj],ic),40,10,110);
            hEtaSel[nj][ic] = new TH1F(Form("hEtaSel%d_%d",nj,ic),Form("Numerator eta  for algorithm %s cent %d",calgo[nj],ic),20,-ketacut,ketacut);
            hPhiSel[nj][ic] = new TH1F(Form("hPhiSel%d_%d",nj,ic),Form("Numerator  phi  for algorithm %s cent %d",calgo[nj],ic),20,-pi,pi);


        }//! ic
    }//! nj
    std::cout<<"Initialized the histograms " <<std::endl;
    /////////////////////////////////////////////////////////////////////////////////////////


    TTree *tr_in=0;
    std::vector<double> vJets;
    Long64_t nbytes=0;

    double nevt [kAlgos][ncent]= {{0}};
    double njets[kAlgos][ncent]= {{0}};

    for(int nj=0; nj<knj; nj++) {

        tr_in = (TTree*)fin->Get(Form("%sJetAnalyzer/t",calgo[nj]));
        Long64_t nentries = tr_in->GetEntries();
        std::cout<<Form("# of entries in TTree for %s %s : ",calgo[nj],ksp)<<nentries<<std::endl;
        std::cout<<std::endl;

        //Declaration of leaves types
        int hiBin;
        int   nref;
        float pthat;
        float weight;
        float corrpt[1000];
        float jtpt[1000];
        float rawpt[1000];
        float jteta[1000];
        float jtphi[1000];
        float refpt[1000];
        float refeta[1000];
        float refphi[1000];
        float refdrjt[1000];
        float chargedMax[1000];
        float chargedSum[1000];
        float photonSum [1000];
        float neutralSum[1000];
        float refparton_pt[1000];
        int subid[1000];

        tr_in->SetBranchAddress("hiBin",&hiBin);
        tr_in->SetBranchAddress("nref",&nref);
        tr_in->SetBranchAddress("pthat",&pthat);
        tr_in->SetBranchAddress("weight",&weight);
        tr_in->SetBranchAddress("rawpt",rawpt);
        tr_in->SetBranchAddress("corrpt",corrpt);
        tr_in->SetBranchAddress("jtpt",jtpt);  //! this is also raw pt
        tr_in->SetBranchAddress("jteta",jteta);
        tr_in->SetBranchAddress("jtphi",jtphi);
        tr_in->SetBranchAddress("refpt",refpt);
        tr_in->SetBranchAddress("refphi",refphi);
        tr_in->SetBranchAddress("refeta",refeta);
        tr_in->SetBranchAddress("refdrjt",refdrjt);
        tr_in->SetBranchAddress("refparton_pt",refparton_pt);
        tr_in->SetBranchAddress("subid",subid);
        if(strcmp(ksp,"pp")!=0) {
            tr_in->SetBranchAddress("chargedMax",chargedMax);
            tr_in->SetBranchAddress("chargedSum",chargedSum);
            tr_in->SetBranchAddress("photonSum",photonSum);
            tr_in->SetBranchAddress("neutralSum",neutralSum);
        }

        //! Load the jet energy correction factors on fly
//     string L2Name, L3Name;
//     JetCorrectorParameters *parHI_l2=0, *parHI_l3=0;
//     vector<JetCorrectorParameters> vpar_HI;
//     FactorizedJetCorrector *_JEC_HI = new FactorizedJetCorrector(vpar_HI);//JR


//      L2Name = "/net/hisrv0001/home/pawan/Validation/Track8_Jet19/combinePtHatBins/ppJEC2014/JECv14/HI_PythiaZ2_2760GeV_5316_v14_L2Relative_"+corrFileName[nj]+"_offline.txt";
//      cout<<"**** ++++++  L2Name "<<L2Name<<endl;
//      L3Name = "/net/hisrv0001/home/pawan/Validation/Track8_Jet19/combinePtHatBins/ppJEC2014/JECv14/HI_PythiaZ2_2760GeV_5316_v14_L3Absolute_"+corrFileName[nj]+"_offline.txt";
//      cout<<"**** ++++++  L3Name "<<L3Name<<endl;

//     L2Name = "/net/hisrv0001/home/pawan/Validation/Track8_Jet19/CMSSW_5_3_16/src/JEC_base/pp2014/txtfiles/JEC_STARTHI53_LV1_Track8_Jet22_dijet_L2Relative_"+corrFileName[nj]+".txt";
//     cout<<"**** ++++++  L2Name "<<L2Name<<endl;
//     L3Name = "/net/hisrv0001/home/pawan/Validation/Track8_Jet19/CMSSW_5_3_16/src/JEC_base/pp2014/txtfiles/JEC_STARTHI53_LV1_Track8_Jet22_dijet_L3Absolute_"+corrFileName[nj]+".txt";
//     cout<<"**** ++++++  L3Name "<<L3Name<<endl;



//     parHI_l2 = new JetCorrectorParameters(L2Name.c_str());
//     parHI_l3 = new JetCorrectorParameters(L3Name.c_str());

//     vpar_HI.push_back(*parHI_l2);
//     vpar_HI.push_back(*parHI_l3);
//     _JEC_HI = new FactorizedJetCorrector(vpar_HI);


        Int_t iEvent=0;
        for (Long64_t i=0; i<nentries; i++) {
            nbytes += tr_in->GetEntry(i);
            //return 0;

            int icent=-1;
            double wcen=1;
            double wvz=1;
            //! weight  for the merging of the samples for different pT hat bins
            double wxs = weight;

            if(strcmp(ksp,"pp")==0) {
                icent=0;
            } else {
                icent = GetCentBin(hiBin);
            }
            //! MinBias
            //icent=0;

            if(i%10000==0)std::cout<<" ********** Event # " <<i<<"\t weight  : "<<weight<<"\t pthat : "<<pthat<<std::endl;
            hBin->Fill(hiBin,wxs*wcen*wvz);

            //! Centrality
            if(icent<0 || icent>=ncent ) {
                //std::cout<<" Something wrong !!!!!  : "  << icent << "\t hiBin : "<< hiBin << " \t event " << i << std::endl;
                continue;
            }
            //! xsec-weight
            hpthat->Fill(pthat,wxs*wcen*wvz);
            nevt[nj][icent]++;

//       //! Jet energy scale comparison with data
//       vJets.clear();
//       for(int igen=0; igen<nref; igen++){
// 	int gj = igen;

// 	if(subid[gj] != 0 || refparton_pt[gj]==-999)continue;

// 	_JEC_HI->setJetEta(jteta[gj]);
// 	_JEC_HI->setJetPt (rawpt[gj]);

// 	//float recopt  = corrpt[gj];
// 	float recopt  = rawpt[gj]*_JEC_HI->getCorrection();  //! correction with JECv14
// 	if(recopt<80 && fabs(jteta[gj])>1.4 && fabs(refdrjt[gj])>kdRcut)continue;
// 	vJets.push_back(recopt);
//       }
//       if(vJets.size()>=2){
// 	std::sort(vJets.begin(),vJets.end());
// 	double B=-9999;
// 	double rn1 = gRandom->Rndm();
// 	double rn2 = gRandom->Rndm();
// 	double ptdij = (vJets[0] + vJets[1])/2.;
// 	if(rn1 > rn2){
// 	  B = (vJets[0] - vJets[1])/(vJets[0] + vJets[1]);
// 	}else{
// 	  B = (vJets[1] - vJets[0])/(vJets[1] + vJets[0]);
// 	}
// 	if(B!=-9999)hJetEnergyScale[nj][icent]->Fill(ptdij,B,wxs*wcen*wvz);
//       }


            //! Gen matched jets loop
            for(int igen=0; igen<nref; igen++) {
                int gj = igen;

                if(subid[gj] != 0)continue;

                //! Reconstruction
                if(fabs(refeta[gj]) < ketacut && refpt[gj]>15) {
                    //! Denominator for reconstruction efficiency
                    hPtAll [nj][icent]->Fill(refpt[gj],wxs*wcen*wvz);
                    hEtaAll[nj][icent]->Fill(refeta[gj],wxs*wcen*wvz);
                    hPhiAll[nj][icent]->Fill(refphi[gj],wxs*wcen*wvz);
                }


                //_JEC_HI->setJetEta(jteta[gj]);
                //_JEC_HI->setJetPt (rawpt[gj]);

                float recopt  = corrpt[gj];
                //float recopt  = rawpt[gj]*_JEC_HI->getCorrection();  //! correction with JECv14
                float recoeta = jteta[gj];
                float recophi = jtphi[gj];
                float delr    = refdrjt[gj];

                if(recopt<kptrecocut || refpt[gj]<kptgencut || refpt[gj]==0 || fabs(recoeta)>ketacut || fabs(delr)>kdRcut)continue;

                if(fabs(refeta[gj])<ketacut && refpt[gj]>15) {
                    //! Numerator for reconstrunction efficiency
                    hPtSel [nj][icent]->Fill(refpt [gj],wxs*wcen*wvz);
                    hEtaSel[nj][icent]->Fill(refeta[gj],wxs*wcen*wvz);
                    hPhiSel[nj][icent]->Fill(refphi[gj],wxs*wcen*wvz);
                }


                if(strcmp(ksp,"pp")!=0) {
                    double jetbkgd = (chargedSum[gj] + photonSum[gj] + neutralSum[gj]) - rawpt[gj];
                    hjbkgComb[nj][icent]->Fill(recopt,jetbkgd,wxs*wcen*wvz);
                }

                hgenjrecoj [nj][icent]->Fill(refpt[gj],recopt,wxs*wcen*wvz);
                hgenjrawj  [nj][icent]->Fill(refpt[gj],rawpt[gj],wxs*wcen*wvz);

                hratiocorrrefpt_genm[nj][icent]->Fill(refpt[gj],recopt/refpt[gj],wxs*wcen*wvz);
                hrecogen[nj][icent]->Fill(refpt[gj],recopt/refpt[gj],wxs*wcen*wvz);
                hrecoraw[nj][icent]->Fill(recopt,recopt/rawpt[gj],wxs*wcen*wvz);
                hrawgen [nj][icent]->Fill(refpt[gj],rawpt[gj]/refpt[gj],wxs*wcen*wvz);


                njets[nj][icent]++;


                int ieta=-1;
                if(fabs(recoeta)<1.3)ieta=0; //! barrel region
                else ieta=1; //! HCAL region


                //! Response in eta
                hratiocorrrefpt_eta[nj][icent][ieta]->Fill(refpt[gj],recopt/refpt[gj],wxs*wcen*wvz);
                hratiorawrefpt_eta [nj][icent][ieta]->Fill(refpt[gj],rawpt[gj]/refpt[gj],wxs*wcen*wvz);

                //! Ratio of recopT / rawpT
                hrajptrpt[nj][icent] ->Fill(recopt,recopt/rawpt[gj],wxs*wcen*wvz);

                //! Jet eta, phi, pt, eta-pt, eta-phi and pt-phi
                hjeteta   [nj][icent]->Fill(jteta[gj],wxs*wcen*wvz);
                hjetphi   [nj][icent]->Fill(jtphi[gj],wxs*wcen*wvz);
                hjetpteta [nj][icent]->Fill(recopt,jteta[gj],wxs*wcen*wvz);
                hjetptphi [nj][icent]->Fill(jtpt[gj],jtphi[gj],wxs*wcen*wvz);
                hjetetaphi[nj][icent]->Fill(jteta[gj],jtphi[gj],wxs*wcen*wvz);

                hgenpt_genm [nj][icent]->Fill(refpt[gj],wxs*wcen*wvz);
                hrecopt_genm[nj][icent]->Fill(recopt,wxs*wcen*wvz);
                hrawpt_genm [nj][icent]->Fill(rawpt[gj],wxs*wcen*wvz);

                //! Very fine bin in ref pt used for response
                hrescrpt_genm [nj][icent]->Fill(refpt[gj],recopt/refpt[gj],wxs*wcen*wvz);
                hresrrpt_genm [nj][icent]->Fill(refpt[gj],rawpt[gj]/refpt[gj],wxs*wcen*wvz);
                hresrcrpt_genm[nj][icent]->Fill(recopt,recopt/rawpt[gj],wxs*wcen*wvz);

                //! Very fine bin in ref eta used for response
                hrescreta_genm [nj][icent]->Fill(refeta[gj],refpt[gj],recopt/refpt[gj],wxs*wcen*wvz);
                hresrreta_genm [nj][icent]->Fill(refeta[gj],refpt[gj],rawpt[gj]/refpt[gj],wxs*wcen*wvz);
                hresrcreta_genm[nj][icent]->Fill(recoeta,refpt[gj],recopt/rawpt[gj],wxs*wcen*wvz);

                //! Very fine bin in ref phi used for response
                hrescrphi_genm [nj][icent]->Fill(refphi[gj],refpt[gj],recopt/refpt[gj],wxs*wcen*wvz);
                hresrrphi_genm [nj][icent]->Fill(refphi[gj],refpt[gj],rawpt[gj]/refpt[gj],wxs*wcen*wvz);
                hresrcrphi_genm[nj][icent]->Fill(recophi,refpt[gj],recopt/rawpt[gj],wxs*wcen*wvz);

                //! Response in different eta and phi bins
                int etabin = GetEtaBin(fabs(refeta[gj]));
                int phibin = GetPhiBin(refphi[gj]);

                //! Response in eta and phi bins
                if(etabin >= 0 && etabin<maxe) {
                    hpteta[nj][icent][etabin]->Fill(refpt[gj],recopt/refpt[gj],wxs*wcen*wvz);
                }
                if(phibin >= 0 && phibin<maxph) {
                    hptphi[nj][icent][phibin]->Fill(refpt[gj],recopt/refpt[gj],wxs*wcen*wvz);
                }

            }//! igen loop


            iEvent++;
            //std::cout<<"Completed event #  "<<ievt<<std::endl;

        }//! event loop ends

        //delete parHI_l2;
        //delete parHI_l3;
        //delete _JEC_HI;

    }//! jet loop

    std::cout<<std::endl;
    for(int nj=0; nj<knj; nj++) {
        std::cout<<calgo[nj] << std::endl;
        if(strcmp(ksp,"pp")==0) {
            std::cout<<"\t # of events : "<< " pp " << "  " << nevt[nj][0] << "  " << njets[nj][0] << std::endl;
        }
        else {
            for(int ic=0; ic<ncent; ic++) {
                std::cout<<"\t # of events : "<< ccent[ic] << "  " << nevt[nj][ic] << "  " << njets[nj][ic] << std::endl;
            }
        }
        std::cout<<std::endl;
    }
    std::cout<<std::endl;



    //! Write to output file
    fout->cd();
    fout->Write();
    fout->Close();


    //! Check
    timer.Stop();
    double rtime  = timer.RealTime();
    double ctime  = timer.CpuTime();

    std::cout<<std::endl;
    std::cout<<Form("RealTime=%f seconds, CpuTime=%f seconds",rtime,ctime)<<std::endl;
    std::cout<<std::endl;
    std::cout<<"Good bye : " <<"\t"<<std::endl;
    return 1;
}