コード例 #1
0
plot_warnmap2D( string warnmapfile , bool writeplots = true )
{
  gStyle->SetOptStat(0);

  /* Read warnmap as tree */
  TTree *twarn = new TTree();
  twarn->ReadFile( warnmapfile.c_str(), "sector/I:y:z:status" );

  // Declaration of leaf types
  Int_t           sector;
  Int_t           y;
  Int_t           z;
  Int_t           status;

  // List of branches
  TBranch        *b_sector;   //!
  TBranch        *b_y;   //!
  TBranch        *b_z;   //!
  TBranch        *b_status;   //!

  twarn->SetBranchAddress("sector", &sector, &b_sector);
  twarn->SetBranchAddress("y", &y, &b_y);
  twarn->SetBranchAddress("z", &z, &b_z);
  twarn->SetBranchAddress("status", &status, &b_status);



  /* Create 2D histograms to visualize warnmap */
  TH2I* h_warnmap[8];
  int zbins = 0;
  int ybins = 0;

  /* Create histogram for each sector */
  for( int sector = 0; sector < 8; sector++ )
    {
      if(sector <6) // PbSc sector
	{
	  zbins = 72;
	  ybins = 36;
	}
      else // PbGl sector
	{
	  zbins = 96;
	  ybins = 48;
	}

      TString name("h_warnmap_sector_");
      name += sector;

      TString title("Warnmap sector ");
      title += sector;

      cout << name <<endl;
      cout << title <<endl;

      h_warnmap[sector] = new TH2I( name, title, zbins, 0, zbins, ybins, 0, ybins );
      h_warnmap[sector]->GetXaxis()->SetTitle("z [cm]");
      h_warnmap[sector]->GetYaxis()->SetTitle("y [cm]");

    } //sector

  /* Loop over warnmap and fill status of towers into map */
  Long64_t nentries = twarn->GetEntriesFast();

  for ( Long64_t jentry = 0; jentry < nentries; jentry++ )
    {
      twarn->GetEntry(jentry);

      //cout << sector << " " << y << " " << z << " " << status << endl;

      // if status > 50 (e.g. 'dead' or 'uncalibrated', set it to 39 for nicer plotting
      if ( status > 50 )
	status = 39;

      h_warnmap[sector]->Fill( z , y , status );

    }

  /* build base filename for plots */
  std::size_t pos = warnmapfile.find("/");
  string filename_cut = warnmapfile.substr( pos+1 );
  (filename_cut.erase( filename_cut.length()-4 ,4 ));//.erase(0,25);


  /* plot warnmaps */
  for( int sector = 0; sector < 8; sector++ )
    {
      TCanvas *c1 = new TCanvas();
      (h_warnmap[sector])->Draw("colz");

      if ( writeplots )
	{
	  TString filename("plots-warnmap-2D/warnmap2D_");
	  filename+=filename_cut;
	  filename+="_sector_";
	  filename+=sector;
	  filename+=".eps";

	  TString filenamep("plots-warnmap-2D/warnmap2D_");
	  filenamep+=filename_cut;
	  filenamep+="_sector_";
	  filenamep+=sector;
	  filenamep+=".png";

	  c1->Print( filename );
	  c1->Print( filenamep );
	}

    }


  /* Draw combined canvas with all sectors */
  TCanvas *c2 = new TCanvas();
  c2->SetCanvasSize( 1000, 500 );
  c2->SetWindowSize( 1000, 500 );
  c2->Divide(4,2);

  for( int sector = 0; sector < 8; sector++ )
    {
      c2->cd(sector+1);
      (h_warnmap[sector])->Draw("colz");
    }

  TString filenameAll("plots-warnmap-2D/warnmap2D_");
  filenameAll+=filename_cut;
  filenameAll+="_sector_all.eps";

  TString filenameAllp("plots-warnmap-2D/warnmap2D_");
  filenameAllp+=filename_cut;
  filenameAllp+="_sector_all.eps";

  c2->Print( filenameAll );
  c2->Print( filenameAllp );



  //  h_warnmap_[sect]->Fill(z, y, warnmap_[sect][z][y]);


//    for(int y=0; y<48; y++)
//{
//      if(sect<6 && y>35) continue;
//      for(int z=0; z<96; z++)
//{
//	if(sect<6 && z>71) continue;
//
//	id = anatools::TowerID(sect, y, z);
//	for(int erng=0; erng<6; erng++)
//{
//	  if(hotmap_[erng][sect][z][y] == 100) continue;
//	  h_counts_hot[erng]->Fill(id, hitmap_[erng][sect][z][y]);
//	}//erng
//      }//z
//    }//y
//    h_warnmap_[sect]->Write();
//  }//sect



  return;
}
コード例 #2
0
ファイル: sqrtByFill.C プロジェクト: keithdlandry/2012IFF
void sqrtByFill(){


	//OPTIONS AND CUTS______________
	bool useBlueBeam = true;
	bool useYellowBeam = true;
	bool randomizeSpin = false;
	bool fullEta = true;
	
	double PI = 3.14159265359;
	
	//LOAD LIBS_____________________
	cout << "\n";
	gROOT->Macro("StRoot/LoadLibs.C");
	gSystem->Load("pionPair");
	cout << " loading of pionPair library done" << endl;
	//______________________________
	
	
	//SET UP INPUT FILE_____________
	TFile* infile = new TFile("/star/u/klandry/ucladisk/2012IFF/schedOut_Full_4_2/allPairs_4_2.root");
	
	string outFileName = "./resultsNew_4_22/pairsFrom4_2ByFill.root"; 
	
	
	
  //______________________________
	
	
	//SET UP TREE TO RECEIVE INPUT__
	pionPair* pair1 = new pionPair();
	TTree* pairTree = infile->Get("pionPairTree");
	pairTree->SetBranchAddress("pionPair", &pair1);
	//______________________________
	
	
	

	
	double histMin = -PI;
	double histMax =  PI;
	const int binNumber = 16;
	
	TH1D * hNumberUp   = new TH1D("hNumberUp","hNumberUp",binNumber,histMin,histMax);
	TH1D * hNumberDown = new TH1D("hNumberDown","hNumberDown",binNumber,histMin,histMax);
	TH1D * hAut = new TH1D("Aut","Aut",binNumber,histMin,histMax);

	
	TH1D* polOfBin[16];
	for (int i = 0; i < 16; i++)
	{
		stringstream ss;
		ss << i;
				
		string fullname = "hPolOfBin_phiSRbin_" + ss.str();
		cout << fullname << endl;
		
		polOfBin[i] = new TH1D(fullname.c_str(),fullname.c_str(),25,0,1);
		
	}
	
	
	
	//BEAM POLARIZATION_____________
	ifstream polFile;
	polFile.open("/star/u/klandry/ucladisk/2012IFF/BeamPolarization2012.txt");
	
	
	map<int, double> polarizationOfFill_Y;
	map<int, double> polErrOfFill_Y;
	
	map<int, double> polarizationOfFill_B;
	map<int, double> polErrOfFill_B;
	
	
	
	int    fill;
	int    beamE;
	int    startT;
	string plusminus;
	
	double pAvrgBlue;
	double pErrAvrgBlue;
	
	double pInitialBlue;
	double pErrInitialBlue;
	double dPdTBlue;
	double dPdTErrBlue;
	
	double pAvrgYellow;
	double pErrAvrgYellow;
	
	double pInitialYellow;
	double pErrInitialYellow;
	double dPdTYellow;
	double dPdTErrYellow;
	
	string header;
	
	for (int i=0; i<19; i++){polFile >> header;}
	
	while (!polFile.eof())
	{
		
		polFile >> fill;
		polFile >> beamE;
		polFile >> startT;
		
		polFile >> pAvrgBlue;
		polFile >> plusminus;
		polFile >> pErrAvrgBlue;
		
		polFile >> pInitialBlue;
		polFile >> plusminus;
		polFile >> pErrInitialBlue;
		
		polFile >> dPdTBlue;
		polFile >> plusminus;
		polFile >> dPdTErrBlue;
		
		polFile >> pAvrgYellow;
		polFile >> plusminus;
		polFile >> pErrAvrgYellow;
		
		polFile >> pInitialYellow;
		polFile >> plusminus;
		polFile >> pErrInitialYellow;
		
		polFile >> dPdTYellow;
		polFile >> plusminus;
		polFile >> dPdTErrYellow;
		
		
		polarizationOfFill_B[fill] = pAvrgBlue/100.;
		polErrOfFill_B[fill] = pErrAvrgBlue/100.;
		
		polarizationOfFill_Y[fill] = pAvrgYellow/100.;
		polErrOfFill_Y[fill] = pErrAvrgYellow/100.;
		
	}
	
	double avgPolOfBinUp[binNumber];
	double polOfBinSumUp[binNumber];
	
	double avgPerrorOfBinUp[binNumber];
	double pErrorOfBinUp[binNumber];
	
	double avgPolOfBinDown[binNumber];
	double polOfBinSumDown[binNumber];
	
	double avgPerrorOfBinDown[binNumber];
	double pErrorOfBinDown[binNumber];
	
	for (int i=0; i<binNumber; i++)
	{
		avgPolOfBinUp[i] = 0;
		polOfBinSumUp[i] = 0;
		
		avgPerrorOfBinUp[i] = 0;
		pErrorOfBinUp[i] = 0;
		
		avgPolOfBinDown[i] = 0;
		polOfBinSumDown[i] = 0;
		
		avgPerrorOfBinDown[i] = 0;
		pErrorOfBinDown[i] = 0;
		
	}
	
	
	
	//CUTS__________________________
	double lowLimitPt    = ptBinStart[0];
	double hiLimitPt     = ptBinEnd[4];
	double lowLimitEta   = etaBinStart[3];  //set up do only do eta bin 3
	double hiLimitEta    = etaBinEnd[3];
	double lowLimitMass  = massBinStart[0];
	double hiLimitMass   = massBinEnd[4];
	
	
	
	
	//______________________________
	//   ======================================================================
	//============================================================================
	//START ANALYSIS==============================================================
	//============================================================================
	//   ======================================================================
	//*
	cout << "\n";
	cout << "<----STARTING ANALYSIS---->" << endl;
  cout << "\n";
	cout << pairTree->GetEntries() << " pairs to analyze" << endl;
	
	
	
	int blueFillNo;
	int yellowFillNo;
	
	int phiSRbin;
	
	
	vector<double> fillAsyms;
	vector<double> fillAsymsE;
	vector<double> fillVec;
	
	TLorentzVector sum;
	TLorentzVector sumY;
	TLorentzVector sumB;
	
	//random number for randomizing spin.
	//set seed to zero to gaurenty unique numbers each time.
	TRandom3 r;
	r.SetSeed(0);
	
	int rand5 = 0;
	int rand6 = 0;
	int rand9 = 0;
	int rand10 = 0;
	
	
	int totalPairsFinal = 0;
	int blueD = 0;
	int blueU = 0;
	int yellowD = 0;
	int yellowU = 0;
	
	int pionStarNumber = 0;
	int runsProcessed = 0;
	
	double currentFillNo = 0;
	double currentRunNo = 0;

	
	for (int iPair = pionStarNumber; iPair < pairTree->GetEntries(); iPair++)
	{
		
		if (iPair%10000 == 0) {cout << "processing pair number " << iPair << endl;}
		//if (iPair == pionStarNumber+300000){break;}
		
		pairTree->GetEntry(iPair);
		
		//if (runsProcessed > 4){break;} 
		
		
		if (pair1->runInfo().beamFillNumber(1) != currentFillNo && currentFillNo != 0 && currentFillNo != 16427)
		//if (pair1->runInfo().runId() != currentRunNo && currentRunNo != 0)
		{
			runsProcessed++;

			cout << "runsProcessed " << runsProcessed << endl;
			
			double* asym = new double();
			double* asymE = new double();
			calcAsyms(hAut, hNumberUp, hNumberDown, polOfBin, asym, asymE);
						
			fillAsyms.push_back(*asym);
			fillAsymsE.push_back(*asymE);
			fillVec.push_back(runsProcessed);
			
			hNumberUp->Reset();
			hNumberDown->Reset();
			hAut->Reset();
			
			for (int i=0; i<binNumber; i++)
			{
				polOfBin[i]->Reset();
			}
			
			
		}
		else if (currentRunNo == 16427)
		{
			//fillAsyms.push_back(*asym);
			//fillAsymsE.push_back(*asymE);
			//fillVec.push_back(runsProcessed);
			
			hNumberUp->Reset();
			hNumberDown->Reset();
			hAut->Reset();
			
			for (int i=0; i<binNumber; i++)
			{
				polOfBin[i]->Reset();
			}
			
		
		}
		
		
		currentRunNo = pair1->runInfo().runId();
		currentFillNo = pair1->runInfo().beamFillNumber(1);
		
		if (pair1->withinRadius(0.05, 0.3))
		{
			
			bool triggerFired = false;
			bool fromKaon = false;
			bool passInitialCut_B = false;
			bool passInitialCut_Y = false;
			bool passDCAcut = false;
			
			StTriggerId trigId = pair1->triggerIds();
			
			//JP0,JP1,JP2,AJP
			if (trigId.isTrigger(370601) || trigId.isTrigger(370611) || trigId.isTrigger(370621) || trigId.isTrigger(370641))
			{
				triggerFired = true;
			}
			
			//BHT0VPD,BHT1VPD,BHT2BBC,BHT2
			if (trigId.isTrigger(370501) || trigId.isTrigger(370511) || trigId.isTrigger(370522) || trigId.isTrigger(370531))
			{
				triggerFired = true;
			}
			
			
			if (triggerFired)
			{
				
				blueFillNo   = pair1->runInfo().beamFillNumber(1); //1 = blue beam
				yellowFillNo = pair1->runInfo().beamFillNumber(0); //0 = yellow beam 
				
				sum = pair1->piPlusLV() + pair1->piMinusLV();
				sumB = sum; //blue beam.
				
				
				//yellow beam must rotate around y axis by pi so the eta cut can be the same for both beams. 				
				sumY = sum;
				sumY.RotateY(PI);

				if (sumB.Pt() >= lowLimitPt && sumB.Pt() <= hiLimitPt && sumB.M() >= lowLimitMass && sumB.M() <= hiLimitMass && sumB.Eta() >= lowLimitEta && sumB.Eta() <= hiLimitEta)
				{
					passInitialCut_B = true;
				}
				if (sumY.Pt() >= lowLimitPt && sumY.Pt() <= hiLimitPt && sumY.M() >= lowLimitMass && sumY.M() <= hiLimitMass && sumY.Eta() >= lowLimitEta && sumY.Eta() <= hiLimitEta)
				{
					passInitialCut_Y = true;
				}
				
				if (passInitialCut_B && useBlueBeam)
				{
					//BLUE BEAM SPIN UP: spin bin 9 and 10
					if (pair1->spinBit() == 9 || pair1->spinBit() == 10)
					{						
						hNumberUp->Fill(pair1->phiSR('b'));
						phiSRbin = hNumberUp->FindBin(pair1->phiSR('b'));
						
						polOfBin[phiSRbin-1]->Fill(polarizationOfFill_B[blueFillNo]);
						/*if (iPair > 39000)
						{
							cout << "polarization = " << polarizationOfFill_B[blueFillNo] << "  " << blueFillNo << endl;
						}*/
						
						
					}
					
					//BLUE BEAM SPIN DOWN: spin bin 5 and 6
					if (pair1->spinBit() == 5 || pair1->spinBit() == 6)
					{
						hNumberDown->Fill(pair1->phiSR('b'));
						phiSRbin = hNumberDown->FindBin(pair1->phiSR('b'));
						
						polOfBin[phiSRbin-1]->Fill(polarizationOfFill_B[blueFillNo]);
						
					}
				}//done with blue beam
				
				if (passInitialCut_Y && useYellowBeam)
				{
					//YELLOW BEAM SPIN UP: spin bin 6 and 10
					if (pair1->spinBit() == 6 || pair1->spinBit() == 10)
					{
						hNumberUp->Fill(pair1->phiSR('y'));
						phiSRbin = hNumberUp->FindBin(pair1->phiSR('y'));
						
						polOfBin[phiSRbin-1]->Fill(polarizationOfFill_Y[yellowFillNo]);
						
					}						
					
					//YELLOW BEAM SPIN DOWN: spin bit 5 and 9
					if (pair1->spinBit() == 5 || pair1->spinBit() == 9)
					{
						hNumberDown->Fill(pair1->phiSR('y'));
						phiSRbin = hNumberDown->FindBin(pair1->phiSR('y'));
						
						polOfBin[phiSRbin-1]->Fill(polarizationOfFill_Y[yellowFillNo]);
					}
				}//done with yellow beam
			}//end trigger check
		}//end radius check
		
		
	}//end pion tree loop
	
	
	cout << "out of tree loop" << endl;
	
	
	cout << fillAsyms.size() << endl;
	
	
	TGraphErrors* gAsymVsFill = new TGraphErrors(fillAsyms.size(), &fillVec[0], &fillAsyms[0], 0, &fillAsymsE[0]);
	
	gAsymVsFill->Draw("AP");
	
	TFile* outFile = new TFile(outFileName.c_str(),"recreate");

	gAsymVsFill->Write();

}
//should include inttype 11, 12, 13 as the signal
void TMVAClassificationApplication_cc1presv2_bdt_ver3noveract( TString myMethodList = "", TString fname )
{
#ifdef __CINT__
    gROOT->ProcessLine( ".O0" ); // turn off optimization in CINT
#endif
    
    //---------------------------------------------------------------
    
    // This loads the library
    TMVA::Tools::Instance();
    
    // Default MVA methods to be trained + tested
    std::map<std::string,int> Use;
    //
    // --- Boosted Decision Trees
    Use["BDT"]             = 1; // uses Adaptive Boost
    
    
    std::cout << std::endl;
    std::cout << "==> Start TMVAClassificationApplication" << std::endl;
    
    // Select methods (don't look at this code - not of interest)
    if (myMethodList != "") {
        for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;
        
        std::vector<TString> mlist = gTools().SplitString( myMethodList, ',' );
        for (UInt_t i=0; i<mlist.size(); i++) {
            std::string regMethod(mlist[i]);
            
            if (Use.find(regMethod) == Use.end()) {
                std::cout << "Method \"" << regMethod
                << "\" not known in TMVA under this name. Choose among the following:" << std::endl;
                for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
                    std::cout << it->first << " ";
                }
                std::cout << std::endl;
                return;
            }
            Use[regMethod] = 1;
        }
    }
    
    // --------------------------------------------------------------------------------------------------
    
    // --- Create the Reader object
    
    TMVA::Reader *reader = new TMVA::Reader( "!Color:!Silent" );
    
    // Create a set of variables and declare them to the reader
    // - the variable names MUST corresponds in name and type to those given in the weight file(s) used
    Float_t mumucl, pmucl;
    Float_t pang_t, muang_t;
    Float_t veract;
    Float_t ppe, mupe;
    Float_t range, coplanarity;
    Float_t opening;//newadd
    
    reader->AddVariable( "mumucl", &mumucl );
    reader->AddVariable( "pmucl", &pmucl );
    reader->AddVariable( "pang_t", &pang_t );
    reader->AddVariable( "muang_t", &muang_t );
    //reader->AddVariable( "veract", &veract );
    reader->AddVariable( "ppe", &ppe);
    reader->AddVariable( "mupe", &mupe);
    reader->AddVariable( "range", &range);
    reader->AddVariable( "coplanarity", &coplanarity);
    reader->AddVariable( "opening", &opening);//newadd
    
    // Spectator variables declared in the training have to be added to the reader, too
    Int_t fileIndex, inttype;
    Float_t nuE, norm, totcrsne;
    reader->AddSpectator( "fileIndex", &fileIndex );
    reader->AddSpectator( "nuE", &nuE );
    reader->AddSpectator( "inttype", &inttype );
    reader->AddSpectator( "norm", &norm );
    reader->AddSpectator( "totcrsne", &totcrsne );
    reader->AddSpectator( "veract", &veract );
    
    // --- Book the MVA methods
    
    TString dir    = "weights/";
    TString prefix = "TMVAClassification_cc1presv2_ver3noveract";//newchange
    
    // Book method(s)
    for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
        if (it->second) {
            TString methodName = TString(it->first) + TString(" method");
            TString weightfile = dir + prefix + TString("_") + TString(it->first) + TString(".weights.xml");
            reader->BookMVA( methodName, weightfile );
        }
    }
    
    // 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.
    //
    
    /*//TString fname = "/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/data_merged_ccqe_addpid_ver3noveract_pid1pres.root";
    //TString fname = "/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/pm_merged_ccqe_tot_addpid_ver3noveract_pid1pres.root";
    //TString fname = "/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/pmbar_merged_ccqe_addpid_ver3noveract_pid1pres.root";
    //TString fname = "/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/ingrid_merged_nd3_ccqe_tot_addpid_ver3noveract_pid1pres.root";
    //TString fname = "/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/wall_merged_ccqe_tot_addpid_ver3noveract_pid1pres.root";
    //check genie signal
    TString fname = "/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/genie_merged_ccqe_coh_addpid_ver3noveract_pid1pres.root";*/
    
    //add for event with more than 2 track
    //TString fname = "/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/data_merged_ccqe_processl2trk.root";
    //TString fname = "/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/pm_merged_ccqe_tot_processl2trk.root";
    //TString fname = "/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/pmbar_merged_ccqe_processl2trk.root";
    //TString fname = "/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/ingrid_merged_nd3_ccqe_tot_processl2trk.root";
    //TString fname = "/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/wall_merged_ccqe_tot_processl2trk.root";
    //check genie signal
    //TString fname = "/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/genie_merged_ccqe_coh_processl2trk.root";
    
    //for correct cc1pres pid
    //TString fname = "/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/data_merged_ccqe_correct1pres.root";
    //TString fname = "/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/pm_merged_ccqe_tot_correct1pres.root";
    //TString fname = "/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/pmbar_merged_ccqe_correct1pres.root";
    //TString fname = "/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/ingrid_merged_nd3_ccqe_tot_correct1pres.root";
    //TString fname = "/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/wall_merged_ccqe_tot_correct1pres.root";
    //TString fname = "/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/genie_merged_ccqe_coh_correct1pres.root";
    //for correct prange/pang_t and additional information
    //TString fname = "/home/cvson/cc1picoh/dataProcess/fix20150420/data_merged_ccqe_addpidFF.root";
   // TString fname = "/home/cvson/cc1picoh/dataProcess/fix20150420/pm_merged_ccqe_tot_addpidFF.root";
    //TString fname = "/home/cvson/cc1picoh/dataProcess/fix20150420/pmbar_merged_ccqe_addpidFF.root";
    //TString fname = "/home/cvson/cc1picoh/dataProcess/fix20150420/ingrid_merged_nd3_ccqe_tot_addpidFF.root";
    //TString fname = "/home/cvson/cc1picoh/dataProcess/fix20150420/wall_merged_ccqe_tot_addpidFF.root";
    //TString fname = "/home/cvson/cc1picoh/dataProcess/fix20150420/genie_merged_ccqe_tot_addpidFF.root";
    
    //
    std::cout << "--- Selecting data sample" << std::endl;
    TFile *pfile = new TFile(fname,"update");
    TTree* theTree = (TTree*)pfile->Get("tree");
    theTree->SetBranchAddress( "mumucl", &mumucl );
    theTree->SetBranchAddress( "pmucl", &pmucl );
    theTree->SetBranchAddress( "pang_t", &pang_t );
    theTree->SetBranchAddress( "muang_t", &muang_t );
    theTree->SetBranchAddress( "veract", &veract );
    theTree->SetBranchAddress( "ppe", &ppe);
    theTree->SetBranchAddress( "mupe", &mupe);
    theTree->SetBranchAddress( "range", &range);
    theTree->SetBranchAddress( "coplanarity", &coplanarity);
    theTree->SetBranchAddress( "opening", &opening);
    
 
    
    Int_t Ntrack;
    theTree->SetBranchAddress( "Ntrack", &Ntrack );
    
    
    Float_t pid1pres;
    TBranch *bpid1pres = theTree->Branch("pid1pres",&pid1pres,"pid1pres/F");
    
    
    
    std::vector<Float_t> vecVar(9); // vector for EvaluateMVA tests
    
    Long64_t nentries = theTree->GetEntriesFast();
    Long64_t iprintProcess = Long64_t(nentries/100.);
    
    std::cout << "--- Processing: " << nentries << " events" << std::endl;
    
    TStopwatch sw;
    sw.Start();
    for (Long64_t ievt=0; ievt<nentries;ievt++) {
        
        if (ievt%iprintProcess == 0) cout<<"Processing "<<int(ievt*100./nentries)<<"% of events"<<endl;
        theTree->GetEntry(ievt);
        Float_t pid_tem;
        if (Use["BDT"])      {
            //if (Ntrack!=2) pid_tem = -999;//change here
            if (Ntrack<2) pid_tem = -999;
            else pid_tem = reader->EvaluateMVA("BDT method");
        }
        pid1pres = pid_tem;
        bpid1pres->Fill();
        
    }
    theTree->Write();
    delete pfile;
    // Get elapsed time
    sw.Stop();
    std::cout << "--- End of event loop: "; sw.Print();
    
    delete reader;
    
    std::cout << "==> TMVAClassificationApplication is done!" << endl << std::endl;
} 
コード例 #4
0
void ppEffJpsiSysSFsSTA__idx_()   
{
  double minRap = 0.0;
  double maxRap = 2.4;
  double minPt = 6.5;
  double maxPt = 30.0;

  // if you want to measure low pT, you can set up minRap = 1.6 and minPt = 3.0, maxPt = 6.5;

  gROOT->SetStyle("Plain");
  gStyle->SetPalette(1);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetFrameFillColor(0);
  gStyle->SetCanvasColor(0);
  gStyle->SetTitleFillColor(0);
  gStyle->SetStatColor(0);
  gStyle->SetPadBorderSize(0);
  gStyle->SetCanvasBorderSize(0);
  gStyle->SetOptTitle(0); // at least most of the time
  gStyle->SetOptStat(0); // most of the time, sometimes "nemriou" might be useful to display name, 
  //number of entries, mean, rms, integral, overflow and underflow
  gStyle->SetOptFit(0); // set to 1 only if you want to display fit results
  //==================================== Define Histograms====================================================

  //==============================================Define Acc Eff Stuff here===========================================
  // Pt bin sizes
  // 0-1.5, 1.5-3, 3-4.5, 4.5-6, 6-7.5...

  TFile *outfile;
  char tmp_output[512];
  sprintf(tmp_output,"ppPrJpsi_pT_%0.1f_%0.1f_y_%0.1f_%0.1f_HighQ_tnpWgt.root", minPt, maxPt, minRap, maxRap);
  outfile =new TFile(tmp_output, "Recreate");

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

    const int nPtBins = 4;
    const int nRapBins = 3; 
    const int ndPhiBins = 4;
    double pt_bound[nPtBins+1] = {6.5, 8.0, 10.0, 13.0, 30.0};
    double xpt_bound[nPtBins] = {0.0};
    //double rap_bound[nRapBins+1] = {0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1, 2.4};
    double rap_bound[nRapBins+1] = {0.0, 1.2, 1.6, 2.4};
    double xrap_bound[nRapBins] = {0.0};
    double dphi_bound[ndPhiBins+1] = {0.0, TMath::Pi()/8, TMath::Pi()/4, 3*TMath::Pi()/8, TMath::Pi()/2};
    double xdphi_bound[ndPhiBins] = {0.0};

    const char *cSp[2] = {"Pts","Raps"};
    char OutTextFile[100];
    sprintf(OutTextFile,"ppPromp_eff_%s_pT_%0.1f_%0.1f_y_%0.1f_%0.1f_HighQ.tex", cSp[iSpec], minPt, maxPt, minRap, maxRap);
    ofstream dataFile(OutTextFile);
    //ofstream dataFile(Form(OutTextFile));

    cout<< "%%%% Getting Efficiency starts : %s !!!!! %%%%%" << endl;
    //dataFile<< "%%%% Getting Efficiency starts : %s !!!!! %%%%%" << endl;

    // x, y, z - axis 
    //dataFile<<""<<endl;
    //dataFile<<"xaxis of pT"<<endl;
    for(int i = 0; i < nPtBins; i++){
      xpt_bound[i] = pt_bound[i] + (pt_bound[i+1]-pt_bound[i])/2;
      cout<<"xpt_bound["<<i<<"] : "<<xpt_bound[i]<<endl;
      //dataFile<<"xpt_bound["<<i<<"] : "<<xpt_bound[i]<<endl;
    }
    //dataFile<<""<<endl;
    //dataFile<<"xaxis of rap"<<endl;
    for(int i = 0; i < nRapBins; i++){
      xrap_bound[i] = rap_bound[i] + (rap_bound[i+1]-rap_bound[i])/2;
      cout<<"xrap_bound["<<i<<"] : "<<xrap_bound[i]<<endl;
      //dataFile<<"xrap_bound["<<i<<"] : "<<xrap_bound[i]<<endl;
    }
    //dataFile<<""<<endl;
    //dataFile<<"xaxis of dphi"<<endl;
    for(int i = 0; i < ndPhiBins; i++){
      xdphi_bound[i] = dphi_bound[i] + (dphi_bound[i+1]-dphi_bound[i])/2;
      cout<<"xdphi_bound["<<i<<"] : "<<xdphi_bound[i]<<endl;
      //dataFile<<"xdphi_bound["<<i<<"] : "<<xdphi_bound[i]<<endl;
    }

    int nBins_tmp = 0;
    if(iSpec == 0) { nBins_tmp = nPtBins; }
    if(iSpec == 1) { nBins_tmp = nRapBins; }
    const int nBins = nBins_tmp;

    TH1F *hTempMass = new TH1F("hTempMass","",100, 2.0, 4.0);
    TH1F *hGenDiMuon[nBins];
    TH1F *hRecoDiMuon[nBins];
    double genNo[nBins];
    double genErr[nBins];
    double recoNo[nBins];
    double recoErr[nBins];
    double eff[nBins];
    double effErr[nBins];
    for(int i = 0; i < nBins; i++){
      hGenDiMuon[i] = (TH1F*)hTempMass->Clone();
      hRecoDiMuon[i] = (TH1F*)hTempMass->Clone();
      hGenDiMuon[i]->Sumw2();
      hRecoDiMuon[i]->Sumw2();
    }

    char fileName[10][512];

    // loop for pT
    cout<<"==================Prompt PrJpsi================================================"<<endl;

    sprintf(fileName[0],"/Users/dmoon/Dropbox/Analysis/HiMC/EffStudy/gRpAngRootFiles_538_pp/HiDiMuonAna_538_pp_NonPromptJpsi_20140317_Trg21.root");


    TFile *infile;
    TTree *tree;
    TTree *gentree;
    TTree *evttree;

    infile=new TFile(fileName[0],"R");
    tree=(TTree*)infile->Get("SingleMuonTree");
    gentree=(TTree*)infile->Get("SingleGenMuonTree");
    evttree=(TTree*)infile->Get("EventTree");
    //Event variables
    int eventNb,runNb,lumiBlock;
    int hbit1;
    //double vertexZ;
    //double GenvertexZ;
    //Jpsi Variables
    Double_t JpsiMass,JpsiPt,JpsiRap, JpsiCharge;
    Double_t JpsiVprob;
    Double_t JpsiPhi;
    Double_t JpsiEta;
    //2.) muon variables RECO                                                                       
    double muPosPx, muPosPy, muPosPz,  muPosEta, muPosPt, muPosP, muPosPhi;
    double muNegPx, muNegPy, muNegPz,  muNegEta, muNegPt, muNegP, muNegPhi;
    //(1).Positive Muon                                     
    double muPos_nchi2In, muPos_dxy, muPos_dz, muPos_nchi2Gl;
    int muPos_found, muPos_pixeLayers, muPos_nValidMuHits,muPos_arbitrated;
    bool muPos_matches,muPos_tracker;
    int muPos_Trigger10, muPos_Trigger2, muPos_Trigger21, muPos_Trigger22;
    //(2).Negative Muon                                     
    double muNeg_nchi2In, muNeg_dxy, muNeg_dz, muNeg_nchi2Gl;
    int muNeg_found, muNeg_pixeLayers, muNeg_nValidMuHits,muNeg_arbitrated;
    bool muNeg_matches,muNeg_tracker;
    int muNeg_Trigger10, muNeg_Trigger2, muNeg_Trigger21, muNeg_Trigger22;

    //Gen Level variables
    //Gen PrJpsi Variables
    double GenJpsiMass, GenJpsiPt, GenJpsiRap;
    double GenJpsiPx, GenJpsiPy, GenJpsiPz;
    double GenJpsiPhi;
    double GenJpsiEta;
    //2.) Gen muon variables 
    double GenmuPosPx, GenmuPosPy, GenmuPosPz,  GenmuPosEta, GenmuPosPt, GenmuPosPhi;
    double GenmuNegPx, GenmuNegPy, GenmuNegPz,  GenmuNegEta, GenmuNegPt, GenmuNegPhi;
    double zVtx;

    //Event variables
    tree->SetBranchAddress("eventNb",&eventNb);
    tree->SetBranchAddress("runNb",&runNb);
    tree->SetBranchAddress("lumiBlock",&lumiBlock);
    tree->SetBranchAddress("hbit1",&hbit1);
    tree->SetBranchAddress("zVtx",&zVtx);
    //tree->SetBranchAddress("vertexZ",&vertexZ);

    //Jpsi Variables
    tree->SetBranchAddress("JpsiCharge",&JpsiCharge);
    tree->SetBranchAddress("JpsiMass",&JpsiMass);
    tree->SetBranchAddress("JpsiPt",&JpsiPt);
    tree->SetBranchAddress("JpsiPhi",&JpsiPhi);
    tree->SetBranchAddress("JpsiEta",&JpsiEta);
    tree->SetBranchAddress("JpsiRap",&JpsiRap);
    tree->SetBranchAddress("JpsiVprob",&JpsiVprob);

    //muon variable
    tree->SetBranchAddress("muPosPx",&muPosPx);
    tree->SetBranchAddress("muPosPy",&muPosPy);
    tree->SetBranchAddress("muPosPz",&muPosPz);
    tree->SetBranchAddress("muPosEta",&muPosEta);
    tree->SetBranchAddress("muPosPhi",&muPosPhi);
    tree->SetBranchAddress("muNegPx", &muNegPx);
    tree->SetBranchAddress("muNegPy", &muNegPy);
    tree->SetBranchAddress("muNegPz", &muNegPz);
    tree->SetBranchAddress("muNegEta", &muNegEta);
    tree->SetBranchAddress("muNegPhi", &muNegPhi);


    //1). Positive Muon
    tree->SetBranchAddress("muPos_nchi2In", &muPos_nchi2In);
    tree->SetBranchAddress("muPos_dxy", &muPos_dxy);
    tree->SetBranchAddress("muPos_dz", &muPos_dz);
    tree->SetBranchAddress("muPos_nchi2Gl", &muPos_nchi2Gl);
    tree->SetBranchAddress("muPos_found", &muPos_found);
    tree->SetBranchAddress("muPos_pixeLayers", &muPos_pixeLayers);
    tree->SetBranchAddress("muPos_nValidMuHits", &muPos_nValidMuHits);
    tree->SetBranchAddress("muPos_matches", &muPos_matches);
    tree->SetBranchAddress("muPos_tracker", &muPos_tracker);
    tree->SetBranchAddress("muPos_arbitrated", &muPos_arbitrated);
    tree->SetBranchAddress("muPos_Trigger10", &muPos_Trigger10);
    tree->SetBranchAddress("muPos_Trigger2", &muPos_Trigger2);
    tree->SetBranchAddress("muPos_Trigger21", &muPos_Trigger21);
    tree->SetBranchAddress("muPos_Trigger22", &muPos_Trigger22);

    //2). Negative Muon                                                                            
    tree->SetBranchAddress("muNeg_nchi2In", &muNeg_nchi2In);
    tree->SetBranchAddress("muNeg_dxy", &muNeg_dxy);
    tree->SetBranchAddress("muNeg_dz", &muNeg_dz);
    tree->SetBranchAddress("muNeg_nchi2Gl", &muNeg_nchi2Gl);
    tree->SetBranchAddress("muNeg_found", &muNeg_found);
    tree->SetBranchAddress("muNeg_pixeLayers", &muNeg_pixeLayers);
    tree->SetBranchAddress("muNeg_nValidMuHits", &muNeg_nValidMuHits);
    tree->SetBranchAddress("muNeg_matches", &muNeg_matches);
    tree->SetBranchAddress("muNeg_tracker", &muNeg_tracker);
    tree->SetBranchAddress("muNeg_arbitrated", &muNeg_arbitrated);
    tree->SetBranchAddress("muNeg_Trigger10", &muNeg_Trigger10);
    tree->SetBranchAddress("muNeg_Trigger2", &muNeg_Trigger2);
    tree->SetBranchAddress("muNeg_Trigger21", &muNeg_Trigger21);
    tree->SetBranchAddress("muNeg_Trigger22", &muNeg_Trigger22);
    //====================================Gen Variables=========================================================
    //Gen Jpsi Variables
    gentree->SetBranchAddress("GenJpsiMass",   &GenJpsiMass);
    gentree->SetBranchAddress("GenJpsiPt",     &GenJpsiPt);
    gentree->SetBranchAddress("GenJpsiPhi",    &GenJpsiPhi);
    gentree->SetBranchAddress("GenJpsiRap",    &GenJpsiRap);
    gentree->SetBranchAddress("GenJpsiEta",    &GenJpsiEta);
    gentree->SetBranchAddress("GenJpsiPx",     &GenJpsiPx);
    gentree->SetBranchAddress("GenJpsiPy",     &GenJpsiPy);
    gentree->SetBranchAddress("GenJpsiPz",     &GenJpsiPz);
    //muon variable
    gentree->SetBranchAddress("GenmuPosPx",    &GenmuPosPx);
    gentree->SetBranchAddress("GenmuPosPy",    &GenmuPosPy);
    gentree->SetBranchAddress("GenmuPosPz",    &GenmuPosPz);
    gentree->SetBranchAddress("GenmuPosEta",   &GenmuPosEta);
    gentree->SetBranchAddress("GenmuPosPhi",   &GenmuPosPhi);
    gentree->SetBranchAddress("GenmuNegPx",    &GenmuNegPx);
    gentree->SetBranchAddress("GenmuNegPy",    &GenmuNegPy);
    gentree->SetBranchAddress("GenmuNegPz",    &GenmuNegPz);
    gentree->SetBranchAddress("GenmuNegEta",   &GenmuNegEta);
    gentree->SetBranchAddress("GenmuNegPhi",   &GenmuNegPhi);
    //gentree->SetBranchAddress("GenvertexZ",&GenvertexZ);

    //====================================================== Gen tree loop ================================================
    int NAccep=0;
    int nGenEntries=gentree->GetEntries();
    cout<<" Total Entries in GenLevel Tree for pT range: "<<fileName[0]<<"  "<<   nGenEntries<< " ==============="<<endl;

    for(int i=0; i< nGenEntries; i++)  {        
      //cout<<"i : "<<i<<endl;
      if(!(gentree->GetEntry(i))) continue;
      //cout<<" gentree ("<<i<<")"<<endl;
      //Only printing 
      if(i%1000000==0){
        cout<<" processing record "<<i<<"/"<<nGenEntries<<endl;
        //cout<<" Mass "<< GenJpsiMass<< " pT "<< GenJpsiPt << " Y " <<GenJpsiRap<<endl;
      }

      bool GenPosIn=0, GenNegIn=0;
      GenmuPosPt= TMath::Sqrt(GenmuPosPx*GenmuPosPx + GenmuPosPy*GenmuPosPy); 
      GenmuNegPt= TMath::Sqrt(GenmuNegPx*GenmuNegPx + GenmuNegPy*GenmuNegPy); 

      if(IsAccept(GenmuPosPt, GenmuPosEta)) {GenPosIn=1;}
      if(IsAccept(GenmuNegPt, GenmuNegEta)) {GenNegIn=1;}

      int AccJpsi = 0;
      //if(GenJpsiPt < 6.5) continue;
      if((GenJpsiPt >= minPt && GenJpsiPt <= maxPt && fabs(GenJpsiRap) >= minRap && TMath::Abs(GenJpsiRap) <= maxRap && GenPosIn == 1 && GenNegIn == 1)
          && GenJpsiMass > 2.0 && GenJpsiMass < 4.0
          ) {AccJpsi = 1;}

      if((GenPosIn ==1 && GenNegIn==1)) NAccep++;

      //cout<<"1. GenJpsiPt : "<<GenJpsiPt<<", GenJpsiEta : "<<GenJpsiEta<<", GenJpsiRap : "<<GenJpsiRap<<", |GenJpsiPsi| : "<<TMath::Abs(GenJpsiPsi)<<endl;
      //cout<<"1. GenPosIn : "<<GenPosIn<<", GenNegIn : "<<GenNegIn<<endl;
      double vars = 0.0, bin1 = 0.0, bin2 = 0.0;
      if(iSpec == 0) vars = GenJpsiPt;
      if(iSpec == 1) vars = fabs(GenJpsiRap);
      for(int j = 0; j < nBins; j++){
        if(iSpec == 0){
          bin1 = pt_bound[j]; bin2 = pt_bound[j+1];
          if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && fabs(GenJpsiRap) >= minRap && TMath::Abs(GenJpsiRap) <= maxRap && TMath::Abs(GenJpsiRap) >= minRap) {
            hGenDiMuon[j]->Fill(GenJpsiMass);
          }
        }
        if(iSpec == 1){
          bin1 = rap_bound[j]; bin2 = rap_bound[j+1];
          if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && GenJpsiPt >= minPt && GenJpsiPt <= maxPt) {
            hGenDiMuon[j]->Fill(GenJpsiMass);
          }
        }
      }
    }//gen loop end

    //cout<<" accepted no "<< NAccep<<endl;

    //=============== Rec Tree Loop ==============================================================================

    int nRecEntries=tree->GetEntries();
    cout<<"Total Entries in reconstructed Tree for pT range "<<fileName[0]<<"  "<<nRecEntries<< "====="<<endl;
    for(int i=0; i<nRecEntries; i++)  {     
      tree->GetEntry(i);
      //Only printing 
      if(i%1000000==0){
        cout<<" processing record "<<i<<"/"<<nRecEntries<<endl;
        //cout<<" processing Run  " <<runNb <<" event "<<eventNb<<" lum block "<<lumiBlock<<endl;    
        //cout<<" Mass "<< JpsiMass<< " pT "<< JpsiPt << " Y " <<JpsiRap<<"  "<<JpsiVprob<<" charge "<<JpsiCharge<<" rbin "<<rbin<<endl; 
      }
      bool PosPass=0, NegPass=0, AllCut=0 ,PosIn=0, NegIn=0;
      muPosPt= TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy); 
      muPosP = TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy+ muPosPz*muPosPz); 
      muNegPt= TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy); 
      muNegP = TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy +muNegPz*muNegPz); 

      double tnpWgt1 = 0.0, tnpWgt2 = 0.0;
      double staWgt1 = 0.0, staWgt2 = 0.0;

      double x = 0.0;
      double xta = 0.0;
      // tnp MuonID X Trg
      if(fabs(muPosEta) < 0.9){
        x = muPosPt;
        tnpWgt1 = tnpSF1->Eval(x);
      }else if(fabs(muPosEta) < 1.6){
        x = muPosPt;
        tnpWgt1 = tnpSF2->Eval(x);
      }else if(fabs(muPosEta) < 2.1){
        x = muPosPt;
        tnpWgt1 = tnpSF3->Eval(x);
      }else{
        x = muPosPt;
        tnpWgt1 = tnpSF4->Eval(x);
      }

      if(fabs(muNegEta) < 0.9){
        x = muNegPt;
        tnpWgt2 = tnpSF1->Eval(x);
      }else if(fabs(muNegEta) < 1.6){
        x = muNegPt;
        tnpWgt2 = tnpSF2->Eval(x);
      }else if(fabs(muNegEta) < 2.1){
        x = muNegPt;
        tnpWgt2 = tnpSF3->Eval(x);
      }else{
        x = muNegPt;
        tnpWgt2 = tnpSF4->Eval(x);
      }

      // tnp STA 
      if(fabs(muPosEta) < 1.6){
        xta = muPosPt;
        staWgt1 = fun1->Eval(xta);
      }else{
        xta = muPosPt;
        staWgt1 = fun2->Eval(xta);
      }

      if(fabs(muNegEta) < 1.6){
        xta = muNegPt;
        staWgt2 = fun1->Eval(xta);
      }else{
        xta = muNegPt;
        staWgt2 = fun2->Eval(xta);
      }

      double RecWeight = 1.0;
      RecWeight = tnpWgt1*tnpWgt2*staWgt1*staWgt2;

      if(IsAccept(muPosPt, muPosEta)){PosIn=1;}
      if(IsAccept(muNegPt, muNegEta)){NegIn=1;}

      int AccJpsi = 0;
      //if(JpsiPt < 6.5) continue;
      if((JpsiPt >= minPt && JpsiPt <= maxPt && fabs(JpsiRap) >= minRap && TMath::Abs(JpsiRap) <= maxRap && PosIn == 1 && NegIn == 1)
          && (JpsiMass >= 2.95 && JpsiMass < 3.25)
          ) {AccJpsi = 1;}

      bool mu_Global = ((muPos_nchi2Gl >=0) && (muNeg_nchi2Gl >=0));
      bool mu_Tracker = ((muPos_tracker==1) && (muNeg_tracker==1));

      if(muPos_found > 10 
          && muPos_pixeLayers > 0 
          && muPos_nchi2In < 4.0 
          && TMath::Abs(muPos_dxy) < 3 
          && TMath::Abs(muPos_dz) < 15 
          && muPos_nchi2Gl < 20 
          && muPos_arbitrated==1 
          && muPos_tracker==1){PosPass=1;}     

      if(muNeg_found > 10 
          && muNeg_pixeLayers > 0 
          && muNeg_nchi2In < 4.0 
          && TMath::Abs(muNeg_dxy) < 3 
          && TMath::Abs(muNeg_dz) < 15 
          && muNeg_nchi2Gl < 20 
          && muNeg_arbitrated==1 
          && muNeg_tracker==1){NegPass=1;}


      // Trigger10 : HLT_PAL2DoubleMu3_v1, Trigger 2 : HLT_PAL1DoubleMu0_HighQ_v1, Trigger 1 : HLT_PAL1DoubleMu0_v1
      // muPos_matches : HLT_PAL1DoubleMuOpen_v1
      //if((muPos_Trigger21==1 && muNeg_Trigger21==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}
      if(hbit1 == 1 && (muPos_Trigger22==1 && muNeg_Trigger22==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}
      //if(hbit1 == 1 && (muPos_Trigger2==1 && muNeg_Trigger2==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}
      //if((muPos_matches==1 && muNeg_matches==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}
      //if((muPos_Trigger10==1 && muNeg_Trigger10==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}

      // without trigger matched
      // if((PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}

      //Eff loop for reco
      double vars = 0.0, bin1 = 0.0, bin2 = 0.0;
      if(iSpec == 0) vars = JpsiPt;
      if(iSpec == 1) vars = fabs(JpsiRap);
      if((JpsiCharge == 0) && (JpsiVprob > 0.01)) {     
        for(int j = 0; j < nBins; j++){
          if(iSpec == 0){
            bin1 = pt_bound[j]; bin2 = pt_bound[j+1];
            if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && TMath::Abs(JpsiRap) <= maxRap && TMath::Abs(JpsiRap) >= minRap) {
              hRecoDiMuon[j]->Fill(JpsiMass,RecWeight);
            }
          }
          if(iSpec == 1){ 
            bin1 = rap_bound[j]; bin2 = rap_bound[j+1];
            if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && JpsiPt >= minPt && JpsiPt <= maxPt) {
              hRecoDiMuon[j]->Fill(JpsiMass,RecWeight);
            }
          }
        }
      }
    } //rec tree loop ends

    //======================  File loop Starts ============================

    ///////////////////////////////////////////////////////////////////
    cout<< " adding "<<endl;
    char gtmp[512], gtmp1[512];
    char rtmp[512], rtmp1[512];

    for(int i = 0; i < nBins; i++){
      if(iSpec == 1) sprintf(gtmp,"hGenDiMuon_Pt_%0.1f_%0.1f",pt_bound[i],pt_bound[i+1]);
      if(iSpec == 2) sprintf(gtmp,"hGenDiMuon_Rap_%0.1f_%0.1f",rap_bound[i],rap_bound[i+1]);
      if(iSpec == 1) sprintf(gtmp1,"plots/Gen/hGenDiMuon_Pt_%0.1f_%0.1f.png",pt_bound[i],pt_bound[i+1]);
      if(iSpec == 2) sprintf(gtmp1,"plots/Gen/hGenDiMuon_Rap_%0.1f_%0.1f.png",rap_bound[i],rap_bound[i+1]);
      if(iSpec == 1) sprintf(rtmp,"hRecDiMuon_Pt_%0.1f_%0.1f",pt_bound[i],pt_bound[i+1]);
      if(iSpec == 2) sprintf(rtmp,"hRecDiMuon_Rap_%0.1f_%0.1f",rap_bound[i],rap_bound[i+1]);
      if(iSpec == 1) sprintf(rtmp1,"plots/Rec/hRecDiMuon_Pt_%0.1f_%0.1f.png",pt_bound[i],pt_bound[i+1]);
      if(iSpec == 2) sprintf(rtmp1,"plots/Rec/hRecDiMuon_Rap_%0.1f_%0.1f.png",rap_bound[i],rap_bound[i+1]);
      hGenDiMuon[i]->SetName(gtmp);
      hRecoDiMuon[i]->SetName(rtmp);
    }

    cout<<"Starts to calculate efficiency"<<endl;
    //dataFile<<""<<endl;
    //=====================Loop for eff========================================================================================//
    //define stuff here for error on weighted samples
    for(int i = 0; i < nBins; i++){
      int Gbinlow =hGenDiMuon[i]->GetXaxis()->FindBin(2.0);//2.95
      int Gbinhi=hGenDiMuon[i]->GetXaxis()->FindBin(4.0);//2.95

      int Rbinlow =hRecoDiMuon[i]->GetXaxis()->FindBin(2.95);//2.95
      int Rbinhi=hRecoDiMuon[i]->GetXaxis()->FindBin(3.25);//2.95

      genNo[i] = hGenDiMuon[i]->IntegralAndError(Gbinlow, Gbinhi, genErr[i]); 
      recoNo[i] = hRecoDiMuon[i]->IntegralAndError(Rbinlow, Rbinhi, recoErr[i]);
      //calculate Eff         
      if(genNo[i] == 0 || recoNo[i] == 0) {
        eff[i] = 0;
        effErr[i] = 0;
      }else{
        eff[i] = recoNo[i]/genNo[i]; 

        effErr[i] = recoNo[i]/genNo[i]*TMath::Sqrt(genErr[i]*genErr[i]/(genNo[i]*genNo[i]) + recoErr[i]*recoErr[i]/(recoNo[i]*recoNo[i]));

        //error without weight
        //dataFile<<" Bin ["<<i<<"] - "<< " Reco Jpsi : "<< recoNo[i]  <<", Gen Jpsi : "<< genNo[i] <<endl;
        //dataFile<<" Eff ["<<i<<"] - "<< eff[i] <<" Error "<< effErr[i] <<endl;
        cout<<" Bin ["<<i<<"] - "<< " Reco Jpsi : "<< recoNo[i]  <<", Gen Jpsi : "<< genNo[i] <<endl;
        cout<<" Eff ["<<i<<"] - "<< eff[i] <<" Error "<< effErr[i] <<endl;
      }
    }
    TH1F *hEff = new TH1F();
    int nEffBins = 0;
    if(iSpec == 0) {hEff = new TH1F("hEff","hEff;p_{T} GeV/c;Efficiency",nPtBins,pt_bound); nEffBins = nPtBins;}
    if(iSpec == 1) {hEff = new TH1F("hEff","hEff;y;Efficiency",nRapBins,rap_bound); nEffBins = nRapBins;}

    //dataFile<<"Efficiency"<<endl;
    for(int i = 0; i < nEffBins; i++){
      hEff->SetBinContent(i+1,eff[i]);
      hEff->SetBinError(i+1,effErr[i]);
      cout<<"Trying to measure eff vs "<<cSp[iSpec]<<endl;
      cout<<"Eff : "<<eff[i]<<", err : "<<effErr[i]<<endl;
      dataFile<<eff[i]<<endl;
    }

    //dataFile<<""<<endl;
    //dataFile<<"Errors"<<endl;
    for(int i = 0; i < nEffBins; i++){
      hEff->SetBinContent(i+1,eff[i]);
      hEff->SetBinError(i+1,effErr[i]);
      cout<<"Trying to measure eff vs "<<cSp[iSpec]<<endl;
      cout<<"Eff : "<<eff[i]<<", err : "<<effErr[i]<<endl;
      //dataFile<<effErr[i]<<endl;
    }


    outfile->cd();
    hEff->Draw();
    char tmp_histo[512];
    sprintf(tmp_histo,"hEff_%s",cSp[iSpec]);
    hEff->SetName(tmp_histo);
    hEff->Write();
    //dataFile<<""<<endl;
    //dataFile.close();
  }
  outfile->Write();
}
コード例 #5
0
ファイル: PRWTest.C プロジェクト: affablelochan/DataAnalysis
int main(int argc, char* argv[])
{
  
    printf("Before tool\n");
    BCHTool::BCHCleaningToolRoot thebchtool("thebchtool");
    thebchtool.SetResponseVsBCHFile("BCHCleaningTool/share/BCH_Response.root");

    ///TileTripReader initialisation and tests outside BCH tool
    
    //prepare a TileTripReader instance
    Root::TTileTripReader *ttr=new Root::TTileTripReader("thetripreader");
    ttr->setTripFile("TileTripReader/data/CompleteTripList_2011-2012.root");
    ttr->setVerbosity(0);
    
    //here we ask the TTR directly to give us the answer of a jet that is on the edge
    //the edges haven't yet been changed, so the answer should be no.
    bool isInDeadRegionBeforeEdgeChange = ttr->checkEtaPhi(211787,25000,0.1,0.35);
    cout << "In dead region, before edge change? " << isInDeadRegionBeforeEdgeChange << endl;

    //Set the edges
    ttr->m_LBOffsets.eta1=0.1;
    ttr->m_LBOffsets.eta2=0.1;
    ttr->m_LBOffsets.phi1=TMath::Pi()/32.;
    ttr->m_LBOffsets.phi2=TMath::Pi()/32.;
    
    //here we ask the TTR directly to give us the answer of a jet that is on the edge
    //the edges have now been changed, so the answer should be yes.
    bool isInDeadRegionAfterEdgeChange = ttr->checkEtaPhi(211787,25000,0.1,0.35);
    //NOTE: THIS IS WHERE IT DOES NOT GIVE ME THE RIGHT ANSWER!!! it should be TRUE below
    cout << "In dead region, after edge change? " << isInDeadRegionAfterEdgeChange << endl;
    
    ///PRW initialisation and tests
    
    //prepare a PRW instance
    Root::TPileupReweighting *prw=new Root::TPileupReweighting("thepileupreweighting");
    //initialise it with a MC file, a data file and tell it what to do with unmatched data
    prw->AddConfigFile("RootFilesForTests/ExcitedQ_2000.prw.root");
    prw->AddLumiCalcFile("RootFilesForTests/ilumicalc_histograms_None_200841-204158.root"); 
    prw->SetUnrepresentedDataAction(2);
    prw->Initialize();
    
    //initialize the BCH tool (for MC at the moment)
    //this will change the edges for the offsets of the TTR
    thebchtool.InitializeTool(false, ttr, prw);
    
    //here we ask the TTR directly to give us the answer of a jet that is on the edge
    //the edges haven't yet been changed, so the answer should be no.
    isInDeadRegionAfterEdgeChange = ttr->checkEtaPhi(211787,25000,0.1,0.35);
    cout << "In dead region, after edge change from BCH tool? " << isInDeadRegionAfterEdgeChange << endl;

    ///Stress test 
    TFile* stressfulFile = TFile::Open("RootFilesForTests/stress_test.root");
    TTree* stressfulTree = (TTree*) stressfulFile->Get("physics");
   
    ///Some random q* MC 
    //TODO add a different sample here
    
    std::vector<float> * v_jets_pt=0;
    std::vector<float> * v_jets_eta=0;
    std::vector<float> * v_jets_phi=0;
    stressfulTree->SetBranchAddress("jet_AntiKt4LCTopo_pt", &v_jets_pt);
    stressfulTree->SetBranchAddress("jet_AntiKt4LCTopo_eta", &v_jets_eta);
    stressfulTree->SetBranchAddress("jet_AntiKt4LCTopo_phi", &v_jets_phi);

    for (Int_t i=0;i<stressfulTree->GetEntries();i++) {
      stressfulTree->GetEntry(i);
      for (UInt_t ijet=0; ijet<v_jets_pt->size(); ijet++) {
        
        cout <<  "Jet pt:" << v_jets_pt->at(ijet) << endl;
        cout <<  "Jet eta:" << v_jets_eta->at(ijet) << endl;
        cout <<  "Jet phi:" << v_jets_phi->at(ijet) << endl;

        ///testing the basic functionality
        
        //note: need to pass the random number from MC to the BCHCleaningTool!! One can decide at this point whether to use mu or not
        //Here I've passed the RunNumber from a MC sample
        double mu = 20;
        int randomRunNumber = prw->GetRandomRunNumber(195847, mu);
        std::cout << "Random run number: " << randomRunNumber << std::endl;
        bool isInMaskedRegionBCH = thebchtool.IsInMaskedRegion(195847, v_jets_pt->at(ijet),v_jets_eta->at(ijet),v_jets_phi->at(ijet),mu);
        cout << "In dead region from BCHCleaningTool? " << isInMaskedRegionBCH  << endl;
        //testing straight from the TTR
        ttr->setVerbosity(0);
        bool isInMaskedRegionTTR = ttr->checkEtaPhi(randomRunNumber,v_jets_pt->at(ijet),v_jets_eta->at(ijet),v_jets_phi->at(ijet));
        cout << "In dead region from TTR? " << isInMaskedRegionTTR << endl;
        
        ///testing the response estimate
        cout << "Jet pT after response correction:" << thebchtool.EstimateJetResponseNoBCH(v_jets_pt->at(ijet), 0.3) << endl;        
        
      }
    }
    
    printf("After tool\n");
    return 0;
}
コード例 #6
0
ファイル: csv.C プロジェクト: aatos/chep09tmva
void csv(TString input="tmva.csvoutput.txt", TString par1="par2", TString par2="par3", TString par3="", TString value="eventEffScaled_5") {
  std::cout << "Usage:" << std::endl
            << ".x scripts/csv.C    with default arguments" << std::endl
            << ".x scripts/csv.C(filename, par1, par2, value)" << std::endl
            << std::endl
            << "  Optional arguments:" << std::endl
            << "    filename        path to CSV file" << std::endl
            << "    par1            name of X-parameter branch" << std::endl
            << "    par2            name of Y-parameter branch (if empty, efficiency is drawn as a function of par1)" << std::endl
            << "    value           name of result (efficiency) branch" << std::endl
            << std::endl;

  TTree *tree = new TTree("data", "data");
  tree->ReadFile(input);

  gStyle->SetPalette(1);
  gStyle->SetPadRightMargin(0.14);

  TCanvas *canvas = new TCanvas("csvoutput", "CSV Output", 1200, 900);

  tree->SetMarkerStyle(kFullDotMedium);
  tree->SetMarkerColor(kRed);
  if(par2.Length() > 0) {
    //tree->Draw(Form("%s:%s", par2.Data(), par1.Data()));
    if(par3.Length() > 0)
      tree->Draw(Form("%s:%s:%s:%s", par1.Data(), par2.Data(), par3.Data(), value.Data()), "", "COLZ"); //, "", "Z");
    else
      tree->Draw(Form("%s:%s:%s", par2.Data(), par1.Data(), value.Data()), "", "COLZ"); //, "", "Z");

    TH1 *histo = tree->GetHistogram();
    if(!histo)
      return;

    histo->SetTitle(Form("%s with different classifier parameters", value.Data()));
    histo->GetXaxis()->SetTitle(Form("Classifier parameter %s", par1.Data()));
    histo->GetYaxis()->SetTitle(Form("Classifier parameter %s", par2.Data()));
    if(par3.Length() > 0)
      histo->GetZaxis()->SetTitle(Form("Classifier parameter %s", par3.Data()));
    else
      histo->GetZaxis()->SetTitle("");

    if(par3.Length() == 0) {
      float x = 0;
      float y = 0;
      float val = 0;
      double maxVal = tree->GetMaximum(value);
      double minVal = tree->GetMinimum(value);

      tree->SetBranchAddress(par1, &x);
      tree->SetBranchAddress(par2, &y);
      tree->SetBranchAddress(value, &val);
      TLatex l;
      l.SetTextSize(0.03);
    
      Long64_t nentries = tree->GetEntries();
      for(Long64_t entry=0; entry < nentries; ++entry) {
        tree->GetEntry(entry);
    
        l.SetTextColor(textColor(val, maxVal, minVal));
        l.DrawLatex(x, y, Form("%.3f", val*100));
      }
    }
  }
  else {
    tree->Draw(Form("%s:%s", value.Data(), par1.Data()));
    TH1 *histo = tree->GetHistogram();
    if(!histo) 
      return;
    histo->SetTitle(Form("%s with different classifier parameters", value.Data()));
    histo->GetXaxis()->SetTitle(Form("Classifier parameter %s", par1.Data()));
    histo->GetYaxis()->SetTitle(value);
  }
}
コード例 #7
0
void ReadTree_normDet(){

  bool testrun          = 0;
  const int norder_     = 2;

  static const int ptBinMin  = 0;
  static const int ptBinMax  = nptbinsDefault-1;
  static const int etaBinMin = 0; //0;
  static const int etaBinMax = netabinsDefault-1;

  TFile * fAna;
  TTree * tree;
  double centval;
  double vtx;
  TH2D * sumw;
  TH2D * sumwqx;
  TH2D * sumwqy;
  TH2I * hMult;

  TFile * fVNDet;
  TH1D * hVNDetX_0;
  TH1D * hVNDetY_0;
  TH1D * hVNDetX_1;
  TH1D * hVNDetY_1;
  TH1D * hVNDetX_full;
  TH1D * hVNDetY_full;

  TFile * fHists;
  TDirectory * qwebye;
  TH2D * hVn2Dfull[NCENT];
  TH2D * hVn2Dsub0[NCENT];
  TH2D * hVn2Dsub1[NCENT];
  TH2D * hVn2D0v1[NCENT];
  TH1D * hVnFull[NCENT];
  TH1D * hVnSub0[NCENT];
  TH1D * hVnSub1[NCENT];
  TH1I * Mult[NCENT];
  TH2D * h2Vn2D0v1[NCENT];
  TH1D * h2Vn2D0v1Magnitude[NCENT];

  double VnRaw_x_0;
  double VnRaw_y_0;
  double VnRaw_x_1;
  double VnRaw_y_1;
  double VnRaw_x_full;
  double VnRaw_y_full;

  double sumw_0;
  double sumw_1;
  double sumw_full;

  double VnCorrected_x_0;
  double VnCorrected_y_0;
  double VnCorrected_x_1;
  double VnCorrected_y_1;
  double VnCorrected_x_full;
  double VnCorrected_y_full;

  int evtMult_0;
  int evtMult_1;
  int evtMult_full;

  //
  // MAIN
  //
  setTDRStyle();
  TH1D::SetDefaultSumw2();
  TH2D::SetDefaultSumw2();
  TH1I::SetDefaultSumw2();

  //-- Set up analyzer objects
  fAna = new TFile(fAnaTreeName);

  tree   = (TTree *) fAna->Get("ebyeana/tree");
  sumwqx = new TH2D(Form("sumwqx%i", norder_), Form("sumwqx%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumwqy = new TH2D(Form("sumwqy%i", norder_), Form("sumwqy%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumw   = new TH2D("sumw",                    "sumw",                    nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  hMult  = new TH2I("hMult",                   "hMult",                   nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);

  tree->SetBranchAddress("Cent",                    &centval);
  tree->SetBranchAddress("Vtx",                     &vtx);
  tree->SetBranchAddress("mult",                    &hMult);
  tree->SetBranchAddress(Form("sumwqx%i", norder_), &sumwqx);
  tree->SetBranchAddress(Form("sumwqy%i", norder_), &sumwqy);
  tree->SetBranchAddress("sumw",                    &sumw);

  //-- Set up VN detector objects 
  fVNDet = new TFile( Form("V%iDet.root", norder_ ) );
  hVNDetX_0    = (TH1D*) fVNDet->Get("SubEvt_0/hVNDetX_0");
  hVNDetY_0    = (TH1D*) fVNDet->Get("SubEvt_0/hVNDetY_0");
  hVNDetX_1    = (TH1D*) fVNDet->Get("SubEvt_1/hVNDetX_1");
  hVNDetY_1    = (TH1D*) fVNDet->Get("SubEvt_1/hVNDetY_1");
  hVNDetX_full = (TH1D*) fVNDet->Get("FullEvt/hVNDetX_full");
  hVNDetY_full = (TH1D*) fVNDet->Get("FullEvt/hVNDetY_full");

  //-- Setup the output objects
  fHists = new TFile("CastleEbyE.root","recreate");
  qwebye = (TDirectory*) fHists->mkdir("qwebye");

  for(int icent = 0; icent < NCENT; icent++){

    qwebye->cd();
    hVn2Dfull[icent]          = new TH2D(Form("hVn2Dfull_c%i", icent), Form("hVn2Dfull_c%i", icent), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
    hVn2Dfull[icent]->SetOption("colz");
    hVn2Dfull[icent]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs}", norder_) );
    hVn2Dfull[icent]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs}", norder_) );

    hVn2Dsub0[icent]          = new TH2D( Form("hVn2Dsub0_c%i", icent), Form("hVn2Dsub0_c%i", icent), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
    hVn2Dsub0[icent]->SetOption("colz");
    hVn2Dsub0[icent]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs,a}", norder_) );
    hVn2Dsub0[icent]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs,a}", norder_) );

    hVn2Dsub1[icent]          = new TH2D( Form("hVn2Dsub1_c%i", icent), Form("hVn2Dsub1_c%i", icent), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
    hVn2Dsub1[icent]->SetOption("colz");
    hVn2Dsub1[icent]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs,b}", norder_) );
    hVn2Dsub1[icent]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs,b}", norder_) );

    hVn2D0v1[icent]           = new TH2D( Form("hVn2D0v1_c%i", icent), Form("hVn2D0v1_c%i", icent), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
    hVn2D0v1[icent]->SetOption("colz");
    hVn2D0v1[icent]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs,a} - v_{%i,x}^{obs,b}", norder_, norder_) );
    hVn2D0v1[icent]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs,a} - v_{%i,y}^{obs,b}", norder_, norder_) );

    hVnFull[icent]            = new TH1D( Form("hVnFull_c%i", icent), Form("hVnFull_c%i", icent), NBins, 0., vnMax[norder_] );
    hVnFull[icent]->GetXaxis()->SetTitle( Form("v_{%i}", norder_) );
    hVnFull[icent]->GetYaxis()->SetTitle( "Events" );

    hVnSub0[icent]            = new TH1D( Form("hVnSub0_c%i", icent), Form("hVnSub0_c%i", icent), NBins, 0., vnMax[norder_] );
    hVnSub0[icent]->GetXaxis()->SetTitle( Form("v_{%i}^{obs,a}", norder_) );

    hVnSub1[icent]            = new TH1D( Form("hVnSub1_c%i", icent), Form("hVnSub1_c%i", icent), NBins, 0., vnMax[norder_] );
    hVnSub1[icent]->GetXaxis()->SetTitle( Form("v_{%i}^{obs,b}", norder_) );
    
    Mult[icent]               = new TH1I( Form("Mult_c%i", icent), Form("Mult_c%i", icent), 300, 1, 1500 );
    Mult[icent]->GetXaxis()->SetTitle("Multiplicity");
	
    h2Vn2D0v1[icent]          = new TH2D( Form("h2Vn2D0v1_c%i", icent), Form("h2Vn2D0v1_c%i", icent), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
    h2Vn2D0v1[icent]->GetXaxis()->SetTitle( Form("(v_{%i,x}^{obs,a} - v_{%i,x}^{obs,b})/2", norder_, norder_) );
    h2Vn2D0v1[icent]->GetYaxis()->SetTitle( Form("(v_{%i,y}^{obs,a} - v_{%i,y}^{obs,b})/2", norder_, norder_) );
    h2Vn2D0v1[icent]->SetOption("colz");

    h2Vn2D0v1Magnitude[icent] = new TH1D( Form("h2Vn2D0v1Magnitude_c%i", icent), Form("h2Vn2D0v1Magnitude_c%i", icent), NBins, 0., vnMax[norder_] );
    h2Vn2D0v1Magnitude[icent]->GetXaxis()->SetTitle( Form("|(v_{%i,x}^{obs,a} - v_{%i,x}^{obs,b})/2|", norder_, norder_) );

  }
    
  //
  // Tree Loop
  //
    
  cout<<"Begin FINAL loop, contains "<<tree->GetEntries()<<" Events"<<endl;
    
  int N;
  if( testrun ) N = 10000;
  else          N = tree->GetEntries();

  for(int ievent = 0; ievent < N; ievent++) {
        
    if((ievent+1)% 500000 == 0) cout<<"Processing Event "<<ievent+1<<"\t"<<100.*(ievent+1)/(double)N<<"% Completed"<<endl;
      
    tree->GetEntry(ievent);

    //-- Vertex Cut
    if(TMath::Abs(vtx) > 3.0) continue;

    //-- Calculate centbin
    if( centval > cent_max[NCENT-1]) continue;
    int icent = hCentBins.FindBin(centval)-1;

    //-- Reset raw and sumw values
    VnRaw_x_0    = 0;
    VnRaw_y_0    = 0;
    VnRaw_x_1    = 0;
    VnRaw_y_1    = 0;
    VnRaw_x_full = 0;
    VnRaw_y_full = 0;                

    sumw_0       = 0;
    sumw_1       = 0;
    sumw_full    = 0;

    evtMult_0    = 0;
    evtMult_1    = 0;
    evtMult_full = 0;

    //-- Begin analyzer histogram loops
    for(int ipt = ptBinMin; ipt <= ptBinMax; ipt++){
      for(int ieta = etaBinMin; ieta <= etaBinMax; ieta++){

	if(sumw->GetBinContent(ipt+1,ieta+1) !=0){

	  //-- Subevent 0 (eta >= 0)
	  if(etabinsDefault[ieta] >= 0){
	    VnRaw_x_0     += sumwqx->GetBinContent(ipt+1,ieta+1);
	    VnRaw_y_0     += sumwqy->GetBinContent(ipt+1,ieta+1);
	    sumw_0        += sumw->GetBinContent(ipt+1,ieta+1);
	    evtMult_0     += hMult->GetBinContent(ipt+1,ieta+1);
	  }
	  //-- Subevent 1 (eta < 0)
	  else{
	    VnRaw_x_1     += sumwqx->GetBinContent(ipt+1,ieta+1);
	    VnRaw_y_1     += sumwqy->GetBinContent(ipt+1,ieta+1);
	    sumw_1        += sumw->GetBinContent(ipt+1,ieta+1);
	    evtMult_1     += hMult->GetBinContent(ipt+1,ieta+1);
	  }
	  //-- Full Event
	  VnRaw_x_full    += sumwqx->GetBinContent(ipt+1,ieta+1);
	  VnRaw_y_full    += sumwqy->GetBinContent(ipt+1,ieta+1);
	  sumw_full       += sumw->GetBinContent(ipt+1,ieta+1);
	  evtMult_full    += hMult->GetBinContent(ipt+1,ieta+1);

	}

      } //-- End eta loop
    } //-- End pt loop

    //-- Fill Histograms, only use events that have at least two tracks in each SE
    if(sumw_0 == 0 || sumw_1 == 0 || evtMult_1 < 2 || evtMult_full < 2) continue;

    VnRaw_x_full /= sumw_full;
    VnRaw_y_full /= sumw_full;
    
    VnRaw_x_0 /= sumw_0;
    VnRaw_y_0 /= sumw_0;
	
    VnRaw_x_1 /= sumw_1;
    VnRaw_y_1 /= sumw_1;
                
    //-- Full Tracker
    VnCorrected_x_full = VnRaw_x_full - hVNDetX_full->GetBinContent(icent+1);
    VnCorrected_y_full = VnRaw_y_full - hVNDetY_full->GetBinContent(icent+1);
    double vn_full     = TMath::Sqrt( VnCorrected_x_full * VnCorrected_x_full +  VnCorrected_y_full * VnCorrected_y_full);

    hVnFull[icent]   -> Fill( vn_full );
    hVn2Dfull[icent] -> Fill(VnCorrected_x_full, VnCorrected_y_full);

    Mult[icent]->Fill(evtMult_full);

    //-- SubEvt 0 (Eta > 0)
    VnCorrected_x_0 = VnRaw_x_0 - hVNDetX_0->GetBinContent(icent+1);
    VnCorrected_y_0 = VnRaw_y_0 - hVNDetY_0->GetBinContent(icent+1);
    double vn_0     = TMath::Sqrt( VnCorrected_x_0 * VnCorrected_x_0 + VnCorrected_y_0 * VnCorrected_y_0 );

    hVnSub0[icent]   -> Fill( vn_0 );
    hVn2Dsub0[icent] -> Fill(VnCorrected_x_0, VnCorrected_y_0);
                
    //-- SubEvt 1 (Eta < 0)
    VnCorrected_x_1 = VnRaw_x_1 - hVNDetX_1->GetBinContent(icent+1);
    VnCorrected_y_1 = VnRaw_y_1 - hVNDetY_1->GetBinContent(icent+1);
    double vn_1     = TMath::Sqrt( VnCorrected_x_1 * VnCorrected_x_1 + VnCorrected_y_1 *VnCorrected_y_1 );

    hVnSub1[icent]   -> Fill( vn_1 );
    hVn2Dsub1[icent] -> Fill(VnCorrected_x_1, VnCorrected_y_1);

    //-- SubEvt Difference
    double vn0m1_x = VnCorrected_x_0 - VnCorrected_x_1;
    double vn0m1_y = VnCorrected_y_0 - VnCorrected_y_1;
    hVn2D0v1[icent]->Fill(vn0m1_x, vn0m1_y);	

    //-- SubEvt Difference for DD response
    double vn0m1_x2 = (VnCorrected_x_0 - VnCorrected_x_1) / 2.;
    double vn0m1_y2 = (VnCorrected_y_0 - VnCorrected_y_1) / 2.;
    h2Vn2D0v1[icent]->Fill(vn0m1_x2, vn0m1_y2);

    double vn0m12 = TMath::Sqrt( pow(vn0m1_x2, 2) + pow(vn0m1_y2, 2) );
    h2Vn2D0v1Magnitude[icent]->Fill(vn0m12);

  } //-- End Event loop

  cout<<"End FINAL loop!"<<endl;
        
  fHists->Write();
  cout<<"File written, process completed"<<endl;
   
}
コード例 #8
0
void gastof_simple()
{
  const unsigned int run_id = 725;
  TFile* f = new TFile(Form("../../gastof_inner_run%d.root", run_id)); //FIXME
  TTree* t = (TTree*)f->Get("tdc");

  const unsigned int channels_to_probe = 32; //64;
  const double tot_min = 70., tot_max = -1.;
  const double lead_min = 6.8, lead_max = 6.95; // in \mus

  int num_hits;
  unsigned int ettt;
  double leading_edge[5000], tot[5000];
  int channel_id[5000];
  t->SetBranchStatus("*", 0);
  t->SetBranchStatus("num_measurements", 1); t->SetBranchAddress("num_measurements", &num_hits);
  t->SetBranchStatus("leading_edge", 1); t->SetBranchAddress("leading_edge", leading_edge);
  t->SetBranchStatus("channel_id", 1); t->SetBranchAddress("channel_id", channel_id);
  t->SetBranchStatus("tot", 1); t->SetBranchAddress("tot", tot);

  const unsigned int num_triggers = t->GetEntries();

  TH1D* h_tot_all_channels = new TH1D("h_tot_all_channels", "", 250, 0., 1000.);
  TH1D* h_lead_all_channels = new TH1D("h_lead_all_channels", "", 500, 0., 10.);

  double last_ettt = -1.;
  unsigned int num_overfl = 0;
  unsigned int mult[channels_to_probe];
  for (unsigned int i=0; i<num_triggers; i++) {
    t->GetEntry(i);
    for (unsigned int j=0; j<channels_to_probe; j++) {
//       lead[j].clear();    //lead[] not defined in gastof_simple
      mult[j] = 0;
    }
    if (i%10000==0) cerr << "Processing event " << i << " / " << num_triggers << endl;

    for (int j=0; j<num_hits; j++) {
      h_lead_all_channels->Fill(leading_edge[j]/1.e3, 1./num_triggers);
      if (leading_edge[j]<lead_min*1.e3 or leading_edge[j]>lead_max*1.e3) continue;
      h_tot_all_channels->Fill(tot[j]);
    }
  }

  GastofCanvas c_tot_all_chan("tot_all-channels", Form("Run %d, all channels", run_id));
  h_tot_all_channels->Draw();
  h_tot_all_channels->GetXaxis()->SetTitle("Time over threshold (ns)");
  h_tot_all_channels->GetYaxis()->SetTitle("Hits");

  {
    TPaveText* cuts = new TPaveText(0.4, 0.8, 0.5, 0.85, "ndc");
    cuts->SetTextAlign(13);
    cuts->SetTextFont(43);
    cuts->SetTextSize(18);
    cuts->SetFillColor(kWhite);
    cuts->SetLineColor(kWhite);
    //cuts->AddText(Form("ToT > %.1f ns", tot_min));
    cuts->AddText(Form("Lead. edge #in [%.1f-%.2f]  #mus", lead_min, lead_max));
    cuts->Draw("same");
  }

  c_tot_all_chan.Pad()->SetLogy();
  {
    TLine* line = new TLine(tot_min, 0., tot_min, h_tot_all_channels->GetMaximum()*0.8); //constructor for line: TLine( x1, y1, x2, y2)
    line->SetLineColor(kBlack);
    line->SetLineStyle(2);
    line->SetLineWidth(2);
    line->Draw("same");
  }
//   if (tot_max>0.) {  //<- condition never met in gastof_simple
//     TLine* line = new TLine(tot_max, 0., tot_max, h_tot_all_channels->GetMaximum()*0.8);
//     line->SetLineColor(kBlack);
//     line->SetLineStyle(2);
//     line->SetLineWidth(2);
//     line->Draw("same");
  }
コード例 #9
0
void TMVARegressionApplication( TString myMethodList = "" ) 
{
   //---------------------------------------------------------------
   // This loads the library
   TMVA::Tools::Instance();

   // Default MVA methods to be trained + tested
   std::map<std::string,int> Use;

   // --- Mutidimensional likelihood and Nearest-Neighbour methods
   Use["PDERS"]           = 0;
   Use["PDEFoam"]         = 1; 
   Use["KNN"]             = 1;
   // 
   // --- Linear Discriminant Analysis
   Use["LD"]		        = 1;
   // 
   // --- Function Discriminant analysis
   Use["FDA_GA"]          = 1;
   Use["FDA_MC"]          = 0;
   Use["FDA_MT"]          = 0;
   Use["FDA_GAMT"]        = 0;
   // 
   // --- Neural Network
   Use["MLP"]             = 1; 
   // 
   // --- Support Vector Machine 
   Use["SVM"]             = 0;
   // 
   // --- Boosted Decision Trees
   Use["BDT"]             = 0;
   Use["BDTG"]            = 1;
   // ---------------------------------------------------------------

   std::cout << std::endl;
   std::cout << "==> Start TMVARegressionApplication" << std::endl;

   // Select methods (don't look at this code - not of interest)
   if (myMethodList != "") {
      for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;

      std::vector<TString> mlist = gTools().SplitString( myMethodList, ',' );
      for (UInt_t i=0; i<mlist.size(); i++) {
         std::string regMethod(mlist[i]);

         if (Use.find(regMethod) == Use.end()) {
            std::cout << "Method \"" << regMethod << "\" not known in TMVA under this name. Choose among the following:" << std::endl;
            for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) std::cout << it->first << " ";
            std::cout << std::endl;
            return;
         }
         Use[regMethod] = 1;
      }
   }

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

   // --- Create the Reader object

   TMVA::Reader *reader = new TMVA::Reader( "!Color:!Silent" );    

   // Create a set of variables and declare them to the reader
   // - the variable names MUST corresponds in name and type to those given in the weight file(s) used
   Float_t var1, var2;
   reader->AddVariable( "var1", &var1 );
   reader->AddVariable( "var2", &var2 );

   // Spectator variables declared in the training have to be added to the reader, too
   Float_t spec1,spec2;
   reader->AddSpectator( "spec1:=var1*2",  &spec1 );
   reader->AddSpectator( "spec2:=var1*3",  &spec2 );

   // --- Book the MVA methods

   TString dir    = "weights/";
   TString prefix = "TMVARegression";

   // Book method(s)
   for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
      if (it->second) {
         TString methodName = it->first + " method";
         TString weightfile = dir + prefix + "_" + TString(it->first) + ".weights.xml";
         reader->BookMVA( methodName, weightfile ); 
      }
   }
   
   // Book output histograms
   TH1* hists[100];
   Int_t nhists = -1;
   for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
      TH1* h = new TH1F( it->first.c_str(), TString(it->first) + " method", 100, -100, 600 );
      if (it->second) hists[++nhists] = h;
   }
   nhists++;
   
   // 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);
   TString fname = "./tmva_reg_example.root";
   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_reg_example.root" ); // if not: download from ROOT server
   }
   
   if (!input) {
      std::cout << "ERROR: could not open data file" << std::endl;
      exit(1);
   }
   std::cout << "--- TMVARegressionApp        : Using input file: " << input->GetName() << std::endl;

   // --- Event loop

   // Prepare the tree
   // - here the variable names have to corresponds 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
   //
   TTree* theTree = (TTree*)input->Get("TreeR");
   std::cout << "--- Select signal sample" << std::endl;
   theTree->SetBranchAddress( "var1", &var1 );
   theTree->SetBranchAddress( "var2", &var2 );

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

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

      theTree->GetEntry(ievt);

      // Retrieve the MVA target values (regression outputs) and fill into histograms
      // NOTE: EvaluateRegression(..) returns a vector for multi-target regression

      for (Int_t ih=0; ih<nhists; ih++) {
         TString title = hists[ih]->GetTitle();
         Float_t val = (reader->EvaluateRegression( title ))[0];
         hists[ih]->Fill( val );    
      }
   }
   sw.Stop();
   std::cout << "--- End of event loop: "; sw.Print();

   // --- Write histograms

   TFile *target  = new TFile( "TMVARegApp.root","RECREATE" );
   for (Int_t ih=0; ih<nhists; ih++) hists[ih]->Write();
   target->Close();

   std::cout << "--- Created root file: \"" << target->GetName() 
             << "\" containing the MVA output histograms" << std::endl;
  
   delete reader;
    
   std::cout << "==> TMVARegressionApplication is done!" << std::endl << std::endl;
}
コード例 #10
0
ファイル: example.C プロジェクト: bvormwald/HHKinFit
int main(int argc, char* argv[])
{
  TFile* f = new TFile("example/ntuple.root","READ");
  TTree* t = (TTree*) f->Get("EleTauKinFit");
  
  TH1F* h_mH    = new TH1F("h_mH",   "distribution of mH_{fit};mH_{fit} [GeV];entries/5GeV", 40,200,400);
  TH1F* h_chi2  = new TH1F("h_chi2", "distribution of #chi^{2}_{fit};#chi^{2}_{fit};entries/1", 100,0,25);
  TH1F* h_prob  = new TH1F("h_prob", "distribution of fit probability;P_{fit};entries/0.05", 100,0,1);
  TH1F* h_pull1 = new TH1F("h_pull1","pull distribution E_{b1};pull;entries/0.25", 20,-5,5);
  TH1F* h_pull2 = new TH1F("h_pull2","pull distribution E_{b2};pull;entries/0.25", 20,-5,5);
  TH1F* h_pullB = new TH1F("h_pullB","pull distribution balance;pull;entries/0.25", 20,-5,5);
  
  Int_t max_nevent = t->GetEntriesFast();

  //Leaf types  
   Int_t           njets;
   Double_t        b1_dR;
   Double_t        b1_csv;
   Double_t        b1_px;
   Double_t        b1_py;
   Double_t        b1_pz;
   Double_t        b1_E;
   Double_t        b2_dR;
   Double_t        b2_csv;
   Double_t        b2_px;
   Double_t        b2_py;
   Double_t        b2_pz;
   Double_t        b2_E;
   Double_t        tauvis1_dR;
   Double_t        tauvis1_px;
   Double_t        tauvis1_py;
   Double_t        tauvis1_pz;
   Double_t        tauvis1_E;
   Double_t        tauvis2_dR;
   Double_t        tauvis2_px;
   Double_t        tauvis2_py;
   Double_t        tauvis2_pz;
   Double_t        tauvis2_E;
   Double_t        met_pt;
   Double_t        met_px;
   Double_t        met_py;
   Double_t        met_cov00;
   Double_t        met_cov10;
   Double_t        met_cov01;
   Double_t        met_cov11;


  // List of branches
   TBranch        *b_njets;
   TBranch        *b_b1_dR;
   TBranch        *b_b1_csv;
   TBranch        *b_b1_px;
   TBranch        *b_b1_py;
   TBranch        *b_b1_pz;
   TBranch        *b_b1_E;
   TBranch        *b_b2_dR;
   TBranch        *b_b2_csv;
   TBranch        *b_b2_px;
   TBranch        *b_b2_py;
   TBranch        *b_b2_pz;
   TBranch        *b_b2_E;
   TBranch        *b_tauvis1_dR;
   TBranch        *b_tauvis1_px;
   TBranch        *b_tauvis1_py;
   TBranch        *b_tauvis1_pz;
   TBranch        *b_tauvis1_E;
   TBranch        *b_tauvis2_dR;
   TBranch        *b_tauvis2_px;
   TBranch        *b_tauvis2_py;
   TBranch        *b_tauvis2_pz;
   TBranch        *b_tauvis2_E;
   TBranch        *b_met_pt;
   TBranch        *b_met_px;
   TBranch        *b_met_py;
   TBranch        *b_met_cov00;
   TBranch        *b_met_cov10;
   TBranch        *b_met_cov01;
   TBranch        *b_met_cov11;
     
   t->SetBranchAddress("Njets", &njets, &b_njets);
   t->SetBranchAddress("b1_dR", &b1_dR, &b_b1_dR);
   t->SetBranchAddress("b1_csv", &b1_csv, &b_b1_csv);
   t->SetBranchAddress("b1_px", &b1_px, &b_b1_px);
   t->SetBranchAddress("b1_py", &b1_py, &b_b1_py);
   t->SetBranchAddress("b1_pz", &b1_pz, &b_b1_pz);
   t->SetBranchAddress("b1_E", &b1_E, &b_b1_E);
   t->SetBranchAddress("b2_dR", &b2_dR, &b_b2_dR);
   t->SetBranchAddress("b2_csv", &b2_csv, &b_b2_csv);
   t->SetBranchAddress("b2_px", &b2_px, &b_b2_px);
   t->SetBranchAddress("b2_py", &b2_py, &b_b2_py);
   t->SetBranchAddress("b2_pz", &b2_pz, &b_b2_pz);
   t->SetBranchAddress("b2_E", &b2_E, &b_b2_E);
   t->SetBranchAddress("tauvis1_dR", &tauvis1_dR, &b_tauvis1_dR);
   t->SetBranchAddress("tauvis1_px", &tauvis1_px, &b_tauvis1_px);
   t->SetBranchAddress("tauvis1_py", &tauvis1_py, &b_tauvis1_py);
   t->SetBranchAddress("tauvis1_pz", &tauvis1_pz, &b_tauvis1_pz);
   t->SetBranchAddress("tauvis1_E", &tauvis1_E, &b_tauvis1_E);
   t->SetBranchAddress("tauvis2_dR", &tauvis2_dR, &b_tauvis2_dR);
   t->SetBranchAddress("tauvis2_px", &tauvis2_px, &b_tauvis2_px);
   t->SetBranchAddress("tauvis2_py", &tauvis2_py, &b_tauvis2_py);
   t->SetBranchAddress("tauvis2_pz", &tauvis2_pz, &b_tauvis2_pz);
   t->SetBranchAddress("tauvis2_E", &tauvis2_E, &b_tauvis2_E);
   t->SetBranchAddress("met_pt", &met_pt, &b_met_pt);
   t->SetBranchAddress("met_px", &met_px, &b_met_px);
   t->SetBranchAddress("met_py", &met_py, &b_met_py);
   t->SetBranchAddress("met_cov00", &met_cov00, &b_met_cov00);
   t->SetBranchAddress("met_cov10", &met_cov10, &b_met_cov10);
   t->SetBranchAddress("met_cov01", &met_cov01, &b_met_cov01);
   t->SetBranchAddress("met_cov11", &met_cov11, &b_met_cov11);

  //define the testd hypotheses
  std::vector<Int_t> hypo_mh1;
  hypo_mh1.push_back(125);
  std::vector<Int_t> hypo_mh2;
  hypo_mh2.push_back(125);
  
  // event loop
  for (int i = 0; i < max_nevent; i++) {
    t->GetEntry(i);
    
    //use only btaged jets and check for correct gen match
    if (b1_csv<0.681 || b2_csv<0.681 || njets < 2 || b1_dR > 0.2 || b2_dR > 0.2 || tauvis1_dR > 0.1 || tauvis2_dR > 0.1)   continue;
    
    //define input vectors
    TLorentzVector b1      = TLorentzVector(b1_px,b1_py,b1_pz,b1_E);
    TLorentzVector b2      = TLorentzVector(b2_px,b2_py,b2_pz,b2_E);
    TLorentzVector tau1vis = TLorentzVector(tauvis1_px,tauvis1_py,tauvis1_pz,tauvis1_E);
    TLorentzVector tau2vis = TLorentzVector(tauvis2_px,tauvis2_py,tauvis2_pz,tauvis2_E);
    
    TLorentzVector ptmiss  = TLorentzVector(met_px,met_py,0,met_pt);
    TMatrixD metcov(2,2);
    metcov(0,0)=met_cov00;
    metcov(1,0)=met_cov10;
    metcov(0,1)=met_cov01;    
    metcov(1,1)=met_cov11;
    
    //intance of fitter master class
    HHKinFitMaster kinFits = HHKinFitMaster(&b1,&b2,&tau1vis,&tau2vis);
    kinFits.setAdvancedBalance(&ptmiss,metcov);
    //kinFits.setSimpleBalance(ptmiss.Pt(),10); //alternative which uses only the absolute value of ptmiss in the fit
    kinFits.addMh1Hypothesis(hypo_mh1);
    kinFits.addMh2Hypothesis(hypo_mh2);
    kinFits.doFullFit();

    //obtain results from different hypotheses
    Double_t chi2_best = kinFits.getBestChi2FullFit();
    Double_t mh_best = kinFits.getBestMHFullFit();
    std::pair<Int_t, Int_t> bestHypo = kinFits.getBestHypoFullFit();
    std::map< std::pair<Int_t, Int_t>, Double_t> fit_results_chi2 = kinFits.getChi2FullFit();
    std::map< std::pair<Int_t, Int_t>, Double_t> fit_results_fitprob = kinFits.getFitProbFullFit();
    std::map< std::pair<Int_t, Int_t>, Double_t> fit_results_mH = kinFits.getMHFullFit();
    std::map< std::pair<Int_t, Int_t>, Double_t> fit_results_pull_b1 = kinFits.getPullB1FullFit();
    std::map< std::pair<Int_t, Int_t>, Double_t> fit_results_pull_b2 = kinFits.getPullB2FullFit();
    std::map< std::pair<Int_t, Int_t>, Double_t> fit_results_pull_balance = kinFits.getPullBalanceFullFit();
    std::map< std::pair<Int_t, Int_t>, Int_t> fit_convergence = kinFits.getConvergenceFullFit();

    std::cout << "#############################" << std::endl;
    std::cout << "EVENT" << i << std::endl;
    std::cout << "#############################" << std::endl;
    std::cout << "=====================================" << std::endl;
    std::cout << "event:           " << i << std::endl;
    std::cout << "best chi2:       " << chi2_best << std::endl;
    std::cout << "best hypothesis: " << bestHypo.first << " " << bestHypo.second << std::endl;
    std::cout << "best mH=         " << mh_best << std::endl;
    std::cout << "*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*" << std::endl;

   //individual loop over results
    for (std::vector<Int_t>::iterator mh2 = hypo_mh2.begin(); mh2 != hypo_mh2.end(); mh2++){
      for (std::vector<Int_t>::iterator mh1 = hypo_mh1.begin(); mh1 != hypo_mh1.end(); mh1++){
        std::pair< Int_t, Int_t > hypo(*mh1,*mh2);
        
        //sanity cuts: use only converged fits and events with chi2<25 and make sure used cov was positive definit (this needs to be fixed!)
        if (fit_convergence.at(hypo)>0 && fit_results_chi2.at(hypo)<25 && fit_results_pull_balance.at(hypo)>0){
        
          std::cout << *mh1 << " " << *mh2 << " " << "chi2_fit:    " << fit_results_chi2.at(hypo) << std::endl;
          std::cout << *mh1 << " " << *mh2 << " " << "prob_fit:    " << fit_results_fitprob.at(hypo) << std::endl;
          std::cout << *mh1 << " " << *mh2 << " " << "mH_fit=      " << fit_results_mH.at(hypo) << std::endl;
          std::cout << "*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*" << std::endl;

          h_mH->Fill(fit_results_mH.at(hypo));
          h_chi2->Fill(fit_results_chi2.at(hypo));
          h_prob->Fill(fit_results_fitprob.at(hypo));
          h_pull1->Fill(fit_results_pull_b1.at(hypo));
          h_pull2->Fill(fit_results_pull_b2.at(hypo));
          h_pullB->Fill(fit_results_pull_balance.at(hypo));
        }
      }
    }    
  }

  TFile fout("result.root","RECREATE");
  h_mH->Write();
  h_chi2->Write();
  h_prob->Write();
  h_pull1->Write();
  h_pull2->Write();
  h_pullB->Write();
  
  return (0);
}
コード例 #11
0
void cut_eff2()
{
	//      TString inputpath = "/afs/cern.ch/work/m/mwang/public/EDBR/trees/productionv1_1130/fullrange/";
	TString inputpath = "/afs/cern.ch/work/m/mwang/public/EDBR/trees/productionv1_1206/fullrange/";
	TString cut = "btag_eff";
	vector<TString> dataSamples;
	vector<TString> bkgSamples;
	vector<TString> sigSamples;
	/*
	   dataSamples.push_back("data_xwh");

	   bkgSamples.push_back("TTBARpowheg_xwh");
	   bkgSamples.push_back("VV_xwh");
	   bkgSamples.push_back("WJetsPt180_xwh");
	   bkgSamples.push_back("DYJets_xwh");
	   bkgSamples.push_back("SingleTop_xwh");

	   sigSamples.push_back("MWp_1000_gg_xwh");
	   sigSamples.push_back("MWp_1500_gg_xwh");
	   sigSamples.push_back("MWp_2000_gg_xwh");
	   sigSamples.push_back("MWp_1000_cc_xwh");
	   sigSamples.push_back("MWp_1500_cc_xwh");
	   sigSamples.push_back("MWp_2000_cc_xwh");
	   sigSamples.push_back("MWp_1000_bb_xwh");
	   sigSamples.push_back("MWp_1500_bb_xwh");
	   sigSamples.push_back("MWp_2000_bb_xwh");

	   sigSamples.push_back("MWp_1000_xwh");
	   sigSamples.push_back("MWp_1500_xwh");
	   sigSamples.push_back("MWp_2000_xwh");
	 */
	dataSamples.push_back("");
	bkgSamples.push_back("TTBARmadgraph_xwh");
	bkgSamples.push_back("WJetsPt180_xwh");
	sigSamples.push_back("MWp_1000_gg_xwh");
	sigSamples.push_back("MWp_1000_cc_xwh");
	sigSamples.push_back("MWp_1000_bb_xwh");
	sigSamples.push_back("MWp_1000_xwh");
	sigSamples.push_back("MWp_1500_gg_xwh");
	sigSamples.push_back("MWp_1500_cc_xwh");
	sigSamples.push_back("MWp_1500_bb_xwh");
	sigSamples.push_back("MWp_1500_xwh");
	sigSamples.push_back("MWp_2000_gg_xwh");
	sigSamples.push_back("MWp_2000_cc_xwh");
	sigSamples.push_back("MWp_2000_bb_xwh");
	sigSamples.push_back("MWp_2000_xwh");


	int ndata = 0;//dataSamples.size();
	int nbkg  = bkgSamples.size();
	int nsig  = sigSamples.size();

	cout<<"data samples "<<ndata<<"  bkg samples "<<nbkg<<"  signal samples "<<nsig<<endl;

	//TH1F * h1 = new TH1F (cut,cut,ndata+nbkg+nsig+1,0,ndata+nbkg+nsig+1);
	TH1F * h1 = new TH1F (cut,cut,14 ,0,14);// number of samples
	//h1->GetYaxis()->SetRangeUser(0,1);
	h1->SetBit(TH1::kCanRebin);
	h1->SetStats(0);
	gStyle->SetPaintTextFormat("1.4f");
	//h1->Sumw2();
	TH1F *h2 = (TH1F*)h1->Clone(cut+"_2");
	TH1F *h3 = (TH1F*)h1->Clone(cut+"_3");
	TH1F *h4 = (TH1F*)h1->Clone(cut+"_4");
	TH1F *h5 = (TH1F*)h1->Clone(cut+"_5");
	TH1F *h6 = (TH1F*)h1->Clone(cut+"_6");
	TH1F *h7 = (TH1F*)h1->Clone(cut+"_7");
	TH1F *h8 = (TH1F*)h1->Clone(cut+"_8");
	TH1F *h9 = (TH1F*)h1->Clone(cut+"_9");
	TH1F *h10 = (TH1F*)h1->Clone(cut+"_10");
	TH1F *h11 = (TH1F*)h1->Clone(cut+"_11");
	TH1F *h12 = (TH1F*)h1->Clone(cut+"_12");
	TH1F *h13 = (TH1F*)h1->Clone(cut+"_13");
	TH1F *h14 = (TH1F*)h1->Clone(cut+"_14");
	TH1F *h15 = (TH1F*)h1->Clone(cut+"_15");
	TH1F *h16 = (TH1F*)h1->Clone(cut+"_16");
	TH1F *h17 = (TH1F*)h1->Clone(cut+"_17");
	TH1F *h18 = (TH1F*)h1->Clone(cut+"_18");

	TCanvas * c1 = new TCanvas();

	for(int i =0; i<ndata+nbkg+nsig; i++   )
	{
		TString filename;
		TString samplename;
		if(i<ndata)
		{
			filename = "treeEDBR_"+dataSamples.at(i)+".root";
			samplename = dataSamples.at(i);//data_xwh  
			samplename.Remove(samplename.Length()-4,4);//data  
			//samplename.Remove(0,12);//2012A_13Jul2012
		}
		else if(i>=ndata&&i<(ndata+nbkg))
		{
			filename = "treeEDBR_"+bkgSamples.at(i-ndata)+".root";
			samplename = bkgSamples.at(i-ndata);//TTBAR_xwh
			samplename.Remove(samplename.Length()-4,4);//TTBAR
		}
		else if(i>=(ndata+nbkg))
		{
			filename = "treeEDBR_"+sigSamples.at(i-ndata-nbkg)+".root";
			samplename = sigSamples.at(i-ndata-nbkg);//MWp_1000_gg_xwh   //RSG_WW_lvjj_c0p2_M1500_xww,BulkG_WW_lvjj_c1p0_M1500_xww
			samplename.Remove(samplename.Length()-4,4);//MWp_1000_gg     // RSG_WW_lvjj_c0p2_M1500,BulkG_WW_lvjj_c1p0_M1500
			if(samplename.Contains("RSG"))samplename.Remove(4,8);//RSG_c0p2_M1500
			if(samplename.Contains("BulkG"))samplename.Remove(6,8);//BulkG_c1p0_M1500
		}
		cout<<filename<<endl;
		cout<<samplename<<endl;


		TFile *fp = new TFile(inputpath+"/"+filename);
		TTree * tree = (TTree *) fp->Get("SelectedCandidates");
		int entries = tree->GetEntries();
		cout<<"entries: "<<entries<<endl;

		double pass1=0;
		double pass2=0;
		double pass3=0;
		double pass4=0;
		double pass5=0;
		double pass6=0;
		double pass7=0;
		double pass8=0;
		double pass9=0;
		double pass10=0;
		double pass11=0;
		double pass12=0;
		double pass13=0;
		double pass14=0;
		double pass15=0;
                double pass16=0;
                double pass17=0;
                double pass18=0;
                double total=0;
		int nLooseEle;
		int nLooseMu;
		float nsubjetbtagL[99];
		float nsubjetbtagM[99];
		float nsubjetbtagT[99];
		float nfatjetbtagL[99];
		float nfatjetbtagM[99];
		float nfatjetbtagT[99];

		//to make cuts
		double met;
		double ptlep1[99];
		double ptZll[99];
		double ptZjj[99];
		double lep[99];
		int    nCands;
		int    nXjets[99];
		double region[99];

		// event weight
		double weight=-1;

		tree->SetBranchAddress("nLooseMu", &nLooseMu);
		tree->SetBranchAddress("nLooseEle",&nLooseEle);
		tree->SetBranchAddress("nsubjetbtagL",nsubjetbtagL);
		tree->SetBranchAddress("nsubjetbtagM",nsubjetbtagM);
		tree->SetBranchAddress("nsubjetbtagT",nsubjetbtagT);
		tree->SetBranchAddress("nfatjetbtagL",nfatjetbtagL); 
		tree->SetBranchAddress("nfatjetbtagM",nfatjetbtagM); 
		tree->SetBranchAddress("nfatjetbtagT",nfatjetbtagT);

		tree->SetBranchAddress("ptlep1", ptlep1);
		tree->SetBranchAddress("ptZll", ptZll);
		tree->SetBranchAddress("ptZjj", ptZjj);
		tree->SetBranchAddress("met", &met);
		tree->SetBranchAddress("nXjets", nXjets);
		tree->SetBranchAddress("lep", lep);
		tree->SetBranchAddress("nCands", &nCands);
		tree->SetBranchAddress("region", &region);

		tree->SetBranchAddress("weight", &weight);

		bool filled = 0;

		for(int j=0;j<entries;j++)
		{
			tree->GetEntry(j);

			//per event weight
			double actualWeight = weight*19538.85;
			if(i<ndata) actualWeight =1; //for data
			//cout<<actualWeight<<endl;

			filled = 0;
			//if(nCands==0)continue;
			for(int ivec=0;ivec<nCands;ivec++){

				if(filled==0)
				{
					//cout<<nXjets[ivec]<<endl;
					//make cuts
					if((nLooseEle+nLooseMu)!=1)continue;
					//if(met<80)continue;
					if(lep[ivec]!=1.)continue;//mu
					if(nXjets[ivec]!=1)continue;
					if(region[ivec]!=1)continue;
					total = total + actualWeight;

					if(nsubjetbtagL[ivec]>=1&&nfatjetbtagL[ivec]>=1)pass1=pass1+actualWeight;
					if(nsubjetbtagM[ivec]>=1&&nfatjetbtagL[ivec]>=1)pass2=pass2+actualWeight;
					if(nsubjetbtagT[ivec]>=1&&nfatjetbtagL[ivec]>=1)pass3=pass3+actualWeight;
					if(nsubjetbtagL[ivec]>=2&&nfatjetbtagL[ivec]>=1)pass4=pass4+actualWeight;
					if(nsubjetbtagM[ivec]>=2&&nfatjetbtagL[ivec]>=1)pass5=pass5+actualWeight;
					if(nsubjetbtagT[ivec]>=2&&nfatjetbtagL[ivec]>=1)pass6=pass6+actualWeight;
					if(nsubjetbtagL[ivec]>=1&&nfatjetbtagM[ivec]>=1)pass7=pass7+actualWeight;
					if(nsubjetbtagM[ivec]>=1&&nfatjetbtagM[ivec]>=1)pass8=pass8+actualWeight;
					if(nsubjetbtagT[ivec]>=1&&nfatjetbtagM[ivec]>=1)pass9=pass9+actualWeight;
					if(nsubjetbtagL[ivec]>=2&&nfatjetbtagM[ivec]>=1)pass10=pass10+actualWeight;
					if(nsubjetbtagM[ivec]>=2&&nfatjetbtagM[ivec]>=1)pass11=pass11+actualWeight;
					if(nsubjetbtagT[ivec]>=2&&nfatjetbtagM[ivec]>=1)pass12=pass12+actualWeight;
					if(nsubjetbtagL[ivec]>=1&&nfatjetbtagT[ivec]>=1)pass13=pass13+actualWeight;
					if(nsubjetbtagM[ivec]>=1&&nfatjetbtagT[ivec]>=1)pass14=pass14+actualWeight;
					if(nsubjetbtagT[ivec]>=1&&nfatjetbtagT[ivec]>=1)pass15=pass15+actualWeight;
                                        if(nsubjetbtagL[ivec]>=2&&nfatjetbtagT[ivec]>=1)pass16=pass16+actualWeight;
                                        if(nsubjetbtagM[ivec]>=2&&nfatjetbtagT[ivec]>=1)pass17=pass17+actualWeight;
                                        if(nsubjetbtagT[ivec]>=2&&nfatjetbtagT[ivec]>=1)pass18=pass18+actualWeight;

					filled =1;
				}
			}//end of candidates loop

		}//end of tree loop

		double eff1=0;
		double eff2=0;
		double eff3=0;
		double eff4=0;
		double eff5=0;
		double eff6=0;
		double eff7=0;
		double eff8=0;
		double eff9=0;
		double eff10=0;
		double eff11=0;
		double eff12=0;
		double eff13=0;
		double eff14=0;
		double eff15=0;
                double eff16=0;
                double eff17=0;
                double eff18=0;
		if(total!=0)
		{
			eff1 = (double)pass1/(double)total;
			eff2 = (double)pass2/(double)total;
			eff3 = (double)pass3/(double)total;
			eff4 = (double)pass4/(double)total;
			eff5 = (double)pass5/(double)total;
			eff6 = (double)pass6/(double)total;
			eff7 = (double)pass7/(double)total;
			eff8 = (double)pass8/(double)total;
			eff9 = (double)pass9/(double)total;
			eff10 = (double)pass10/(double)total;
			eff11 = (double)pass11/(double)total;
			eff12 = (double)pass12/(double)total;
			eff13 = (double)pass13/(double)total;
			eff14 = (double)pass14/(double)total;
			eff15 = (double)pass15/(double)total;
                        eff16 = (double)pass16/(double)total;
                        eff17 = (double)pass17/(double)total;
                        eff18 = (double)pass18/(double)total;
		}
		cout<<"total: "<<total<<" pass1: "<<pass1<<" eff: "<<eff1<<endl;
		cout<<"total: "<<total<<" pass2: "<<pass2<<" eff: "<<eff2<<endl;
		cout<<"total: "<<total<<" pass3: "<<pass3<<" eff: "<<eff3<<endl;
		cout<<"total: "<<total<<" pass4: "<<pass4<<" eff: "<<eff4<<endl;
		cout<<"total: "<<total<<" pass5: "<<pass5<<" eff: "<<eff5<<endl;
		cout<<"total: "<<total<<" pass6: "<<pass6<<" eff: "<<eff6<<endl;
		cout<<"total: "<<total<<" pass7: "<<pass7<<" eff: "<<eff7<<endl;
		cout<<"total: "<<total<<" pass8: "<<pass8<<" eff: "<<eff8<<endl;
		cout<<"total: "<<total<<" pass9: "<<pass9<<" eff: "<<eff9<<endl;
		cout<<"total: "<<total<<" pass10: "<<pass10<<" eff: "<<eff10<<endl;
		cout<<"total: "<<total<<" pass11: "<<pass11<<" eff: "<<eff11<<endl;
		cout<<"total: "<<total<<" pass12: "<<pass12<<" eff: "<<eff12<<endl;
		cout<<"total: "<<total<<" pass13: "<<pass13<<" eff: "<<eff13<<endl;
		cout<<"total: "<<total<<" pass14: "<<pass14<<" eff: "<<eff14<<endl;
		cout<<"total: "<<total<<" pass15: "<<pass15<<" eff: "<<eff15<<endl;
                cout<<"total: "<<total<<" pass16: "<<pass16<<" eff: "<<eff16<<endl;
                cout<<"total: "<<total<<" pass17: "<<pass17<<" eff: "<<eff17<<endl;
                cout<<"total: "<<total<<" pass18: "<<pass18<<" eff: "<<eff18<<endl;
		h1->Fill(samplename,eff1);
		h2->Fill(samplename,eff2);
		h3->Fill(samplename,eff3);
		h4->Fill(samplename,eff4);
		h5->Fill(samplename,eff5);
		h6->Fill(samplename,eff6);
		h7->Fill(samplename,eff7);
		h8->Fill(samplename,eff8);
		h9->Fill(samplename,eff9);
		h10->Fill(samplename,eff10);
		h11->Fill(samplename,eff11);
		h12->Fill(samplename,eff12);
		h13->Fill(samplename,eff13);
		h14->Fill(samplename,eff14);
		h15->Fill(samplename,eff15);
                h16->Fill(samplename,eff16);
                h17->Fill(samplename,eff17);
                h18->Fill(samplename,eff18);
	}//end of sample loop

	c1->SetGridy(1);

	h1->SetTitle(cut+"_subL1fatL1");
	h1->Draw();
	h1->Draw("TEXT0same");
	c1->SaveAs(cut+"_subL1fatL1.png");

	h2->SetTitle(cut+"_subM1fatL1");
	h2->Draw();
	h2->Draw("TEXT0same");
	c1->SaveAs(cut+"_subM1fatL1.png");

	h3->SetTitle(cut+"_subT1fatL1");
	h3->Draw();
	h3->Draw("TEXT0same");
	c1->SaveAs(cut+"_subT1fatL1.png");

	h4->SetTitle(cut+"_subL2fatL1");
	h4->Draw();
	h4->Draw("TEXT0same");
	c1->SaveAs(cut+"_subL2fatL1.png");

	h5->SetTitle(cut+"_subM2fatL1");
	h5->Draw();
	h5->Draw("TEXT0same");
	c1->SaveAs(cut+"_subM2fatL1.png");

	h6->SetTitle(cut+"_subT2fatL1");
	h6->Draw();
	h6->Draw("TEXT0same");
	c1->SaveAs(cut+"_subT2fatL1.png");	

	h7->SetTitle(cut+"_subL1fatM1");
	h7->Draw();
	h7->Draw("TEXT0same");
	c1->SaveAs(cut+"_subL1fatM1.png");

	h8->SetTitle(cut+"_subM1fatM1");
	h8->Draw();
	h8->Draw("TEXT0same");
	c1->SaveAs(cut+"_subM1fatM1.png");

	h9->SetTitle(cut+"_subT1fatM1");
	h9->Draw();
	h9->Draw("TEXT0same");
	c1->SaveAs(cut+"_subT1fatM1.png");

	h10->SetTitle(cut+"_subL2fatM1");
	h10->Draw();
	h10->Draw("TEXT0same");
	c1->SaveAs(cut+"_subL2fatM1.png");

	h11->SetTitle(cut+"_subM2fatM1");
	h11->Draw();
	h11->Draw("TEXT0same");
	c1->SaveAs(cut+"_subM2fatM1.png");

	h12->SetTitle(cut+"_subT2fatM1");
	h12->Draw();
	h12->Draw("TEXT0same");
	c1->SaveAs(cut+"_subT2fatM1.png");

	h13->SetTitle(cut+"_subL1fatT1");
	h13->Draw();
	h13->Draw("TEXT0same");
	c1->SaveAs(cut+"_subL1fatT1.png");

	h14->SetTitle(cut+"_subM1fatT1");
	h14->Draw();
	h14->Draw("TEXT0same");
	c1->SaveAs(cut+"_subM1fatT1.png");

	h15->SetTitle(cut+"_subT1fatT1");
	h15->Draw();
	h15->Draw("TEXT0same");
	c1->SaveAs(cut+"_subT1fatT1.png");

        h16->SetTitle(cut+"_subL2fatT1");
        h16->Draw();
        h16->Draw("TEXT0same");
        c1->SaveAs(cut+"_subL2fatT1.png");

        h17->SetTitle(cut+"_subM2fatT1");
        h17->Draw();
        h17->Draw("TEXT0same");
        c1->SaveAs(cut+"_subM2fatT1.png");

        h18->SetTitle(cut+"_subT2fatT1");
        h18->Draw();
        h18->Draw("TEXT0same");
        c1->SaveAs(cut+"_subT2fatT1.png");
}
コード例 #12
0
ファイル: jhadd.cpp プロジェクト: pastika/jhadd
void MergeRootfile(std::map<std::pair<std::string, std::string>, TObject*>& outputMap, std::vector<std::pair<std::string, TObject*> >& outputVec, TDirectory *target, TFile *source)
{
    using namespace std;
    string path(target->GetPath());
    path = path.substr(path.find(":") + 1);

    source->cd(path.c_str());
    TDirectory *current_sourcedir = gDirectory;
    //gain time, do not add the objects in the list in memory
    Bool_t status = TH1::AddDirectoryStatus();
    TH1::AddDirectory(kFALSE);

    // loop over all keys in this directory
    TIter nextkey( current_sourcedir->GetListOfKeys() );
    TKey *key, *oldkey = 0;
    while(key = (TKey*)nextkey())
    {
        //keep only the highest cycle number for each key
        if (oldkey && !strcmp(oldkey->GetName(), key->GetName())) continue;
        oldkey = key;

        // read object from source file
        source->cd(path.c_str());
        TObject *obj = key->ReadObj();

        if(obj->IsA()->InheritsFrom(TH1::Class()))
        {
            if(verbosity >= 4) 
            {
                printf("| Found TH1: %s\n", obj->GetName());
                fflush(stdout);
            }
            string path(target->GetPath());
            pair<string, string> okey(path.substr(path.find(':') + 2), obj->GetName());
            //cout << okey.first << "\t" << okey.second << endl;
            if(outputMap.find(okey) == outputMap.end())
            {
                outputVec.push_back(make_pair(path.substr(path.find(':') + 2), obj));
                outputMap[okey] = obj;
            }
            else
            {
                ((TH1*)outputMap[okey])->Add((TH1*)obj);
                ((TH1*)obj)->Delete();
            }
        }
        else if(obj->IsA()->InheritsFrom(TTree::Class()))
        {
            string path(target->GetPath());
            if(verbosity >= 4) 
            {
                printf("| Found Tree: %s\n", obj->GetName());
                fflush(stdout);
            }
            pair<string, string> okey(path.substr(path.find(':') + 2), obj->GetName());
            if(outputMap.find(okey) == outputMap.end())
            {
                string fname(okey.first);
                fname = fname + "_" + obj->GetName() + "tmpfile";
                for(size_t pos; (pos = fname.find('/')) != size_t(-1); ) fname[pos] = '_';
                tmpFiles.push_back(make_pair(fname, new TFile(fname.c_str(), "RECREATE")));
                TTree* tree = ((TTree*)obj)->CloneTree();
                ((TTree*)obj)->GetListOfClones()->Remove(tree);
                ((TTree*)obj)->ResetBranchAddresses();
                tree->ResetBranchAddresses();
                outputVec.push_back(make_pair(path.substr(path.find(':') + 2), (TObject*)tree));
                outputMap[okey] = (TObject*)tree;
            }
            else 
            {
                TTree* tm = (TTree*)outputMap[okey];
                TTree* ts = (TTree*)obj;
                tm->CopyAddresses(ts);
                for(int i = 0; i < ts->GetEntries(); i++)
                {
                    ts->GetEntry(i);
                    tm->Fill();
                }
                ts->ResetBranchAddresses();
                if (tm->GetTreeIndex()) tm->GetTreeIndex()->Append(ts->GetTreeIndex(), kTRUE); 
                ((TTree*)obj)->Delete();
            }
        }
        else if(obj->IsA()->InheritsFrom(TDirectory::Class()))
        {
            if(verbosity >= 3) 
            {
                printf("Hadding Directory: %s\n", ((TDirectory*)obj)->GetPath());
                fflush(stdout);
            }
            string path(((TDirectory*)obj)->GetPath());
            pair<string, string> okey(path.substr(path.find(':') + 2), " -------- ");
            if(outputMap.find(okey) == outputMap.end())
            {
                outputVec.push_back(make_pair(path.substr(path.find(':') + 2), (TDirectory*)0));
                outputMap[okey] = 0;
            }
            MergeRootfile(outputMap, outputVec, (TDirectory*)obj, source);
        }
        else
        {
            printf("Unknown object type, name: %s title: %s\n", obj->GetName(), obj->GetTitle());
            fflush(stdout);
        }
    } // while ( ( TKey *key = (TKey*)nextkey() ) )
}
コード例 #13
0
double TrimEventContent(Int_t iRapBin = 1,
		      Int_t iPTBin = 1,
		      Double_t fracL = 0.5, Double_t nSigma = 2., 
		      Int_t nUpsState=0,//[0]... 1S, [1]... 2S, [2]... 3S
		      bool UpsMC=false,
		      bool f_BG_zero=false,
		      bool ProjectLSBdata=false,
		      bool ProjectRSBdata=false,
		      bool CombineSignalPeaks=false,
		      bool Y1Sto2S_SB=false,
		      bool LeftSided=false,
		      bool RightSided=false,
		      bool MassScan=false,
		      bool adjustOverlapBorders=true
		      ){

  printf("\n\n\nfracL = %1.3f, nSigma = %1.1f, iState = %d, rap %d, pT %d\n", fracL, nSigma, nUpsState, iRapBin, iPTBin);

  Char_t name[100], title[100];
  Char_t fileNameIn[100];
  sprintf(fileNameIn, "tmpFiles/data_Ups_rap%d_pT%d.root", iRapBin, iPTBin);
  //==============================
  //read inputs from input file:
  TFile *fIn = new TFile(fileNameIn);
  TLorentzVector *lepP;
  TLorentzVector *lepN;
  TTree *treeIn = (TTree *) gDirectory->Get("selectedData");
  if(gDirectory->Get("selectedData")==NULL){
    printf("\n\n\nskip processing this bin.\n\n\n");
    return -999.;
  }

  TH2D *hBG_cosThetaPhiLR[onia::kNbFrames][2];
  for(int iFrame = 0; iFrame < onia::kNbFrames; iFrame++){
    sprintf(name, "hBG_cosThetaPhi_%s_L", onia::frameLabel[iFrame]);
    hBG_cosThetaPhiLR[iFrame][L] = (TH2D *) gDirectory->Get(name);
    sprintf(name, "hBG_cosThetaPhi_%s_R", onia::frameLabel[iFrame]);
    hBG_cosThetaPhiLR[iFrame][R] = (TH2D *) gDirectory->Get(name);
  }
  //==============================

  //definition of output variables 
  Char_t fileNameOut[100];
  sprintf(fileNameOut, "AllStates_%1.2fSigma_FracLSB%dPercent/data_%dSUps_rap%d_pT%d.root", nSigma, int(fracL*100), nUpsState+1, iRapBin, iPTBin);
  TFile *fOut = new TFile(fileNameOut, "RECREATE");
  gStyle->SetPadRightMargin(0.2);
  TTree *treeOut = treeIn->CloneTree(0);
  // treeOut->SetName("data");
  TH2D *hBG_cosThetaPhi[onia::kNbFrames];
  // TH2D *hBG_cosThetaPhiSignal[onia::kNbFrames];
  for(int iFrame = 0; iFrame < onia::kNbFrames; iFrame++){
    // //book the histo for the signal
    // sprintf(name, "total_%s", onia::frameLabel[iFrame]);
    // sprintf(title, ";cos#theta_{%s};#phi_{%s} [deg]", onia::frameLabel[iFrame], onia::frameLabel[iFrame]);
    // hBG_cosThetaPhiSignal[iFrame] = new TH2D(name, title, onia::kNbBinsCosT, onia::cosTMin, onia::cosTMax, 
    // 					  onia::kNbBinsPhiPol, onia::phiPolMin, onia::phiPolMax);
    // hBG_cosThetaPhiSignal[iFrame]->Sumw2();
    //copy the L and R sideband histos into one output BG histogram
    hBG_cosThetaPhiLR[iFrame][L]->Scale(fracL/hBG_cosThetaPhiLR[iFrame][L]->Integral());
    hBG_cosThetaPhiLR[iFrame][R]->Scale((1.-fracL)/hBG_cosThetaPhiLR[iFrame][R]->Integral());
    sprintf(name, "background_costhphi%s", onia::frameLabel[iFrame]);
    hBG_cosThetaPhi[iFrame] = (TH2D *) hBG_cosThetaPhiLR[iFrame][L]->Clone(name);
    hBG_cosThetaPhi[iFrame]->Add(hBG_cosThetaPhiLR[iFrame][R]);
  }

  //==========================================================
  //reading fit parameters to establish signal mass window
  //as well as the L and R sideband window for the 3D BG histo
  //==========================================================
  fIn->cd();
  TTree *treeFitPar = (TTree *) gDirectory->Get("massFitParameters");
  TF1 *fUps[kNbSpecies], *fBG = 0;
  fUps[0] = 0, fUps[1] = 0, fUps[2] = 0;
  treeFitPar->SetBranchAddress("fUps1S", &fUps[0]);
  treeFitPar->SetBranchAddress("fUps2S", &fUps[1]);
  treeFitPar->SetBranchAddress("fUps3S", &fUps[2]);
  treeFitPar->SetBranchAddress("fBG", &fBG);
  treeFitPar->LoadTree(0);
  treeFitPar->GetEntry(0);


  Double_t mass[kNbSpecies], sigma[kNbSpecies];
  for(int iState = 0; iState < kNbSpecies; iState++){
    mass[iState] = fUps[iState]->GetParameter(1);
    sigma[iState] = fUps[iState]->GetParameter(2);
  }
  printf("1S: mass = %1.3f GeV, sigma = %1.3f GeV\n", mass[UPS1S], sigma[UPS1S]);
  printf("2S: mass = %1.3f GeV, sigma = %1.3f GeV\n", mass[UPS2S], sigma[UPS2S]);
  printf("3S: mass = %1.3f GeV, sigma = %1.3f GeV\n", mass[UPS3S], sigma[UPS3S]);
  Double_t poleMass = mass[nUpsState], massMin, massMax;
  massMin = poleMass - nSigma*sigma[nUpsState];
  massMax = poleMass + nSigma*sigma[nUpsState];

  if(LeftSided){
	  massMin = poleMass - nSigma*sigma[nUpsState];
	  massMax = poleMass;
  }

  if(RightSided){
	  massMin = poleMass;
	  massMax = poleMass + nSigma*sigma[nUpsState];
  }

//	  massMin = poleMass - 3.*sigma[nUpsState];
//	  massMax = poleMass - 1.*sigma[nUpsState];

//	  massMin = poleMass + 1.*sigma[nUpsState];
//	  massMax = poleMass + 3.*sigma[nUpsState];

  cout<<"massMin = "<<massMin<<endl;
  cout<<"massMax = "<<massMax<<endl;


  if(adjustOverlapBorders){
  if( nUpsState==2 && mass[2]-nSigma*sigma[2]<mass[1]+nSigma*sigma[1] ){
	  cout<<"adjusting lower border of Y(3S) mass window due to overlap"<<endl;
	  massMin=(sigma[2]*mass[1]+sigma[1]*mass[2])/(sigma[1]+sigma[2]);
  }
  if( nUpsState==1 && mass[1]-nSigma*sigma[1]<mass[0]+nSigma*sigma[0] ){
	  cout<<"adjusting lower border of Y(2S) mass window due to overlap"<<endl;
	  massMin=(sigma[1]*mass[0]+sigma[0]*mass[1])/(sigma[1]+sigma[0]);
  }
  if( nUpsState==1 && mass[2]-nSigma*sigma[2]<mass[1]+nSigma*sigma[1] ){
	  cout<<"adjusting upper border of Y(2S) mass window due to overlap"<<endl;
	  massMax=(sigma[2]*mass[1]+sigma[1]*mass[2])/(sigma[1]+sigma[2]);
  }
  if( nUpsState==0 && mass[1]-nSigma*sigma[1]<mass[0]+nSigma*sigma[0] ){
	  cout<<"adjusting upper border of Y(1S) mass window due to overlap"<<endl;
	  massMax=(sigma[1]*mass[0]+sigma[0]*mass[1])/(sigma[1]+sigma[0]);
  }
  }


  if( nUpsState==0){
  contamination2Sin1S=fUps[1]->Integral(massMin, massMax)/(fUps[0]->Integral(massMin, massMax)+fUps[1]->Integral(massMin, massMax));
  cout<<"Contamination of the 1S sample by 2S events = "<<contamination2Sin1S*100<<" %"<<endl;
  }
  if( nUpsState==1){
  contamination1Sin2S=fUps[0]->Integral(massMin, massMax)/(fUps[0]->Integral(massMin, massMax)+fUps[1]->Integral(massMin, massMax));
  contamination3Sin2S=fUps[2]->Integral(massMin, massMax)/(fUps[2]->Integral(massMin, massMax)+fUps[1]->Integral(massMin, massMax));
  cout<<"Contamination of the 2S sample by 1S events = "<<contamination1Sin2S*100<<" %"<<endl;
  cout<<"Contamination of the 2S sample by 3S events = "<<contamination3Sin2S*100<<" %"<<endl;
  }
  if( nUpsState==2){
  contamination2Sin3S=fUps[1]->Integral(massMin, massMax)/(fUps[2]->Integral(massMin, massMax)+fUps[1]->Integral(massMin, massMax));
  cout<<"Contamination of the 3S sample by 2S events = "<<contamination2Sin3S*100<<" %"<<endl;
  }

  if(CombineSignalPeaks) {
	  massMin=9.15;
	  massMax=10.65;
  }

  if(Y1Sto2S_SB){
	  massMin = mass[0] + 3.*sigma[0];
	  massMax = mass[1] - 4.*sigma[1];
  }

////////////////// Background mass scan
const int nMassScan=12;
int nMassScanCurrent;
//double MassScanBorders[nMassScan+1] = {8.6, 8.95, 9.3, 9.45, 9.6, 9.85, 10.0125, 10.175, 10.3425, 10.51, 10.8, 11.1, 11.4};
double MassScanBorders[nMassScan+1] = {8.6, 8.95, 9.3, 9.45, 9.6, 9.85, 10.0125, 10.175, 10.3425, 10.51, 10.8, 11.1, 11.4};

for(int i=1;i<nMassScan+1;i++){
if(nSigma<i+0.5) {nMassScanCurrent=i; break;}
}

double BuffMinL=onia::massMinL;
double BuffMaxL=mass[UPS1S] - onia::nSigmaL*sigma[UPS1S];
double BuffMinR=mass[UPS3S] + onia::nSigmaR*sigma[UPS3S];
double BuffMaxR=onia::massMaxR;

double MassScanMin=MassScanBorders[nMassScanCurrent-1];
double MassScanMax=MassScanBorders[nMassScanCurrent];

if(nSigma==1){
	MassScanMin=BuffMinL;
	MassScanMax=BuffMinL+1./3.*(BuffMaxL-BuffMinL);
}
if(nSigma==2){
	MassScanMin=BuffMinL+1./3.*(BuffMaxL-BuffMinL);
	MassScanMax=BuffMinL+2./3.*(BuffMaxL-BuffMinL);
}
if(nSigma==3){
	MassScanMin=BuffMinL+2./3.*(BuffMaxL-BuffMinL);
	MassScanMax=BuffMaxL;
}
if(nSigma==4){
	MassScanMin=BuffMinL;
	MassScanMax=BuffMaxL;
}

if(nSigma==5){
	MassScanMin=BuffMinR;
	MassScanMax=BuffMinR+1./3.*(BuffMaxR-BuffMinR);
}
if(nSigma==6){
	MassScanMin=BuffMinR+1./3.*(BuffMaxR-BuffMinR);
	MassScanMax=BuffMinR+2./3.*(BuffMaxR-BuffMinR);
}
if(nSigma==7){
	MassScanMin=BuffMinR+2./3.*(BuffMaxR-BuffMinR);
	MassScanMax=BuffMaxR;
}
if(nSigma==8){
	MassScanMin=BuffMinR;
	MassScanMax=BuffMaxR;
}
if(nSigma>8){
	BuffMaxL=mass[UPS1S] - 7*sigma[UPS1S];
	BuffMinR=mass[UPS3S] + onia::nSigmaR*sigma[UPS3S];
}
if(nSigma==9){
	MassScanMin=BuffMinL;
	MassScanMax=BuffMinL+1./3.*(BuffMaxL-BuffMinL);
}
if(nSigma==10){
	MassScanMin=BuffMinL+1./3.*(BuffMaxL-BuffMinL);
	MassScanMax=BuffMinL+2./3.*(BuffMaxL-BuffMinL);
}
if(nSigma==11){
	MassScanMin=BuffMinL+2./3.*(BuffMaxL-BuffMinL);
	MassScanMax=BuffMaxL;
}
if(nSigma==12){
	MassScanMin=BuffMinL;
	MassScanMax=BuffMaxL;
}


  if(MassScan){
  massMin=MassScanMin;
  massMax=MassScanMax;
  }
/////////////////////////////////////

  printf("--> signal mass window: %1.3f < M < %1.3f GeV\n", massMin, massMax);

  //calculate the fraction of BG under the signal mass window
  Double_t nBG = fBG->Integral(massMin, massMax);
//  Double_t nSignal = fUps[nUpsState]->Integral(massMin, massMax);
  Double_t nSignal = fUps[0]->Integral(massMin, massMax)+fUps[1]->Integral(massMin, massMax)+fUps[2]->Integral(massMin, massMax);
  Double_t fracBG = nBG / (nBG + nSignal);
  sprintf(name, ";;fraction of BG in %1.1f sigma window", nSigma);
  TH1D *hFracBG = new TH1D("background_fraction", name, 1, 0., 1.);
  if(!UpsMC&&!f_BG_zero) hFracBG->SetBinContent(1, fracBG);
  if(UpsMC||f_BG_zero)  hFracBG->SetBinContent(1, 0.001);

 /* fBG->ReleaseParameter(1);
  cout<<"fBG "<<fBG->Integral(massMin, massMax) / (fBG->Integral(massMin, massMax) + fUps[nUpsState]->Integral(massMin, massMax))<<endl;
  double fBGPar0=fBG->GetParameter(1);
  double err_fBGPar0=fBG->GetParError(1);
  cout<<"fBGPar0 "<<fBGPar0<<endl;
  cout<<"err_fBGPar0 "<<err_fBGPar0<<endl;

  fBG->FixParameter(1,fBGPar0+100*err_fBGPar0);
  cout<<"fBGPar0 "<<fBG->GetParameter(1)<<endl;
  cout<<"fBG "<<fBG->Integral(massMin, massMax) / (fBG->Integral(massMin, massMax) + fUps[nUpsState]->Integral(massMin, massMax))<<endl;
  fBG->SetParameter(1,fBGPar0);
  cout<<"fBG "<<fBG->Integral(massMin, massMax) / (fBG->Integral(massMin, massMax) + fUps[nUpsState]->Integral(massMin, massMax))<<endl;
*/

  if(Y1Sto2S_SB){
cout<<"Y1Sto2S_SB fBG = "<<fBG->Integral(massMin, massMax) / (fBG->Integral(massMin, massMax) + fUps[0]->Integral(massMin, massMax)+fUps[1]->Integral(massMin, massMax))<<endl;
  }

  backgroundFrac=fracBG;

  //calculate the L and R mass windows:
  Double_t massMinBG[2], massMaxBG[2];
  massMinBG[L] = onia::massMinL;
  massMaxBG[L] = mass[UPS1S] - onia::nSigmaL*sigma[UPS1S];
  massMinBG[R] = mass[UPS3S] + onia::nSigmaR*sigma[UPS3S];
  massMaxBG[R] = onia::massMaxR;
  printf("--> L mass window: %1.3f < M < %1.3f GeV\n", massMinBG[L], massMaxBG[L]);
  printf("--> R mass window: %1.3f < M < %1.3f GeV\n", massMinBG[R], massMaxBG[R]);
//cout<<"here?"<<endl;
  bool PseudoBin=false;

  if(CombineSignalPeaks) {
	  massMin=9.15;
	  massMax=10.65;
  }

  if(!UpsMC){
  if(massMaxBG[L] > massMin){
    printf("the right sideband window is LARGER than the left signal window!!!!\n\n\n\n");
    massMaxBG[L]=9.;
    massMinBG[L]=8.6;
    massMin=9.;
    PseudoBin=true;
//    exit(0);
  }
  if(massMinBG[R] < massMax){
    printf("the left sideband window is SMALLER than the right signal window!!!!\n\n\n\n");
    massMaxBG[R]=11.4;
    massMinBG[R]=11.;
    massMax=10.;
    PseudoBin=true;
//    exit(0);
  }
  }

  if(ProjectLSBdata){
	  massMin=massMinBG[L];
	  massMax=massMaxBG[L];
  }
  if(ProjectRSBdata){
	  massMin=massMinBG[R];
	  massMax=massMaxBG[R];
  }

  if(CombineSignalPeaks) {
	  massMin=9.15;
	  massMax=10.65;
  }

  double meanMass=0;
  double MassDistCurrent=0.001;
  TH1D *hMassScanInfo = new TH1D("hMassScanInfo", "hMassScanInfo", 2, 0., 1.);

  if(MassScan){
  massMin=MassScanMin;
  massMax=MassScanMax;

  double IntCurrent = fBG->Integral(massMin, massMax);
  for(int i=1;i<1000000;i++){
	  if(fBG->Integral(massMin, massMin+i*MassDistCurrent)>IntCurrent/2.) {meanMass=massMin+i*MassDistCurrent; break;}
  }

  hMassScanInfo->SetBinContent(1,meanMass);
  hMassScanInfo->SetBinContent(2,1-fracBG);

  }

  if(Y1Sto2S_SB){
	  massMin = mass[0] + 3.*sigma[0];
	  massMax = mass[1] - 4.*sigma[1];

	  double IntCurrent = fBG->Integral(massMin, massMax);
	  for(int i=1;i<1000000;i++){
		  if(fBG->Integral(massMin, massMin+i*MassDistCurrent)>IntCurrent/2.) {meanMass=massMin+i*MassDistCurrent; break;}
	  }
	  hMassScanInfo->SetBinContent(1,meanMass);
	  hMassScanInfo->SetBinContent(2,1-fracBG);
  }


  if(UpsMC&&iPTBin>5&&fracL<0.35){
	  cout<<"using exact mass window definition of data"<<endl;

  Double_t massMinUps1S_1sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 9.38372, 9.38435, 9.38425, 9.38487, 9.38326},
    {0,0,0,0,0, 9.35644, 9.3574, 9.35555, 9.35522, 9.34896}};
  Double_t massMaxUps1S_1sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 9.518, 9.51711, 9.51826, 9.51701, 9.51941},
    {0,0,0,0,0, 9.53728, 9.53853, 9.5394, 9.54169, 9.54538}};

  Double_t massMinUps2S_1sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 9.94218, 9.94285, 9.94275, 9.9434, 9.94169},
    {0,0,0,0,0, 9.91328, 9.91429, 9.91234, 9.91198, 9.90535}};
  Double_t massMaxUps2S_1sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 10.0844, 10.0835, 10.0847, 10.0834, 10.086},
    {0,0,0,0,0, 10.1049, 10.1062, 10.1071, 10.1096, 10.1135}};

  Double_t massMinUps3S_1sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 10.2715, 10.2722, 10.2721, 10.2728, 10.271},
    {0,0,0,0,0, 10.2416, 10.2427, 10.2407, 10.2403, 10.2335}};
  Double_t massMaxUps3S_1sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 10.4185, 10.4175, 10.4188, 10.4174, 10.42},
    {0,0,0,0,0, 10.4396, 10.441, 10.4419, 10.4444, 10.4485}};

  //=============================

  Double_t massMinUps1S_3sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 9.24945, 9.2516, 9.25025, 9.25273, 9.24711},
    {0,0,0,0,0, 9.1756, 9.17626, 9.17171, 9.16874, 9.15253}};
  Double_t massMaxUps1S_3sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 9.65227, 9.64987, 9.65227, 9.64915, 9.65557},
    {0,0,0,0,0, 9.71811, 9.71966, 9.72048, 9.72149, 9.72017}};

  Double_t massMinUps2S_3sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 9.79992, 9.80219, 9.80076, 9.80339, 9.79744},
    {0,0,0,0,0, 9.72168, 9.72238, 9.72048, 9.72149, 9.72017}};
  Double_t massMaxUps2S_3sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 10.1765, 10.1763, 10.1769, 10.1765, 10.177},
    {0,0,0,0,0, 10.1721, 10.1733, 10.1728, 10.1739, 10.1725}};

  Double_t massMinUps3S_3sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 10.1765, 10.1763, 10.1769, 10.1765, 10.177},
    {0,0,0,0,0, 10.1721, 10.1733, 10.1728, 10.1739, 10.1725}};
  Double_t massMaxUps3S_3sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 10.5655, 10.5628, 10.5655, 10.562, 10.5691},
    {0,0,0,0,0, 10.6375, 10.6392, 10.6432, 10.6485, 10.6635}};


  if(nSigma==1){
	  if(nUpsState==0){
		  massMin=massMinUps1S_1sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps1S_1sigma[iRapBin][iPTBin-1];
	  }
	  if(nUpsState==1){
		  massMin=massMinUps2S_1sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps2S_1sigma[iRapBin][iPTBin-1];
	  }
	  if(nUpsState==2){
		  massMin=massMinUps3S_1sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps3S_1sigma[iRapBin][iPTBin-1];
	  }
  }

  if(nSigma==3){
	  if(nUpsState==0){
		  massMin=massMinUps1S_3sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps1S_3sigma[iRapBin][iPTBin-1];
	  }
	  if(nUpsState==1){
		  massMin=massMinUps2S_3sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps2S_3sigma[iRapBin][iPTBin-1];
	  }
	  if(nUpsState==2){
		  massMin=massMinUps3S_3sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps3S_3sigma[iRapBin][iPTBin-1];
	  }
  }

  if(nSigma==0.5){
	  if(nUpsState==0){
		  massMin=massMinUps1S_1sigma[iRapBin][iPTBin-1]+(massMaxUps1S_1sigma[iRapBin][iPTBin-1]-massMinUps1S_1sigma[iRapBin][iPTBin-1])/4.;
		  massMax=massMaxUps1S_1sigma[iRapBin][iPTBin-1]-(massMaxUps1S_1sigma[iRapBin][iPTBin-1]-massMinUps1S_1sigma[iRapBin][iPTBin-1])/4.;
	  }
	  if(nUpsState==1){
		  massMin=massMinUps2S_1sigma[iRapBin][iPTBin-1]+(massMaxUps2S_1sigma[iRapBin][iPTBin-1]-massMinUps2S_1sigma[iRapBin][iPTBin-1])/4.;
		  massMax=massMaxUps2S_1sigma[iRapBin][iPTBin-1]-(massMaxUps2S_1sigma[iRapBin][iPTBin-1]-massMinUps2S_1sigma[iRapBin][iPTBin-1])/4.;
	  }
	  if(nUpsState==2){
		  massMin=massMinUps3S_1sigma[iRapBin][iPTBin-1]+(massMaxUps3S_1sigma[iRapBin][iPTBin-1]-massMinUps3S_1sigma[iRapBin][iPTBin-1])/4.;
		  massMax=massMaxUps3S_1sigma[iRapBin][iPTBin-1]-(massMaxUps3S_1sigma[iRapBin][iPTBin-1]-massMinUps3S_1sigma[iRapBin][iPTBin-1])/4.;
	  }
  }

  if(nSigma==0.1){
	  if(nUpsState==0){
		  massMin=massMinUps1S_1sigma[iRapBin][iPTBin-1]+(massMaxUps1S_1sigma[iRapBin][iPTBin-1]-massMinUps1S_1sigma[iRapBin][iPTBin-1])/20.;
		  massMax=massMaxUps1S_1sigma[iRapBin][iPTBin-1]-(massMaxUps1S_1sigma[iRapBin][iPTBin-1]-massMinUps1S_1sigma[iRapBin][iPTBin-1])/20.;
	  }
	  if(nUpsState==1){
		  massMin=massMinUps2S_1sigma[iRapBin][iPTBin-1]+(massMaxUps2S_1sigma[iRapBin][iPTBin-1]-massMinUps2S_1sigma[iRapBin][iPTBin-1])/20.;
		  massMax=massMaxUps2S_1sigma[iRapBin][iPTBin-1]-(massMaxUps2S_1sigma[iRapBin][iPTBin-1]-massMinUps2S_1sigma[iRapBin][iPTBin-1])/20.;
	  }
	  if(nUpsState==2){
		  massMin=massMinUps3S_1sigma[iRapBin][iPTBin-1]+(massMaxUps3S_1sigma[iRapBin][iPTBin-1]-massMinUps3S_1sigma[iRapBin][iPTBin-1])/20.;
		  massMax=massMaxUps3S_1sigma[iRapBin][iPTBin-1]-(massMaxUps3S_1sigma[iRapBin][iPTBin-1]-massMinUps3S_1sigma[iRapBin][iPTBin-1])/20.;
	  }
  }

  if(nSigma==9){
	  if(nUpsState==0){
		  massMin=massMinUps1S_1sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps1S_1sigma[iRapBin][iPTBin-1]-(massMaxUps1S_1sigma[iRapBin][iPTBin-1]-massMinUps1S_1sigma[iRapBin][iPTBin-1])/2.;
	  }
	  if(nUpsState==1){
		  massMin=massMinUps2S_1sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps2S_1sigma[iRapBin][iPTBin-1]-(massMaxUps2S_1sigma[iRapBin][iPTBin-1]-massMinUps2S_1sigma[iRapBin][iPTBin-1])/2.;
	  }
	  if(nUpsState==2){
		  massMin=massMinUps3S_1sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps3S_1sigma[iRapBin][iPTBin-1]-(massMaxUps3S_1sigma[iRapBin][iPTBin-1]-massMinUps3S_1sigma[iRapBin][iPTBin-1])/2.;
	  }
  }

  if(nSigma==10){
	  if(nUpsState==0){
		  massMax=massMaxUps1S_1sigma[iRapBin][iPTBin-1];
		  massMin=massMaxUps1S_1sigma[iRapBin][iPTBin-1]-(massMaxUps1S_1sigma[iRapBin][iPTBin-1]-massMinUps1S_1sigma[iRapBin][iPTBin-1])/2.;
	  }
	  if(nUpsState==1){
		  massMax=massMaxUps2S_1sigma[iRapBin][iPTBin-1];
		  massMin=massMaxUps2S_1sigma[iRapBin][iPTBin-1]-(massMaxUps2S_1sigma[iRapBin][iPTBin-1]-massMinUps2S_1sigma[iRapBin][iPTBin-1])/2.;
	  }
	  if(nUpsState==2){
		  massMax=massMaxUps3S_1sigma[iRapBin][iPTBin-1];
		  massMin=massMaxUps3S_1sigma[iRapBin][iPTBin-1]-(massMaxUps3S_1sigma[iRapBin][iPTBin-1]-massMinUps3S_1sigma[iRapBin][iPTBin-1])/2.;
	  }
  }


}





  ActualMassMin=massMin;
  ActualMassMax=massMax;


  //calculate central fracL

  double fracLCentral;

  if(!f_BG_zero){
  double mean_LSB;
  double mean_RSB;
  double mean_nS;

  double MassDist=0.001;
  double IntLSB = fBG->Integral(massMinBG[L], massMaxBG[L]);
  for(int i=1;i<1000000;i++){
	  if(fBG->Integral(massMinBG[L], massMinBG[L]+i*MassDist)>IntLSB/2.) {mean_LSB=massMinBG[L]+i*MassDist; break;}
  }
  double IntRSB = fBG->Integral(massMinBG[R], massMaxBG[R]);
  for(int i=1;i<1000000;i++){
	  if(fBG->Integral(massMinBG[R], massMinBG[R]+i*MassDist)>IntRSB/2.) {mean_RSB=massMinBG[R]+i*MassDist; break;}
  }
  double IntSig = fBG->Integral(massMin, massMax);
  for(int i=1;i<1000000;i++){
	  if(fBG->Integral(massMin, massMin+i*MassDist)>IntSig/2.) {mean_nS=massMin+i*MassDist; break;}
  }

  fracLCentral=1-(mean_nS-mean_LSB)/(mean_RSB-mean_LSB);
  cout<<"Median LSB: "<<mean_LSB<<endl;
  cout<<"Median RSB: "<<mean_RSB<<endl;
  cout<<"Median signal region: "<<mean_nS<<endl;
  cout<<"Central FracL: "<<fracLCentral<<endl;


  }



  //build the 3D (pT, |y|, M) histos for the L and R mass sideband 
  TH3D *hBG_pTRapMass[2];
  hBG_pTRapMass[L] = new TH3D("hBG_pTRapMass_L", ";p_{T} [GeV/c]; |y|; M [GeV]", 
			      7, onia::pTRange[iRapBin][iPTBin-1], onia::pTRange[iRapBin][iPTBin],
			      2, onia::rapForPTRange[iRapBin-1], onia::rapForPTRange[iRapBin],
			      7, massMin, massMax);//*signal* mass window!
  hBG_pTRapMass[L]->Sumw2();
  //
  hBG_pTRapMass[R] = new TH3D("hBG_pTRapMass_R", ";p_{T} [GeV/c]; |y|; M [GeV]", 
			      7, onia::pTRange[iRapBin][iPTBin-1], onia::pTRange[iRapBin][iPTBin],
			      2, onia::rapForPTRange[iRapBin-1], onia::rapForPTRange[iRapBin],
			      7, massMin, massMax);//*signal* mass window!
  hBG_pTRapMass[R]->Sumw2();

  lepP = 0; lepN = 0;
  treeIn->SetBranchAddress("lepP", &lepP);
  treeIn->SetBranchAddress("lepN", &lepN);
  TLorentzVector *onia = new TLorentzVector();


  Double_t onia_mass;
  for(int iEn = 0; iEn < treeIn->GetEntries(); iEn++){ 
    Long64_t iEntry = treeIn->LoadTree(iEn);
    treeIn->GetEntry(iEntry);
    if(iEn % 10000 == 0)
      cout << "entry " << iEntry << " out of " << treeIn->GetEntries() << endl;

    *onia = *(lepP) + *(lepN);
    onia_mass = onia->M();

	  if(UpsMC||f_BG_zero) hBG_pTRapMass[L]->Fill(onia->Pt(), TMath::Abs(onia->Rapidity()), gRandom->Uniform(massMin, massMax));
	  if(UpsMC||f_BG_zero) hBG_pTRapMass[R]->Fill(onia->Pt(), TMath::Abs(onia->Rapidity()), gRandom->Uniform(massMin, massMax));

	  if(!UpsMC&&!f_BG_zero){
    if(onia_mass  > massMinBG[L] && onia_mass < massMaxBG[L])
      hBG_pTRapMass[L]->Fill(onia->Pt(), TMath::Abs(onia->Rapidity()), fBG->GetRandom(massMin, massMax));
    else if(onia_mass > massMinBG[R] && onia_mass < massMaxBG[R])
      hBG_pTRapMass[R]->Fill(onia->Pt(), TMath::Abs(onia->Rapidity()), fBG->GetRandom(massMin, massMax));
	  }

    if(onia_mass > massMin && onia_mass < massMax){
      treeOut->Fill(); //stores TLorenzVectors of the two muons

      // //store now the cosTheta and phi distributions of the signal window:
      // calcPol(*lepP, *lepN);

      // for(int iFrame = 0; iFrame < onia::kNbFrames; iFrame++)
      // 	hCosThetaPhiSignal[iFrame]->Fill(thisCosTh[iFrame], thisPhi[iFrame]);
    }


  }



/*  Char_t name2[100];
  sprintf(name2, "Reco_Onia_mass_rap%d_pT%d", iRapBin, iPTBin);
  TH1F* hMass = (TH1F*) gDirectory->Get(name2);
  hMass->Rebin(2);
  double binWidth = hMass->GetBinWidth(1); //valid only for an equal bin histogram!
  printf("binwidth = %1.2e\n", binWidth);
*/
  double nY[3];
  double nBG_;
  double binWidth = 0.02; //You have to manually change that parameter from the mass fit!!!

    nY[2] = fUps[2]->Integral(massMin, massMax)/binWidth;
    nY[1] = fUps[1]->Integral(massMin, massMax)/binWidth;
    nY[0] = fUps[0]->Integral(massMin, massMax)/binWidth;
    nBG_ = fBG->Integral(massMin, massMax)/binWidth;
    double nAll=nY[0]+nY[1]+nY[2]+nBG_;

    printf("1 sigma region num background = %1.3f\n",nBG_);
    printf("1 sigma region num 1S = %1.3f\n",nY[0]);
    printf("1 sigma region num 2S = %1.3f\n",nY[1]);
    printf("1 sigma region num 3S = %1.3f\n",nY[2]);
    printf("1 sigma region num all = %1.3f\n",nAll);
    printf("1 sigma region calcNumAll - numEventsInDataSet = %1.3f\n",nAll-treeOut->GetEntries());

    double tempBfrac=nBG_/(treeOut->GetEntries());
    printf("1 sigma region background fraction = %1.3f\n",tempBfrac);
    printf("Used           background fraction = %1.3f\n",backgroundFrac);

    SignalEvents=nY[nUpsState];

    double BackgroundEvents=SignalEvents*(1-backgroundFrac)/backgroundFrac;

    err_backgroundFrac=TMath::Power(SignalEvents*BackgroundEvents,0.5)/TMath::Power(SignalEvents+BackgroundEvents,1.5);

  //now, add the L and R 3D (pT, |y|, M) histos
  TH3D *hBG_pTRapMassSum;
  hBG_pTRapMass[L]->Scale(fracL/hBG_pTRapMass[L]->Integral());
  hBG_pTRapMass[R]->Scale((1.-fracL)/hBG_pTRapMass[R]->Integral());
  sprintf(name, "background_pTrapMass");
  hBG_pTRapMassSum = (TH3D*) hBG_pTRapMass[L]->Clone(name);
  hBG_pTRapMassSum->Add(hBG_pTRapMass[R]);

  //write the output
  fOut->cd();
  treeOut->Write();

  for(int iFrame = 0; iFrame < onia::kNbFrames; iFrame++){
    hBG_cosThetaPhi[iFrame]->Write();
    hBG_cosThetaPhiLR[iFrame][L]->Write();
    hBG_cosThetaPhiLR[iFrame][R]->Write();
    // hCosThetaPhiSignal[iFrame]->Write();
  }
  hBG_pTRapMassSum->Write();
  hFracBG->Write();
  if(MassScan){
	  hMassScanInfo->Write();
  }
  fOut->Close();
  fIn->Close();

  return fracLCentral;
}
コード例 #14
0
ファイル: MakeTree_2012.c プロジェクト: nfilipov/cvs-code
void MakeTree_2012(){
	//gROOT->LoadMacro("setTDRStyle_modified.C");
	//setTDRStyle();
	TFile *f = TFile::Open("Upsilon_Histos_191212_FULL.root");
	//TFile *f = TFile::Open("/castor/cern.ch/user/t/tdahms/Jpsi_Histos_ppReReco.root");
	TTree *t =(TTree*)f->Get("myTree");
	Long64_t nentries = t->GetEntries();

	const int NMAX=100;
	UInt_t eventNb;
	UInt_t runNb;
	Int_t Centrality;
	Int_t HLTriggers;
	Int_t Reco_QQ_size;
	Int_t Reco_QQ_trig[NMAX];
	Int_t Reco_QQ_type[NMAX];
	Int_t Reco_QQ_sign[NMAX];
	Float_t Reco_QQ_VtxProb[NMAX];
	TClonesArray *Reco_QQ_4mom;
	TClonesArray *Reco_QQ_mupl_4mom;
	TClonesArray *Reco_QQ_mumi_4mom;
	Int_t Reco_mu_size;
	Int_t Reco_mu_type[NMAX];
	Int_t Reco_mu_charge[NMAX];
	TClonesArray *Reco_mu_4mom;
	int nPlusMu;
	int nMinusMu;
	float muPt[NMAX];
	float muEta[NMAX];
	float muPhi[NMAX];
	//Int_t nReco_QQ;
	Float_t invariantMass;
	Int_t QQtrig;
	Int_t QQsign;
	float weight;
	float weight2;
	Float_t upsPt;
	Float_t upsEta;
	Float_t upsRapidity;	
	Float_t vProb;
	Float_t muPlusPt;
	Float_t muMinusPt;
	Float_t muPlusEta;
	Float_t muMinusEta;
	Float_t muPlusPhi;
	Float_t muMinusPhi;
	Float_t RmuPlusPhi = 0;
	Float_t RmuMinusPhi = 0;
	//float theta_HX;
	//float phi_HX;
	//float theta_CS;
	//float phi_CS;

	float QQmuPlusDxy[100];
	float QQmuPlusDz[100];
	int QQmuPlusNhits[100];
	int QQmuPlusNPixelhits[100];
	int QQmuPlusNPxlLayers[100];
	float QQmuPlusInnerChi[100];
	float QQmuPlusGlobalChi[100];
	int QQmuPlusNMuonhits[100];
	float QQmuPlusDB[100];

	float QQmuMinusDxy[100];
	float QQmuMinusDz[100];
	int QQmuMinusNhits[100];
	int QQmuMinusNPixelhits[100];
	int QQmuMinusNPxlLayers[100];
	float QQmuMinusInnerChi[100];
	float QQmuMinusGlobalChi[100];
	int QQmuMinusNMuonhits[100];
	float QQmuMinusDB[100];

	float muPlusDxy;
	float muPlusDz;
	int muPlusNhits;
	int muPlusNPixelhits;
	int muPlusNPxlLayers;
	float muPlusInnerChi;
	float muPlusGlobalChi;
	int muPlusNMuonhits;
	float muPlusDB;

	float muMinusDxy;
	float muMinusDz;
	int muMinusNhits;
	int muMinusNPixelhits;
	int muMinusNPxlLayers;
	float muMinusInnerChi;
	float muMinusGlobalChi;
	int muMinusNMuonhits;
	float muMinusDB;

	t->SetBranchAddress("Centrality",    &Centrality    );
	t->SetBranchAddress("eventNb",    &eventNb    );
	t->SetBranchAddress("runNb",    &runNb    );
	t->SetBranchAddress("HLTriggers",    &HLTriggers    );
	t->SetBranchAddress("Reco_QQ_size",  &Reco_QQ_size  );
	t->SetBranchAddress("Reco_QQ_trig",  &Reco_QQ_trig  );
	t->SetBranchAddress("Reco_QQ_type",  Reco_QQ_type   );
	t->SetBranchAddress("Reco_QQ_sign",  Reco_QQ_sign   );
	t->SetBranchAddress("Reco_QQ_VtxProb",  Reco_QQ_VtxProb);
	t->SetBranchAddress("Reco_QQ_4mom",  &Reco_QQ_4mom  );
	t->SetBranchAddress("Reco_QQ_mupl_4mom", &Reco_QQ_mupl_4mom);
	t->SetBranchAddress("Reco_QQ_mumi_4mom", &Reco_QQ_mumi_4mom);

	/*
	   t->SetBranchAddress("muPlusDxy",QQmuPlusDxy);
	   t->SetBranchAddress("muPlusDz",QQmuPlusDz);
	   t->SetBranchAddress("muPlusNhits",QQmuPlusNhits);
	   t->SetBranchAddress("muPlusNPixelhits",QQmuPlusNPixelhits);
	   t->SetBranchAddress("muPlusNPxlLayers",QQmuPlusNPxlLayers);
	   t->SetBranchAddress("muPlusInnerChi",QQmuPlusInnerChi);
	   t->SetBranchAddress("muPlusGlobalChi",QQmuPlusGlobalChi);
	   t->SetBranchAddress("muPlusNMuonhits",QQmuPlusNMuonhits);
	   t->SetBranchAddress("muPlusDB",QQmuPlusDB);

	   t->SetBranchAddress("muMinusDxy",QQmuMinusDxy);
	   t->SetBranchAddress("muMinusDz",QQmuMinusDz);
	   t->SetBranchAddress("muMinusNhits",QQmuMinusNhits);
	   t->SetBranchAddress("muMinusNPixelhits",QQmuMinusNPixelhits);
	   t->SetBranchAddress("muMinusNPxlLayers",QQmuMinusNPxlLayers);
	   t->SetBranchAddress("muMinusInnerChi",QQmuMinusInnerChi);
	   t->SetBranchAddress("muMinusGlobalChi",QQmuMinusGlobalChi);
	   t->SetBranchAddress("muMinusNMuonhits",QQmuMinusNMuonhits);
	   t->SetBranchAddress("muMinusDB",QQmuMinusDB);
	 */
	t->SetBranchAddress("Reco_mu_size",  &Reco_mu_size  );
	t->SetBranchAddress("Reco_mu_type",  Reco_mu_type   );
	t->SetBranchAddress("Reco_mu_charge",Reco_mu_charge );
	t->SetBranchAddress("Reco_mu_4mom",  &Reco_mu_4mom);

	TH1F *h_QQ_mass = new TH1F("h_QQ_mass","",70,7,14);
	TH1F *h_QQ_mass_1 = new TH1F("h_QQ_mass_1","",70,7,14);
	TH1F *h_QQ_mass_2 = new TH1F("h_QQ_mass_2","",70,7,14);	

	TFile *f1 = new TFile("dimuonTree_fullFiltered.root","RECREATE");

	TTree *MuTree = new TTree("MuTree","MuTree");
	TTree *UpsilonTree = new TTree("UpsilonTree","UpsilonTree");
	TTree *UpsilonTree_allsign = new TTree("UpsilonTree_allsign","UpsilonTree_allsign");
	TTree *UpsilonTree_trkRot = new TTree("UpsilonTree_trkRot","UpsilonTree_trkRot");

	MuTree->Branch("Reco_mu_size",   &Reco_mu_size,   "Reco_mu_size/I");
	MuTree->Branch("nPlusMu",        &nPlusMu,        "nPlusMu/I");
	MuTree->Branch("nMinusMu",       &nMinusMu,       "nMinusMu/I");
	MuTree->Branch("muPt",           &muPt,           "muPt[Reco_mu_size]/F");
	MuTree->Branch("muEta",          &muEta,          "muEta[Reco_mu_size]/F");
	MuTree->Branch("muPhi",          &muPhi,          "muPhi[Reco_mu_size]/F");
	MuTree->Branch("Reco_mu_type",   Reco_mu_type,    "Reco_mu_type[Reco_mu_size]/I");
	MuTree->Branch("Reco_mu_charge", Reco_mu_charge,  "Reco_mu_charge[Reco_mu_size]/I" );
	MuTree->Branch("eventNb",    &eventNb,     "eventNb/I");
	MuTree->Branch("runNb",    &runNb,     "runNb/I");


	//UpsilonTree->Branch("nReco_QQ", &nReco_QQ, "nReco_QQ/I");
	UpsilonTree->Branch("Centrality",    &Centrality,    "Centrality/I");
	UpsilonTree->Branch("HLTriggers",    &HLTriggers,    "HLTriggers/I");
	UpsilonTree->Branch("QQtrig",   &QQtrig,    "QQtrig/I");
	UpsilonTree->Branch("QQsign",   &QQsign,    "QQsign/I");
	UpsilonTree->Branch("vProb",    &vProb,     "vProb/F");
	UpsilonTree->Branch("eventNb",    &eventNb,     "eventNb/I");
	UpsilonTree->Branch("runNb",    &runNb,     "runNb/I");
	UpsilonTree->Branch("invariantMass", &invariantMass, "invariantMass/F");
	UpsilonTree->Branch("upsPt", &upsPt, "upsPt/F");
	UpsilonTree->Branch("upsEta", &upsEta, "upsEta/F");
	UpsilonTree->Branch("upsRapidity", &upsRapidity, "upsRapidity/F");
	UpsilonTree->Branch("muPlusPt", &muPlusPt, "muPlusPt/F");
	UpsilonTree->Branch("muMinusPt", &muMinusPt, "muMinusPt/F");
	UpsilonTree->Branch("muPlusEta", &muPlusEta, "muPlusEta/F");
	UpsilonTree->Branch("muMinusEta", &muMinusEta, "muMinusEta/F");
	UpsilonTree->Branch("muPlusPhi", &muPlusPhi, "muPlusPhi/F");
	UpsilonTree->Branch("muMinusPhi", &muMinusPhi, "muMinusPhi/F");
	//	UpsilonTree->Branch("theta_HX", &theta_HX, "theta_HX/F");
	//	UpsilonTree->Branch("phi_HX", &phi_HX, "phi_HX/F");
	//	UpsilonTree->Branch("theta_CS", &theta_CS, "theta_CS/F");
	//	UpsilonTree->Branch("phi_CS", &phi_CS, "phi_CS/F");

	/*
	   UpsilonTree->Branch("muPlusDxy", &muPlusDxy,"muPlusDxy/F");
	   UpsilonTree->Branch("muPlusDz", &muPlusDz,"muPlusDz/F");
	   UpsilonTree->Branch("muPlusNhits", &muPlusNhits,"muPlusNhits/I");
	   UpsilonTree->Branch("muPlusNPixelhits", &muPlusNPixelhits,"muPlusNPixelhits/I");
	   UpsilonTree->Branch("muPlusNPxlLayers", &muPlusNPxlLayers,"muPlusNPxlLayers/I");
	   UpsilonTree->Branch("muPlusInnerChi", &muPlusInnerChi,"muPlusInnerChi/F");
	   UpsilonTree->Branch("muPlusGlobalChi", &muPlusGlobalChi,"muPlusGlobalChi/F");
	   UpsilonTree->Branch("muPlusNMuonhits", &muPlusNMuonhits,"muPlusNMuonhits/I");
	   UpsilonTree->Branch("muPlusDB", &muPlusDB,"muPlusDB/F");

	   UpsilonTree->Branch("muMinusDxy", &muMinusDxy,"muMinusDxy/F");
	   UpsilonTree->Branch("muMinusDz", &muMinusDz,"muMinusDz/F");
	   UpsilonTree->Branch("muMinusNhits", &muMinusNhits,"muMinusNhits/I");
	   UpsilonTree->Branch("muMinusNPixelhits", &muMinusNPixelhits,"muMinusNPixelhits/I");
	   UpsilonTree->Branch("muMinusNPxlLayers", &muMinusNPxlLayers,"muMinusNPxlLayers/I");
	   UpsilonTree->Branch("muMinusInnerChi", &muMinusInnerChi,"muMinusInnerChi/F");
	   UpsilonTree->Branch("muMinusGlobalChi", &muMinusGlobalChi,"muMinusGlobalChi/F");
	   UpsilonTree->Branch("muMinusNMuonhits", &muMinusNMuonhits,"muMinusNMuonhits/I");
	   UpsilonTree->Branch("muMinusDB", &muMinusDB,"muMinusDB/F");
	 */
	UpsilonTree_allsign->Branch("Centrality",    &Centrality,    "Centrality/I");
	UpsilonTree_allsign->Branch("HLTriggers",    &HLTriggers,    "HLTriggers/I");
	UpsilonTree_allsign->Branch("QQtrig",   &QQtrig,    "QQtrig/I");
	UpsilonTree_allsign->Branch("QQsign",   &QQsign,    "QQsign/I");
	UpsilonTree_allsign->Branch("weight",   &weight,    "weight/F");
	UpsilonTree_allsign->Branch("weight2",   &weight2,    "weight2/F");
	UpsilonTree_allsign->Branch("vProb",    &vProb,     "vProb/F");
	UpsilonTree_allsign->Branch("eventNb",    &eventNb,     "eventNb/I");
	UpsilonTree_allsign->Branch("runNb",    &runNb,     "runNb/I");
	UpsilonTree_allsign->Branch("invariantMass", &invariantMass, "invariantMass/F");
	UpsilonTree_allsign->Branch("upsPt", &upsPt, "upsPt/F");
	UpsilonTree_allsign->Branch("upsEta", &upsEta, "upsEta/F");
	UpsilonTree_allsign->Branch("upsRapidity", &upsRapidity, "upsRapidity/F");
	UpsilonTree_allsign->Branch("muPlusPt", &muPlusPt, "muPlusPt/F");
	UpsilonTree_allsign->Branch("muMinusPt", &muMinusPt, "muMinusPt/F");
	UpsilonTree_allsign->Branch("muPlusEta", &muPlusEta, "muPlusEta/F");
	UpsilonTree_allsign->Branch("muMinusEta", &muMinusEta, "muMinusEta/F");
	UpsilonTree_allsign->Branch("muPlusPhi", &muPlusPhi, "muPlusPhi/F");
	UpsilonTree_allsign->Branch("muMinusPhi", &muMinusPhi, "muMinusPhi/F");
	//	UpsilonTree_allsign->Branch("theta_HX", &theta_HX, "theta_HX/F");
	//	UpsilonTree_allsign->Branch("phi_HX", &phi_HX, "phi_HX/F");
	//	UpsilonTree_allsign->Branch("theta_CS", &theta_CS, "theta_CS/F");
	//	UpsilonTree_allsign->Branch("phi_CS", &phi_CS, "phi_CS/F");

	UpsilonTree_trkRot->Branch("Centrality",    &Centrality,    "Centrality/I");
	UpsilonTree_trkRot->Branch("HLTriggers",    &HLTriggers,    "HLTriggers/I");
	UpsilonTree_trkRot->Branch("QQtrig",   &QQtrig,    "QQtrig/I");
	UpsilonTree_trkRot->Branch("QQsign",   &QQsign,    "QQsign/I");
	UpsilonTree_trkRot->Branch("weight",   &weight,    "weight/F");
	UpsilonTree_trkRot->Branch("weight2",   &weight2,    "weight2/F");
	UpsilonTree_trkRot->Branch("vProb",    &vProb,     "vProb/F");
	UpsilonTree_trkRot->Branch("eventNb",    &eventNb,     "eventNb/I");
	UpsilonTree_trkRot->Branch("runNb",    &runNb,     "runNb/I");
	UpsilonTree_trkRot->Branch("invariantMass", &invariantMass, "invariantMass/F");
	UpsilonTree_trkRot->Branch("upsPt", &upsPt, "upsPt/F");
	UpsilonTree_trkRot->Branch("upsEta", &upsEta, "upsEta/F");
	UpsilonTree_trkRot->Branch("upsRapidity", &upsRapidity, "upsRapidity/F");
	UpsilonTree_trkRot->Branch("muPlusPt", &muPlusPt, "muPlusPt/F");
	UpsilonTree_trkRot->Branch("muMinusPt", &muMinusPt, "muMinusPt/F");
	UpsilonTree_trkRot->Branch("muPlusEta", &muPlusEta, "muPlusEta/F");
	UpsilonTree_trkRot->Branch("muMinusEta", &muMinusEta, "muMinusEta/F");
	UpsilonTree_trkRot->Branch("muPlusPhi", &muPlusPhi, "muPlusPhi/F");
	UpsilonTree_trkRot->Branch("muMinusPhi", &muMinusPhi, "muMinusPhi/F");


	for (int i=0; i<nentries; i++) {
		t->GetEntry(i);
		//nReco_QQ=0;
		if (i%1000==0) cout<<i<<endl;
		nPlusMu=0;
		nMinusMu=0;
		for(int iMu = 0; iMu < Reco_mu_size; iMu++){
			if (Reco_mu_charge[iMu] == 1) nPlusMu++;
			else nMinusMu++;
			TLorentzVector *Reco_mu = (TLorentzVector *) Reco_mu_4mom->At(iMu);
			muPt[iMu]=Reco_mu->Pt();
			muEta[iMu]=Reco_mu->Eta();
			muPhi[iMu]=Reco_mu->Phi();
		}
		MuTree->Fill();

		for(int iQQ = 0; iQQ < Reco_QQ_size; iQQ++){
			//eventNb=eventNb[iQQ];
			//runNb=runNb[iQQ];
			vProb = Reco_QQ_VtxProb[iQQ];
			QQtrig = Reco_QQ_trig[iQQ];
			QQsign = Reco_QQ_sign[iQQ];
			if (Reco_QQ_sign[iQQ] == 0) { 
				weight = 1;
				weight2 = 1;
			}
			else {
				weight = -1;
				float likesign_comb = (float)nPlusMu*(nPlusMu-1.0)/2.0+(float)nMinusMu*(nMinusMu-1.0)/2.0;
				float unlikesign_bkgd_comb = (float)nPlusMu*nMinusMu - (nPlusMu>nMinusMu?nMinusMu:nPlusMu);
				weight2 = -1.0 * unlikesign_bkgd_comb/likesign_comb;
			}

			TLorentzVector *Reco_QQ = (TLorentzVector *) Reco_QQ_4mom->At(iQQ);
			TLorentzVector *Reco_QQ_mupl = (TLorentzVector *) Reco_QQ_mupl_4mom->At(iQQ);
			TLorentzVector *Reco_QQ_mumi = (TLorentzVector *) Reco_QQ_mumi_4mom->At(iQQ);
			invariantMass=Reco_QQ->M();
			upsPt=Reco_QQ->Pt();
			upsEta=Reco_QQ->Eta();
			upsRapidity=Reco_QQ->Rapidity();
			muMinusPt=Reco_QQ_mumi->Pt();
			muMinusEta=Reco_QQ_mumi->Eta();
			muMinusPhi=Reco_QQ_mumi->Phi();
			muPlusPt=Reco_QQ_mupl->Pt();
			muPlusEta=Reco_QQ_mupl->Eta();
			muPlusPhi=Reco_QQ_mupl->Phi();
			//	theta_HX = GetAngles_HX(*Reco_QQ_mupl,*Reco_QQ_mumi).first;
			//	phi_HX = GetAngles_HX(*Reco_QQ_mupl,*Reco_QQ_mumi).second;
			//	theta_CS = GetAngles_CS(*Reco_QQ_mupl,*Reco_QQ_mumi).first;
			//	phi_CS = GetAngles_CS(*Reco_QQ_mupl,*Reco_QQ_mumi).second;

			muPlusDxy=QQmuPlusDxy[iQQ];
			muPlusDz=QQmuPlusDz[iQQ];
			muPlusNhits=QQmuPlusNhits[iQQ];
			muPlusNPixelhits=QQmuPlusNPixelhits[iQQ];
			muPlusNPxlLayers=QQmuPlusNPxlLayers[iQQ];
			muPlusInnerChi=QQmuPlusInnerChi[iQQ];
			muPlusGlobalChi=QQmuPlusGlobalChi[iQQ];
			muPlusNMuonhits=QQmuPlusNMuonhits[iQQ];
			muPlusDB=QQmuPlusDB[iQQ];

			muMinusDxy=QQmuMinusDxy[iQQ];
			muMinusDz=QQmuMinusDz[iQQ];
			muMinusNhits=QQmuMinusNhits[iQQ];
			muMinusNPixelhits=QQmuMinusNPixelhits[iQQ];
			muMinusNPxlLayers=QQmuMinusNPxlLayers[iQQ];
			muMinusInnerChi=QQmuMinusInnerChi[iQQ];
			muMinusGlobalChi=QQmuMinusGlobalChi[iQQ];
			muMinusNMuonhits=QQmuMinusNMuonhits[iQQ];
			muMinusDB=QQmuMinusDB[iQQ];
			/*
			   if (fabs(muPlusDxy)<3 && fabs(muPlusDz)<15 
			   && muPlusNhits>10 && muPlusNPxlLayers>0 && muPlusNMuonhits>6 
			   && muPlusInnerChi<4 && muPlusGlobalChi<6
			   && fabs(muMinusDxy)<3 && fabs(muMinusDz)<15 
			   && muMinusNhits>10 && muMinusNPxlLayers>0 && muMinusNMuonhits>6 
			   && muMinusInnerChi<4 && muMinusGlobalChi<6 
			   && vProb>0.01) 

			   if (fabs(muPlusDxy)<3 && fabs(muPlusDz)<15 
			   && muPlusNhits>10 && muPlusNPxlLayers>0 && muPlusNMuonhits>12 
			   && muPlusInnerChi<2.1 && muPlusGlobalChi<2.7
			   && fabs(muMinusDxy)<3 && fabs(muMinusDz)<15 
			   && muMinusNhits>10 && muMinusNPxlLayers>0 && muMinusNMuonhits>12 
			   && muMinusInnerChi<2.1 && muMinusGlobalChi<2.7 
			   && vProb>0.19) 
			 */

			if ((HLTriggers&1)==1 && (Reco_QQ_trig[iQQ]&1)==1 && (Reco_QQ_type[iQQ]<3) 
			   )
			{
				UpsilonTree_allsign->Fill();
				if (Reco_QQ_sign[iQQ]==0) {
					UpsilonTree->Fill();
					if (Reco_QQ->M()>8.5 && Reco_QQ->M()<11.5) {
						h_QQ_mass->Fill(Reco_QQ->M());
					}
					if (Reco_QQ_mupl->Pt()>=ptcut && Reco_QQ_mumi->Pt()>=ptcut && Reco_QQ->M()>8.5 && Reco_QQ->M()<11.5) {
						h_QQ_mass_1->Fill(Reco_QQ->M());
					}
				}
				else if (Reco_QQ_mupl->Pt()>=ptcut && Reco_QQ_mumi->Pt()>=ptcut && Reco_QQ->M()>8.5 && Reco_QQ->M()<11.5) {
					h_QQ_mass_2->Fill(Reco_QQ->M());
				}

				//track rotation
				Double_t ran = gRandom->Rndm();

				if(ran < 0.5 ) RmuPlusPhi = muPlusPhi + TMath::Pi();
				else  RmuMinusPhi = muMinusPhi + TMath::Pi();

				TLorentzVector mu1;
				mu1.SetPtEtaPhiM( muPlusPt, muPlusEta, RmuPlusPhi, 0.105);
				TLorentzVector mu2;
				mu2.SetPtEtaPhiM( muMinusPt, muMinusEta, RmuMinusPhi, 0.105);

				TLorentzVector dimuon;
				dimuon = mu1 + mu2;

				invariantMass=dimuon.M();
				upsPt=dimuon.Pt();
				upsEta=dimuon.Eta();
				upsRapidity=dimuon.Rapidity();

				if ((HLTriggers&1)==2 && (Reco_QQ_trig[iQQ]&1)==1 && (Reco_QQ_type[iQQ]==0)
				   )
				{
					UpsilonTree_trkRot->Fill();
				}

				/*
				   for (int k=0;k<10;k++){
				//track rotation
				//if(ran < 0.5 ) RmuPlusPhi = muPlusPhi + TMath::Pi();
				//else  RmuMinusPhi = muMinusPhi + TMath::Pi();
				Double_t ran = gRandom->Rndm();

				if (k<5) {
				muMinusPhi = muMinusPhi + TMath::Pi()*ran;
				}   
				else {
				muPlusPhi = muPlusPhi + TMath::Pi()*ran;
				}   

				TLorentzVector mu1;
				mu1.SetPtEtaPhiM( muPlusPt, muPlusEta, muPlusPhi, 0.105);
				TLorentzVector mu2;
				mu2.SetPtEtaPhiM( muMinusPt, muMinusEta, muMinusPhi, 0.105);

				TLorentzVector dimuon;
				dimuon = mu1 + mu2;

				invariantMass=dimuon.M();
				upsPt=dimuon.Pt();
				upsEta=dimuon.Eta();
				upsRapidity=dimuon.Rapidity();

				UpsilonTree_trkRot->Fill();
				} 
				 */  
			}
		}		//	UpsilonTree->Fill();
	}

	gROOT->SetStyle("Plain");
	gStyle->SetPalette(1);
	gStyle->SetFrameBorderMode(0);
	gStyle->SetFrameFillColor(0);
	gStyle->SetCanvasColor(0);
	gStyle->SetTitleFillColor(0);
	gStyle->SetStatColor(0);
	gStyle->SetPadBorderSize(0);
	gStyle->SetCanvasBorderSize(0);
	gStyle->SetOptTitle(0); // at least most of the time
	gStyle->SetOptStat(0); // most of the time, sometimes "nemriou" might be useful to display name, number of entries, mean, rms, integral, overflow and underflow
	gStyle->SetOptFit(0); // set to 1 only if you want to display fit results

	TCanvas *c1 = new TCanvas("c1","c1");
	//h_QQ_mass->GetYaxis()->SetRangeUser(0,180);
	h_QQ_mass->SetMarkerColor(kRed);
	h_QQ_mass->SetMarkerStyle(22);
	h_QQ_mass->SetXTitle("m_{#mu#mu} (GeV/c^{2})");
	h_QQ_mass->SetYTitle("Events/(0.1 GeV/c^{2})");
	h_QQ_mass->Draw("PE");

	h_QQ_mass_1->SetMarkerColor(kBlue);
	h_QQ_mass_1->SetMarkerStyle(20);
	h_QQ_mass_1->GetXaxis()->CenterTitle(kTRUE);
	h_QQ_mass_1->SetXTitle("m_{#mu#mu} (GeV/c^{2})");
	h_QQ_mass_1->SetYTitle("Events/(0.1 GeV/c^{2})");
	h_QQ_mass_1->Draw("PEsame");

	//h_QQ_mass_2->GetYaxis()->SetRangeUser(0,400);
	h_QQ_mass_2->SetMarkerColor(kRed);
	h_QQ_mass_2->SetMarkerStyle(24);
	h_QQ_mass_2->GetXaxis()->CenterTitle(kTRUE);
	h_QQ_mass_2->SetXTitle("m_{#mu#mu} (GeV/c^{2})");
	h_QQ_mass_2->SetYTitle("Events/(0.1 MeV/c^{2})");
	h_QQ_mass_2->Draw("PEsame");

	TLegend *legend = new TLegend(.5,.7,.9,.9);
	legend->AddEntry(h_QQ_mass,"N_{#mu^{+}#mu^{-}} acceptance cut","P");
	legend->AddEntry(h_QQ_mass_1,"Unlike-Sign, N_{#mu^{+}#mu^{-}}","P");
	legend->AddEntry(h_QQ_mass_2,"Like-sign, N_{#mu^{+}#mu^{+}}+N_{#mu^{-}#mu^{-}}","P");
	legend->AddEntry((TObject*)0,"#mu p_{T} > 3 GeV/c","");
	legend->Draw();

	h_QQ_mass->Write();
	h_QQ_mass_1->Write();
	h_QQ_mass_2->Write();
	c1->SaveAs("dimuon_likesign_pt4.pdf");
	c1->SaveAs("dimuon_likesign_pt4.gif");
	c1->Write();
	f1->Write();

}
コード例 #15
0
ファイル: kanaelec.C プロジェクト: kalanand/UserCode
void kanaelec::Loop(int wda, int wsp, const char *outfilename)
{
  if (fChain == 0) return;
  Long64_t nentries = fChain->GetEntries();
  // Out Put File Here
  TFile fresults = TFile(outfilename,"RECREATE");
  TTree *newtree = fChain->CloneTree();
  
  Float_t fit_mu_px=0,   fit_mu_py =0,   fit_mu_pz=0,   fit_mu_e=0;
  Float_t fit_nv_px=0,   fit_nv_py =0,   fit_nv_pz=0,   fit_nv_e=0;
  Float_t fit_aj_px=0,   fit_aj_py =0,   fit_aj_pz=0,   fit_aj_e=0;
  Float_t fit_bj_px=0,   fit_bj_py =0,   fit_bj_pz=0,   fit_bj_e=0;
  Float_t fit_mlvjj=0,   fit_chi2  =999;  
  Int_t   fit_NDF  =999, fit_status=999, gdevtt   =0;

  TBranch *branch_mu_px = newtree->Branch("fit_el_px", &fit_mu_px,  "fit_el_px/F");
  TBranch *branch_mu_py = newtree->Branch("fit_el_py", &fit_mu_py,  "fit_el_py/F");
  TBranch *branch_mu_pz = newtree->Branch("fit_el_pz", &fit_mu_pz,  "fit_el_pz/F");
  TBranch *branch_mu_e  = newtree->Branch("fit_el_e",  &fit_mu_e,   "fit_el_e/F");
  	   
  TBranch *branch_nv_px = newtree->Branch("fit_nv_px", &fit_nv_px,  "fit_nv_px/F");
  TBranch *branch_nv_py = newtree->Branch("fit_nv_py", &fit_nv_py,  "fit_nv_py/F");
  TBranch *branch_nv_pz = newtree->Branch("fit_nv_pz", &fit_nv_pz,  "fit_nv_pz/F");
  TBranch *branch_nv_e  = newtree->Branch("fit_nv_e",  &fit_nv_e,   "fit_nv_e/F");
  	   
  TBranch *branch_aj_px = newtree->Branch("fit_aj_px", &fit_aj_px,  "fit_aj_px/F");
  TBranch *branch_aj_py = newtree->Branch("fit_aj_py", &fit_aj_py,  "fit_aj_py/F");
  TBranch *branch_aj_pz = newtree->Branch("fit_aj_pz", &fit_aj_pz,  "fit_aj_pz/F");
  TBranch *branch_aj_e  = newtree->Branch("fit_aj_e",  &fit_aj_e,   "fit_aj_e/F");
  	   
  TBranch *branch_bj_px = newtree->Branch("fit_bj_px", &fit_bj_px,  "fit_bj_px/F");
  TBranch *branch_bj_py = newtree->Branch("fit_bj_py", &fit_bj_py,  "fit_bj_py/F");
  TBranch *branch_bj_pz = newtree->Branch("fit_bj_pz", &fit_bj_pz,  "fit_bj_pz/F");
  TBranch *branch_bj_e  = newtree->Branch("fit_bj_e",  &fit_bj_e,   "fit_bj_e/F");
  
  TBranch *branch_mlvjj = newtree->Branch("fit_mlvjj", &fit_mlvjj,  "fit_mlvjj/F");
  TBranch *branch_chi2  = newtree->Branch("fit_chi2",  &fit_chi2,   "fit_chi2/F");
  TBranch *branch_NDF   = newtree->Branch("fit_NDF",   &fit_NDF,    "fit_NDF/I");
  TBranch *branch_status= newtree->Branch("fit_status",&fit_status, "fit_status/I");
  TBranch *branch_gdevtt= newtree->Branch("gdevtt",    &gdevtt,     "gdevtt/I");

  Float_t fi2_mu_px=0,   fi2_mu_py =0,   fi2_mu_pz=0,   fi2_mu_e=0;
  Float_t fi2_nv_px=0,   fi2_nv_py =0,   fi2_nv_pz=0,   fi2_nv_e=0;
  Float_t fi2_aj_px=0,   fi2_aj_py =0,   fi2_aj_pz=0,   fi2_aj_e=0;
  Float_t fi2_bj_px=0,   fi2_bj_py =0,   fi2_bj_pz=0,   fi2_bj_e=0;
  Float_t fi2_mlvjj=0,   fi2_chi2  =999;  
  Int_t   fi2_NDF  =999, fi2_status=999;

  TBranch *branc2_mu_px = newtree->Branch("fi2_el_px", &fi2_mu_px,  "fi2_el_px/F");
  TBranch *branc2_mu_py = newtree->Branch("fi2_el_py", &fi2_mu_py,  "fi2_el_py/F");
  TBranch *branc2_mu_pz = newtree->Branch("fi2_el_pz", &fi2_mu_pz,  "fi2_el_pz/F");
  TBranch *branc2_mu_e  = newtree->Branch("fi2_el_e",  &fi2_mu_e,   "fi2_el_e/F");
  	   
  TBranch *branc2_nv_px = newtree->Branch("fi2_nv_px", &fi2_nv_px,  "fi2_nv_px/F");
  TBranch *branc2_nv_py = newtree->Branch("fi2_nv_py", &fi2_nv_py,  "fi2_nv_py/F");
  TBranch *branc2_nv_pz = newtree->Branch("fi2_nv_pz", &fi2_nv_pz,  "fi2_nv_pz/F");
  TBranch *branc2_nv_e  = newtree->Branch("fi2_nv_e",  &fi2_nv_e,   "fi2_nv_e/F");
  	   
  TBranch *branc2_aj_px = newtree->Branch("fi2_aj_px", &fi2_aj_px,  "fi2_aj_px/F");
  TBranch *branc2_aj_py = newtree->Branch("fi2_aj_py", &fi2_aj_py,  "fi2_aj_py/F");
  TBranch *branc2_aj_pz = newtree->Branch("fi2_aj_pz", &fi2_aj_pz,  "fi2_aj_pz/F");
  TBranch *branc2_aj_e  = newtree->Branch("fi2_aj_e",  &fi2_aj_e,   "fi2_aj_e/F");
  	   
  TBranch *branc2_bj_px = newtree->Branch("fi2_bj_px", &fi2_bj_px,  "fi2_bj_px/F");
  TBranch *branc2_bj_py = newtree->Branch("fi2_bj_py", &fi2_bj_py,  "fi2_bj_py/F");
  TBranch *branc2_bj_pz = newtree->Branch("fi2_bj_pz", &fi2_bj_pz,  "fi2_bj_pz/F");
  TBranch *branc2_bj_e  = newtree->Branch("fi2_bj_e",  &fi2_bj_e,   "fi2_bj_e/F");
  
  TBranch *branc2_mlvjj = newtree->Branch("fi2_mlvjj", &fi2_mlvjj,  "fi2_mlvjj/F");
  TBranch *branc2_chi2  = newtree->Branch("fi2_chi2",  &fi2_chi2,   "fi2_chi2/F");
  TBranch *branc2_NDF   = newtree->Branch("fi2_NDF",   &fi2_NDF,    "fi2_NDF/I");
  TBranch *branc2_status= newtree->Branch("fi2_status",&fi2_status, "fi2_status/I");

  // Loop over all events
  Long64_t nbytes = 0, nb = 0;
  for (Long64_t jentry=0; jentry<nentries;jentry++) {
    //Long64_t ientry = LoadTree(jentry);
    //if (ientry < 0) break;
    nb = newtree->GetEntry(jentry);   nbytes += nb;
    // Cut variable definitions
    double jess    = 1.00; // control the jet energy scale
    //double muoniso = (W_muon_trackiso+W_muon_hcaliso+W_muon_ecaliso-event_RhoForLeptonIsolation*3.141592653589*0.09)/W_muon_pt;
    double dijetpt = sqrt(JetPFCor_Pt[0]*JetPFCor_Pt[0]+
			  JetPFCor_Pt[1]*JetPFCor_Pt[1]+
			  2*JetPFCor_Pt[0]*JetPFCor_Pt[1]*cos(JetPFCor_Phi[0]-JetPFCor_Phi[1]));

    // Save variable initialization
    fit_mu_px = 0; fit_mu_py = 0; fit_mu_pz = 0;  fit_mu_e  = 0; 
    fit_nv_px = 0; fit_nv_py = 0; fit_nv_pz = 0;  fit_nv_e  = 0; 
    fit_aj_px = 0; fit_aj_py = 0; fit_aj_pz = 0;  fit_aj_e  = 0; 
    fit_bj_px = 0; fit_bj_py = 0; fit_bj_pz = 0;  fit_bj_e  = 0; 
    fit_mlvjj = 0; fit_chi2  =999;fit_NDF   =999; fit_status=999;

    gdevtt    = 0;

    fi2_mu_px = 0; fi2_mu_py = 0; fi2_mu_pz = 0;  fi2_mu_e  = 0; 
    fi2_nv_px = 0; fi2_nv_py = 0; fi2_nv_pz = 0;  fi2_nv_e  = 0; 
    fi2_aj_px = 0; fi2_aj_py = 0; fi2_aj_pz = 0;  fi2_aj_e  = 0; 
    fi2_bj_px = 0; fi2_bj_py = 0; fi2_bj_pz = 0;  fi2_bj_e  = 0; 
    fi2_mlvjj = 0; fi2_chi2  =999;fi2_NDF   =999; fi2_status=999;

    // Good Event Selection Requirement
    if (JetPFCor_Pt[0]>30. 
	&& JetPFCor_Pt[1]>30. 
	&& JetPFCor_Pt[2]<0.5 
	&& abs(JetPFCor_Eta[0]-JetPFCor_Eta[1])<1.5 
	&& W_electron_et>30. 
	&& W_electron_isWP80==1 
	&& (W_electron_trackiso+W_electron_hcaliso+W_electron_ecaliso-event_RhoForLeptonIsolation*3.141592653589*0.09)/W_electron_pt<0.05 
	&& ((abs(W_electron_eta)<1.5 && abs(W_electron_deltaphi_in)<0.03 && abs(W_electron_deltaeta_in)<0.004) || (abs(W_electron_eta)>1.5 && abs(W_electron_deltaphi_in)<0.02 && abs(W_electron_deltaeta_in)<0.005)) 
	&& sqrt((W_electron_vx-event_BeamSpot_x)*(W_electron_vx-event_BeamSpot_x)+(W_electron_vy-event_BeamSpot_y)*(W_electron_vy-event_BeamSpot_y))<0.02 
	&& JetPFCor_bDiscriminator[0]<1.19 
	&& JetPFCor_bDiscriminator[1]<1.19 
	&& cosJacksonAngle2j_PFCor<0.8 
	&& cosJacksonAngle2j_PFCor>-0.6 
	&& event_met_pfmet>30. 
	&& W_mt>40.
	&& dijetpt > 40.	)      {
      gdevtt = 1;
      // Do the kinematic fit for all event!!!
      int Aj = 0, Bj = 1;    TLorentzVector  mup, nvp, ajp, bjp; 
      mup.SetPtEtaPhiE(W_electron_pt,      W_electron_eta,   W_electron_phi,   W_electron_e               );
      nvp.SetPxPyPzE(event_met_pfmet * cos(event_met_pfmetPhi), event_met_pfmet * sin(event_met_pfmetPhi), 
		     W_pzNu1, sqrt(event_met_pfmet*event_met_pfmet + W_pzNu1*W_pzNu1)                     );
      ajp.SetPtEtaPhiE(jess * JetPFCor_Pt[Aj], JetPFCor_Eta[Aj], JetPFCor_Phi[Aj], jess * JetPFCor_E[Aj]  );
      bjp.SetPtEtaPhiE(jess * JetPFCor_Pt[Bj], JetPFCor_Eta[Bj], JetPFCor_Phi[Bj], jess * JetPFCor_E[Bj]  );
      
      TLorentzVector fit_mup(0,0,0,0), fit_nvp(0,0,0,0), fit_ajp(0,0,0,0), fit_bjp(0,0,0,0) ; 
      doKinematicFit( 1, mup, nvp, ajp, bjp,  fit_mup, fit_nvp, fit_ajp, fit_bjp, fit_chi2, fit_NDF, fit_status);
      fit_mu_px = fit_mup.Px(); fit_mu_py = fit_mup.Py(); fit_mu_pz = fit_mup.Pz(); fit_mu_e = fit_mup.E(); 
      fit_nv_px = fit_nvp.Px(); fit_nv_py = fit_nvp.Py(); fit_nv_pz = fit_nvp.Pz(); fit_nv_e = fit_nvp.E(); 
      fit_aj_px = fit_ajp.Px(); fit_aj_py = fit_ajp.Py(); fit_aj_pz = fit_ajp.Pz(); fit_aj_e = fit_ajp.E(); 
      fit_bj_px = fit_bjp.Px(); fit_bj_py = fit_bjp.Py(); fit_bj_pz = fit_bjp.Pz(); fit_bj_e = fit_bjp.E(); 
      fit_mlvjj = (fit_mup+fit_nvp+fit_ajp+fit_bjp).M();

      TLorentzVector fi2_mup(0,0,0,0), fi2_nvp(0,0,0,0), fi2_ajp(0,0,0,0), fi2_bjp(0,0,0,0) ; 
      doKinematicFit( 2, mup, nvp, ajp, bjp,  fi2_mup, fi2_nvp, fi2_ajp, fi2_bjp, fi2_chi2, fi2_NDF, fi2_status);
      fi2_mu_px = fi2_mup.Px(); fi2_mu_py = fi2_mup.Py(); fi2_mu_pz = fi2_mup.Pz(); fi2_mu_e = fi2_mup.E(); 
      fi2_nv_px = fi2_nvp.Px(); fi2_nv_py = fi2_nvp.Py(); fi2_nv_pz = fi2_nvp.Pz(); fi2_nv_e = fi2_nvp.E(); 
      fi2_aj_px = fi2_ajp.Px(); fi2_aj_py = fi2_ajp.Py(); fi2_aj_pz = fi2_ajp.Pz(); fi2_aj_e = fi2_ajp.E(); 
      fi2_bj_px = fi2_bjp.Px(); fi2_bj_py = fi2_bjp.Py(); fi2_bj_pz = fi2_bjp.Pz(); fi2_bj_e = fi2_bjp.E(); 
      fi2_mlvjj = (fi2_mup+fi2_nvp+fi2_ajp+fi2_bjp).M();
    }	 // Only Good event will be performed kinematic fit
    branch_mu_px->Fill();
    branch_mu_py->Fill();
    branch_mu_pz->Fill();
    branch_mu_e ->Fill();
    
    branch_nv_px->Fill();
    branch_nv_py->Fill();
    branch_nv_pz->Fill();
    branch_nv_e ->Fill();
    
    branch_aj_px->Fill();
    branch_aj_py->Fill();
    branch_aj_pz->Fill();
    branch_aj_e ->Fill();
    
    branch_bj_px->Fill();
    branch_bj_py->Fill();
    branch_bj_pz->Fill();
    branch_bj_e ->Fill();
   
    branch_mlvjj->Fill();
    branch_chi2 ->Fill();
    branch_NDF  ->Fill();
    branch_status->Fill();

    branch_gdevtt->Fill();

    branc2_mu_px->Fill();
    branc2_mu_py->Fill();
    branc2_mu_pz->Fill();
    branc2_mu_e ->Fill();
    
    branc2_nv_px->Fill();
    branc2_nv_py->Fill();
    branc2_nv_pz->Fill();
    branc2_nv_e ->Fill();
    
    branc2_aj_px->Fill();
    branc2_aj_py->Fill();
    branc2_aj_pz->Fill();
    branc2_aj_e ->Fill();
    
    branc2_bj_px->Fill();
    branc2_bj_py->Fill();
    branc2_bj_pz->Fill();
    branc2_bj_e ->Fill();
   
    branc2_mlvjj->Fill();
    branc2_chi2 ->Fill();
    branc2_NDF  ->Fill();
    branc2_status->Fill();
  } // end event loop
  fresults.cd();
  newtree->Write("WJet");
  fresults.Close();
  std::cout <<  wda << "-" << wsp << "   ::   " << outfilename << "    "<< nentries  << std::endl;
  
}
コード例 #16
0
/*
EXAMPLE
root
.L particleDrawer.C++
particleDrawer("../test/test.root",11,2)
 */
void particleDrawer(TString filename, int entry = 0, int PVAssoc = 2, bool debug = false) {

   cout << "particleDrawer::Setting the TDR style ... ";
   setTDRStyle();
   cout << "DONE" << endl;

   cout << "particleDrawer::Drawing the default (TDR) frame ... " << endl;
   TH1D* frame = new TH1D();
   frame->GetXaxis()->SetLimits(-5,5);
   frame->GetXaxis()->SetTitle("#eta");
   frame->GetYaxis()->SetRangeUser(-TMath::Pi(),TMath::Pi());
   frame->GetYaxis()->SetTitle("#phi");
   TCanvas* c = tdrCanvas("particleBasedEvent",frame,4,0,true);
   c->GetPad(0)->SetLogz();
   cout << "\r\r\r\r\r\r" << flush;
   cout << setw(52) << " " << "DONE" << endl << endl;

   cout << "particleDrawer::Opening the input file (" << filename << " ) ... ";
   TFile* inFile = TFile::Open(filename,"READ");
   assert(inFile!=NULL);
   cout << "DONE" << endl;

   cout << "particleDrawer::Getting the input trees ... ";
   TTree* puppiTree = (TTree*)inFile->Get("puppiReader/puppiTree");
   assert(puppiTree!=NULL);
   TTree* jetTree = (TTree*)inFile->Get("nt_AK4PFchs/t");
   assert(jetTree!=NULL);
   cout << "DONE" << endl;

   cout << "particleDrawer::Making the ntuples ... ";
   puppiNtuple*     pNtuple = new puppiNtuple(puppiTree);
   validatorNtuple* jNtuple = new validatorNtuple(jetTree);
   cout << "DONE" << endl;

   cout << "particleDrawer::Getting entry " << entry << " for puppiTree ... ";
   puppiTree->GetEntry(entry);
   cout << "DONE" << endl;

   cout << "particleDrawer::Filling the histograms ... ";
   TH2F* hPU = new TH2F("hPU","hPU",50,-5,5,60,-TMath::Pi(),TMath::Pi());
   TH2F* hHard = new TH2F("hHard","hHard",50,-5,5,60,-TMath::Pi(),TMath::Pi());

   for(unsigned int iparticle=0; iparticle<(*pNtuple->px).size(); iparticle++) {
      TLorentzVector tempVect((*pNtuple->px)[iparticle],(*pNtuple->py)[iparticle],
                              (*pNtuple->pz)[iparticle],(*pNtuple->e)[iparticle]);

      if((*pNtuple->fromPV)[iparticle]<PVAssoc) {
         if(debug) cout << "Filling PU::fromPV = " << (*pNtuple->fromPV)[iparticle] << endl;
         hPU->Fill(tempVect.Eta(),tempVect.Phi(),tempVect.Pt());
      }
      else {
         if(debug) cout << "Filling hard-scatter:: fromPV = " << (*pNtuple->fromPV)[iparticle] << endl;
         hHard->Fill(tempVect.Eta(),tempVect.Phi(),tempVect.Pt());
      }
   }
   if(debug) {
      cout << "hPU->GetEntries() = " << hPU->GetEntries() << endl;
      cout << "hHard->GetEntries() = " << hHard->GetEntries() << endl;
   }
   else
      cout << "DONE" << endl;

   cout << "particleDrawer::Drawing the histograms ... ";
   //tdrDraw(hPU,"BOX",kFullSquare,kNone,kSolid,kGray,kNone,kNone);
   //tdrDraw(hHard,"colz");
   THStack* stack = new THStack("stack","stack");
   hPU->SetLineStyle(kSolid);
   hPU->SetLineColor(kGray);
   hPU->SetFillStyle(1001);
   hPU->SetFillColor(kNone);
   hPU->SetMarkerStyle(kFullSquare);
   hPU->SetMarkerColor(kNone);
   if(hHard->GetEntries()>0)
      stack->Add(hHard,"colz");
   if(hPU->GetEntries()>0)
      stack->Add(hPU,"BOX");
   tdrDraw(stack,"nostack");

   set_plot_style();
   c->Update();
   c->RedrawAxis();
   cout << "DONE" << endl;

   cout << "particleDrawer::Getting entry " << entry << " for jetTree ... ";
   jetTree->GetEntry(entry);
   cout << "DONE" << endl;

   cout << "particleDrawer::Drawing the jets ... " << endl;
   vector<JetCircle> jets;
   for(unsigned int ijet=0; ijet<jNtuple->nref; ijet++) {
      if((*jNtuple->jtpt)[ijet]<20) continue;
      double RJet = TMath::Sqrt((*jNtuple->jtarea)[ijet]/TMath::Pi());
      jets.push_back(JetCircle((*jNtuple->jteta)[ijet],(*jNtuple->jtphi)[ijet],RJet,(*jNtuple->jtpt)[ijet]));
   }
   for(unsigned int ijet=0; ijet<jets.size(); ijet++) {
      for(unsigned int jjet=ijet+1; jjet<jets.size(); jjet++) {
         if(check_overlap(jets[ijet].getX(),jets[ijet].getY(),jets[ijet].getRadius(),
                          jets[jjet].getX(),jets[jjet].getY(),jets[jjet].getRadius())) {
            cout << "Jet " << ijet << " overlaps with jet " << jjet << endl;
            if(jets[ijet].getPt()>jets[jjet].getPt()) {
               //find angle for jjet;
               jets[jjet].findAngles(jets[ijet]);               
            }
            else if(jets[ijet].getPt()<jets[jjet].getPt()) {
               //find angle for ijet
               jets[ijet].findAngles(jets[jjet]);
            }
            else {
               //must find angle for both jets
               //then must draw a straight line between the two intersection points
               jets[jjet].findAngles(jets[ijet]);
               jets[ijet].findAngles(jets[jjet]);
               //NEED TO COMPLETE THIS FUNCTION. CURRENTLY DOESNOT DRAW LINE BETWEEN THE JETS.
            }
            cout << "Jet " << ijet << ": \n" << jets[ijet] << endl;
            cout << "Jet " << jjet << ": \n" << jets[jjet] << endl;
         }
      }
   }
   for(unsigned int ijet=0; ijet<jets.size(); ijet++) {
      loadbar2(ijet+1, jets.size());
      TEllipse* cJet = new TEllipse(jets[ijet].getX(),jets[ijet].getY(),
                                    jets[ijet].getRadius(),jets[ijet].getRadius(),
                                    jets[ijet].getStartAngle(),jets[ijet].getEndAngle());
      cJet->SetFillStyle(0);
      cJet->SetFillColor(kNone);
      cJet->SetLineStyle(kSolid);
      cJet->SetLineColor(kRed);
      cJet->SetLineWidth(3);
      cJet->Draw("only same");
   }
   //cout << "\r\r\r\r" << flush;
   //cout << setw(37) << " " << "DONE" << endl << endl;

   cout << "particleDrawer::Saving the canvas ... ";
   TString name = Form("particleMap_entry%i_PVAssoc%i",entry,PVAssoc);
   c->SaveAs(name+".png");
   c->SaveAs(name+".pdf");
   c->SaveAs(name+".C");
   cout << "DONE" << endl;
}
コード例 #17
0
void SkimClassification(TString process="ZnnH125")
{
    gROOT->LoadMacro("HelperFunctions.h" );  // make functions visible to TTreeFormula
    gROOT->SetBatch(1);

    //TChain * chain  = new TChain("tree");
    //TString fname   = "";
    //TString dijet   = "DiJetPt_";
    //TString dirMC   = "dcache:/pnfs/cms/WAX/resilient/jiafu/ZnunuHbb/" + tagMC + "/";
    //TString dirData = "dcache:/pnfs/cms/WAX/resilient/jiafu/ZnunuHbb/" + tagData + "/";
    TString indir   = "/afs/cern.ch/work/d/degrutto/public/MiniAOD/ZnnHbb_Spring15_PU20bx25/skimV12_v2/step3/";
    TString outdir  = "/afs/cern.ch/work/d/degrutto/public/MiniAOD/ZnnHbb_Spring15_PU20bx25/skimV12_v2/step3/skim_ZnnH_classification/";
    TString prefix  = "Step3_";
    TString suffix  = ".root";

    TFile *input = TFile::Open(indir + prefix + process + suffix);
    if (!input) {
        std::cout << "ERROR: Could not open input file." << std::endl;
        exit(1);
    }
    TTree *tree   = (TTree *) input->Get("tree");
    Long64_t entries = tree->GetEntriesFast();
    
    // Make output directory if it doesn't exist
    if (gSystem->AccessPathName(outdir))
        gSystem->mkdir(outdir);
    TString outname = outdir + prefix + Form("%s.root", process.Data());

    TFile* output = TFile::Open(outname, "RECREATE");

    // Get selections
    const std::vector < std::string > & selExpressions = GetSelExpressions("ZnunuHighPt") ;
    //    const UInt_t nsels = 3;  // ZnunuHighPt, ZnunuLowPt, ZnunuLowCSV
    const UInt_t nsels = 1;  // just one now...  ZnunuHighPt, ZnunuLowPt, ZnunuLowCSV

    //    assert(nsels == selExpressions.size()); <-- fixME
    // even-number events for training, odd-number events for testing
    TCut evenselection = "evt  %2 == 0";
    TCut oddselection  = "evt %2 == 1";

    TTreeFormula *ttf = 0;
    std::vector < TTreeFormula * >::const_iterator formIt, formItEnd;

    // Loop over selections
    std::vector<Long64_t> ventries;
    for (unsigned int i = 0; i < nsels; i++) {
        TString selname = "ZnunuHighPt";
        if (i == 1) {
            selname = "ZnunuMedPt";
	    //	    selExpressions = GetSelExpressions("ZnunuMedPt") ;
        } else if (i == 2) {
            selname = "ZnunuLowPt";
	    // selExpressions = GetSelExpressions("ZnunuLowPt") ;
        }

        TTree *t1 = (TTree*) tree->CloneTree(0);
        TTree *t2 = (TTree*) tree->CloneTree(0);
        
        t1->SetName(TString::Format("%s_%s_train", tree->GetName(), selname.Data()));
        t2->SetName(TString::Format("%s_%s", tree->GetName(), selname.Data()));
        
        // The clones should not delete any shared i/o buffers.
        ResetDeleteBranches(t1);
        ResetDeleteBranches(t2);
        
        ttf = new TTreeFormula(Form("ttfsel%i", i), selExpressions.at(i).c_str(), tree);
        ttf->SetQuickLoad(1);
        TTreeFormula *ttf1 = new TTreeFormula(Form("ttfeven%i", i), evenselection, tree);
        ttf1->SetQuickLoad(1);
        TTreeFormula *ttf2 = new TTreeFormula(Form("ttfodd%i", i), oddselection, tree);
        ttf2->SetQuickLoad(1);
        if (!ttf || !ttf->GetNdim()) {
            std::cerr << "ERROR: Failed to find any TTree variable from the selection: " << selExpressions.at(i) << std::endl;
            return;
        }

        
        /// Loop over events
        Int_t curTree = tree->GetTreeNumber();
        const Long64_t nentries = tree->GetEntries();
        for (Long64_t ievt = 0; ievt < nentries; ievt++) {
            Long64_t entryNumber = tree->GetEntryNumber(ievt);
            if (entryNumber < 0)  break;
            Long64_t localEntry = tree->LoadTree(entryNumber);
            if (localEntry < 0)  break;
            if (tree->GetTreeNumber() != curTree) {
                curTree = tree->GetTreeNumber();
                ttf ->UpdateFormulaLeaves();  // if using TChain
                ttf1->UpdateFormulaLeaves();  // if using TChain
                ttf2->UpdateFormulaLeaves();  // if using TChain
            }
            
            const Int_t ndata = ttf->GetNdata();
            Bool_t keep = kFALSE;
            for(Int_t current = 0; current<ndata && !keep; current++) {
                keep |= (bool(ttf->EvalInstance(current)) != 0);
            }
            if (!keep)  continue;


            bool even  = (bool) ttf1->EvalInstance();
            bool odd   = (bool) ttf2->EvalInstance();
            if (even && odd) {
                std::cerr << "ERROR: An event cannot be even and odd at the same time." << std::cout;
                return;
            }

            tree->GetEntry(entryNumber, 1);  // get all branches
            if (even) {
                t1->Fill();
            } else {
                t2->Fill();
            }
        }  // end loop over events

        t1->Write();
        t2->Write();
        
        ventries.push_back(t1->GetEntriesFast() + t2->GetEntriesFast());
        
        delete ttf;
        delete ttf1;
        delete ttf2;
    }
    
    std::clog << process << ": skimmed from " << entries << " to " << ventries[0] << " (ZnunuHighPt), " << ventries[1] << " (ZnunuLowPt), " << ventries[2] << " (ZnunuLowCSV) " << " entries." << std::endl;

    output->Close();
    input->Close();

    delete output;
    delete input;

    return;
}
コード例 #18
0
ファイル: Fitting.C プロジェクト: TJHague/XGT2
void Fitting(){
	TString RootFile_Name;
	TString Target, Arm;
	gSystem->Exec("ls -l *.root");
	cerr<<" --- Target (H2,He3,He4) = "; cin >> Target;
	cerr<<" --- Arm (L, R) = "; cin >> Arm;
	RootFile_Name = Form("%s_Yield_%s_All.root",Target.Data(),Arm.Data());
	TFile *f1 = new TFile(RootFile_Name.Data(),"r");
	TTree *T  = (TTree*) gDirectory->Get("T");

	TString OutFile_Name = RootFile_Name;
	OutFile_Name.ReplaceAll(".root",".out");
	ofstream outfile(OutFile_Name);

	TString File_Name1 = RootFile_Name;
	TString File_Name2 = RootFile_Name;
	TString File_Name3 = RootFile_Name;
	TString File_Name4 = RootFile_Name;
	File_Name1.ReplaceAll(".root",".png");
	File_Name2.ReplaceAll(".root",".pdf");
	File_Name3.ReplaceAll(".root","_0.png");
	File_Name4.ReplaceAll(".root","_0.pdf");

	double VZ, I, Y, Y_Err;
	int size, runno, Bin;

	T->SetBranchAddress("runsize",&size);
	T->SetBranchAddress("Bin",&Bin);
	T->SetBranchAddress("RunNo",&runno);
	T->SetBranchAddress("I",&I);
	T->SetBranchAddress("Y",&Y);
	T->SetBranchAddress("Y_Err",&Y_Err);
	T->SetBranchAddress("VZ",&VZ);

	int N = T->GetEntries();
	T->GetEntry(0);
	const int Size = size;
	int temp=20;
	if(Target=="C12"||Target=="Ca40"||Target=="Ca48")
		temp=1;
	const int Bin_Size = temp;

	/*Read Root File{{{*/
	cerr<<" @@@ Reading Root File ..."<<endl;
	double vI[Bin_Size][Size];
	double vI_Err[Bin_Size][Size];
	double vY[Bin_Size][Size];
	double vY_Err[Bin_Size][Size];
	double vVZ[Bin_Size];
	double Y_Max=-1e32,Y_Min=1e32, X_Max=-1000,X_Min=1000;
	int k=0;
	for(int j=0;j<Bin_Size; j++){
		k=0;
		for(int i=0;i<N;i++){
			T->GetEntry(i);
			if(Y>-0.5 && Bin==j){
				vI[j][k]=I;
				vI_Err[j][k]=0.;
				vY[j][k]=Y;
				vY_Err[j][k]=Y_Err;

				vVZ[j] = VZ;
				if(X_Max<vI[j][k])
					X_Max = vI[j][k];
				if(X_Min>vI[j][k])
					X_Min = vI[j][k];
				if(Y_Max<vY[j][k])
					Y_Max = vY[j][k];
				if(Y_Min>vY[j][k])
					Y_Min = vY[j][k];
				// Y_Max = Y_Max?vY[j][k]:Y_Max<vY[j][k];
				// Y_Min = Y_Min?vY[j][k]:Y_Min>vY[j][k];
				// X_Max = X_Max?vI[j][k]:X_Max<vI[j][k];
				// X_Min = X_Min?vI[j][k]:X_Min>vI[j][k];

				cerr<<Form("--- Bin = %d, VZ=%6.4f, I=%6.4f, Y=%e",
						Bin, VZ, I, Y)<<endl;
				k++;
				if(k>Size)
					cerr<<"*** Something wrong?!"<<endl;
			}
		}
	}
	/*}}}*/

	/*Plot and Fit{{{*/
	cerr<<" @@@ Making Plots and Fitting ..."<<endl;
	cerr<<Form(" ---- X_Min=%f, X_Max=%f, Y_Min=%e, Y_Max=%e",X_Min,X_Max, Y_Min, Y_Max)<<endl;

	TCanvas *c3 = new TCanvas("c3","c3",1200,700);
	c3->cd();
	TH2F *h3 = new TH2F("h3","",300,X_Min-2.0,X_Max+2.0,300,0.0,Y_Max/Y_Min*1.12);
	h3->SetStats(kFALSE);
	h3->SetXTitle("I (uA)");
	h3->GetXaxis()->CenterTitle(1);
	h3->GetXaxis()->SetTitleFont(32);
	h3->GetXaxis()->SetTitleSize(0.06);
	h3->GetYaxis()->SetTitleOffset(0.8);
	h3->SetYTitle("Yield_{normalized}");
	h3->GetYaxis()->CenterTitle(1);
	h3->GetYaxis()->SetTitleFont(32);
	h3->GetYaxis()->SetTitleSize(0.06);
	h3->GetYaxis()->SetTitleOffset(0.8);

	gStyle->SetOptStat(1);
	gStyle->SetOptFit(1);
	double S[Bin_Size],S_Err[Bin_Size];
	double Y0[Bin_Size],Y0_Err[Bin_Size];
	double BF[Bin_Size],BF_Err[Bin_Size];
	double Zero[Bin_Size];

	for(int l=0; l<Bin_Size; l++){
		for(int m=0; m<Size; m++){
			vY[l][m]/=Y_Min;   	
			vY_Err[l][m]/=Y_Min;   	
		}
	}
	TLatex *tex;
	outfile<<Form("%12s %12s %12s %12s %12s", "VZ","Y0","Y0_Err","BF","BF_Err")<<endl; 
	Y_Max=-1e32,Y_Min=1e32;
	for(int l=0; l<Bin_Size; l++){
		h3->Draw();
		for(int m=0;m<Size;m++)
			cerr<<Form(" VZ=%6.4f, I = %6.3f, Y = %e", vVZ[l], vI[l][m],vY[l][m])<<endl;

		TGraphErrors *ex = new TGraphErrors(Size, vI[l], vY[l], vI_Err[l], vY_Err[l]);
		ex->SetMarkerStyle(25);
		ex->SetMarkerColor(4);
		ex->SetLineColor(4);
		ex->Draw("P");
		ex->Fit("pol1","IM","",X_Min,X_Max);

		if(l==0){//For C12 only
//	if(l==30){
			tex=new TLatex(0.25, 0.6, Form("%s Boiling Effect Fit at z_{react} = %4.2f cm on HRS-%s",Target.Data(), vVZ[l]*100, Arm.Data()));
			tex->SetNDC();
			tex->SetTextFont(32);
			tex->SetTextSize(0.05);
			tex->Draw();
			c3->Print(File_Name3.Data());
			c3->Print(File_Name4.Data());
		}
		Y0[l]   = ex->GetFunction("pol1")->GetParameter(0) ;
		Y0_Err[l]   = ex->GetFunction("pol1")->GetParError(0) ;
		S[l] = ex->GetFunction("pol1")->GetParameter(1);
		S_Err[l] = ex->GetFunction("pol1")->GetParError(1);
		BF[l] = S[l]/Y0[l];
		BF_Err[l] = BF[l] * sqrt( pow(Y0_Err[l]/Y0[l],2) + pow(S_Err[l]/S[l],2) );
		Zero[l] = 0.0;

		if(Y_Max<S[l])
			Y_Max = S[l];
		if(Y_Min>S[l])
			Y_Min = S[l];

		cerr<<Form("  VZ=%f, Slop=%f",vVZ[l],S[l])<<endl; 
		outfile<<Form("  %12.8f %12.8f %12.8f %12.8f %12.8f",vVZ[l],Y0[l], Y0_Err[l], BF[l],BF_Err[l])<<endl; 

		c3->Clear();
	}
	c3->Close();

	TCanvas *c4 = new TCanvas("c4","c4",1200,700);
	c4->cd();
	TH2F *h4 = new TH2F("h4","",300, -0.14, 0.14, 300, -0.011, 0.001);
	h4->SetStats(kFALSE);
	h4->SetXTitle("z_{react} (m)");
	h4->GetXaxis()->CenterTitle(1);
	h4->GetXaxis()->SetTitleFont(32);
	h4->GetXaxis()->SetTitleSize(0.06);
	h4->GetXaxis()->SetTitleOffset(0.7);
	h4->SetYTitle("BF");
	h4->GetYaxis()->CenterTitle(1);
	h4->GetYaxis()->SetTitleFont(32);
	h4->GetYaxis()->SetTitleSize(0.04);
	h4->GetYaxis()->SetTitleOffset(1.2);
	h4->Draw();

	TGraphErrors *ex1 = new TGraphErrors(Bin_Size, vVZ, BF, Zero, BF_Err);
	ex1->SetMarkerStyle(20);
	ex1->SetMarkerColor(4);
	ex1->SetLineColor(4);
	ex1->Draw("P");
	tex=new TLatex(0.3, 0.2, Form("%s Boiling Effect on HRS-%s",Target.Data(), Arm.Data()));
	tex->SetNDC();
	tex->SetTextFont(32);
	tex->SetTextSize(0.05);
	tex->Draw();

	c4->Print(File_Name1.Data());
	c4->Print(File_Name2.Data());
	/*}}}*/
}
コード例 #19
0
ファイル: makeQnCuts.C プロジェクト: jrcastle/EbyEAnalysis
void makeQnCuts(){

  bool testrun    = 0;
  const int NBins = 1000;

  double qn_min  = 0;
  double qn_max  = 0.61;
  int    qnselect_ = 2;
  double vtxCut  = 15.;

  TFile * fIn;
  TTree * tree;
  double centval;
  double vtx;
  double qnHFx_EP[NumEPNames];
  double qnHFy_EP[NumEPNames];
  double sumET_EP[NumEPNames];

  TFile * fQNDet;
  TH1D * hqnHFDet_x[NumEPNames];
  TH1D * hqnHFDet_y[NumEPNames];

  TFile * fOut;
  TH1D * hqnHF_EP[NCENT][NEPSymm];
  TCanvas * chqnHF_EP[NCENT][NEPSymm];

  double splitBinMin[NCENT][NEPSymm][NQN];
  double splitBinMax[NCENT][NEPSymm][NQN];

  TLine * splitLine[NCENT][NEPSymm][NQN-1];

  TH1D * hqbins[NCENT][NEPSymm];
  double qbins[NCENT][NEPSymm][NQN+1];

  TLatex latex;

  //
  // MAIN
  //

  setTDRStyle();
  latex.SetNDC();

  //-- Get the analyzer file
  fIn = new TFile(fAnaTreeName);

  //-- Get the analyzer tree and set the branches
  tree = (TTree*) fIn->Get("ebyeana/tree");
  tree->SetBranchAddress("Cent", &centval);
  tree->SetBranchAddress("Vtx",  &vtx);
  tree->SetBranchAddress("qnHFx_EP",  &qnHFx_EP);
  tree->SetBranchAddress("qnHFy_EP",  &qnHFy_EP);
  tree->SetBranchAddress("sumET_EP",  &sumET_EP);

  //-- Get the QN Detector histograms
  fQNDet = new TFile( Form("../../../v%i/eta2.4/AnalyzerResults/Q%iDet.root", qnselect_, qnselect_) );
  for(int iEP = 0; iEP < NumEPNames; iEP++){
    int EPbin  = EPSymmPartnerBin[iEP];
    if( EPbin != EPSymmBin ) continue;
    hqnHFDet_x[iEP] = (TH1D*) fQNDet->Get( Form("hqnHFDet_x_%s", EPNames[iEP].data()) );
    hqnHFDet_y[iEP] = (TH1D*) fQNDet->Get( Form("hqnHFDet_y_%s", EPNames[iEP].data()) );
  }

  //-- Make the output file
  fOut = new TFile( Form("q%iCuts.root", qnselect_), "recreate" );

  //-- Initialize the 1D histograms
  for(int iEP = 0; iEP < NEPSymm; iEP++){
    if( iEP != EPSymmBin ) continue;
    for(int icent = 0; icent < NCENT; icent++){
      fOut->cd();
      hqnHF_EP[icent][iEP] = new TH1D( Form("hqnHF_c%i_EP%i", icent, iEP), Form("hqnHF_c%i_EP%i", icent, iEP), NBins, qn_min, qn_max );
      hqnHF_EP[icent][iEP]->GetXaxis()->SetTitle( Form("q_{%i}", qnselect_) );
      hqnHF_EP[icent][iEP]->GetYaxis()->SetTitle( "Events" );
    }
  }


  //-- Begin Event loop
  int Nevt;
  if(!testrun) Nevt = tree->GetEntries();
  else         Nevt = 10000;
  std::cout<<"Begin QN SPLIT loop, contains "<< Nevt << " events..." << std::endl;
  for(int ievt = 0; ievt < Nevt; ievt++){

    if((ievt+1)% 500000 == 0) cout<<"Processing Event "<<ievt+1<<"\t"<<(100.*(ievt+1)/Nevt)<<"% Completed"<<endl;
    tree->GetEntry(ievt);

    //-- Vertex Cut
    if(TMath::Abs(vtx) > vtxCut) continue;

    //-- Calculate centbin
    if( centval > cent_max[NCENT-1]) continue;
    int icent = hCentBins.FindBin(centval)-1;

    //-- Begin EP loop
    for(int iEP = 0; iEP < NEP; iEP++){

      int EPbin  = EPSymmPartnerBin[iEP];
      if( EPbin != EPSymmBin ) continue;

      double qx    = qnHFx_EP[iEP];
      double qy    = qnHFy_EP[iEP];
      double qxDet = hqnHFDet_x[iEP]->GetBinContent(icent+1);
      double qyDet = hqnHFDet_y[iEP]->GetBinContent(icent+1);
      double sumET = sumET_EP[iEP];
      if(sumET == 0) continue;

      qx -= qxDet;
      qy -= qyDet;
      qx /= sumET;
      qy /= sumET;
      double qn    = TMath::Sqrt( qx*qx + qy*qy );

      //-- Consolodate into symmetric HF bins
      hqnHF_EP[icent][EPbin]->Fill(qn);

    } //-- End EP loop

  } //-- End event loop
  std::cout<<"End QN loop"<<std::endl;

  //-- Divide each histogram into NQN equal areas
  bool splitSuccess = 1;

  for(int icent = 0; icent < NCENT; icent++){
    for(int iEP = 0; iEP < NEPSymm; iEP++){
      if( iEP != EPSymmBin ) continue;

      double integral = hqnHF_EP[icent][iEP]->Integral(1, NBins);
      double binwidth = integral/(double)NQN;
      int startbin = 1;
      double sum = 0.;

      for(int iqn = 0; iqn < NQN-1; iqn++){
	splitBinMin[icent][iEP][iqn] = startbin;

	for(int ibin = startbin; ibin <= NBins; ibin++){
	  double A = hqnHF_EP[icent][iEP]->Integral(startbin, ibin);
	  if( A > binwidth ){
	    double B = hqnHF_EP[icent][iEP]->Integral(startbin, ibin-1);
	    if( fabs(A - binwidth) < fabs(B - binwidth) ){
	      startbin = ibin+1;
	      splitBinMax[icent][iEP][iqn] = ibin;
	      break;
	    }
	    else{
	      startbin = ibin;
	      splitBinMax[icent][iEP][iqn] = ibin-1;
	      break;
	    }
	  }

	}//-- End bin loop

	sum += hqnHF_EP[icent][iEP]->Integral(splitBinMin[icent][iEP][iqn], splitBinMax[icent][iEP][iqn]);

	double binc = hqnHF_EP[icent][iEP]->GetBinCenter(startbin);
	double max  = hqnHF_EP[icent][iEP]->GetBinContent(startbin);
	splitLine[icent][iEP][iqn] = new TLine(binc, 0, binc, max);
	splitLine[icent][iEP][iqn]->SetLineColor(2);
	splitLine[icent][iEP][iqn]->SetLineStyle(2);
	splitLine[icent][iEP][iqn]->SetLineWidth(2);

      } //-- End split loop

      splitBinMin[icent][iEP][NQN-1] = splitBinMax[icent][iEP][NQN-2] + 1;

      // Make the last bin edge to be the bin where the integral is full
      for(int ibin = 1; ibin <= NBins; ibin++){

	double integ = hqnHF_EP[icent][iEP]->Integral(1, ibin);
	if( integ == integral ){
	  splitBinMax[icent][iEP][NQN-1] = ibin;
	  break;
	}

      } //-- End bin loop

      sum += hqnHF_EP[icent][iEP]->Integral(splitBinMin[icent][iEP][NQN-1], splitBinMax[icent][iEP][NQN-1]);
      if(sum == integral) std::cout<<"Histogram division check..."<<"\tCent bin = "<<icent<<"\tEP bin = "<<iEP<<"\tPASS!"<<std::endl;
      else{
	std::cout<<"Histogram division check..."<<"\tCent bin = "<<icent<<"\tEP bin = "<<iEP<<"\tFAIL!"<<std::endl;
	splitSuccess = 0;
      }

    } //-- End EP loop
  } //-- End cent loop

  if( !splitSuccess ){
    std::cout << "Histogram area splitting failed in one or more bin!" << std::endl;
    std::cout << "Refusing to go futher, please fix and run again." <<std::endl;
    std::cout << "Exiting... Have a nice day." << std::endl;
    //exit(0);
  }

  //-- If all is good, proceed to fill the 2D arrays that contain the bin boundaries for qn
  for(int iqn = 0; iqn <= NQN; iqn++){
    for(int icent = 0; icent < NCENT; icent++){
      for(int iEP = 0; iEP < NEPSymm; iEP++){
	if( iEP != EPSymmBin ) continue;

	if( iqn < NQN ){
	  int bmin = splitBinMin[icent][iEP][iqn];
	  double qmin = hqnHF_EP[icent][iEP]->GetBinLowEdge(bmin);
	  qbins[icent][iEP][iqn] = qmin; 
	}
	else{
	  int bmax = splitBinMax[icent][iEP][NQN-1] + 1;
	  double qmax = hqnHF_EP[icent][iEP]->GetBinLowEdge(bmax);
	  qbins[icent][iEP][iqn] = qmax;
	}
      }
    }
  }

  //-- Set up histograms based on these arrays (so I can use the find bin option in the subsequent programs)
  for(int icent = 0; icent < NCENT; icent++){
    for(int iEP = 0; iEP < NEPSymm; iEP++){
      if( iEP != EPSymmBin ) continue;

      fOut->cd();
      hqbins[icent][iEP] = new TH1D( Form("hqbins_%s_c%i", EPSymmNames[iEP].data(), icent), Form("hqbins_%s_c%i", EPSymmNames[iEP].data(), icent), NQN, qbins[icent][iEP] );
      hqbins[icent][iEP]->GetXaxis()->SetTitle( Form("q_%i", qnselect_) );

      for(int iqn = 1; iqn <= NQN; iqn++) hqbins[icent][iEP]->SetBinContent( iqn, iqn );

   
    }
  }

  //-- Draw the observed qn histograms with the split lines and save the canvases
    for(int iEP = 0; iEP < NEPSymm; iEP++){
      if( iEP != EPSymmBin ) continue;
      for(int icent = 0; icent < NCENT; icent++){
	chqnHF_EP[icent][iEP] = new TCanvas(Form("chqnHF_%s_c%i", EPSymmNames[iEP].data(), icent), Form("chqnHF_%s_c%i", EPSymmNames[iEP].data(), icent), 500, 500);
	chqnHF_EP[icent][iEP]->cd();
	chqnHF_EP[icent][iEP]->SetLogy();
	hqnHF_EP[icent][iEP]->Draw();
	for(int i = 0; i < NQN-1; i++) splitLine[icent][iEP][i]->Draw("same");
	//latex.DrawLatex(0.56,0.88, Form("%s", EPSymmNames[iEP].data()) );
	latex.DrawLatex(0.56,0.88, Form("Centrality %i - %i%s", cent_min[icent], cent_max[icent], "%") );
	latex.DrawLatex(0.56,0.82,  Form("%.1f < |#eta| < %.1f", EPSymmAbsEtaMin[iEP], EPSymmAbsEtaMax[iEP]) );
	chqnHF_EP[icent][iEP]->SaveAs( Form("../plots/qnsplitting/hq%i_%s_c%i.C", qnselect_, EPSymmNames[iEP].data(), icent) );
    }
  }

  fOut->Write();

}
コード例 #20
0
ファイル: checkPullTree.C プロジェクト: ktf/AliPhysics
//_________________________________________________________________________________________
Int_t checkPullTree(TString pathTree,  TString pathNameThetaMap, TString pathNameSigmaMap,
                    TString mapSuffix, const Int_t collType /*0: pp, 1: pPb, 2: PbPb*/, const Bool_t plotPull = kTRUE,
                    const Double_t downScaleFactor = 1,
                    TString pathNameSplinesFile = "", TString prSplinesName = "",
                    TString fileNameTree = "bhess_PIDetaTree.root", TString treeName = "fTree")
{
  const Bool_t isNonPP = collType != 0;
  const Double_t massProton = AliPID::ParticleMass(AliPID::kProton);
  
  Bool_t recalculateExpecteddEdx = pathNameSplinesFile != "";
  
  TFile* f = 0x0;
	
  f = TFile::Open(Form("%s/%s", pathTree.Data(), fileNameTree.Data()));
  if (!f)  {
    std::cout << "Failed to open tree file \"" << Form("%s/%s", pathTree.Data(), fileNameTree.Data()) << "\"!" << std::endl;
    return -1;
  }
      
  // Extract the data Tree
  TTree* tree = dynamic_cast<TTree*>(f->Get(treeName.Data()));
  if (!tree) {
    std::cout << "Failed to load data tree!" << std::endl;
    return -1;
  }
  
  // Extract the splines, if desired
  TSpline3* splPr = 0x0;
  if (recalculateExpecteddEdx) {
    std::cout << "Loading splines to recalculate expected dEdx!" << std::endl << std::endl;
    
    TFile* fSpl = TFile::Open(pathNameSplinesFile.Data());
    if (!fSpl) {
      std::cout << "Failed to open spline file \"" << pathNameSplinesFile.Data() << "\"!" << std::endl;
      return 0x0;
    }
    
    TObjArray* TPCPIDResponse = (TObjArray*)fSpl->Get("TPCPIDResponse");
    if (!TPCPIDResponse) {
      splPr = (TSpline3*)fSpl->Get(prSplinesName.Data());
      
      // If splines are in file directly, without TPCPIDResponse object, try to load them
      if (!splPr) {
        std::cout << "Failed to load object array from spline file \"" << pathNameSplinesFile.Data() << "\"!" << std::endl;
        return 0x0;
      }
    }
    else {
      splPr = (TSpline3*)TPCPIDResponse->FindObject(prSplinesName.Data());
      
      if (!splPr) {
        std::cout << "Failed to load splines from file \"" << pathNameSplinesFile.Data() << "\"!" << std::endl;
        return 0x0;
      }
    }
  }
  else
    std::cout << "Taking dEdxExpected from Tree..." << std::endl << std::endl;

  // Extract the correction maps
  TFile* fMap = TFile::Open(pathNameThetaMap.Data());
  if (!fMap)  {
    std::cout << "Failed to open thetaMap file \"" << pathNameThetaMap.Data() << "\"! Will not additionally correct data...." << std::endl;
  }

  TH2D* hMap = 0x0;
  
  if (fMap) {
    hMap = dynamic_cast<TH2D*>(fMap->Get(Form("hRefined%s", mapSuffix.Data())));
    if (!hMap) {
      std::cout << "Failed to load theta map!" << std::endl;
      return -1;
    }
  }

  TFile* fSigmaMap = TFile::Open(pathNameSigmaMap.Data());
  if (!fSigmaMap)  {
    std::cout << "Failed to open simgaMap file \"" << pathNameSigmaMap.Data() << "\"!" << std::endl;
    return -1;
  }

  TH2D* hThetaMapSigmaPar1 = dynamic_cast<TH2D*>(fSigmaMap->Get("hThetaMapSigmaPar1"));
  if (!hThetaMapSigmaPar1) {
    std::cout << "Failed to load sigma map for par 1!" << std::endl;
    return -1;
  }

  Double_t c0 = -1;
  TNamed* c0Info = dynamic_cast<TNamed*>(fSigmaMap->Get("c0"));
  if (!c0Info) {
    std::cout << "Failed to extract c0 from file with sigma map!" << std::endl;
    return -1;
  }

  TString c0String = c0Info->GetTitle();
  c0 = c0String.Atof();
  printf("Loaded parameter 0 for sigma: %f\n\n", c0);

  if (plotPull)
    std::cout << "Plotting pull..." << std::endl << std::endl;
  else
    std::cout << "Plotting delta'..." << std::endl << std::endl;

  Long64_t nTreeEntries = tree->GetEntriesFast();

  Double_t dEdx = 0.; // Measured dE/dx
  Double_t dEdxExpected = 0.; // Expected dE/dx according to parametrisation
  Double_t tanTheta = 0.; // Tangens of (local) theta at TPC inner wall
  Double_t pTPC = 0.; // Momentum at TPC inner wall
  UShort_t tpcSignalN = 0; // Number of clusters used for dEdx
  UChar_t  pidType = 0;
  Int_t    fMultiplicity = 0;
  //Double_t phiPrime = 0;

  // Only activate the branches of interest to save processing time
  tree->SetBranchStatus("*", 0); // Disable all branches
  tree->SetBranchStatus("pTPC", 1);
  tree->SetBranchStatus("dEdx", 1);
  tree->SetBranchStatus("dEdxExpected", 1);
  tree->SetBranchStatus("tanTheta", 1);
  tree->SetBranchStatus("tpcSignalN", 1);
  tree->SetBranchStatus("pidType", 1);
  //tree->SetBranchStatus("phiPrime", 1);
  if (isNonPP)
    tree->SetBranchStatus("fMultiplicity", 1);

  
  tree->SetBranchAddress("dEdx", &dEdx);
  tree->SetBranchAddress("dEdxExpected", &dEdxExpected);
  tree->SetBranchAddress("tanTheta", &tanTheta);
  tree->SetBranchAddress("tpcSignalN", &tpcSignalN);
  tree->SetBranchAddress("pTPC", &pTPC);
  tree->SetBranchAddress("pidType", &pidType);
  //tree->SetBranchAddress("phiPrime", &phiPrime);
  if (isNonPP)
    tree->SetBranchAddress("fMultiplicity", &fMultiplicity);

  
  // Output file
  TDatime daTime;
  TString savefileName = Form("%s%s_checkPullSigma_%04d_%02d_%02d__%02d_%02d.root", fileNameTree.ReplaceAll(".root", "").Data(),
                              recalculateExpecteddEdx ? "_recalcdEdx" : "",
                              daTime.GetYear(), daTime.GetMonth(), daTime.GetDay(), daTime.GetHour(), daTime.GetMinute());

  TFile* fSave = TFile::Open(Form("%s/%s", pathTree.Data(), savefileName.Data()), "recreate");
  if (!fSave) {
    std::cout << "Failed to open save file \"" << Form("%s/%s", pathTree.Data(), savefileName.Data()) << "\"!" << std::endl;
    return -1;
  }
  
  const Double_t pBoundLow = 0.1;
  const Double_t pBoundUp = 5;

  const Int_t nBins1 = TMath::Ceil(180 / downScaleFactor);
  const Int_t nBins2 = TMath::Ceil(100 / downScaleFactor);
  const Int_t nBins3 = TMath::Ceil(60 / downScaleFactor);
  
  const Int_t nPbinsForMap = nBins1 + nBins2 + nBins3;
  Double_t binsPforMap[nPbinsForMap + 1];
  
  Double_t binWidth1 = (1.0 - pBoundLow) / nBins1;
  Double_t binWidth2 = (2.0 - 1.0 ) / nBins2;
  Double_t binWidth3 = (pBoundUp - 2.0) / nBins3;
  
  for (Int_t i = 0; i < nBins1; i++)  {
    binsPforMap[i] = pBoundLow + i * binWidth1;
  }
  for (Int_t i = nBins1, j = 0; i < nBins1 + nBins2; i++, j++)  {
    binsPforMap[i] = 1.0 + j * binWidth2;
  }
  for (Int_t i = nBins1 + nBins2, j = 0; i < nBins1 + nBins2 + nBins3; i++, j++)  {
    binsPforMap[i] = 2.0 + j * binWidth3;
  }
  binsPforMap[nPbinsForMap] = pBoundUp;

  TH2D* hPull = new TH2D("hPull", "Pull vs. p_{TPC} integrated over tan(#Theta);p_{TPC} (GeV/c);Pull", nPbinsForMap, binsPforMap, 
                         plotPull ? 120 : 240, plotPull ? -6 : -0.6, plotPull ? 6 : 0.6);
  TH2D* hPullAdditionalCorr = (TH2D*)hPull->Clone("hPullAdditionalCorr");
  hPullAdditionalCorr->SetTitle("Pull vs. p_{TPC} integrated over tan(#Theta) with additional dEdx correction w.r.t. tan(#Theta)");
  /*
  const Int_t nThetaHistos = 3;
  TH2D* hPullTheta[nThetaHistos];
  TH2D* hPullAdditionalCorrTheta[nThetaHistos];
  Double_t tThetaLow[nThetaHistos] = { 0.0, 0.4, 0.9 };
  Double_t tThetaHigh[nThetaHistos] = { 0.1, 0.5, 1.0 };
  */
  const Int_t nThetaHistos = 10;
  TH2D* hPullTheta[nThetaHistos];
  TH2D* hPullAdditionalCorrTheta[nThetaHistos];
  Double_t tThetaLow[nThetaHistos] = { 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 };
  Double_t tThetaHigh[nThetaHistos] = { 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 };
  

  for (Int_t i = 0; i < nThetaHistos; i++)    {
    hPullTheta[i] = new TH2D(Form("hPullTheta_%d", i),
                             Form("Pull vs. p_{TPC} for %.2f <= |tan(#Theta)| < %.2f;p_{TPC} (GeV/c);Pull", tThetaLow[i], tThetaHigh[i]),
                             nPbinsForMap, binsPforMap, plotPull ? 120 : 240, plotPull ? -6 : -0.6, plotPull ? 6 : 0.6);

    hPullAdditionalCorrTheta[i] =
      new TH2D(Form("hPullAdditionalCorrTheta_%d", i),
               Form("Pull vs. p_{TPC} for %.2f <= |tan(#Theta)| < %.2f with additional dEdx correction w.r.t. tan(#Theta);p_{TPC} (GeV/c);Pull",
                    tThetaLow[i], tThetaHigh[i]),
               nPbinsForMap, binsPforMap, plotPull ? 120 : 240, plotPull ? -6 : -0.6, plotPull ? 6 : 0.6);
  }

  
  
  
  
  
  TF1 corrFuncMult("corrFuncMult", "[0] + [1]*TMath::Max([4], TMath::Min(x, [3])) + [2] * TMath::Power(TMath::Max([4], TMath::Min(x, [3])), 2)",
                   0., 0.2);
  TF1 corrFuncMultTanTheta("corrFuncMultTanTheta", "[0] * (x -[2]) + [1] * (x * x - [2] * [2])", -1.5, 1.5);
  TF1 corrFuncSigmaMult("corrFuncSigmaMul", "TMath::Max(0, [0] + [1]*TMath::Min(x, [3]) + [2] * TMath::Power(TMath::Min(x, [3]), 2))", 0., 0.2);
  
  
  // LHC13b.pass2
  if (isNonPP)
    printf("Using corr Parameters for 13b.pass2\n!");
  
  corrFuncMult.SetParameter(0, -5.906e-06);
  corrFuncMult.SetParameter(1, -5.064e-04);
  corrFuncMult.SetParameter(2, -3.521e-02);
  corrFuncMult.SetParameter(3,  2.469e-02);
  corrFuncMult.SetParameter(4, 0);
  
  corrFuncMultTanTheta.SetParameter(0, -5.32e-06);
  corrFuncMultTanTheta.SetParameter(1,  1.177e-05);
  corrFuncMultTanTheta.SetParameter(2, -0.5);
  
  corrFuncSigmaMult.SetParameter(0, 0.);
  corrFuncSigmaMult.SetParameter(1, 0.);
  corrFuncSigmaMult.SetParameter(2, 0.);
  corrFuncSigmaMult.SetParameter(3, 0.);
  
  
  /* OK, but PID task was not very satisfying
  corrFuncMult.SetParameter(0, -6.27187e-06);
  corrFuncMult.SetParameter(1, -4.60649e-04);
  corrFuncMult.SetParameter(2, -4.26450e-02);
  corrFuncMult.SetParameter(3, 2.40590e-02);
  corrFuncMult.SetParameter(4, 0);
  
  corrFuncMultTanTheta.SetParameter(0, -5.338e-06);
  corrFuncMultTanTheta.SetParameter(1,  1.220e-05);
  corrFuncMultTanTheta.SetParameter(2, -0.5);
  
  corrFuncSigmaMult.SetParameter(0, 7.89237e-05);
  corrFuncSigmaMult.SetParameter(1, -1.30662e-02);
  corrFuncSigmaMult.SetParameter(2, 8.91548e-01);
  corrFuncSigmaMult.SetParameter(3, 1.47931e-02);
  */
  
  
  /*
  // LHC11a10a
  if (isNonPP)
    printf("Using corr Parameters for 11a10a\n!");
  
  corrFuncMult.SetParameter(0, 6.90133e-06);
  corrFuncMult.SetParameter(1, -1.22123e-03);
  corrFuncMult.SetParameter(2, 1.80220e-02);
  corrFuncMult.SetParameter(3, 0.1);
  corrFuncMult.SetParameter(4, 6.45306e-03);
  
  corrFuncMultTanTheta.SetParameter(0, -2.85505e-07);
  corrFuncMultTanTheta.SetParameter(1, -1.31911e-06);
  corrFuncMultTanTheta.SetParameter(2, -0.5);
  
  corrFuncSigmaMult.SetParameter(0, -4.29665e-05);
  corrFuncSigmaMult.SetParameter(1, 1.37023e-02);
  corrFuncSigmaMult.SetParameter(2, -6.36337e-01);
  corrFuncSigmaMult.SetParameter(3, 1.13479e-02);
  */
  
  /* OLD without saturation and large error for negative slopes
  corrFuncSigmaMult.SetParameter(0, -4.79684e-05);
  corrFuncSigmaMult.SetParameter(1, 1.49938e-02);
  corrFuncSigmaMult.SetParameter(2, -7.15269e-01);
  corrFuncSigmaMult.SetParameter(3, 1.06855e-02);
  */
  
  /* OLD very good try, but with fewer pBins for the fitting
  corrFuncMult.SetParameter(0, 6.88365e-06);
  corrFuncMult.SetParameter(1, -1.22324e-03);
  corrFuncMult.SetParameter(2, 1.81625e-02);
  corrFuncMult.SetParameter(3, 0.1);
  corrFuncMult.SetParameter(4, 6.36890e-03);
  
  corrFuncMultTanTheta.SetParameter(0, -2.85505e-07);
  corrFuncMultTanTheta.SetParameter(1, -1.31911e-06);
  corrFuncMultTanTheta.SetParameter(2, -0.5);
  
  corrFuncSigmaMult.SetParameter(0, -4.28401e-05);
  corrFuncSigmaMult.SetParameter(1, 1.24812e-02);
  corrFuncSigmaMult.SetParameter(2, -5.28531e-01);
  corrFuncSigmaMult.SetParameter(3, 1.25147e-02);
  */
  /*OLD good try
  corrFuncMult.SetParameter(0, 7.50321e-06);
  corrFuncMult.SetParameter(1, -1.25250e-03);
  corrFuncMult.SetParameter(2, 1.85437e-02);
  corrFuncMult.SetParameter(3, 0.1);
  corrFuncMult.SetParameter(4, 6.21192e-03);
  
  corrFuncMultTanTheta.SetParameter(0, -1.43112e-07);
  corrFuncMultTanTheta.SetParameter(1, -1.53e-06);
  corrFuncMultTanTheta.SetParameter(2, 0.3);
  
  corrFuncSigmaMult.SetParameter(0, -2.54019e-05);
  corrFuncSigmaMult.SetParameter(1, 8.68883e-03);
  corrFuncSigmaMult.SetParameter(2, -3.36176e-01);
  corrFuncSigmaMult.SetParameter(3, 1.29230e-02);
  */
  
  /*
  // LHC10h.pass2
  if (isNonPP)
    printf("Using corr Parameters for 10h.pass2\n!");
  
  corrFuncMult.SetParameter(0, 3.21636e-07);
  corrFuncMult.SetParameter(1, -6.65876e-04);
  corrFuncMult.SetParameter(2, 1.28786e-03);
  corrFuncMult.SetParameter(3, 1.47677e-02);
  corrFuncMult.SetParameter(4, 0.);
  
  corrFuncMultTanTheta.SetParameter(0, 7.23591e-08);
  corrFuncMultTanTheta.SetParameter(1, 2.7469e-06);
  corrFuncMultTanTheta.SetParameter(2, -0.5);
  
  corrFuncSigmaMult.SetParameter(0, -1.22590e-05);
  corrFuncSigmaMult.SetParameter(1, 6.88888e-03);
  corrFuncSigmaMult.SetParameter(2, -3.20788e-01);
  corrFuncSigmaMult.SetParameter(3, 1.07345e-02);
  */
  
  /*OLD bad try
  corrFuncMult.SetParameter(0, 2.71514e-07);
  corrFuncMult.SetParameter(1, -6.92031e-04);
  corrFuncMult.SetParameter(2, 3.56042e-03);
  corrFuncMult.SetParameter(3, 1.47497e-02);
  corrFuncMult.SetParameter(4, 0.);
  
  corrFuncMultTanTheta.SetParameter(0, 8.53204e-08);
  corrFuncMultTanTheta.SetParameter(1, 2.85591e-06);
  corrFuncMultTanTheta.SetParameter(2, -0.5);
  
  corrFuncSigmaMult.SetParameter(0, -6.82477e-06);
  corrFuncSigmaMult.SetParameter(1, 4.97051e-03);
  corrFuncSigmaMult.SetParameter(2, -1.64954e-01);
  corrFuncSigmaMult.SetParameter(3, 9.21061e-03);
  */
  

  //TODO NOW
  TF1* fShapeSmallP = new TF1("fShapeSmallP", "pol5", -0.4, 0.4);
  fShapeSmallP->SetParameters(1.01712, -0.0202725, -0.260692, 0.261623, 0.671854, -1.14014);
    
  for (Long64_t i = 0; i < nTreeEntries; i++) {
    tree->GetEntry(i);

    if (dEdx <= 0 || dEdxExpected <= 0 || tpcSignalN <= 10)
      continue;
    /*
    Double_t pT = pTPC*TMath::Sin(-TMath::ATan(tanTheta)+TMath::Pi()/2.0);
    if ((phiPrime > 0.072/pT+TMath::Pi()/18.0-0.035 && phiPrime < 0.07/pT/pT+0.1/pT+TMath::Pi()/18.0+0.035)) 
      continue;
    */
      
    if (pidType != kMCid) {
      if (pidType == kTPCid && pTPC > 0.6)
        continue;
      if (pidType == kTPCandTOFid && (pTPC < 0.6 || pTPC > 2.0))
        continue;
      if ((collType == 2) && pidType == kTPCandTOFid && pTPC > 1.0)
        continue;// Only V0's in case of PbPb above 1.0 GeV/c
      if (pidType == kV0idPlusTOFrejected) //TODO NOW NEW
        continue;
    }
    
    if (recalculateExpecteddEdx) {
      dEdxExpected = 50. * splPr->Eval(pTPC / massProton); //WARNING: What, if MIP is different from 50.? Seems not to be used (tested for pp, MC_pp, PbPb and MC_PbPb), but can in principle happen
    }
      
    //TODO NOW
    /*
    if (TMath::Abs(tanTheta) <= 0.4) {
      Double_t p0 = fShapeSmallP->Eval(tanTheta) - 1.0; // Strength of the correction
      Double_t p1 = -9.0; // How fast the correction is turned off
      Double_t p2 = -0.209; // Turn off correction around 0.2 GeV/c
      Double_t p3 = 1.0; // Delta' for large p should be 1

      Double_t corrFactor = TMath::Erf((pTPC + p2) * p1) * p0 + p3 + p0; // Add p0 to have 1 for p3 = 1 and large pTPC
      dEdxExpected *= corrFactor;
    }*/
    
     /*TODO old unsuccessful try 
    Double_t thetaGlobalTPC = -TMath::ATan(tanTheta) + TMath::Pi() / 2.;
    Double_t pTtpc = pTPC * TMath::Sin(thetaGlobalTPC);
    Double_t pTtpcInv = (pTtpc > 0) ? 1. / pTtpc : 0;
    Double_t p0 = 1.0;
    Double_t p1 = 1./ 0.5;//TODO 2.0;
    Double_t p2 = -0.2;//TODO 0.1
    Double_t pTcorrFactor = p0 + (pTtpcInv > p1) * p2 * (pTtpcInv - p1);
    
    dEdxExpected *= pTcorrFactor;
    */
    
      
    // From the momentum (via dEdxExpected) and the tanTheta of the track, the expected dEdx can be calculated (correctedDeDxExpected).
    // If the splines are correct, this should give in average the same value as dEdx. 
    // Now valid: Maps created from corrected data with splines adopted to corrected data, so lookup should be for dEdxExpected=dEdxSplines (no further
    // eta correction) or the corrected dEdx from the track (which should ideally be = dEdxSplines)
    
    // Tested with corrected data for LHC10d.pass2: using dEdx for the lookup (which is the corrected value and should ideally be = dEdxSplines):
    // Results almost the same. Maybe slightly better for dEdxExpected.
    
    // No longer valid: Note that the maps take always the uncorrected dEdx w.r.t.
    // tanTheta, so that correctedDeDxExpected is needed here normally. However, the information for the correction will be lost at some point.
    // Therefore, dEdxExpected can be used instead and should provide a good approximation.
    Double_t c1FromSigmaMap = hThetaMapSigmaPar1->GetBinContent(getBinX(hThetaMapSigmaPar1, tanTheta), getBinY(hThetaMapSigmaPar1, 1./dEdxExpected));
    
    Double_t expectedSigma = dEdxExpected * TMath::Sqrt( c0 * c0 + (c1FromSigmaMap * c1FromSigmaMap) / tpcSignalN);
    Double_t pull = (dEdx - dEdxExpected) / (plotPull ? expectedSigma: dEdxExpected);

    // Fill pull histo
    hPull->Fill(pTPC, pull);

    Double_t tanThetaAbs = TMath::Abs(tanTheta);
    
    for (Int_t j = 0; j < nThetaHistos; j++)    {
      if (tanThetaAbs  >= tThetaLow[j] && tanThetaAbs < tThetaHigh[j])  {
        hPullTheta[j]->Fill(pTPC, pull);
      }
    }

    if (!hMap)
      continue;

    Double_t correctionFactor = 1.;
    
    if (isNonPP) {
      // 1. Correct eta dependence
      correctionFactor = hMap->GetBinContent(getBinX(hMap, tanTheta), getBinY(hMap, 1./dEdxExpected));
      
      // 2. Correct for multiplicity dependence:
      Double_t multCorrectionFactor = 1.;
      
      if (fMultiplicity > 0) {
        Double_t relSlope = corrFuncMult.Eval(1. / (dEdxExpected * correctionFactor));
        relSlope += corrFuncMultTanTheta.Eval(tanTheta);

        multCorrectionFactor = 1. + relSlope * fMultiplicity;
      }

      c1FromSigmaMap = hThetaMapSigmaPar1->GetBinContent(getBinX(hThetaMapSigmaPar1, tanTheta), getBinY(hThetaMapSigmaPar1, 1./dEdxExpected));
      
      // Multiplicity dependence of sigma depends on the real dEdx at zero multiplicity, i.e. the eta (only) corrected dEdxExpected value has to be used
      // since all maps etc. have been created for ~zero multiplicity
      Double_t relSigmaSlope = corrFuncSigmaMult.Eval(1. / (dEdxExpected * correctionFactor));
      Double_t multSigmaCorrectionFactor = 1. + relSigmaSlope * fMultiplicity;
      
      dEdxExpected *= correctionFactor * multCorrectionFactor; 
      
      expectedSigma = dEdxExpected * TMath::Sqrt( c0 * c0 + (c1FromSigmaMap * c1FromSigmaMap) / tpcSignalN);
      expectedSigma *= multSigmaCorrectionFactor;
      
      pull = (dEdx - dEdxExpected) / (plotPull ? expectedSigma: dEdxExpected);
    }
    else {
      correctionFactor = hMap->GetBinContent(getBinX(hMap, tanTheta), getBinY(hMap, 1./dEdxExpected));
      
      c1FromSigmaMap = hThetaMapSigmaPar1->GetBinContent(getBinX(hThetaMapSigmaPar1, tanTheta), getBinY(hThetaMapSigmaPar1, 1./dEdxExpected));
   
      dEdxExpected *= correctionFactor; // If data is not corrected, but the sigma map is for corrected data, re-do analysis with corrected dEdx
      
      expectedSigma = dEdxExpected * TMath::Sqrt( c0 * c0 + (c1FromSigmaMap * c1FromSigmaMap) / tpcSignalN);
      pull = (dEdx - dEdxExpected) / (plotPull ? expectedSigma: dEdxExpected);
    }

    pull = (dEdx - dEdxExpected) / (plotPull ? expectedSigma: dEdxExpected);

    hPullAdditionalCorr->Fill(pTPC, pull);

    for (Int_t j = 0; j < nThetaHistos; j++)    {
      if (tanThetaAbs  >= tThetaLow[j] && tanThetaAbs < tThetaHigh[j])  {
        hPullAdditionalCorrTheta[j]->Fill(pTPC, pull);
      }
    }
  }
/*
  // Mean, Sigma, chi^2/NDF of pull of different theta bins and all in one plot
  TCanvas* canvPullMean = new TCanvas("canvPullMean", "canvPullMean", 100,10,1380,800);
  canvPullMean->SetLogx(kTRUE);
  canvPullMean->SetGridx(kTRUE);
  canvPullMean->SetGridy(kTRUE);
  TCanvas* canvPullSigma = new TCanvas("canvPullSigma", "canvPullSigma", 100,10,1380,800);
  canvPullSigma->SetLogx(kTRUE);
  canvPullSigma->SetGridx(kTRUE);
  canvPullSigma->SetGridy(kTRUE);
  TCanvas* canvPullChi2 = new TCanvas("canvPullChi2", "canvPullChi2", 100,10,1380,800);
  canvPullChi2->SetLogx(kTRUE);
  canvPullChi2->SetGridx(kTRUE);
  canvPullChi2->SetGridy(kTRUE);
  

  TCanvas* canvPull[nThetaHistos + 1];
  for (Int_t i = 0, j = nThetaHistos; i < nThetaHistos + 1; i++, j--)  {
    canvPull[i] = new TCanvas(Form("canvPull_%d", i), "canvPull", 100,10,1380,800);
    canvPull[i]->cd();
    canvPull[i]->SetLogx(kTRUE);
    canvPull[i]->SetLogz(kTRUE);
    canvPull[i]->SetGrid(kTRUE, kTRUE);

    TH2D* hTemp = 0x0;
    TString thetaString = "";
    if (i == nThetaHistos)  {
      hTemp = hPull;
      thetaString = "tan(#Theta) integrated";
    }
    else {
      hTemp = hPullTheta[i];
      thetaString = Form("%.2f #leq |tan(#Theta)| < %.2f", tThetaLow[i], tThetaHigh[i]);
    }
    
    normaliseHisto(hTemp);
    hTemp->FitSlicesY();
    hTemp->GetYaxis()->SetNdivisions(12);
    hTemp->GetXaxis()->SetMoreLogLabels(kTRUE);
    TH1D* hTempMean = (TH1D*)gDirectory->Get(Form("%s_1", hTemp->GetName()));
    hTempMean->SetTitle(Form("mean(pull), %s", thetaString.Data()));
    hTempMean->GetXaxis()->SetMoreLogLabels(kTRUE);
    hTempMean->SetLineWidth(2);
    hTempMean->SetMarkerStyle(20);
    TH1D* hTempSigma = (TH1D*)gDirectory->Get(Form("%s_2", hTemp->GetName()));
    hTempSigma->SetTitle(Form("#sigma(pull), %s", thetaString.Data()));
    hTempSigma->GetXaxis()->SetMoreLogLabels(kTRUE);
    hTempSigma->SetLineColor(kMagenta);
    hTempSigma->SetMarkerStyle(20);
    hTempSigma->SetMarkerColor(kMagenta);
    hTempSigma->SetLineWidth(2);
    TH1D* hTempChi2 = (TH1D*)gDirectory->Get(Form("%s_chi2", hTemp->GetName()));
    hTempChi2->SetTitle(Form("#chi^{2} / NDF (pull), %s", thetaString.Data()));
    hTempChi2->GetXaxis()->SetMoreLogLabels(kTRUE);
    hTempChi2->SetLineColor(kMagenta + 2);
    hTempChi2->SetMarkerStyle(20);
    hTempChi2->SetMarkerColor(kMagenta + 2);
    hTempChi2->SetLineWidth(2);

    hTemp->DrawCopy("colz");
    hTempMean->DrawCopy("same");
    hTempSigma->DrawCopy("same");
    hTempChi2->Scale(-1./10.);
    hTempChi2->DrawCopy("same");
    hTempChi2->Scale(-10.);

    canvPullMean->cd();
    hTempMean->SetLineColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
    hTempMean->SetMarkerColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
    hTempMean->DrawCopy((i == 0 ? "" : "same"));

    canvPullSigma->cd();
    hTempSigma->SetLineColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
    hTempSigma->SetMarkerColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
    hTempSigma->DrawCopy((i == 0 ? "" : "same"));

    canvPullChi2->cd();
    hTempChi2->SetLineColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
    hTempChi2->SetMarkerColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
    hTempChi2->DrawCopy((i == 0 ? "" : "same"));
  }

  canvPullMean->BuildLegend();
  canvPullSigma->BuildLegend();
  canvPullChi2->BuildLegend();
*/
  // Histograms with additional correction
  TCanvas* canvPullMeanCorr = 0x0;
  TCanvas* canvPullSigmaCorr = 0x0;
  TCanvas* canvPullChi2Corr = 0x0;
  TCanvas* canvPullCorr[nThetaHistos + 1];
  for (Int_t i = 0; i < nThetaHistos + 1; i++) 
    canvPullCorr[i] = 0x0;
  
  if (hMap) {
    // Mean, Sigma, chi^2/NDF of pull of different theta bins and all in one plot
    canvPullMeanCorr = new TCanvas("canvPullMeanCorr", "canvPullMeanCorr", 100,10,1380,800);
    canvPullMeanCorr->SetLogx(kTRUE);
    canvPullMeanCorr->SetGridx(kTRUE);
    canvPullMeanCorr->SetGridy(kTRUE);
    canvPullSigmaCorr = new TCanvas("canvPullSigmaCorr", "canvPullSigmaCorr", 100,10,1380,800);
    canvPullSigmaCorr->SetLogx(kTRUE);
    canvPullSigmaCorr->SetGridx(kTRUE);
    canvPullSigmaCorr->SetGridy(kTRUE);
    canvPullChi2Corr = new TCanvas("canvPullChi2Corr", "canvPullChi2Corr", 100,10,1380,800);
    canvPullChi2Corr->SetLogx(kTRUE);
    canvPullChi2Corr->SetGridx(kTRUE);
    canvPullChi2Corr->SetGridy(kTRUE);
    
    for (Int_t i = 0, j = nThetaHistos; i < nThetaHistos + 1; i++, j--)  {
      canvPullCorr[i] = new TCanvas(Form("canvPullCorr_%d", i), "canvPullCorr", 100,10,1380,800);
      canvPullCorr[i]->cd();
      canvPullCorr[i]->SetLogx(kTRUE);
      canvPullCorr[i]->SetLogz(kTRUE);
      canvPullCorr[i]->SetGrid(kTRUE, kTRUE);

      TH2D* hTemp = 0x0;
      TString thetaString = "";
      
      if (i == nThetaHistos)  {
        hTemp = hPullAdditionalCorr;
        thetaString = "tan(#Theta) integrated";
      }
      else    {
        hTemp = hPullAdditionalCorrTheta[i];
        thetaString = Form("%.2f #leq |tan(#Theta)| < %.2f", tThetaLow[i], tThetaHigh[i]);
      }

      normaliseHisto(hTemp);
      hTemp->FitSlicesY();
      hTemp->GetYaxis()->SetNdivisions(12);
      hTemp->GetXaxis()->SetMoreLogLabels(kTRUE);
      TH1D* hTempMean = (TH1D*)gDirectory->Get(Form("%s_1", hTemp->GetName()));
      hTempMean->SetTitle(Form("mean(pull), %s", thetaString.Data()));
      hTempMean->GetXaxis()->SetMoreLogLabels(kTRUE);
      hTempMean->SetLineWidth(2);
      hTempMean->SetMarkerStyle(20);
      TH1D* hTempSigma = (TH1D*)gDirectory->Get(Form("%s_2", hTemp->GetName()));
      hTempSigma->SetTitle(Form("#sigma(pull), %s", thetaString.Data()));
      hTempSigma->GetXaxis()->SetMoreLogLabels(kTRUE);
      hTempSigma->SetLineColor(kMagenta);
      hTempSigma->SetMarkerStyle(20);
      hTempSigma->SetMarkerColor(kMagenta);
      hTempSigma->SetLineWidth(2);
      TH1D* hTempChi2 = (TH1D*)gDirectory->Get(Form("%s_chi2", hTemp->GetName()));
      hTempChi2->SetTitle(Form("#chi^{2} / NDF (pull), %s", thetaString.Data()));
      hTempChi2->GetXaxis()->SetMoreLogLabels(kTRUE);
      hTempChi2->SetLineColor(kMagenta + 2);
      hTempChi2->SetMarkerStyle(20);
      hTempChi2->SetMarkerColor(kMagenta + 2);
      hTempChi2->SetLineWidth(2);

      hTemp->DrawCopy("colz");
      hTempMean->DrawCopy("same");
      hTempSigma->DrawCopy("same");
      hTempChi2->Scale(-1./10.);
      hTempChi2->DrawCopy("same");
      hTempChi2->Scale(-10.);
  
      canvPullMeanCorr->cd();
      hTempMean->SetLineColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
      hTempMean->SetMarkerColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
      hTempMean->DrawCopy((i == 0 ? "" : "same"));
      
      canvPullSigmaCorr->cd();
      hTempSigma->SetLineColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
      hTempSigma->SetMarkerColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
      hTempSigma->DrawCopy((i == 0 ? "" : "same"));
      
      canvPullChi2Corr->cd();
      hTempChi2->SetLineColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
      hTempChi2->SetMarkerColor(1 + ((j >= 9) ? (39 + 2 * (j - 9)) : j));
      hTempChi2->DrawCopy((i == 0 ? "" : "same"));
    }
    
    canvPullMeanCorr->BuildLegend();
    canvPullSigmaCorr->BuildLegend();
    canvPullChi2Corr->BuildLegend();
  }
  
  
  
  
  
  fSave->cd();
  /*canvPullMean->Write();
  canvPullSigma->Write();
  canvPullChi2->Write();
  
  for (Int_t  i = 0; i < nThetaHistos + 1; i++) {
    canvPull[i]->Write();
  }*/
  
  canvPullMeanCorr->Write();
  canvPullSigmaCorr->Write();
  canvPullChi2Corr->Write();
  
  for (Int_t  i = 0; i < nThetaHistos + 1; i++) {
    canvPullCorr[i]->Write();
  }

  TNamed* info = new TNamed(Form("Theta map: %s\n\nSigma map: %s\n\nSplines file: %s\n\nSplines name: %s", pathNameThetaMap.Data(), 
                                 pathNameSigmaMap.Data(), pathNameSplinesFile.Data(), prSplinesName.Data()),
                            "info");
  info->Write();
  fSave->Close();
  
  return 0;
}
コード例 #21
0
void centralityCalibrationRD(TString inHiForestFileName,  TString outFileName)
{
  TFile *outFile = new TFile(outFileName,"RECREATE");
  TFile *inFile = TFile::Open(inHiForestFileName);
  TTree *fEvtTree = (TTree*)inFile->Get("hiEvtAnalyzer/HiTree");
  TTree *fSkimTree = (TTree*)inFile->Get("skimanalysis/HltTree");
  TTree *l1Tree = (TTree*)inFile->Get("UnpackerResults/L1UpgradeTree");
  TTree *hltTree = (TTree*)inFile->Get("hltanalysis/HltTree");
  TFile *inFileCen = new TFile("/data/yilmaz/centrality2015/friendly_centrality_HiForest_Streamer_run262315.root");
  TTree* tcen = (TTree*)inFileCen->Get("anaCentrality");
  l1Tree->AddFriend(tcen);

  Int_t l1_event, l1_run, l1_lumi;  

  vector<int>     *legacyregion_et;
  vector<int>     *legacyregion_gctEta;
  vector<int>     *legacyregion_bx;
  TBranch        *b_legacyregion_et;   //!
  TBranch        *b_legacyregion_gctEta;   //!
  TBranch        *b_legacyregion_bx;   //!


  Int_t HLT_HIL1MinimumBiasHF1AND_v1; 
  // Int_t L1_Centrality_ext0_100_HFplusANDminusTH0; 
  hltTree->SetBranchAddress("HLT_HIL1MinimumBiasHF1AND_v1",&HLT_HIL1MinimumBiasHF1AND_v1);
  // hltTree->SetBranchAddress("L1_Centrality_ext0_100_HFplusANDminusTH0",&L1_Centrality_ext0_100_HFplusORminusTH0);

  Int_t f_evt, f_run, f_lumi,f_phfCoincFilter3;
  Float_t vz;
  Int_t hiBin;
  float hiHF;

  legacyregion_et=0;
  legacyregion_gctEta=0;
  legacyregion_bx=0;
  l1Tree->SetBranchAddress("event",&l1_event);
  l1Tree->SetBranchAddress("run",&l1_run);
  l1Tree->SetBranchAddress("lumi",&l1_lumi);
  l1Tree->SetBranchAddress("legacyregion_et", &legacyregion_et, &b_legacyregion_et);
  l1Tree->SetBranchAddress("legacyregion_gctEta", &legacyregion_gctEta, &b_legacyregion_gctEta);
  l1Tree->SetBranchAddress("legacyregion_bx", &legacyregion_bx, &b_legacyregion_bx);
  l1Tree->SetBranchAddress("anaBin",&hiBin);

  fSkimTree->SetBranchAddress("phfCoincFilter3",&f_phfCoincFilter3);
  fEvtTree->SetBranchAddress("evt",&f_evt);
  fEvtTree->SetBranchAddress("run",&f_run);
  fEvtTree->SetBranchAddress("lumi",&f_lumi);
  fEvtTree->SetBranchAddress("vz",&vz);
  //fEvtTree->SetBranchAddress("hiBin",&hiBin);
  fEvtTree->SetBranchAddress("hiHF",&hiHF);

  Int_t pcollisionEventSelection;
  //Int_t pHBHENoiseFilterResultProducer;
  pcollisionEventSelection = 1;
  //pHBHENoiseFilterResultProducer = 1;
  //fSkimTree->SetBranchAddress("pcollisionEventSelection",&pcollisionEventSelection);
  //fSkimTree->SetBranchAddress("pHBHENoiseFilterResultProducer",&pHBHENoiseFilterResultProducer);

  TH2D *hcorrl1EtsumPlusVscorrl1EtsumMinus = new TH2D("hcorrl1EtsumPlusVscorrl1EtsumMinus","L1 EtsumPlus vs L1 EtsumMinus; L1 EtsumMinus ; L1 EtsumPlus",100,0,9000,100,0,9000); 
  TH2D *hcorrl1EtsumPlusVscorrl1EtsumMinusNoEvSel = new TH2D("hcorrl1EtsumPlusVscorrl1EtsumMinusNoEvSel","L1 EtsumPlus vs L1 EtsumMinus; L1 EtsumMinus ; L1 EtsumPlus",100,0,9000,100,0,9000);
  TH2D *hcorrl1EtsumVsofflineCentrality = new TH2D("hcorrl1EtsumVsofflineCentrality","L1 Etsum vs offline centrality; offline centrality ; L1 Etsum",100,0,200,100,0,9000);
  TH2D *hcorrofflineCentralityVsl1Etsum = new TH2D("hcorrofflineCentralityVsl1Etsum","Offline centrality vs L1 Etsum; L1 Etsum ; offline centrality",100,0,9000,100,0,200);  
  TH2D *hcorrL1CentralityVsfflineCentrality = new TH2D("hcorrL1CentralityVsfflineCentrality","Online centrality vs offline centrality; L1 Etsum ; offline centrality",200,0,200,200,0,200);  
  TH1D *hofflineCentrality = new TH1D("hofflineCentrality","Offline cent; Offline centrality; Entries",40,0.,200.);
  TH1D *hl1Etsum = new TH1D("hl1Etsum","L1 Etsum ; L1 Etsum; Entries ",40,0.,9000.);
  TH1D *hofflineEtsum = new TH1D("hofflineEtsum","Offline Etsum ; Offline Etsum; Entries ",40,0.,9000.);
  TH2D *hcorrOfflineEtsumVsL1Etsum = new TH2D("hcorrOfflineEtsumVsL1Etsum","Offline Etsum vs L1 Etsum; Offline Etsum; L1 Etsum",100,0.,9000.,100,0.,9000.);

  TProfile *profilel1EtsumVsofflineCentrality = new TProfile("profilel1EtsumVsofflineCentrality","L1 Etsum vs offline centrality; offline centrality ; L1 Etsum",100,0,200,0,9000);
  TProfile *profileofflineCentralityVsl1Etsum = new TProfile("profileofflineCentralityVsl1Etsum","Offline centrality vs L1 Etsum; L1 Etsum ; offline centrality",400,0,9000,0,200);
  TProfile *profileofflineCentralityVsl1Etsum_Calibration = new TProfile("profileofflineCentralityVsl1Etsum_Calibration","Offline centrality vs L1 Etsum; L1 Etsum ; offline centrality",200,0,9000,0,200);
  TProfile *profilel1EtsumVsofflineCentrality_Calibration = new TProfile("profilel1EtsumVsofflineCentrality_Calibration","Offline centrality vs L1 Etsum; L1 Etsum ; offline centrality",50,0,200,0,9000);
  TProfile *profilel1CentralityVsofflineCentrality = new TProfile("profilel1CentralityVsofflineCentrality","L1 centrality vs Offline Centrality; Offline Centrality ; L1 centrality",100,0,200,0,200);

  TH1D *fCenOffline = new TH1D("fCenOffline",";Offline Centrality",nBins,0,maxCen);
  TH1D *hOffline[NBINSCentrality];


  for(int i = 0; i < NBINSCentrality; ++i){
    hOffline[i]= new TH1D(Form("hOffline_Bin%d",i),Form("hOffline_Bin%d; Offline Centrality; Entries",i),220,-10,210);
  }

  TH1D *accepted[12];

  for(int i = 0; i < 12; ++i){
    accepted[i]= new TH1D(Form("accepted_cen%d",(int)(L1_THRESHOLD[i])),"",nBins,0,maxCen);
  }

  int countCalib = 0;
  Long64_t entries = l1Tree->GetEntries();
  //Long64_t entries=10000;
  for(Long64_t j = 0; j < entries; ++j)
  {
    if(j % 10000 == 0)
      printf("%lld / %lld\n",j,entries);

    // Only use good collision events ********
    fEvtTree->GetEntry(j);
    fSkimTree->GetEntry(j);
    l1Tree->GetEntry(j);
    hltTree->GetEntry(j);

    bool goodEvent = false;
    if((HLT_HIL1MinimumBiasHF1AND_v1==1 &&pcollisionEventSelection == 1 && f_phfCoincFilter3==1) && (TMath::Abs(vz) < 15))
      //if((HLT_HIL1MinimumBiasHF1AND_v1==1 &&pcollisionEventSelection == 1) && (TMath::Abs(vz) < 15))
    {
      goodEvent = true;
    }
    if(!goodEvent) continue;

    int etsum=0;
    int l1_etsumPlus=0;
    int l1_etsumMinus=0;

    int maxsizevector=legacyregion_gctEta->size();
    for (int i=0;i<maxsizevector; i++){
      if(legacyregion_bx->at(i)==0){
        if (legacyregion_gctEta->at(i)<=3) l1_etsumPlus=l1_etsumPlus+legacyregion_et->at(i);
        if (legacyregion_gctEta->at(i)>=18) l1_etsumMinus=l1_etsumMinus+legacyregion_et->at(i);
      }
    }



    etsum=l1_etsumPlus+l1_etsumMinus;
    //std::cout<<"etsum="<<etsum<<std::endl;
    //std::cout<<"l1_etsumPlus="<<l1_etsumPlus<<std::endl;
    //std::cout<<"l1_etsumMinus="<<l1_etsumMinus<<std::endl;
    profileofflineCentralityVsl1Etsum_Calibration->Fill(etsum,hiBin); 
    profilel1EtsumVsofflineCentrality_Calibration->Fill(hiBin,etsum); 
    countCalib++;
  }
  //************** second loop ************** 

  TF1 *fprofileofflineCentralityVsl1Etsum_Calibration = new TF1("fprofileofflineCentralityVsl1Etsum_Calibration","pol9",0,3500);
  profileofflineCentralityVsl1Etsum_Calibration->Fit("fprofileofflineCentralityVsl1Etsum_Calibration");
  TF1 *fprofileofflinel1EtsumVsCentrality_Calibration = new TF1("fprofileofflinel1EtsumVsCentrality_Calibration","pol9",0,7000);
  profilel1EtsumVsofflineCentrality_Calibration->Fit("fprofileofflinel1EtsumVsCentrality_Calibration");


  printf("Matching entries: %d\n",countCalib);
  double L1centrality=0.;


  for(Long64_t j = 0; j < entries; ++j)
  {
    if(j % 10000 == 0)
      printf("%lld / %lld\n",j,entries);

    // Only use good collision events ********
    fEvtTree->GetEntry(j);
    fSkimTree->GetEntry(j);
    l1Tree->GetEntry(j);
    hltTree->GetEntry(j);

    bool goodEvent = false;
    if((HLT_HIL1MinimumBiasHF1AND_v1==1 &&pcollisionEventSelection == 1 && f_phfCoincFilter3==1) && (TMath::Abs(vz) < 15))
      //if((HLT_HIL1MinimumBiasHF1AND_v1==1 &&pcollisionEventSelection == 1) && (TMath::Abs(vz) < 15))

    {
      goodEvent = true;
    }
    if(!goodEvent) continue;

    int etsum=0;
    int l1_etsumPlus=0;
    int l1_etsumMinus=0;
    int maxsizevector2=legacyregion_gctEta->size();
    for (int i=0;i<maxsizevector2; i++){
      if(legacyregion_bx->at(i)==0){
        if (legacyregion_gctEta->at(i)<=3) l1_etsumPlus=l1_etsumPlus+legacyregion_et->at(i);
        if (legacyregion_gctEta->at(i)>=18) l1_etsumMinus=l1_etsumMinus+legacyregion_et->at(i);
      }
    }

    etsum=l1_etsumPlus+l1_etsumMinus;
    //printf("et value %d\n",etsum);
    //printf("hiBin %d\n",hiBin);
    //printf("hiHF %f\n",hiHF);

    hcorrl1EtsumPlusVscorrl1EtsumMinus->Fill(l1_etsumMinus,l1_etsumPlus);
    hcorrl1EtsumVsofflineCentrality->Fill(hiBin,etsum);
    hcorrofflineCentralityVsl1Etsum->Fill(etsum,hiBin);
    hofflineCentrality->Fill(hiBin);
    hl1Etsum->Fill(etsum);
    hofflineEtsum->Fill(hiHF);
    hcorrOfflineEtsumVsL1Etsum->Fill(hiHF,etsum); 
    profileofflineCentralityVsl1Etsum->Fill(etsum,hiBin);  
    profilel1EtsumVsofflineCentrality->Fill(hiBin,etsum);  	  
    //L1centrality=fprofileofflineCentralityVsl1Etsum_Calibration->Eval(etsum);
    L1centrality=fprofileofflinel1EtsumVsCentrality_Calibration->GetX(etsum);
    //printf("L1centrality %f\n",L1centrality);
    hcorrL1CentralityVsfflineCentrality->Fill(hiBin,L1centrality);
    profilel1CentralityVsofflineCentrality->Fill(hiBin,L1centrality);

    double Etsum_Bin[10];
    double newResLimit[10];
    for (int j=0; j<10;j++){
      if (j==0 || (j%2)==0){
        newResLimit[j]=limit[j]+deltaC[j];
      }
      else {newResLimit[j]=limit[j]-deltaC[j];}
      Etsum_Bin[j]=fprofileofflinel1EtsumVsCentrality_Calibration->Eval((double)(newResLimit[j]));
      //std::cout<< "etSum = " << Etsum_Bin[j] << endl;
    }

    if(etsum>Etsum_Bin[0]) {hOffline[0]->Fill(hiBin);} 
    if(etsum>Etsum_Bin[2] && etsum<Etsum_Bin[1]) {hOffline[1]->Fill(hiBin);}
    if(etsum>Etsum_Bin[4] && etsum<Etsum_Bin[3]) {hOffline[2]->Fill(hiBin);}
    if(etsum>Etsum_Bin[6] && etsum<Etsum_Bin[5]) {hOffline[3]->Fill(hiBin);}
    if(etsum>Etsum_Bin[8] && etsum<Etsum_Bin[7]) {hOffline[4]->Fill(hiBin);}
    if(etsum<Etsum_Bin[9]) {hOffline[5]->Fill(hiBin);}

    fCenOffline->Fill(hiBin);

    for(int k = 0; k < 12; ++k){
      if(L1centrality>L1_THRESHOLD[k]){
        accepted[k]->Fill(hiBin);
      }
    }
  }  

  outFile->cd();
  hcorrl1EtsumPlusVscorrl1EtsumMinus->Write();
  hcorrl1EtsumPlusVscorrl1EtsumMinusNoEvSel->Write();
  hcorrl1EtsumVsofflineCentrality->Write();
  hcorrofflineCentralityVsl1Etsum->Write();
  hofflineCentrality->Write();
  hl1Etsum->Write();
  hofflineEtsum->Write();
  hcorrOfflineEtsumVsL1Etsum->Write();
  profilel1EtsumVsofflineCentrality->Write();
  profileofflineCentralityVsl1Etsum->Write();
  profileofflineCentralityVsl1Etsum_Calibration->Write();
  fprofileofflineCentralityVsl1Etsum_Calibration->SetName("fprofileofflineCentralityVsl1Etsum_Calibration");
  fprofileofflineCentralityVsl1Etsum_Calibration->Write();
  fprofileofflinel1EtsumVsCentrality_Calibration->SetName("fprofileofflinel1EtsumVsCentrality_Calibration");
  fprofileofflinel1EtsumVsCentrality_Calibration->Write();
  hcorrL1CentralityVsfflineCentrality->Write();
  profilel1CentralityVsofflineCentrality->Write();
  profilel1EtsumVsofflineCentrality_Calibration->Write();

  for(int i = 0; i < NBINSCentrality; ++i){
    hOffline[i]->Write();
  }

  TGraphAsymmErrors *a[12];
  for(int k = 0; k < 12; ++k){
    a[k] = new TGraphAsymmErrors();
    a[k]->BayesDivide(accepted[k],fCenOffline);
    a[k]->SetName(Form("asymm_cen_%d_cen",(int)(L1_THRESHOLD[k])));
  }  
  fCenOffline->Write();

  for(int k = 0; k < 12; ++k){
    accepted[k]->Write();
    a[k]->Write();
  }
  outFile->Close();
} 
コード例 #22
0
ファイル: mk_tree.C プロジェクト: c-dilks/scalers12
void mk_tree(const char * acc_file="datfiles/acc.dat")
{
  // read acc file into tree
  TTree * acc = new TTree("acc","counts tree from acc.dat");
  char cols[2048];
  char bbc_cols[256];
  char zdc_cols[256];
  char vpd_cols[256];
  for(Int_t i=0; i<=7; i++)
  {
    if(i==0) 
    {
      sprintf(bbc_cols,"bbc_%d/D",i);
      sprintf(zdc_cols,"zdc_%d/D",i);
      sprintf(vpd_cols,"vpd_%d/D",i);
    }
    else
    {
      sprintf(bbc_cols,"%s:bbc_%d/D",bbc_cols,i);
      sprintf(zdc_cols,"%s:zdc_%d/D",zdc_cols,i);
      sprintf(vpd_cols,"%s:vpd_%d/D",vpd_cols,i);
    };
  };
  sprintf(cols,"i/I:runnum/I:fi/I:fill/I:t/D:bx/I:%s:%s:%s:tot_bx/D:blue/I:yell/I",bbc_cols,zdc_cols,vpd_cols);
  printf("%s\n",cols);
  acc->ReadFile(acc_file,cols);

  acc->Print();

  Int_t IMAX_tmp = acc->GetMaximum("i");
  const Int_t IMAX = IMAX_tmp;

  // set branch addresses to read through acc tree
  Int_t index,runnum,fill_index,fill,bx;
  Double_t bbc[8];
  Double_t zdc[8];
  Double_t vpd[8];
  Double_t time;
  Double_t tot_bx;
  Int_t blue,yell;
  acc->SetBranchAddress("i",&index);
  acc->SetBranchAddress("runnum",&runnum);
  acc->SetBranchAddress("fi",&fill_index);
  acc->SetBranchAddress("fill",&fill);
  acc->SetBranchAddress("t",&time);
  acc->SetBranchAddress("bx",&bx);
  char str[16];
  for(Int_t i=0; i<8; i++) { sprintf(str,"bbc_%d",i); acc->SetBranchAddress(str,&bbc[i]); };
  for(Int_t i=0; i<8; i++) { sprintf(str,"zdc_%d",i); acc->SetBranchAddress(str,&zdc[i]); };
  for(Int_t i=0; i<8; i++) { sprintf(str,"vpd_%d",i); acc->SetBranchAddress(str,&vpd[i]); };
  acc->SetBranchAddress("tot_bx",&tot_bx);
  acc->SetBranchAddress("blue",&blue);
  acc->SetBranchAddress("yell",&yell);


  // build arrays for restructuring; arrays are needed so that
  // we can implement bXing shift corrections
  Double_t bbce_arr[IMAX][120];
  Double_t bbcw_arr[IMAX][120];
  Double_t bbcx_arr[IMAX][120];
  Double_t zdce_arr[IMAX][120];
  Double_t zdcw_arr[IMAX][120];
  Double_t zdcx_arr[IMAX][120];
  Double_t vpde_arr[IMAX][120];
  Double_t vpdw_arr[IMAX][120];
  Double_t vpdx_arr[IMAX][120];
  Int_t runnum_arr[IMAX];
  Int_t fi_arr[IMAX];
  Int_t fill_arr[IMAX];
  Double_t time_arr[IMAX];
  Double_t tot_bx_arr[IMAX][120];
  Int_t blue_arr[IMAX][120];
  Int_t yell_arr[IMAX][120];
  Bool_t kicked_arr[IMAX][120];


  // restructure tree into one suitable for analysis
  TTree * sca = new TTree("sca","restructured tree");
  Double_t bbce,bbcw,bbcx; // e=east, w=west, x=coincidence
  Double_t zdce,zdcw,zdcx;
  Double_t vpde,vpdw,vpdx;
  Bool_t okEntry,kicked;
  sca->Branch("i",&index,"i/I");
  sca->Branch("runnum",&runnum,"runnum/I");
  sca->Branch("fi",&fill_index,"fi/I");
  sca->Branch("fill",&fill,"fill/I");
  sca->Branch("t",&time,"t/D");
  sca->Branch("bx",&bx,"bx/I");
  sca->Branch("bbce",&bbce,"bbce/D");
  sca->Branch("bbcw",&bbcw,"bbcw/D");
  sca->Branch("bbcx",&bbcx,"bbcx/D");
  sca->Branch("zdce",&zdce,"zdce/D");
  sca->Branch("zdcw",&zdcw,"zdcw/D");
  sca->Branch("zdcx",&zdcx,"zdcx/D");
  sca->Branch("vpde",&vpde,"vpde/D");
  sca->Branch("vpdw",&vpdw,"vpdw/D");
  sca->Branch("vpdx",&vpdx,"vpdx/D");
  sca->Branch("tot_bx",&tot_bx,"tot_bx/D");
  sca->Branch("blue",&blue,"blue/I");
  sca->Branch("yell",&yell,"yell/I");
  sca->Branch("kicked",&kicked,"kicked/O");


  // read kicked bunches tree from "kicked" file
  TTree * kicked_tr = new TTree();
  kicked_tr->ReadFile("kicked","fill/I:bx/I:spinbit/I");
  Int_t kicked_fill,kicked_bx,kicked_spinbit;
  kicked_tr->SetBranchAddress("fill",&kicked_fill);
  kicked_tr->SetBranchAddress("bx",&kicked_bx);
  kicked_tr->SetBranchAddress("spinbit",&kicked_spinbit);
  
  for(Int_t q=0; q<acc->GetEntries(); q++)
  {
    acc->GetEntry(q);

    // -- see doc for bit details
    // BBC, ZDC, VPD bits: [ x w e ]
    bbce = bbc[1] + bbc[3] + bbc[5] + bbc[7]; // e + we + xe + xwe
    bbcw = bbc[2] + bbc[3] + bbc[6] + bbc[7]; // w + we + xw + xwe
    bbcx = bbc[3] + bbc[7]; // we + xwe

    zdce = zdc[1] + zdc[3] + zdc[5] + zdc[7]; // e + we + xe + xwe
    zdcw = zdc[2] + zdc[3] + zdc[6] + zdc[7]; // w + we + xw + xwe
    zdcx = zdc[3] + zdc[7]; // we + xwe
    
    vpde = vpd[1] + vpd[3] + vpd[5] + vpd[7]; // e + we + xe + xwe
    vpdw = vpd[2] + vpd[3] + vpd[6] + vpd[7]; // w + we + xw + xwe
    vpdx = vpd[3] + vpd[7]; // we + xwe


    // KICKED BUNCHES
    // manually omit empty bunches documented in pathologies.dat -- CLEAN UP PROCEDURE
    // (see 09.01.14 log entry)
    okEntry=true;
    // kicked bunches (presumably empty) 
    /*
    if(fill==17384 && (bx==29 || bx==30 || bx==117)) okEntry=false;
    if(fill==17416 && bx==79) okEntry=false;
    if(fill==17491 && bx==105) okEntry=false;
    if(fill==17519 && (bx==94 || bx==109)) okEntry=false;
    if(fill==17520 && bx==0) okEntry=false;
    if(fill==17529 && bx==97) okEntry=false;
    if(fill==17534 && bx==112) okEntry=false;
    if(fill==17553 && bx==73) okEntry=false;
    if(fill==17554 && (bx==7 || bx==14)) okEntry=false;
    if(fill==17555 && bx==61) okEntry=false;
    if(fill==17576 && bx==94) okEntry=false;
    // afterpulse-like bunches -- remove 1st 2 bunches after abort gaps 
    //if(fill==17512 && (bx>=40 && bx<=59)) okEntry=false;
    //if((fill>=17513 && fill<=17520) && ((bx>=0 && bx<=19) || (bx>=40 && bx<=59))) okEntry=false;
    */
    for(Int_t kk=0; kk<kicked_tr->GetEntries(); kk++)
    {
      kicked_tr->GetEntry(kk);
      if(fill==kicked_fill && bx==kicked_bx) okEntry=false;
    };
    
    kicked=!okEntry; // cleaned up analysis
    //kicked=0; // take all bXings
    

    // store data into arrays, implementing bXing shift corrections on scalers
    if(fill==16570 ||
       fill==16567)
    {
      bbce_arr[index-1][(bx+113)%120] = bbce; // shift down 7 bXings
      bbcw_arr[index-1][(bx+113)%120] = bbcw;
      bbcx_arr[index-1][(bx+113)%120] = bbcx;
      zdce_arr[index-1][(bx+113)%120] = zdce; // shift down 7 bXings
      zdcw_arr[index-1][(bx+113)%120] = zdcw;
      zdcx_arr[index-1][(bx+113)%120] = zdcx;
      vpde_arr[index-1][(bx+113)%120] = vpde; // shift down 7 bXings
      vpdw_arr[index-1][(bx+113)%120] = vpdw;
      vpdx_arr[index-1][(bx+113)%120] = vpdx;
    }
    else if(fill == 16582 ||
            fill == 16586 ||
            fill == 16587 || 
            fill == 16592 || 
            fill == 16593 || 
            fill == 16594 || 
            fill == 16597 || 
            fill == 16602)
    {
      bbce_arr[index-1][bx] = bbce; // no shift
      bbcw_arr[index-1][bx] = bbcw;
      bbcx_arr[index-1][bx] = bbcx;
      zdce_arr[index-1][bx] = zdce; // no shift
      zdcw_arr[index-1][bx] = zdcw;
      zdcx_arr[index-1][bx] = zdcx;
      vpde_arr[index-1][(bx+1)%120] = vpde; // shift up 1 bXings
      vpdw_arr[index-1][(bx+1)%120] = vpdw;
      vpdx_arr[index-1][(bx+1)%120] = vpdx;
    }
    else
    {
      bbce_arr[index-1][bx] = bbce;
      bbcw_arr[index-1][bx] = bbcw;
      bbcx_arr[index-1][bx] = bbcx;
      zdce_arr[index-1][bx] = zdce;
      zdcw_arr[index-1][bx] = zdcw;
      zdcx_arr[index-1][bx] = zdcx;
      vpde_arr[index-1][bx] = vpde;
      vpdw_arr[index-1][bx] = vpdw;
      vpdx_arr[index-1][bx] = vpdx;
    };

    runnum_arr[index-1] = runnum;
    fi_arr[index-1] = fill_index;
    fill_arr[index-1] = fill;
    time_arr[index-1] = time;
    tot_bx_arr[index-1][bx] = tot_bx;
    blue_arr[index-1][bx] = blue;
    yell_arr[index-1][bx] = yell;
    kicked_arr[index-1][bx] = kicked;
  };


  // fill restructured tree
  for(Int_t i=0; i<IMAX; i++)
  {
    index = i+1;
    runnum = runnum_arr[i];
    fill_index = fi_arr[i];
    fill = fill_arr[i];

    time = time_arr[i];
    for(Int_t b=0; b<120; b++)
    {
      bx = b;
      bbce = bbce_arr[i][b];
      bbcw = bbcw_arr[i][b];
      bbcx = bbcx_arr[i][b];
      zdce = zdce_arr[i][b];
      zdcw = zdcw_arr[i][b];
      zdcx = zdcx_arr[i][b];
      vpde = vpde_arr[i][b];
      vpdw = vpdw_arr[i][b];
      vpdx = vpdx_arr[i][b];
      tot_bx = tot_bx_arr[i][b];
      blue = blue_arr[i][b];
      yell = yell_arr[i][b];
      kicked = kicked_arr[i][b];
      sca->Fill();
    };
  };

  TFile * outfile = new TFile("counts.root","RECREATE");
  acc->Write("acc");
  sca->Write("sca");
  printf("counts.root written\n");
};
コード例 #23
0
ファイル: DrawCosmicResult.C プロジェクト: laerad84/Analysis
void DrawCosmicResult(){
  
  TFile* tf = new TFile("Cosmic3Out.root");
  TTree* trin = (TTree*)tf->Get("trOut");


  const int nCSI = 2716;
  Int_t    RunNumber;
  Int_t    EventNumber;
  Double_t ScintiSignal = 0;
  Double_t ScintiHHTime = -500.;
  Double_t ScintiTime   =-500.;
  Int_t    nCSIDigi     = 0;
  Double_t CSIDigiE[nCSI];//nCSIDigi
  Double_t CSIDigiTime[nCSI];//nCSIDigi
  Double_t CSIDigiHHTime[nCSI];//nCSIDigi
  Int_t    CSIDigiID[nCSI];//nCSIDigi
  Double_t CSIDigiSignal[nCSI];//nCSIDigi
  Double_t FitP0[2];
  Double_t FitP1[2];
  Double_t FitChisq[2];
  Double_t CSIDigiDeltaT0[nCSI];//nCSIDigi
  Double_t CSIDigiDeltaT1[nCSI];//nCSIDigi
  Int_t    CosmicTrigUp;
  Int_t    CosmicTrigDn;
  Double_t Roh;
  Double_t Theta;

  trin->SetBranchAddress( "RunNumber"     , &RunNumber      );
  trin->SetBranchAddress( "EventNumber"   , &EventNumber    );
  trin->SetBranchAddress( "ScintiSignal"  , &ScintiSignal   );
  trin->SetBranchAddress( "ScintiHHTimne" , &ScintiHHTime   );
  trin->SetBranchAddress( "ScintiTime"    , &ScintiTime     );
  trin->SetBranchAddress( "nCSIDigi"      , &nCSIDigi       );
  trin->SetBranchAddress( "CSIDigiE"      , CSIDigiE        );
  trin->SetBranchAddress( "CSIDigiTime"   , CSIDigiTime     );
  trin->SetBranchAddress( "CSIDigiHHTime" , CSIDigiHHTime   );
  trin->SetBranchAddress( "CSIDigiID"     , CSIDigiID       );
  trin->SetBranchAddress( "CSIDigiSignal" , CSIDigiSignal   );
  trin->SetBranchAddress( "CSIDigiDeltaT0" , CSIDigiDeltaT0 );
  trin->SetBranchAddress( "CSIDigiDeltaT1" , CSIDigiDeltaT1 );
  trin->SetBranchAddress( "FitP0"         , FitP0           );
  trin->SetBranchAddress( "FitP1"         , FitP1           );
  trin->SetBranchAddress( "FitChisq"      , FitChisq        );
  trin->SetBranchAddress( "CosmicTrigUp"  , &CosmicTrigUp   );
  trin->SetBranchAddress( "CosmicTrigDn"  , &CosmicTrigDn   );
  trin->SetBranchAddress( "Roh"           , &Roh            );
  trin->SetBranchAddress( "Theta"         , &Theta          );

  TFile* tfout = new TFile("CosmicOut_hist3.root", "recreate");
  TH2D* hisDeltaChannel = new TH2D("hisDeltaChannel","hisDeltaChannel",2716,0,2716,100,-10,10);
  TH1D* hisDelta[2716];
  TGraphErrors* grDelta = new TGraphErrors();
  TGraphErrors* grRES   = new TGraphErrors(); 
  TCanvas *can = new TCanvas("can","",800,800);


  for( int i = 0; i< 2716; i++){
    hisDelta[i] = new TH1D(Form("hisDelta%d",i ),Form("hisDelta%d",i),100,-10,10);
  }

  for( int ievent = 0; ievent < trin->GetEntries(); ievent++){

    trin->GetEntry(ievent);
    
    for( int idigi = 0; idigi < nCSIDigi ; idigi++){
      hisDelta[ CSIDigiID[ idigi ] ]->Fill( CSIDigiDeltaT1[ idigi ] );
      hisDeltaChannel->Fill( CSIDigiID[ idigi  ] , CSIDigiDeltaT1[ idigi ] );
      //std::cout  << CSIDigiID[ idigi ] << std::endl;
    }
  }
  for( int i = 0; i< 2716; i++){
    //std::cout << hisDelta[i]->GetEntries() << std::endl;
    if( hisDelta[i]->GetEntries() > 10){
      int rst = hisDelta[i]->Fit("gaus","Q","",hisDelta[i]->GetBinCenter( hisDelta[i]->GetMaximumBin() ) - 3, hisDelta[i]->GetBinCenter( hisDelta[i]->GetMaximumBin() )+3);
      TF1* func = NULL;
      func = hisDelta[i]->GetFunction("gaus");
      if( func != NULL ){
	grDelta->SetPoint( grDelta->GetN(), i, func->GetParameter(1));
	grDelta->SetPointError( grDelta->GetN()-1, 0, func->GetParError(2));
	grRES->SetPoint( grRES->GetN() , i , func->GetParameter(2));
      }
    }
    /*
    hisDelta[i]->Draw();
    can->Modified();
    can->Update();
    getchar();
    */
    hisDelta[ i ]  ->Write(); 
  }

  std::ofstream ofs("TimeResolutionCosmic3.dat");
  int    ID[2716];
  double Delta[2716];
  double Resolution[2716];
  for( int i = 0; i< 2716; i++){
    Resolution[i] = 0xFFFF;
    Delta[i]      = 0xFFFF;
  }
  for( int i = 0; i< grRES->GetN(); i++){
    Delta[(int)(grDelta->GetX()[i])] = grDelta->GetY()[i];
    Resolution[(int)(grRES->GetX()[i])] = grRES->GetY()[i] ;
  }
  for( int i = 0; i< 2716; i++){
    ofs << i             << "\t" 
	<< Delta[i]      << "\t"
	<< Resolution[i] << "\n";
  }
  
  grDelta->SetNameTitle("grDelta","grDelta");
  grRES->SetNameTitle("grRES","grRES");
  grDelta->Write();
  grRES->Write();
  hisDeltaChannel->Write();
  tfout->Close();
  ofs.close();
}
コード例 #24
0
void cutFlowStudyMu( TString weightFile = "TMVAClassificationPtOrd_qqH115vsWZttQCD_Cuts.weights.xml",
		     Double_t effS_ = 0.3) 
{
  
  ofstream out("cutFlow-MuTauStream.txt");
  out.precision(4);

  TMVA::Tools::Instance();
  TMVA::Reader *reader = new TMVA::Reader( "!Color:!Silent" );   

  Float_t pt1, pt2;
  Float_t Deta, Mjj;
  Float_t eta1,eta2;

  reader->AddVariable( "pt1", &pt1);
  reader->AddVariable( "pt2", &pt2);
  reader->AddVariable( "Deta",&Deta);
  reader->AddVariable( "Mjj", &Mjj);
  reader->AddSpectator("eta1",&eta1);
  reader->AddSpectator("eta2",&eta2);
  reader->BookMVA( "Cuts", TString("/home/llr/cms/lbianchini/CMSSW_3_9_9/src/Bianchi/TauTauStudies/test/Macro/weights/")+weightFile ); 
 
  TFile *fFullSignalVBF           = new TFile("/data_CMS/cms/lbianchini//MuTauStream2011/treeMuTauStream_VBFH115-Mu-powheg-PUS1.root","READ"); 
  TFile *fFullSignalGGH           = new TFile("/data_CMS/cms/lbianchini//MuTauStream2011/treeMuTauStream_GGFH115-Mu-powheg-PUS1.root","READ");  
  TFile *fFullBackgroundDYTauTau  = new TFile("/data_CMS/cms/lbianchini//MuTauStream2011/treeMuTauStream_DYToTauTau-Mu-20-PUS1.root","READ"); 
  TFile *fFullBackgroundDYMuMu    = new TFile("/data_CMS/cms/lbianchini//MuTauStream2011/treeMuTauStream_DYToMuMu-20-PUS1.root","READ"); 
  TFile *fFullBackgroundWJets     = new TFile("/data_CMS/cms/lbianchini//MuTauStream2011/treeMuTauStream_WJets-Mu-madgraph-PUS1.root","READ"); 
  TFile *fFullBackgroundQCD       = new TFile("/data_CMS/cms/lbianchini//MuTauStream2011/treeMuTauStream_QCDmu.root","READ"); 
  TFile *fFullBackgroundTTbar     = new TFile("/data_CMS/cms/lbianchini//MuTauStream2011/treeMuTauStream_TTJets-Mu-madgraph-PUS1.root","READ"); 
  TFile *fFullBackgroundDiBoson   = new TFile("/data_CMS/cms/lbianchini//MuTauStream2011/treeMuTauStream_DiBoson-Mu.root","READ"); 

  // OpenNTuples
  TString fSignalNameVBF           = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011/v2/nTupleVBFH115-Mu-powheg-PUS1_Open_MuTauStream.root";
  TString fSignalNameGGH           = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011/v2/nTupleGGFH115-Mu-powheg-PUS1_Open_MuTauStream.root";
  TString fBackgroundNameDYTauTau  = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011/v2/nTupleDYToTauTau-Mu-20-PUS1_Open_MuTauStream.root";
  TString fBackgroundNameDYMuMu  = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011/v2/nTupleDYToMuMu-20-PUS1_Open_MuTauStream.root";
  TString fBackgroundNameWJets     = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011/v2/nTupleWJets-Mu-madgraph-PUS1_Open_MuTauStream.root";
  TString fBackgroundNameQCD       = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011/v2/nTupleQCDmu_Open_MuTauStream.root";
  TString fBackgroundNameTTbar     = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011/v2/nTupleTTJets-Mu-madgraph-PUS1_Open_MuTauStream.root";
  TString fBackgroundNameDiBoson   = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011/v2/nTupleDiBoson-Mu_Open_MuTauStream.root";

  TFile *fSignalVBF(0); 
  TFile *fSignalGGH(0); 
  TFile *fBackgroundDYTauTau(0);
  TFile *fBackgroundDYMuMu(0);
  TFile *fBackgroundWJets(0);
  TFile *fBackgroundQCD(0);
  TFile *fBackgroundTTbar(0);
  TFile *fBackgroundDiBoson(0);
 
  fSignalVBF          = TFile::Open( fSignalNameVBF ); 
  fSignalGGH          = TFile::Open( fSignalNameGGH ); 
  fBackgroundDYTauTau = TFile::Open( fBackgroundNameDYTauTau ); 
  fBackgroundDYMuMu   = TFile::Open( fBackgroundNameDYMuMu ); 
  fBackgroundWJets    = TFile::Open( fBackgroundNameWJets ); 
  fBackgroundQCD      = TFile::Open( fBackgroundNameQCD ); 
  fBackgroundTTbar    = TFile::Open( fBackgroundNameTTbar ); 
  fBackgroundDiBoson  = TFile::Open( fBackgroundNameDiBoson ); 

  if(!fSignalVBF || !fBackgroundDYTauTau || !fBackgroundWJets || !fBackgroundQCD || !fBackgroundTTbar ||
     !fSignalGGH || !fBackgroundDYMuMu || !fBackgroundDiBoson ){
    std::cout << "ERROR: could not open files" << std::endl;
    exit(1);
  }

  TString tree = "outTreePtOrd";

  TTree *signalVBF           = (TTree*)fSignalVBF->Get(tree);
  TTree *signalGGH           = (TTree*)fSignalGGH->Get(tree);
  TTree *backgroundDYTauTau  = (TTree*)fBackgroundDYTauTau->Get(tree);
  TTree *backgroundDYMuMu    = (TTree*)fBackgroundDYMuMu->Get(tree);
  TTree *backgroundWJets     = (TTree*)fBackgroundWJets->Get(tree);
  TTree *backgroundQCD       = (TTree*)fBackgroundQCD->Get(tree);
  TTree *backgroundTTbar     = (TTree*)fBackgroundTTbar->Get(tree);
  TTree *backgroundDiBoson   = (TTree*)fBackgroundDiBoson->Get(tree);

  // here I define the map between a sample name and its tree
  std::map<std::string,TTree*> tMap;
  tMap["ggH115"]=signalGGH;
  tMap["qqH115"]=signalVBF;
  tMap["Ztautau"]=backgroundDYTauTau;
  tMap["Zmumu"]=backgroundDYMuMu;
  tMap["Wjets"]=backgroundWJets;
  tMap["QCD"]=backgroundQCD;
  tMap["TTbar"]=backgroundTTbar;
  tMap["DiBoson"]=backgroundDiBoson;

  std::map<std::string,TTree*>::iterator jt;

  Float_t pt1_, pt2_;
  Float_t Deta_, Mjj_;
  Float_t Dphi,diTauSVFitPt,diTauSVFitEta,diTauVisMass,diTauSVFitMass,ptL1,ptL2,etaL1,etaL2,diTauCharge,MtLeg1,numPV,combRelIsoLeg1,sampleWeight,ptVeto,HLT;
  Int_t tightestHPSWP;

  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////



  // here I choose the order in the stack
  std::vector<string> samples;
  samples.push_back("ggH115");
  samples.push_back("qqH115");
  samples.push_back("DiBoson");
  samples.push_back("TTbar");
  samples.push_back("Wjets");
  samples.push_back("Zmumu");
  samples.push_back("Ztautau");
  samples.push_back("QCD");

  std::map<std::string,float> crossSec;
  crossSec["ggH115"]=( 7.65e-02 * 18.13 );
  crossSec["qqH115"]=( 0.1012);
  crossSec["DiBoson"]=( -1  );
  crossSec["TTbar"]=( 157.5 );
  crossSec["Wjets"]=( 31314.0);
  crossSec["Zmumu"]=( 1666  );
  crossSec["Ztautau"]=( 1666  );
  crossSec["QCD"]=( 296600000*0.0002855 );

  float Lumi = 1000;


  // here I choose the order in the stack
  std::vector<string> filters;
  filters.push_back("total");
  filters.push_back("vertex");
  filters.push_back("1-mu");
  filters.push_back("0-e");
  filters.push_back("mu-ID");
  filters.push_back("tau-ID");
  filters.push_back("Delta R mu-tau");
  filters.push_back("mu-iso");
  filters.push_back("tau-iso");
  filters.push_back("Mt");
  filters.push_back("OS");
  filters.push_back("2-jets");
  filters.push_back("VBF cuts");
  filters.push_back("jet-veto");
  filters.push_back("HLT");

  // here I define the map between a sample name and its file ptr
  std::map<std::string,TFile*> fullMap;
  fullMap["ggH115"]   = fFullSignalGGH;
  fullMap["qqH115"]   = fFullSignalVBF;
  fullMap["Ztautau"]  = fFullBackgroundDYTauTau;
  fullMap["Zmumu"]    = fFullBackgroundDYMuMu;
  fullMap["Wjets"]    = fFullBackgroundWJets;
  fullMap["QCD"]      = fFullBackgroundQCD;
  fullMap["TTbar"]    = fFullBackgroundTTbar;
  fullMap["DiBoson"]  = fFullBackgroundDiBoson;

  std::map<std::string,TFile*>::iterator it;

  std::map<std::string,float> cutMap_allEventsFilter;
  std::map<std::string,float> cutMap_allEventsFilterE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    float totalEquivalentEvents = allEvents->GetEffectiveEntries();
    float tot = totalEvents;
    if(crossSec[it->first]>0) tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    cutMap_allEventsFilter[it->first] = tot;
    cutMap_allEventsFilterE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
  }
  std::map<std::string,float> cutMap_vertexScrapingFilter;
  std::map<std::string,float> cutMap_vertexScrapingFilterE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    allEvents = (TH1F*)(it->second)->Get("vertexScrapingFilter/totalEvents");
    float tot =  allEvents->GetBinContent(1);
    float totalEquivalentEvents = allEvents->GetEffectiveEntries();
    if(crossSec[it->first]>0){
      tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
      //totalEquivalentEvents *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    }
    cutMap_vertexScrapingFilter[it->first] = tot;
    cutMap_vertexScrapingFilterE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
  }
  std::map<std::string,float> cutMap_oneElectronFilter;
  std::map<std::string,float> cutMap_oneElectronFilterE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    allEvents = (TH1F*)(it->second)->Get("oneMuonFilter/totalEvents");
    float tot =  allEvents->GetBinContent(1);
    float totalEquivalentEvents = allEvents->GetEffectiveEntries();
    if(crossSec[it->first]>0){
      tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
      //totalEquivalentEvents *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    }
    cutMap_oneElectronFilter[it->first] = tot;
    cutMap_oneElectronFilterE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
  }
  std::map<std::string,float> cutMap_noMuonFilter;
  std::map<std::string,float> cutMap_noMuonFilterE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    allEvents = (TH1F*)(it->second)->Get("noElecFilter/totalEvents");
    float tot =  allEvents->GetBinContent(1);
    float totalEquivalentEvents = allEvents->GetEffectiveEntries();
    if(crossSec[it->first]>0){
      tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
      //totalEquivalentEvents *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    }
    cutMap_noMuonFilter[it->first] = tot;
    cutMap_noMuonFilterE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
  }
  std::map<std::string,float> cutMap_electronLegFilter;
  std::map<std::string,float> cutMap_electronLegFilterE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    allEvents = (TH1F*)(it->second)->Get("muonLegFilter/totalEvents");
    float tot =  allEvents->GetBinContent(1);
    float totalEquivalentEvents = allEvents->GetEffectiveEntries();
    if(crossSec[it->first]>0){
      tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
      //totalEquivalentEvents *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    }
    cutMap_electronLegFilter[it->first] = tot;
    cutMap_electronLegFilterE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
  }
  std::map<std::string,float> cutMap_tauLegFilter;
  std::map<std::string,float> cutMap_tauLegFilterE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    allEvents = (TH1F*)(it->second)->Get("tauLegFilter/totalEvents");
    float tot =  allEvents->GetBinContent(1);
    float totalEquivalentEvents = allEvents->GetEffectiveEntries();
    if(crossSec[it->first]>0){
      tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
      //totalEquivalentEvents *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    }
    cutMap_tauLegFilter[it->first] = tot;
    cutMap_tauLegFilterE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
  }
  std::map<std::string,float> cutMap_atLeastOneDiTauFilter;
  std::map<std::string,float> cutMap_atLeastOneDiTauFilterE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    allEvents = (TH1F*)(it->second)->Get("atLeastOneDiTauFilter/totalEvents");
    float tot = allEvents->GetBinContent(1);
    float totalEquivalentEvents = allEvents->GetEffectiveEntries();
    if(crossSec[it->first]>0){
      tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
      //totalEquivalentEvents *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    }
    cutMap_atLeastOneDiTauFilter[it->first] = tot;
    cutMap_atLeastOneDiTauFilterE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
  }
  std::map<std::string,float> cutMap_ElecIso;
  std::map<std::string,float> cutMap_ElecIsoE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    cout<<it->first<<endl;
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    TH1F* h1 = new TH1F("h1","",1,-10,10); 
    TCut cut =  (crossSec[it->first]>0) ?  "(chIsoLeg1+nhIsoLeg1+phIsoLeg1)/diTauLegsP4[0].Pt()<0.1"
      : "weight*((chIsoLeg1+nhIsoLeg1+phIsoLeg1)/diTauLegsP4[0].Pt()<0.1)";
    ((TTree*) (it->second->Get("muTauStreamAnalyzer/tree")) )->Draw("diTauLegsP4[0].Eta()>>h1",cut);
    float tot = h1->Integral();
    float totalEquivalentEvents = h1->GetEffectiveEntries();
    if(crossSec[it->first]>0){
      tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
      //totalEquivalentEvents *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    }
    cutMap_ElecIso[it->first] = tot;
    cutMap_ElecIsoE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
    delete h1;
  }
  std::map<std::string,float> cutMap_TauIso;
  std::map<std::string,float> cutMap_TauIsoE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    cout<<it->first<<endl;
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    TH1F* h1 = new TH1F("h1","",1,-10,10); 
    TCut cut =  (crossSec[it->first]>0) ?  "(chIsoLeg1+nhIsoLeg1+phIsoLeg1)/diTauLegsP4[0].Pt()<0.1 && tightestHPSWP>0"
      : "weight*((chIsoLeg1+nhIsoLeg1+phIsoLeg1)/diTauLegsP4[0].Pt()<0.1 && tightestHPSWP>0)";
    ((TTree*) (it->second->Get("muTauStreamAnalyzer/tree")) )->Draw("diTauLegsP4[0].Eta()>>h1",cut);
    float tot = h1->Integral();
    float totalEquivalentEvents = h1->GetEffectiveEntries();
    if(crossSec[it->first]>0){
      tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
      //totalEquivalentEvents *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    }
    cutMap_TauIso[it->first] = tot;
    cutMap_TauIsoE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
    delete h1;
  }
  std::map<std::string,float> cutMap_Mt;
  std::map<std::string,float> cutMap_MtE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    cout<<it->first<<endl;
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    TH1F* h1 = new TH1F("h1","",1,-10,10); 
    TCut cut =  (crossSec[it->first]>0) ?  "(chIsoLeg1+nhIsoLeg1+phIsoLeg1)/diTauLegsP4[0].Pt()<0.1 && tightestHPSWP>0 && MtLeg1<40"
      : "weight*((chIsoLeg1+nhIsoLeg1+phIsoLeg1)/diTauLegsP4[0].Pt()<0.1 && tightestHPSWP>0 && MtLeg1<40)";
    ((TTree*) (it->second->Get("muTauStreamAnalyzer/tree")) )->Draw("diTauLegsP4[0].Eta()>>h1",cut);
    float tot = h1->Integral();
    float totalEquivalentEvents = h1->GetEffectiveEntries();
    if(crossSec[it->first]>0){
      tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
      //totalEquivalentEvents *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    }
    cutMap_Mt[it->first] = tot;
    cutMap_MtE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
    delete h1;
  }
  std::map<std::string,float> cutMap_OS;
  std::map<std::string,float> cutMap_OSE;
  for(it = fullMap.begin(); it != fullMap.end(); it++){
    cout<<it->first<<endl;
    TH1F* allEvents = (TH1F*)(it->second)->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);
    TH1F* h1 = new TH1F("h1","",1,-10,10); 
    TCut cut =  (crossSec[it->first]>0) ?  "(chIsoLeg1+nhIsoLeg1+phIsoLeg1)/diTauLegsP4[0].Pt()<0.1 && tightestHPSWP>0 && diTauCharge==0 && MtLeg1<40"
      : "weight*((chIsoLeg1+nhIsoLeg1+phIsoLeg1)/diTauLegsP4[0].Pt()<0.1 && tightestHPSWP>0 && diTauCharge==0 && MtLeg1<40)";
    ((TTree*) (it->second->Get("muTauStreamAnalyzer/tree")) )->Draw("diTauLegsP4[0].Eta()>>h1",cut);
    float tot = h1->Integral();
    float totalEquivalentEvents = h1->GetEffectiveEntries();
    if(crossSec[it->first]>0){
      tot *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
      //totalEquivalentEvents *= (Lumi/ (totalEvents/crossSec[it->first])  ) ;
    }
    cutMap_OS[it->first] = tot;
    cutMap_OSE[it->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
    delete h1;
  }
  std::map<std::string,float> cutMap_VBFPre;
  std::map<std::string,float> cutMap_VBFPreE;
  for(jt = tMap.begin(); jt != tMap.end(); jt++){
    cout<<jt->first<<endl;
    TH1F* h1 = new TH1F("h1","",1,-10,10); 
    TCut cut =  "sampleWeight*(pt1>0 && combRelIsoLeg1<0.1 && tightestHPSWP>0 && diTauCharge==0 && MtLeg1<40)"; 
    jt->second->Draw("etaL1>>h1",cut);
    float tot = h1->Integral();
    float totalEquivalentEvents = h1->GetEffectiveEntries();
    cutMap_VBFPre[jt->first] = tot;
    cutMap_VBFPreE[jt->first] = totalEquivalentEvents>0 ? sqrt(totalEquivalentEvents)*(tot/totalEquivalentEvents) : 0;
    delete h1;
  }
  std::map<std::string,float> cutMap_VBF;
  std::map<std::string,float> cutMap_VBFE;
  std::map<std::string,float> cutMap_JetVeto;
  std::map<std::string,float> cutMap_JetVetoE;
  std::map<std::string,float> cutMap_HLT;
  std::map<std::string,float> cutMap_HLTE;
  for(jt = tMap.begin(); jt != tMap.end(); jt++){
    cout<<jt->first<<endl;
    TCut cut =  "(pt1>0 && combRelIsoLeg1<0.1 && tightestHPSWP>0 && diTauCharge==0 && MtLeg1<40)"; 

    TFile* dummy = new TFile("dummy.root","RECREATE");  
    TTree* currentTree = (TTree*)(jt->second)->CopyTree(cut);
    float tot = 0;
    int counter = 0;
    float tot2 = 0;
    int counter2 = 0;
    float tot3 = 0;
    int counter3 = 0;

    currentTree->SetBranchAddress( "pt1", &pt1_ );
    currentTree->SetBranchAddress( "pt2", &pt2_ );
    currentTree->SetBranchAddress( "Deta",&Deta_ );
    currentTree->SetBranchAddress( "Mjj", &Mjj_ );
    currentTree->SetBranchAddress( "diTauSVFitPt",&diTauSVFitPt);
    //currentTree->SetBranchAddress( "diTauSVFitEta",&diTauSVFitEta);
    currentTree->SetBranchAddress( "diTauSVFitMass",&diTauSVFitMass);
    currentTree->SetBranchAddress( "diTauVisMass",&diTauVisMass);
    currentTree->SetBranchAddress( "ptL1", &ptL1 );
    currentTree->SetBranchAddress( "ptL2",  &ptL2 );
    currentTree->SetBranchAddress( "etaL1", &etaL1 );
    currentTree->SetBranchAddress( "etaL2", &etaL2 );
    currentTree->SetBranchAddress( "combRelIsoLeg1",&combRelIsoLeg1);
    currentTree->SetBranchAddress( "tightestHPSWP",&tightestHPSWP);
    currentTree->SetBranchAddress( "diTauCharge",&diTauCharge);
    currentTree->SetBranchAddress( "MtLeg1",&MtLeg1);
    currentTree->SetBranchAddress( "numPV",&numPV);
    currentTree->SetBranchAddress( "sampleWeight",&sampleWeight);
    currentTree->SetBranchAddress( "ptVeto",&ptVeto);
    currentTree->SetBranchAddress( "HLT",&HLT);

    for (Long64_t ievt=0; ievt<currentTree->GetEntries();ievt++) {

      currentTree->GetEntry(ievt);

      if (ievt%10000 == 0){
	std::cout << (jt->first) << " ---> processing event: " << ievt << " ..." <<std::endl;
      }

      pt1  = pt1_;
      pt2  = pt2_;
      Deta = Deta_;
      Mjj  = Mjj_;

      bool pass = effS_>0 ? reader->EvaluateMVA( "Cuts", effS_ ) : (pt1>0);

      if(pass){
	tot+=sampleWeight;
	counter++;
	if(ptVeto<20){
	  tot2+=sampleWeight;
	  counter2++;
	  if(HLT>0.5 && HLT<1.5){
	    tot3+=sampleWeight;
	    counter3++;
	  }
	}
      }
    
    }// end loop   

    cutMap_VBF[jt->first] = tot;
    cutMap_VBFE[jt->first] = counter>0 ? sqrt(counter)*tot/counter : 0;
    cutMap_JetVeto[jt->first] = tot2;
    cutMap_JetVetoE[jt->first] = counter2>0 ? sqrt(counter2)*tot2/counter2 : 0;
    cutMap_HLT[jt->first] = tot3;
    cutMap_HLTE[jt->first] = counter3>0 ? sqrt(counter3)*tot3/counter3 : 0;
  }


  
 

  std::vector< std::map<std::string,float> > allFilters;
  allFilters.push_back(cutMap_allEventsFilter);
  allFilters.push_back(cutMap_vertexScrapingFilter);
  allFilters.push_back(cutMap_oneElectronFilter);
  allFilters.push_back(cutMap_noMuonFilter);
  allFilters.push_back(cutMap_electronLegFilter);
  allFilters.push_back(cutMap_tauLegFilter);
  allFilters.push_back(cutMap_atLeastOneDiTauFilter);
  allFilters.push_back(cutMap_ElecIso);
  allFilters.push_back(cutMap_TauIso);
  allFilters.push_back(cutMap_Mt);
  allFilters.push_back(cutMap_OS);
  allFilters.push_back(cutMap_VBFPre);
  allFilters.push_back(cutMap_VBF);
  allFilters.push_back(cutMap_JetVeto);
  allFilters.push_back(cutMap_HLT);

  std::vector< std::map<std::string,float> > allFiltersE;
  allFiltersE.push_back(cutMap_allEventsFilterE);
  allFiltersE.push_back(cutMap_vertexScrapingFilterE);
  allFiltersE.push_back(cutMap_oneElectronFilterE);
  allFiltersE.push_back(cutMap_noMuonFilterE);
  allFiltersE.push_back(cutMap_electronLegFilterE);
  allFiltersE.push_back(cutMap_tauLegFilterE);
  allFiltersE.push_back(cutMap_atLeastOneDiTauFilterE);
  allFiltersE.push_back(cutMap_ElecIsoE);
  allFiltersE.push_back(cutMap_TauIsoE);
  allFiltersE.push_back(cutMap_MtE);
  allFiltersE.push_back(cutMap_OSE);
  allFiltersE.push_back(cutMap_VBFPreE);
  allFiltersE.push_back(cutMap_VBFE);
  allFiltersE.push_back(cutMap_JetVetoE);
  allFiltersE.push_back(cutMap_HLTE);

  //out<<"\\begin{center}"<<endl;
  out<<"\\begin{tabular}[!htbp]{|c";
  for(int k = 0 ; k < samples.size(); k++) out<<"|c";
  out<<"|} \\hline"<<endl;
  out<< "Cut & ";
  for(int k = 0 ; k < samples.size(); k++){
    out << (fullMap.find(samples[k]))->first;
    if(k!=samples.size()-1) out <<" & " ;
    else out << " \\\\ " << endl;
  }
  out <<  " \\hline" << endl;

  
  for(int i = 0; i < allFilters.size(); i++){
    out << filters[i] << " & ";
    for(int k = 0 ; k < samples.size(); k++){
      out << (allFilters[i].find(samples[k]))->second << " $\\pm$ " << (allFiltersE[i].find(samples[k]))->second;
      if(k!=samples.size()-1) out <<" & " ;
      else out << " \\\\ " << endl;
    }
    out <<  " \\hline" << endl;

  }
  
  out<<"\\end{tabular}"<<endl;
  //out<<"\\end{center}"<<endl;
 

  return;

}
コード例 #25
0
ファイル: MCCTRapDep.C プロジェクト: cmironov/UserCode
void MCCTRapDep()   
{
  for(int iSpec = 0; iSpec < 3; iSpec++){
    int Prompt =1; int PutWeight = 1;
    bool bDefault = true; // true : cowboy only, false : salior
    bool bCowboy = false; // true : cowboy only, false : salior
    bool bSailor = false; // true : cowboy only, false : salior
    double fake_v2 = 0.3;

    // iSpec : choose the condition for default/cowboy/sailor
    if(iSpec == 0) {bDefault = true;bCowboy = false;bSailor = false;}
    if(iSpec == 1) {bDefault = false;bCowboy = true;bSailor = false;}
    if(iSpec == 2) {bDefault = false;bCowboy = false;bSailor = true;}

    char cCond[512];
    int iCond = 0; // the number of the cases, 1 : default, 2 : cowboy, 3 : sailor
    if(bDefault) {sprintf(cCond, "default"); iCond = 0;}
    if(bCowboy)  {sprintf(cCond, "cowboy"); iCond = 1;}
    if(bSailor)  {sprintf(cCond, "sailor"); iCond = 2;}

    // iCat : decide the categories for Rapidity (1: 0.0 - 1.2, 2: 1.2 - 1.6, 3: 1.6 - 2.4)
    for(int iCat = 0; iCat < 4; iCat++){
      gROOT->SetStyle("Plain");
      gStyle->SetPalette(1);
      gStyle->SetFrameBorderMode(0);
      gStyle->SetFrameFillColor(0);
      gStyle->SetCanvasColor(0);
      gStyle->SetTitleFillColor(0);
      gStyle->SetStatColor(0);
      gStyle->SetPadBorderSize(0);
      gStyle->SetCanvasBorderSize(0);
      gStyle->SetOptTitle(0); // at least most of the time
      gStyle->SetOptStat("emri");
      gStyle->SetOptFit(1); // set to 1 only if you want to display fit results
      //==================================== Define Histograms====================================================
      char OutTextFile[100]; 
      if(iCat == 0) sprintf(OutTextFile,"MCCT_PrJpsi_Raps_0012_dPhi_%s.tex", cCond);
      if(iCat == 1) sprintf(OutTextFile,"MCCT_PrJpsi_Raps_1216_dPhi_%s.tex", cCond);
      if(iCat == 2) sprintf(OutTextFile,"MCCT_PrJpsi_Raps_1624H_dPhi_%s.tex", cCond);
      if(iCat == 3) sprintf(OutTextFile,"MCCT_PrJpsi_Raps_1624L_dPhi_%s.tex", cCond);
      ofstream dataFile(Form(OutTextFile));
      TH1D *diMuonsInvMass_Gen = new TH1D("diMuonsInvMass_Gen","diMuonsInvMass_Gen", 100,2.98,3.16);

      TH1D *diMuonsPt_Gen = new TH1D("diMuonsPt_Gen","diMuonsPt_Gen", 100,0,50);
      TH1D *Bin_Gen = new TH1D("Bin_Gen","Bin_Gen", 40,0,40);
      //==============================================Define Acc Eff Stuff here===========================================
      // Pt bin sizes
      // 0-1.5, 1.5-3, 3-4.5, 4.5-6, 6-7.5...

      const int nFiles = 6;
      const int ndPhiBins = 4;
      double dphi_bound[100] = {0};

      dphi_bound[0] = 0.0;
      dphi_bound[1] = TMath::Pi()*2/16;
      dphi_bound[2] = TMath::Pi()*4/16;
      dphi_bound[3] = TMath::Pi()*6/16;
      dphi_bound[4] = TMath::Pi()*8/16;

      //X Axis error on Eff graph 
      double xdphi_bound[ndPhiBins] = {0.0};
      for(int i = 0; i < ndPhiBins; i++){
        xdphi_bound[i] = dphi_bound[i] + (dphi_bound[i+1]-dphi_bound[i])/2;
        cout<<"xdphi_bound["<<i<<"] : "<<xdphi_bound[i]<<endl;
        dataFile<<"xdphi_bound["<<i<<"] : "<<xdphi_bound[i]<<endl;
      }

      double mom_err[ndPhiBins] = {0.0};

      double genError, recError;
      double gen_pt[100]={0}, gen_ptError[100]={0}; 
      double rec_pt[100]={0}, rec_ptError[100]={0}; 
      double Eff_cat_1[100]={0},Err_Eff_cat_1[100]={0};  

      // Histogram 2D Arrays
      TH1D *diMuonsInvMass_GenA[10][1000];
      TH1D *diMuonsInvMass_RecA[10][1000];
      TH1D *diMuonsPt_GenA[10][1000];
      TH1D *diMuonsPt_RecA[10][1000];
      char nameGen[10][500], nameRec[10][500], nameGenPt[10][500], nameRecPt[10][500];
      char namePt_1B[500];//for bkg func
      for (int ifile = 0; ifile < nFiles; ifile++) {
        for (Int_t idphi = 0; idphi < ndPhiBins; idphi++) {
          sprintf(nameGen[ifile],"DiMuonMassGen_pt_%d_%d_%d",ifile,iCat,idphi);
          sprintf(nameRec[ifile],"DiMuonMassRec_pt_%d_%d_%d",ifile,iCat,idphi);

          sprintf(nameGenPt[ifile],"DiMuonPtGen_pt_%d_%d_%d",ifile,iCat,idphi);
          sprintf(nameRecPt[ifile],"DiMuonPtRec_pt_%d_%d_%d",ifile,iCat,idphi);

          diMuonsInvMass_GenA[ifile][idphi]= new TH1D(nameGen[ifile],nameGen[ifile],  100,2.98,3.16); //for eff Gen;
          diMuonsInvMass_GenA[ifile][idphi]->Sumw2();
          diMuonsInvMass_GenA[ifile][idphi]->SetMarkerStyle(7);
          diMuonsInvMass_GenA[ifile][idphi]->SetMarkerColor(4);
          diMuonsInvMass_GenA[ifile][idphi]->SetLineColor(4);

          diMuonsInvMass_RecA[ifile][idphi] = new TH1D(nameRec[ifile],nameRec[ifile], 100,2.98,3.16); //for eff Rec;
          diMuonsInvMass_RecA[ifile][idphi]->Sumw2();
          diMuonsInvMass_RecA[ifile][idphi]->SetMarkerStyle(8);
          diMuonsInvMass_RecA[ifile][idphi]->SetMarkerColor(4);
          diMuonsInvMass_RecA[ifile][idphi]->SetLineColor(4);

          diMuonsPt_GenA[ifile][idphi]= new TH1D(nameGenPt[ifile],nameGenPt[ifile],  100,0,40); //for eff Gen;
          diMuonsPt_RecA[ifile][idphi]= new TH1D(nameRecPt[ifile],nameRecPt[ifile],  100,0,40); //for eff Rec;
        }
      }

      //===========================================Input Root File============================================================
      char fileName[10][500];
      //scales for different pT bins
      double scale[10]={0};  
      scale[0]=2.35829e-07;
      scale[1]=1.99854e-07;
      scale[2]=4.48263e-08;
      scale[3]=1.01144e-08;
      scale[4]=4.89604e-09;
      scale[5]=2.62102e-09;

      if(PutWeight==0){scale[0]=(1);scale[1]=(1);scale[2]=(1);scale[3]=(1);scale[4]=(1);scale[5]=(1);}

      if(Prompt ==1){
        cout<<"==================Prompt PrJpsi================================================"<<endl;
        sprintf(fileName[0],"/Users/donghomoon/Analysis/2011HIRData/2011JpsiV2/20111126_Jpsi_Psi/EffCorrection/JpsiEff_New_0329_NewBins_3DEff/0430_4Deff_lowPt_With_dPhi_JpsiGenPsi_HighPt/gRpRootFiles/DiMuonTTree_PromptJpsi_Pt0003_total.root");
        sprintf(fileName[1],"/Users/donghomoon/Analysis/2011HIRData/2011JpsiV2/20111126_Jpsi_Psi/EffCorrection/JpsiEff_New_0329_NewBins_3DEff/0430_4Deff_lowPt_With_dPhi_JpsiGenPsi_HighPt/gRpRootFiles/DiMuonTTree_PromptJpsi_Pt0306_total.root");
        sprintf(fileName[2],"/Users/donghomoon/Analysis/2011HIRData/2011JpsiV2/20111126_Jpsi_Psi/EffCorrection/JpsiEff_New_0329_NewBins_3DEff/0430_4Deff_lowPt_With_dPhi_JpsiGenPsi_HighPt/gRpRootFiles/DiMuonTTree_PromptJpsi_Pt0609_total.root");
        sprintf(fileName[3],"/Users/donghomoon/Analysis/2011HIRData/2011JpsiV2/20111126_Jpsi_Psi/EffCorrection/JpsiEff_New_0329_NewBins_3DEff/0430_4Deff_lowPt_With_dPhi_JpsiGenPsi_HighPt/gRpRootFiles/DiMuonTTree_PromptJpsi_Pt0912_total.root");
        sprintf(fileName[4],"/Users/donghomoon/Analysis/2011HIRData/2011JpsiV2/20111126_Jpsi_Psi/EffCorrection/JpsiEff_New_0329_NewBins_3DEff/0430_4Deff_lowPt_With_dPhi_JpsiGenPsi_HighPt/gRpRootFiles/DiMuonTTree_PromptJpsi_Pt1215_total.root");
        sprintf(fileName[5],"/Users/donghomoon/Analysis/2011HIRData/2011JpsiV2/20111126_Jpsi_Psi/EffCorrection/JpsiEff_New_0329_NewBins_3DEff/0430_4Deff_lowPt_With_dPhi_JpsiGenPsi_HighPt/gRpRootFiles/DiMuonTTree_PromptJpsi_Pt1530_total.root");

        //sprintf(fileName[6],"../RootFiles/DiMuonTTree_PromptJpsi_Pt30XX_total.root");
      }

      TFile *infile;
      TTree *tree;
      TTree *gentree;

      //======================  File loop Starts ============================
      for(int ifile = 0; ifile < nFiles; ifile++){
        infile=new TFile(fileName[ifile],"R");
        tree=(TTree*)infile->Get("SingleMuonTree");
        gentree=(TTree*)infile->Get("SingleGenMuonTree");
        //Event variables
        int eventNb,runNb,lumiBlock, gbin, rbin;
        //Jpsi Variables
        Double_t JpsiMass,JpsiPt,JpsiRap, JpsiCharge;
        Double_t JpsiVprob;
        Double_t JpsiPhi;
        Double_t JpsiEta;
        Double_t JpsiPsi[38];
        Double_t JpsiGenPsi;
        //2.) muon variables RECO                                                                       
        double muPosPx, muPosPy, muPosPz,  muPosEta, muPosPt,muPosP, muPosPhi;
        double muNegPx, muNegPy, muNegPz,  muNegEta, muNegPt,muNegP, muNegPhi;
        //(1).Positive Muon                                     
        double muPos_nchi2In, muPos_dxy, muPos_dz, muPos_nchi2Gl;
        int muPos_found, muPos_pixeLayers, muPos_nValidMuHits,muPos_arbitrated;
        bool muPos_matches,muPos_tracker;
        //(2).Negative Muon                                     
        double muNeg_nchi2In, muNeg_dxy, muNeg_dz, muNeg_nchi2Gl;
        int muNeg_found, muNeg_pixeLayers, muNeg_nValidMuHits,muNeg_arbitrated;
        bool muNeg_matches,muNeg_tracker;

        //Gen Level variables
        //Gen PrJpsi Variables
        double GenJpsiMass, GenJpsiPt, GenJpsiRap;
        double GenJpsiPx, GenJpsiPy, GenJpsiPz;
        double GenJpsiPhi;
        double GenJpsiEta;
        double GenJpsiPsi;
        //2.) Gen muon variables 
        double GenmuPosPx, GenmuPosPy, GenmuPosPz,  GenmuPosEta, GenmuPosPt, GenmuPosPhi;
        double GenmuNegPx, GenmuNegPy, GenmuNegPz,  GenmuNegEta, GenmuNegPt, GenmuNegPhi;

        // HLTrigger
        int hbit1;

        //Event variables
        tree->SetBranchAddress("eventNb",&eventNb);
        tree->SetBranchAddress("runNb",&runNb);
        tree->SetBranchAddress("lumiBlock",&lumiBlock);
        tree->SetBranchAddress("hbit1",&hbit1);

        //Jpsi Variables
        tree->SetBranchAddress("JpsiCharge",&JpsiCharge);
        tree->SetBranchAddress("JpsiMass",&JpsiMass);
        tree->SetBranchAddress("JpsiPt",&JpsiPt);
        tree->SetBranchAddress("JpsiPhi",&JpsiPhi);
        tree->SetBranchAddress("JpsiEta",&JpsiEta);
        tree->SetBranchAddress("JpsiPsi",&JpsiPsi);
        tree->SetBranchAddress("JpsiGenPsi",&JpsiGenPsi);
        //tree->SetBranchAddress("JpsiPsi",&JpsiPsi[38]);
        tree->SetBranchAddress("JpsiRap",&JpsiRap);
        tree->SetBranchAddress("JpsiVprob",&JpsiVprob);
        tree->SetBranchAddress("rbin",&rbin);

        //muon variable
        tree->SetBranchAddress("muPosPx",&muPosPx);
        tree->SetBranchAddress("muPosPy",&muPosPy);
        tree->SetBranchAddress("muPosPz",&muPosPz);
        tree->SetBranchAddress("muPosEta",&muPosEta);
        tree->SetBranchAddress("muPosPhi",&muPosPhi);
        tree->SetBranchAddress("muNegPx", &muNegPx);
        tree->SetBranchAddress("muNegPy", &muNegPy);
        tree->SetBranchAddress("muNegPz", &muNegPz);
        tree->SetBranchAddress("muNegEta", &muNegEta);
        tree->SetBranchAddress("muNegPhi", &muNegPhi);


        //1). Positive Muon
        tree->SetBranchAddress("muPos_nchi2In", &muPos_nchi2In);
        tree->SetBranchAddress("muPos_dxy", &muPos_dxy);
        tree->SetBranchAddress("muPos_dz", &muPos_dz);
        tree->SetBranchAddress("muPos_nchi2Gl", &muPos_nchi2Gl);
        tree->SetBranchAddress("muPos_found", &muPos_found);
        tree->SetBranchAddress("muPos_pixeLayers", &muPos_pixeLayers);
        tree->SetBranchAddress("muPos_nValidMuHits", &muPos_nValidMuHits);
        tree->SetBranchAddress("muPos_matches", &muPos_matches);
        tree->SetBranchAddress("muPos_tracker", &muPos_tracker);
        tree->SetBranchAddress("muPos_arbitrated", &muPos_arbitrated);

        //2). Negative Muon                                                                            
        tree->SetBranchAddress("muNeg_nchi2In", &muNeg_nchi2In);
        tree->SetBranchAddress("muNeg_dxy", &muNeg_dxy);
        tree->SetBranchAddress("muNeg_dz", &muNeg_dz);
        tree->SetBranchAddress("muNeg_nchi2Gl", &muNeg_nchi2Gl);
        tree->SetBranchAddress("muNeg_found", &muNeg_found);
        tree->SetBranchAddress("muNeg_pixeLayers", &muNeg_pixeLayers);
        tree->SetBranchAddress("muNeg_nValidMuHits", &muNeg_nValidMuHits);
        tree->SetBranchAddress("muNeg_matches", &muNeg_matches);
        tree->SetBranchAddress("muNeg_tracker", &muNeg_tracker);
        tree->SetBranchAddress("muNeg_arbitrated", &muNeg_arbitrated);
        //====================================Gen Variables=========================================================
        //Gen Jpsi Variables
        gentree->SetBranchAddress("GenJpsiMass",   &GenJpsiMass);
        gentree->SetBranchAddress("GenJpsiPt",     &GenJpsiPt);
        gentree->SetBranchAddress("GenJpsiPhi",    &GenJpsiPhi);
        gentree->SetBranchAddress("GenJpsiEta",    &GenJpsiEta);
        gentree->SetBranchAddress("GenJpsiPsi",    &GenJpsiPsi);
        gentree->SetBranchAddress("GenJpsiRap",    &GenJpsiRap);
        gentree->SetBranchAddress("GenJpsiPx",     &GenJpsiPx);
        gentree->SetBranchAddress("GenJpsiPy",     &GenJpsiPy);
        gentree->SetBranchAddress("GenJpsiPz",     &GenJpsiPz);
        gentree->SetBranchAddress("gbin",&gbin);
        //muon variable
        gentree->SetBranchAddress("GenmuPosPx",    &GenmuPosPx);
        gentree->SetBranchAddress("GenmuPosPy",    &GenmuPosPy);
        gentree->SetBranchAddress("GenmuPosPz",    &GenmuPosPz);
        gentree->SetBranchAddress("GenmuPosEta",    &GenmuPosEta);
        gentree->SetBranchAddress("GenmuPosPhi",    &GenmuPosPhi);
        gentree->SetBranchAddress("GenmuNegPx",    &GenmuNegPx);
        gentree->SetBranchAddress("GenmuNegPy",    &GenmuNegPy);
        gentree->SetBranchAddress("GenmuNegPz",    &GenmuNegPz);
        gentree->SetBranchAddress("GenmuNegEta",    &GenmuNegEta);
        gentree->SetBranchAddress("GenmuNegPhi",    &GenmuNegPhi);

        //====================================================== Gen tree loop ================================================
        int NAccep=0;
        int nGenEntries=gentree->GetEntries();
        cout<<" Total Entries in GenLevel Tree for pT range: "<<fileName[ifile]<<"  "<<   nGenEntries<< " ==============="<<endl;

        for(int i=0; i< nGenEntries; i++)  {        
          gentree->GetEntry(i);
          //Only printing 
          if(i%100000==0){
            //cout<<" processing record "<<i<<"/"<<nGenEntries<<endl;
            //cout<<" Mass "<< GenJpsiMass<< " pT "<< GenJpsiPt << " Y " <<GenJpsiRap<<endl;
          }

          //if(GenJpsiPt < 6.5) continue;

          bool GenPosIn=0, GenNegIn=0;
          GenmuPosPt= TMath::Sqrt(GenmuPosPx*GenmuPosPx + GenmuPosPy*GenmuPosPy); 
          GenmuNegPt= TMath::Sqrt(GenmuNegPx*GenmuNegPx + GenmuNegPy*GenmuNegPy); 

          diMuonsInvMass_Gen->Fill(GenJpsiMass);
          diMuonsPt_Gen->Fill(GenJpsiPt);

          if(IsAccept(GenmuPosPt, GenmuPosEta)) {GenPosIn=1;}
          if(IsAccept(GenmuNegPt, GenmuNegEta)) {GenNegIn=1;}

          int AccHighPtJpsi = 0;
          int AccLowPtJpsi = 0;
          if(GenJpsiPt >= 6.5 && fabs(GenJpsiRap) < 2.4 && GenPosIn == 1 && GenNegIn == 1) AccHighPtJpsi = 1;
          if(GenJpsiPt < 6.5 && GenJpsiPt >= 3.0 && fabs(GenJpsiRap) >= 1.6 && fabs(GenJpsiRap) < 2.4 && GenPosIn == 1 && GenNegIn == 1) AccLowPtJpsi = 1;

          double gdPhi2mu = GenmuPosPhi - GenmuNegPhi;
          while (gdPhi2mu > TMath::Pi()) gdPhi2mu -= 2*TMath::Pi();
          while (gdPhi2mu <= -TMath::Pi()) gdPhi2mu += 2*TMath::Pi();
          double gchkCowboy = 1*gdPhi2mu;

          if(bCowboy && !(gchkCowboy > 0.)) continue;
          if(bSailor && (gchkCowboy > 0.)) continue;

          if((GenPosIn ==1 && GenNegIn==1)) NAccep++;

          Bin_Gen->Fill(gbin);

          double GenCenWeight =0, GenWeight =0;
          GenCenWeight=FindCenWeight(gbin);
          
          double gJpsidPhi = TMath::Abs(GenJpsiPsi);
          double gmean_dphi = TMath::Pi()/16;
          if (gJpsidPhi>TMath::Pi()/8) gmean_dphi = 3*TMath::Pi()/16;
          if (gJpsidPhi>TMath::Pi()/4) gmean_dphi = 5*TMath::Pi()/16;
          if (gJpsidPhi>3*TMath::Pi()/8) gmean_dphi = 7*TMath::Pi()/16;
          GenWeight=GenCenWeight*scale[ifile]*(2.0/TMath::Pi()*(1+2*fake_v2*cos(2*gJpsidPhi)*TMath::Gaus(GenJpsiPt,15,4,0)));

          if(PutWeight==0) GenWeight=1; 


          for (Int_t idphi = 0; idphi < ndPhiBins; idphi++) {

            //adding pT of all pt bins to see diss is cont

            if(iCat == 0) {
              if(  AccHighPtJpsi == 1 && (gbin >= 4 && gbin < 24) && (GenPosIn==1 && GenNegIn==1) && (GenJpsiPt >= 6.5 && GenJpsiPt < 40.0) &&  
                  (TMath::Abs(GenJpsiRap)<1.2 && TMath::Abs(GenJpsiRap) >= 0.0 ) && 
                  (TMath::Abs(GenJpsiPsi)>=dphi_bound[idphi] && TMath::Abs(GenJpsiPsi)<dphi_bound[idphi+1])){diMuonsInvMass_GenA[ifile][idphi]->Fill(GenJpsiMass,GenWeight);}
            }
            if(iCat == 1) {
              if(  AccHighPtJpsi == 1 && (gbin >= 4 && gbin < 24) && (GenPosIn==1 && GenNegIn==1) && (GenJpsiPt >= 6.5 && GenJpsiPt < 40.0) &&  
                  (TMath::Abs(GenJpsiRap)<1.6 && TMath::Abs(GenJpsiRap) >= 1.2 ) && 
                  (TMath::Abs(GenJpsiPsi)>=dphi_bound[idphi] && TMath::Abs(GenJpsiPsi)<dphi_bound[idphi+1])){diMuonsInvMass_GenA[ifile][idphi]->Fill(GenJpsiMass,GenWeight);}
            }
            if(iCat == 2) {
              if(  AccHighPtJpsi == 1 &&  (gbin >= 4 && gbin < 24) && (GenPosIn==1 && GenNegIn==1) && (GenJpsiPt >= 6.5 && GenJpsiPt < 40.0) &&  
                  (TMath::Abs(GenJpsiRap)<2.4 && TMath::Abs(GenJpsiRap) >= 1.6 ) && 
                  (TMath::Abs(GenJpsiPsi)>=dphi_bound[idphi] && TMath::Abs(GenJpsiPsi)<dphi_bound[idphi+1])){diMuonsInvMass_GenA[ifile][idphi]->Fill(GenJpsiMass,GenWeight);}
            }
            if(iCat == 3) {
              if(  AccLowPtJpsi == 1 && (gbin >= 4 && gbin < 24) && (GenPosIn==1 && GenNegIn==1) && (GenJpsiPt >= 3.0 && GenJpsiPt < 6.5) &&  
                  (TMath::Abs(GenJpsiRap)<2.4 && TMath::Abs(GenJpsiRap) >= 1.6 ) && 
                  (TMath::Abs(GenJpsiPsi)>=dphi_bound[idphi] && TMath::Abs(GenJpsiPsi)<dphi_bound[idphi+1])){diMuonsInvMass_GenA[ifile][idphi]->Fill(GenJpsiMass,GenWeight);}
            }
          }
        }//gen loop end



        cout<<" accepted no "<< NAccep<<endl;
        dataFile<<" accepted no "<< NAccep<<endl;

        //dataFile<<" accepted no "<< NAccep<<endl;
        //   new TCanvas;
        //diMuonsInvMass_Gen->Draw();
        //gPad->Print("plots/diMuonsInvMass_Gen.png");

        new TCanvas;
        diMuonsPt_Gen->Draw();

        //=============== Rec Tree Loop ==============================================================================

         // start to fill up reco corrected by efficiency
        char tmp_eff_input[512], tmp_input_histo[512];
        if(!(iCat == 3)) sprintf(tmp_eff_input,"../../EffRoots_New/PrJpsi_HighPt_%s.root", cCond);
        if(iCat == 3) sprintf(tmp_eff_input,"../../EffRoots_New/PrJpsi_LowPt_%s.root", cCond);
        sprintf(tmp_input_histo,"eff_%s", cCond);

        TFile *eff_input;
        eff_input=new TFile(tmp_eff_input,"R");

        int nRecEntries=tree->GetEntries();
        cout<<"Total Entries in reconstructed Tree for pT range "<<fileName[ifile]<<"  "<<nRecEntries<< "====="<<endl;
        for(int i=0; i<nRecEntries; i++)  {     
          tree->GetEntry(i);
          //if(bCowboy && !(gchkCowboy > 0.)) {cout<<"This is not Cowboy from Gen"<<endl; continue;}
          //if(bSailor && (gchkCowboy > 0.)) {cout<<"This is not Sailor from Gen"<<endl; continue;}
          //Only printing 
          if(i%10000==0){
            //cout<<" processing record "<<i<<"/"<<nRecEntries<<endl;
            //cout<<" processing Run  " <<runNb <<" event "<<eventNb<<" lum block "<<lumiBlock<<endl;    
            //cout<<" Mass "<< JpsiMass<< " pT "<< JpsiPt << " Y " <<JpsiRap<<"  "<<JpsiVprob<<" charge "<<JpsiCharge<<" rbin "<<rbin<<endl; 
          }
          //if(JpsiPt < 6.5) continue;
          bool PosPass=0, NegPass=0, AllCut=0 ,PosIn=0, NegIn=0;
          muPosPt= TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy); 
          muPosP = TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy+ muPosPz*muPosPz); 
          muNegPt= TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy); 
          muNegP = TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy +muNegPz*muNegPz); 

          if(IsAccept(muPosPt, muPosEta)){PosIn=1;}
          if(IsAccept(muNegPt, muNegEta)){NegIn=1;}

          bool mu_Global = ((muPos_nchi2Gl >=0) && (muNeg_nchi2Gl >=0));
          bool mu_Tracker = ((muPos_tracker==1) && (muNeg_tracker==1));

          double dPhi2mu = muPosPhi - muNegPhi;
          while (dPhi2mu > TMath::Pi()) dPhi2mu -= 2*TMath::Pi();
          while (dPhi2mu <= -TMath::Pi()) dPhi2mu += 2*TMath::Pi();
          double chkCowboy = 1*dPhi2mu;

          if(bCowboy && !(chkCowboy > 0.)) continue;
          if(bSailor && (chkCowboy > 0.)) continue;

          if(muPos_found > 10 && muPos_pixeLayers > 0 && muPos_nchi2In < 4.0 && TMath::Abs(muPos_dxy) < 3 && TMath::Abs(muPos_dz) < 15 && muPos_nchi2Gl < 20  &&
              muPos_arbitrated==1 && muPos_tracker==1){PosPass=1;}
          if(muNeg_found >10 && muNeg_pixeLayers >0 && muNeg_nchi2In <4.0 && TMath::Abs(muNeg_dxy) < 3 && TMath::Abs(muNeg_dz) < 15 && muNeg_nchi2Gl < 20 &&
              muNeg_arbitrated==1 && muNeg_tracker==1){NegPass=1;}

          //cout<<"Cut checks, muPos_matches : "<<muPos_matches<<", muNeg_matches : "<<muNeg_matches<<", PosIn : "<<PosIn<<", NegIn : "<<NegIn
          //    <<", PosPass : "******", NegPass : "******", mu_Global : "<<mu_Global<<", mu_Tracker : "<<mu_Tracker<<endl;
          //if((PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}
          int AccHighPtJpsi = 0;
          int AccLowPtJpsi = 0;
          if(JpsiPt >= 6.5 && fabs(JpsiRap) < 2.4 && PosIn == 1 && NegIn == 1) AccHighPtJpsi = 1;
          if(JpsiPt < 6.5 && JpsiPt >= 3.0 && fabs(JpsiRap) >= 1.6 && fabs(JpsiRap) < 2.4 && PosIn == 1 && NegIn == 1) AccLowPtJpsi = 1;

          if(hbit1 == 1 && (muPos_matches==1 && muNeg_matches==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}

          //AllCut = 1;
          //without ID cut
          // if((muPos_matches==1 && muNeg_matches==1) && (PosIn==1 && NegIn==1) && mu_Global && mu_Tracker){AllCut=1;}

          //without trigger matched
          //if((PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}

          double eff_cor[2];
          double RecCenWeight=0,RecWeight=0;
          RecCenWeight=FindCenWeight(rbin);
          
          double JpsidPhi = 0.0;
          JpsidPhi = TMath::Abs(JpsiGenPsi);

          double rmean_dphi = TMath::Pi()/16;
          if (JpsidPhi>TMath::Pi()/8) rmean_dphi = 3*TMath::Pi()/16;
          if (JpsidPhi>TMath::Pi()/4) rmean_dphi = 5*TMath::Pi()/16;
          if (JpsidPhi>3*TMath::Pi()/8) rmean_dphi = 7*TMath::Pi()/16;
          RecWeight=RecCenWeight*scale[ifile]*(2.0/TMath::Pi()*(1+2*fake_v2*cos(2*JpsidPhi)*TMath::Gaus(JpsiPt,15,4,0)));


          if(PutWeight==0)RecWeight=1;


          //Eff loop for reco
          for (Int_t idphi = 0; idphi < ndPhiBins; idphi++) {
            if((JpsiCharge == 0) && (JpsiVprob > 0.01)) {     
                if(iCat == 0) {
                  if(AccHighPtJpsi == 1 && (AllCut==1) && (rbin >= 4 && rbin < 24) && (JpsiPt>=6.5 && JpsiPt<40.0) && 
                      (TMath::Abs(JpsiRap) < 1.2 && TMath::Abs(JpsiRap) >= 0.0) && 
                      (TMath::Abs(JpsiGenPsi) > dphi_bound[idphi] && TMath::Abs(JpsiGenPsi) <=dphi_bound[idphi+1])){
                  DoEffCor3D(eff_input, iCond, rbin, JpsiPt, fabs(JpsiRap), eff_cor);
                  diMuonsInvMass_RecA[ifile][idphi]->Fill(JpsiMass,RecWeight*((double)1.0/eff_cor[0]));}
                }
                if(iCat == 1) {
                  if(AccHighPtJpsi == 1 && (AllCut==1) && (rbin >= 4 && rbin < 24) && (JpsiPt>=6.5 && JpsiPt<40.0) && 
                      (TMath::Abs(JpsiRap) < 1.6 && TMath::Abs(JpsiRap) >= 1.2) && 
                      (TMath::Abs(JpsiGenPsi) > dphi_bound[idphi] && TMath::Abs(JpsiGenPsi) <=dphi_bound[idphi+1])){
                  DoEffCor3D(eff_input, iCond, rbin, JpsiPt, fabs(JpsiRap), eff_cor);
                  diMuonsInvMass_RecA[ifile][idphi]->Fill(JpsiMass,RecWeight*((double)1.0/eff_cor[0]));}
                }
                if(iCat == 2) {
                  if(AccHighPtJpsi == 1 && (AllCut==1) && (rbin >= 4 && rbin < 24) && (JpsiPt>=6.5 && JpsiPt<40.0) && 
                      (TMath::Abs(JpsiRap) < 2.4 && TMath::Abs(JpsiRap) >= 1.6) && 
                      (TMath::Abs(JpsiGenPsi) > dphi_bound[idphi] && TMath::Abs(JpsiGenPsi) <=dphi_bound[idphi+1])){
                  DoEffCor3D(eff_input, iCond, rbin, JpsiPt, fabs(JpsiRap), eff_cor);
                  diMuonsInvMass_RecA[ifile][idphi]->Fill(JpsiMass,RecWeight*((double)1.0/eff_cor[0]));}
                }
                if(iCat == 3) {
                  if(AccLowPtJpsi == 1 && (AllCut==1) && (rbin >= 4 && rbin < 24) && (JpsiPt>=3.0 && JpsiPt<6.5) && 
                      (TMath::Abs(JpsiRap) < 2.4 && TMath::Abs(JpsiRap) >= 1.6) && 
                      (TMath::Abs(JpsiGenPsi) > dphi_bound[idphi] && TMath::Abs(JpsiGenPsi) <=dphi_bound[idphi+1])){
                  DoEffCor3D(eff_input, iCond, rbin, JpsiPt, fabs(JpsiRap), eff_cor);
                  diMuonsInvMass_RecA[ifile][idphi]->Fill(JpsiMass,RecWeight*((double)1.0/eff_cor[0]));}
                }
            }
          }
        }//rec tree loop ends
      }  // file loop ends

      ///////////////////////////////////////////////////////////////////
      cout<< " adding "<<endl;
      TH1D *diMuonsInvMass_RecA1[100];
      TH1D *diMuonsInvMass_GenA1[100];
      TH1D *diMuonsPt_GenA1[100];
      TH1D *diMuonsPt_RecA1[100];
      TF1 *backfun_1;

      for(Int_t idphi = 0; idphi < ndPhiBins; idphi++){
        diMuonsInvMass_RecA1[idphi] = diMuonsInvMass_RecA[0][idphi];
        diMuonsInvMass_GenA1[idphi] = diMuonsInvMass_GenA[0][idphi];
        diMuonsPt_GenA1[idphi] = diMuonsPt_GenA[0][idphi];
        diMuonsPt_RecA1[idphi] = diMuonsPt_RecA[0][idphi];

        for (int ifile = 1; ifile < nFiles; ifile++) {
          diMuonsInvMass_RecA1[idphi]->Add(diMuonsInvMass_RecA[ifile][idphi]);
          diMuonsInvMass_GenA1[idphi]->Add(diMuonsInvMass_GenA[ifile][idphi]);     
          diMuonsPt_GenA1[idphi]->Add(diMuonsPt_GenA[ifile][idphi]); 
          diMuonsPt_RecA1[idphi]->Add(diMuonsPt_RecA[ifile][idphi]); 
        }
      }
      //===========================Fitting=================================================================================//
      // Fit ranges
      double mass_low, mass_high;
      double MassJpsi, WeidthJpsi;
      // Fit Function crystall ball
      // Jpsi Settings
      MassJpsi = 3.096; 
      WeidthJpsi = 0.028;
      mass_low = 2.945; 
      mass_high = 3.24;  // Fit ranges

      TF1 *GAUSPOL = new TF1("GAUSPOL",CrystalBall,2.4,3.8,6);//2.4,3.8,6);
      GAUSPOL->SetParNames("Yield (J/#psi)","BinWidth","Mean","Sigma","#alpha","n");
      GAUSPOL->SetParameter(2, MassJpsi);
      GAUSPOL->SetParameter(3, WeidthJpsi);
      //GAUSPOL->SetParLimits(3, 0.1*WeidthJpsi,2.0*WeidthJpsi);
      GAUSPOL->SetParameter(4, 1.2);
      GAUSPOL->SetParameter(5, 20.0);
      GAUSPOL->SetLineWidth(2.0);
      GAUSPOL->SetLineColor(2);


      //=====================Loop for eff========================================================================================//
      //define stuff here for error on weighted samples
      double GenNo[100]={0};
      double GenError[100]={0};
      double RecError[100]={0};

      for (Int_t idphi = 0; idphi < ndPhiBins; idphi++) {

        gen_pt[idphi] = diMuonsInvMass_GenA1[idphi]->IntegralAndError(1, 100, genError);
        gen_ptError[idphi]= genError;
        cout<<" gen_pt[idphi] "<< gen_pt[idphi] <<" error   "<<  gen_ptError[idphi]<<endl;

        // cout<<" *********************** "<<diMuonsInvMass_RecA1[idphi]->GetMaximum()<<endl;
        //giving inetial value for crystall ball fourth parameter 
        GAUSPOL->SetParameter(0, diMuonsInvMass_RecA1[idphi]->Integral(0,50));
        GAUSPOL->FixParameter(1, diMuonsInvMass_RecA1[idphi]->GetBinWidth(1));
        //GAUSPOL->SetParameter(0, diMuonsInvMass_RecA1[idphi]->GetMaximum());
        //new TCanvas;
        //diMuonsInvMass_RecA1[idphi]->Draw();

        new TCanvas;
        diMuonsInvMass_RecA1[idphi]->Fit("GAUSPOL","EMRQ", "", mass_low, mass_high); // Jpsi
        //diMuonsInvMass_RecA1[idphi]->Fit("GAUSPOL","LLMERQ", "", 8.5,10.5); // Jpsi
        //diMuonsInvMass_RecA1[idphi]->Fit("GAUSPOL","LLMER", "", mass_low, mass_high); // Jpsi
        diMuonsInvMass_RecA1[idphi]->DrawCopy("EPLsame");

        // new TCanvas;
        //diMuonsInvMass_RecA1[idphi]->Fit("GAUSPOL_1","LLMER", "", mass_low, mass_high);
        //diMuonsInvMass_RecA1[idphi]->DrawCopy("EPLsame");
        //gPad->Print(PlotName);
        //gPad->Print(PlotName1);

        //  cout << GAUSPOL_1->GetChisquare()<<endl;
        //for(int i=0;i<=100;i++) {cout<<i<<"  "<<diMuonsInvMass_RecA1[idphi]->GetBinContent(i)<<endl;}
        //return;
        //double JpsiMass = GAUSPOL_1->GetParameter(2);
        //double JpsiWidth = GAUSPOL_1->GetParameter(3);
        //double JpsiYield = GAUSPOL_1->GetParameter(4); 

        double JpsiMass = GAUSPOL->GetParameter(2);
        double JpsiWidth = GAUSPOL->GetParameter(3);

        double JpsiYield = GAUSPOL->GetParameter(0); 
        Double_t JpsiYieldError = GAUSPOL->GetParError(0); 

        //cout<<JpsiYieldError<<"*****************"<<endl;

        //if(TMath::IsNan(JpsiYieldError)=1) {JpsiYieldError=TMath::Sqrt(JpsiYield);}

        double par[20];
        GAUSPOL->GetParameters(par);
        sprintf(namePt_1B,"pt_1B_%d",idphi);

        backfun_1 = new TF1(namePt_1B, Pol2, mass_low, mass_high, 3);
        backfun_1->SetParameters(&par[3]);

        double MassLow=(JpsiMass-3*JpsiWidth);
        double MassHigh=(JpsiMass+3*JpsiWidth);


        int binlow =diMuonsInvMass_RecA1[idphi]->GetXaxis()->FindBin(MassLow);
        int binhi =diMuonsInvMass_RecA1[idphi]->GetXaxis()->FindBin(MassHigh);

        //double binwidth=diMuonsInvMass_RecA1[idphi]->GetBinWidth(1);
        //yield by function 
        //rec_pt[idphi] = JpsiYield;
        //rec_ptError[idphi]= JpsiYieldError;

        //yield by histogram integral
        binlow = 1;
        binhi = 100;
        rec_pt[idphi] = diMuonsInvMass_RecA1[idphi]->IntegralAndError(binlow, binhi,recError);
        rec_ptError[idphi]= recError;
      }

      TFile *outfile;
      char tmp_output[512];
      if(iCat == 0) sprintf(tmp_output,"MCCT_PrJpsi_Raps_0012_dPhi_%s.root",cCond);
      if(iCat == 1) sprintf(tmp_output,"MCCT_PrJpsi_Raps_1216_dPhi_%s.root",cCond);
      if(iCat == 2) sprintf(tmp_output,"MCCT_PrJpsi_Raps_1624H_dPhi_%s.root",cCond);
      if(iCat == 3) sprintf(tmp_output,"MCCT_PrJpsi_Raps_1624L_dPhi_%s.root",cCond);
      outfile =new TFile(tmp_output,"Recreate");

      double gsum = 0.0;
      double gen_pt_Norm[ndPhiBins];
      double gen_ptError_Norm[ndPhiBins];
      for(int i = 0; i < ndPhiBins; i++){
        gsum += gen_pt[i];
      }
      gsum = gsum*(dphi_bound[1]-dphi_bound[0]);

      for(int i = 0; i < ndPhiBins; i++){
        gen_pt_Norm[i] = gen_pt[i]/gsum;
        gen_ptError_Norm[i] = gen_ptError[i]/gsum;
      }

      double sum = 0.0;
      double rec_pt_Norm[ndPhiBins];
      double rec_ptError_Norm[ndPhiBins];
      for(int i = 0; i < ndPhiBins; i++){
        sum += rec_pt[i];
      }
      sum = sum*(dphi_bound[1]-dphi_bound[0]);

      for(int i = 0; i < ndPhiBins; i++){
        rec_pt_Norm[i] = rec_pt[i]/sum;
        rec_ptError_Norm[i] = rec_ptError[i]/sum;
      }

      TH1F *hJpsi_Gen = new TH1F("hJpsi_Gen","hJpsi_Gen",ndPhiBins,0,TMath::Pi()/2);
      TH1F *hJpsi_Reco = new TH1F("hJpsi_Reco","hJpsi_Reco",ndPhiBins,0,TMath::Pi()/2);
      hJpsi_Gen->Sumw2();
      hJpsi_Reco->Sumw2();
      for(int i = 0; i < ndPhiBins; i++){
        hJpsi_Gen->SetBinContent(i+1,gen_pt[i]);
        hJpsi_Gen->SetBinError(i+1,gen_ptError[i]);
        hJpsi_Reco->SetBinContent(i+1,rec_pt[i]);
        hJpsi_Reco->SetBinError(i+1,rec_ptError[i]);
      }

      TGraphErrors *Jpsi_Reco_Norm = new TGraphErrors(ndPhiBins, xdphi_bound, rec_pt_Norm, mom_err, rec_ptError_Norm);
      TGraphErrors *Jpsi_Gen_Norm = new TGraphErrors(ndPhiBins, xdphi_bound, gen_pt_Norm, mom_err, gen_ptError_Norm);
      if(iCat == 0){
        hJpsi_Gen->SetName("hGen_Jpsi_Raps_0012");
        hJpsi_Reco->SetName("hReco_Jpsi_Raps_0012");
        Jpsi_Reco_Norm->SetName("nReco_Jpsi_Raps_0012");
        Jpsi_Gen_Norm->SetName("nGen_Jpsi_Raps_0012");
      }
      if(iCat == 1){
        hJpsi_Gen->SetName("hGen_Jpsi_Raps_1216");
        hJpsi_Reco->SetName("hReco_Jpsi_Raps_1216");
        Jpsi_Reco_Norm->SetName("nReco_Jpsi_Raps_1216");
        Jpsi_Gen_Norm->SetName("nGen_Jpsi_Raps_1216");
      }
      if(iCat == 2){
        hJpsi_Gen->SetName("hGen_Jpsi_Raps_1624H");
        hJpsi_Reco->SetName("hReco_Jpsi_Raps_1624H");
        Jpsi_Reco_Norm->SetName("nReco_Jpsi_Raps_1624H");
        Jpsi_Gen_Norm->SetName("nGen_Jpsi_Raps_1624H");
      }
      if(iCat == 3){
        hJpsi_Gen->SetName("hGen_Jpsi_Raps_1624L");
        hJpsi_Reco->SetName("hReco_Jpsi_Raps_1624L");
        Jpsi_Reco_Norm->SetName("nReco_Jpsi_Raps_1624L");
        Jpsi_Gen_Norm->SetName("nGen_Jpsi_Raps_1624L");
      }
      hJpsi_Gen->Write();
      hJpsi_Reco->Write();
      Jpsi_Reco_Norm->Write();
      Jpsi_Gen_Norm->Write();

      outfile->Write();
      outfile->Close();
    }
  }
}
コード例 #26
0
ファイル: add_branch.C プロジェクト: yezhihong/My-DVCS
//int add_branch(TString particle,int energy_flag){
int main(){
	TString particle; cerr<<"--- Particle (n or p)"; cin>>particle;
	Int_t energy_flag; cerr<<"--- Energy Flag (11 or 8)"; cin>>energy_flag;

	gStyle->SetOptStat(1);
	//const double Lumi = 1.0e36; // cm-2*s-1, for He3 nuclear not for nucleons
	//const double KHz = 1e-3;
	//const double nBcm2 = 1e-33;
	double hMass = 0.0;
	double EBeam = 0.0;
	TString Target = "";
	TString TargetName = "";
	TString Energy = "";
	gRandom->SetSeed(0);
	/* Target and Energy variables{{{*/
	if(particle=="p"){
		TargetName = "Proton";
		Target = "NH3"; hMass = 0.938272;	
		if(energy_flag==11){
			Energy = "11GeV";
			EBeam = 11.0;
		}
		else if(energy_flag==8){
			Energy = "8.8GeV";
			EBeam = 8.80;
		}
	}else if(particle=="n"){
		TargetName = "Neutron";
		Target = "3he"; hMass = 0.939565;	
		if(energy_flag==11){
			Energy = "11GeV";
			EBeam = 11.0;
		}
		else if(energy_flag==8){
			Energy = "8.8GeV";
			EBeam = 8.80;
		}
	}/*}}}*/

	/*CLEO{{{*/
	TCanvas *dummycavan = new TCanvas();
	TFile *file_negative=new TFile("../acceptance/acceptance_solid_SIDIS_NH3_electron_output.root","r");
	TFile *file_positive=new TFile("../acceptance/acceptance_solid_SIDIS_NH3_pionp_output.root","r");
	TFile *file_photon =new TFile("../acceptance/acceptance_solid_SIDIS_NH3_photon_output.root","r");
	//negative particle forward angle acceptance
	TH3F *accep_ele_forward=(TH3F*)file_negative->Get("acceptance_ThetaPhiP_forwardangle");       
	//negative particle large angle acceptance
	TH3F *accep_ele_large=(TH3F*)file_negative->Get("acceptance_ThetaPhiP_largeangle");           
	//neutral particle forward angle acceptance
	TH3F *accep_pho_forward=(TH3F*)file_photon->Get("acceptance_ThetaPhiP_forwardangle");       
	//neutral particle large angle acceptance
	TH3F *accep_pho_large=(TH3F*)file_photon->Get("acceptance_ThetaPhiP_largeangle");           
		
	TH3F *accep_had_forward; TH3F *accep_had_large;
	if(particle=="pim"){//pionm is the same as electron acceptance   
		accep_had_forward=(TH3F*)accep_ele_forward->Clone("accep_had_forward");
		accep_had_large  =(TH3F*)accep_ele_large->Clone("accep_had_large");
	}
	if(particle=="pip"){  // for positive pions
		accep_had_forward=(TH3F*)file_positive->Get("acceptance_ThetaPhiP_forwardangle");	
		accep_had_large=(TH3F*)file_positive->Get("acceptance_ThetaPhiP_largeangle");	
	}
	if(particle=="p"){  // for positive pions
		accep_had_forward=(TH3F*)file_positive->Get("acceptance_ThetaPhiP_forwardangle");	
		accep_had_large=(TH3F*)file_positive->Get("acceptance_ThetaPhiP_largeangle");	
	}
	if(particle=="n"){  // for positive pions
	//	accep_had_forward=(TH3F*)file_photon->Get("acceptance_ThetaPhiP_forwardangle");	
	//	accep_had_large=(TH3F*)file_photon->Get("acceptance_ThetaPhiP_largeangle");	
		accep_had_forward=(TH3F*)accep_pho_forward->Clone("accep_had_forward");
		accep_had_large  =(TH3F*)accep_pho_large->Clone("accep_had_large");
	}
	/*}}}*/

	/*Vectors & Variables{{{*/
	TLorentzVector *P_E0 = new TLorentzVector();//incoming electron
	TLorentzVector *P_e_i = new TLorentzVector();//scattered electron
	TLorentzVector *P_e_f = new TLorentzVector();//scattered electron with Eloss
	TLorentzVector *P_g = new TLorentzVector();//photon
	TLorentzVector *P_h = new TLorentzVector();//proton or neutron
	TLorentzVector *P_t = new TLorentzVector();//target, either proton or neutron
	TLorentzVector *P_e_res = new TLorentzVector();//scattered electron with resolution
	TLorentzVector *P_g_res = new TLorentzVector();//photon with resolution

	Double_t vertexz, E0; 
	Double_t ePx_ini, ePy_ini, ePz_ini; 
	//Double_t hP_ini, hPx_ini, hPy_ini,hPz_ini,hTheta_ini,hPhi_ini;
	Double_t ePx, ePy, ePz, gPx, gPy, gPz, hPx, hPy, hPz;
	Double_t eP_ini,eP, gP,hP;
	Double_t Q2, x, t, phi, XS_P, XS_M, XS_BHp, XS_BHm, PSF;
	Double_t ePhi_ini, ePhi, gPhi,hPhi;
	Double_t eTheta_ini, eTheta, gTheta,hTheta;
	Int_t Ngen,Nacc;

	//Define new measured quantities that include detector resolutions
	double eE_i, eE_f, gE, hE;
	double eE_i_res, eE_f_res,eP_res, eTheta_res, ePhi_res, ePx_res, ePy_res, ePz_res;
	double gP_res, gTheta_res, gPhi_res, gPx_res, gPy_res, gPz_res;
	double MM = 0.0,MM_res = 0.0, W=0.0, Wp=0.0;

	int e_theta_bin= 0, e_phi_bin= 0, e_p_bin=0;
	int h_theta_bin= 0, h_phi_bin= 0, h_p_bin=0;
	int g_theta_bin= 0, g_phi_bin=0, g_p_bin=0;
	double e_acc_f= 0.0, e_acc_l= 0.0, g_acc_f=0, g_acc_l=0, h_acc_f=0, h_acc_l=0;
	/*}}}*/

	/*DVCS: Define Rootfile and variables{{{*/
	TString filename = "";
	if(particle=="p"){
		if(energy_flag==11)
			filename = "../DVCS_Proton_11GeV.root";
		else if(energy_flag==8)
			filename = "../DVCS_Proton_8.8GeV.root";
	}else if(particle=="n"){
		if(energy_flag==11)
			filename = "../DVCS_Neutron_11GeV.root";
		else if(energy_flag==8)
			filename = "../DVCS_Neutron_8.8GeV.root";
	}

	TFile *file = new TFile(filename.Data(), "r");
	TTree *T = (TTree*) file->Get("T");

	T->SetBranchAddress("vertexz", &vertexz);
	T->SetBranchAddress("E0", &E0);

	T->SetBranchAddress("eP_ini", &eP_ini);
	T->SetBranchAddress("ePx_ini", &ePx_ini);
	T->SetBranchAddress("ePy_ini", &ePy_ini);
	T->SetBranchAddress("ePz_ini", &ePz_ini);
	T->SetBranchAddress("eTheta_ini",&eTheta_ini);
	T->SetBranchAddress("ePhi_ini",&ePhi_ini);

	T->SetBranchAddress("eP", &eP);
	T->SetBranchAddress("ePx", &ePx);
	T->SetBranchAddress("ePy", &ePy);
	T->SetBranchAddress("ePz", &ePz);
	T->SetBranchAddress("eTheta",&eTheta);
	T->SetBranchAddress("ePhi",&ePhi);

	T->SetBranchAddress("gP", &gP);
	T->SetBranchAddress("gPx", &gPx);
	T->SetBranchAddress("gPy", &gPy);
	T->SetBranchAddress("gPz", &gPz);
	T->SetBranchAddress("gTheta", &gTheta);
	T->SetBranchAddress("gPhi", &gPhi);

	T->SetBranchAddress("hP", &hP);
	T->SetBranchAddress("hPx", &hPx);
	T->SetBranchAddress("hPy", &hPy);
	T->SetBranchAddress("hPz", &hPz);
	T->SetBranchAddress("hTheta",&hTheta);
	T->SetBranchAddress("hPhi",&hPhi);

	T->SetBranchAddress("Q2", &Q2);
	T->SetBranchAddress("x", &x);
	T->SetBranchAddress("t", &t);
	T->SetBranchAddress("phi", &phi);
	T->SetBranchAddress("XS_P", &XS_P);
	T->SetBranchAddress("XS_M", &XS_M);
	T->SetBranchAddress("XS_BHp", &XS_BHp);
	T->SetBranchAddress("XS_BHm", &XS_BHm);
	T->SetBranchAddress("PSF", &PSF);
	T->SetBranchAddress("Ngen", &Ngen);
	T->SetBranchAddress("Nacc", &Nacc);

	Long64_t N_entries=T->GetEntries();
	T->GetEntry(0);
	Long64_t N_gen = Ngen;
	cout<<"DVCS: total generated events number: "<<N_gen<<"--- and accepted: "<<N_entries<<endl;
	/*}}}*/

	/*Add new branches{{{*/
	filename.ReplaceAll(".root","_New0.root");
	TFile *newfile = new TFile(filename.Data(), "recreate");
	TTree *NewT = T->CloneTree(0);;

	NewT->Branch("W", &W, "W/D");
	NewT->Branch("Wp", &Wp, "Wp/D");
	NewT->Branch("MM", &MM, "MM/D");
	NewT->Branch("MM_res", &MM_res, "MM_res/D");
	NewT->Branch("e_acc_f", &e_acc_f, "e_acc_f/D");
	NewT->Branch("e_acc_l", &e_acc_l, "e_acc_l/D");
	NewT->Branch("g_acc_f", &g_acc_f, "g_acc_f/D");
	NewT->Branch("g_acc_l", &g_acc_l, "g_acc_l/D");
	NewT->Branch("h_acc_f", &h_acc_f, "h_acc_f/D");
	NewT->Branch("h_acc_l", &h_acc_l, "h_acc_l/D");

	NewT->Branch("eP_res", &eP_res, "eP_res/D");
	NewT->Branch("ePx_res", &ePx_res, "ePx_res/D");
	NewT->Branch("ePy_res", &ePy_res, "ePy_res/D");
	NewT->Branch("ePz_res", &ePz_res, "ePz_res/D");
	NewT->Branch("eTheta_res", &eTheta_res, "eTheta_res/D");
	NewT->Branch("ePhi_res", &ePhi_res, "ePhi_res/D");

	NewT->Branch("gP_res", &gP_res, "gP_res/D");
	NewT->Branch("gPx_res", &gPx_res, "gPx_res/D");
	NewT->Branch("gPy_res", &gPy_res, "gPy_res/D");
	NewT->Branch("gPz_res", &gPz_res, "gPz_res/D");
	NewT->Branch("gTheta_res", &gTheta_res, "gTheta_res/D");
	NewT->Branch("gPhi_res", &gPhi_res, "gPhi_res/D");

	Double_t tmin, BSA_L, TSA_L, DSA_L;
	Double_t Sigma_L, SigmaPP_L,SigmaPM_L, SigmaMP_L, SigmaMM_L;
	Double_t BSA_Tx, TSA_Tx, DSA_Tx;
	Double_t Sigma_Tx, SigmaPP_Tx,SigmaPM_Tx, SigmaMP_Tx, SigmaMM_Tx;
	Double_t BSA_Ty, TSA_Ty, DSA_Ty;
	Double_t Sigma_Ty, SigmaPP_Ty,SigmaPM_Ty, SigmaMP_Ty, SigmaMM_Ty;

	NewT->Branch("tmin",      &tmin,     "tmin/D");
	NewT->Branch("Sigma_L",   &Sigma_L,   "Sigma_L/D");
	NewT->Branch("SigmaPP_L", &SigmaPP_L, "SigmaPP_L/D");
	NewT->Branch("SigmaPM_L", &SigmaPM_L, "SigmaPM_L/D");
	NewT->Branch("SigmaMP_L", &SigmaMP_L, "SigmaMP_L/D");
	NewT->Branch("SigmaMM_L", &SigmaMM_L, "SigmaMM_L/D");
	NewT->Branch("BSA_L",     &BSA_L,     "BSA_L/D");
	NewT->Branch("TSA_L",     &TSA_L,     "TSA_L/D");
	NewT->Branch("DSA_L",     &DSA_L,     "DSA_L/D");

	NewT->Branch("Sigma_Tx",   &Sigma_Tx,   "Sigma_Tx/D");
	NewT->Branch("SigmaPP_Tx", &SigmaPP_Tx, "SigmaPP_Tx/D");
	NewT->Branch("SigmaPM_Tx", &SigmaPM_Tx, "SigmaPM_Tx/D");
	NewT->Branch("SigmaMP_Tx", &SigmaMP_Tx, "SigmaMP_Tx/D");
	NewT->Branch("SigmaMM_Tx", &SigmaMM_Tx, "SigmaMM_Tx/D");
	NewT->Branch("BSA_Tx",     &BSA_Tx,     "BSA_Tx/D");
	NewT->Branch("TSA_Tx",     &TSA_Tx,     "TSA_Tx/D");
	NewT->Branch("DSA_Tx",     &DSA_Tx,     "DSA_Tx/D");

	NewT->Branch("Sigma_Ty",   &Sigma_Ty,   "Sigma_Ty/D");
	NewT->Branch("SigmaPP_Ty", &SigmaPP_Ty, "SigmaPP_Ty/D");
	NewT->Branch("SigmaPM_Ty", &SigmaPM_Ty, "SigmaPM_Ty/D");
	NewT->Branch("SigmaMP_Ty", &SigmaMP_Ty, "SigmaMP_Ty/D");
	NewT->Branch("SigmaMM_Ty", &SigmaMM_Ty, "SigmaMM_Ty/D");
	NewT->Branch("BSA_Ty",     &BSA_Ty,     "BSA_Ty/D");
	NewT->Branch("TSA_Ty",     &TSA_Ty,     "TSA_Ty/D");
	NewT->Branch("DSA_Ty",     &DSA_Ty,     "DSA_Ty/D");
	/*}}}*/ 

	TString Data_Dir = "/work/halla/solid/yez/dvcs/DVCS_XS_Grid/";
	TString TargetPol = ""; //Tx, Ty, L 
	Int_t Debug = 0, err = 0;

	DVCSGrid *grid = new DVCSGrid();
	grid->Init(EBeam,TargetName.Data(), Data_Dir.Data(), Debug);

	/*Loop DVCS Events{{{*/  

	for(int i=0;i<N_entries; i++){
		T->GetEntry(i);

		grid->FindBin(Q2, x, -t, phi);// here -t was used instead of t
		//grid->PrintRanges();
		tmin = grid->GetTMin();	

		/*Reading the Longitudinal Target Spin{{{*/
		SigmaPP_L = 1e-36; SigmaPM_L = 1e-36;  SigmaMP_L = 1e-36;  SigmaMM_L = 1e-36; 
		Sigma_L = 1e-36;   BSA_L = 1e-36; TSA_L = 1e-36; DSA_L = 1e-36;
		TargetPol = "L";
		err = grid->LoadXS(TargetPol);
		if(err>=0){
			//grid->PrintXS();
			SigmaPP_L = grid->GetSigmaPP();//++
			SigmaPM_L = grid->GetSigmaPM();//+-
			SigmaMP_L = grid->GetSigmaMP();//-+
			SigmaMM_L = grid->GetSigmaMM();//--
			Sigma_L = grid->GetSigma();//average of four XSs above
			BSA_L = grid->GetBSA();//beam spin asym
			TSA_L = grid->GetTSA();//target spin asym
			DSA_L = grid->GetDSA();//double spin asym
		}
		/*Reading the Longitudinal Target Spin}}}*/	

		/*Reading the Transverse Target Spin on x{{{*/	
		SigmaPP_Tx = 1e-36;SigmaPM_Tx = 1e-36; SigmaMP_Tx = 1e-36; SigmaMM_Tx = 1e-36; 
		Sigma_Tx = 1e-36;  BSA_Tx = 1e-36;TSA_Tx = 1e-36;DSA_Tx = 1e-36;
		TargetPol = "Tx";
		err = grid->LoadXS(TargetPol);
		if(err>=0){
			//grid->PrintXS();
			SigmaPP_Tx = grid->GetSigmaPP();//++
			SigmaPM_Tx = grid->GetSigmaPM();//+-
			SigmaMP_Tx = grid->GetSigmaMP();//-+
			SigmaMM_Tx = grid->GetSigmaMM();//--
			Sigma_Tx = grid->GetSigma();//average of four XSs above
			BSA_Tx = grid->GetBSA();//beam spin asym
			TSA_Tx = grid->GetTSA();//target spin asym
			DSA_Tx = grid->GetDSA();//double spin asym
		//	cerr<<Form("-Tx-- BS = %e (%e)", BSA_Tx, (SigmaPP_Tx+SigmaPM_Tx - SigmaMP_Tx-SigmaMM_Tx)/4. )<<endl;
	//		cerr<<Form("-Tx-- TS = %e (%e)", TSA_Tx, (SigmaPP_Tx+SigmaMP_Tx - SigmaPM_Tx-SigmaMM_Tx)/4. )<<endl;
	//		cerr<<Form("-Tx-- DS = %e (%e)", DSA_Tx, (SigmaPP_Tx+SigmaMM_Tx - SigmaPM_Tx-SigmaMP_Tx)/4. )<<endl;
	//		cerr<<Form("-Tx-- AVG = %e ", Sigma_Tx)<<endl;
		}
		/*Reading the Transverse Target Spin on x}}}*/	

		/*Reading the Transverse Target Spin on y{{{*/	
		SigmaPP_Ty = 1e-36;SigmaPM_Ty = 1e-36; SigmaMP_Ty = 1e-36; SigmaMM_Ty = 1e-36; 
		Sigma_Ty = 1e-36;  BSA_Ty = 1e-36;TSA_Ty = 1e-36;DSA_Ty = 1e-36;

		TargetPol = "Ty";
		err = grid->LoadXS(TargetPol);
		if(err>=0){
			//grid->PrintXS();
			SigmaPP_Ty = grid->GetSigmaPP();//++
			SigmaPM_Ty = grid->GetSigmaPM();//+-
			SigmaMP_Ty = grid->GetSigmaMP();//-+
			SigmaMM_Ty = grid->GetSigmaMM();//--
			Sigma_Ty = grid->GetSigma();//average of four XSs above
			BSA_Ty = grid->GetBSA();//beam spin asym
			TSA_Ty = grid->GetTSA();//target spin asym
			DSA_Ty = grid->GetDSA();//double spin asym
		}
		/*Reading the Transverse Target Spin on y}}}*/	

		/*Acceptance{{{*/
		e_theta_bin= 0;	e_phi_bin=0;;	e_p_bin=0;
		e_acc_f= -1e6; e_acc_l= -1e6;	g_acc_f= -1e6; g_acc_l= -1e6;
		MM = -1e6; MM_res = -1e6; W = -1e6;; Wp = -1e6;
		eP_res = -1e6; ePx_res = -1e6; ePy_res = -1e6; ePz_res = -1e6; eTheta_res = -1e6; ePhi_res = -1e6;
		gP_res = -1e6; gPx_res = -1e6; gPy_res = -1e6; gPz_res = -1e6; gTheta_res = -1e6; gPhi_res = -1e6;

		e_theta_bin=int(eTheta/0.5)+1;    //0.5 degree per bin
		e_phi_bin=int(ePhi/2.0)+1;    //2 degree per bin
		e_p_bin=int(eP/0.1)+1;      //0.1 GeV per bin for mom
		e_acc_f=accep_ele_forward->GetBinContent(e_theta_bin,e_phi_bin,e_p_bin);
		e_acc_l=accep_ele_large->GetBinContent(e_theta_bin,e_phi_bin,e_p_bin);

		if(eP<1.0||eTheta>14.5||eTheta<8.0)//GeV, CLEO
			e_acc_f=0.0;//Farward-Angle EC Cut at 1 GeV
		if(eP<1.0||eTheta<15.5||eTheta>24)//GeV,CLEO
			e_acc_l=0.0; //Larger-Angle EC Cut at 3 GeV
		if(e_acc_f>1.) 
			e_acc_f=1.0; 
		if(e_acc_l>1.) 
			e_acc_l=1.0; 

		h_theta_bin=int(hTheta/0.5)+1;  //0.5 degree per bin
		h_phi_bin=int(hPhi/2.0)+1;  //2 degree per bin
		h_p_bin=int(hP/0.1)+1;     //0.1 GeV per bin
		h_acc_f=accep_had_forward->GetBinContent(h_theta_bin,h_phi_bin,h_p_bin);
		h_acc_l=accep_had_large->GetBinContent(h_theta_bin,h_phi_bin,h_p_bin);

		g_theta_bin=int(gTheta/0.5)+1;  //0.5 degree per bin
		g_phi_bin=int(gPhi/2.0)+1;  //2.0 degree per bin
		g_p_bin=int(gP/0.1)+1;     //0.1 GeV per bin for mom
		g_acc_f=accep_pho_forward->GetBinContent(g_theta_bin,g_phi_bin,g_p_bin);
		g_acc_l=accep_pho_large->GetBinContent(g_theta_bin,g_phi_bin,g_p_bin);

		/*Additional cuts{{{*/
		/*
		   if(gTheta<=14.8&&gTheta>=8.0&&gP>=1.0&&gP<=11.){
		   g_acc_f=1.0; 
		   g_acc_l=0.0; 
		   }
		   else if(gTheta<=24.0&&gTheta>=16.&&gP>=1.0&&gP<=11.){
		   g_acc_f=0.0; 
		   g_acc_l=1.0; 
		   }else{
		   g_acc_f=0.0; 
		   g_acc_l=0.0; 
		   }
		   */
		/*}}}*/

		//	double e_acceptance = e_acc_f+e_acc_l;
		//	double g_acceptance = g_acc_f+g_acc_l;
		//	double eg_acceptance = e_acceptance*g_acceptance;
		//double event_weight=(XS_P+XS_M)*PSF/N_gen*Lumi*nBcm2;   //put into Hz, Note, XS in nb
		/*Acceptance}}}*/

		/*Missing Mass w/o resolutions{{{*/
		eE_i = sqrt(eP_ini*eP_ini + eMass*eMass);
		eE_f = sqrt(eP*eP + eMass*eMass);
		hE = sqrt(hP*hP + hMass*hMass);
		gE = gP;

		P_E0->SetPxPyPzE(0.,0.,E0, E0);
		P_t->SetPxPyPzE(0.,0.,0., hMass);
		P_e_i->SetPxPyPzE(ePx_ini, ePy_ini, ePz_ini, eE_i);
		P_e_f->SetPxPyPzE(ePx, ePy, ePz, eE_f);	
		P_g->SetPxPyPzE(gPx, gPy, gPz, gE);	
		P_h->SetPxPyPzE(hPx, hPy, hPz, hE);

		int err = CheckLaws(P_t, P_E0, P_e_i, P_g, P_h);//Check whether momentum and energy conserve first
		if (err < 1e-33){
			cerr<<"---- Momentum and Energy Conservation Laws are broken!! Something is wrong!!!"<<endl;
			return -222;
		}

		MM = GetMM(P_t, P_E0, P_e_i, P_g);	
		/*}}}*/

		/*Missing Mass w resolutions{{{*/
		//////////////////////////////////////////////////////////////////////////
		//Now consider the detector resolution here
		//////////////////////////////////////////////////////////////////////////
		//
		/////////////////////////////////////////
		//Electron w/o E-loss
		eP_res = gRandom->Gaus(eP_ini, Sigma_EC_E*eP_ini);//GeV, for electron, E ~= P
		eTheta_res = gRandom->Gaus(eTheta_ini*Deg2Rad, Sigma_Theta_E);//rad
		ePhi_res = gRandom->Gaus(ePhi_ini*Deg2Rad, Sigma_Phi_E);//rad

		ePx_res = eP_res * sin(eTheta_res)*cos(ePhi_res); 
		ePy_res = eP_res * sin(eTheta_res)*sin(ePhi_res); 
		ePz_res = eP_res * cos(eTheta_res);

		eE_i_res = sqrt(eP_res*eP_res + eMass*eMass);
		P_e_res->SetPxPyPzE(ePx_res, ePy_res, ePz_res, eE_i_res);	

		/////////////////////////////////////////
		//Electron with E-loss
		/*
		   eP_res = gRandom->Gaus(eP, Sigma_EC_E*sqrt(eP));//GeV, for electron, E ~= P
		   eTheta_res = gRandom->Gaus(eTheta*Deg2Rad, Sigma_Theta_E);//rad
		   ePhi_res = gRandom->Gaus(ePhi*Deg2Rad, Sigma_Phi_E);//rad

		   ePx_res = eP_res * sin(eTheta_res)*cos(ePhi_res); 
		   ePy_res = eP_res * sin(eTheta_res)*sin(ePhi_res); 
		   ePz_res = eP_res * cos(eTheta_res);

		   eE_f_res = sqrt(eP_res*eP_res + eMass*eMass);
		//P_e_res->SetPxPyPzE(ePx_res, ePy_res, ePz_res, eE_i_res);	
		*/
		/////////////////////////////////////////
		//Photon
		double gZ = Length-vertexz; 
		double gX = gZ * tan(gTheta*Deg2Rad)*cos(gPhi*Deg2Rad); 
		double gY = gZ * tan(gTheta*Deg2Rad)*sin(gPhi*Deg2Rad); 
		double gX_res =gRandom->Gaus(gX, Sigma_X_G);//cm
		double gY_res =gRandom->Gaus(gY, Sigma_Y_G);//cm
		double gZ_res =gRandom->Gaus(gZ, Sigma_VZ);//cm 

		gP_res = gRandom->Gaus(gP, Sigma_EC_G*sqrt(gP));//GeV, for photon, E = P
		gPhi_res = atan2(gY_res, gX_res);
		gTheta_res = atan2(sqrt(gX_res*gX_res+gY_res*gY_res), gZ_res);

		gPx_res = gP_res * sin(gTheta_res)*cos(gPhi_res); 
		gPy_res = gP_res * sin(gTheta_res)*sin(gPhi_res); 
		gPz_res = gP_res * cos(gTheta_res);
		P_g_res->SetPxPyPzE(gPx_res, gPy_res, gPz_res, gP_res);	

		/////////////////////////////////////////
		MM_res = GetMM(P_t, P_E0, P_e_res, P_g_res);	
		/////////////////////////////////////////
		/*}}}*/

		W = (*P_E0 + *P_t - *P_e_i)*(*P_E0 + *P_t - *P_e_i);
		Wp = (*P_E0 + *P_t - *P_e_i - *P_h)*(*P_E0 + *P_t - *P_e_i - *P_h);
		W = sqrt(W);
		Wp = sqrt(Wp);


		if(!(i%1000)) cerr<<Form("--- Processing #event = %d/%d", i,(int)(N_entries) ) <<"\r";

		NewT->Fill();
	}
	/*}}}*/

	/*Save and Free{{{*/
	NewT->Write("",TObject::kOverwrite);
	newfile->Close();
	file->Close();
	delete grid;
	delete P_g; delete P_t; delete P_e_i; delete P_e_f; delete P_h; delete P_e_res; delete P_g_res;
	/*Save and Free}}}*/
}
コード例 #27
0
ファイル: makesigback.C プロジェクト: twighk/gbmsci
int makesigback(){
    
    TFile * infile = new TFile("../root/combo115.root");
//    TFile * infile = new TFile("../root/combo160.root");

    Int_t type1 = 1;
    Int_t type2 = 0;
    Double_t weight;
    Int_t switchpoint;
    TTree * intree = (TTree*)infile->Get("combotree");
    TTree * inmeta = (TTree*)infile->Get("metadata");
    inmeta->SetBranchAddress("BeginIndex", &switchpoint);
    inmeta->GetEntry(2);
    cout << switchpoint << endl;
    
    TObjArray* lob = intree->GetListOfBranches();

    intree->SetBranchStatus("*",0);
    
	for (Int_t i = 0; i < lob->GetEntriesFast(); ++i) {
		TBranch * branch = (TBranch *)lob->At(i);
		string bname = string(branch -> GetName());
        if(string(bname).compare(0,4,"type")){
            if (bname == "weight") {
                continue;
            }
            intree->SetBranchStatus(bname.c_str(),1);

		}
    }
    
    TFile *newfile = new TFile("../root/combo115sb.root","recreate");
    TTree *newtree = intree->CloneTree(0);
    newtree->Branch("type1", &type1);
    newtree->Branch("type2", &type2);
    newtree->Branch("weight", &weight);
    weight = (1. / Double_t(switchpoint) );

    for (UInt_t j = 0; j < intree->GetEntriesFast(); ++j) {
            if (j == switchpoint) {
                type1 = 0;
                type2 = 1;
                weight = (1. / Double_t(intree->GetEntriesFast() - switchpoint) );
            }
             intree->GetEntry(j);
             newtree->Fill();
          }
    
    Int_t newbegin;
    Int_t newend;
    TString newchannelname;
    TTree * newmeta = new TTree("metadata", "metadata");
    newmeta->Branch("BeginIndex", &newbegin);
    newmeta->Branch("EndIndex", &newend);
    newmeta->Branch("ChannelName",&newchannelname,256000,0);
    
    newbegin = 0;
    newend = switchpoint - 1;
    newchannelname = "signal";
    newmeta->Fill();
    
    newbegin = switchpoint;
    newend = (intree->GetEntriesFast()) - 1;
    newchannelname = "backgr";
    newmeta->Fill();

    newfile->Write();
    delete infile;
    delete newfile;
    
//    vector <TFile*> files;
//    vector <TTree*> trees;
//    vector < vector<Double_t> > Int_lum;
//    vector <TFile*> outfiles;
//    vector <TTree*> outtrees;
//    vector <string> names;
    
//    Int_lum.resize(15);
//    Int_lum[0].push_back(7852.);
//    Int_lum[1].push_back(3831.);
//    Int_lum[2].push_back(36823.);
//    Int_lum[3].push_back(11400.);
//    Int_lum[4].push_back(10.4);
//    Int_lum[5].push_back(8.4);
//    Int_lum[6].push_back(47.2);
//    Int_lum[7].push_back(6.28);
//    Int_lum[8].push_back(7.94);
//    Int_lum[9].push_back(18.1);
//    Int_lum[10].push_back(2562.);
//    Int_lum[11].push_back(243.);
//    Int_lum[12].push_back(3483.);
//    Int_lum[13].push_back(3483.);
//    Int_lum[14].push_back(331.);

//    names.push_back("AH115");
//    names.push_back("AH115bb");
//    names.push_back("AH160");
//    names.push_back("AH160bb");
//    names.push_back("QCD_BCtoE_Pt20to30");
//    names.push_back("QCD_BCtoE_Pt30to80");
//    names.push_back("QCD_BCtoE_Pt80to170");
//    names.push_back("QCD_EMenriched_Pt20to30");
//    names.push_back("QCD_EMenriched_Pt30to80");
//    names.push_back("QCD_EMenriched_Pt80to170");
//    names.push_back("TTplusJets");
//    names.push_back("WplusJets");
//    names.push_back("Zbb");
//    names.push_back("Zcc");
//    names.push_back("ZplusJets");

    
//    for (UInt_t i = 0; i < names.size(); ++i) {
//        files.push_back(new TFile( ("../root/oldroot/"+names[i]+".root").c_str() ));
//        trees.push_back( (TTree*)files[i]->Get("bbAHCutTree") );
//        outfiles.push_back(new TFile ( ("../root/"+names[i]+".root").c_str() , "RECREATE"));
//        outtrees.push_back( trees[i]->CloneTree(0) );
//        outtrees[i]->Branch("intlum", &(Int_lum[i]));
//        for (UInt_t j = 0; j < trees[i]->GetEntriesFast(); ++j) {
//            trees[i]->GetEntry(j);
//            outtrees[i]->Fill();
//        }
//        outfiles[i]->Write();
//    }
                           
    return 0;


}
コード例 #28
0
void absorbedSubtraction (char* bkgndTreeName, char* absTreeName, char* outHistName, int numberOfSlices,float sliceWidth ,int extent, float modifier,TFile* backgroundFile, TFile* inFile, TFile* outFile,float startY, int nBinsX, int nBinsZ,float xMax, float xMin,float zMax, float zMin) 
{
  // ******************** absorbed muon tree
  double xCut, xGrad, zCut, zGrad;

  TTree* abs = (TTree*) inFile->Get(absTreeName);
  
  abs->SetBranchAddress("xCut",&xCut);
  abs->SetBranchAddress("yCut",&zCut);

  abs->SetBranchAddress("xGrad",&xGrad);
  abs->SetBranchAddress("yGrad",&zGrad);

  int nEntriesS = abs->GetEntries();

  // ******************** background absorbed muon tree
  double xCutB, xGradB, zCutB, zGradB;

  TTree* absB = (TTree*) backgroundFile->Get(bkgndTreeName);
  
  absB->SetBranchAddress("xCut",&xCutB);
  absB->SetBranchAddress("yCut",&zCutB);

  absB->SetBranchAddress("xGrad",&xGradB);
  absB->SetBranchAddress("yGrad",&zGradB);

  int nEntriesB = absB->GetEntries();

  // ******************** calculate the threshold and similar

  float vol = std::pow ((float) (2*extent+1),3);

  float threshold = modifier; 

  float scalingConstant = ((float) nEntriesS) / ((float)nEntriesB); 
  
  // ******************** run for each slice 

  for (int j = 0; j < numberOfSlices; j++)
    {
      double y = (j*sliceWidth + startY); // the 'real' value of y
      char name  [25];
      char nameS [25];
      char nameB [25];
      char yVal  [5];
	  
      sprintf (yVal, "%d",(int)y);

      strcpy (name,outHistName);
      strcat (name, yVal);
      
      strcpy (nameB, outHistName);
      strcat (nameB, "B");
      strcat (nameB, yVal);
      
      strcpy (nameS, outHistName);
      strcat (nameS, "S");
      strcat (nameS, yVal);

      TH2D* out  = new TH2D (name, name,  nBinsX,xMin,xMax, nBinsZ,zMin,zMax);
      TH2D* outS = new TH2D (nameS,nameS, nBinsX,xMin,xMax, nBinsZ,zMin,zMax);
      TH2D* outB = new TH2D (nameB,nameB, nBinsX,xMin,xMax, nBinsZ,zMin,zMax);
      
      // ******************** create the source histo
      for (int entry = 0; entry < nEntriesS; entry++)
	{
	  abs->GetEntry(entry);
	  
	  if(xGrad == 0 || zGrad == 0) continue; // if there is null gradient ignore and continue      

	  double x = (y - xCut)/ xGrad;  // calculate x and z positions using the y value (x = (y-cut)/grad)
	  double z = (y - zCut)/ zGrad;  
	  
	  outS->Fill (x,z,1);
	}
  
      outFile->Add(outS);
      // ******************** create background histo 

      for (int entryB = 0; entryB < nEntriesB; entryB++)
	{
	  absB->GetEntry(entryB);
	  
	  if(xGradB == 0 || zGradB == 0) continue; // if there is null gradient ignore and continue      

	  double x = (y - xCutB)/ xGradB;  // calculate x and z positions using the y value (x = (y-cut)/grad)
	  double z = (y - zCutB)/ zGradB;
	  
	  outB->Fill (x,z,1);
	}
       outFile->Add(outB);

      // ******************** test the source density against background density

      for (int i =0; i < nBinsX; i++)
	{
	  for (int k = 0; k < nBinsZ; k++)
	    {
	      float bkgnd = 0;
	      float test  = 0;

	      for (int io = -extent; io <= extent; io++)
		{
		  for (int ko = -extent; ko <= extent; ko++)
		    {
		      test  += outS->GetBinContent ((i+io),(k+ko));
		      bkgnd += outB->GetBinContent ((i+io),(k+ko));
		    }
		}

	      test  = (test/vol) /scalingConstant; // ensures that the densities are comparable
	      bkgnd = (bkgnd/vol)*scalingConstant;

	      if (std::fabs (test-bkgnd) > threshold)
		{
		  out->SetBinContent (i,k,1);  
		}    
	    }
	  if (!(i%10)) std::cout<<(j*nBinsX)+ i<<" of "<<(numberOfSlices*nBinsX)<<std::endl;
	}
      outFile->Add(out);
    }
  std::cout<<vol<<" "<<threshold<<std::endl;
}
コード例 #29
0
ファイル: genPlots02.C プロジェクト: frmeier/usercode
// draw the same thing but after reco
void genPlots02(std::string fullPath, int nOverlay = 500, bool custBinning = false)
{
    const int fVerbose(1);
    setTDRStyle();
    gStyle->SetOptStat(112211);
    gStyle->SetPalette(1);
    // Canvas
    c = new TCanvas("c2","c2",1000,600);
    const unsigned int nPadX = 1;
    const unsigned int nPadY = 1;
    c->Divide(nPadX,nPadY);
    const unsigned int nPads=nPadX*nPadY;
    for(unsigned int i=1; i<=nPads; i++)
    {
	TPad* pad= (TPad*)c->cd(i);
	pad->SetTopMargin(0.10);
	pad->SetRightMargin(0.20);
	pad->SetLeftMargin(0.15);
    }
    // Open file
    TFile *f = TFile::Open(fullPath.c_str());
    if (f==0)
    {
	cout << "File " << fullPath << " not found -- exiting" << endl;
	return;
    }
    if(fVerbose>0)
	cout << "Succesfully opened file " << fullPath << endl;
    // Get TTree
    TTree* t = (TTree*) f->Get("events");
    if(fVerbose>0) cout << "Got TTree with " << t->GetEntries() << " entries" << endl;
    // Do a cut, if needed
    //t->Draw(">>lst","chi2lb>.1&&mlb>5.61&&mlb<5.63");
    //t->Draw(">>lst","chi2lb>.1&&isSig==1");
    t->Draw(">>lst","(rid1m&4)==4&&(rid2m&4)==4&&mjp>2.895&&mjp<3.295&&prob1m>0.1&&prob2m>0.1&&ptjp>2&&probjp>0.005&&ml0>1.101&&ml0<1.129&&probpr>0.02&&probpi>0.02&&rptpr>rptpi&&ptl0>3&&rptpr>1&&rptpi>0.5&&probl0>0.02&&alphal0<0.3&&d3l0>1&&d3l0/d3El0>10&&problb>0.001&&alphalb<0.3");
    TEventList *lst;
    lst = (TEventList*)gDirectory->Get("lst");
    t->SetEventList(lst);
    if(fVerbose>0) cout << "Got TTree with " << t->GetEntries() << " entries" << endl;

    // Do plots
    c->cd(1);
    //doPlot2d(t,"hrzL0vtx", "vrl0:TMath::Abs(vzl0)",30,0,300,30,0,120,"Tit","|z|","r","cm","cm");
    if (custBinning)
    {
	double newbinsX[]={0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50};
	const int newbinsX_size = sizeof(newbinsX)/sizeof(double);
	std::vector<double> binvecX(newbinsX,newbinsX+newbinsX_size);
	//double newbinsY[]={0,1,2,3,4,5,6,7,8,9,10};
	double newbinsY[]={0,0.5,1,2,4,8,16,32};
	const int newbinsY_size = sizeof(newbinsY)/sizeof(double);
	std::vector<double> binvecY(newbinsY,newbinsY+newbinsY_size);
	doPlot2d(t,"hrzL0vtxreco", "vrl0:TMath::Abs(vzl0)",binvecX, binvecY,"#Lambda vertices","|z|","r","cm","cm");
    }
    else
    {
	doPlot2d(t,"hrzL0vtxreco", "vrl0:TMath::Abs(vzl0)",30,0,50,30,0,30,"#Lambda vertices","|z|","r","cm","cm");
    }

    // add tracker
    TPad* pad;
    pad = (TPad*)c->cd(1);
    pad->Modified();
    pad->Update();
    repositionPalette("hrzL0vtxreco");
    pad->Update();
    pad->SetLogz();
    drawTracker(pad);

    if (nOverlay<=0) return;
    int maxN = nOverlay;
    if (maxN > t->GetEntries()) maxN = t->GetEntries();
    double vrl0,vzl0,ppr,ppi,etapr,etapi;
    t->SetBranchAddress("vrl0",&vrl0);
    t->SetBranchAddress("vzl0",&vzl0);
    t->SetBranchAddress("ppr",&ppr);
    t->SetBranchAddress("etapr",&etapr);
    t->SetBranchAddress("ppi",&ppi);
    t->SetBranchAddress("etapi",&etapi);
    double scalepr = 4;
    double scalepi = 8;

    { // reference indicator
	const double x1pr = 0; const double y1pr = -3;
	const double x2pr = scalepr; const double y2pr = y1pr;
	const double versatz = 14;
	const double x1pi = x1pr+versatz; const double y1pi = -3;
	const double x2pi = x2pr+versatz+scalepi; const double y2pi = y1pi;
	TArrow *a;
	a = new TArrow(x1pr,y1pr,x2pr,y2pr,.01,">");
	a->SetLineColor(24);
	a->Draw();
	TLatex tl;
	tl.SetTextSize(20);
	tl.SetTextFont(4);
	tl.DrawLatex(x1pr,y2pr-1.2,"p(p) / 1 GeV");
	a = new TArrow(x1pi,y1pi,x2pi,y2pi,.01,">");
	a->SetLineColor(20);
	a->Draw();
	tl.SetTextSize(20);
	tl.SetTextFont(4);
	tl.DrawLatex(x1pi,y2pi-1.2,"p(#pi) / 1 GeV");
    }
    for (int i = 0; i!=maxN; i++)
    {
	t->GetEntry(i);
	const double thetapr = 2*TMath::ATan(TMath::Exp(-TMath::Abs(etapr)));
	const double thetapi = 2*TMath::ATan(TMath::Exp(-TMath::Abs(etapi)));
	const double x1=TMath::Abs(vzl0);
	const double y1=vrl0;
	const double x2pr=x1+scalepr*ppr*TMath::Cos(thetapr);
	const double y2pr=y1+scalepr*ppr*TMath::Sin(thetapr);
	const double x2pi=x1+scalepi*ppi*TMath::Cos(thetapi);
	const double y2pi=y1+scalepi*ppi*TMath::Sin(thetapi);
	TArrow *a;
        a = new TArrow(x1,y1,x2pr,y2pr,.01,">");
	a->SetLineColor(24);
	a->Draw();
        a = new TArrow(x1,y1,x2pi,y2pi,.01,">");
	a->SetLineColor(20);
	a->Draw();
	TMarker *m = new TMarker(x1,y1,7);
	m->SetMarkerColor(28);
	m->Draw();
    }
}
コード例 #30
0
ファイル: LYZ.C プロジェクト: XuQiao/HI
// ------------ method called for each event  ------------
void
LYZ::calcV(int way)	//way=0: Prod way=1: Sum
{
   using namespace std;


	TComplex g[ntheta][nstepr];
	double Q[ntheta];	double Qx;	double Qy;
	int mult, ntrk;
        Float_t phi[10000], eta[10000], pt[10000];
        TFile *infile = TFile::Open(filename);
        TTree* t = (TTree*)infile->Get("tree");
        t->SetBranchAddress("n",&mult);
        t->SetBranchAddress("ptg",pt);
        t->SetBranchAddress("phig",phi);
        t->SetBranchAddress("etag",eta);
        int nevent = t->GetEntries();
        for(int ievt=0; ievt<nevent; ievt++){
                t->GetEntry(ievt);
	//	if(ievt%10000==0) cout<<"has processed "<<ievt<<" events"<<endl;
			for(int itheta=0;itheta<ntheta;itheta++){
       			Q[itheta]=0;
                	for(int ir=0; ir<nstepr; ir++)
                		if(way==0)
                        		g[itheta][ir]=1.;
                        	else
                        		g[itheta][ir]=0.;
	        	}
			Qx=0,Qy=0;

		ntrk = mult; int nTracks = ntrk;	int xbin=-1;
		for(int j=0;j<nbin;j++)
                if(nTracks<trkbin[j]&&nTracks>=trkbin[j+1])
                        xbin=j;
        	if(xbin<0 || xbin==nbin) continue;	
                tottrk[xbin]+=ntrk;
		for(int imult=0;imult<mult;imult++){
		//	if(eta[imult]<-2.40||eta[imult]>2.40) continue;
                //        if(pt[imult]<ptmin||pt[imult]>ptmax) continue; //event selection
			Qx+=1.*cos(nn*phi[imult]);
			Qy+=1.*sin(nn*phi[imult]);
			for(int itheta=0;itheta<ntheta;itheta++){
                        	double temp=TMath::Cos(nn*(phi[imult]-theta[itheta]));
				for(int ir=0; ir<nstepr; ir++)
	                           if(way==0){
					g[itheta][ir]*=TComplex(1.,r[xbin][ir]*temp);
                                   }
                	        //   else 
				//	g[itheta][0]+=temp;
                	}
                        totptall[xbin]+=pt[imult];
                        totetaall[xbin]+=eta[imult];
			totmultall[xbin]++;
		}
			Qx1[xbin]+=Qx;	Qy1[xbin]+=Qy;
			Qx2[xbin]+=Qx*Qx;	Qy2[xbin]+=Qy*Qy;
			for(int itheta=0;itheta<ntheta;itheta++){
				Q[itheta]=Qx*TMath::Cos(nn*theta[itheta])+Qy*TMath::Sin(nn*theta[itheta]);
				for(int ir=0; ir<nstepr; ir++){
					if(way!=0)	g[itheta][ir]=TComplex::Exp(TComplex(0,r[xbin][ir]*Q[itheta]));//g[itheta][0]
					GRe[xbin][itheta][ir]+=g[itheta][ir].Re();
					GIm[xbin][itheta][ir]+=g[itheta][ir].Im();
				}
		}

		Nevent[xbin]++;
	}
	infile->Close();
}