/*Given the impact point on the front face (vin) and the incoming particle LorentzVector (chi for invisible decay, A' for visible),
 *  determine the interaction point within the fiducial volume and save it in vhit.
 Use a random distribution along the chi flight path, with uniform probability
 This function returns the length (in m) of the trajectory within the fiducial volume.
 Displacement is the lateral displacement (in m) of the detector, along x
 */
double KinUtils::findInteractionPoint(const TLorentzVector &chi, const TVector3 &fiducialV, const TVector3 &vin, TVector3 &vout, TVector3 &vhit) {

	double tz, tx, ty, tout, L;
	int sigPx, sigPy;

	sigPx = (chi.Px() > 0 ? 1 : -1);
	sigPy = (chi.Py() > 0 ? 1 : -1);

	tz = fiducialV.Z() / chi.Pz();
	tx = (sigPx * fiducialV.X() / 2 - vin.X()) / chi.Px();
	ty = (sigPy * fiducialV.Y() / 2 - vin.Y()) / chi.Py();
	tout = 0;

	if ((tz < tx) && (tz < ty)) {
		tout = tz;
	} else if ((tx < ty) && (tx < tz)) {
		tout = tx;
	} else if ((ty < tx) && (ty < tz)) {
		tout = ty;
	}
	vout.SetXYZ(tout * chi.Px() + vin.X(), tout * chi.Py() + vin.Y(), tout * chi.Pz() + vin.Z());
	vhit.SetXYZ(Rand.Uniform(vin.X(), vout.X()), Rand.Uniform(vin.Y(), vout.Y()), Rand.Uniform(vin.Z(), vout.Z()));
	L = (vout - vin).Mag();

	return L;
}
示例#2
0
void KVFAZIALNS2016::BuildFAZIA()
{
   //Build geometry of FAZIASYM
   //All telescopes are : Si(300µm)-Si(500µm)-CsI(10cm)
   //No attempt has been made to implement real thicknesses
   //
   Info("BuildFAZIA", "Compact geometry, %f cm from target",
        fFDist);

   TGeoVolume* top = gGeoManager->GetTopVolume();

   Double_t distance_block_cible = fFDist * KVUnits::cm;
   Double_t thick_si1 = 300 * KVUnits::um;
   TGeoTranslation trans;
   trans.SetDz(distance_block_cible + thick_si1 / 2.);

   KVFAZIABlock* block = new KVFAZIABlock;

   TGeoRotation rot1, rot2;
   TGeoHMatrix h;
   TGeoHMatrix* ph = 0;
   Double_t theta = 0;
   Double_t phi = 0;

   Double_t theta_min = fFThetaMin;//smallest lab polar angle in degrees
   Double_t centre_hole = 2.*tan(theta_min * TMath::DegToRad()) * distance_block_cible;
   Double_t dx = (block->GetTotalSideWithBlindage()) / 2.;

   TVector3 centre;
   for (Int_t bb = 0; bb < fNblocks; bb += 1) {

      if (bb == 1)        centre.SetXYZ(-1 * (dx - centre_hole / 2), -dx - centre_hole / 2, distance_block_cible);
      else if (bb == 2)   centre.SetXYZ(-1 * (dx + centre_hole / 2), dx - centre_hole / 2, distance_block_cible);
      else if (bb == 3)   centre.SetXYZ(-1 * (-dx + centre_hole / 2), dx + centre_hole / 2, distance_block_cible);
      else if (bb == 0)   centre.SetXYZ(-1 * (-dx - centre_hole / 2), -dx + centre_hole / 2, distance_block_cible);
      else if (bb == 4)   centre.SetXYZ(-1 * (-dx - centre_hole / 2), -3 * dx + centre_hole / 2, distance_block_cible); //centre.SetXYZ(-1 * (dx - centre_hole / 2), -3 * dx - centre_hole / 2, distance_block_cible);
      else {
         Warning("BuildFAZIA", "Block position definition is done only for %d blocks", fNblocks);
      }
      theta = centre.Theta() * TMath::RadToDeg();
      phi = centre.Phi() * TMath::RadToDeg();
      printf("BLK #%d => theta=%1.2lf - phi=%1.2lf\n", bb, theta, phi);

      rot2.SetAngles(phi + 90., theta, 0.);
      rot1.SetAngles(-1.*phi, 0., 0.);
      h = rot2 * trans * rot1;
      ph = new TGeoHMatrix(h);
      top->AddNode(block, bb, ph);
   }

   // add telescope for elastic scattering monitoring
//   RutherfordTelescope();
   // Change default geometry import angular range for rutherford telescope
   SetGeometryImportParameters(.25, 1., 1.84);
}
示例#3
0
TVector3 KVParticle::GetVelocity() const
{
   //returns velocity vector in cm/ns units
   TVector3 beta;
   if (E()) {
      beta = GetMomentum() * (1. / E());
   } else {
      beta.SetXYZ(0, 0, 0);
   }
   return (kSpeedOfLight * beta);
}
//This is the function to determine the interaction point in case of a cylinder (case1), for BDXmini.
//The cylinder is with the axis along y(vertical), center at x=0,y=0,z=ldet, radius is R,height is h
double KinUtils::findInteractionPointCylinder1(const TLorentzVector &chi,double ldet,double h,double R,TVector3 &vin,TVector3 &vout,TVector3 &vhit){

	double tIN,tOUT,t2,t3,t,L;

	double px=chi.Px();
	double py=chi.Py();
	double pz=chi.Pz();

	double delta=pz*pz*ldet*ldet-(pz*pz+px*px)*(ldet*ldet-R*R);
	if (delta<0){
		cout<<"KinUtils::findInteractionPointCylinder1 error, the delta is: "<<delta<<endl;
		return 0;
	}

	//entry point
	tIN = (pz*ldet - sqrt(delta))/(px*px+pz*pz);
	t2 = (pz*ldet + sqrt(delta))/(px*px+pz*pz);

	t3 = (h/2)/py;


	if ((t3>0)&&(t3<t2)&&(t3>tIN)){
		tOUT=t3;
	}else{
		tOUT=t2;
	}

	t=Rand.Uniform(tIN,tOUT);

	vin.SetXYZ(tIN*px,tIN*py,tIN*pz);
	vout.SetXYZ(tOUT*px,tOUT*py,tOUT*pz);

	vhit.SetXYZ(t*px,t*py,t*pz);


	L = (vout - vin).Mag();



	return L;
}
示例#5
0
// This is the pt corrected MR - here, we assume the pt
// of the Higgs is (MET+Pt+Qt);
// L1 and L2 are the 4-vectors for the 2 hemispheres, or in you case,
// the two leptons - setting mass to 0 should be fine
// MET is the MET 3 vector (don't forget to set the z-component of
// MET to 0)
// Also, 2 times this variable should give you the Higgs mass
double HWWKinematics::CalcMRNEW(){
  TVector3 vI = MET+L1.Vect()+L2.Vect();
  vI.SetZ(0.0);
  double L1pL2 = CalcMR(); //Note - this calls the old MR function
  double vptx = (L1+L2).Px();
  double vpty = (L1+L2).Py();
  TVector3 vpt;
  vpt.SetXYZ(vptx,vpty,0.0);
  
  float MR2 = 0.5*(L1pL2*L1pL2-vpt.Dot(vI)+L1pL2*sqrt(L1pL2*L1pL2+vI.Dot(vI)-2.*vI.Dot(vpt)));
  
  return sqrt(MR2);
  
}
示例#6
0
// M is the MET 3 vector (don't forget to set the z-component of
// MET to 0)
double HWWKinematics::CalcMRNEW(TLorentzVector P, TLorentzVector Q, TVector3 M){
 TVector3 vI = M+P.Vect()+Q.Vect();
 vI.SetZ(0.0);
 double PpQ = CalcMR(P,Q); //Note - this calls the old MR function
 double vptx = (P+Q).Px();
 double vpty = (P+Q).Py();
 TVector3 vpt;
 vpt.SetXYZ(vptx,vpty,0.0);

 float MR2 = 0.5*(PpQ*PpQ-vpt.Dot(vI)+PpQ*sqrt(PpQ*PpQ+vI.Dot(vI)-2.*vI.Dot(vpt)));

 return sqrt(MR2);

}
示例#7
0
文件: tv3.C 项目: alcap-org/AlcapDAQ
void tv3Write() {
   //creates the Tree
   TVector3 *v = new TVector3();
   TVector3::Class()->IgnoreTObjectStreamer();
   TFile *f = new TFile("v3.root","recreate");
   TTree *T = new TTree("T","v3 Tree");
   T->Branch("v3","TVector3",&v,32000,1);
   TRandom r;
   for (Int_t i=0;i<10000;i++) {
      v->SetXYZ(r.Gaus(0,1),r.Landau(0,1),r.Gaus(100,10));
      T->Fill();
   }
   T->Write();
   T->Print();
   delete f;
}
int main(int argc,char **argv){
	if (argc==1){
		PrintHelp();
		exit(1);
	}
	ParseCommandLine(argc,argv);
	//Load Cintex and the shared library
	LOADLIBS

	if (fDoBatch)  gROOT->SetBatch();



	if (fSigName.length()==0){
		cerr<<"Missing SIGNAL file name!"<<endl;
		return -1;
	}
	if (fBckName.length()==0){
		cerr<<"Missing BCK file name!"<<endl;
		return -1;
	}
	if (fDetName.length()==0){
		cerr<<"Missing DET file name"<<endl;
		return -1;
	}
	if (fSetupName.length()==0){
		cerr<<"Missing Setup file name"<<endl;
		return -1;
	}
	if (fReconName.length()==0){
		cerr<<"Missing Recon file name"<<endl;
		return -1;
	}
	else if (fReconName.find(".root")!=std::string::npos){
		cout<<"ROOT mode"<<endl;
		fDoRoot=1;
	}
	else{
		cout<<"Model mode";
		fDoRoot=0;
	}
	if (fOutName.length()==0){
		cout<<"Missing OUT file name, auto-selecting"<<endl;
		fOutName=fSigName+".out";
	}
	fOutNameRoot=fOutName+".root";
	fOutNamePS=fOutName+".ps";
	TFile *f1=new TFile(fSigName.c_str());
	TFile *f2=new TFile(fBckName.c_str());

	TFile *fOut=new TFile(fOutNameRoot.c_str(),"recreate");


	TTree *tSig=(TTree*)f1->Get("fTdata");
	TTree *tBck=(TTree*)f2->Get("fTdata");

	Float_t ADC[TMarocSetupHandler::nMarocChannels];
	Bool_t hit[TMarocSetupHandler::nMarocChannels];
	double PedSig[TMarocSetupHandler::nMarocChannels],PedBck[TMarocSetupHandler::nMarocChannels],MeanDiff[TMarocSetupHandler::nMarocChannels];

	double fExp[6][MAX_DETECTORS][TMarocSetupHandler::nH8500Pixels];double fNormExp;
	double fTeo[6][MAX_DETECTORS][TMarocSetupHandler::nH8500Pixels];double fNormTeo;
	double fMC[6][MAX_DETECTORS][TMarocSetupHandler::nH8500Pixels];double fNormMC;

	Int_t EvtMultiplicity;
	int Nb,Ns,Nped;
	int id;
	int ix,iy,iH8500,iMarocChannel,iMarocCard,iRealDet,iReconDet,iReconFace,iReconPixel;
	int iPad;

	int flagQcut;
	double Q,QSigTot,QBckTot;
	double QSigTotL,QBckTotL;
	double QSigTotR,QBckTotR;

	const double QTotThr=-20E3;
	const double QTotLThr=0;
	const double QTotRThr=0;

	double Scale;
	double oldMeanSig,oldMeanBck,oldMeanDiff;
	double MeanDiffCorrected;
	double Gain,F,Corr;
	double min,max;
	TVector3 vin;


	int Nx,Ny;
	TDetector *m_detector=new TDetector(fDetName);
	TMarocSetupHandler *m_setup=new TMarocSetupHandler(fSetupName);
	TDetectorUtils *m_utils=0;

	/*MC DATA INPUT CASE*/
	TChain *cMC;

	vector < TH1D* > hSimChargeMC[6][MAX_DETECTORS];
	vector < double > chargeMC[6][MAX_DETECTORS];


	TEvent *event = 0;
	TClonesArray *digi;
	int NeventsMC;
	int Nhits,faceNumber,detNumber,pixelNumber;
	int nBckCut,nSigCut;
	double qMeanMC;


	m_setup->Print(1);

	m_detector->PrintPixels();
	m_detector->Print();

	if (fDoRoot){
		cMC=new TChain("Event"); //must have the TTree name I am going to read
		cMC->Add(fReconName.c_str());
		NeventsMC=cMC->GetEntries(); //1 entry=1 event
		cMC->SetBranchAddress("Event", &event);
	}

	m_utils=new TDetectorUtils(m_detector);




	/*Set the first gain, i.e. the Hamamatsu one. The index is the H8500ID!!!*/
	double PmtDA0359[TMarocSetupHandler::nH8500Pixels]={76,79,86,96,100,95,88,83,76,71,80,89,95,89,87,82,75,68,82,87,92,91,81,77,71,64,79,83,88,88,75,74,69,63,74,79,78,83,73,70,68,61,71,75,76,73,68,65,63,60,65,69,66,62,59,60,61,64,66,70,65,60,56,52};
	double PmtDA0361[TMarocSetupHandler::nH8500Pixels]={56,71,76,81,89,87,78,82,61,66,72,77,82,78,76,85,60,64,72,74,75,81,80,88,61,65,70,72,73,82,82,93,63,66,71,72,73,85,86,99,68,68,77,75,82,91,89,100,73,75,83,88,95,97,92,99,60,73,80,85,92,99,90,71};

	for (int ii=0;ii<TMarocSetupHandler::nH8500Pixels;ii++){
		iReconPixel=m_setup->getPixelReconId(32,ii);
		iMarocChannel=m_setup->getMarocChannelFromH8500(ii);
		iReconFace=m_setup->getReconstructionDetectorFace(32);
		iReconDet=m_setup->getReconstructionDetectorID(32);
		m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,1,PmtDA0359[ii]/100.);
		m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,3,0.718); /*This is the gain configuration PMT359 vs PMT361*/
		m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,2,.5);

		//	if (iMarocChannel<=31)			m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,2,.5);
		//	else if (iMarocChannel<=47)		m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,2,.375);
		//	else if (iMarocChannel<=63)		m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,2,.25);



		iReconPixel=m_setup->getPixelReconId(33,ii);
		iMarocChannel=m_setup->getMarocChannelFromH8500(ii);
		iReconFace=m_setup->getReconstructionDetectorFace(33);
		iReconDet=m_setup->getReconstructionDetectorID(33);
		m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,1,PmtDA0361[ii]/100.);
		m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,3,1.); /*This is the gain configuration PMT359 vs PMT361*/
		m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,2,.5);
		//	if (iMarocChannel<=31)			m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,2,.5);
		//	else if (iMarocChannel<=47)		m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,2,.375);
		//	else if (iMarocChannel<=63)		m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,2,.25);

	}


	m_setup->Print(1);




	/*Define here the histograms*/
	/*These are indexed by the real pixel id*/
	TH1D **hChargeSig=new TH1D*[Ntot];  TH1D **hChargeSigCorr=new TH1D*[Ntot];  TH1D **hChargeHitSig=new TH1D*[Ntot];
	TH1D **hChargeBck=new TH1D*[Ntot];  TH1D **hChargeBckCorr=new TH1D*[Ntot];  TH1D **hChargeHitBck=new TH1D*[Ntot];
	TH1D **hChargeDiff=new TH1D*[Ntot];

	TH2D **hChargeSigVsTot=new TH2D*[Ntot];
	TH2D **hChargeBckVsTot=new TH2D*[Ntot];




	TH2D *hGrid=new TH2D("hGrid","hGrid",16,-8.5,7.5,8,-0.5,7.5);
	TH2D *hGainMap=new TH2D("hGainMap","hGainMap",16,-8.5,7.5,8,-0.5,7.5);
	TH2D *hMeanSig=new TH2D("hMeanSig","hMeanSig",16,-8.5,7.5,8,-0.5,7.5);
	TH2D *hMeanBck=new TH2D("hMeanBck","hMeanBck",16,-8.5,7.5,8,-0.5,7.5);
	TH2D *hMeanDiff=new TH2D("hMeanDiff","hMeanDiff",16,-8.5,7.5,8,-0.5,7.5);

	TH2D *hHitSig=new TH2D("hHitSig","hHitSig",16,-8.5,7.5,8,-0.5,7.5);
	TH2D *hHitBck=new TH2D("hHitBck","hHitBck",16,-8.5,7.5,8,-0.5,7.5);
	TH2D *hHitDiff=new TH2D("hHitDiff","hHitDiff",16,-8.5,7.5,8,-0.5,7.5);


	TH1D* hChargeExp[6][MAX_DETECTORS];
	TH1D* hChargeTeo[6][MAX_DETECTORS];
	TH1D* hChargeMC[6][MAX_DETECTORS];
	TH2D* hChargeComparison[6][MAX_DETECTORS];

	TH1D* hChargeSigTot=new TH1D("hChargeSigTot","hChargeSigTot",5000,-10E3,200E3);
	TH1D* hChargeBckTot=new TH1D("hChargeBckTot","hChargeBckTot",5000,-10E3,200E3);
	TH1D* hChargeDiffTot=new TH1D("hChargeDiffTot","hChargeDiffTot",5000,-10E3,200E3);

	TH1D* hChargeSigTotR=new TH1D("hChargeSigTotR","hChargeSigTotR",5000,-10E3,200E3);
	TH1D* hChargeBckTotR=new TH1D("hChargeBckTotR","hChargeBckTotR",5000,-10E3,200E3);
	TH1D* hChargeDiffTotR=new TH1D("hChargeDiffTotR","hChargeDiffTotR",5000,-10E3,200E3);

	TH1D* hChargeSigTotL=new TH1D("hChargeSigTotL","hChargeSigTotL",5000,-10E3,200E3);
	TH1D* hChargeBckTotL=new TH1D("hChargeBckTotL","hChargeBckTotL",5000,-10E3,200E3);
	TH1D* hChargeDiffTotL=new TH1D("hChargeDiffTotL","hChargeDiffTotL",5000,-10E3,200E3);

	TH2D* hChargeSigTotLR=new TH2D("hChargeSigTotLR","hChargeSigTotLR",2000,-10E3,200E3,2000,-10E3,200E3);
	TH2D* hChargeBckTotLR=new TH2D("hChargeBckTotLR","hChargeBckTotLR",2000,-10E3,200E3,2000,-10E3,200E3);


	cout<<"Creating channel histograms"<<endl;
	for (int ii=0;ii<Ntot;ii++){
		iH8500=m_setup->getH8500IdFromGlobal(ii+N0);

		hChargeSig[ii]=new TH1D(Form("hChargeSig%i",ii),Form("hChargeSig%i:H8500_%i",ii,iH8500),4096,-0.5,4095.5);
		hChargeBck[ii]=new TH1D(Form("hChargeBck%i",ii),Form("hChargeBck%i:H8500_%i",ii,iH8500),4096,-0.5,4095.5);
		hChargeHitSig[ii]=new TH1D(Form("hChargeHitSig%i",ii),Form("hChargeHitSig%i:H8500_%i",ii,iH8500),4096,-0.5,4095.5);
		hChargeHitBck[ii]=new TH1D(Form("hChargeHitBck%i",ii),Form("hChargeHitBck%i:H8500_%i",ii,iH8500),4096,-0.5,4095.5);

		hChargeDiff[ii]=new TH1D(Form("hChargeDiff%i",ii),Form("hChargeDiff%i:H8500_%i",ii,iH8500),6000,-2000.5,3999.5);

		hChargeSigCorr[ii]=new TH1D(Form("hChargeSigCorr%i",ii),Form("hChargeSigCorr%i:H8500_%i",ii,iH8500),6096,-2000.5,4095.5);
		hChargeBckCorr[ii]=new TH1D(Form("hChargeBckCorr%i",ii),Form("hChargeBckCorr%i:H8500_%i",ii,iH8500),6096,-2000.5,4095.5);


		hChargeSigVsTot[ii]=new TH2D(Form("hChargeSigVsTot%i",ii),Form("hChargeSigVsTot%i",ii),500,-1000.5,5095.5,500,-10E3,200E3);
		hChargeBckVsTot[ii]=new TH2D(Form("hChargeBckVsTot%i",ii),Form("hChargeBckVsTot%i",ii),500,-1000.5,4095.5,500,-10E3,200E3);
	}
	cout<<"Done"<<endl;
	cout<<"Creating comparison histograms"<<endl;
	for (int ii=0;ii<6;ii++){
		for (int jj=0;jj<m_detector->getNdet(ii);jj++){
			if (m_detector->isDetPresent(ii,jj)){
				Nx=m_detector->getNPixelsX(ii,jj);
				Ny=m_detector->getNPixelsY(ii,jj);
				hChargeExp[ii][jj]=new TH1D(Form("hChargeExp%i_%i",ii,jj),Form("hChargeExp%i_%i; Pixel ID",ii,jj),Nx*Ny,-0.5,Nx*Ny-0.5);
				hChargeTeo[ii][jj]=new TH1D(Form("hChargeTeo%i_%i",ii,jj),Form("hChargeTeo%i_%i; Pixel ID",ii,jj),Nx*Ny,-0.5,Nx*Ny-0.5);
				hChargeMC[ii][jj]=new TH1D(Form("hChargeMC%i_%i",ii,jj),Form("hChargeMC%i_%i; Pixel ID",ii,jj),Nx*Ny,-0.5,Nx*Ny-0.5);
				hChargeComparison[ii][jj]=new TH2D(Form("hChargeComparison%i_%i",ii,jj),Form("hChargeComparison%i_%i",ii,jj),Nx,-0.5,Nx-0.5,Ny,-0.5,Ny-0.5);
				for (int kk=0;kk<Nx*Ny;kk++){
					hSimChargeMC[ii][jj].push_back(new TH1D(Form("hChargeMC_%i_%i_%i",ii,jj,kk),Form("hCharge_%i_%i_%i",ii,jj,kk),1000,-0.5,999.5));
					chargeMC[ii][jj].push_back(0.);
				}
			}
		}
	}
	cout<<"Done creating histograms"<<endl;

	/*Process the signal*/
	tSig->SetBranchAddress("ADC",ADC);
	tSig->SetBranchAddress("EvtMultiplicity",&EvtMultiplicity);
	tSig->SetBranchAddress("hit",hit);

	nSigCut=nBckCut=0;
	Ns=tSig->GetEntries();
	cout<<"There are "<<Ns<<" signals "<<endl;
	for (int ii=0;ii<Ns;ii++){
		tSig->GetEntry(ii);
		for (int jj=0;jj<Ntot;jj++){
			id=jj+N0;


			iRealDet=m_setup->getMarocCard(id);
			iH8500=m_setup->getH8500IdFromGlobal(id);
			iMarocChannel=m_setup->getMarocChannelFromGlobal(id);
			iReconDet=m_setup->getReconstructionDetectorID(iRealDet);
			iReconFace=m_setup->getReconstructionDetectorFace(iRealDet);
			iReconPixel=m_setup->getPixelReconId(id);
			if (iRealDet==32){
				ix=iH8500%8;
			}
			else {
				ix=-iH8500%8-1;
			}
			iy=7-iH8500/8;
			Gain=m_setup->getPixelGain(iReconFace,iReconDet,iReconPixel);
			Q=ADC[id];
			hChargeSig[jj]->Fill(Q);
			if (hit[id]){
				hHitSig->Fill(ix,iy,+1);
				hHitDiff->Fill(ix,iy,+1);
				hChargeHitSig[jj]->Fill(Q);
			}


			if (ii==0){
				MeanDiff[jj]=0;
			}
			//  hChargeDiff[jj]->Fill(Q,+1);
		}
	}

	/*Process the background*/
	tBck->SetBranchAddress("ADC",ADC);
	tBck->SetBranchAddress("EvtMultiplicity",&EvtMultiplicity);
	tBck->SetBranchAddress("hit",hit);

	Nb=tBck->GetEntries();
	cout<<"There are "<<Nb<<" backgrounds"<<endl;
	for (int ii=0;ii<Nb;ii++){
		tBck->GetEntry(ii);
		for (int jj=0;jj<Ntot;jj++){
			id=jj+N0;

			iRealDet=m_setup->getMarocCard(id);
			iH8500=m_setup->getH8500IdFromGlobal(id);
			iMarocChannel=m_setup->getMarocChannelFromGlobal(id);
			iReconDet=m_setup->getReconstructionDetectorID(iRealDet);
			iReconFace=m_setup->getReconstructionDetectorFace(iRealDet);
			iReconPixel=m_setup->getPixelReconId(id);
			Gain=m_setup->getPixelGain(iReconFace,iReconDet,iReconPixel);

			if (iRealDet==32){
				ix=iH8500%8;
			}
			else {
				ix=-iH8500%8-1;
			}
			iy=7-iH8500/8;
			Gain=m_setup->getPixelGain(iReconFace,iReconDet,iReconPixel);
			Q=ADC[id];
			hChargeBck[jj]->Fill(Q);

			if (hit[id]){
				hHitBck->Fill(ix,iy,+1);
				hHitDiff->Fill(ix,iy,-1);
				hChargeHitBck[jj]->Fill(Q);
			}

		}
	}
	/*Compute the pedestals*/
	for (int jj=0;jj<Ntot;jj++){
		min=hChargeSig[jj]->GetBinCenter(hChargeSig[jj]->GetMaximumBin());
		max=min;
		min-=15;
		max+=15;
		hChargeSig[jj]->Fit("gaus","RL","",min,max);

		min=hChargeBck[jj]->GetBinCenter(hChargeBck[jj]->GetMaximumBin());
		max=min;
		min-=15;
		max+=15;
		hChargeBck[jj]->Fit("gaus","RL","",min,max);
		PedSig[jj]=hChargeSig[jj]->GetFunction("gaus")->GetParameter(1);
		PedBck[jj]=hChargeBck[jj]->GetFunction("gaus")->GetParameter(1);
	}




	/*Process the signal, again*/
	tSig->SetBranchAddress("ADC",ADC);
	tSig->SetBranchAddress("EvtMultiplicity",&EvtMultiplicity);
	tSig->SetBranchAddress("hit",hit);
	Ns=tSig->GetEntries();

	for (int ii=0;ii<Ns;ii++){
		QSigTot=0;
		QSigTotL=0;
		QSigTotR=0;
		tSig->GetEntry(ii);
		for (int jj=0;jj<Ntot;jj++){
			id=jj+N0;

			iRealDet=m_setup->getMarocCard(id);
			iH8500=m_setup->getH8500IdFromGlobal(id);
			iMarocChannel=m_setup->getMarocChannelFromGlobal(id);
			iReconDet=m_setup->getReconstructionDetectorID(iRealDet);
			iReconFace=m_setup->getReconstructionDetectorFace(iRealDet);
			iReconPixel=m_setup->getPixelReconId(id);
			Gain=m_setup->getPixelGain(iReconFace,iReconDet,iReconPixel);
			Q=ADC[id]-PedSig[jj];
			QSigTot+=Q/Gain;
			if (jj<Ntot/2) QSigTotL+=Q/Gain;
			else QSigTotR+=Q/Gain;
		}
		hChargeSigTot->Fill(QSigTot);
		hChargeSigTotL->Fill(QSigTotL);
		hChargeSigTotR->Fill(QSigTotR);
		hChargeSigTotLR->Fill(QSigTotR,QSigTotL);

		hChargeDiffTot->Fill(QSigTot,+1);
		hChargeDiffTotR->Fill(QSigTotR,+1);
		hChargeDiffTotL->Fill(QSigTotL,+1);


		flagQcut=1;
		if (QSigTot<QTotThr) flagQcut=0;
		for (int jj=0;jj<Ntot;jj++){
			id=jj+N0;

			iRealDet=m_setup->getMarocCard(id);
			iH8500=m_setup->getH8500IdFromGlobal(id);
			iMarocChannel=m_setup->getMarocChannelFromGlobal(id);
			iReconDet=m_setup->getReconstructionDetectorID(iRealDet);
			iReconFace=m_setup->getReconstructionDetectorFace(iRealDet);
			iReconPixel=m_setup->getPixelReconId(id);
			Gain=m_setup->getPixelGain(iReconFace,iReconDet,iReconPixel);

			Q=ADC[id]-PedSig[jj];

			//hChargeSigVsTot[jj]->Fill(Q,QSigTot);


			if (flagQcut){
				hChargeDiff[jj]->Fill(Q,+1);
				hChargeSigCorr[jj]->Fill(Q);
				MeanDiff[jj]+=Q;
				if (jj==0) nSigCut++;
			}
		}
	}


	/*Process the bck, again*/
	tBck->SetBranchAddress("ADC",ADC);
	tBck->SetBranchAddress("EvtMultiplicity",&EvtMultiplicity);
	tBck->SetBranchAddress("hit",hit);

	for (int ii=0;ii<Nb;ii++){
		QBckTot=0;
		QBckTotR=0;
		QBckTotL=0;
		tBck->GetEntry(ii);
		for (int jj=0;jj<Ntot;jj++){
			id=jj+N0;

			iRealDet=m_setup->getMarocCard(id);
			iH8500=m_setup->getH8500IdFromGlobal(id);
			iMarocChannel=m_setup->getMarocChannelFromGlobal(id);
			iReconDet=m_setup->getReconstructionDetectorID(iRealDet);
			iReconFace=m_setup->getReconstructionDetectorFace(iRealDet);
			iReconPixel=m_setup->getPixelReconId(id);
			Gain=m_setup->getPixelGain(iReconFace,iReconDet,iReconPixel);
			Q=ADC[id]-PedBck[jj];
			QBckTot+=Q/Gain;


			if (jj<Ntot/2) QBckTotL+=Q/Gain;
			else QBckTotR+=Q/Gain;
		}
		hChargeBckTot->Fill(QBckTot);
		hChargeDiffTot->Fill(QBckTot,-1);

		hChargeBckTotL->Fill(QBckTotL);
		hChargeBckTotR->Fill(QBckTotR);
		hChargeBckTotLR->Fill(QBckTotR,QBckTotL);

		hChargeDiffTotR->Fill(QBckTotR,-1);
		hChargeDiffTotL->Fill(QBckTotL,-1);


		flagQcut=1;
		if (QBckTot<QTotThr) flagQcut=0;

		for (int jj=0;jj<Ntot;jj++){
			id=jj+N0;

			iRealDet=m_setup->getMarocCard(id);
			iH8500=m_setup->getH8500IdFromGlobal(id);
			iMarocChannel=m_setup->getMarocChannelFromGlobal(id);
			iReconDet=m_setup->getReconstructionDetectorID(iRealDet);
			iReconFace=m_setup->getReconstructionDetectorFace(iRealDet);
			iReconPixel=m_setup->getPixelReconId(id);
			Gain=m_setup->getPixelGain(iReconFace,iReconDet,iReconPixel);

			Q=ADC[id]-PedBck[jj];
			//hChargeBckVsTot[jj]->Fill(Q,QBckTot);

			if (flagQcut){
				hChargeBckCorr[jj]->Fill(Q);
				hChargeDiff[jj]->Fill(Q,-1);
				MeanDiff[jj]-=Q;
				if (jj==0) nBckCut++;
			}
		}
	}

	for (int jj=0;jj<Ntot;jj++){
		MeanDiff[jj]/=(nSigCut-nBckCut);
	}

	for (int iGlobal=N0;iGlobal<(Ntot+N0);iGlobal++){
		iRealDet=m_setup->getMarocCard(iGlobal);
		iH8500=m_setup->getH8500IdFromGlobal(iGlobal);
		iMarocChannel=m_setup->getMarocChannelFromGlobal(iGlobal);

		iReconDet=m_setup->getReconstructionDetectorID(iRealDet);
		iReconFace=m_setup->getReconstructionDetectorFace(iRealDet);
		iReconPixel=m_setup->getPixelReconId(iGlobal);

		if (iRealDet==32){
			ix=iH8500%8;
		}
		else {
			ix=-iH8500%8-1;
		}
		iy=7-iH8500/8;

		oldMeanSig=hChargeSig[iGlobal-N0]->GetMean();
		oldMeanBck=hChargeBck[iGlobal-N0]->GetMean();
		oldMeanDiff=hChargeDiff[iGlobal-N0]->GetMean();


		Gain=m_setup->getPixelGain(iReconFace,iReconDet,iReconPixel);

		MeanDiffCorrected=MeanDiff[iGlobal-N0]/Gain;


		hGrid->Fill(ix,iy,iGlobal-N0);
		hGainMap->Fill(ix,iy,Gain);
		hMeanSig->Fill(ix,iy,oldMeanSig);
		hMeanBck->Fill(ix,iy,oldMeanBck);
		hMeanDiff->Fill(ix,iy,MeanDiffCorrected);



		hChargeDiff[iGlobal-N0]->Fit("pol1","LQ","R",0.5E3,.9E3);
		hChargeDiff[iGlobal-N0]->GetFunction("pol1")->SetLineColor(2);

		fExp[iReconFace][iReconDet][iReconPixel]=MeanDiffCorrected;

	}



	if (fDoRoot){
		cout<<"Geant4 recon: start filling histograms"<<endl;
		cout<<"There are: "<<NeventsMC<<" MonteCarlo events"<<endl;
		for (int ii=0;ii<NeventsMC;ii++){
			cMC->GetEntry(ii);

			digi=event->getCollection(OpNoviceDigi::Class(),"DetDigiMC");

			Nhits=digi->GetEntries();
			for (int jj=0;jj<Nhits;jj++){
				faceNumber=((OpNoviceDigi*)digi->At(jj))->GetFaceNumber();
				detNumber=((OpNoviceDigi*)digi->At(jj))->GetDetectorNumber();
				pixelNumber=((OpNoviceDigi*)digi->At(jj))->GetPixelNumber();
				hSimChargeMC[faceNumber][detNumber].at(pixelNumber)->Fill(((OpNoviceDigi*)digi->At(jj))->GetPheCount());
				chargeMC[faceNumber][detNumber].at(pixelNumber)+=((OpNoviceDigi*)digi->At(jj))->GetPheCount();
			}
		}
		cout<<"Geant4 recon: mean"<<endl;
		for (int ii=0;ii<6;ii++){
			for (int jj=0;jj<m_detector->getNdet(ii);jj++){
				if (m_detector->isDetPresent(ii,jj)){
					for (int kk=0;kk<m_detector->getNPixels(ii,jj);kk++){
						qMeanMC=chargeMC[ii][jj].at(kk)/NeventsMC;
						fMC[ii][jj][kk]=qMeanMC;
					}
				}
			}
		}
	}


	vin.SetXYZ(xSource,3.,ySource);
	for (int ii=0;ii<6;ii++){
		for (int jj=0;jj<m_detector->getNdet(ii);jj++){
			if (m_detector->isDetPresent(ii,jj)){
				for (int kk=0;kk<m_detector->getNPixels(ii,jj);kk++){
					F=m_utils->SinglePixelAverageCharge(vin,ii,jj,kk);
					//Corr=CorrectionPixel(vin,ii,jj,kk,m_detector);
				//	cout<<"Setting: "<<F<<" "<<ii<<" "<<jj<<" "<<kk<<endl;
				//	cin.get();
					fTeo[ii][jj][kk]=F;
					if (!fDoRoot) {
						fMC[ii][jj][kk]=0;
						for (int qq=0;qq<1000;qq++){
							hSimChargeMC[ii][jj].at(kk)->Fill(gRandom->Poisson(F));
						}
					}
				}
			}
		}
	}



	cout<<"Comparison, fixing normalization"<<endl;
	/*Now compute normalization and fill histograms*/
	fNormTeo=fNormExp=fNormMC=0;
	for (int iface=0;iface<6;iface++){
		for (int idetector=0;idetector<m_detector->getNdet(iface);idetector++){
			if (m_detector->isDetPresent(iface,idetector)){
				for (int ipixel=0;ipixel<m_detector->getNPixels(iface,idetector);ipixel++){
					fNormTeo+=fTeo[iface][idetector][ipixel];
					fNormMC+=fMC[iface][idetector][ipixel];
					fNormExp+=fExp[iface][idetector][ipixel];
					hChargeTeo[iface][idetector]->Fill(ipixel,fTeo[iface][idetector][ipixel]);
					hChargeExp[iface][idetector]->Fill(ipixel,fExp[iface][idetector][ipixel]);
					if (fDoRoot) hChargeMC[iface][idetector]->Fill(ipixel,fMC[iface][idetector][ipixel]);
				}
			}
		}
	}


	/*Histograms have been filled. Scale them to compare*/
	for (int ii=0;ii<6;ii++){
		for (int jj=0;jj<m_detector->getNdet(ii);jj++){
			if (m_detector->isDetPresent(ii,jj)){
				hChargeExp[ii][jj]->Scale(1./fNormExp);
				hChargeTeo[ii][jj]->Scale(1./fNormTeo);
				if (fDoRoot) hChargeMC[ii][jj]->Scale(1./fNormMC);
				/*Set the error*/
				for (int ipixel=0;ipixel<m_detector->getNPixels(ii,jj);ipixel++){
					hChargeExp[ii][jj]->SetBinError(ipixel+1,3E-3); //the error is ~ 3E-3
				}

				for (int ipixel=0;ipixel<m_detector->getNPixels(ii,jj);ipixel++){
					ix=7-ipixel%8;
					iy=ipixel/8;
					hChargeComparison[ii][jj]->Fill(ix,iy,hChargeExp[ii][jj]->GetBinContent(ipixel+1)-hChargeTeo[ii][jj]->GetBinContent(ipixel+1));

				}

			}
		}
	}

	/*Plots*/
	TCanvas **c=new TCanvas*[Ntot];
	TLatex latex;

	for (int iGlobal=N0;iGlobal<(Ntot+N0);iGlobal++){
		iRealDet=m_setup->getMarocCard(iGlobal);
		iH8500=m_setup->getH8500IdFromGlobal(iGlobal);
		iMarocChannel=m_setup->getMarocChannelFromGlobal(iGlobal);

		iReconDet=m_setup->getReconstructionDetectorID(iRealDet);
		iReconFace=m_setup->getReconstructionDetectorFace(iRealDet);
		iReconPixel=m_setup->getPixelReconId(iGlobal);



		c[iGlobal-N0]=new TCanvas(Form("c%i",(iGlobal-N0)),Form("c%i:H8500_%i",(iGlobal-N0),iH8500));
		c[iGlobal-N0]->Divide(3,3);
		c[iGlobal-N0]->cd(1)->SetLogy();


		c[iGlobal-N0]->cd(1)->SetLogy();
		hChargeSig[iGlobal-N0]->GetXaxis()->SetRangeUser(1250,3000);

		hChargeSig[iGlobal-N0]->SetLineColor(1);
		hChargeSig[iGlobal-N0]->Draw();
		hChargeHitSig[iGlobal-N0]->SetLineColor(4);
		hChargeHitSig[iGlobal-N0]->Draw("SAMES");

		c[iGlobal-N0]->cd(2)->SetLogy();
		hChargeBck[iGlobal-N0]->GetXaxis()->SetRangeUser(1250,3000);
		hChargeBck[iGlobal-N0]->SetLineColor(2);
		hChargeBck[iGlobal-N0]->Draw();
		hChargeHitBck[iGlobal-N0]->SetLineColor(6);
		hChargeHitBck[iGlobal-N0]->Draw("SAMES");

		c[iGlobal-N0]->cd(3)->SetLogy();
		hChargeSig[iGlobal-N0]->GetXaxis()->SetRangeUser(1250,3000);
		hChargeSig[iGlobal-N0]->Draw();
		hChargeBck[iGlobal-N0]->Draw("SAMES");

		c[iGlobal-N0]->cd(4)->SetLogy();
		//	hChargeSigCorr[iGlobal-N0]->GetXaxis()->SetRangeUser(1250,3000);
		hChargeSigCorr[iGlobal-N0]->SetFillColor(kYellow-9);
		hChargeSigCorr[iGlobal-N0]->Draw();
		hChargeBckCorr[iGlobal-N0]->SetLineColor(2);
		hChargeBckCorr[iGlobal-N0]->SetFillColor(kRed-9);
		hChargeBckCorr[iGlobal-N0]->Draw("SAMES");

		c[iGlobal-N0]->cd(5)->SetLogy();
		hChargeDiff[iGlobal-N0]->GetXaxis()->SetRangeUser(-500,1600);
		hChargeDiff[iGlobal-N0]->Draw();
		latex.DrawLatex(1000,100,Form("m: %f",MeanDiff[iGlobal-N0]));
		c[iGlobal-N0]->cd(6);
		hSimChargeMC[iReconFace][iReconDet].at(iReconPixel)->Draw();


		//hChargeDiffCorr[iGlobal-N0]->GetXaxis()->SetRangeUser(-500,1600);
		//	hChargeDiffCorr[iGlobal-N0]->Draw();

		c[iGlobal-N0]->cd(7);
		//hChargeSigVsTot[iGlobal-N0]->Draw("colz");

		c[iGlobal-N0]->cd(8);
		//hChargeBckVsTot[iGlobal-N0]->Draw("colz");

		c[iGlobal-N0]->cd(9);





		if ((iGlobal-N0)==0) c[iGlobal-N0]->Print((fOutNamePS+"(").c_str());
		else  c[iGlobal-N0]->Print(fOutNamePS.c_str());
		fOut->cd();
		c[iGlobal-N0]->Write();
	}

	TLine *l=new TLine(-0.5,-0.5,-0.5,7.5);l->SetLineWidth(2);l->SetLineColor(2);



	TCanvas *ca=new TCanvas("ca","ca");
	ca->Divide(3,3);
	ca->cd(1);
	hGainMap->GetXaxis()->SetRangeUser(1000,2000);
	hGainMap->Draw("colz");
	hGrid->SetMarkerSize(1.8);hGrid->SetMarkerColor(0);
	hGrid->Draw("TEXTSAME");
	l->Draw("SAME");


	ca->cd(2);
	hMeanSig->SetStats(0);
	hMeanSig->Draw("colz");
	hGrid->Draw("TEXTSAME");
	l->Draw("SAME");

	ca->cd(3);
	hMeanBck->SetStats(0);
	hMeanBck->Draw("colz");
	hGrid->Draw("TEXTSAME");

	ca->cd(4);
	hMeanDiff->SetStats(0);
	hMeanDiff->Draw("colz");
	hGrid->Draw("TEXTSAME");
	l->Draw("SAME");

	ca->cd(7);
	hHitSig->SetStats(0);
	hHitSig->Draw("colz");
	hGrid->Draw("TEXTSAME");

	ca->cd(8);
	hHitBck->SetStats(0);
	hHitBck->Draw("colz");
	hGrid->Draw("TEXTSAME");


	ca->cd(9);
	hHitDiff->SetStats(0);
	hHitDiff->Draw("colz");
	hGrid->Draw("TEXTSAME");

	ca->Print(fOutNamePS.c_str());
	fOut->cd();
	ca->Write();

	TCanvas *ctot=new TCanvas("ctot","ctot");
	ctot->Divide(3,3);
	ctot->cd(1);
	hChargeSigTot->Draw();
	hChargeBckTot->SetLineColor(2);
	hChargeBckTot->Draw("SAMES");
	ctot->cd(2);
	hChargeSigTotL->Draw();
	hChargeBckTotL->SetLineColor(2);
	hChargeBckTotL->Draw("SAMES");
	ctot->cd(3);
	hChargeSigTotR->Draw();
	hChargeBckTotR->SetLineColor(2);
	hChargeBckTotR->Draw("SAMES");



	ctot->cd(4);
	hChargeDiffTot->Draw();
	ctot->cd(5);
	hChargeDiffTotL->Draw();
	ctot->cd(6);
	hChargeDiffTotR->Draw();

	ctot->cd(7);
	hChargeSigTotLR->Draw("colz");

	ctot->cd(8);
	hChargeBckTotLR->Draw("colz");



	ctot->Print(fOutNamePS.c_str());
	fOut->cd();
	ctot->Write();



	TCanvas *cRecon01=new TCanvas("cRecon01","cRecon01");
	cRecon01->Divide(2,2);
	iPad=0;
	for (int ii=0;ii<6;ii++){
		for (int jj=0;jj<m_detector->getNdet(ii);jj++){
			if (m_detector->isDetPresent(ii,jj)){
				cRecon01->cd(1+iPad)->SetGridx();
				cRecon01->cd(1+iPad)->SetGridy();

				hChargeExp[ii][jj]->SetStats(0);
				hChargeExp[ii][jj]->SetLineWidth(2);
				//hChargeExp[ii][jj]->GetYaxis()->SetRangeUser(0.,2);
				hChargeExp[ii][jj]->Draw();
				//hChargeExp[ii][jj]->GetYaxis()->SetRangeUser(0.,2);


				hChargeTeo[ii][jj]->SetStats(0);
				hChargeTeo[ii][jj]->SetLineWidth(2);
				hChargeTeo[ii][jj]->SetLineColor(2);
				hChargeTeo[ii][jj]->Draw("SAME");
				if (fDoRoot){
					hChargeMC[ii][jj]->SetStats(0);
					hChargeMC[ii][jj]->SetLineWidth(2);
					hChargeMC[ii][jj]->SetLineColor(3);
					hChargeMC[ii][jj]->Draw("SAME");
				}
				/*Also write histograms to file*/
				fOut->cd();
				hChargeExp[ii][jj]->Write();
				hChargeTeo[ii][jj]->Write();
				hChargeMC[ii][jj]->Write();
				iPad++;
			}
		}
	}

	for (int ii=0;ii<6;ii++){
		for (int jj=0;jj<m_detector->getNdet(ii);jj++){
			if (m_detector->isDetPresent(ii,jj)){
				cRecon01->cd(1+iPad)->SetGridx();
				cRecon01->cd(1+iPad)->SetGridy();

				hChargeComparison[ii][jj]->SetStats(0);
				hChargeComparison[ii][jj]->Draw("colz");

				iPad++;
			}
		}
	}

	cRecon01->Print((fOutNamePS+")").c_str());
	fOut->cd();
	cRecon01->Write();




	if (fDoBatch==0){
		gui.Run(1);
	}




	cout<<"Done"<<endl;
}
示例#9
0
void HwwDYBkgEstimate(const string inputFilename, Double_t mHiggs,
                 const string Label) 
{  
  gBenchmark->Start("WWTemplate");

  
  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  
  Double_t lumi = 35.5;              // luminosity (pb^-1)
  Int_t ChargeSelection = 0;
//   ChargeSelection = 1;
    
  Double_t fPtMaxLowerCut;
  Double_t fPtMinLowerCut;
  Double_t fDileptonMassUpperCut;
  Double_t fDeltaPhiCut;

  Double_t fHiggsMass = mHiggs;

  //Configure Higgs Mass Dependant Cuts
  if (fHiggsMass == 120) { fPtMaxLowerCut = 20.0;        fPtMinLowerCut = 20.0; 
                           fDileptonMassUpperCut = 40.0; fDeltaPhiCut = 60.0;
  }
  if (fHiggsMass == 130) { fPtMaxLowerCut = 25.0;        fPtMinLowerCut = 20.0;
                           fDileptonMassUpperCut = 45.0; fDeltaPhiCut = 60.0;
  }
  if (fHiggsMass == 140) { fPtMaxLowerCut = 25.0;        fPtMinLowerCut = 20.0;
                           fDileptonMassUpperCut = 45.0; fDeltaPhiCut = 60.0;
  }
  if (fHiggsMass == 150) { fPtMaxLowerCut = 27.0;        fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 50.0; fDeltaPhiCut = 60.0;
  }
  if (fHiggsMass == 160) { fPtMaxLowerCut = 30.0;        fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 50.0; fDeltaPhiCut = 60.0;
  }
  if (fHiggsMass == 170) { fPtMaxLowerCut = 34.0;        fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 50.0; fDeltaPhiCut = 60.0;
  }
  if (fHiggsMass == 180) { fPtMaxLowerCut = 36.0;        fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 60.0; fDeltaPhiCut = 70.0;
  }
  if (fHiggsMass == 190) { fPtMaxLowerCut = 38.0;        fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 80.0; fDeltaPhiCut = 90.0;
  }
  if (fHiggsMass == 200) { fPtMaxLowerCut = 40.0;        fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 90.0; fDeltaPhiCut = 100.0;
  }
  if (fHiggsMass == 210) { fPtMaxLowerCut = 44.0;         fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 110.0; fDeltaPhiCut = 110.0;
  }
  if (fHiggsMass == 220) { fPtMaxLowerCut = 48.0;         fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 120.0; fDeltaPhiCut = 120.0;
  }
  if (fHiggsMass == 230) { fPtMaxLowerCut = 52.0;         fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 130.0; fDeltaPhiCut = 130.0;
  }
  if (fHiggsMass == 250) { fPtMaxLowerCut = 55.0;         fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 150.0; fDeltaPhiCut = 140.0;
  }
  if (fHiggsMass == 300) { fPtMaxLowerCut = 70.0;         fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 200.0; fDeltaPhiCut = 175.0;
  }
  if (fHiggsMass == 350) { fPtMaxLowerCut = 80.0;         fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 250.0; fDeltaPhiCut = 175.0;
  }
  if (fHiggsMass == 400) { fPtMaxLowerCut = 90.0;         fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 300.0; fDeltaPhiCut = 175.0;
  }
  if (fHiggsMass == 450) { fPtMaxLowerCut = 110.0;        fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 350.0; fDeltaPhiCut = 175.0;
  }
  if (fHiggsMass == 500) { fPtMaxLowerCut = 120.0;        fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 400.0; fDeltaPhiCut = 175.0;
  }
  if (fHiggsMass == 550) { fPtMaxLowerCut = 130.0;        fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 450.0; fDeltaPhiCut = 175.0;
  }
  if (fHiggsMass == 600) { fPtMaxLowerCut = 140.0;        fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 500.0; fDeltaPhiCut = 175.0;
  }


  //--------------------------------------------------------------------------------------------------------------
  // Histograms
  //==============================================================================================================  
  TH1D *DileptonMass_allOtherCuts_ee = new TH1D("DileptonMass_allOtherCuts_ee", ";Mass_{ll};Number of Events",150,0.,300.);
  TH1D *DileptonMass_allOtherCuts_emu = new TH1D("DileptonMass_allOtherCuts_emu", ";Mass_{ll};Number of Events",150,0.,300.);
  TH1D *DileptonMass_allOtherCuts_mumu = new TH1D("DileptonMass_allOtherCuts_mumu", ";Mass_{ll};Number of Events",150,0.,300.);
  TH1D *DileptonMass_allOtherCutsExceptMetCut_ee = new TH1D("DileptonMass_allOtherCutsExceptMetCut_ee", ";Mass_{ll};Number of Events",150,0.,300.);
  TH1D *DileptonMass_allOtherCutsExceptMetCut_emu = new TH1D("DileptonMass_allOtherCutsExceptMetCut_emu", ";Mass_{ll};Number of Events",150,0.,300.);
  TH1D *DileptonMass_allOtherCutsExceptMetCut_mumu = new TH1D("DileptonMass_allOtherCutsExceptMetCut_mumu", ";Mass_{ll};Number of Events",150,0.,300.);

  Double_t NEventsIn_BeforeMetCut_ee = 0;
  Double_t NEventsIn_BeforeMetCut_em = 0;
  Double_t NEventsIn_BeforeMetCut_mm = 0;
  Double_t NEventsOut_BeforeMetCut_ee = 0;
  Double_t NEventsOut_BeforeMetCut_em = 0;
  Double_t NEventsOut_BeforeMetCut_mm = 0;
  Double_t NEventsIn_AfterMetCut_ee = 0;
  Double_t NEventsIn_AfterMetCut_em = 0;
  Double_t NEventsIn_AfterMetCut_mm = 0;
  Double_t NEventsOut_AfterMetCut_ee = 0;
  Double_t NEventsOut_AfterMetCut_em = 0;
  Double_t NEventsOut_AfterMetCut_mm = 0;


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  //
  // Access samples and fill histograms
  TFile *inputFile=0;
  TTree *eventTree=0;  
   
  // Data structures to store info from TTrees
  mithep::TEventInfo *info    = new mithep::TEventInfo();
  TClonesArray *electronArr = new TClonesArray("mithep::TElectron");
  TClonesArray *muonArr = new TClonesArray("mithep::TMuon");
  TClonesArray *jetArr = new TClonesArray("mithep::TJet");
  
  //********************************************************
  // Good RunLumi Selection
  //********************************************************
  Bool_t hasJSON = kTRUE;
  mithep::RunLumiRangeMap rlrm;
//   rlrm.AddJSONFile("Cert_TopOct22_Merged_135821-148058_allPVT.txt"); 
   rlrm.AddJSONFile("Cert_136033-149442_7TeV_Dec22ReReco_Collisions10_JSON_v3.txt"); 
   hasJSON = kFALSE;

  //********************************************************
  // Get Tree
  //********************************************************
  eventTree = getTreeFromFile(inputFilename.c_str(),"Events"); 
  TBranch *infoBr;
  TBranch *electronBr;
  TBranch *muonBr;
  TBranch *jetBr;


  //*****************************************************************************************
  //Loop over muon Data Tree
  //*****************************************************************************************
  // Set branch address to structures that will store the info  
  eventTree->SetBranchAddress("Info",       &info);      infoBr       = eventTree->GetBranch("Info");
  eventTree->SetBranchAddress("Electron", &electronArr); electronBr = eventTree->GetBranch("Electron");
  eventTree->SetBranchAddress("Muon", &muonArr);         muonBr = eventTree->GetBranch("Muon");
  eventTree->SetBranchAddress("PFJet", &jetArr);         jetBr = eventTree->GetBranch("PFJet");
  
  for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {       	
    infoBr->GetEntry(ientry);
    if (ientry % 100000 == 0) cout << "Event " << ientry << endl;
		
    mithep::RunLumiRangeMap::RunLumiPairType rl(info->runNum, info->lumiSec);      
    if(hasJSON && !rlrm.HasRunLumi(rl)) continue;  // not certified run? Skip to next event...
     
    //for the skimmed input, I already required the HLT bits.
    //    if (!passHLT(info->triggerBits, info->runNum, kTRUE)) continue;

    //********************************************************
    // Load the branches
    //********************************************************
    electronArr->Clear(); 
    muonArr->Clear(); 
    jetArr->Clear(); 
    electronBr->GetEntry(ientry);
    muonBr->GetEntry(ientry);
    jetBr->GetEntry(ientry);

    //event weight
    Double_t eventweight = info->eventweight * lumi;

    //********************************************************
    // TcMet
    //********************************************************
    TVector3 met;        
    if(info->tcMEx!=0 || info->tcMEy!=0) {       
      met.SetXYZ(info->tcMEx, info->tcMEy, 0);
    }

    //********************************************************
    // TcMet
    //********************************************************

    Int_t NSoftMuons = 0;
    Int_t NLeptons = 0;
    vector<Int_t> leptonType;
    vector<Int_t> leptonIndex;
    vector<Double_t> leptonPt;
    vector<Double_t> leptonEta;
    vector<Double_t> leptonPhi;
    vector<Int_t> leptonCharge;

    Int_t NJets = 0;
    const mithep::TJet *leadingJet = 0;
    
    for(Int_t i=0; i<muonArr->GetEntries(); i++) {
      const mithep::TMuon *mu = (mithep::TMuon*)((*muonArr)[i]);      
      if ( (0==0)
           &&
           passMuonCuts(mu)
           &&
           fabs(mu->eta) < 2.4
           && 
           mu->pt > 10.0
        ) {
        leptonPt.push_back(mu->pt);
        leptonEta.push_back(mu->eta);
        leptonPhi.push_back(mu->phi);
        leptonType.push_back(13);
        leptonIndex.push_back(i);  
        leptonCharge.push_back(mu->q);
      }
    }
    //soft muons
    for(Int_t i=0; i<muonArr->GetEntries(); i++) {
      const mithep::TMuon *mu = (mithep::TMuon*)((*muonArr)[i]);
      Bool_t isCleanMuon = kFALSE;
      for (int k=0; k<leptonPt.size(); ++k) {
        if ( leptonType[k] == 13 
             && mithep::MathUtils::DeltaR(mu->phi, mu->eta, leptonPhi[k],leptonEta[k]) < 0.1
          ) {
          isCleanMuon = kTRUE; 
          break;
        }
      }
      if ( mu->pt > 3.0
           && (mu->qualityBits & kTMLastStationAngTight)
           && mu->nTkHits > 10
           && fabs(mu->d0) < 0.2
           && (mu->typeBits & kTracker)
           && !isCleanMuon
        ) {
        NSoftMuons++;
      }
    }
    for(Int_t i=0; i<electronArr->GetEntries(); i++) {
      const mithep::TElectron *ele = (mithep::TElectron*)((*electronArr)[i]);
      Bool_t isMuonOverlap = kFALSE;
      for (int k=0; k<leptonPt.size(); ++k) {
        if ( leptonType[k] == 13 
             && mithep::MathUtils::DeltaR(ele->phi, ele->eta, leptonPhi[k],leptonEta[k]) < 0.1
          ) {
          isMuonOverlap = kTRUE; 
          break;
        }        
      }

      if ( (0==0)
           && 
           passElectronCuts(ele)
           &&
           fabs(ele->eta) < 2.5
           && 
           ele->pt > 10.0
           &&
           !isMuonOverlap
        ) {
        leptonPt.push_back(ele->pt);
        leptonEta.push_back(ele->eta);
        leptonPhi.push_back(ele->phi);
        leptonType.push_back(11);
        leptonIndex.push_back(i);
        leptonCharge.push_back(ele->q);
      }
    }


    //sort leptons
    Int_t tempType;
    Int_t tempIndex;
    Double_t tempPt;
    Double_t tempEta;
    Double_t tempPhi;
    Int_t tempCharge;
    for (int l=0; l<leptonIndex.size(); l++) {
      for (int k=0; k < leptonIndex.size() - 1; k++) {
        if (leptonPt[k+1] > leptonPt[k]) {
          tempType = leptonType[k];
          tempIndex = leptonIndex[k];
          tempPt = leptonPt[k];
          tempEta = leptonEta[k];
          tempPhi = leptonPhi[k];
          tempCharge = leptonCharge[k];
          
          leptonType[k] = leptonType[k+1];
          leptonIndex[k] = leptonIndex[k+1];
          leptonPt[k] = leptonPt[k+1];
          leptonEta[k] = leptonEta[k+1];
          leptonPhi[k] = leptonPhi[k+1];
          leptonCharge[k] = leptonCharge[k+1];

          leptonType[k+1] = tempType;
          leptonIndex[k+1] = tempIndex;
          leptonPt[k+1] = tempPt;
          leptonEta[k+1] = tempEta;
          leptonPhi[k+1] = tempPhi;
          leptonCharge[k+1] = tempCharge;
          
        }
      }
    }

    double maxBtag = -99999;
    for(Int_t i=0; i<jetArr->GetEntries(); i++) {
      const mithep::TJet *jet = (mithep::TJet*)((*jetArr)[i]);

      Bool_t leptonOverlap = kFALSE;
      for (int k=0; k<leptonPt.size(); ++k) {
        if (mithep::MathUtils::DeltaR(jet->phi, jet->eta, leptonPhi[k],leptonEta[k]) < 0.3) {
          leptonOverlap = kTRUE;
        }
      }

      if (!leptonOverlap) {
        if (jet->pt > 25 && fabs(jet->eta) < 5.0 ) {
          if (!leadingJet || jet->pt > leadingJet->pt) {
            leadingJet = jet;
          }
          NJets++;
        } else {
          if (jet->TrackCountingHighEffBJetTagsDisc > maxBtag ) maxBtag = jet->TrackCountingHighEffBJetTagsDisc;
        }
      }
    }


    //******************************************************************************
    //dilepton preselection
    //******************************************************************************
    if (leptonPt.size() < 2) continue;
    if (!(leptonPt[0] > 20.0 && leptonPt[1] > 10.0)) continue;

    for(int i = 0; i < leptonPt.size(); ++i) {
      for(int j = i+1; j < leptonPt.size(); ++j) {

        //require opposite sign
        if ((ChargeSelection == 0 && leptonCharge[i] == leptonCharge[j]) || (ChargeSelection == 1 && leptonCharge[0] != leptonCharge[j])) continue;


        Int_t finalState = -1;
        if (leptonType[i] == 11 && leptonType[j] == 11) {
          finalState = 0;
        } else if (leptonType[i] == 13 && leptonType[j] == 13) {
          finalState = 1;
        } else if (leptonType[i] == 11 && leptonType[j] == 13) {
          finalState = 2;
        } else if (leptonType[i] == 13 && leptonType[j] == 11) {
          finalState = 3;
        }


        //***********************************************************************************************
        //|Z_vert-Z_l| maximum
        //***********************************************************************************************
        double zDiffMax = 0.0;
       
        double dz_i = 0;
        if (leptonType[0] == 11) {
          dz_i = ((mithep::TElectron*)((*electronArr)[leptonIndex[i]]))->dz;
        } else {
          dz_i = ((mithep::TMuon*)((*muonArr)[leptonIndex[i]]))->dz;
        }
        if (dz_i > zDiffMax) zDiffMax = dz_i;
    
        double dz_j;
        if (leptonType[j] == 11) {
          dz_j = ((mithep::TElectron*)((*electronArr)[leptonIndex[j]]))->dz;
        } else {
          dz_j = ((mithep::TMuon*)((*muonArr)[leptonIndex[j]]))->dz;
        }
        if (dz_j > zDiffMax) zDiffMax = dz_j;
        //szDiffMax = fabs(dz_i - dz_j);

        //******************************************************************************
        //construct event variables
        //******************************************************************************
        mithep::FourVectorM lepton1;
        mithep::FourVectorM lepton2;
        if (leptonType[i] == 11) {
          lepton1.SetCoordinates(leptonPt[i], leptonEta[i], leptonPhi[i], 0.51099892e-3 );
        } else {
          lepton1.SetCoordinates(leptonPt[i], leptonEta[i], leptonPhi[i], 105.658369e-3 );
        }
        if (leptonType[j] == 11) {
          lepton2.SetCoordinates(leptonPt[j], leptonEta[j], leptonPhi[j], 0.51099892e-3 );
        } else {
          lepton2.SetCoordinates(leptonPt[j], leptonEta[j], leptonPhi[j], 105.658369e-3 );
        }
        mithep::FourVectorM dilepton = lepton1+lepton2;

        double deltaPhiLeptons = mithep::MathUtils::DeltaPhi(lepton1.Phi(), 
                                                             lepton2.Phi())* 180.0 / TMath::Pi();    
        double deltaPhiDileptonMet = mithep::MathUtils::DeltaPhi(met.Phi(), 
                                                                 dilepton.Phi())*180.0 / TMath::Pi();    
        double mtHiggs = TMath::Sqrt(2.0*dilepton.Pt() * met.Phi()*
                                     (1.0 - cos(deltaPhiDileptonMet * TMath::Pi() / 180.0)));

        //angle between MET and closest lepton
        double deltaPhiMetLepton[2] = {mithep::MathUtils::DeltaPhi(met.Phi(), lepton1.Phi()),
                                       mithep::MathUtils::DeltaPhi(met.Phi(), lepton2.Phi())};
  
        double mTW[2] = {TMath::Sqrt(2.0*lepton1.Pt()*met.Pt()*
                                     (1.0 - cos(deltaPhiMetLepton[0]))),
                         TMath::Sqrt(2.0*lepton2.Pt()*met.Pt()*
                                     (1.0 - cos(deltaPhiMetLepton[1])))};

        double minDeltaPhiMetLepton = (deltaPhiMetLepton[0] < deltaPhiMetLepton[1])?
          deltaPhiMetLepton[0]:deltaPhiMetLepton[1];

        double METdeltaPhilEt = met.Pt();
        if(minDeltaPhiMetLepton < TMath::Pi()/2.)
          METdeltaPhilEt = METdeltaPhilEt * sin(minDeltaPhiMetLepton);

    
        //*********************************************************************************************
        //Define Cuts
        //*********************************************************************************************
        const int nCuts = 14;
        bool passCut[nCuts] = {false, false, false, false, false, false, false, false, false, false,
                               false, false, false, false};
  
        if(lepton1.Pt() >  20.0 &&
           lepton2.Pt() >= 10.0) passCut[0] = true;

        if(zDiffMax < 1.0)                    passCut[1] = true;
  
        if(met.Pt()    > 20.0)               passCut[2] = true;
  
        if(dilepton.M() > 12.0)            passCut[3] = true;
   
        if (finalState == 0 || finalState == 1){ // mumu/ee
          if(fabs(dilepton.M()-91.1876)   > 15.0)   passCut[4] = true;
          if(METdeltaPhilEt > 35) passCut[5] = true;
        }
        else if(finalState == 2 ||finalState == 3 ) { // emu
          passCut[4] = true;
          if(METdeltaPhilEt > 35) passCut[5] = true;
        }

        if(NJets     < 1)              passCut[6] = true;
        
        if (NSoftMuons == 0 )      passCut[7] = true;

        if (!(leptonPt.size() >= 3 && leptonPt[2] > 10.0)) passCut[8] = true;

        if(maxBtag < 2.1)                     passCut[9] = true;

        if (lepton1.Pt() > fPtMaxLowerCut) passCut[10] = true;
        if (lepton2.Pt() > fPtMinLowerCut) passCut[11] = true;
        if (dilepton.M() < fDileptonMassUpperCut)   passCut[12] = true;
        if (deltaPhiLeptons < fDeltaPhiCut) passCut[13] = true;

        //*********************************************************************************************
        //Make Selection Histograms. Number of events passing each level of cut
        //*********************************************************************************************  
        bool passAllCuts = true;
        for(int c=0; c<nCuts; c++) passAllCuts = passAllCuts & passCut[c];
    
  
        //*****************************************************************************************
        //Make Histograms Before Met Cut
        //*****************************************************************************************
        if (passCut[0] && passCut[1] && passCut[3] && passCut[6] &&passCut[7] && passCut[8] && passCut[9] 
//             && passCut[10] && passCut[11] && passCut[13] 
          ) {

          if (finalState == 0) {
            DileptonMass_allOtherCutsExceptMetCut_ee->Fill(dilepton.M());
            if(fabs(dilepton.M()-91.1876)   > 15.0) {
              NEventsOut_BeforeMetCut_ee++;
            } else {
              NEventsIn_BeforeMetCut_ee++;
            }

          } else if (finalState == 1) {
            DileptonMass_allOtherCutsExceptMetCut_mumu->Fill(dilepton.M());
            if(fabs(dilepton.M()-91.1876)   > 15.0) {
              NEventsOut_BeforeMetCut_mm++;
            } else {
              NEventsIn_BeforeMetCut_mm++;
            }

          } else {
            DileptonMass_allOtherCutsExceptMetCut_emu->Fill(dilepton.M());
            if(fabs(dilepton.M()-91.1876)   > 15.0) {
              NEventsOut_BeforeMetCut_em++;
            } else {
              NEventsIn_BeforeMetCut_em++;
            }
          }        
        }

        //*****************************************************************************************
        //Make Histograms  
        //*****************************************************************************************
        if (passCut[0] && passCut[1] && passCut[2] && passCut[3] && passCut[5] &&passCut[6] &&passCut[7] && passCut[8] && passCut[9] 
//             && passCut[10] && passCut[11] && passCut[13] 
          ) {

          if (finalState == 0) {
            DileptonMass_allOtherCuts_ee->Fill(dilepton.M());
            if(fabs(dilepton.M()-91.1876)   > 15.0) {
              NEventsOut_AfterMetCut_ee++;
            } else {
              NEventsIn_AfterMetCut_ee++;
              cout << info->runNum << " " << info->lumiSec << " " << info->evtNum << " : " << dilepton.M() << " " 
                   << finalState << " : " << lepton1.Pt() << " " << lepton1.Eta() << " " << lepton1.Phi() << " : " 
                   << " : " << lepton2.Pt() << " " << lepton2.Eta() << " " << lepton2.Phi() << " \n" ;
            }
          } else if (finalState == 1) {
            DileptonMass_allOtherCuts_mumu->Fill(dilepton.M());
            if(fabs(dilepton.M()-91.1876)   > 15.0) {
              NEventsOut_AfterMetCut_mm++;
            } else {
              NEventsIn_AfterMetCut_mm++;
              cout << info->runNum << " " << info->lumiSec << " " << info->evtNum << " : " << dilepton.M() << " " 
                   << finalState << " : " << lepton1.Pt() << " " << lepton1.Eta() << " " << lepton1.Phi() << " : " 
                   << " : " << lepton2.Pt() << " " << lepton2.Eta() << " " << lepton2.Phi() << " \n" ;
            }
          } else {
            DileptonMass_allOtherCuts_emu->Fill(dilepton.M());
            if(fabs(dilepton.M()-91.1876)   > 15.0) {
              NEventsOut_AfterMetCut_em++;
            } else {
              NEventsIn_AfterMetCut_em++;
              cout << info->runNum << " " << info->lumiSec << " " << info->evtNum << " : " << dilepton.M() << " " 
                   << finalState << " : " << lepton1.Pt() << " " << lepton1.Eta() << " " << lepton1.Phi() << " : " 
                   << " : " << lepton2.Pt() << " " << lepton2.Eta() << " " << lepton2.Phi() << " \n" ;
            }
          }        
        }



      }
    }
  

  } //end loop over data     



  delete info;
  delete electronArr;
  delete muonArr;
  delete jetArr;


  //--------------------------------------------------------------------------------------------------------------
  // Make plots
  //==============================================================================================================
  TCanvas *cv = new TCanvas("cv","cv", 800,600);

  //--------------------------------------------------------------------------------------------------------------
  // Summary print out
  //============================================================================================================== 



  cout << "Before Met Cut\n";
  cout << "Number of Events in Z window : (ee) " << NEventsIn_BeforeMetCut_ee << " (mm) " << NEventsIn_BeforeMetCut_mm << endl;
  cout << "Number of Events out of Z window : (ee) " << NEventsOut_BeforeMetCut_ee << " (mm) " << NEventsOut_BeforeMetCut_mm << endl;
  cout << "Ratio Out/In : (ee) " << NEventsOut_BeforeMetCut_ee / NEventsIn_BeforeMetCut_ee << " (mm) "
       << NEventsOut_BeforeMetCut_mm / NEventsIn_BeforeMetCut_mm << endl; 


  cout << "After Met Cut\n";
  cout << "Number of Events in Z window : (ee) " << NEventsIn_AfterMetCut_ee << " (mm) " 
       << NEventsIn_AfterMetCut_mm << " (em) " << NEventsIn_AfterMetCut_em << endl;
  cout << "Number of Events out of Z window : (ee) " << NEventsOut_AfterMetCut_ee << " (mm) " 
       << NEventsOut_AfterMetCut_mm << " (em) " << NEventsOut_AfterMetCut_em << endl;








  //--------------------------------------------------------------------------------------------------------------
  // Save Histograms;
  //============================================================================================================== 
  TFile *file = new TFile("HwwSelectionPlots.root", "RECREATE");
  
  
  file->WriteTObject(DileptonMass_allOtherCuts_ee ,DileptonMass_allOtherCuts_ee->GetName(), "WriteDelete");
  file->WriteTObject(DileptonMass_allOtherCuts_mumu ,DileptonMass_allOtherCuts_mumu->GetName(), "WriteDelete");
  file->WriteTObject(DileptonMass_allOtherCuts_emu ,DileptonMass_allOtherCuts_emu->GetName(), "WriteDelete");

  file->WriteTObject(DileptonMass_allOtherCutsExceptMetCut_ee ,DileptonMass_allOtherCutsExceptMetCut_ee->GetName(), "WriteDelete");
  file->WriteTObject(DileptonMass_allOtherCutsExceptMetCut_mumu ,DileptonMass_allOtherCutsExceptMetCut_mumu->GetName(), "WriteDelete");
  file->WriteTObject(DileptonMass_allOtherCutsExceptMetCut_emu ,DileptonMass_allOtherCutsExceptMetCut_emu->GetName(), "WriteDelete");
  file->Close();
  delete file;

        
  gBenchmark->Show("WWTemplate");       
} 
示例#10
0
int main(int argc, char* argv[])
{
  TApplication theApp(srcName.Data(), &argc, argv);
//=============================================================================

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

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

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

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

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

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

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

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

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

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

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

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

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

  TList *list = new TList();
  TH1D *hWeightSum = new TH1D("hWeightSum", "", 1, 0., 1.); list->Add(hWeightSum);

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

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

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

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

  while (evt) {
    fjInput.resize(0);
    double dXsect  = evt->cross_section()->cross_section() / 1e9;
    double dWeight = evt->weights().back();
    double dNorm = dWeight * dXsect;
    hWeightSum->Fill(0.5, dWeight);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  cout << "DONE" << endl;
  return 0;
}
void MakeNtuple(const string inputFilename, const string outputFilename, Int_t Option)
{  
  gBenchmark->Start("WWTemplate");

  //*****************************************************************************************
  //Setup
  //*****************************************************************************************
  TFile *outputFile = new TFile(outputFilename.c_str(), "RECREATE");
  ElectronTree *eleTree = new ElectronTree;
  eleTree->CreateTree();
  eleTree->tree_->SetAutoFlush(0);

  UInt_t NElectronsFilled = 0;
  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  //
  // Access samples and fill histograms
  TTree *eventTree=0;  
   
  // Data structures to store info from TTrees
  higgsana::TEventInfo *info    = new higgsana::TEventInfo();
  TClonesArray *electronArr = new TClonesArray("higgsana::TElectron");
  TClonesArray *muonArr = new TClonesArray("higgsana::TMuon");
  TClonesArray *jetArr = new TClonesArray("higgsana::TJet");
  TClonesArray *photonArr = new TClonesArray("higgsana::TPhoton");
  TClonesArray *pfcandidateArr = new TClonesArray("higgsana::TPFCandidate");
  
  //********************************************************
  // Good RunLumi Selection
  //********************************************************
  Bool_t hasJSON = kTRUE;
  mithep::RunLumiRangeMap rlrm;
  rlrm.AddJSONFile("/data/smurf/data/Winter11_4700ipb/auxiliar/hww.Full2011.json"); 
  rlrm.AddJSONFile("/data/blue/sixie/HZZ4l/auxiliar/2012/Cert_190456-196531_8TeV_PromptReco_Collisions12_JSON.txt");

  Int_t NEvents = 0;

  UInt_t DataEra = kDataEra_NONE;

  vector<string> inputfiles;
  if (inputFilename == "LIST") {
    inputfiles.push_back("/home/sixie/hist/HZZ4lNtuples/data/AllNtuple_HZZ4lNtuple_r11a-del-m10-v1.FakeTriggerSkim.root");
    inputfiles.push_back("/home/sixie/hist/HZZ4lNtuples/data/AllNtuple_HZZ4lNtuple_r11a-del-pr-v4.FakeTriggerSkim.root");
    inputfiles.push_back("/home/sixie/hist/HZZ4lNtuples/data/AllNtuple_HZZ4lNtuple_r11a-del-a05-v1.FakeTriggerSkim.root");
    inputfiles.push_back("/home/sixie/hist/HZZ4lNtuples/data/AllNtuple_HZZ4lNtuple_r11a-del-o03-v1.FakeTriggerSkim.root");
    inputfiles.push_back("/home/sixie/hist/HZZ4lNtuples/data/AllNtuple_HZZ4lNtuple_r11b-del-pr-v1.FakeTriggerSkim.root");    
  } 
  else if (inputFilename == "2012Data") {
    inputfiles.push_back("/data/smurf/sixie/hist/HZZ4lNtuples/data/AllNtuple_HZZ4lNtuple_r12a-del-pr-v1_FakeRateTriggerSkimmed.root");
    inputfiles.push_back("/data/smurf/sixie/hist/HZZ4lNtuples/data/AllNtuple_HZZ4lNtuple_r12b-del-pr-v1_FakeRateTriggerSkimmed.root");
    DataEra = kDataEra_2012_MC;
  }
  else {
    inputfiles.push_back(inputFilename);
  }

  for (UInt_t f = 0; f < inputfiles.size(); ++f) {

    //********************************************************
    // Get Tree
    //********************************************************
    eventTree = getTreeFromFile(inputfiles[f].c_str(),"Events"); 
    TBranch *infoBr;
    TBranch *electronBr;
    TBranch *muonBr;
    TBranch *jetBr;
    TBranch *photonBr;
    TBranch *pfcandidateBr;


    //*****************************************************************************************
    //Loop over Data Tree
    //*****************************************************************************************
    // Set branch address to structures that will store the info  
    eventTree->SetBranchAddress("Info",       &info);      infoBr       = eventTree->GetBranch("Info");
    eventTree->SetBranchAddress("Electron", &electronArr); electronBr = eventTree->GetBranch("Electron");
    eventTree->SetBranchAddress("Muon", &muonArr);         muonBr = eventTree->GetBranch("Muon");
    eventTree->SetBranchAddress("Photon", &photonArr);     photonBr = eventTree->GetBranch("Photon");
    eventTree->SetBranchAddress("PFJet", &jetArr);         jetBr = eventTree->GetBranch("PFJet");
    eventTree->SetBranchAddress("PFCandidate", &pfcandidateArr); pfcandidateBr = eventTree->GetBranch("PFCandidate");

    cout << "InputFile " << inputfiles[f] << " --- Total Events : " << eventTree->GetEntries() << endl;
    for(UInt_t ientry=0; ientry < eventTree->GetEntries(); ientry++) {       	
      infoBr->GetEntry(ientry);
		
      if (ientry % 100000 == 0) cout << "Event " << ientry << endl;

      Double_t eventweight = info->eventweight;

      mithep::RunLumiRangeMap::RunLumiPairType rl(info->runNum, info->lumiSec);      
      if(hasJSON && !rlrm.HasRunLumi(rl)) continue;  // not certified run? Skip to next event...

      NEvents++;

      //********************************************************
      // Load the branches
      //********************************************************
      electronArr->Clear(); 
      muonArr->Clear(); 
      photonArr->Clear(); 
      jetArr->Clear(); 
      pfcandidateArr->Clear(); 
      electronBr->GetEntry(ientry);
      muonBr->GetEntry(ientry);
      photonBr->GetEntry(ientry);
      jetBr->GetEntry(ientry);
      pfcandidateBr->GetEntry(ientry);


      //********************************************************
      // Pileup Energy Density
      //********************************************************
      Double_t rhoEleIso = 0;
      UInt_t EleEAEra = 0;

      if (DataEra == kDataEra_2011_MC) {     
        if (!(isnan(info->RhoKt6PFJetsForIso25) || 
              isinf(info->RhoKt6PFJetsForIso25))) {
          rhoEleIso = info->RhoKt6PFJetsForIso25;
        }
        EleEAEra = kDataEra_2011_Data;
      } else if (DataEra == kDataEra_2012_MC) {
        if (!(isnan(info->RhoKt6PFJets) || 
              isinf(info->RhoKt6PFJets))) {
          rhoEleIso = info->RhoKt6PFJets;
        }
        EleEAEra = kDataEra_2012_Data;
      }

      //********************************************************
      // TcMet
      //********************************************************
      TVector3 pfMet;        
      if(info->pfMEx!=0 || info->pfMEy!=0) {       
        pfMet.SetXYZ(info->pfMEx, info->pfMEy, 0);
      }
      Double_t met = pfMet.Pt();

      Int_t NElectrons = electronArr->GetEntries();
 

      //********************************************************
      // Event Selection Cuts
      //********************************************************
      //veto events with more than 1 reco electron
      if (NElectrons > 1) continue;
      //met cut removed W events
      if (met > 20) continue;


      //******************************************************************************
      //loop over electrons 
      //******************************************************************************
      for(Int_t i=0; i<electronArr->GetEntries(); i++) {
        const higgsana::TElectron *ele = (higgsana::TElectron*)((*electronArr)[i]);
 

        //make cut on dz
        if (fabs(ele->dz) > 0.1) continue;

        //protect against pathologies
        if (TMath::IsNaN(ele->sigiPhiiPhi)) {
          cout << "Pathological SigmaIPhiIPhi : " 
               << info->runNum << " " << info->lumiSec << " " << info->evtNum << endl;
          continue;
        }
        
        //********************************************************
        //find leading jet in the event
        //********************************************************
        Double_t leadingJetPt = -1;
        //pass event selection     
        for(Int_t j=0; j<jetArr->GetEntries(); j++) {
          const higgsana::TJet *jet = (higgsana::TJet*)((*jetArr)[j]);        
          if (jet->pt > leadingJetPt &&
              higgsana::deltaR(jet->eta, jet->phi, ele->eta, ele->phi) > 1.0) {
            leadingJetPt = jet->pt;          
          }
        }
      
        //Fill These Electrons
        NElectronsFilled++;
        
        if (Option == 0) {
          FillElectronTree( eleTree, ele, pfcandidateArr, rhoEleIso, EleEAEra, 
                            info->nPV0, info->runNum, info->lumiSec, info->evtNum);
        } else if (Option == 1) {
          FillElectronTree( eleTree, ele, pfcandidateArr, rhoEleIso, kDataEra_NONE, 
                            info->nPV0, info->runNum, info->lumiSec, info->evtNum);
        }

      } //loop over electrons

    } //end loop over data  

    cout << "Total Electrons: " << NElectronsFilled << endl;

  } //end loop over files

  delete info;
  delete electronArr;
  delete muonArr;
  delete jetArr;


  cout << "Total Electrons: " << NElectronsFilled << endl;
  outputFile->Write();
  outputFile->Close();

  gBenchmark->Show("WWTemplate");       
} 
示例#12
0
KVFAZIABlock::KVFAZIABlock() : TGeoVolumeAssembly("STRUCT_BLOCK")
{
   // Default constructor

   SetMedium(gGeoManager->GetMedium("Vacuum"));//to avoid warnings about STRUCT_BLOCK has dummy medium

   KVMaterial mat_si("Si");
   TGeoMedium *Silicon = mat_si.GetGeoMedium();

   KVMaterial mat_csi("CsI");
   TGeoMedium *CesiumIodide = mat_csi.GetGeoMedium();

   KVMaterial mat_plomb("Lead");
   TGeoMedium *Plomb = mat_plomb.GetGeoMedium();

   TGeoVolumeAssembly* quartet = gGeoManager->MakeVolumeAssembly("STRUCT_QUARTET");
   quartet->SetMedium(gGeoManager->GetMedium("Vacuum"));//to avoid warnings about STRUCT_QUARTET has dummy medium

   TGeoVolume* si = 0;
   TGeoVolume* csi = 0;

   Double_t distance_si2_si1 = 0.220;
   Double_t distance_csi_si2 = 0.434;

   Double_t side_si = 2;
   Double_t side_csi_front = 2.050;
   Double_t side_csi_back = 2.272;

   Double_t inter_si = 0.24;

   Double_t thick_si1 = 300 * KVUnits::um;
   Double_t thick_si2 = 500 * KVUnits::um;
   Double_t thick_csi = 10;

   Double_t adjust_csi = 0.0165;

   Int_t ndet = 1;;
   TGeoTranslation* tr = 0;

   Double_t shift = side_si / 2 + inter_si / 2;
   //printf("%lf\n", shift);

   Double_t coefx[4] = { -1., -1., 1., 1.};
   Double_t coefy[4] = {1., -1., -1., 1.};

   for (Int_t nt = 1; nt <= 4; nt += 1) {

      shift = side_si / 2 + inter_si / 2;

      si = gGeoManager->MakeBox(Form("DET_SI1-T%d", nt), Silicon, side_si / 2, side_si / 2, thick_si1 / 2.);
      tr = new TGeoTranslation(coefx[nt - 1]*shift, coefy[nt - 1]*shift, thick_si1 / 2.);

      quartet->AddNode(si, ndet++, tr);
      ((TGeoNodeMatrix*)quartet->GetNodes()->Last())->SetName(Form("DET_SI1-T%d", nt));

      si = gGeoManager->MakeBox(Form("DET_SI2-T%d", nt), Silicon, side_si / 2, side_si / 2, thick_si2 / 2.);
      tr = new TGeoTranslation(coefx[nt - 1]*shift, coefy[nt - 1]*shift, thick_si2 / 2. + distance_si2_si1);
      quartet->AddNode(si, ndet++, tr);
      ((TGeoNodeMatrix*)quartet->GetNodes()->Last())->SetName(Form("DET_SI2-T%d", nt));

      shift = side_si / 2 + inter_si / 2 + adjust_csi;

      csi = gGeoManager->MakeTrd2(Form("DET_CSI-T%d", nt), CesiumIodide, side_csi_front / 2, side_csi_back / 2, side_csi_front / 2, side_csi_back / 2, thick_csi / 2.);
      tr = new TGeoTranslation(coefx[nt - 1]*shift, coefy[nt - 1]*shift, thick_csi / 2. + distance_csi_si2);
      quartet->AddNode(csi, ndet++, tr);
      ((TGeoNodeMatrix*)quartet->GetNodes()->Last())->SetName(Form("DET_CSI-T%d", nt));

   }

   Int_t nbl = 1;
   TGeoVolume* blindage = 0;
//Double_t thick_bld = thick_si1+distance_si2_si1+thick_si2;
   /* l'epaisseur du si1 est compris dans la distance_si2_si1 */
   Double_t thick_bld = distance_si2_si1 + thick_si2;
   Double_t shift_bld = (side_si + inter_si) / 2.;
///Croix inter quartet
//
// Separation des 4 télescopes
//
//
   blindage = gGeoManager->MakeBox("DEADZONE_BLINDAGE_1", Plomb, inter_si / 2, (side_si + inter_si / 2), thick_bld / 2.);
   //printf("%s\n", blindage->GetMaterial()->GetTitle());
   tr = new TGeoTranslation(0, 0, thick_bld / 2.);
   quartet->AddNode(blindage, nbl++, tr);

   blindage = gGeoManager->MakeBox("DEADZONE_BLINDAGE_2", Plomb, (side_si / 2), inter_si / 2, thick_bld / 2.);
   tr = new TGeoTranslation(-1 * shift_bld, 0, thick_bld / 2.);
   quartet->AddNode(blindage, nbl++, tr);
   tr = new TGeoTranslation(+1 * shift_bld, 0, thick_bld / 2.);
   quartet->AddNode(blindage, nbl++, tr);

///Contour de l ensemble du quartet
//
//Délimiation des bords exterieurs
//
//
   shift_bld = (side_si + inter_si);

   blindage = gGeoManager->MakeBox("DEADZONE_BLINDAGE_3", Plomb, (side_si + inter_si / 2), inter_si / 2, thick_bld / 2.);
   tr = new TGeoTranslation(0, shift_bld, thick_bld / 2.);
   quartet->AddNode(blindage, nbl++, tr);
   tr = new TGeoTranslation(0, -1 * shift_bld, thick_bld / 2.);
   quartet->AddNode(blindage, nbl++, tr);
///
   blindage = gGeoManager->MakeBox("DEADZONE_BLINDAGE_4", Plomb, inter_si / 2, (side_si + inter_si * 1.5), thick_bld / 2.);
   tr = new TGeoTranslation(shift_bld, 0, thick_bld / 2.);
   quartet->AddNode(blindage, nbl++, tr);
   tr = new TGeoTranslation(-1 * shift_bld, 0, thick_bld / 2.);
   quartet->AddNode(blindage, nbl++, tr);

   fTotSidWBlind = 4 * side_si + 5 * inter_si;
//Coordonnées extraite des côtes données par Yvan M.
//vecteur pointant le milieu d un quartet
//X=-2.231625
//Y=-2.230525
//Z=99.950350
// Mag=100.000139
// Theta=1.808104
// Phi = -135.014124
   TVector3* placement = new TVector3(-2.231625, -2.230525, 99.950350);
   TVector3* Centre = new TVector3();

   TGeoRotation rot1, rot2;
   TGeoTranslation trans;
   TGeoTranslation invZtrans(0, 0, -100);

   TGeoHMatrix h;
   TGeoHMatrix* ph = 0;

//Boucle sur les 4 quartets d un block
   Double_t tx[4] = {1, -1, -1, 1};
   Double_t ty[4] = {1, 1, -1, -1};

   Double_t theta = 0;
   Double_t phi = 0;
   Double_t trans_z = 0;

   for (Int_t nq = 1; nq <= 4; nq += 1) {

      Centre->SetXYZ(placement->X()*tx[nq - 1], placement->Y()*ty[nq - 1], placement->Z());

      theta = Centre->Theta() * TMath::RadToDeg();
      phi = Centre->Phi() * TMath::RadToDeg();

      trans_z = Centre->Mag() + thick_si1 / 2.;

      rot2.SetAngles(phi + 90., theta, 0.);
      rot1.SetAngles(-1.*phi, 0., 0.);
      trans.SetDz(trans_z);

      h = invZtrans * rot2 * trans * rot1;
      ph = new TGeoHMatrix(h);

      AddNode(quartet, nq, ph);
   }
}
示例#13
0
void testRotation(){
	

	//LOAD LIBS
	cout << "\n";
	gROOT->Macro("StRoot/LoadLibs.C");
	gSystem->Load("pionPair");
	cout << " loading of pionPair library done" << endl;
	
	
	
	
	TFile* infile = new TFile("/star/u/klandry/ucladisk/2012IFF/schedOutputAll/all_0.root");

	
	//SET UP TREE TO RECEIVE INPUT
	pionPair* pair1 = new pionPair();
	TTree* pairTree = infile->Get("pionPairTree");
	pairTree->SetBranchAddress("pionPair", &pair1);

	
	for (int iPair = 0; iPair < pairTree->GetEntries(); iPair++)
	{
		if (iPair%10000 == 0) {cout << "processing pair number " << iPair << endl;}
		//cout << "processing pair number " << iPair << endl;
		
		
		//if (iPair == 661){continue;}
		
		pairTree->GetEntry(iPair);
		
		TVector3 spinVec;
		
		
		if (pair1->withinRadius(0.05, 0.3))
		{
			
			
			int spinB = pair1->spinBit();
			
			if (spinB == 5 || spinB == 9) //yelow down
			{
				spinVec.SetXYZ(0, -1, 0);
			}
			
			if (spinB == 6 || spinB == 10) //yellow up
			{
				spinVec.SetXYZ(0, 1, 0);
			}
			
			if (spinB == 5 || spinB == 6 || spinB == 9 || spinB == 10)
			{
				
				
				
				TVector3 Ph = pair1->piPlusLV().Vect() + pair1->piMinusLV().Vect();
				TVector3 Rh  = pair1->piPlusLV().Vect() - pair1->piMinusLV().Vect();
				
				
				TVector3 Pa;
				Pa.SetXYZ(0, 0, 1);   //blue is unpolarized beam
				
				TVector3 Pb;
				Pb.SetXYZ(0, 0, -1);  //yellow is polarized beam
				
				
				//ROTATE EVERYTHING BY PI AROUND Y AXIS
				
				Ph.RotateY(TMath::Pi());
				Rh.RotateY(TMath::Pi());
				Pa.RotateY(TMath::Pi());
				Pb.RotateY(TMath::Pi());
				
				
			//	cout << Ph << endl;
			//	cout << Rh << endl;
			//	cout << Pa << endl;
			//	cout << Pb << endl;
				
				
				//cout << "\n";
				
				//cout << Ph.Unit().Cross(Pa) << endl;
				//cout << Ph.Unit().Cross(Rh) << endl;
				
				double cosPhi_S = Pb.Unit().Cross(Ph).Unit() * Pb.Unit().Cross(spinVec).Unit();
				
				double cosPhi_R = Ph.Unit().Cross(Pa).Unit() * Ph.Unit().Cross(Rh).Unit();
				
				double sinPhi_S = Ph.Cross(spinVec) * Pb.Unit() / (Pb.Unit().Cross(Ph).Mag() * Pb.Unit().Cross(spinVec).Mag());
				
				double sinPhi_R = Pa.Cross(Rh) * Ph.Unit() / (Ph.Unit().Cross(Pa).Mag() * Ph.Unit().Cross(Rh).Mag());
				
				
				
				double sinPhi_S_R = sinPhi_S*cosPhi_R - cosPhi_S*sinPhi_R;
				
				double cosPhi_S_R = cosPhi_S*cosPhi_R + sinPhi_S*sinPhi_R;
				
				
				
				double phi_S_R;
				
				if (cosPhi_S_R >= 0)
				{
					phi_S_R = asin(sinPhi_S_R);
				}
				else if (cosPhi_S_R < 0)
				{
					
					if (sinPhi_S_R >= 0)
					{
						phi_S_R = TMath::Pi() - asin(sinPhi_S_R);
					}
					if (sinPhi_S_R < 0)
					{
						phi_S_R = -TMath::Pi() - asin(sinPhi_S_R);
					}
					
				}
				
				
				
				cout << "regular Phi_SR = " << pair1->phiSR('y') << "   rotated Phi_SR = " << phi_S_R << endl;
				
			}
			
			
			
			
		}
		
	}
	
	
	
	
	
	
	
}
示例#14
0
// Main macro function
//--------------------------------------------------------------------------------------------------
void SkimMultipleFiles_fakes(string inputFilename, string outputFilename) 
{
  gBenchmark->Start("SkimNtuples");
    
  TTree::SetMaxTreeSize(kMaxLong64);
  
  // Don't write TObject part of the objects
  mithep::TEventInfo::Class()->IgnoreTObjectStreamer();
  mithep::TMuon::Class()->IgnoreTObjectStreamer();
  mithep::TElectron::Class()->IgnoreTObjectStreamer();
  mithep::TJet::Class()->IgnoreTObjectStreamer();
  mithep::TPhoton::Class()->IgnoreTObjectStreamer();

  // Data structures to store info from TTrees
  mithep::TEventInfo *info  = new mithep::TEventInfo();
  TClonesArray *muonArr     = new TClonesArray("mithep::TMuon");
  TClonesArray *electronArr     = new TClonesArray("mithep::TElectron");
  TClonesArray *jetArr    = new TClonesArray("mithep::TJet");
  TClonesArray *photonArr     = new TClonesArray("mithep::TPhoton");
    
  UInt_t nInputEvts = 0;
  UInt_t nPassEvts  = 0;
  UInt_t nEventsTotal = 0;

  TFile* outfile = new TFile(outputFilename.c_str(), "RECREATE");
  
  //
  // Initialize data trees and structs
  // 
  TTree *outEventTree = new TTree("Events","Events"); 
  outEventTree->Branch("Info",     &info);
  outEventTree->Branch("Muon",     &muonArr);
  outEventTree->Branch("Electron", &electronArr);
  outEventTree->Branch("PFJet",    &jetArr);
  outEventTree->Branch("Photon",   &photonArr);


  // list input ntuple files to be skimmed
  vector<string> infilenames;  
  ifstream ifs;
  ifs.open(inputFilename.c_str()); 
  assert(ifs.is_open());
  string line;
  while(getline(ifs,line)) { infilenames.push_back(line); }
  ifs.close();

  for(UInt_t ifile=0; ifile<infilenames.size(); ifile++) {
    cout << "Skimming " << infilenames[ifile] << "..." << endl;
    TTree *eventTree = getTreeFromFile(infilenames[ifile].c_str(),"Events"); 
    nEventsTotal += getNEvents(infilenames[ifile].c_str()); 
    assert(eventTree);
    
    // Set branch address to structures that will store the info  
    eventTree->SetBranchAddress("Info",     &info);        TBranch *infoBr     = eventTree->GetBranch("Info");
    eventTree->SetBranchAddress("Muon",     &muonArr);     TBranch *muonBr     = eventTree->GetBranch("Muon");
    eventTree->SetBranchAddress("Electron", &electronArr); TBranch *electronBr = eventTree->GetBranch("Electron");
    eventTree->SetBranchAddress("PFJet",    &jetArr);      TBranch *jetBr      = eventTree->GetBranch("PFJet");
    eventTree->SetBranchAddress("Photon",    &photonArr);  TBranch *photonBr   = eventTree->GetBranch("Photon");
     
    for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) { 
      infoBr->GetEntry(ientry);
      muonArr->Clear();     muonBr->GetEntry(ientry);
      electronArr->Clear(); electronBr->GetEntry(ientry);
      jetArr->Clear();      jetBr->GetEntry(ientry);
      
      if (ientry % 100000 == 0) cout << "Events: " << ientry << endl;

      nInputEvts++;
      
      //********************************************************
      // TcMet
      //********************************************************
      TVector3 met;        
      if(info->tcMEx!=0 || info->tcMEy!=0) {       
        met.SetXYZ(info->tcMEx, info->tcMEy, 0);
      }
      
      Double_t tempLeadingJetPt = 0;
      for(Int_t i=0; i<jetArr->GetEntries(); i++) {
        const mithep::TJet *jet = (mithep::TJet*)((*jetArr)[i]);
        if( jet->pt > tempLeadingJetPt) tempLeadingJetPt = jet->pt;
      }


      Bool_t keep = kTRUE;
    
      Int_t NRecoMuon = 0;
      Int_t NDenominatorMuon = 0;
      Int_t NMuons = 0;
      for(Int_t i=0; i<muonArr->GetEntries(); i++) {
        const mithep::TMuon *mu = (mithep::TMuon*)((*muonArr)[i]);      
        if (fabs(mu->eta) < 2.4 && mu->pt > 10.0) {
          NRecoMuon++;
          if (passMuonDenominatorCuts(mu)) {
            NDenominatorMuon++;
          }
        }
      }
      Int_t NRecoElectrons = 0;
      Int_t NDenominatorElectrons = 0;
      for(Int_t i=0; i<electronArr->GetEntries(); i++) {
        const mithep::TElectron *ele = (mithep::TElectron*)((*electronArr)[i]);
        if ( fabs(ele->eta) < 2.5 && ele->pt > 10.0 ) {
          NRecoElectrons++;
          if (passElectronDenominatorCuts(ele) ) {
            NDenominatorElectrons++;
          }
        }
      }

      //Skim Lepton + Jet
      if (!(
            (NRecoMuon == 1 || NRecoElectrons == 1)
            &&
            tempLeadingJetPt > 15.0
            &&
            met.Pt() < 20
            )
        ) {
        keep = kFALSE;
      }

      if(keep) {
        outEventTree->Fill();
        nPassEvts++;
      }
    }
  }
  outfile->Write();
  outfile->Close();
  
  delete info;
  delete muonArr;
  delete electronArr;
  delete jetArr;
    
  std::cout << outputFilename << " created!" << std::endl;
  std::cout << " >>> Total Number of Events: " << nEventsTotal << std::endl;
  std::cout << " >>> Events processed: " << nInputEvts << std::endl;
  std::cout << " >>>   Events passing: " << nPassEvts << std::endl;

  gBenchmark->Show("SkimNtuples");
}  
示例#15
0
void figureOutpiover2(int ptBin, double ptCutLo, double ptCutHi, int massBin, double mCutLo, double mCutHi, int etaBin, double etaCutLo, double etaCutHi) {

    //OPTIONS AND CUTS------------
    bool useBlueBeam = false;
    bool useYellowBeam = true;
    double PI = 3.14159265359;


    if (useBlueBeam && useYellowBeam) {
        cout << "using both beams" << endl;
    }
    if (useBlueBeam && !useYellowBeam) {
        cout << "using blue beam" << endl;
    }
    if (!useBlueBeam && useYellowBeam) {
        cout << "using yellow beam" << endl;
    }


    //PION PAIR CUTS:
    /*
     double ptCutLo = 4;
     double ptCutHi = 10;
     double mCutLo = .4;
     double mCutHi = 1;
     double etaCutLo = -1.4;
     double etaCutHi = 1.4;
     //*/
    //double phiCutLo = -.5;
    //double phiCutHi = .5;

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


    //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/all2012dataAll.root");
    //TFile* infile = new TFile("/star/u/klandry/ucladisk/2012IFF/schedOutputWithinRad/allWithRadcut.root");
    TFile* infile = new TFile("/star/u/klandry/ucladisk/2012IFF/schedOutAllDataTry1/allDataTry1.root");





    //SET UP TREE TO RECEIVE INPUT
    pionPair* pair1 = new pionPair();
    TTree* pairTree = infile->Get("pionPairTree");
    pairTree->SetBranchAddress("pionPair", &pair1);


    //SET UP HISTOGRAMS

    //event variable histograms
    TH1D* hInvarM    = new TH1D("invarM","invarM",80,0,2);
    TH1D* hEtaTot	   = new TH1D("etaTot","etaTot",60,-1.5,1.5);
    TH1D* hPhiR      = new TH1D("hPhiR","hPhiR",60,-4,4);
    TH1D* hPhiS      = new TH1D("hPhiS","hPhiS",60,-4,4);
    TH1D* hPhiSR     = new TH1D("hPhiSR","hPhiSR",60,-4,4);
    TH1D* hTheta     = new TH1D("hTheta","hTheta",30,-0.85,4);
    TH1D* hCosTheta  = new TH1D("hCosTheta","hCosTheta",80,-1,1);
    TH1D* hZ         = new TH1D("hZ","hZ",80,0,1);
    TH1D* hPtot      = new TH1D("hPtot","hPtot",80,0,20);
    TH1D* hPtTOT     = new TH1D("hPt","hPt",80,0,15);

    //histos for asym analysis
    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 * hDiff  = new TH1D("hNumberSum","hNumberSum",binNumber,histMin,histMax);
    TH1D * hAut = new TH1D("Aut","Aut",binNumber,histMin,histMax);


    //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;

    }


    //   ======================================================================
    //============================================================================
    //START ANALYSIS==============================================================
    //============================================================================
    //   ======================================================================

    cout << pairTree->GetEntries() << endl;

    cout << "\n";
    cout << "<----STARTING ANALYSIS---->" << endl;
    cout << "\n";


    double blueFillNo;
    double yellowFillNo;

    int bin;

    TLorentzVector sum;
    TLorentzVector sumY;
    TLorentzVector sumB;

    TRandom3 r;


    int totalPairsFinal = 0;


    for (int iPair = 0; iPair < pairTree->GetEntries(); iPair++)
    {
        if (iPair%10000 == 0) {
            cout << "processing pair number " << iPair << endl;
        }
        //cout << "processing pair number " << iPair << endl;


        //if (iPair == 80000){break;}

        pairTree->GetEntry(iPair);




        if (pair1->withinRadius(0.05, 0.3))
        {

            bool triggerFired = false;
            bool fromKaon = false;

            StTriggerId trigId = pair1->triggerIds();


            if (trigId.isTrigger(370601) || trigId.isTrigger(370611) || trigId.isTrigger(370621))
            {
                triggerFired = true;
            }

            if (trigId.isTrigger(370501) || trigId.isTrigger(370511) || trigId.isTrigger(370522) || trigId.isTrigger(370531))
            {
                triggerFired = true;
            }


            if (pair1->invarientMass() > .4921 && pair1->invarientMass() < .4990)
            {
                fromKaon = true;
            }



            if (triggerFired)
            {


                blueFillNo   = pair1->runInfo().beamFillNumber(1); //1 = blue beam
                yellowFillNo = pair1->runInfo().beamFillNumber(0); //0 = yellow beam

                //cout << blueFillNo << "  " << yellowFillNo << endl;


                if (polarizationOfFill_B[blueFillNo] == 0 || polarizationOfFill_Y[yellowFillNo] == 0)
                {
                    continue;
                }


                hInvarM->Fill(pair1->invarientMass());

                TVector3 spinVec;


                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);


                double randomSpin = r.Uniform(0, 1);

                int randomSpinBit;

                if (randomSpin >=0 && randomSpin <0.25)  {
                    randomSpinBit = 5;
                }
                if (randomSpin >=0.25 && randomSpin <0.5) {
                    randomSpinBit = 6;
                }
                if (randomSpin >=0.5 && randomSpin <0.75) {
                    randomSpinBit = 9;
                }
                if (randomSpin >=0.75 && randomSpin <1.0) {
                    randomSpinBit = 10;
                }


                //CHECK CUTS
                if (sumB.Pt() > ptCutLo && sumB.Pt() < ptCutHi && sumB.M() > mCutLo && sumB.M() < mCutHi && sumB.Eta() > etaCutLo && sumB.Eta() < etaCutHi && useBlueBeam == true)
                {

                    //BLUE BEAM SPIN UP: spin bin 9 and 10
                    if (pair1->spinBit() == 9 || pair1->spinBit() == 10)
                    {
                        bin = hNumberUp->FindBin(pair1->phiSR('b'));
                        //hNumberUp->Fill(pair1->phiSR('b'));



                        polOfBinSumUp[bin] += polarizationOfFill_B[blueFillNo];
                        pErrorOfBinUp[bin] += polErrOfFill_B[blueFillNo];
                    }

                    //BLUE BEAM SPIN DOWN: spin bin 5 and 6
                    if (pair1->spinBit() == 5 || pair1->spinBit() == 6)
                    {
                        bin = hNumberDown->FindBin(pair1->phiSR('b'));
                        hNumberDown->Fill(pair1->phiSR('b'));

                        polOfBinSumDown[bin] += polarizationOfFill_B[blueFillNo];
                        pErrorOfBinDown[bin] += polErrOfFill_B[blueFillNo];
                    }

                }//end blue cuts

                TVector3 Pa;
                Pa.SetXYZ(0, 0, 1);   //blue is unpolarized beam

                TVector3 Pb;
                Pb.SetXYZ(0, 0, -1);  //yellow is polarized beam


                if (sumY.Pt()>ptCutLo && sumY.Pt() < ptCutHi && sumY.M() > mCutLo && sumY.M() < mCutHi && sumY.Eta() > etaCutLo && sumY.Eta() < etaCutHi && useYellowBeam == true)
                {

                    //YELLOW BEAM SPIN UP: spin bin 6 and 10
                    //if (pair1->spinBit() == 6 || pair1->spinBit() == 10)
                    if (randomSpinBit == 6 || randomSpinBit == 10)

                    {

                        totalPairsFinal++;


                        spinVec.SetXYZ(0, 1, 0);

                        TVector3 Ph = pair1->piPlusLV().Vect() + pair1->piMinusLV().Vect();
                        TVector3 Rh  = pair1->piPlusLV().Vect() - pair1->piMinusLV().Vect();


                        double cosPhi_S = -Pb.Unit().Cross(Ph).Unit() * Pb.Unit().Cross(spinVec).Unit();

                        double cosPhi_R = Ph.Unit().Cross(Pb).Unit() * Ph.Unit().Cross(Rh).Unit();

                        double sinPhi_S = Ph.Cross(spinVec) * Pb.Unit() / (Pb.Unit().Cross(Ph).Mag() * Pb.Unit().Cross(spinVec).Mag());

                        double sinPhi_R = Pb.Cross(Rh) * Ph.Unit() / (Ph.Unit().Cross(Pb).Mag() * Ph.Unit().Cross(Rh).Mag());



                        double sinPhi_S_R = sinPhi_S*cosPhi_R - cosPhi_S*sinPhi_R;

                        double cosPhi_S_R = cosPhi_S*cosPhi_R + sinPhi_S*sinPhi_R;



                        double phi_S_R;

                        if (cosPhi_S_R >= 0)
                        {
                            phi_S_R = asin(sinPhi_S_R);
                        }
                        else if (cosPhi_S_R < 0)
                        {

                            if (sinPhi_S_R >= 0)
                            {
                                phi_S_R = TMath::Pi() - asin(sinPhi_S_R);
                            }
                            if (sinPhi_S_R < 0)
                            {
                                phi_S_R = -TMath::Pi() - asin(sinPhi_S_R);
                            }

                        }

                        //cout <<  "phisr = " << phi_S_R << endl;



                        bin = hNumberUp->FindBin(phi_S_R);
                        hNumberUp->Fill(phi_S_R);

                        polOfBinSumUp[bin] += polarizationOfFill_Y[yellowFillNo];
                        pErrorOfBinUp[bin] += polErrOfFill_Y[yellowFillNo];
                    }
                    //YELLOW BEAM SPIN DOWN: spin bit 5 and 9
                    if (randomSpinBit == 5 || randomSpinBit == 9)
                    {

                        totalPairsFinal++;

                        spinVec.SetXYZ(0, -1, 0);

                        TVector3 Ph = pair1->piPlusLV().Vect() + pair1->piMinusLV().Vect();
                        TVector3 Rh  = pair1->piPlusLV().Vect() - pair1->piMinusLV().Vect();


                        double cosPhi_S = -Pb.Unit().Cross(Ph).Unit() * Pb.Unit().Cross(spinVec).Unit();

                        double cosPhi_R = Ph.Unit().Cross(Pa).Unit() * Ph.Unit().Cross(Rh).Unit();

                        double sinPhi_S = Ph.Cross(spinVec) * Pb.Unit() / (Pb.Unit().Cross(Ph).Mag() * Pb.Unit().Cross(spinVec).Mag());

                        double sinPhi_R = Pa.Cross(Rh) * Ph.Unit() / (Ph.Unit().Cross(Pa).Mag() * Ph.Unit().Cross(Rh).Mag());



                        double sinPhi_S_R = sinPhi_S*cosPhi_R - cosPhi_S*sinPhi_R;

                        double cosPhi_S_R = cosPhi_S*cosPhi_R + sinPhi_S*sinPhi_R;



                        double phi_S_R;

                        if (cosPhi_S_R >= 0)
                        {
                            phi_S_R = asin(sinPhi_S_R);
                        }
                        else if (cosPhi_S_R < 0)
                        {

                            if (sinPhi_S_R >= 0)
                            {
                                phi_S_R = TMath::Pi() - asin(sinPhi_S_R);
                            }
                            if (sinPhi_S_R < 0)
                            {
                                phi_S_R = -TMath::Pi() - asin(sinPhi_S_R);
                            }

                        }

                        //	cout <<  "phisr = " << phi_S_R << endl;


                        bin = hNumberDown->FindBin(phi_S_R);
                        hNumberDown->Fill(phi_S_R);

                        polOfBinSumDown[bin] += polarizationOfFill_Y[yellowFillNo];
                        pErrorOfBinDown[bin] += polErrOfFill_Y[yellowFillNo];
                    }
                }//end yellow cuts





            }//end triger check
        }//end radius check
    }//end pairTree loop


    //CALCULATE ASYMMETRY BIN BY BIN
    cout << "\n";
    cout << "<----CALCULATING ASYMMETRY---->" << endl;
    cout << "\n";
    //*
    for (int ibin=1; ibin<=binNumber; ibin++)
    {

        if (ibin <= binNumber*0.5)
        {
            double nUp   = hNumberUp->GetBinContent(ibin);
            double nUpPi = hNumberUp->GetBinContent(ibin+binNumber*0.5);

            double nDown   = hNumberDown->GetBinContent(ibin);
            double nDownPi = hNumberDown->GetBinContent(ibin+binNumber*0.5);


            cout << nUp << "  " << nUpPi << "  " << nDown << "  " << nDownPi << "  "  << endl;

            int binIndexPi = ibin+binNumber*0.5;

            double avgPolA = (polOfBinSumUp[ibin]+polOfBinSumDown[binIndexPi])/(nUp+nDownPi);
            double avgPolB = (polOfBinSumUp[binIndexPi]+polOfBinSumDown[ibin])/(nUpPi+nDown);

            double realAvgPol = (polOfBinSumUp[ibin]+polOfBinSumDown[binIndexPi]+polOfBinSumUp[binIndexPi]+polOfBinSumDown[ibin])/(nUp+nUpPi+nDown+nDownPi);

        }
        else
        {
            double nUp   = hNumberUp->GetBinContent(ibin);
            double nUpPi = hNumberUp->GetBinContent(ibin-binNumber*0.5);

            double nDown   = hNumberDown->GetBinContent(ibin);
            double nDownPi = hNumberDown->GetBinContent(ibin-binNumber*0.5);

            int binIndexPi = ibin-binNumber*0.5;

            cout << nUp << "  " << nUpPi << "  " << nDown << "  " << nDownPi << "  "  << endl;


            double avgPolA = (polOfBinSumUp[ibin]+polOfBinSumDown[binIndexPi])/(nUp+nDownPi);
            double avgPolB = (polOfBinSumUp[binIndexPi]+polOfBinSumDown[ibin])/(nUpPi+nDown);

            double realAvgPol = (polOfBinSumUp[ibin]+polOfBinSumDown[binIndexPi]+polOfBinSumUp[binIndexPi]+polOfBinSumDown[ibin])/(nUp+nUpPi+nDown+nDownPi);

            double realAvgPolE = (pErrorOfBinUp[ibin]+pErrorOfBinDown[binIndexPi]+pErrorOfBinUp[binIndexPi]+pErrorOfBinDown[ibin])/(nUp+nUpPi+nDown+nDownPi);

        }


        cout << avgPolA << "   " << avgPolB << endl;




        hDiff->SetBinContent(ibin, sqrt(nUp*nDownPi) - sqrt(nDown*nUpPi));

        //hAut->SetBinContent(ibin, (1/avgPolA * sqrt(nUp*nDownPi) - 1/avgPolB * sqrt(nDown*nUpPi)) / (sqrt(nUp*nDownPi) + sqrt(nDown*nUpPi))    );


        hAut->SetBinContent(ibin, 1/realAvgPol * (sqrt(nUp*nDownPi) - sqrt(nDown*nUpPi)) / (sqrt(nUp*nDownPi) + sqrt(nDown*nUpPi))    );




        //error
        if (realAvgPol*pow(sqrt(nUp*nDownPi)+sqrt(nDown*nUpPi), 2) != 0)
        {

            double a = sqrt(nUp*nDownPi);
            double b = sqrt(nUpPi*nDown);


            double firstTerm = realAvgPol**2 * (nUpPi*nDown*(nUp+nDownPi) + nDownPi*nUp*(nUpPi+nDown));

            //double secondTerm = ((nUp*nDownPi)**2 +(nUpPi*nDown)**2 - 2*nUp*nDown*nUpPi*nDownPi)*realAvgPolE**2;

            double secondTerm = 0;


            double binError = 1/realAvgPol**2 * 1/(a+b)**2 * sqrt(firstTerm + secondTerm);


        }
        else
        {
            double binError = 0.01;
            cout << "bin " << ibin << " Has problem with error" << endl;
        }

        hAut->SetBinError(ibin, binError);

    }//end Asym calc

    //*/

    //DRAW HISTOGRAMS

    hInvarM->Draw();

    TCanvas* cNup = new TCanvas();
    hNumberUp->Draw();

    TCanvas* cNdown = new TCanvas();
    hNumberDown->Draw();

    TCanvas* cAut = new TCanvas();
    cAut->SetName("cAut");

    TF1* fitFunc = new TF1("fitFunc","[0]*sin(x)+[1]",-PI,PI);
    //hAut->Fit("fitFunc","R");
    hAut->Draw();

    hAut->GetXaxis()->SetTitle("#phi_{S} - #phi_{R}");

    char title[150];
    sprintf(title, "%.1f < P_{T}^{#pi^{+}#pi^{-}} < %.1f  %.1f < M_{inv}^{#pi^{+}#pi^{-}} < %.1f  %.1f < #eta^{#pi^{+}#pi^{-}} < %.1f", ptCutLo, ptCutHi, mCutLo, mCutHi, etaCutLo, etaCutHi);

    hAut->SetTitle(title);





    //SAVE CANVAS


    stringstream pt;
    stringstream eta;
    stringstream mass;

    string part1 = "_ptBin";
    string part2 = "_massBin";
    string part3 = "_etaBin";

    string ptBinStr;
    string etaBinStr;
    string massBinStr;


    pt << ptBin;

    eta << etaBin;

    mass << massBin;

    if (ptBin == 9) {
        ptBinStr = "All";
    }
    else {
        ptBinStr = pt.str();
    }

    if (massBin == 9) {
        massBinStr = "All";
    }
    else {
        massBinStr = mass.str();
    }

    if (etaBin == 9) {
        etaBinStr = "All";
    }
    else {
        etaBinStr = eta.str();
    }

    cout << "total pairs " << totalPairsFinal << endl;

    string outFileName = "./resultsTesting/piover2issue"+part1+ptBinStr+part2+massBinStr+part3+etaBinStr+".root";
    TFile* outFile = new TFile(outFileName.c_str(),"Recreate");


    cout << "---WRITING FILE---" << endl;
    //cAut->SaveAs(outFileName.c_str());
    hAut->Write();
    hNumberUp->Write();
    hNumberDown->Write();

    cout << "---END---" << endl;
}
示例#16
0
TH1F* AnalyzeDs1pToDstKs(TChain* fChain,TString DATAorMC,Int_t MatterOrAntiMatter,TString Mode,TString NtupleDir,Int_t WhichCuts){

  Int_t test;
  
  //
  Bool_t TruthMatch=false;
  if(DATAorMC=="MC")TruthMatch=true;
 
  // Declaration of leave types
  Float_t beamSX;
  Float_t beamSY;
  Float_t beamSZ;

  Int_t   nDs1p;
  Float_t Ds1pChi2[400];  
  Float_t Ds1pMass[400];  
  Float_t Ds1pcosth[400];  
  Float_t Ds1pcosthCM[400];  
  Float_t Ds1pp3CM[400];  
  Float_t Ds1pphiCM[400];  
  Int_t   Ds1pLund[400];  
  Int_t   Ds1pMCIdx[400];  
  Int_t   Ds1pd1Lund[400];  
  Int_t   Ds1pd1Idx[400];  
  Int_t   Ds1pd2Lund[400];  
  Int_t   Ds1pd2Idx[400];  
  Float_t Ds1pVtxx[500];  
  Float_t Ds1pVtxy[500];  
  Float_t Ds1pVtxz[500];     

  Int_t   nKs;
  Float_t KsMass[400]; 
  Float_t Ksp3CM[400]; 
  Int_t   KsLund[400]; 
  Int_t   Ksd1Lund[400]; 
  Int_t   Ksd1Idx[400]; 
  Int_t   Ksd2Lund[400]; 
  Int_t   Ksd2Idx[400];  
  Int_t   KsMCIdx[400];
  Float_t KsChi2[400];
  Int_t   KsnDof[400];
  Float_t KsVtxx[500]; 
  Float_t KsVtxy[500]; 
  Float_t KsVtxz[500]; 
  Float_t Kscosth[500]; 
  Float_t Ksphi[500]; 

  Int_t   nDstar;
  Float_t DstarMass[400];  
  Float_t DstarMassErr[400];  
  Float_t Dstarcosth[400];  
  Float_t Dstarp3[400];  
  Float_t Dstarp3CM[400];  
  Int_t   DstarLund[400];  
  Int_t   Dstard1Lund[400];  
  Int_t   Dstard1Idx[400];  
  Int_t   Dstard2Lund[400];  
  Int_t   Dstard2Idx[400];    
  Int_t   DstarMCIdx[400];
 
  Int_t   nD0;
  Float_t D0Mass[400];  
  Float_t D0MassErr[400];  
  Float_t D0p3CM[400];  
  Int_t   D0Lund[400];  
  Int_t   D0d1Lund[400];  
  Int_t   D0d1Idx[400];  
  Int_t   D0d2Lund[400];  
  Int_t   D0d2Idx[400];   
  Int_t   D0d3Lund[400];  
  Int_t   D0d3Idx[400];
  Int_t   D0d4Lund[400];     
  Int_t   D0d4Idx[400];
  Int_t   D0MCIdx[400];
  Float_t D0Chi2[400];
  Int_t   D0nDof[400];

  Int_t   nPi;
  Float_t Pip3[400];  
  Int_t   PiLund[400];   
  Int_t   PiMCIdx[400];
  Int_t   PiTrkIdx[400];
  Int_t   PiSelectorsMap[400];
  
  Int_t   nK;
  Float_t Kp3[400]; 
  Int_t   KLund[400]; 
  Int_t   KMCIdx[400];
  Int_t   KTrkIdx[400];

  Int_t   nPi0;
  Float_t Pi0Mass[400];
  Float_t Pi0p3[400];  
  Int_t   Pi0Lund[400];  
  Int_t   Pi0MCIdx[400];
  Int_t   Pi0d1Lund[400];
  Int_t   Pi0d1Idx[400];

  Float_t GammaECal[400];
  Int_t   GammaMCIdx[400];
  Int_t   GammaLund[400];

  Int_t TRKnSvt[400];
  Int_t TRKLund[400];
  

  ////MC block
  Int_t mcLen;
  Int_t mcLund[400];
  Int_t mothIdx[400];
  Int_t dauLen[400];
  Int_t dauIdx[400];
  Float_t mcmass[400]; 
  Float_t mccosth[400];
  Float_t mcp3[400];
  Float_t mccosthCM[400];
  Float_t mcp3CM[400]; 


 

  //////My derived variables
  Float_t D0Probab;
  Float_t KsProbab;
  Float_t KsCosine;  
  TVector3 Ksp3Direction;
  TVector3 KsFlightDirection;

  Int_t MCDs1pCounterPerEvent=0;
  Int_t MCDs1pCounterTotal=0;
  Int_t RecoDs1pCounterTotal=0;


  Int_t   Ds1pIdx;
  Int_t   DstarIdx;
  Int_t   KsIdx;
  Int_t   D0Idx;
  Int_t   PiIdx;
  Int_t   SlowPiIdx;
  Int_t   KIdx;
  Int_t   Pi0Idx;
  Int_t   GammaIdx;  
  Int_t   PitrkIdx;
  Int_t   SlowPitrkIdx;
  Int_t   KsPi1Idx;
  Int_t   KsPi2Idx;
  Int_t   KsPi1trkIdx;
  Int_t   KsPi2trkIdx;

  //TChain* fChain=DstToD0PiChain(firstfile,lastfile, DATAorMC,Mode, ModeSubDir);
  if(fChain==NULL){
    cout<<"No chain."<<endl;
    return NULL;
  }
  fChain->SetBranchAddress("beamSX",&beamSX);
  fChain->SetBranchAddress("beamSY",&beamSY);
  fChain->SetBranchAddress("beamSZ",&beamSZ);

  fChain->SetBranchAddress("nDs1p",&nDs1p);
  fChain->SetBranchAddress("Ds1pMass",Ds1pMass);
  fChain->SetBranchAddress("Ds1pcosthCM",Ds1pcosthCM);
  fChain->SetBranchAddress("Ds1pp3CM",Ds1pp3CM);
  fChain->SetBranchAddress("Ds1pLund",Ds1pLund); 
  fChain->SetBranchAddress("Ds1pd1Lund",Ds1pd1Lund);
  fChain->SetBranchAddress("Ds1pd1Idx",Ds1pd1Idx);
  fChain->SetBranchAddress("Ds1pd2Lund",Ds1pd2Lund);
  fChain->SetBranchAddress("Ds1pd2Idx",Ds1pd2Idx);
  fChain->SetBranchAddress("Ds1pVtxx",Ds1pVtxx);
  fChain->SetBranchAddress("Ds1pVtxy",Ds1pVtxy);
  fChain->SetBranchAddress("Ds1pVtxz",Ds1pVtxz);


  fChain->SetBranchAddress("nKs",&nKs);
  fChain->SetBranchAddress("KsMass",KsMass);
  fChain->SetBranchAddress("Ksp3CM",Ksp3CM);  
  fChain->SetBranchAddress("KsLund",KsLund);
  fChain->SetBranchAddress("Ksd1Lund",Ksd1Lund);
  fChain->SetBranchAddress("Ksd1Idx",Ksd1Idx);
  fChain->SetBranchAddress("Ksd2Lund",Ksd2Lund);
  fChain->SetBranchAddress("Ksd2Idx",Ksd2Idx);
  fChain->SetBranchAddress("KsChi2",KsChi2);
  fChain->SetBranchAddress("KsnDof",KsnDof);
  fChain->SetBranchAddress("KsMCIdx",KsMCIdx);
  fChain->SetBranchAddress("KsVtxx",KsVtxx);
  fChain->SetBranchAddress("KsVtxy",KsVtxy);
  fChain->SetBranchAddress("KsVtxz",KsVtxz);
  fChain->SetBranchAddress("Kscosth",Kscosth);
  fChain->SetBranchAddress("Ksphi",Ksphi);


  fChain->SetBranchAddress("nDstar",&nDstar);
  fChain->SetBranchAddress("DstarMass",DstarMass);
  fChain->SetBranchAddress("DstarLund",DstarLund);
  fChain->SetBranchAddress("Dstard1Lund",Dstard1Lund);
  fChain->SetBranchAddress("Dstard1Idx",Dstard1Idx);
  fChain->SetBranchAddress("Dstard2Lund",Dstard2Lund);
  fChain->SetBranchAddress("Dstard2Idx",Dstard2Idx);

  fChain->SetBranchAddress("nD0",&nD0);
  fChain->SetBranchAddress("D0Mass",D0Mass);
  fChain->SetBranchAddress("D0p3CM",D0p3CM);  
  fChain->SetBranchAddress("D0Lund",D0Lund);
  fChain->SetBranchAddress("D0d1Lund",D0d1Lund);
  fChain->SetBranchAddress("D0d1Idx",D0d1Idx);
  fChain->SetBranchAddress("D0d2Lund",D0d2Lund);
  fChain->SetBranchAddress("D0d2Idx",D0d2Idx);
  fChain->SetBranchAddress("D0Chi2",D0Chi2);
  fChain->SetBranchAddress("D0nDof",D0nDof);

  fChain->SetBranchAddress("nPi",&nPi);
  fChain->SetBranchAddress("Pip3",Pip3);
  fChain->SetBranchAddress("PiLund",PiLund);
  fChain->SetBranchAddress("PiTrkIdx",PiTrkIdx);

  fChain->SetBranchAddress("nK",&nK);
  fChain->SetBranchAddress("Kp3",Kp3);
  fChain->SetBranchAddress("KLund",KLund);
  fChain->SetBranchAddress("KTrkIdx",KTrkIdx);

  fChain->SetBranchAddress("TRKnSvt",TRKnSvt);
  fChain->SetBranchAddress("TRKLund",TRKLund);
  fChain->SetBranchAddress("piSelectorsMap",PiSelectorsMap);

 
  if(Mode=="D0ToKPiPi0"){
    fChain->SetBranchAddress("D0d3Lund",D0d3Lund);
    fChain->SetBranchAddress("D0d3Idx",D0d3Idx);
    fChain->SetBranchAddress("nPi0",&nPi0);
    fChain->SetBranchAddress("Pi0Mass",Pi0Mass);
    fChain->SetBranchAddress("Pi0p3",Pi0p3);
    fChain->SetBranchAddress("Pi0Lund",Pi0Lund);
    fChain->SetBranchAddress("Pi0d1Lund",Pi0d1Lund);
    fChain->SetBranchAddress("Pi0d1Idx",Pi0d1Idx);
    fChain->SetBranchAddress("GammaLund",GammaLund);
    fChain->SetBranchAddress("GammaECal",GammaECal);
 
    if(TruthMatch){
      fChain->SetBranchAddress("Pi0MCIdx",Pi0MCIdx);    
      fChain->SetBranchAddress("GammaMCIdx", GammaMCIdx);
   
    }

  }
  if(Mode=="D0ToK3Pi"){
    fChain->SetBranchAddress("D0d3Lund",D0d3Lund);
    fChain->SetBranchAddress("D0d3Idx",D0d3Idx);
    fChain->SetBranchAddress("D0d4Lund",D0d4Lund);
    fChain->SetBranchAddress("D0d4Idx",D0d4Idx);
  }

  if(TruthMatch){
    fChain->SetBranchAddress("Ds1pMCIdx",Ds1pMCIdx);
    fChain->SetBranchAddress("DstarMCIdx",DstarMCIdx);
    fChain->SetBranchAddress("D0MCIdx",D0MCIdx);
    fChain->SetBranchAddress("KMCIdx",KMCIdx);
    fChain->SetBranchAddress("PiMCIdx",PiMCIdx);
    fChain->SetBranchAddress("mcLund",mcLund);
    fChain->SetBranchAddress("mcLen",&mcLen);
    fChain->SetBranchAddress("mcp3",mcp3);
    fChain->SetBranchAddress("mccosth",mccosth);
    fChain->SetBranchAddress("mcp3CM",mcp3CM);
    fChain->SetBranchAddress("mccosthCM",mccosthCM); 
  }
  
 
  //Histosgrams
  Float_t DstarMassWindow=.090;  
  Float_t D0MassWindow=.090;
  Float_t KsMassWindow=.030;
  Int_t NMassBins=62;
  Float_t Ds1pMassLo=2.470;  
  Float_t Ds1pMassHi=2.600;  
  Int_t NDs1pMassBins=70;


  //////Cuts
  ///Loose
  Float_t D0p3CMCut=0.;
  Float_t D0ProbabCut=0.;
  Float_t KsProbabCut=0.;
  Float_t KsCosineCut=0.;

  ///Define Signal Region
  Float_t Ds1pMassCutLo=0.;
  Float_t Ds1pMassCutHi=0.;
  Float_t Ds1pMassResolution=0.;
  //////////////
  

  if(Mode=="D0ToKPi"){
    //loose
    if(WhichCuts==1){       
      D0p3CMCut=2.4; 
      D0ProbabCut=5e-3; 
      KsProbabCut=5e-3; 
      KsCosineCut=0; 
    }
    Ds1pMassResolution=.009;
    Ds1pMassCutLo=Ds1pPDGMass-4*Ds1pMassResolution;
    Ds1pMassCutHi=Ds1pPDGMass+4*Ds1pMassResolution;

  }
  if(Mode=="D0ToKPiPi0"){
    //loose
    if(WhichCuts==1){       
      D0p3CMCut=2.2; 
      D0ProbabCut=5e-3; 
      KsProbabCut=5e-3; 
      KsCosineCut=0; 
    }
    Ds1pMassResolution=.013;
    Ds1pMassCutLo=Ds1pPDGMass-4*Ds1pMassResolution;
    Ds1pMassCutHi=Ds1pPDGMass+4*Ds1pMassResolution;

  }

  if(Mode=="D0ToK3Pi"){
    //loose
    if(WhichCuts==1){       
      D0p3CMCut=2.2; 
      D0ProbabCut=5e-3; 
      KsProbabCut=5e-3; 
      KsCosineCut=0; 
    }
    Ds1pMassResolution=.006;
    Ds1pMassCutLo=Ds1pPDGMass-4*Ds1pMassResolution;
    Ds1pMassCutHi=Ds1pPDGMass+4*Ds1pMassResolution;

  }
  

  //////////////  
  //BeamPlots  
  TH1F HBeamRadius;
  SetHistoXY(&HBeamRadius,"Beam R",100,0,.5,"R (cm)","Entries/50#mu m");
  
  TH1F HBeamZ;
  SetHistoXY(&HBeamZ,"Beam Z",100,-4.,4.,"Z (cm)","Entries/1mm");
   
  ////Kaon
  TH1F HKMomentum;
  SetHistoXY(&HKMomentum,"K Momentum ",80,0,8,"p (GeV/c)","Entries/100MeV");

  TH1F HKMomentumTruthMatched;
  SetHistoXY(&HKMomentumTruthMatched,"K Momentum ",80,0,8,"p (GeV/c)","Entries/100MeV");
  
  /////pion 
  TH1F HPiMomentum;
  SetHistoXY(&HPiMomentum," Pion Momentum ",80,0,8,"p (GeV/c)","Entries/100MeV");

  TH1F HPiMomentumTruthMatched;
  SetHistoXY(&HPiMomentumTruthMatched," Pion Momentum ",80,0,8,"p (GeV/c)","Entries/100MeV");

  ///////////Mode dependent histos
  ////////////Mode=="D0ToKPiPi0"
  ////Gamma
  TH1F HGammaEnergy;
  SetHistoXY(&HGammaEnergy,"Gamma Energy",30,0,1.2,"calor. energy (GeV/c^{2})","Entries/40MeV");

  TH1F HGammaEnergyTruthMatched;
  SetHistoXY(&HGammaEnergyTruthMatched,"Gamma Energy",30,0,1.2,"calor. energy (GeV/c^{2})","Entries/40MeV");
  
  ////Pi0 
  TH1F HPi0MassPreCuts;
  SetHistoXY(&HPi0MassPreCuts,"Pi0 Mass After Cuts ",120,.075,.195," mass (GeV/c^{2})","Entries/1MeV");

  TH1F HPi0Mass;
  SetHistoXY(&HPi0Mass,"Pi0 Mass After Cuts ",120,.075,.195," mass (GeV/c^{2})","Entries/1MeV");

  TH1F HPi0MassTruthMatched;
  SetHistoXY(&HPi0MassTruthMatched,"Pi0 Mass After Cuts ",120,.075,.195," mass (GeV/c^{2})","Entries/1MeV");
  
 
  /////D0 
  TH1F HD0p3CM;
  SetHistoXY(&HD0p3CM,"D0 CM Momentum ",80,0,8,"p* (GeV/c)","Entries/100MeV");

  TH1F HD0MassPreCuts;
  SetHistoXY(&HD0MassPreCuts,"D0 Mass Before Cuts",NMassBins,D0PDGMass-D0MassWindow-.001,D0PDGMass+D0MassWindow+.001,"D0 Cand. Mass (GeV/c^{2})","Entries/1MeV");

  TH1F HD0Mass;
  SetHistoXY(&HD0Mass,"D0 Mass After Cuts ",NMassBins,D0PDGMass-D0MassWindow-.001,D0PDGMass+D0MassWindow+.001,"D0 Cand. Mass (GeV/c^{2})","Entries/1MeV");

  TH1F HD0MassTruthMatched;
  SetHistoXY(&HD0MassTruthMatched,"D0 Mass After Cuts ",NMassBins,D0PDGMass-D0MassWindow-.001,D0PDGMass+D0MassWindow+.001,"D0 Cand. Mass (GeV/c^{2})","Entries/1MeV");

  TH1F HD0Probab;
  SetHisto(&HD0Probab,"D0 Vtx Probab ",200,-8,0,"log(p(#chi^{2}))");


  //slow pion
  TH1F HSlowPiMomentum;
  SetHistoXY(&HSlowPiMomentum,"Slow Pion Momentum ",30,0,1.2,"p (GeV/c)","Entries/40MeV");

  TH1F HSlowPiMomentumTruthMatched;
  SetHistoXY(&HSlowPiMomentumTruthMatched,"Slow Pion Momentum ",30,0,1.2,"p (GeV/c)","Entries/40MeV");

  ////Dstar
  TH1F HDstarMassPreCuts;
  SetHistoXY(&HDstarMassPreCuts,"D* Mass Before Cuts",NMassBins,DstarPDGMass-DstarMassWindow-.001,DstarPDGMass+DstarMassWindow+.001,"D* Cand. Mass (GeV/c^{2})","Entries/1MeV");
  HDstarMassPreCuts.SetLineColor(1);

  TH1F HDstarMass;
  SetHistoXY(&HDstarMass,"D* Mass After Cuts",NMassBins,DstarPDGMass-DstarMassWindow-.001,DstarPDGMass+DstarMassWindow+.001,"D* Cand. Mass (GeV/c^{2})","Entries/1MeV");
  HDstarMass.SetLineColor(1);
  
  TH1F HDstarMassTruthMatched;
  SetHistoXY(&HDstarMassTruthMatched,"D* Mass After Cuts and Truth Matched",NMassBins,DstarPDGMass-DstarMassWindow-.001,DstarPDGMass+DstarMassWindow+.001,"D* Cand. Mass (GeV/c^{2})","Entries/1MeV");
  HDstarMassTruthMatched.SetLineColor(1);

  TH1F HMassDiff;
  SetHistoXY(&HMassDiff,"#Delta M After Cuts",300,.139,.160,"D* Cand. Mass - D0 Cand. Mass (GeV/c^{2})","Entries/.1MeV");  


  /////pion1 
  TH1F HPi1Momentum;
  SetHistoXY(&HPi1Momentum," Pion1 Momentum ",100,0,2,"p (GeV/c)","Entries/20MeV");

  TH1F HPi1MomentumTruthMatched;
  SetHistoXY(&HPi1MomentumTruthMatched," Pion1 Momentum ",100,0,2,"p (GeV/c)","Entries/20MeV");

  /////Ks 
  TH1F HKsp3CM;
  SetHistoXY(&HKsp3CM,"Ks CM Momentum ",80,0,8,"p* (GeV/c)","Entries/100MeV");

  TH1F HKsMassPreCuts;
  SetHistoXY(&HKsMassPreCuts,"Ks Mass Before Cuts",NMassBins,K0PDGMass-KsMassWindow-.001,K0PDGMass+KsMassWindow+.001,"Ks Cand. Mass (GeV/c^{2})","Entries/1MeV");

  TH1F HKsMass;
  SetHistoXY(&HKsMass,"Ks Mass After Cuts ",NMassBins,K0PDGMass-KsMassWindow-.001,K0PDGMass+KsMassWindow+.001,"Ks Cand. Mass (GeV/c^{2})","Entries/1MeV");

  TH1F HKsMassTruthMatched;
  SetHistoXY(&HKsMassTruthMatched,"Ks Mass After Cuts ",NMassBins,K0PDGMass-KsMassWindow-.001,K0PDGMass+KsMassWindow+.001,"Ks Cand. Mass (GeV/c^{2})","Entries/1MeV");

  TH1F HKsCosine;
  SetHistoXY(&HKsCosine,"Ks Direction",100,-1.00001,1.00001,"cos(#theta)","Entries/.02");

  TH1F HKsProbab;
  SetHisto(&HKsProbab,"Ks Vtx Probab ",200,-8,0,"log(p(#chi^{2}))");

 
  ////Ds1p
  TH1F HDs1pMassPreCuts;
  SetHistoXY(&HDs1pMassPreCuts,"D'_{s1} Mass Before Cuts",NDs1pMassBins,Ds1pMassLo,Ds1pMassHi,"Ds1p Cand. Mass (GeV/c^{2})","Entries/1MeV");
  HDs1pMassPreCuts.SetLineColor(1);

  TH1F HDs1pMassPID;
  SetHistoXY(&HDs1pMassPID,"D'_{s1} Mass After Cuts",NDs1pMassBins,Ds1pMassLo,Ds1pMassHi,"Ds1p Cand. Mass (GeV/c^{2})","Entries/1MeV");
  HDs1pMassPID.SetLineColor(1);

  TH1F HDs1pMass;
  SetHistoXY(&HDs1pMass,"D'_{s1} Mass After Cuts",NDs1pMassBins,Ds1pMassLo,Ds1pMassHi,"Ds1p Cand. Mass (GeV/c^{2})","Entries/1MeV");
  HDs1pMass.SetLineColor(1);
  
  TH1F HDs1pMassSignal;
  SetHistoXY(&HDs1pMassSignal,"D'_{s1} Mass After Cuts",NDs1pMassBins,Ds1pMassLo,Ds1pMassHi,"Ds1p Cand. Mass (GeV/c^{2})","Entries/1MeV");
  HDs1pMassSignal.SetLineColor(1);

  TH1F HDs1pMassTruthMatched;
  SetHistoXY(&HDs1pMassTruthMatched,"D'_{s1} Mass After Cuts and Truth Matched",NDs1pMassBins,Ds1pMassLo,Ds1pMassHi,"Ds1p Cand. Mass (GeV/c^{2})","Entries/1MeV");
  HDs1pMassTruthMatched.SetLineColor(1);

  
  Float_t Ds1pp3CMmax=8;
  Float_t Ds1pp3CMmin=0;
  Int_t Ds1pp3CMNbins=80;
  if(TruthMatch){
    Ds1pp3CMmax=5;
    Ds1pp3CMmin=0;
    Ds1pp3CMNbins=50;
  }
  
  TH1F HDs1pp3CMPreCuts;
  SetHistoXY(&HDs1pp3CMPreCuts,"D's1 CM Momentum ",Ds1pp3CMNbins,Ds1pp3CMmin,Ds1pp3CMmax,"p* (GeV/c)","Entries/100MeV");

  TH1F HDs1pp3CM;
  SetHistoXY(&HDs1pp3CM,"D's1 CM Momentum ",Ds1pp3CMNbins,Ds1pp3CMmin,Ds1pp3CMmax,"p* (GeV/c)","Entries/100MeV");

  TH1F HDs1pp3CMPIDCut;
  SetHistoXY(&HDs1pp3CMPIDCut,"D's1 CM Momentum ",Ds1pp3CMNbins,Ds1pp3CMmin,Ds1pp3CMmax,"p* (GeV/c)","Entries/100MeV");
  HDs1pp3CMPIDCut.SetLineColor(2);

  TH1F HDs1pp3CMPIDCutD0PCut;
  SetHistoXY(&HDs1pp3CMPIDCutD0PCut,"D's1 CM Momentum ",Ds1pp3CMNbins,Ds1pp3CMmin,Ds1pp3CMmax,"p* (GeV/c)","Entries/100MeV");
  HDs1pp3CMPIDCutD0PCut.SetLineColor(3);

  TH1F HDs1pp3CMPIDCutD0PCutDeltaMCut;
  SetHistoXY(&HDs1pp3CMPIDCutD0PCutDeltaMCut,"D's1 CM Momentum ",Ds1pp3CMNbins,Ds1pp3CMmin,Ds1pp3CMmax,"p* (GeV/c)","Entries/100MeV");
  HDs1pp3CMPIDCutD0PCutDeltaMCut.SetLineColor(4);

  TH1F HDs1pp3CMPIDCutD0PCutDeltaMCutD0Probab;
  SetHistoXY(&HDs1pp3CMPIDCutD0PCutDeltaMCutD0Probab,"D's1 CM Momentum ",Ds1pp3CMNbins,Ds1pp3CMmin,Ds1pp3CMmax,"p* (GeV/c)","Entries/100MeV");
  HDs1pp3CMPIDCutD0PCutDeltaMCutD0Probab.SetLineColor(6);    


  TH1F HDs1pcosthCMPreCuts;
  SetHistoXY(&HDs1pcosthCMPreCuts,"D's1 Angular Distribution  ",100,-1,1,"cos(#theta)*","Entries/.02");

  TH1F HDs1pcosthCM;
  SetHistoXY(&HDs1pcosthCM,"D's1 Angular Distribution  ",100,-1,1,"cos(#theta)*","Entries/.02");

  TH1F HDs1pcosthCMPIDCut;
  SetHistoXY(&HDs1pcosthCMPIDCut,"D's1 Angular Distribution  ",100,-1,1,"cos(#theta)*","Entries/.02");
  HDs1pcosthCMPIDCut.SetLineColor(2);

  TH1F HDs1pcosthCMPIDCutD0PCut;
  SetHistoXY(&HDs1pcosthCMPIDCutD0PCut,"D's1 Angular Distribution  ",100,-1,1,"cos(#theta)*","Entries/.02");
  HDs1pcosthCMPIDCutD0PCut.SetLineColor(3);

  TH1F HDs1pcosthCMPIDCutD0PCutDeltaMCut;
  SetHistoXY(&HDs1pcosthCMPIDCutD0PCutDeltaMCut,"D's1 Angular Distribution  ",100,-1,1,"cos(#theta)*","Entries/.02");
  HDs1pcosthCMPIDCutD0PCutDeltaMCut.SetLineColor(4);

  TH1F HDs1pcosthCMPIDCutD0PCutDeltaMCutD0Probab;
  SetHistoXY(&HDs1pcosthCMPIDCutD0PCutDeltaMCutD0Probab,"D's1 Angular Distribution  ",100,-1,1,"cos(#theta)*","Entries/.02");
  HDs1pcosthCMPIDCutD0PCutDeltaMCutD0Probab.SetLineColor(6);
    
  TH2F H2Ds1pCMPvsTheta;
  SetHisto2D(&H2Ds1pCMPvsTheta," #theta* vs  p* ",Ds1pp3CMNbins,Ds1pp3CMmin,Ds1pp3CMmax,"p* (GeV/c)",100,-1,1,"cos(#theta)*","entries/(.01x100MeV)");


  /////////MC 
  TH1F HMCDs1pMass;
  SetHistoXY(&HMCDs1pMass,"MC D's1 Mass",NDs1pMassBins,Ds1pMassLo,Ds1pMassHi,"Ds1p Cand. Mass (GeV/c^{2})","Entries/1MeV");

  TH1F HMCDs1pp3CM;
  SetHistoXY(&HMCDs1pp3CM,"MC D's1 Momentum ",Ds1pp3CMNbins,Ds1pp3CMmin,Ds1pp3CMmax,"p* (GeV/c)","Entries/100MeV");

  TH1F HMCDs1pcosthCM;
  SetHistoXY(&HMCDs1pcosthCM,"MC D's1 Angular Distribution ",100,-1,1,"cos(#theta)*","Entries/.02");
  
  TH2F H2MCDs1pCMPvsTheta;
  SetHisto2D(&H2MCDs1pCMPvsTheta,"MC  #theta* vs p* ",Ds1pp3CMNbins,Ds1pp3CMmin,Ds1pp3CMmax,"p* (GeV/c)",100,-1,1,"cos(#theta*)","entries/(.02x100MeV)");


  TH1F HMCNDs1p;
  SetHistoXY(&HMCNDs1p,"MC Number of D's1 Generated",10,-.5,10.5,"nDs1p/event","Counts");
 
  //check particle id 
  TH1F HLundCheck;SetHisto(&HLundCheck,"Lund Id Check",15,-.5,14.5,"ParticleLund - LundExp");

  ////////+++++++++Important
  // Dstard1=D0,Dstard2=Pi;D0d1=K;D0d2=Pi
  //Lunds:

    
  
  //Start the event loop;
  Int_t eventid=0;
  while(fChain->GetEntry(eventid,0)>0){   
    eventid++;
    if(eventid%5000==0)cout<<eventid<<" Events done."<<endl;    
           
    HBeamRadius.Fill(sqrt( beamSX*beamSX + beamSY*beamSY));
    HBeamZ.Fill(beamSZ);     
         
    if(nDs1p>400){cout<<"Too many cands at event"<<eventid<<endl;continue;}
    ///Loop over the reconstructed
    Ds1pIdx=-1;
    while( Ds1pIdx< nDs1p-1){
      Ds1pIdx++;

      ////For Monte Carlo decide to analyze matter or antimatter
      if(!(Ds1pLund[Ds1pIdx]==MatterOrAntiMatter*myDs1pLund || MatterOrAntiMatter==0))continue;

      //Check that Im using proper indexes
      if(Mode=="D0ToKPi"||Mode=="D0ToK3Pi"){
	KsIdx=Ds1pd2Idx[Ds1pIdx];  
	KsPi1Idx=Ksd1Idx[KsIdx];
	KsPi2Idx=Ksd2Idx[KsIdx];    
	DstarIdx=Ds1pd1Idx[Ds1pIdx];
	SlowPiIdx=Dstard2Idx[DstarIdx];
	D0Idx=Dstard1Idx[DstarIdx];
	PiIdx=D0d2Idx[D0Idx];
	KIdx=D0d1Idx[D0Idx];

	PitrkIdx=PiTrkIdx[PiIdx];
	SlowPitrkIdx=PiTrkIdx[SlowPiIdx];
	KsPi1trkIdx=PiTrkIdx[KsPi1Idx];
	KsPi2trkIdx=PiTrkIdx[KsPi2Idx];

	if(abs(Dstard1Lund[DstarIdx]-D0Lund[D0Idx])>0)HLundCheck.Fill(1);
	else if(abs(Dstard2Lund[DstarIdx]-PiLund[SlowPiIdx])>0)HLundCheck.Fill(2);
	else if(abs(D0d1Lund[D0Idx]-KLund[KIdx])>0)HLundCheck.Fill(3);
	else if(abs(D0d2Lund[D0Idx]-PiLund[PiIdx])>0)HLundCheck.Fill(4);
	else if(abs(TRKLund[SlowPitrkIdx]-PiLund[SlowPiIdx])>0)HLundCheck.Fill(5);
	else if(abs(TRKLund[PitrkIdx]-PiLund[PiIdx])>0)HLundCheck.Fill(6);
	else if(abs(Ds1pd1Lund[Ds1pIdx]-DstarLund[DstarIdx])>0)HLundCheck.Fill(7);
	else if(abs(Ds1pd2Lund[Ds1pIdx]-KsLund[KsIdx])>0)HLundCheck.Fill(8);
	else if(abs(TRKLund[KsPi1trkIdx]-PiLund[KsPi1Idx])>0)HLundCheck.Fill(9);
	else if(abs(TRKLund[KsPi2trkIdx]-PiLund[KsPi2Idx])>0)HLundCheck.Fill(10);
	else if(abs(Ksd1Lund[KsIdx]-PiLund[KsPi1Idx])>0)HLundCheck.Fill(11);
	else if(abs(Ksd2Lund[KsIdx]-PiLund[KsPi2Idx])>0)HLundCheck.Fill(12);	
	else HLundCheck.Fill(0);
      }      


      if(Mode=="D0ToKPiPi0"){
	KsIdx=Ds1pd2Idx[Ds1pIdx]; 
	KsPi1Idx=Ksd1Idx[KsIdx];
	KsPi2Idx=Ksd2Idx[KsIdx]; 
	DstarIdx=Ds1pd1Idx[Ds1pIdx];
   	SlowPiIdx=Dstard2Idx[DstarIdx];
	D0Idx=Dstard1Idx[DstarIdx];
	PiIdx=D0d2Idx[D0Idx];
	KIdx=D0d1Idx[D0Idx];
	Pi0Idx=D0d3Idx[D0Idx];
	GammaIdx=Pi0d1Idx[Pi0Idx];

	PitrkIdx=PiTrkIdx[PiIdx];
	SlowPitrkIdx=PiTrkIdx[SlowPiIdx];
	KsPi1trkIdx=PiTrkIdx[KsPi1Idx];
	KsPi2trkIdx=PiTrkIdx[KsPi2Idx];


	if(abs(Dstard1Lund[DstarIdx]-D0Lund[D0Idx])>0)HLundCheck.Fill(1);
	else if(abs(Dstard2Lund[DstarIdx]-PiLund[SlowPiIdx])>0)HLundCheck.Fill(2);
	else if(abs(D0d1Lund[D0Idx]-KLund[KIdx])>0)HLundCheck.Fill(3);
	else if(abs(D0d2Lund[D0Idx]-PiLund[PiIdx])>0)HLundCheck.Fill(4);
	else if(abs(TRKLund[SlowPitrkIdx]-PiLund[SlowPiIdx])>0)HLundCheck.Fill(5);
	else if(abs(TRKLund[PitrkIdx]-PiLund[PiIdx])>0)HLundCheck.Fill(6);
	else if(abs(Ds1pd1Lund[Ds1pIdx]-DstarLund[DstarIdx])>0)HLundCheck.Fill(7);
	else if(abs(Ds1pd2Lund[Ds1pIdx]-KsLund[KsIdx])>0)HLundCheck.Fill(8);
	else if(abs(TRKLund[KsPi1trkIdx]-PiLund[KsPi1Idx])>0)HLundCheck.Fill(9);
	else if(abs(TRKLund[KsPi2trkIdx]-PiLund[KsPi2Idx])>0)HLundCheck.Fill(10);
	else if(abs(Ksd1Lund[KsIdx]-PiLund[KsPi1Idx])>0)HLundCheck.Fill(11);
	else if(abs(Ksd2Lund[KsIdx]-PiLund[KsPi2Idx])>0)HLundCheck.Fill(12);
	else if(abs(D0d3Lund[D0Idx]-Pi0Lund[Pi0Idx])>0)HLundCheck.Fill(13);
	else if(abs(Pi0d1Lund[Pi0Idx]-GammaLund[GammaIdx])>0)HLundCheck.Fill(14);	
	else HLundCheck.Fill(0);

      }


      ///compute some quantities
      D0Probab=TMath::Prob(D0Chi2[D0Idx],D0nDof[D0Idx]);     
      KsProbab=TMath::Prob(KsChi2[D0Idx],KsnDof[D0Idx]);     
         
      Ksp3Direction.SetXYZ(sin(acos(Kscosth[KsIdx]))*cos(Ksphi[KIdx]),
			   sin(acos(Kscosth[KsIdx]))*sin(Ksphi[KIdx]),
			   Kscosth[KsIdx]); 
      KsFlightDirection.SetXYZ(KsVtxx[KsIdx]-Ds1pVtxx[Ds1pIdx],
			       KsVtxy[KsIdx]-Ds1pVtxy[Ds1pIdx],
			       KsVtxz[KsIdx]-Ds1pVtxz[Ds1pIdx]);
      KsCosine=Ksp3Direction*KsFlightDirection/KsFlightDirection.Mag();

      ///Fill Distributions  
      if(Mode=="D0ToKPiPi0"){        
	HPi0MassPreCuts.Fill(Pi0Mass[Pi0Idx]);  
      }

      HD0p3CM.Fill(D0p3CM[D0Idx]);
      HD0MassPreCuts.Fill(D0Mass[D0Idx]);
      HD0Probab.Fill(log(D0Probab));

      HDstarMassPreCuts.Fill(DstarMass[DstarIdx]);   

      HKsMassPreCuts.Fill(KsMass[KsIdx]);
      HKsProbab.Fill(log(KsProbab));
      HKsCosine.Fill(KsCosine);

      HDs1pMassPreCuts.Fill(Ds1pMass[Ds1pIdx]);  


      //Apply Cuts       
      //     if((PiSelectorsMap[KsPi1trkIdx] & (1<<4) ) != 0 && (PiSelectorsMap[KsPi2trkIdx] & (1<<4) ) != 0){
      //	HDs1pMassPID.Fill(Ds1pMass[Ds1pIdx]);

      if(D0p3CM[D0Idx] > D0p3CMCut){
	if(D0Probab > D0ProbabCut){
	  if(KsProbab > KsProbabCut && KsCosine>KsCosineCut){

	    HDs1pMass.Fill(Ds1pMass[Ds1pIdx]);

	    ///Fill histograms only for the signal region of Ds1p
	    if(Ds1pMassCutLo<Ds1pMass[Ds1pIdx]&&Ds1pMass[Ds1pIdx]<Ds1pMassCutHi){

	      HDs1pMassSignal.Fill(Ds1pMass[Ds1pIdx]);
	      if(Ds1pMCIdx[Ds1pIdx]>0){
		HDs1pMassTruthMatched.Fill(Ds1pMass[Ds1pIdx]); 	
		HDs1pp3CM.Fill(Ds1pp3CM[Ds1pIdx]); 
		HDs1pcosthCM.Fill(Ds1pcosthCM[Ds1pIdx]); 		  
		H2Ds1pCMPvsTheta.Fill(Ds1pp3CM[Ds1pIdx],Ds1pcosthCM[Ds1pIdx]);	
	      }	  
	  
	      HKsMass.Fill(KsMass[KsIdx]);	   
	      if(KsMCIdx[KsIdx]>0){
		HKsMassTruthMatched.Fill(KsMass[KsIdx]); 		
	      }
	  
	      HPi1Momentum.Fill(Pip3[KsPi1Idx]);
	      if(PiMCIdx[KsPi1Idx]>0)
		HPi1MomentumTruthMatched.Fill(Pip3[KsPi1Idx]);	

	      HDstarMass.Fill(DstarMass[DstarIdx]); 		  
	      if(DstarMCIdx[DstarIdx]>0){
		HDstarMassTruthMatched.Fill(DstarMass[DstarIdx]); 		
	      }	  
	      HMassDiff.Fill(DstarMass[DstarIdx]-D0Mass[D0Idx]);   

	  
	      HD0Mass.Fill(D0Mass[D0Idx]); 
	      if(D0MCIdx[D0Idx]>0)
		HD0MassTruthMatched.Fill(D0Mass[D0Idx]); 

	      HSlowPiMomentum.Fill(Pip3[SlowPiIdx]);	
	      if(PiMCIdx[SlowPiIdx]>0)
		HSlowPiMomentumTruthMatched.Fill(Pip3[SlowPiIdx]);	    

	      HKMomentum.Fill(Kp3[KIdx]);
	      if(KMCIdx[KIdx]>0)
		HKMomentumTruthMatched.Fill(Kp3[KIdx]);

	      HPiMomentum.Fill(Pip3[PiIdx]);
	      if(PiMCIdx[PiIdx]>0)
		HPiMomentumTruthMatched.Fill(Pip3[PiIdx]);	

	      if(Mode=="D0ToKPiPi0"){ 
		HGammaEnergy.Fill(GammaECal[GammaIdx]);
		if(GammaMCIdx[GammaIdx]>0)
		  HGammaEnergyTruthMatched.Fill(GammaECal[GammaIdx]);

		HPi0Mass.Fill(Pi0Mass[Pi0Idx]);
		if(Pi0MCIdx[Pi0Idx]>0)
		  HPi0MassTruthMatched.Fill(Pi0Mass[Pi0Idx]);
	      }
	 

	      RecoDs1pCounterTotal++;
	    }//signal region
	  }//Ks Cuts
	}//D0Probab Cut     
      }//D0 p* cut  
      
    }//Ds1p loop
	 

    //now loop over MC    
    MCDs1pCounterPerEvent=0; 
    Int_t mcid=-1;
    while(mcid<mcLen){
      mcid++;

      if(mcLund[mcid]==MatterOrAntiMatter*myDs1pLund){
	MCDs1pCounterPerEvent++; 
	MCDs1pCounterTotal++;
		
	HMCDs1pMass.Fill(mcmass[mcid]);
	HMCDs1pp3CM.Fill(mcp3CM[mcid]); 
	HMCDs1pcosthCM.Fill(mccosthCM[mcid]); 	
	H2MCDs1pCMPvsTheta.Fill(mcp3CM[mcid],mccosthCM[mcid]);
      }
    }
    HMCNDs1p.Fill(MCDs1pCounterPerEvent);
        
  }

  //print summary
  cout<<"--------Summary-------"<<endl;
  cout<<"Total events="<<eventid<<endl;
  cout<<"Total Generated="<<MCDs1pCounterTotal<<" Reconstructed="<<RecoDs1pCounterTotal<<endl;
  cout<<"--------End Summary---"<<endl;

 
  ////Save histograms
  TString filename;
  filename=NtupleDir+"/"+"Plots.ps";
  TCanvas Canvas(filename,filename);
  Canvas.Print(filename+"[");

  TLine cutline;
  cutline.SetLineColor(2);

  //beam
  Canvas.Clear();
  HBeamRadius.Draw();
  Canvas.Print(filename);
  Canvas.Clear();
  HBeamZ.Draw();
  Canvas.Print(filename);    

  ///The Kaon 
  Canvas.Clear();
  HKMomentum.Draw();
  Canvas.Print(filename);
  TH1F* HKMomentumTruthDifference=(TH1F*)HKMomentum.Clone();
  HKMomentumTruthDifference->Add(&HKMomentumTruthMatched,-1.);
  HKMomentumTruthDifference->SetTitle("Truth Difference");
  HKMomentumTruthDifference->Draw();
  Canvas.Print(filename);

  //ThePion
  Canvas.Clear();
  HPiMomentum.Draw();
  Canvas.Print(filename);
  Canvas.Clear();
  TH1F* HPiMomentumTruthDifference=(TH1F*)HPiMomentum.Clone();
  HPiMomentumTruthDifference->Add(&HPiMomentumTruthMatched,-1.);
  HPiMomentumTruthDifference->SetTitle("Truth Difference");
  HPiMomentumTruthDifference->Draw();
  Canvas.Print(filename);

  
  if(Mode=="D0ToKPiPi0"){ 
    ///Gamma
    Canvas.Clear();
    HGammaEnergy.Draw();
    Canvas.Print(filename);
    Canvas.Clear();
    TH1F* HGammaEnergyTruthDifference=(TH1F*)HGammaEnergy.Clone();
    HGammaEnergyTruthDifference->Add(&HGammaEnergyTruthMatched,-1.);
    HGammaEnergyTruthDifference->SetTitle("Truth Difference");
    HGammaEnergyTruthDifference->Draw();
    Canvas.Print(filename);

    //The Pi0
    Canvas.Clear();
    HPi0MassPreCuts.GetYaxis()->SetRangeUser(0,1.05*HPi0MassPreCuts.GetMaximum());
    HPi0MassPreCuts.Draw();
    HPi0Mass.Draw("same");
    Canvas.Print(filename);
    Canvas.Clear();
    TH1F* HPi0MassTruthDifference=(TH1F*)HPi0Mass.Clone();
    HPi0MassTruthDifference->Add(&HPi0MassTruthMatched,-1.);
    HPi0MassTruthDifference->SetTitle("Truth Difference");
    HPi0MassTruthDifference->Draw();
    Canvas.Print(filename);

  }

  //The D0 
  Canvas.Clear();
  HD0p3CM.Draw();
  cutline.DrawLine(D0p3CMCut,0,D0p3CMCut, HD0p3CM.GetMaximum());
  Canvas.Print(filename);
  Canvas.Clear();
  HD0MassPreCuts.GetYaxis()->SetRangeUser(0,1.05*HD0MassPreCuts.GetMaximum());
  HD0MassPreCuts.Draw();
  HD0Mass.Draw("same");
  Canvas.Print(filename);
  Canvas.Clear();
  TH1F* HD0MassTruthDifference=(TH1F*)HD0Mass.Clone();
  HD0MassTruthDifference->Add(&HD0MassTruthMatched,-1.);
  HD0MassTruthDifference->SetTitle("Truth Difference");
  HD0MassTruthDifference->Draw();
  Canvas.Print(filename);

  ///The Slow Pion
  Canvas.Clear();
  HSlowPiMomentum.Draw();
  Canvas.Print(filename);
  Canvas.Clear();
  TH1F* HSlowPiMomentumTruthDifference=(TH1F*)HSlowPiMomentum.Clone();
  HSlowPiMomentumTruthDifference->Add(&HSlowPiMomentumTruthMatched,-1.);
  HSlowPiMomentumTruthDifference->SetTitle("Truth Difference");
  HSlowPiMomentumTruthDifference->Draw();
  Canvas.Print(filename);


  ///The Dstar
  Canvas.Clear();
  HDstarMassPreCuts.GetYaxis()->SetRangeUser(0,1.05*HDstarMassPreCuts.GetMaximum());
  HDstarMassPreCuts.Draw();
  HDstarMass.Draw("same");
  //HDstarMassTruthMatched.Draw("same");
  Canvas.Print(filename); 
  Canvas.Clear();
  TH1F* HDstarMassTruthDifference=(TH1F*)HDstarMass.Clone();
  HDstarMassTruthDifference->Add(&HDstarMassTruthMatched,-1.);
  HDstarMassTruthDifference->SetTitle("Truth Difference");
  HDstarMassTruthDifference->Draw();
  Canvas.Print(filename);
  Canvas.Clear();
  HMassDiff.Draw();
  Canvas.Print(filename);


  //Pi1 and Pi2
  Canvas.Clear();
  HPi1Momentum.Draw();
  Canvas.Print(filename);
  Canvas.Clear();
  TH1F* HPi1MomentumTruthDifference=(TH1F*)HPi1Momentum.Clone();
  HPi1MomentumTruthDifference->Add(&HPi1MomentumTruthMatched,-1.);
  HPi1MomentumTruthDifference->SetTitle("Truth Difference");
  HPi1MomentumTruthDifference->Draw();
  Canvas.Print(filename);


  //Ks  
  Canvas.Clear();
  HKsProbab.Draw();
  Canvas.Print(filename); 
  Canvas.Clear();
  Canvas.SetLogy(1);
  HKsCosine.Draw();
  Canvas.Print(filename); 
  Canvas.SetLogy(0);
  Canvas.Clear();
  HKsMassPreCuts.GetYaxis()->SetRangeUser(0,1.05*HKsMassPreCuts.GetMaximum());
  HKsMassPreCuts.Draw();
  HKsMass.Draw("same");  
  //HKsMassTruthMatched.Draw("same");
  Canvas.Print(filename); 
  Canvas.Clear();
  TH1F* HKsMassTruthDifference=(TH1F*)HKsMass.Clone();
  HKsMassTruthDifference->Add(&HKsMassTruthMatched,-1.);
  HKsMassTruthDifference->SetTitle("Truth Difference");
  HKsMassTruthDifference->Draw();
  Canvas.Print(filename);


  //Ds1p
  Canvas.Clear();
  HDs1pMassPreCuts.GetYaxis()->SetRangeUser(0,1.05*HDs1pMassPreCuts.GetMaximum());
  HDs1pMassPreCuts.Draw();
  HDs1pMassPID.Draw("same");  
  HDs1pMass.Draw("same");
  cutline.DrawLine(Ds1pMassCutLo,0,Ds1pMassCutLo,HDs1pMass.GetMaximum());
  cutline.DrawLine(Ds1pMassCutHi,0,Ds1pMassCutHi,HDs1pMass.GetMaximum());  
  Canvas.Print(filename); 
  Canvas.Clear();
  Canvas.Divide(2,2);
  Canvas.cd(1);
  HDs1pMassSignal.Draw();
  HDs1pMassTruthMatched.Draw("same");
  Canvas.cd(2);
  TH1F* HDs1pMassTruthDifference=(TH1F*)HDs1pMassSignal.Clone();
  HDs1pMassTruthDifference->Add(&HDs1pMassTruthMatched,-1.);
  HDs1pMassTruthDifference->SetTitle("Truth Difference");
  HDs1pMassTruthDifference->Draw();
  Canvas.cd(3);
  TH1F* HDs1pMassTruthRatio=(TH1F*)HDs1pMassTruthMatched.Clone();
  HDs1pMassTruthRatio->Divide(&HDs1pMassSignal);
  HDs1pMassTruthRatio->SetTitle("Truth Ratio"); 
  HDs1pMassTruthRatio->GetYaxis()->SetTitle("TruthMatched/Reconstructed");
  HDs1pMassTruthRatio->Draw();
  Canvas.Print(filename);


  Canvas.Clear();
  if(TruthMatch){
    HMCDs1pp3CM.GetYaxis()->SetRangeUser(0,1.05*HMCDs1pp3CM.GetMaximum());
    HMCDs1pp3CM.Draw();  
    HDs1pp3CMPreCuts.Draw("same");
  }else {
    HDs1pp3CMPreCuts.GetYaxis()->SetRangeUser(1,1.05*HDs1pp3CMPreCuts.GetMaximum());
    HDs1pp3CMPreCuts.Draw();
  }       
  HDs1pp3CMPIDCut.Draw("same");
  HDs1pp3CMPIDCutD0PCut.Draw("same");
  HDs1pp3CMPIDCutD0PCutDeltaMCut.Draw("same");
  HDs1pp3CMPIDCutD0PCutDeltaMCutD0Probab.Draw("same");
  HDs1pp3CM.Draw("same");
  Canvas.Print(filename);

  //For bins were MC is less than 100 set efficiency to 0
  for(Int_t bin=0;bin<=HMCDs1pp3CM.GetNbinsX();bin++)
    if(HMCDs1pp3CM.GetBinContent(bin)<100)
      HMCDs1pp3CM.SetBinContent(bin,1e30);  

  Canvas.Clear();  
  TH1F HDs1pp3CMEfficiency0=*(TH1F*)HDs1pp3CMPreCuts.Clone();
  HDs1pp3CMEfficiency0.Divide(&HMCDs1pp3CM);
  HDs1pp3CMEfficiency0.SetTitle("CM Momentum Efficiency");
  HDs1pp3CMEfficiency0.GetYaxis()
    //->SetRangeUser(0,1.05*HDs1pp3CMEfficiency0.GetBinContent(HDs1pp3CMEfficiency0.GetMaximumBin()));
    ->SetRangeUser(0,1);
  HDs1pp3CMEfficiency0.Draw();
//   TH1F HDs1pp3CMEfficiency1=*(TH1F*)HDs1pp3CMPIDCut.Clone();
//   HDs1pp3CMEfficiency1.Divide(&HMCDs1pp3CM);
//   HDs1pp3CMEfficiency1.Draw("same");
//   TH1F HDs1pp3CMEfficiency2=*(TH1F*)HDs1pp3CMPIDCutD0PCut.Clone();
//   HDs1pp3CMEfficiency2.Divide(&HMCDs1pp3CM);
//   HDs1pp3CMEfficiency2.Draw("same");
//   TH1F HDs1pp3CMEfficiency3=*(TH1F*)HDs1pp3CMPIDCutD0PCutDeltaMCut.Clone();
//   HDs1pp3CMEfficiency3.Divide(&HMCDs1pp3CM);
//   HDs1pp3CMEfficiency3.Draw("same");
//   TH1F HDs1pp3CMEfficiency4=*(TH1F*)HDs1pp3CMPIDCutD0PCutDeltaMCutD0Probab.Clone();
//   HDs1pp3CMEfficiency4.Divide(&HMCDs1pp3CM);
//   HDs1pp3CMEfficiency4.Draw("same");  
  TH1F HDs1pp3CMEfficiencyFinal=*(TH1F*)HDs1pp3CM.Clone();
  HDs1pp3CMEfficiencyFinal.Divide(&HMCDs1pp3CM);  
  HDs1pp3CMEfficiencyFinal.Draw("same");
  Canvas.Print(filename);
  
  Canvas.Clear();
  if(TruthMatch){
    HMCDs1pcosthCM.GetYaxis()->SetRangeUser(0,1.05*HMCDs1pcosthCM.GetMaximum());
    HMCDs1pcosthCM.Draw();  
    HDs1pcosthCMPreCuts.Draw("same");
  }else {
    HDs1pcosthCMPreCuts.GetYaxis()->SetRangeUser(1,1.05*HDs1pcosthCMPreCuts.GetMaximum());
    HDs1pcosthCMPreCuts.Draw();
  }       
//   HDs1pcosthCMPIDCut.Draw("same");
//   HDs1pcosthCMPIDCutD0PCut.Draw("same");
//   HDs1pcosthCMPIDCutD0PCutDeltaMCut.Draw("same");
//   HDs1pcosthCMPIDCutD0PCutDeltaMCutD0Probab.Draw("same");
  HDs1pcosthCM.Draw("same");
  Canvas.Print(filename);
  
  Canvas.Clear();  
  TH1F HDs1pcosthCMEfficiency0=*(TH1F*)HDs1pcosthCMPreCuts.Clone();
  HDs1pcosthCMEfficiency0.Divide(&HMCDs1pcosthCM);
  HDs1pcosthCMEfficiency0.SetTitle("Angular Efficiency");
  HDs1pcosthCMEfficiency0.GetYaxis()
    //->SetRangeUser(0,1.05*HDs1pcosthCMEfficiency0.GetBinContent(HDs1pcosthCMEfficiency0.GetMaximumBin()));
    ->SetRangeUser(0,1);
  HDs1pcosthCMEfficiency0.Draw();
//   TH1F HDs1pcosthCMEfficiency1=*(TH1F*)HDs1pcosthCMPIDCut.Clone();
//   HDs1pcosthCMEfficiency1.Divide(&HMCDs1pcosthCM);
//   HDs1pcosthCMEfficiency1.Draw("same");
//   TH1F HDs1pcosthCMEfficiency2=*(TH1F*)HDs1pcosthCMPIDCutD0PCut.Clone();
//   HDs1pcosthCMEfficiency2.Divide(&HMCDs1pcosthCM);
//   HDs1pcosthCMEfficiency2.Draw("same");
//   TH1F HDs1pcosthCMEfficiency3=*(TH1F*)HDs1pcosthCMPIDCutD0PCutDeltaMCut.Clone();
//   HDs1pcosthCMEfficiency3.Divide(&HMCDs1pcosthCM);
//   HDs1pcosthCMEfficiency3.Draw("same");
//   TH1F HDs1pcosthCMEfficiency4=*(TH1F*)HDs1pcosthCMPIDCutD0PCutDeltaMCutD0Probab.Clone();
//   HDs1pcosthCMEfficiency4.Divide(&HMCDs1pcosthCM);
//   HDs1pcosthCMEfficiency4.Draw("same");  
  TH1F HDs1pcosthCMEfficiencyFinal=*(TH1F*)HDs1pcosthCM.Clone();
  HDs1pcosthCMEfficiencyFinal.Divide(&HMCDs1pcosthCM);  
  HDs1pcosthCMEfficiencyFinal.Draw("same");
  Canvas.Print(filename);

  Canvas.Clear();
  H2Ds1pCMPvsTheta.Draw("colz");
  Canvas.Print(filename);
  Canvas.Clear();
  H2MCDs1pCMPvsTheta.Draw("colz");
  Canvas.Print(filename);
  Canvas.Clear();
  //For bins were MC is less than 5 set efficiency to 0
  for(Int_t binx=0;binx<=H2MCDs1pCMPvsTheta.GetNbinsX();binx++)
    for(Int_t biny=0;biny<=H2MCDs1pCMPvsTheta.GetNbinsY();biny++)
      if(H2MCDs1pCMPvsTheta.GetBinContent(binx,biny)<20)
	H2MCDs1pCMPvsTheta.SetBinContent(binx,biny,1e30); 

  TH2F H2Ds1pPvsThetaEfficiency=*(TH2F*)H2Ds1pCMPvsTheta.Clone();
  H2Ds1pPvsThetaEfficiency.Divide(&H2MCDs1pCMPvsTheta);
  H2Ds1pPvsThetaEfficiency.SetTitle("D* Efficiency");
  H2Ds1pPvsThetaEfficiency.GetZaxis()->SetTitle("efficiency");
  H2Ds1pPvsThetaEfficiency.SetTitleOffset(.68,"Z");
  H2Ds1pPvsThetaEfficiency.SetStats(kFALSE);
  H2Ds1pPvsThetaEfficiency.Draw("colz");
  Canvas.Print(filename);





  ///Make plot of TruthMatched vs particle: 
  Float_t KTruthRatio=0;
  Float_t PiTruthRatio=0;
  Float_t GammaTruthRatio=0;
  Float_t Pi0TruthRatio=0;
  Float_t D0TruthRatio=0;
  Float_t SlowPiTruthRatio=0;
  Float_t DstarTruthRatio=0;
  Float_t Pi1TruthRatio=0;
  Float_t KsTruthRatio=0;
  Float_t Ds1pTruthRatio=0;

  if(HKMomentum.Integral()>0) KTruthRatio=HKMomentumTruthMatched.Integral()/HKMomentum.Integral();
  if(HPiMomentum.Integral()>0) PiTruthRatio=HPiMomentumTruthMatched.Integral()/HPiMomentum.Integral();
  if(HGammaEnergy.Integral()>0) GammaTruthRatio=HPiMomentumTruthMatched.Integral()/HPiMomentum.Integral();
  if(HPi0Mass.Integral()>0) Pi0TruthRatio=HPi0MassTruthMatched.Integral()/HPi0Mass.Integral();
  if(HD0Mass.Integral()>0) D0TruthRatio=HD0MassTruthMatched.Integral()/HD0Mass.Integral();
  if(HSlowPiMomentum.Integral()>0) SlowPiTruthRatio=HSlowPiMomentumTruthMatched.Integral()/HSlowPiMomentum.Integral();
  if(HDstarMass.Integral()>0) DstarTruthRatio=HDstarMassTruthMatched.Integral()/HDstarMass.Integral();
  if(HPi1Momentum.Integral()>0) Pi1TruthRatio=HPi1MomentumTruthMatched.Integral()/HPi1Momentum.Integral();
  if(HKsMass.Integral()>0) KsTruthRatio=HKsMassTruthMatched.Integral()/HKsMass.Integral();
  if(HDs1pMass.Integral()>0) Ds1pTruthRatio=HDs1pMassTruthMatched.Integral()/HDs1pMassSignal.Integral();
  

  TH1F HTruthRatioVsParticle;
  SetHistoXY(&HTruthRatioVsParticle,"Truth Match Ratios",10,.5,10.5,"Particle Type","TruthMatched/Reconstructed");
  HTruthRatioVsParticle.SetBinContent(1,KTruthRatio);
  HTruthRatioVsParticle.SetBinContent(2,PiTruthRatio);
  HTruthRatioVsParticle.SetBinContent(3,GammaTruthRatio);
  HTruthRatioVsParticle.SetBinContent(4,Pi0TruthRatio); 
  HTruthRatioVsParticle.SetBinContent(5,D0TruthRatio);
  HTruthRatioVsParticle.SetBinContent(6,SlowPiTruthRatio);
  HTruthRatioVsParticle.SetBinContent(7,DstarTruthRatio); 
  HTruthRatioVsParticle.SetBinContent(8,PiTruthRatio);   
  HTruthRatioVsParticle.SetBinContent(9,KsTruthRatio); 
  HTruthRatioVsParticle.SetBinContent(10,Ds1pTruthRatio); 
  HTruthRatioVsParticle.GetYaxis()->SetRangeUser(0,1);
  HTruthRatioVsParticle.SetStats(kFALSE);
  HTruthRatioVsParticle.SetBarWidth(.9);
  
  TText text;
  text.SetTextSize(.03);

  Canvas.Clear();
  HTruthRatioVsParticle.Draw("b");
  text.DrawText(1-.2,.1,"K");
  text.DrawText(2-.2,.1,"Pi");
  text.DrawText(3-.4,.1,"Gamma");
  text.DrawText(4-.2,.1,"Pi0");
  text.DrawText(5-.2,.1,"D0");
  text.DrawText(6-.4,.1,"SlowPi");
  text.DrawText(7-.2,.1,"D*");
  text.DrawText(8-.2,.1,"Pi1");
  text.DrawText(9-.2,.1,"Ks");
  text.DrawText(10-.2,.1,"Ds1");
  text.DrawText(1-.35,KTruthRatio*.9,TString("")+long(100*KTruthRatio)+"."+long(1000*KTruthRatio)%10+"%");
  text.DrawText(2-.35,PiTruthRatio*.9,TString("")+long(100*PiTruthRatio)+"."+long(1000*PiTruthRatio)%10+"%");
  text.DrawText(3-.35,GammaTruthRatio*.9,TString("")+long(100*GammaTruthRatio)+"."+long(1000*GammaTruthRatio)%10+"%");
  text.DrawText(4-.35,Pi0TruthRatio*.9,TString("")+long(100*Pi0TruthRatio)+"."+long(1000*Pi0TruthRatio)%10+"%");
  text.DrawText(5-.35,D0TruthRatio*.9,TString("")+long(100*D0TruthRatio)+"."+long(1000*D0TruthRatio)%10+"%");
  text.DrawText(6-.35,SlowPiTruthRatio*.9,TString("")+long(100*SlowPiTruthRatio)+"."+long(1000*SlowPiTruthRatio)%10+"%");
  text.DrawText(7-.35,DstarTruthRatio*.9,TString("")+long(100*DstarTruthRatio)+"."+long(1000*DstarTruthRatio)%10+"%");
  text.DrawText(8-.35,Pi1TruthRatio*.9,TString("")+long(100*Pi1TruthRatio)+"."+long(1000*Pi1TruthRatio)%10+"%");
  text.DrawText(9-.35,KsTruthRatio*.9,TString("")+long(100*KsTruthRatio)+"."+long(1000*KsTruthRatio)%10+"%");
  text.DrawText(10-.35,Ds1pTruthRatio*.9,TString("")+long(100*Ds1pTruthRatio)+"."+long(1000*Ds1pTruthRatio)%10+"%");
  Canvas.Print(filename);

  Canvas.Clear(); 
  HLundCheck.SetBarOffset(0);
  HLundCheck.SetBarWidth(.05);
  HLundCheck.Draw();
  Canvas.Print(filename);
   

  Canvas.Print(filename+"]");  
  return (TH1F*) HMassDiff.Clone(); 
}
示例#17
0
void ElectronTagAndProbeMC(const string dataInputFilename, const string Label, 
                           Int_t ChargeSelection = 0) {   

  gBenchmark->Start("ElectronTagAndProbe");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  string label = Label;
  if (Label != "") label = "_" + label;

  Double_t lumi;              // luminosity (pb^-1)
    

  //********************************************************
  // Define Bins
  //********************************************************
  vector<string> ptbinLabel;
  vector<Double_t> ptbinLowEdge;
  vector<Double_t> ptbinUpEdge;
   ptbinLabel.push_back("Pt20ToInf"); ptbinLowEdge.push_back(20.0); ptbinUpEdge.push_back(14000.0);
//   ptbinLabel.push_back("Pt10To15"); ptbinLowEdge.push_back(10.0); ptbinUpEdge.push_back(15.0);
//   ptbinLabel.push_back("Pt15To20"); ptbinLowEdge.push_back(15.0); ptbinUpEdge.push_back(20.0);
//   ptbinLabel.push_back("Pt20To30"); ptbinLowEdge.push_back(20.0); ptbinUpEdge.push_back(30.0);
//   ptbinLabel.push_back("Pt30To40"); ptbinLowEdge.push_back(30.0); ptbinUpEdge.push_back(40.0);
//   ptbinLabel.push_back("Pt40To50"); ptbinLowEdge.push_back(40.0); ptbinUpEdge.push_back(50.0);
//   ptbinLabel.push_back("Pt50ToInf"); ptbinLowEdge.push_back(50.0); ptbinUpEdge.push_back(14000.0);
  vector<string> etabinLabel;
  vector<Double_t> etabinLowEdge;
  vector<Double_t> etabinUpEdge;
  etabinLabel.push_back("EE"); etabinLowEdge.push_back(1.5); etabinUpEdge.push_back(2.5);
  etabinLabel.push_back("EB"); etabinLowEdge.push_back(0); etabinUpEdge.push_back(1.5);
  vector<string> chargebinLabel;
  vector<Double_t> chargeSelection;
  chargebinLabel.push_back("All");  chargeSelection.push_back(0);
  chargebinLabel.push_back("Plus"); chargeSelection.push_back(1);
  chargebinLabel.push_back("Minus"); chargeSelection.push_back(-1);
  vector<vector<vector<Double_t> > > EventCount_TagPlusRecoFailWWTightIdIso_binned;
  vector<vector<vector<Double_t> > > EventCount_TagPlusRecoPassWWTightIdIso_binned;
  vector<vector<vector<Double_t> > > EventCount_TagPlusWWTightIdIsoPassHLT_binned;
  vector<vector<vector<Double_t> > > EventCount_TagPlusWWTightIdIsoFailHLT_binned;
  for (int k=0; k < chargebinLabel.size(); ++k) {
    vector<vector<Double_t> > tmp_tmp_EventCount_TagPlusRecoFailWWTightIdIso_binned;
    vector<vector<Double_t> > tmp_tmp_EventCount_TagPlusRecoPassWWTightIdIso_binned;
    vector<vector<Double_t> > tmp_tmp_EventCount_TagPlusWWTightIdIsoPassHLT_binned;
    vector<vector<Double_t> > tmp_tmp_EventCount_TagPlusWWTightIdIsoFailHLT_binned;    
    
    for (int i=0; i < etabinLabel.size(); ++i) {
      vector<Double_t> tmp_EventCount_TagPlusRecoFailWWTightIdIso_binned;
      vector<Double_t> tmp_EventCount_TagPlusRecoPassWWTightIdIso_binned;
      vector<Double_t> tmp_EventCount_TagPlusWWTightIdIsoPassHLT_binned;
      vector<Double_t> tmp_EventCount_TagPlusWWTightIdIsoFailHLT_binned;    
      
      for (int j=0; j < ptbinLabel.size(); ++j) {
        Double_t tmp_EventCount_TagPlusRecoFailWWTightIdIso = 0;
        tmp_EventCount_TagPlusRecoFailWWTightIdIso_binned.push_back(tmp_EventCount_TagPlusRecoFailWWTightIdIso);
        
        Double_t tmp_EventCount_TagPlusRecoPassWWTightIdIso = 0;
        tmp_EventCount_TagPlusRecoPassWWTightIdIso_binned.push_back(tmp_EventCount_TagPlusRecoPassWWTightIdIso);
        
        Double_t tmp_EventCount_TagPlusWWTightIdIsoFailHLT = 0;
        tmp_EventCount_TagPlusWWTightIdIsoFailHLT_binned.push_back(tmp_EventCount_TagPlusWWTightIdIsoFailHLT);
        
        Double_t tmp_EventCount_TagPlusWWTightIdIsoPassHLT = 0;
        tmp_EventCount_TagPlusWWTightIdIsoPassHLT_binned.push_back(tmp_EventCount_TagPlusWWTightIdIsoPassHLT);
        
        cout << "make bins : " << k << " " << i << " " << j << " " << endl;
        
      }
      
      tmp_tmp_EventCount_TagPlusRecoFailWWTightIdIso_binned.push_back(tmp_EventCount_TagPlusRecoFailWWTightIdIso_binned);
      tmp_tmp_EventCount_TagPlusRecoPassWWTightIdIso_binned.push_back(tmp_EventCount_TagPlusRecoPassWWTightIdIso_binned);
      tmp_tmp_EventCount_TagPlusWWTightIdIsoPassHLT_binned.push_back(tmp_EventCount_TagPlusWWTightIdIsoPassHLT_binned);
      tmp_tmp_EventCount_TagPlusWWTightIdIsoFailHLT_binned.push_back(tmp_EventCount_TagPlusWWTightIdIsoFailHLT_binned);
      
    }

    EventCount_TagPlusRecoFailWWTightIdIso_binned.push_back(tmp_tmp_EventCount_TagPlusRecoFailWWTightIdIso_binned);
    EventCount_TagPlusRecoPassWWTightIdIso_binned.push_back(tmp_tmp_EventCount_TagPlusRecoPassWWTightIdIso_binned);
    EventCount_TagPlusWWTightIdIsoPassHLT_binned.push_back(tmp_tmp_EventCount_TagPlusWWTightIdIsoPassHLT_binned);
    EventCount_TagPlusWWTightIdIsoFailHLT_binned.push_back(tmp_tmp_EventCount_TagPlusWWTightIdIsoFailHLT_binned);
    
  }

  //--------------------------------------------------------------------------------------------------------------
  // Histograms
  //==============================================================================================================  
  Double_t EventCount_TagPlusRecoFailWWTightIdIso = 0;
  Double_t EventCount_TagPlusRecoPassWWTightIdIso = 0;
  Double_t EventCount_TagPlusWWTightIdIsoFailHLT = 0;
  Double_t EventCount_TagPlusWWTightIdIsoPassHLT = 0;

  Int_t nbins = 20;
  TH1F *histogram = new TH1F ("histogram", "; xaxis; yaxis; ", 100, 0 , 200);
  TH1F *ProbePt = new TH1F ("ProbePt", "; xaxis; yaxis; ", 100, 0 , 200);
  TH1F *TagPt = new TH1F ("TagPt", "; xaxis; yaxis; ", 100, 0 , 200);
  TH1F *TagPlusRecoFailWWTightIdIso = new TH1F ("TagPlusRecoFailWWTightIdIso", "; xaxis; yaxis; ", nbins, 60 , 120);
  TH1F *TagPlusRecoPassWWTightIdIso = new TH1F ("TagPlusRecoPassWWTightIdIso", "; xaxis; yaxis; ", nbins, 60 , 120);
  TH1F *TagPlusWWTightIdIsoFailHLT = new TH1F ("TagPlusWWTightIdIsoFailHLT", "; xaxis; yaxis; ", nbins, 60 , 120);
  TH1F *TagPlusWWTightIdIsoPassHLT = new TH1F ("TagPlusWWTightIdIsoPassHLT", "; xaxis; yaxis; ", nbins, 60 , 120);


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  //
  // Access samples and fill histograms
  //  
  TFile *infile=0;
  TTree *eventTree=0;  
  
  // Data structures to store info from TTrees
  mithep::TEventInfo *info    = new mithep::TEventInfo();
  TClonesArray *electronArr = new TClonesArray("mithep::TElectron");
  

  //********************************************************
  // Get Tree
  //********************************************************
  eventTree = getTreeFromFile(dataInputFilename.c_str(),"Events");
  
  // Set branch address to structures that will store the info  
  eventTree->SetBranchAddress("Info",       &info);          TBranch *infoBr       = eventTree->GetBranch("Info");
  eventTree->SetBranchAddress("Electron", &electronArr); TBranch *electronBr = eventTree->GetBranch("Electron");
  

  //*****************************************************************************************
  //Loop over Data Tree
  //*****************************************************************************************
  Double_t nsel=0, nselvar=0;
  for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {       	
    infoBr->GetEntry(ientry);
	
    if (ientry % 100000 == 0) cout << "Event " << ientry << endl;

    //********************************************************
    // Load the branches
    //********************************************************
    electronArr->Clear();    
    electronBr->GetEntry(ientry);
 

    //********************************************************
    // TcMet
    //********************************************************
    TVector3 met;        
    if(info->tcMEx!=0 || info->tcMEy!=0) {       
      met.SetXYZ(info->tcMEx, info->tcMEy, 0);
    }

    //******************************************************************************
    //dilepton preselection
    //******************************************************************************
    if (electronArr->GetEntries() < 2) continue;


    //******************************************************************************
    //loop over electron pairs
    //******************************************************************************
    for(Int_t i=0; i<electronArr->GetEntries(); i++) {
      const mithep::TElectron *tag = (mithep::TElectron*)((*electronArr)[i]);
      if ( !(
             fabs(tag->eta) < 2.5
             && 
             tag->pt > 20.0
             &&
             passElectronTagCuts(tag)
             )
        ) continue;
      

      for(Int_t j=0; j<electronArr->GetEntries(); j++) {
        if (i==j) continue;

        const mithep::TElectron *probe = (mithep::TElectron*)((*electronArr)[j]);
        if ( !(
               fabs(probe->eta) < 2.5
               && probe->pt > 10.0
               && probe->isEcalDriven
               )
          ) continue;
        
        mithep::FourVectorM tagVector;
        mithep::FourVectorM probeVector;
        tagVector.SetCoordinates(tag->pt, tag->eta, tag->phi, 0.51099892e-3 );
        probeVector.SetCoordinates(probe->pt, probe->eta, probe->phi, 0.51099892e-3 );
        mithep::FourVectorM dilepton = tagVector+probeVector;
 
        if (dilepton.M() > 60 && dilepton.M() < 120
            
          ) {
          
          //For binned efficiencies
          for (int q=0; q < chargebinLabel.size(); ++q) {
            for (int e=0; e < etabinLabel.size(); ++e) {
              for (int p=0; p < ptbinLabel.size(); ++p) {
                
                //Require the probe is in the right pt and eta bin
                if ( 		  
                (probe->pt >= ptbinLowEdge[p] && probe->pt < ptbinUpEdge[p])
                &&
                (fabs(probe->eta) >= etabinLowEdge[e] && fabs(probe->eta) < etabinUpEdge[e]) 
                && 
                (probe->q == chargeSelection[q] || chargeSelection[q] == 0)
//                 &&
//                 met.Pt() < 20.0
                  ) {
                  
                  //*****************************************************************************************************
                  //Reco -> WWTight
                  //*****************************************************************************************************	    
                
                  if (passElectronCuts(probe)) {	 
                    EventCount_TagPlusRecoPassWWTightIdIso_binned[q][e][p]++;                  
                  } else {
                  EventCount_TagPlusRecoFailWWTightIdIso_binned[q][e][p]++;
                  }
                  
                  //*****************************************************************************************************
                  //WWTight -> HLT
                  //*****************************************************************************************************	    
                  if (passElectronCuts(probe)) {
                    if (passHLT(probe, info->runNum)) {	 		     
                      EventCount_TagPlusWWTightIdIsoPassHLT_binned[q][e][p]++;
                    } else {
                      EventCount_TagPlusWWTightIdIsoFailHLT_binned[q][e][p]++;
                    }
                  }	    	    	
                }
              }
            }
          }            

          //*****************************************************************************************************
          //Reco -> WWTight
          //*****************************************************************************************************	    
          if (passElectronCuts(probe)) {	 
            EventCount_TagPlusRecoPassWWTightIdIso++;
            TagPlusRecoPassWWTightIdIso->Fill(dilepton.M());	      		  	      
          } else {
            EventCount_TagPlusRecoFailWWTightIdIso++;
            TagPlusRecoFailWWTightIdIso->Fill(dilepton.M());	   
          }
	    
          //*****************************************************************************************************
          //WWTight -> HLT
          //*****************************************************************************************************	    
          if (passElectronCuts(probe)) {
            if (passHLT(probe, info->runNum)) {	 
              EventCount_TagPlusWWTightIdIsoPassHLT++;
              TagPlusWWTightIdIsoPassHLT->Fill(dilepton.M());	
              ProbePt->Fill(probe->pt);
            } else {
              EventCount_TagPlusWWTightIdIsoFailHLT++;
              TagPlusWWTightIdIsoPassHLT->Fill(dilepton.M());			
            }
          }

        } //passes T&P selection

              
      } //loop over probes
    } //loop over tags


  } //end loop over data     

  delete info;
  delete electronArr;


  //--------------------------------------------------------------------------------------------------------------
  // Make plots
  //==============================================================================================================
  TCanvas *cv = new TCanvas("cv","cv", 800,600);
  TagPlusRecoPassWWTightIdIso->Draw();
  cv->SaveAs("TagPlusRecoPassWWTightIdIso.gif");
  TagPlusRecoFailWWTightIdIso->Draw();
  cv->SaveAs("TagPlusRecoFailWWTightIdIso.gif");
  TagPlusWWTightIdIsoPassHLT->Draw();
  cv->SaveAs("TagPlusWWTightIdIsoPassHLT.gif");
  TagPlusWWTightIdIsoFailHLT->Draw();
  cv->SaveAs("TagPlusWWTightIdIsoFailHLT.gif");

  ProbePt->Draw();
  cv->SaveAs("ProbePt.gif");
  TagPt->Draw();
  cv->SaveAs("TagPt.gif");

  //*****************************************************************************************
  //Summarize Efficiencies
  //*****************************************************************************************
  cout << "**********************************************************************\n";
  cout << "Summarize MC Efficiencies\n";
  TFile *file = new TFile("Efficiencies.root", "UPDATE");

  for (int q=0; q < chargebinLabel.size(); ++q) {    
    for (int e=0; e < etabinLabel.size(); ++e) {
      vector<Double_t> efficiency_RecoToWWTight;
      vector<Double_t> efficiency_RecoToWWTight_lowErr;
      vector<Double_t> efficiency_RecoToWWTight_highErr;
      vector<Double_t> efficiency_WWTightToHLT;
      vector<Double_t> efficiency_WWTightToHLT_lowErr;
      vector<Double_t> efficiency_WWTightToHLT_highErr;
      
      for (int p=0; p < ptbinLabel.size(); ++p) {
    
        cout << etabinLabel[e] << "  " << ptbinLabel[p] << "  Charge = " << chargeSelection[q] << endl;
        cout << endl;

        Int_t errorType = 2; //Clopper Pearson intervals
        Double_t ratio;
        Double_t errLow;
        Double_t errHigh;     
        Double_t n1;
        Double_t n2;

        n1 = TMath::Nint(EventCount_TagPlusRecoPassWWTightIdIso_binned[q][e][p]);
        n2 = TMath::Nint(EventCount_TagPlusRecoPassWWTightIdIso_binned[q][e][p] + EventCount_TagPlusRecoFailWWTightIdIso_binned[q][e][p]);
        if (n1 > n2) n1 = n2;
        mithep::MathUtils::CalcRatio(n1 , n2, ratio, errLow, errHigh, errorType);      
        cout << "Reco -> WWTight  Efficiency (MC) : " << n1 << " / " << n2 << " = " << ratio << " + " << errHigh << " - " << errLow << endl;
        cout << "\n";
        efficiency_RecoToWWTight.push_back(ratio);
        efficiency_RecoToWWTight_lowErr.push_back(errLow);
        efficiency_RecoToWWTight_highErr.push_back(errHigh);


        n1 = TMath::Nint(EventCount_TagPlusWWTightIdIsoPassHLT_binned[q][e][p]);
        n2 = TMath::Nint(EventCount_TagPlusWWTightIdIsoPassHLT_binned[q][e][p] + EventCount_TagPlusWWTightIdIsoFailHLT_binned[q][e][p]);
        if (n1 > n2) n1 = n2;
        mithep::MathUtils::CalcRatio(n1 , n2, ratio, errLow, errHigh, errorType);      
        cout << "WWTight  -> HLT : " << n1 << " / " << n2 << " = " << ratio << " + " << errHigh << " - " << errLow << endl;
        cout << "\n";

        efficiency_WWTightToHLT.push_back(ratio);
        efficiency_WWTightToHLT_lowErr.push_back(errLow);
        efficiency_WWTightToHLT_highErr.push_back(errHigh);

  
        cout << "\n\n\n";
      }

    //Make Efficiency Graphs
    const Int_t nbins = efficiency_RecoToWWTight.size();
    Double_t x[nbins];
    Double_t y[nbins];
    Double_t xErr[nbins];
    Double_t yErrLow[nbins];
    Double_t yErrHigh[nbins];

    //***********************************************************
    //Reco -> WW Tight    
    //***********************************************************
    for (int b=0; b< efficiency_RecoToWWTight.size(); ++b) {
      x[b] = (ptbinUpEdge[b] + ptbinLowEdge[b]) / 2;
      xErr[b] = fabs(ptbinUpEdge[b] - ptbinLowEdge[b]) / 2;
      if (b==efficiency_RecoToWWTight.size() - 1) {
        x[b] = (100 + ptbinLowEdge[b]) / 2;
        xErr[b] = fabs(100 - ptbinLowEdge[b]) / 2;
      }
      y[b] = efficiency_RecoToWWTight[b];
      yErrLow[b] = fabs(efficiency_RecoToWWTight_lowErr[b]);
      yErrHigh[b] = efficiency_RecoToWWTight_highErr[b];
    }
   
    TGraphAsymmErrors *efficiencyGraph_RecoToWWTight = new TGraphAsymmErrors(nbins, x, y, xErr, xErr, yErrLow,yErrHigh );
    efficiencyGraph_RecoToWWTight->SetName(("MCEfficiency_RecoToWWTight_" + chargebinLabel[q] + "_" + etabinLabel[e]).c_str());
    efficiencyGraph_RecoToWWTight->SetTitle("");
    efficiencyGraph_RecoToWWTight->GetXaxis()->SetTitle("p_{T} [GeV/c]");
    efficiencyGraph_RecoToWWTight->GetYaxis()->SetTitle("Efficiency");
    efficiencyGraph_RecoToWWTight->SetMaximum(1.0);
    efficiencyGraph_RecoToWWTight->SetMinimum(0.0);
    efficiencyGraph_RecoToWWTight->SetMarkerSize(1);
    efficiencyGraph_RecoToWWTight->SetLineWidth(2);
    efficiencyGraph_RecoToWWTight->GetXaxis()->SetRangeUser(0,100);

    file->WriteTObject(efficiencyGraph_RecoToWWTight, efficiencyGraph_RecoToWWTight->GetName(), "WriteDelete");


    //***********************************************************
    //WW Tight -> HLT
    //***********************************************************
    for (int b=0; b< efficiency_WWTightToHLT.size(); ++b) {
      x[b] = (ptbinUpEdge[b] + ptbinLowEdge[b]) / 2;
      xErr[b] = fabs(ptbinUpEdge[b] - ptbinLowEdge[b]) / 2;
      if (b==efficiency_RecoToWWTight.size() - 1) {
        x[b] = (100 + ptbinLowEdge[b]) / 2;
        xErr[b] = fabs(100 - ptbinLowEdge[b]) / 2;
      }
      y[b] = efficiency_WWTightToHLT[b];
      yErrLow[b] = fabs(efficiency_WWTightToHLT_lowErr[b]);
      yErrHigh[b] = efficiency_WWTightToHLT_highErr[b];
    }      
    TGraphAsymmErrors *efficiencyGraph_WWTightToHLT = new TGraphAsymmErrors(nbins, x, y, xErr, xErr, yErrLow,yErrHigh );
    efficiencyGraph_WWTightToHLT->SetName(("MCEfficiency_WWTightToHLT_" + chargebinLabel[q] + "_" + etabinLabel[e]).c_str());
    efficiencyGraph_WWTightToHLT->SetTitle("");
    efficiencyGraph_WWTightToHLT->GetXaxis()->SetTitle("p_{T} [GeV/c]");
    efficiencyGraph_WWTightToHLT->GetYaxis()->SetTitle("Efficiency");
    efficiencyGraph_WWTightToHLT->SetMaximum(1.0);
    efficiencyGraph_WWTightToHLT->SetMinimum(0.0);
    efficiencyGraph_WWTightToHLT->SetMarkerSize(1);
    efficiencyGraph_WWTightToHLT->SetLineWidth(2);
    efficiencyGraph_WWTightToHLT->GetXaxis()->SetRangeUser(0,100);

    file->WriteTObject(efficiencyGraph_WWTightToHLT, efficiencyGraph_WWTightToHLT->GetName(), "WriteDelete");

    } //end for loop over eta bins
  } //end for loop over charge bins

  file->Close();

  Int_t errorType = 2; //Clopper Pearson intervals
  Double_t ratio;
  Double_t errLow;
  Double_t errHigh;     
  Double_t n1;
  Double_t n2;


  n1 = TMath::Nint(EventCount_TagPlusRecoPassWWTightIdIso);
  n2 = TMath::Nint(EventCount_TagPlusRecoPassWWTightIdIso + EventCount_TagPlusRecoFailWWTightIdIso);
  if (n1 > n2) n1 = n2;
  mithep::MathUtils::CalcRatio(n1 , n2, ratio, errLow, errHigh, errorType);      
  cout << "Reco -> WWTight  Efficiency (MC) : " << n1 << " / " << n2 << " = " << ratio << " + " << errHigh << " - " << errLow << endl;
  cout << "\n";



  n1 = TMath::Nint(EventCount_TagPlusWWTightIdIsoPassHLT);
  n2 = TMath::Nint(EventCount_TagPlusWWTightIdIsoPassHLT + EventCount_TagPlusWWTightIdIsoFailHLT);
  if (n1 > n2) n1 = n2;
  mithep::MathUtils::CalcRatio(n1 , n2, ratio, errLow, errHigh, errorType);      
  cout << "WWTight  -> HLT : " << n1 << " / " << n2 << " = " << ratio << " + " << errHigh << " - " << errLow << endl;
  cout << "\n";

  

  cout << "**********************************************************************\n";

      
  gBenchmark->Show("ElectronTagAndProbe");       


} 
void selectEleHZZHCP2012IDGivenIsoWithTightTagPerFile(const string inputfile,          // input file
                              const string outputfile,         // output directory
                              const Bool_t  matchGen = kFALSE, // match to generator muons
                              Int_t dataType = 0,              // del = 0, sel = 1, mc = -1
                              Int_t DataEraInput = 2
  ) {
  gBenchmark->Start("selectEleMVAIsoTightGivenID");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 
  UInt_t DataEra = kDataEra_NONE;
  if (DataEraInput == 1) DataEra = kDataEra_2011_MC;
  if (DataEraInput == 2) DataEra = kDataEra_2012_MC;
  if (DataEraInput == 11) DataEra = kDataEra_2011_Data;
  if (DataEraInput == 12) DataEra = kDataEra_2012_Data;

  //*****************************************************************************************
  //Setup MVA
  //*****************************************************************************************
  EGammaMvaEleEstimator *eleIDMVA = new EGammaMvaEleEstimator();
  vector<string> weightFiles;

  weightFiles.push_back((string(getenv("CMSSW_BASE"))+string("/src/HiggsAna/HZZ4l/data/ElectronIDMVAWeights/Electrons_BDTG_NonTrigV0_Cat1.weights.xml")).c_str());
  weightFiles.push_back((string(getenv("CMSSW_BASE"))+string("/src/HiggsAna/HZZ4l/data/ElectronIDMVAWeights/Electrons_BDTG_NonTrigV0_Cat2.weights.xml")).c_str());
  weightFiles.push_back((string(getenv("CMSSW_BASE"))+string("/src/HiggsAna/HZZ4l/data/ElectronIDMVAWeights/Electrons_BDTG_NonTrigV0_Cat3.weights.xml")).c_str());
  weightFiles.push_back((string(getenv("CMSSW_BASE"))+string("/src/HiggsAna/HZZ4l/data/ElectronIDMVAWeights/Electrons_BDTG_NonTrigV0_Cat4.weights.xml")).c_str());
  weightFiles.push_back((string(getenv("CMSSW_BASE"))+string("/src/HiggsAna/HZZ4l/data/ElectronIDMVAWeights/Electrons_BDTG_NonTrigV0_Cat5.weights.xml")).c_str());
  weightFiles.push_back((string(getenv("CMSSW_BASE"))+string("/src/HiggsAna/HZZ4l/data/ElectronIDMVAWeights/Electrons_BDTG_NonTrigV0_Cat6.weights.xml")).c_str());
  eleIDMVA->initialize( "BDT", EGammaMvaEleEstimator::kNonTrig,  kTRUE, weightFiles);
  

  // mass region
  Double_t massLo = 40;
  Double_t massHi = 200;

  
  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  Double_t nProbes = 0;
  
  //
  // Set up output ntuple
  //
  TFile *outFile = new TFile(outputfile.c_str(),"RECREATE"); 
  TTree *outTree = new TTree("Events","Events");
  EffData data;
  outTree->Branch("Events",&data.mass,"mass/F:pt:eta:phi:weight:q/I:npv/i:npu:pass:runNum:lumiSec:evtNum:rho/F");

  TFile *infile=0;
  TTree *eventTree=0;
  
  // Data structures to store info from TTrees
  higgsana::TEventInfo *info  = new higgsana::TEventInfo();
  higgsana::TGenInfo *gen     = new higgsana::TGenInfo();
  TClonesArray *electronArr = new TClonesArray("higgsana::TElectron");
  TClonesArray *pfcandidateArr = new TClonesArray("higgsana::TPFCandidate");
  TClonesArray *muonArr = new TClonesArray("higgsana::TMuon");

  // Read input file and get the TTrees
  cout << "Processing " << inputfile << "..." << endl;
  infile = TFile::Open(inputfile.c_str(),"read");
  assert(infile);



  //********************************************************
  // Good RunLumi Selection
  //********************************************************
  Bool_t hasJSON = kFALSE;
  mithep::RunLumiRangeMap rlrm;
  if (!matchGen) {
    hasJSON = kTRUE;
    rlrm.AddJSONFile("/afs/cern.ch/work/s/sixie/public/HZZ4l/auxiliar/2012/Cert_Full2012_53X_JSON.txt"); 
    rlrm.AddJSONFile("/afs/cern.ch/work/s/sixie/public/HZZ4l/auxiliar/2011/2011Combined.json");
  }
    
  eventTree = (TTree*)infile->Get("Events"); assert(eventTree);  
  eventTree->SetBranchAddress("Info",     &info);        TBranch *infoBr     = eventTree->GetBranch("Info");
  eventTree->SetBranchAddress("Electron", &electronArr); TBranch *electronBr = eventTree->GetBranch("Electron");
  eventTree->SetBranchAddress("Muon", &muonArr);         TBranch *muonBr = eventTree->GetBranch("Muon");
  eventTree->SetBranchAddress("PFCandidate", &pfcandidateArr);  TBranch *pfcandidateBr = eventTree->GetBranch("PFCandidate");
  cout << "NEvents = " << eventTree->GetEntries() << endl;

  TBranch *genBr = 0;
  if(matchGen) {
    eventTree->SetBranchAddress("Gen", &gen);
    genBr = eventTree->GetBranch("Gen");
  }
    
  Double_t weight = 1;

  // loop over events
  for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
    if (ientry % 100000 == 0) cout << "Processed Event " << ientry << endl;
    infoBr->GetEntry(ientry);

    // check for certified runs
    mithep::RunLumiRangeMap::RunLumiPairType rl(info->runNum, info->lumiSec);      
    if(hasJSON && !rlrm.HasRunLumi(rl)) continue;  
 
    //***********************************************************
    // Definition of Pileup Energy density
    //***********************************************************
    Double_t rhoEleIso = 0;
    UInt_t EleEAEra = 0;
    if (DataEra == kDataEra_2011_MC) {
        
      if (!(isnan(info->RhoKt6PFJetsForIso25) || 
            isinf(info->RhoKt6PFJetsForIso25))) {
        rhoEleIso = info->RhoKt6PFJetsForIso25;
      }
      EleEAEra = kDataEra_2011_Data;
        
    } else if (DataEra == kDataEra_2012_MC) {
        
      if (!(isnan(info->RhoKt6PFJets) || 
            isinf(info->RhoKt6PFJets))) {
        rhoEleIso = info->RhoKt6PFJets;
      }
      EleEAEra = kDataEra_2012_Data;
    }

    //use only odd numbered events to evaluate efficiency for data. even numbered events were used for training
    //if (info->evtNum % 2 == 0 && !matchGen) continue;


    // trigger requirement               
    Bool_t passTrigger = kFALSE;
    if(dataType == 0) {
      if ((info->triggerBits & kHLT_Ele20_CaloIdVT_CaloIsoVT_TrkIdT_TrkIsoVT_SC4_Mass50) == kHLT_Ele20_CaloIdVT_CaloIsoVT_TrkIdT_TrkIsoVT_SC4_Mass50) passTrigger = kTRUE;
      if ((info->triggerBits & kHLT_Ele17_CaloIdVT_CaloIsoVT_TrkIdT_TrkIsoVT_SC8_Mass30) == kHLT_Ele17_CaloIdVT_CaloIsoVT_TrkIdT_TrkIsoVT_SC8_Mass30) passTrigger = kTRUE;
      if ((info->triggerBits & kHLT_Ele32_CaloIdL_CaloIsoVL_SC17) == kHLT_Ele32_CaloIdL_CaloIsoVL_SC17) passTrigger = kTRUE;
    } else if(dataType == 1) {
      if(DataEraInput == 2) {
        if(info->triggerBits & kHLT_Ele20_CaloIdVT_CaloIsoVT_TrkIdT_TrkIsoVT_SC4_Mass50)  continue;
        if(info->triggerBits & kHLT_Ele17_CaloIdVT_CaloIsoVT_TrkIdT_TrkIsoVT_SC8_Mass30)  continue;
        if(info->triggerBits & kHLT_Ele32_CaloIdL_CaloIsoVL_SC17)                         continue;
      }
        
      if ((info->triggerBits & kHLT_Ele27_CaloIdVT_CaloIsoT_TrkIdT_TrkIsoT) == kHLT_Ele27_CaloIdVT_CaloIsoT_TrkIdT_TrkIsoT) passTrigger = kTRUE;
    }
    if(dataType != -1 && !passTrigger) continue;     
      
    // good vertex requirement
    if(!(info->hasGoodPV)) continue;

    if(matchGen) genBr->GetEntry(ientry);
      
    electronArr->Clear();
    muonArr->Clear(); 
    pfcandidateArr->Clear(); 
    electronBr->GetEntry(ientry);
    muonBr->GetEntry(ientry);
    pfcandidateBr->GetEntry(ientry);

    //********************************************************
    //Low Met Requirement
    //********************************************************
    TVector3 met;        
    if(info->pfMEx!=0 || info->pfMEy!=0) {       
      met.SetXYZ(info->pfMEx, info->pfMEy, 0);
    }
    if (met.Pt() > 25) continue;
      

    //********************************************************
    //Loop over TAG electrons
    //********************************************************
    for(Int_t i=0; i<electronArr->GetEntriesFast(); i++) {

      const higgsana::TElectron *tag = (higgsana::TElectron*)((*electronArr)[i]);
	
      if(matchGen) {
        Bool_t match1 = (higgsana::deltaR(tag->eta, tag->phi, gen->eta_1, gen->phi_1) < 0.5);
        Bool_t match2 = (higgsana::deltaR(tag->eta, tag->phi, gen->eta_2, gen->phi_2) < 0.5);
        if(!match1 && !match2)
          continue;
      }

      if(tag->pt          < 20)  continue;
      if(fabs(tag->scEta) > 2.5) continue;

      if (!PassEleSimpleCutsVeryTight(tag,pfcandidateArr,rhoEleIso,EleEAEra)) continue;

      if(dataType == 0 &&
         !((info->triggerBits & kHLT_Ele20_CaloIdVT_CaloIsoVT_TrkIdT_TrkIsoVT_SC4_Mass50) && (tag->hltMatchBits & kHLTObject_Ele20_CaloIdVT_CaloIsoVT_TrkIdT_TrkIsoVT)) &&
         !((info->triggerBits & kHLT_Ele17_CaloIdVT_CaloIsoVT_TrkIdT_TrkIsoVT_SC8_Mass30) && (tag->hltMatchBits & kHLTObject_Ele17_CaloIdVT_CaloIsoVT_TrkIdT_TrkIsoVT)) &&
         !((info->triggerBits & kHLT_Ele32_CaloIdL_CaloIsoVL_SC17) && (tag->hltMatchBits & kHLTObject_Ele32_CaloIdL_CaloIsoVL)) &&
         !((info->triggerBits & kHLT_Ele32_CaloIdL_CaloIsoVL_SC17) && (tag->hltMatchBits & kHLTObject_Ele32_CaloIdT_CaloIsoT_TrkIdT_TrkIsoT)) &&
         !((info->triggerBits & kHLT_Ele17_CaloIdL_CaloIsoVL) && (tag->hltMatchBits & kHLTObject_Ele17_CaloIdL_CaloIsoVL)) ) 
        continue;
      
      if (dataType == 1) {
        if(dataType == 1 &&
           !((info->triggerBits & kHLT_Ele27_CaloIdVT_CaloIsoT_TrkIdT_TrkIsoT) && (tag->hltMatchBits & kHLTObject_Ele27_CaloIdVT_CaloIsoT_TrkIdT_TrkIsoT) && tag->pt > 30) &&
           !((info->triggerBits & kHLT_Ele27_CaloIdVT_CaloIsoT_TrkIdT_TrkIsoT) && (tag->hltMatchBits & kHLTObject_Ele32_CaloIdVT_CaloIsoT_TrkIdT_TrkIsoT) && tag->pt > 35) &&
           !((info->triggerBits & kHLT_Ele27_CaloIdVT_CaloIsoT_TrkIdT_TrkIsoT) && (tag->hltMatchBits & kHLTObject_Ele52_CaloIdVT_TrkIdT) && tag->pt > 60) &&
           !((info->triggerBits & kHLT_Ele27_CaloIdVT_CaloIsoT_TrkIdT_TrkIsoT) && (tag->hltMatchBits & kHLTObject_Ele27_WP80) && tag->pt > 30) && 
           !((info->triggerBits & kHLT_Ele27_CaloIdVT_CaloIsoT_TrkIdT_TrkIsoT) && (tag->hltMatchBits & kHLTObject_Ele32_WP70) && tag->pt > 35)  
          )
          continue;       
      }

      const Double_t m = 0.000511;
      TLorentzVector vtag;
      vtag.SetPtEtaPhiM(tag->pt, tag->eta, tag->phi, m);
        
      for(Int_t j=0; j<electronArr->GetEntriesFast(); j++) {
        if(i==j) continue;
	  
        const higgsana::TElectron *probe = (higgsana::TElectron*)((*electronArr)[j]);
        if(probe->q == tag->q) continue;
	  
// 	  if(typev[ifile]==eDiEl &&
// 	     !((info->triggerBits & kHLT_Ele17_CaloIdVT_CaloIsoVT_TrkIdT_TrkIsoVT_SC8_Mass30) && (probe->hltMatchBits & kHLTObject_SC8)) &&
// 	     !((info->triggerBits & kHLT_Ele17_CaloIdVT_CaloIsoVT_TrkIdT_TrkIsoVT_SC8_Mass30) && (probe->hltMatchBits & kHLTObject_Ele8)) &&
// 	     !((info->triggerBits & kHLT_Ele32_CaloIdL_CaloIsoVL_SC17) && (probe->hltMatchBits & kHLTObject_SC17)))
// 	    continue;
	  
        if(matchGen) {
          Bool_t match1 = (higgsana::deltaR(probe->eta, probe->phi, gen->eta_1, gen->phi_1) < 0.5);
          Bool_t match2 = (higgsana::deltaR(probe->eta, probe->phi, gen->eta_2, gen->phi_2) < 0.5);
          if(!match1 && !match2)
            continue;
        }
	  
        if(fabs(probe->scEta) > 2.5) continue;

        TLorentzVector vprobe;
        vprobe.SetPtEtaPhiM(probe->pt, probe->eta, probe->phi, m);
	  
        TLorentzVector vdielectron = vtag + vprobe;
        if((vdielectron.M()<massLo) || (vdielectron.M()>massHi)) continue;	  	  

        //for probes with pT < 10, require the Ele20_SC4 trigger
        if (probe->pt < 10) {
          if(dataType == 0) {

            if (!((info->triggerBits & kHLT_Ele20_CaloIdVT_CaloIsoVT_TrkIdT_TrkIsoVT_SC4_Mass50) == kHLT_Ele20_CaloIdVT_CaloIsoVT_TrkIdT_TrkIsoVT_SC4_Mass50)) continue;
            if (!((info->triggerBits & kHLT_Ele20_CaloIdVT_CaloIsoVT_TrkIdT_TrkIsoVT_SC4_Mass50) && (tag->hltMatchBits & kHLTObject_Ele20_CaloIdVT_CaloIsoVT_TrkIdT_TrkIsoVT))) continue;
          }
        }

        nProbes++;

        Bool_t passID = (PassEleHZZ4lPreselection(probe) && PassEleHZZ4lICHEP2012ID(probe, eleIDMVA));
        
        vector<const higgsana::TPFCandidate*> photonsToVeto;
        Bool_t passIsolation = PassEleHZZ4lICHEP2012Iso(probe,j,pfcandidateArr,rhoEleIso,EleEAEra,photonsToVeto);
        if (!passIsolation) continue;

        //******************
        //PASS
        //******************
        Bool_t pass = passID && passIsolation;

        // Fill tree
        data.mass   = vdielectron.M();
        data.pt     = probe->pt;
        data.eta    = probe->scEta;
        data.phi    = probe->phi;
        data.weight = weight;
        data.q      = probe->q;
        data.npv    = info->nPV0;
        data.npu    = info->nPUEvents;
        data.pass   = (pass) ? 1 : 0;
        data.rho    = rhoEleIso;
        data.runNum = info->runNum;
        data.lumiSec = info->lumiSec;
        data.evtNum = info->evtNum;

        outTree->Fill();	  
      }
    }
  }

  delete infile;
  infile=0, eventTree=0;      
  delete info;
  delete gen;
  delete electronArr;
  
     
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;
  cout << endl;
  cout << " Number of probes selected: " << nProbes << endl;
  
  outFile->Write();
  outFile->Close();
  delete outFile;
  
  cout << endl;
  cout << "  <> Output saved in " << outputfile << endl;    
  cout << endl;  
      
  gBenchmark->Show("selectEleLHEffTP"); 
}
示例#19
0
void ZmmSelection(const string dataInputFilename, const string Label) {   

  gBenchmark->Start("ZeeSelection");

  
  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  
  Double_t lumi;              // luminosity (pb^-1)
    

  //--------------------------------------------------------------------------------------------------------------
  // Histograms
  //==============================================================================================================  
  TH1D *dileptonMass = new TH1D("dileptonMass", "; Mass [GeV/c^{2}]; Number of Events", 50, 0, 200);
  TH1D *dileptonMass_ee = new TH1D("dileptonMass_ee", "; Mass [GeV/c^{2}]; Number of Events", 50, 0, 200);
  TH1D *dileptonMass_emu = new TH1D("dileptonMass_emu", "; Mass [GeV/c^{2}]; Number of Events", 50, 0, 200);
  TH1D *dileptonMass_mumu = new TH1D("dileptonMass_mumu", "; Mass [GeV/c^{2}]; Number of Events", 50, 0, 200);
  Int_t Count_ee_BB = 0;
  Int_t Count_ee_BE = 0;
  Int_t Count_ee_EE = 0;
  Int_t Count_mm_BB = 0;
  Int_t Count_mm_BE = 0;
  Int_t Count_mm_EE = 0;
  Int_t Count_em_BB = 0;
  Int_t Count_em_BE = 0;
  Int_t Count_em_EE = 0;
  ofstream eventListFile("eventList.txt");

  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  //
  // Access samples and fill histograms
  //  
  TFile *infile=0;
  TTree *eventTree=0;  
  
  // Data structures to store info from TTrees
  mithep::TEventInfo *info    = new mithep::TEventInfo();
  TClonesArray *muonArr = new TClonesArray("mithep::TMuon");
  TClonesArray *jetArr = new TClonesArray("mithep::TJet");
  

  infile = new TFile(dataInputFilename.c_str());
  assert(infile);

    
  //********************************************************
  // Good RunLumi Selection
  //********************************************************
  Bool_t hasJSON = kTRUE;
  mithep::RunLumiRangeMap rlrm;
  rlrm.AddJSONFile("Cert_TopNov5_Merged_135821-149442_allPVT.txt"); 

  

  //********************************************************
  // Get Tree
  //********************************************************
  eventTree = getTreeFromFile(dataInputFilename.c_str(),"Events"); 
  
  // Set branch address to structures that will store the info  
  eventTree->SetBranchAddress("Info",       &info);          TBranch *infoBr       = eventTree->GetBranch("Info");
  eventTree->SetBranchAddress("Muon", &muonArr); TBranch *muonBr = eventTree->GetBranch("Muon");
  eventTree->SetBranchAddress("PFJet", &jetArr); TBranch *jetBr = eventTree->GetBranch("PFJet");
  
  cout << "Total: " << eventTree->GetEntries() << endl;
  //*****************************************************************************************
  //Loop over Data Tree
  //*****************************************************************************************
  Double_t nsel=0, nselvar=0;
  for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {       	
    infoBr->GetEntry(ientry);
	
//     Double_t eventweight = info->eventweight*3.1;
    double eventweight = 1;
//    cout << eventweight << endl;
    if (ientry % 100000 == 0) cout << "Event " << ientry << endl;

    mithep::RunLumiRangeMap::RunLumiPairType rl(info->runNum, info->lumiSec);      
    if(hasJSON && !rlrm.HasRunLumi(rl)) continue;  // not certified run? Skip to next event...
     
    if (!passHLT(info->triggerBits, info->runNum, kTRUE)) continue;


    //********************************************************
    // Load the branches
    //********************************************************
    muonArr->Clear();    
    jetArr->Clear(); 
    muonBr->GetEntry(ientry);
    jetBr->GetEntry(ientry);


    //********************************************************
    // TcMet
    //********************************************************
    TVector3 met;        
    if(info->tcMEx!=0 || info->tcMEy!=0) {       
      met.SetXYZ(info->tcMEx, info->tcMEy, 0);
    }
	
    //********************************************************
    // TcMet
    //********************************************************

     Int_t NJets = 0;
    const mithep::TJet *leadingJet = 0;
    
    for(Int_t i=0; i<jetArr->GetEntries(); i++) {
      const mithep::TJet *jet = (mithep::TJet*)((*jetArr)[i]);

      if (!(jet->pt > 25 && fabs(jet->pt) < 5.0)) continue;
      if (!leadingJet || jet->pt > leadingJet->pt) {
        leadingJet = jet;
      }
      NJets++;
    }


    //******************************************************************************
    //dilepton preselection
    //******************************************************************************
    if (muonArr->GetEntries() < 2) continue;


    //******************************************************************************
    //loop over muon pairs
    //******************************************************************************
    for(Int_t i=0; i<muonArr->GetEntries(); i++) {
      const mithep::TMuon *mu1 = (mithep::TMuon*)((*muonArr)[i]);
      if ( !(
//              fabs(mu1->eta) < 2.1
//              && 
             mu1->pt > 20.0
             &&
             passMuonCuts(mu1)
             )
        ) continue;
      

      for(Int_t j=i+1; j<muonArr->GetEntries(); j++) {
        const mithep::TMuon *mu2 = (mithep::TMuon*)((*muonArr)[j]);
        if ( !(
//                fabs(mu2->eta) < 2.1
//                && 
               mu2->pt > 20.0
               && passMuonCuts(mu2)
               )
          ) continue;
        
        mithep::FourVectorM lepton1;
        mithep::FourVectorM lepton2;
        lepton1.SetCoordinates(mu1->pt, mu1->eta, mu1->phi, 0.51099892e-3 );
        lepton2.SetCoordinates(mu2->pt, mu2->eta, mu2->phi, 0.51099892e-3 );
        mithep::FourVectorM dilepton = lepton1+lepton2;
 

        dileptonMass->Fill(dilepton.M());
        dileptonMass_mumu->Fill(dilepton.M());
        if (dilepton.M() > 60 
            //  && dilepton.M() < 120
          ) {
          if (fabs(lepton1.Eta()) < 1.5 && fabs(lepton2.Eta()) < 1.5) {
            Count_mm_BB += eventweight;
          } else if (fabs(lepton1.Eta()) > 1.5 && fabs(lepton2.Eta()) > 1.5) {
            Count_mm_EE += eventweight;
          } else {
            Count_mm_BE += eventweight;
          }
        }
        
      }
    }


  } //end loop over data     

  delete info;
  delete muonArr;
  delete jetArr;


  //--------------------------------------------------------------------------------------------------------------
  // Make plots
  //==============================================================================================================
  TCanvas *cv = new TCanvas("cv","cv", 800,600);
  dileptonMass->Draw("E");
  cv->SaveAs("dileptonMass_mm.gif");

  //--------------------------------------------------------------------------------------------------------------
  // Summary print out
  //============================================================================================================== 
  cout << "**************************************************************\n";
  cout << "Event Count : mm final state\n";
  cout << "BB :" << Count_mm_BB << endl;
  cout << "BE :" << Count_mm_BE << endl;
  cout << "EE :" << Count_mm_EE << endl;
  cout << "Total :" << Count_mm_BB + Count_mm_BE + Count_mm_EE << endl;



        
  gBenchmark->Show("ZeeSelection");       
}