コード例 #1
0
ファイル: tmvaglob.C プロジェクト: CeF3TB/BTFAnalysis
   // used to create output file for canvas
   void imgconv( TCanvas* c, const TString & fname )
   {
      // return;
      if (NULL == c) {
         cout << "*** Error in TMVAGlob::imgconv: canvas is NULL" << endl;
      }
      else {
         // create directory if not existing
         TString f = fname;
         TString dir = f.Remove( f.Last( '/' ), f.Length() - f.Last( '/' ) );
         gSystem->mkdir( dir );

         TString pngName = fname + ".png";
         TString gifName = fname + ".gif";
         TString epsName = fname + ".eps";
         c->cd();

         // create eps (other option: c->Print( epsName ))
         if (UsePaperStyle) {
            c->Print(epsName);
         } 
         else {
            cout << "--- --------------------------------------------------------------------" << endl;
            cout << "--- If you want to save the image as eps, gif or png, please comment out " << endl;
            cout << "--- the corresponding lines (line no. 239-241) in tmvaglob.C" << endl;
            cout << "--- --------------------------------------------------------------------" << endl;
            c->Print(epsName);
            c->Print(pngName);
            // c->Print(gifName);
         }
      }
   }
コード例 #2
0
ファイル: runFindSource.C プロジェクト: asmagina1995/roottest
void FindAny(bool found, const TString& fsname, TClass* cl, TString baseexpected, const char* ext, const char* tag) {

   if (baseexpected == "") {
      baseexpected = cl->GetName();
      Ssiz_t posCol = baseexpected.First('<');
      if (posCol != -1) {
         baseexpected.Remove(posCol, baseexpected.Length());
      }
      posCol = baseexpected.Last(':');
      if (posCol != -1) {
         baseexpected.Remove(0, posCol + 1);
      }
      baseexpected += ext;
   }

   if (!found) {
      if (baseexpected != "FAIL") {
         printf("FAIL: %s file for class %s not found\n", tag, cl->GetName());
      }
      return;
   } else {
      if (baseexpected == "FAIL") {
         printf("FAIL: expected to not find %s file for class %s but got %s\n",
                tag, cl->GetName(), fsname.Data());
         return;
      }
   }
   if (!fsname.EndsWith(baseexpected)) {
      printf("FAIL: class %s expected %s file %s, got %s\n",
             cl->GetName(), tag, baseexpected.Data(), fsname.Data());
      return;
   }
}
コード例 #3
0
ファイル: AnalysisMacroGlob.C プロジェクト: ktf/AliPhysics
TString GetFormatFromDataSet(TString dataset) {
  
//   Info("runAAF.C","Detecting format from dataset (may take while, depends on network connection)...");
  TString dsTreeName;
  if (dataset.Contains("#")) {
    Info("runAAF.C",Form("Detecting format from dataset name '%s' ...",dataset.Data()));
    dsTreeName=dataset(dataset.Last('#'),dataset.Length());
  } else {
    Info("runAAF.C",Form("Detecting format from dataset '%s' (may take while, depends on network connection) ...",dataset.Data()));
    TFileCollection *ds = gProof->GetDataSet(dataset.Data());
    if (!ds) {
      Error(Form("Dataset %s doesn't exist on proof cluster!!!!",dataset.Data()));
      return "";
    }
    dsTreeName = ds->GetDefaultTreeName();
  }

  if (dsTreeName.Contains("esdTree")) {
    Info("runAAF.C","ESD input format detected ...");
    return "ESD";
  } else if (dsTreeName.Contains("aodTree"))  {
    Info("runAAF.C","AOD input format detected ...");
    return "AOD";
  } else {
    Error("runAAF.C",Form("Tree %s is not supported !!!",dsTreeName.Data()));
    Error("runAAF.C",Form("Maybe set your DS to %s#esdTree or %s#aodTree",dataset.Data(),dataset.Data()));
  }
  
  return "";
}
コード例 #4
0
ファイル: RecoQA.C プロジェクト: star-bnl/star-macros
void RecoQA(const char* inFile) {
  gROOT->LoadMacro("bfcread_hist_prefixes_add_to_ps.C");

  TString baseName = inFile;
  if (baseName.EndsWith(".daq"))
    baseName.ReplaceAll(".daq",".hist.root");
  else if (baseName.EndsWith(".event.root"))
    baseName.ReplaceAll(".event.root",".hist.root");
  else if (baseName.EndsWith(".MuDst.root"))
    baseName.ReplaceAll(".MuDst.root",".hist.root");

  TString histFile = baseName;

  baseName.Remove(0,baseName.Last('/')+1);

  TString outputName = baseName;
  outputName.ReplaceAll(".root",".CC");

  TString histList = "StRoot/St_QA_Maker/QAhlist_Reco.h";
  if (! gSystem->Which(".",histList.Data()))
    histList.Prepend(gSystem->ExpandPathName("$STAR/"));
  
  bfcread_hist_prefixes_add_to_ps(histFile.Data(),"EventQA",
    "bfcTree",outputName.Data(),baseName.Data(),histList.Data());
}
コード例 #5
0
ファイル: makehlt_tree.C プロジェクト: manuelfs/ucsb_analysis
void makehlt_tree(TString filename, TString outfolder="root/hlt/sep4/"){
  TString cuts[] = {"onelpt>15", "onmupt>15"};
  TString tags[] = {"el15", "mu15"}, folder, sCut;

  TChain tree("tree"); TChain treeglobal("treeglobal");
  tree.Add(filename); treeglobal.Add(filename);
  vector<int> genlep_thresh, v_nori_genels, v_nori_genmus;
  vector<int> *nori_genels = &v_nori_genels, *nori_genmus = &v_nori_genmus;
  int noriginal, nori_genmu0, nori_genel0;
  treeglobal.SetBranchAddress("noriginal",&noriginal);
  treeglobal.GetEntry(0);

  genlep_thresh.push_back(0); genlep_thresh.push_back(10); 
  genlep_thresh.push_back(15); genlep_thresh.push_back(17); 
  genlep_thresh.push_back(20); genlep_thresh.push_back(25); 
  for(unsigned ind(0); ind<genlep_thresh.size(); ind++){
    sCut = "Max$(genels_pt)>"; sCut += genlep_thresh[ind];
    v_nori_genels.push_back(tree.GetEntries(sCut));
    sCut = "Max$(genmus_pt)>"; sCut += genlep_thresh[ind];
    v_nori_genmus.push_back(tree.GetEntries(sCut));
  }
  nori_genel0 = v_nori_genels[0]; nori_genmu0 = v_nori_genmus[0]; 

  filename.Remove(0,filename.Last('/')+1);
  filename.ReplaceAll(".root","");
  for(int cut(0); cut<2; cut++){
    folder = outfolder+"/"+tags[cut]+"/";
    gSystem->mkdir(folder, kTRUE);
    TTree *ctree = tree.CopyTree(cuts[cut]);
    folder += filename+"_"+tags[cut]+".root";
    ctree->SaveAs(folder);

    TFile file(folder,"UPDATE");
    file.cd();
    TTree ctreeglobal("treeglobal", "treeglobal");
    ctreeglobal.Branch("noriginal",&noriginal);
    ctreeglobal.Branch("nori_genels",&nori_genels);
    ctreeglobal.Branch("nori_genmus",&nori_genmus);
    ctreeglobal.Branch("nori_genel0",&nori_genel0);
    ctreeglobal.Branch("nori_genmu0",&nori_genmu0);
    ctreeglobal.Branch("genlep_thresh", &genlep_thresh);
    ctreeglobal.Fill();
    ctreeglobal.Write();
    file.Close();
  }


}
コード例 #6
0
void misalignmentDependence(Int_t nFiles,TString *files,TString *names,TString misalignment,Double_t *values,Double_t *phases,TString xvar,TString yvar,
                            TString function,Int_t nParameters,Int_t *parameters,TString *parameternames,TString functionname = "",
                            Bool_t resolution = false,
                            TString saveas = "")
{
    for (int i = 0; i < nParameters; i++)
    {
        TString saveasi = saveas;
        TString insert = nPart(1,parameternames[i]);
        insert.Prepend(".");
        saveasi.Insert(saveasi.Last('.'),insert);    //insert the parameter name before the file extension
        misalignmentDependence(nFiles,files,names,misalignment,values,phases,xvar,yvar,
                               function,parameters[i],parameternames[i],functionname,
                               resolution,
                               saveasi);
    }
}
コード例 #7
0
void writeFile(const char* inRootFile)
{
  TFile inRoot(inRootFile);
  if(!inRoot.IsOpen()){
    cout << "Cannot open " << inRootFile << endl;
    return;
  }
  TIterator* iterator = inRoot.GetListOfKeys()->MakeIterator();
  TKey* key;

  TString outText = inRootFile;
  outText.Replace(0,outText.Last('/')+1,"");

  ofstream os(outText.Data());

  char buf[500];

  int count(0);
  while( (key=dynamic_cast<TKey*>(iterator->Next())) != 0){
    cout << key->GetName() << endl;
    TH1* h = (TH1*)inRoot.Get(key->GetName());
    if(h->GetDimension()!=1) continue;

    if(++count>1) break;

    int nBin = h->GetNbinsX();
    os << "name: " << h->GetName() << endl
       << "title: " << h->GetTitle() << endl
       << "bins: " << h->GetNbinsX() << endl
       << "min: " << h->GetXaxis()->GetBinLowEdge(1) 
       << ", max: " << h->GetXaxis()->GetBinUpEdge(h->GetNbinsX()) << endl;

    for(int i=1; i<=nBin; i++){
      os << "bin: " << i << " value: " << (float)h->GetBinContent(i)
	 << " error: " << (float)h->GetBinError(i) << endl;
    }
  }
   
}
コード例 #8
0
void write_ist_pednoise() {
	gSystem->Setenv("DB_ACCESS_MODE", "write");
  	gROOT->Macro("LoadLogger.C");
  	gSystem->Load("St_base.so");
  	gSystem->Load("libStDb_Tables.so");
  	gSystem->Load("StDbLib.so");

	std::ifstream fPDlist("/star/u/ypwang/disk01/offline_hft/DB/pedNoiseTable4DB/pedNoiseFiles_Corr/pedRunList_Corr.txt");
        if(!fPDlist.is_open())
        {
                std::cout << " There is no corrected pedRunList file! " << endl;
                exit(0);
        }

        while(!fPDlist.eof()) {
                TString  sPDfile;
                fPDlist >> sPDfile;

                int found = sPDfile.Last('_');
                if(found >= 0)
                        sPDfile.Replace(0, found + 1, "");

                found = sPDfile.Last('.');
                if(found >= 0)
                        sPDfile.Replace(found, sPDfile.Length(), "");

                int runnumb = sPDfile.Atoi();
                if(runnumb)
                        pedRunNumVec.push_back(runnumb);
        }
        fPDlist.close();
	const int nPedRuns = pedRunNumVec.size();
	cout << nPedRuns << " good pedestal runs recorded! " << endl;
        if(debug) {
                for(int i=0; i<nPedRuns; i++)
                        cout << i << "th pedestal run: " << pedRunNumVec[i] << endl;
        }


  	std::ifstream fCosmicRunList("/star/u/ypwang/disk01/offline_hft/DB/pedNoiseTable4DB/cmNoise_cosmic/cosmicRunlist.txt");
        if(!fCosmicRunList.is_open())
        {
                std::cout << " There is no cosmicRunList file! " << endl;
                exit(0);
        }

        while(!fCosmicRunList.eof()) {
                TString  sCMNfile;
                fCosmicRunList >> sCMNfile;

                int found = sCMNfile.First('.');
                if(found >= 0)
                        sCMNfile.Replace(found, sCMNfile.Length(), "");

                int runnumb = sCMNfile.Atoi();
                if(runnumb)
                        cosmicRunNumVec.push_back(runnumb);
        }
        fCosmicRunList.close();
	const int nCosmicRuns = cosmicRunNumVec.size();
	cout << nCosmicRuns << " good cosmic runs recorded! " << endl;
        if(debug) {
                for(int i=0; i<nCosmicRuns; i++)
                        cout << i << "th cosmic run: " << cosmicRunNumVec[i] << endl;
        }

	Int_t   isBadChannel[110592];
        Int_t   isBadChip[864];
	//loop pedestal runs
	for(int iRun=0; iRun<nPedRuns; iRun++)
        {
                int runNumber = pedRunNumVec[iRun];
		//below only for testing
		//if(runNumber<15065020) continue;

                int TbinPD = PDTBin(runNumber);
		cout << "Reading pedestal run " << runNumber << " with " << TbinPD << " time bins! " << endl;
		
		//retrieve time stamp information
		char cmd[256];
            	sprintf(cmd, "/usr/bin/mysql -h dbbak.starp.bnl.gov --port=3413 -e \"SELECT FROM_UNIXTIME(startRunTime) as beginTime_human FROM RunLog.runDescriptor WHERE runNumber = %d\" >timeStamp_tmp", runNumber);
            	system(cmd);

            	TString mTimeStamp;
            	FILE *inR = fopen("timeStamp_tmp","r");
            	while(!feof(inR)) {
                	char buff[64];
                	if(fgets(buff,sizeof(buff),inR) == 0) continue ;
                	switch(buff[0]) {
                    		case 'b' : //beginTime_human
                        		continue ;
                	}
                	mTimeStamp = Form(buff);
            	}
            	fclose(inR);

            	sprintf(cmd, "/bin/rm timeStamp_tmp");
            	system(cmd);

		int found = 19;
            	mTimeStamp.Replace(found, mTimeStamp.Length(), "");
            	cout << iRun << ": \t" << runNumber << "\t" << mTimeStamp << endl;
	
		//find the closest cosmic run to match, and using its common-mode noise
		int diffRun = 15000000, miniDiffRun = 15000000;
		int matchedCosmicRunNumber = 15032029;
		for(int iCosmic=0; iCosmic<nCosmicRuns; iCosmic++) {
			diffRun = cosmicRunNumVec[iCosmic] - runNumber;
			if(diffRun < miniDiffRun && diffRun > 0) { //corresponding cosmic run should come after the pedestal run
				miniDiffRun = diffRun;
				matchedCosmicRunNumber = cosmicRunNumVec[iCosmic];
			}
		}
		if(runNumber>=15158006) matchedCosmicRunNumber = 15157002; //if no later cosmic runs found, then use the last one
		int TbinCMN = CMTBin(matchedCosmicRunNumber);
		cout << "Matched cosmic run " << matchedCosmicRunNumber << " with " << TbinCMN << " time bins! " << endl;
		
		StDbManager* mgr = StDbManager::Instance();
  		StDbConfigNode* node = mgr->initConfig("Calibrations_ist");
  		StDbTable* dbtable = node->addDbTable("istPedNoise");
  		mgr->setStoreTime(mTimeStamp.Data());
		
		//open matched CMN DB file
		std::ifstream inCMN(Form("/star/u/ypwang/disk01/offline_hft/DB/pedNoiseTable4DB/cmNoise_cosmic/%d.istCmNoise.dat", matchedCosmicRunNumber));
    		if (!inCMN.is_open()) {
    			std::cout << " There is no CMN DB file  " << end ;
    			exit(0);
    		}

		//open corrected pedestal/RMS DB file
		std::ifstream inPD(Form("/star/u/ypwang/disk01/offline_hft/DB/pedNoiseTable4DB/pedNoiseFiles_Corr/IST_pedestals_%d.txt", runNumber));
    		if (!inPD.is_open()) {
    			std::cout << " There is no PED/RMS DB file  " << end ;
    			exit(0);
    		}
	
		//retreive online masking chip/channel and offline channel masking
		for(int i=0; i<110592; i++) {
                    isBadChannel[i] = 0;
                }

		for(int i=0; i<864; i++) {
                    isBadChip[i] = 0;
                }
		
		//online masking-out chips
		int tem_Run, tem_Rdo, tem_Arm, tem_Group, tem_Apv, tem_Status, ChipEID;
		int deadChipsInRun14 = 31, deadChipCounter=0;
                if(runNumber<15181030) {
                    std::ifstream deadChipList("/star/u/ypwang/disk01/offline_hft/DB/pedNoiseTable4DB/ist_apv_dead.txt");
                }
                else {
                    std::ifstream deadChipList("/star/u/ypwang/disk01/offline_hft/DB/pedNoiseTable4DB/ist_apv_dead_AuHe3.txt");
                    deadChipsInRun14 = 29; //since run 15174075 (June 23, 2014), two chips (566/567) were taken out of online mask-out chip list
                }
		if(!deadChipList.is_open()) 
		{
                        cout << "ist_apv_dead file was NOT found " << endl;
                        exit(0);
                }

		int deadChipId = -1;
                while(!deadChipList.eof() && deadChipCounter<deadChipsInRun14) {
                    deadChipList >> tem_Rdo >> tem_Arm >> tem_Apv;
                    deadChipId = (tem_Rdo-1)*6*24 + tem_Arm*24 + tem_Apv; //electronics ID
                    if(deadChipId<0 || deadChipId>=864) continue;

		    int deadChipGeomIdx = elecIdToGeomId(deadChipId);
                    isBadChip[deadChipGeomIdx-1] = 1; //dead chip
                    deadChipCounter++;
                }
                deadChipList.close();
		cout << "Number of online masking-out chips: " << deadChipCounter << endl;

		//mis-configured chips
                std::ifstream misConfigChiplist("/star/u/ypwang/disk01/offline_hft/DB/pedNoiseTable4DB/ist_apv_bad.txt");
                if(!misConfigChiplist.is_open())
                {
                        cout << "ist_apv_bad file was NOT found " << endl;
                        exit(0);
                }
		
		int badChipCounter = 0;
		while(!misConfigChiplist.eof()) //mis-configured chips recorded since 15065020
                {
                        misConfigChiplist >> tem_Run >> tem_Rdo >> tem_Arm >> tem_Group >> tem_Apv >> tem_Status;
                        if(tem_Run == matchedCosmicRunNumber)
                        {
                                ChipEID = (tem_Rdo - 1) * 6 * 24 + tem_Arm * 24 + tem_Group * 12 + tem_Apv;
                                if(ChipEID<0 || ChipEID>=864) continue;

				int badChipGeomIdx = elecIdToGeomId(ChipEID);
                                isBadChip[badChipGeomIdx-1] = 2; //mis-configured chip
                                badChipCounter++;
                        }
                }
                misConfigChiplist.close();
		cout << "Number of offine masking-out chips: " << badChipCounter << endl;

		//online masking-out channel list
		Int_t   rdoIndex = -1, armIndex = -1, apvIndex = -1, chanIndex = -1;
                Int_t   channelId = -1;

		std::ifstream badChannelListOnline("/star/u/ypwang/disk01/offline_hft/DB/pedNoiseTable4DB/channelMaskingList_ist_online.txt"); //179 bad channels masked out online
		if(!badChannelListOnline.is_open()) 
		{
                        cout << "channelMaskingList_ist_online file was NOT found " << endl;
                        exit(0);
                }

		int deadChannelCounter = 0;
                while(!badChannelListOnline.eof()) {
                        badChannelListOnline >> rdoIndex >> armIndex >> apvIndex >> chanIndex;
                        channelId = (rdoIndex-1)*6*24 + armIndex*24 + apvIndex*128 + chanIndex;
                        isBadChannel[channelId] = 1;
			deadChannelCounter++;
                }
                badChannelListOnline.close();
		cout << "Number of online masking-out channels: " << deadChannelCounter << endl;

		//offline masking-out channel list
                std::ifstream badChannelListOfflineB("/star/u/ypwang/disk01/offline_hft/DB/pedNoiseTable4DB/ChannelMaskList.20140601.txt"); //336 bad channels masked out offline
		if(!badChannelListOfflineB.is_open())
		{
			cout << "ChannelMaskList.20140601 file was NOT found " << endl;
                        exit(0);
		}

		int badChannelCounter = 0;
                while(!badChannelListOfflineB.eof()) {
                        badChannelListOfflineB >> channelId;
                        isBadChannel[channelId] = 2;
			badChannelCounter++;
                }
                badChannelListOfflineB.close();
		cout << "Number of offline masking-out channels: " << badChannelCounter << endl;

		istPedNoise_st table;
		for (int i = 0; i < 110592; i++) {
    			table.pedestal[i] = 0;
    			table.rmsNoise[i] = 0;
  		}

  		for (int i = 0; i < 864; i++) {
    			table.cmNoise[i] = 0;
  		}

		//Pedestal and RMS Noise
		Float_t pedestalT, rmsT;
		Float_t averagePed = 0., averageRms = 0.;
		Int_t timebin = -1;
		channelId = -1;
		for (int counter=0; counter<110592*TbinPD; counter++){
			inPD >> rdoIndex >> armIndex >> apvIndex >> chanIndex >> timebin >> pedestalT >> rmsT;
			channelId = (rdoIndex - 1) * 6 * 24 * 128 + armIndex * 24 * 128 + apvIndex * 128 + chanIndex;
			if(channelId<0 || channelId>=110592) continue;
    			averagePed += pedestalT/TbinPD;
    			averageRms += rmsT/TbinPD;

    			if(((timebin+1)/TbinPD) && ((counter+1)/TbinPD)) {
        			//cout << counter/TbinPD << ": channelId = " << channelId<<"\t pedestal = "<<averagePed<<"\t rms = "<<averageRms<<endl;

        			table.pedestal[channelId] = (int)averagePed;
        			table.rmsNoise[channelId] = (int)(averageRms*100);
				//masking-out online/offline bad channels
				if(isBadChannel[channelId]) 
					table.rmsNoise[channelId] = 10000;
				if(debug)
					cout << counter/TbinPD << ": channelId = " << channelId << "\t pedestal = " << table.pedestal[channelId] << "\t rms = " << table.rmsNoise[channelId] <<endl;
        			averagePed = 0.;
        			averageRms = 0.;
    			}
  		}
  		inPD.close();

		//Common Mode Noise
		Float_t cmNoiseT;
		Float_t averageCmNoise = 0.;
		Int_t chipId;
		Int_t numTimeBins = 9; //IST CMN DB files output 9 time bins format in default
		for(int counter=0; counter<864*numTimeBins; counter++){
    			inCMN >> chipId >> timebin >> cmNoiseT;
    			averageCmNoise += cmNoiseT/TbinCMN;

    			if(((timebin+1)/numTimeBins) && ((counter+1)/numTimeBins)) {
        			//cout << counter/numTimeBins << ": chipId = " << chipId << " cmNoiseT = " << averageCmNoise << endl;
        			table.cmNoise[chipId] = (int)(averageCmNoise*100);
				//masking-out online/offline bad chips
				if(isBadChip[chipId])
					table.cmNoise[chipId] = 10000;
				if(debug)
					cout << counter/numTimeBins << ": chipId = " << chipId << " cmNoiseT = " << table.cmNoise[chipId] << endl;
        			averageCmNoise = 0.;
    			}
  		}
  		inCMN.close();

		// Please comment out below lines if you do testing, or it will write the DB!!!!
		// Store data to the StDbTable
		dbtable->SetTable((char*)&table, 1);

		// Store table to database
		mgr->storeDbTable(dbtable);

		//exit(0); //only for testing
	}
};
コード例 #9
0
ファイル: studyBinZero.C プロジェクト: ktf/AliPhysics
//___________________________________________________________________
Int_t studyBinZero(TString pathData, TString fileNameData, TString listName = "",
                   Double_t etaLow = -0.9, Double_t etaUp = 0.9,
                   Double_t lowerCentrality = -2, Double_t upperCentrality = -2)
{
  PrintSettingsAxisRangeForMultiplicityAxisForMB();
  
  TString pathNameData = Form("%s/%s", pathData.Data(), fileNameData.Data());
  
  if (listName == "") {
    listName = pathNameData;
    listName.Replace(0, listName.Last('/') + 1, "");
    listName.ReplaceAll(".root", "");
  }
  
  TObjArray* histList = 0x0;
  
  TFile* f = TFile::Open(pathNameData.Data());
  if (!f)  {
    std::cout << std::endl;
    std::cout << "Failed to open file \"" << pathNameData.Data() << "\"!" << std::endl;
    return -1;
  }
  
  histList = (TObjArray*)(f->Get(listName.Data()));
  if (!histList) {
    std::cout << std::endl;
    std::cout << "Failed to load list \"" << listName.Data() << "\"!" << std::endl;
    return -1;
  }
  
  // Extract the data histograms
  TH1* hNumEventsTriggerSel = dynamic_cast<TH1*>(histList->FindObject("fhEventsTriggerSel"));
  TH1* hNumEventsTriggerSelVtxCut = dynamic_cast<TH1*>(histList->FindObject("fhEventsTriggerSelVtxCut"));
  TH1* hNumEventsTriggerSelVtxCutZ= dynamic_cast<TH1*>(histList->FindObject("fhEventsProcessedNoPileUpRejection"));
  TH1* hNumEventsTriggerSelVtxCutZPileUpRej= dynamic_cast<TH1*>(histList->FindObject("fhEventsProcessed"));
  
  THnSparse* hDataTriggerSel = dynamic_cast<THnSparse*>(histList->FindObject("fChargedGenPrimariesTriggerSel"));
  THnSparse* hDataTriggerSelVtxCut = dynamic_cast<THnSparse*>(histList->FindObject("fChargedGenPrimariesTriggerSelVtxCut"));
  THnSparse* hDataTriggerSelVtxCutZ = dynamic_cast<THnSparse*>(histList->FindObject("fChargedGenPrimariesTriggerSelVtxCutZ"));
  THnSparse* hDataTriggerSelVtxCutZPileUpRej = dynamic_cast<THnSparse*>(histList->FindObject("fChargedGenPrimariesTriggerSelVtxCutZPileUpRej"));
  
  setSparseErrors(hDataTriggerSel);
  setSparseErrors(hDataTriggerSelVtxCut);
  setSparseErrors(hDataTriggerSelVtxCutZ);
  setSparseErrors(hDataTriggerSelVtxCutZPileUpRej);
  
  
  
  // Set multiplicity range, if desired. Note that mult and pT axes are the same for all histos
  Int_t lowerCentralityBinLimit = -1;
  Int_t upperCentralityBinLimit = -2;
  Bool_t restrictCentralityAxis = kFALSE;
  Double_t actualLowerCentrality = -1.;
  Double_t actualUpperCentrality = -1.;
  
  if (lowerCentrality >= -1 && upperCentrality >= -1) {
    // Add subtract a very small number to avoid problems with values right on the border between to bins
    lowerCentralityBinLimit = hNumEventsTriggerSel->GetXaxis()->FindFixBin(lowerCentrality + 0.001);
    upperCentralityBinLimit = hNumEventsTriggerSel->GetXaxis()->FindFixBin(upperCentrality - 0.001);
    
    // Check if the values look reasonable
    if (lowerCentralityBinLimit <= upperCentralityBinLimit && lowerCentralityBinLimit >= 1
        && upperCentralityBinLimit <= hNumEventsTriggerSel->GetXaxis()->GetNbins()) {
      actualLowerCentrality = hNumEventsTriggerSel->GetXaxis()->GetBinLowEdge(lowerCentralityBinLimit);
      actualUpperCentrality = hNumEventsTriggerSel->GetXaxis()->GetBinUpEdge(upperCentralityBinLimit);

      restrictCentralityAxis = kTRUE;
    }
    else {
      std::cout << std::endl;
      std::cout << "Requested centrality range out of limits or upper and lower limit are switched!" << std::endl;
      return -1;
    }
  }
  
  if (!restrictCentralityAxis)
    GetAxisRangeForMultiplicityAxisForMB(hNumEventsTriggerSel->GetXaxis(), lowerCentralityBinLimit, upperCentralityBinLimit);
  
  hNumEventsTriggerSel->GetXaxis()->SetRange(lowerCentralityBinLimit, upperCentralityBinLimit);
  
  actualLowerCentrality = hNumEventsTriggerSel->GetXaxis()->GetBinLowEdge(hNumEventsTriggerSel->GetXaxis()->GetFirst());
  actualUpperCentrality = hNumEventsTriggerSel->GetXaxis()->GetBinUpEdge(hNumEventsTriggerSel->GetXaxis()->GetLast());
  
  std::cout << "centrality: ";
  if (restrictCentralityAxis) {
    std::cout << actualLowerCentrality << " - " << actualUpperCentrality << std::endl;
    std::cout << "WARNING: Does it really make sense to restrict the centrality? Usually, centrality estimators imply centrality >= 0!"
              << std::endl;
  }
  else
    std::cout << "MB (" << actualLowerCentrality << " - " << actualUpperCentrality << ")" << std::endl;
    
  if (restrictCentralityAxis) {
    hDataTriggerSel->GetAxis(iMult)->SetRange(lowerCentralityBinLimit, upperCentralityBinLimit);
    hDataTriggerSelVtxCut->GetAxis(iMult)->SetRange(lowerCentralityBinLimit, upperCentralityBinLimit);
    hDataTriggerSelVtxCutZ->GetAxis(iMult)->SetRange(lowerCentralityBinLimit, upperCentralityBinLimit);
    hDataTriggerSelVtxCutZPileUpRej->GetAxis(iMult)->SetRange(lowerCentralityBinLimit, upperCentralityBinLimit);
  }
  
  
  // Restrict eta range
  const Int_t lowerEtaBinLimit = hDataTriggerSel->GetAxis(iEta)->FindFixBin(etaLow + 0.0001);
  const Int_t upperEtaBinLimit = hDataTriggerSel->GetAxis(iEta)->FindFixBin(etaUp  - 0.0001);
  
  const Double_t actualLowerEta = hDataTriggerSel->GetAxis(iEta)->GetBinLowEdge(lowerEtaBinLimit);
  const Double_t actualUpperEta = hDataTriggerSel->GetAxis(iEta)->GetBinUpEdge(upperEtaBinLimit);
  
  std::cout << "Eta: ";
  std::cout << actualLowerEta << " - " << actualUpperEta << std::endl;
  
  
  
  Bool_t symmetricInEta = TMath::Abs(TMath::Abs(actualLowerEta) - TMath::Abs(actualUpperEta)) < 1e-6;
  TString etaRange = symmetricInEta ? Form("|#it{#eta}| < %.1f", TMath::Abs(actualLowerEta)) 
                                    : Form("%.1f < #it{#eta} < %.1f", actualLowerEta, actualUpperEta); 
  
  hDataTriggerSel->GetAxis(iEta)->SetRange(lowerEtaBinLimit, upperEtaBinLimit);
  hDataTriggerSelVtxCut->GetAxis(iEta)->SetRange(lowerEtaBinLimit, upperEtaBinLimit);
  hDataTriggerSelVtxCutZ->GetAxis(iEta)->SetRange(lowerEtaBinLimit, upperEtaBinLimit);
  hDataTriggerSelVtxCutZPileUpRej->GetAxis(iEta)->SetRange(lowerEtaBinLimit, upperEtaBinLimit);
  
  // Obtain number of events for each class
  // Note: Under- and overflow automatically taken into account for unrestricted axis by using -1 and -2 for limits
  const Double_t numEvtsTriggerSel = hNumEventsTriggerSel->Integral(lowerCentralityBinLimit, upperCentralityBinLimit);
  const Double_t numEvtsTriggerSelVtxCut = hNumEventsTriggerSelVtxCut->Integral(lowerCentralityBinLimit, upperCentralityBinLimit);
  const Double_t numEvtsTriggerSelVtxCutZ = hNumEventsTriggerSelVtxCutZ->Integral(lowerCentralityBinLimit, upperCentralityBinLimit);
  const Double_t numEvtsTriggerSelVtxCutZPileUpRej = hNumEventsTriggerSelVtxCutZPileUpRej->Integral(lowerCentralityBinLimit,
                                                                                                    upperCentralityBinLimit);
  
  // Project pT spectra
  TH1D* hSpectraTriggerSel = (TH1D*)hDataTriggerSel->Projection(iPt, "e");
  TH1D* hSpectraTriggerSelVtxCut = (TH1D*)hDataTriggerSelVtxCut->Projection(iPt, "e");
  TH1D* hSpectraTriggerSelVtxCutZ = (TH1D*)hDataTriggerSelVtxCutZ->Projection(iPt, "e");
  TH1D* hSpectraTriggerSelVtxCutZPileUpRej = (TH1D*)hDataTriggerSelVtxCutZPileUpRej->Projection(iPt, "e");
  
  // Normalise histos to 1/Nevt dN/dPt
  normaliseHist(hSpectraTriggerSel, numEvtsTriggerSel);
  normaliseHist(hSpectraTriggerSelVtxCut, numEvtsTriggerSelVtxCut);
  normaliseHist(hSpectraTriggerSelVtxCutZ, numEvtsTriggerSelVtxCutZ);
  normaliseHist(hSpectraTriggerSelVtxCutZPileUpRej, numEvtsTriggerSelVtxCutZPileUpRej);
  
  setupHist(hSpectraTriggerSel, kBlack, "Trigger selection");
  setupHist(hSpectraTriggerSelVtxCut, kRed, "& vertex cut");
  setupHist(hSpectraTriggerSelVtxCutZ, kBlue, "& vertex #it{z} cut");
  setupHist(hSpectraTriggerSelVtxCutZPileUpRej, kGreen, "& pile-up rejection");
  
  TCanvas* canvSpectra = new TCanvas("canvSpectra", "Spectra", 760, 420);
  canvSpectra->SetLogx();
  canvSpectra->SetLogy();
  canvSpectra->SetGrid(0, 0);
  SetCanvasMargins(canvSpectra);
  
  TLegend* leg = new TLegend(0.14, 0.26, 0.62, 0.55);
  leg->SetHeader(Form("MC pp #sqrt{s}=7 TeV, inclusive, %s", etaRange.Data()));
  leg->AddEntry(hSpectraTriggerSel, "", "l");
  leg->AddEntry(hSpectraTriggerSelVtxCut, "", "l");
  leg->AddEntry(hSpectraTriggerSelVtxCutZ, "", "l");
  if (drawPileUp)
    leg->AddEntry(hSpectraTriggerSelVtxCutZPileUpRej, "", "l");
  SetupLegend(leg);
  leg->SetMargin(0.15);
  
  hSpectraTriggerSel->Draw();
  hSpectraTriggerSelVtxCut->Draw("same");
  hSpectraTriggerSelVtxCutZ->Draw("same");
  if (drawPileUp)
    hSpectraTriggerSelVtxCutZPileUpRej->Draw("same");
  
  leg->Draw("same");
  
  // Ratios (take binomial errors, since real sub-samples)
  
  TH1D* hRatioVtxCut = new TH1D(*hSpectraTriggerSelVtxCut);
  hRatioVtxCut->SetName("hRatioVtxCut");
  setupHist(hRatioVtxCut, kBlack, "MB & vtx / MB");
  hRatioVtxCut->GetYaxis()->SetTitle("1/#it{N}_{evt} d#it{N}/d#it{p}_{T}^{gen} ratio");
  hRatioVtxCut->Divide(hRatioVtxCut, hSpectraTriggerSel, 1., 1., "B");
  hRatioVtxCut->GetYaxis()->SetRangeUser(1.08, 1.14);
  
  // Mean ratio of spectra and of Nevt
  TF1* funcRatioVtxCut = new TF1("funcRatioVtxCut", "pol0",
                                 0.15, hRatioVtxCut->GetXaxis()->GetBinUpEdge(hSpectraTriggerSelVtxCut->FindLastBinAbove(0)));
  funcRatioVtxCut->SetLineWidth(2);
  funcRatioVtxCut->SetLineColor(kRed);
  hRatioVtxCut->Fit(funcRatioVtxCut, "N");
  const Double_t meanRatioVtxCut = funcRatioVtxCut->GetParameter(0);
  const Double_t ratioNevtVtxCut = numEvtsTriggerSelVtxCut > 0 ? numEvtsTriggerSel / numEvtsTriggerSelVtxCut : -1.;
  const Double_t doubleRatioMinusOne = meanRatioVtxCut > 0 ? (ratioNevtVtxCut / meanRatioVtxCut - 1.) : -999.;
  
  
  
  TH1D* hRatioVtxCutZ = new TH1D(*hSpectraTriggerSelVtxCutZ);
  hRatioVtxCutZ->SetName("hRatioVtxCutZ");
  setupHist(hRatioVtxCutZ, kBlack, "MB & vtx & #it{z} vtx / MB & vtx");
  hRatioVtxCutZ->GetYaxis()->SetTitle("1/#it{N}_{evt} d#it{N}/d#it{p}_{T}^{gen} ratio");
  hRatioVtxCutZ->Divide(hRatioVtxCutZ, hSpectraTriggerSelVtxCut, 1., 1., "B");
  hRatioVtxCutZ->GetYaxis()->SetRangeUser(0.95, 1.05);
  
  // Mean ratio of spectra and of Nevt
  TF1* funcRatioVtxCutZ = new TF1("funcRatioVtxCutZ", "pol0",
                                  0.15, hRatioVtxCutZ->GetXaxis()->GetBinUpEdge(hSpectraTriggerSelVtxCutZ->FindLastBinAbove(0)));
  hRatioVtxCutZ->Fit(funcRatioVtxCutZ, "N");
  funcRatioVtxCutZ->SetLineWidth(2);
  funcRatioVtxCutZ->SetLineColor(kRed);
  const Double_t meanRatioVtxCutZ = funcRatioVtxCutZ->GetParameter(0);
  const Double_t ratioNevtVtxCutZ = numEvtsTriggerSelVtxCutZ > 0 ? numEvtsTriggerSelVtxCut / numEvtsTriggerSelVtxCutZ : -1.;
  
  TH1D* hRatioPileUp = new TH1D(*hSpectraTriggerSelVtxCutZPileUpRej);
  hRatioPileUp->SetName("hRatioPileUp");
  setupHist(hRatioPileUp, kBlack, "MB & vtx & #it{z} vtx & pile-up / MB & vtx & #it{z} vtx");
  hRatioPileUp->GetYaxis()->SetTitle("1/#it{N}_{evt} d#it{N}/d#it{p}_{T}^{gen} ratio");
  hRatioPileUp->Divide(hRatioPileUp, hSpectraTriggerSelVtxCutZ, 1., 1., "B");
  
  /*
  TF1* funcRatioPileUp = new TF1("funcRatioPileUp", "pol0",
                                 0.15, hRatioPileUp->GetXaxis()->GetBinUpEdge(hSpectraTriggerSelVtxCutZPileUpRej->FindLastBinAbove(0)));
  hRatioPileUp->Fit(funcRatioPileUp, "N");*/
  
  ClearTitleFromHistoInCanvas(canvSpectra);
  
  TCanvas* canvRatioVtx = new TCanvas("canvRatioVtx", "Ratio vertex", 760, 420);
  canvRatioVtx->SetLogx();
  canvRatioVtx->SetGrid(0, 1);
  SetCanvasMargins(canvRatioVtx);
  
  hRatioVtxCut->Draw();
  funcRatioVtxCut->Draw("same");
  
  TLegend* leg2 = new TLegend(0.22, 0.7, drawPileUp ? 0.87 : 0.72, 0.9);
  leg2->SetHeader(Form("MC pp #sqrt{s}=7 TeV, inclusive, %s", etaRange.Data()));
  leg2->AddEntry(hRatioVtxCut, "", "l");
  SetupLegend(leg2);
  leg2->SetMargin(0.1);
  
  leg2->Draw("same");
  
  ClearTitleFromHistoInCanvas(canvRatioVtx);
  
  TCanvas* canvRatioOther = new TCanvas("canvRatioOther", "Ratio others", 760, 420);
  canvRatioOther->SetLogx();
  canvRatioOther->SetGrid(0, 1);
  SetCanvasMargins(canvRatioOther);
  
  hRatioVtxCutZ->Draw();
  if (drawPileUp)
    hRatioPileUp->Draw("same");

  TLegend* leg3 = new TLegend(0.22, drawPileUp ? 0.63 : 0.7, drawPileUp ? 0.87 : 0.72, 0.9);
  leg3->SetHeader(Form("MC pp #sqrt{s}=7 TeV, inclusive, %s", etaRange.Data()));
  leg3->AddEntry(hRatioVtxCutZ, "", "l");
  if (drawPileUp)
    leg3->AddEntry(hRatioPileUp, "", "l");
  SetupLegend(leg3);
  leg3->SetMargin(0.1);
  
  leg3->Draw("same");
  
  ClearTitleFromHistoInCanvas(canvRatioOther);

  
  printf("meanRatioVtxCut %f <-> ratioNevtVtxCut %f => meanRatioVtxCutZ/ratioNevtVtxCutZ - 1 = %f\nmeanRatioVtxCutZ %f <-> ratioNevtVtxCutZ %f\n",
         meanRatioVtxCut, ratioNevtVtxCut, doubleRatioMinusOne, meanRatioVtxCutZ, ratioNevtVtxCutZ);
  
  
  TNamed* settings = new TNamed(
      Form("Settings: Data file \"%s\", lowerEta %.2f, uppEta %.2f, lowerCentrality %.3f, upperCentrality %.3f, doubleRatioMinusOne %.4f\n",
           pathNameData.Data(), etaLow, etaUp, lowerCentrality, upperCentrality, doubleRatioMinusOne), "");
  
  // Save results to file
  TString saveFileName = pathNameData;
  saveFileName = Form("%s_binZeroStudy.root", saveFileName.ReplaceAll(".root", "").Data());
  TFile *saveFile = TFile::Open(saveFileName.Data(), "RECREATE");
  saveFile->cd();
  hSpectraTriggerSel->Write();
  hSpectraTriggerSelVtxCut->Write();
  hSpectraTriggerSelVtxCutZ->Write();
  hSpectraTriggerSelVtxCutZPileUpRej->Write();
  
  hRatioVtxCut->Write();
  hRatioVtxCutZ->Write();
  hRatioPileUp->Write();
  
  funcRatioVtxCut->Write();
  funcRatioVtxCutZ->Write();
  
  canvSpectra->Write();
  canvRatioVtx->Write();
  canvRatioOther->Write();
  
  settings->Write();
  
  saveFile->Close();
  
  TString temp = saveFileName;
  canvRatioVtx->SaveAs(Form("%s", temp.ReplaceAll(".root", "_ratioVtx.pdf").Data()));
  temp = saveFileName;
  canvRatioOther->SaveAs(Form("%s", temp.ReplaceAll(".root", "_ratioOther.pdf").Data()));
  
  PrintSettingsAxisRangeForMultiplicityAxisForMB();
  
  return 0;
}
コード例 #10
0
ファイル: PlotSingle.C プロジェクト: manuelfs/babar_code
void PlotSingle(TString hname){
  TString sam = hname; sam.Remove(0,sam.First('_')+1);
  sam.Remove(sam.First('_'),sam.Length());
  TString smoo = hname;smoo.Remove(0,smoo.Last('_')+1);
  smoo.Remove(smoo.First('.'),smoo.Length());
  TString binString = hname; binString.Remove(binString.Last('_'),binString.Length());
  binString.Remove(0,binString.Last('_')+1);
  int nM2bin = binString.Atoi(); int nPlbin = nM2bin%1000;
  nM2bin = nM2bin/1000;
  TString basename(hname);
  Int_t slashpos = basename.Last('D');
  if (slashpos>=0) {
    basename.Remove(0,slashpos+1); basename.Remove(basename.First('.'),basename.Length());
  } else { cout<<hname<<" is incorrect"<<endl; return;}

  TString Base = "_"; Base += sam; Base += "_"; 
  Base += binString; Base += "_"; Base += smoo; 

  TFile hfile(hname); 
  TH2F *h2 = (TH2F *)gDirectory->Get("h2");
  TString inputfile = "fitSamples/pdfSample"; inputfile += sam; inputfile += ".root";
  cout << "File = " << inputfile << endl;	
  TChain c("ntp1");
  c.Add(inputfile);
  TCanvas mm("mm","KEYS fits to mmiss-pstarl",1200,800);
  double m2min = -4, m2max = 12, plmin = 0, plmax = 2.4;
  double xlow = m2min,xhigh = m2max, ylow = plmin,yhigh = plmax;
  Int_t nbinx = 80,nbiny = 80, Sam = sam.Atoi();
  if (Sam==0 || Sam==2 || Sam==10 || Sam==12 || Sam == 20 || Sam == 23 || Sam == 26 || Sam == 29) {
    xlow = -2; xhigh = 4;
    if (Sam > 12) {nbinx = 40; nbiny = 40;}
  } else if (Sam==1 || Sam==11) { xlow = -2; xhigh = 6;}
  if (Sam==6 || Sam==7 || Sam==16 || Sam==17) {nbinx = 40; nbiny = 40;}
  if (Sam==8 || Sam==18) {xhigh = 4; nbinx = 40; nbiny = 40;}
  if (Sam==9 || Sam==19) {nbinx = 40; nbiny = 40;}
  if (Sam==21 || Sam==22 || Sam==24 || Sam==25 || Sam==27 || Sam==28 || Sam==30 || Sam==31) {
    xhigh = 8; nbinx = 40; nbiny = 20;}
  if (Sam > 31) {nbinx = 40; nbiny = 20;}
  if(Sam==0){xlow=-1; xhigh=1;}
  double entries = c.GetEntries();
  Double_t hIntegral=h2->Integral();

  TString M2titles[] = {"0 < p*_{l} < 1 GeV","1 < p*_{l} < 1.4 GeV","1.4 < p*_{l} < 1.8 GeV",
		      "1.8 < p*_{l} < 2.4 GeV","0 < p*_{l} < 2.4 GeV"};
  TString Pltitles[] = {"-4 < m^{2}_{miss} < 1 GeV^{2}","1 < m^{2}_{miss} < 12 GeV^{2}",
			"-4 < m^{2}_{miss} < 12 GeV^{2}"};
  TCut M2cuts[] = {"candPstarLep<1","candPstarLep>1&&candPstarLep<1.4",
		      "candPstarLep>1.4&&candPstarLep<1.8","candPstarLep>1.8&&candPstarLep<2.4", ""};
  TCut Plcuts[] = {"candM2<1","candM2>=1",""};
  double PlLimits[] = {0, 1, 1.4, 1.8, 2.4};
  double M2Limits[] = {0., 5., 16.};
  int binlim[5]; int plbinlim[3];
  for(int i=0;i<5;i++) {
    PlLimits[i] = PlLimits[i]/2.4*(double)nPlbin;
    binlim[i] = (int)PlLimits[i];
    if(i<3){
      M2Limits[i] = M2Limits[i]/16.*(double)nM2bin;
      plbinlim[i] = (int)M2Limits[i];
    }
  }

  TString psname = "AWG82/results/keys/eps/Stitch/epsKeys"; psname += Base; psname += ".ps";
  mm.Print(psname+"[");
  TH1F *hm2[5], *m2[5], *hpl[3], *pl[3];
  TString M2names[5], Plnames[3];
  for(int i=0;i<5;i++){
    M2names[i] = "hm2_"; M2names[i] += i;
    hm2[i] = new TH1F(M2names[i],M2titles[i],nM2bin,m2min,m2max); 
    if(i<3) {
      Plnames[i] = "hpl_"; Plnames[i] += i;
      hpl[i] = new TH1F(Plnames[i],Pltitles[i],nPlbin,plmin,plmax); 
    }
  }
  
  hIntegral = h2->Integral();
  for(int i=0;i<5;i++){
    TString hdname = "dm2"; hdname += i;
    TString vari = "candM2>>"; vari+=hdname; vari+="("; vari+= nbinx; vari+=",";vari+= xlow; 
    vari+=",";vari+= xhigh; vari+=")";
    //M2cuts[i] += "weight<100";M2cuts[i] *= "wFF";
    c.Draw(vari,M2cuts[i]);
    m2[i] = (TH1F*)gDirectory->Get(hdname);
    m2[i]->SetXTitle("m^{2}_{miss} [GeV^{2}]");
    formatHisto(m2[i]);
    gStyle->SetOptStat(0);
    if(i<4){
      for(int j=1; j<nM2bin+1; j++){
	double binVal = 0;
	for(int binp = binlim[i]+1; binp < binlim[i+1]+1; binp++){
	  binVal+=h2->GetBinContent(j,binp)*entries*nM2bin*(xhigh-xlow)/nbinx/(m2max-m2min)/hIntegral;
	}
	hm2[i]->SetBinContent(j,binVal);
      }
    } 
    hm2[i]->SetLineColor(4);
    hm2[i]->SetLineWidth(1);
    if(i<4) hm2[4]->Add(hm2[i]);
  }
  for(int i=0;i<3;i++){
    TString hdname = "pl"; hdname += i;
    TString vari = "candPstarLep>>"; vari+=hdname; vari+="("; vari+= nbiny; vari+=",";vari+= ylow; 
    vari+=",";vari+= yhigh; vari+=")";
    cout<<vari<<"  "<<endl;
    //Plcuts[i] += "weight<100";Plcuts[i] *= "wFF";
    c.Draw(vari,Plcuts[i]);
    pl[i] = (TH1F*)gDirectory->Get(hdname);
    pl[i]->SetXTitle("p*_{l} [GeV]");
    formatHisto(pl[i]);
    gStyle->SetOptStat(0);
    if(i<2){
      for(int j=1; j<nPlbin+1; j++){
	double binVal = 0;
	for(int binp = plbinlim[i]+1; binp < plbinlim[i+1]+1; binp++){
	  binVal += h2->GetBinContent(binp,j)*entries*nPlbin/nbiny/hIntegral;	
	}
	hpl[i]->SetBinContent(j,binVal);
      }
    }
    hpl[i]->SetLineColor(4);
    hpl[i]->SetLineWidth(1);
    if(i<2) hpl[2]->Add(hpl[i]);
  }
  cout<<"End for"<<endl;
  m2[4]->Draw("e0"); m2[4]->Draw("e1 same"); hm2[4]->Draw("c same"); mm.Print(psname);
  pl[2]->Draw("e0"); pl[2]->Draw("e1 same"); hpl[2]->Draw("c same"); mm.Print(psname);
  for(int i=0;i<4;i++){
    m2[i]->Draw("e0"); m2[i]->Draw("e1 same"); hm2[i]->Draw("c same"); mm.Print(psname);
  }
  for(int i=0;i<2;i++){
    pl[i]->Draw("e0"); pl[i]->Draw("e1 same"); hpl[i]->Draw("c same"); mm.Print(psname);
  }
  mm.Print(psname+"]");

  TLatex *label = new TLatex(); label->SetNDC(kTRUE); label->SetTextSize(0.055);

  TCanvas all6("all6","KEYS fits to mmiss-pstarl",1700,1800);
  all6.cd();
  all6.Divide(2,3,0.001,0.001);
  all6.cd(1);gPad->SetTopMargin(0.004);gPad->SetRightMargin(0.003);gPad->SetBottomMargin(0.11);
  gPad->SetFillColor(10);gPad->SetFrameFillColor(10);
  m2[4]->Draw("e0");  m2[4]->Draw("e1 same"); hm2[4]->Draw("c same");
  all6.cd(2);gPad->SetTopMargin(0.004);gPad->SetRightMargin(0.003);gPad->SetBottomMargin(0.11);
  gPad->SetFillColor(10);gPad->SetFrameFillColor(10);
  pl[2]->Draw("e0");  pl[2]->Draw("e1 same"); hpl[2]->Draw("c same");
  for(int i=0;i<4;i++){
    all6.cd(i+3);gPad->SetTopMargin(0.003);gPad->SetRightMargin(0.003);gPad->SetBottomMargin(0.11);
    gPad->SetFillColor(10);gPad->SetFrameFillColor(10);
    m2[i]->Draw("e0"); label->DrawLatex(0.69,0.92,M2titles[i]);
    m2[i]->Draw("e1 same"); hm2[i]->Draw("c same"); 
  }
  TString epsname = "AWG82/results/keys/eps/Stitch/EpsKeys";
  epsname += Base; epsname += ".eps";
  all6.SaveAs(epsname);

  h2->Delete();
  return; 

}
コード例 #11
0
ファイル: glxlut_avr.C プロジェクト: pomm/gluexdirc
void glxlut_avr(TString baseFile = "../data/lut100000.root"){
  gROOT->ProcessLine(".L ../src/GlxLutNode.cxx+");
  gInterpreter->GenerateDictionary("vector<TVector3>","TVector3.h"); 
  
  TString inFile =baseFile;
  TString outFile = baseFile.Remove(baseFile.Last('.'))+"_avr.root";

  TFile* f = new TFile(inFile);
  TTree *t=(TTree *) f->Get("glxlut") ;
  TClonesArray* fLut[48];
  for(Int_t l=0; l<48; l++){
    fLut[l] = new TClonesArray("GlxLutNode");
    t->SetBranchAddress(Form("LUT_%d",l),&fLut[l]); 
  }

 
  TFile *fFileNew = TFile::Open(outFile, "RECREATE");
  TClonesArray *fLutNew[48];

  TTree *fTreeNew = new TTree("glxlut","Look-up table for DIRC. Averaged");

  Int_t Nnodes = 20000;
  for(Int_t l=0; l<48; l++){
    fLutNew[l] = new TClonesArray("GlxLutNode");
    fTreeNew->Branch(Form("LUT_%d",l),&fLutNew[l],256000,2);
    TClonesArray &fLutaNew = *fLutNew[l];
    for (Long64_t n=0; n<Nnodes; n++) {
      new((fLutaNew)[n]) GlxLutNode(-1);
    }
  }

  // TCanvas* c = new TCanvas("c","c",0,0,800,1200); c->Divide(1,2);
  // TH1F * histNode = new TH1F("LutNode","Node vs Multiplicity",30000,0,150000);
  // TH1F * hTime = new TH1F("hTime","Time",5000,0,10);
  // TH1F * hDir = new TH1F("hDir","X component",1000,-1,1);


  std::vector<TVector3> vArray[100];
  std::vector<Double_t> tArray[100];
  std::vector<Double_t> pArray;
  
  TVector3 dir, dir2, sum;
  Double_t angle, minangle,pathid,time,sumt;
  GlxLutNode *node;

  for(Int_t l=0; l<48; l++){
    t->GetEntry(l);
    for (Int_t inode=0; inode<fLut[l]->GetEntriesFast(); inode++){
      if(inode%1000==0) cout<<"Node # "<<inode << "  L "<<l<<endl;
      node= (GlxLutNode*) fLut[l]->At(inode);
      //histNode->Fill(node->GetNodeId(),node->Entries());
      Int_t size = node->Entries();    
      if(size<1) continue;
      for(int i=0; i<size; i++){
	dir = node->GetEntry(i);
	time = node->GetTime(i);
	pathid = node->GetPathId(i);
      
	// hDir->Fill(dir.X());
	// hTime->Fill(time);

	bool newid = true;
	for(int j=0; j<pArray.size(); j++){
	  if(pathid == pArray[j]){
	    vArray[j].push_back(dir);
	    tArray[j].push_back(time);
	    newid= false;
	  }
	}
	if(newid) {
	  vArray[pArray.size()].push_back(dir);
	  tArray[pArray.size()].push_back(time);
	  pArray.push_back(pathid);
	}
      }
  
      for(int j=0; j<pArray.size(); j++){
	sum = TVector3(0,0,0);
	sumt=0;
	for(int v=0; v<vArray[j].size(); v++) {
	  sum += vArray[j][v]; 
	  sumt += tArray[j][v]; 

	  // hDir->Fill(vArray[j][v].X());
	  // hTime->Fill(tArray[j][v]);
	}
      
	// c->cd(1);
	// hTime->Draw();
	// c->cd(2);
	// hDir->Draw();
	// c->Update();  
	// c->WaitPrimitive();
	// hDir->Reset();
	// hTime->Reset();

	if(vArray[j].size()<1) continue;
	Double_t weight = 1/(Double_t)vArray[j].size(); 
	sum *= weight;
	sumt *= weight;
      
	((GlxLutNode*)(fLutNew[l]->At(inode)))->AddEntry(node->GetDetectorId(), sum,j,node->GetNRefl(0),sumt, node->GetDigiPos(),node->GetDigiPos(),vArray[j].size()/(Double_t)size); 
      }
      for(int i=0; i<100; i++) {vArray[i].clear();  tArray[i].clear();}
      pArray.clear();
    }
  }

  fTreeNew->Fill();
  fTreeNew->Write();
  //fFileNew->Write();

}
コード例 #12
0
void bfcread_hist_extract(
  const Char_t *MainFile=
    "/afs/rhic.bnl.gov/star/data/samples/gstar.hist.root",
  const Char_t *MakerHistDir="EventQA",
  const Char_t *TopDirTree="bfcTree",
  Char_t *OutFile=0,
  const Char_t *PrintList="")
{

  cout << "bfcread_hist_extract.C, input hist file = " 
       << MainFile << endl;
  cout << "bfcread_hist_extract.C, directory name for hist = " 
       << MakerHistDir << endl;
  cout << "bfcread_hist_extract.C, top level directory in hist file = " 
       << TopDirTree << endl;

//
    gSystem->Load("St_base");
    gSystem->Load("StChain");
    gSystem->Load("StIOMaker");
    gSystem->Load("StarClassLibrary");
    gSystem->Load("StUtilities");
    gSystem->Load("StAnalysisUtilities");
    gSystem->Load("libglobal_Tables");

// setup chain with IOMaker - can read in .dst.root, .dst.xdf files
  StIOMaker *IOMk = new StIOMaker("IO","r",MainFile,TopDirTree);
  IOMk->SetDebug();
  IOMk->SetIOMode("r");
  IOMk->SetBranch("*",0,"0");                 //deactivate all branches
  IOMk->SetBranch("histBranch",0,"r"); //activate dst Branch


// constructor for other maker (not used in chain)
   StHistUtil   *HU  = new StHistUtil;

// now must set pointer to StMaker so HistUtil can find histograms
//  with StHistUtil methods
// -- input any maker pointer but must cast as type StMaker
   HU->SetPntrToMaker((StMaker *)IOMk);

// ONLY use StIOMaker in chain 
// --- now execute chain member functions - 1 event (histograms) only
  IOMk->Init();
  IOMk->Clear();
  IOMk->Make();

// method to print out list of histograms
// - can do this anytime after they're booked
// - default is to print out QA hist branch
   Int_t NoHist=0;
   //NoHist = HU->ListHists(MakerHistDir);
   TList* dList = HU->FindHists(MakerHistDir);
   if (PrintList) HU->SetDefaultPrintList(MakerHistDir,PrintList);
   NoHist = HU->CopyHists(dList);
   TH1** nh = HU->getNewHist();

   TString name = MainFile;
   if (!OutFile) {
     name.Remove(0,name.Last('/')+1);
     TString name2 = MakerHistDir;
     name2.Remove(0,name2.Last('/')+1);
     name.Insert(name.First('.'),"_");
     name.Insert(name.First('.'),name2);
     OutFile = name.Data();
   }
   cout <<  "Output hist file: " << OutFile << endl;
   TFile* ofile = new TFile(OutFile,"RECREATE");
   for (int i=0; i<NoHist; i++) {
     printf("Extracting: %d. %s : %s\n",
       i+1,nh[i]->GetName(),nh[i]->GetTitle());
     nh[i]->Write();
   }
   ofile->Close();
      
}
コード例 #13
0
void minuitFit()
{

  TH1F::SetDefaultSumw2(); 
  TH1D::SetDefaultSumw2(); 

  cout << "Must Use Same Binning as previous Analysis!" << endl;

  gStyle->SetOptFit(1111);
  gStyle->SetOptStat(0);
  haveName = kFALSE;
  char fname[100];
  TFile* file;
  Bool_t makePDF = checkMakePDF();
  Bool_t makeROOT = checkMakeRoot();
  if(makeROOT){
    sprintf(fname,"/Users/zach/Research/pythia/200GeVTemplate/FFOutput/%s_FIT.root",FileNameR);
    file = new TFile(fname,"RECREATE");
    if (file->IsOpen()==kFALSE)
    {
      std::cout << "!!! Outfile Not Opened !!!" << std::endl;
      makeROOT = kFALSE;
    }
  }


  char name[1000];
  sprintf(name,"/Users/zach/Research/pythia/200GeVTemplate/currentTemplate.root");
  TFile *fT = new TFile(name,"READ");
  sprintf(name,"/Users/zach/Research/rootFiles/run12NPEhPhi/currentData.root");
  TFile *fD = new TFile(name,"READ");
  if (fT->IsOpen()==kFALSE || fD->IsOpen()==kFALSE)
  { std::cout << "!!!!!! Either B,C, or Data File not found !!!!!!" << std::endl
    << "Looking for currentB.root, currentC.root, and currentData.root" << std::endl;
    exit(1); }

  // Set constants and projection bins (from header file anaConst, analysis constants)

  Float_t lowpt[numPtBins],highpt[numPtBins];
  for(Int_t c=0; c< numPtBins; c++){
    lowpt[c] = anaConst::lpt[c];
    highpt[c] = anaConst::hpt[c];
  }
  Float_t hptCut=anaConst::hptCut;

  // Make Canvases
  TCanvas* deltaPhi  = new TCanvas("deltaPhi","Pythia Delta Phi",150,0,1150,1000);
  TCanvas* deltaPhi2  = new TCanvas("deltaPhi2","Pythia Delta Phi",150,0,1150,1000);
  TCanvas* fitResult0 = new TCanvas("fitResult0","RB Extraction HT0",150,0,1150,1000);
  TCanvas* fitResult2 = new TCanvas("fitResult2","RB Extraction HT2",150,0,1150,1000);
  TCanvas* fitResultC = new TCanvas("fitResultC","RB Extraction Combined Trigs",150,0,1150,1000);
  TCanvas* fitResultP = new TCanvas("fitResultP","RB Previous Analysis",150,0,1150,1000);
  TCanvas* scaleCheck = new TCanvas("scaleCheck","Check scale diff",150,0,1150,1000);
  TCanvas* prettyPlot = new TCanvas("prettyPlot","PrettyPlot",150,0,1150,1000);
  deltaPhi  ->Divide(3,3);
  deltaPhi2 ->Divide(3,3);
  fitResult0->Divide(3,4);
  fitResult2->Divide(3,4);
  fitResultC->Divide(3,4);
  fitResultP->Divide(2,2);
  scaleCheck->Divide(1,2);

  // Get and Draw histos
  TPaveText* lbl[numPtBins];
  TPaveText* stat[4][numPtBins];
  char statLabel[100];
  char textLabel[100];
  Int_t plotbin;
  Double_t norm0,norm2,normB,normC;

  // Get ptbin independent hists
  histoNorms = (TH2F*)fD->Get("histoNorms");
   // Get Previous Analysis
  TFile *file3 = new TFile("/Users/zach/Research/previousNPEhFigures/Chi2_25_35.root");
  Hdphi[0]  = (TH1D*)file3->Get("fit_25_35");
  HpphiD[0] = (TH1D*)file3->Get("De_25_35");
  HpphiB[0] = (TH1D*)file3->Get("Be_25_35");
  TFile *file4 = new TFile("/Users/zach/Research/previousNPEhFigures/Chi2_55_65.root");
  Hdphi[1]  = (TH1D*)file4->Get("fit_55_65");
  HpphiD[1] = (TH1D*)file4->Get("De_55_65");
  HpphiB[1] = (TH1D*)file4->Get("Be_55_65");

  for(Int_t ptbin=0; ptbin<numPtBins; ptbin++)
  {
    bPtNorms[ptbin]   = (TH1F*)fT->Get(Form("beEventTally_%i",ptbin));
    cPtNorms[ptbin]   = (TH1F*)fT->Get(Form("ceEventTally_%i",ptbin));

    norm0 = histoNorms->GetBinContent(histoNorms->GetBin(1,ptbin+1));
    norm2 = histoNorms->GetBinContent(histoNorms->GetBin(3,ptbin+1));
    normB = bPtNorms[ptbin]->GetBinContent(1);
    normC = cPtNorms[ptbin]->GetBinContent(1);

    cout << ptbin << "; 0: " << norm0 << " 2: " << norm2 << endl;

    if( norm0 == 0)
    {
      cout << ptbin << " For this bin, some norm0 = 0" << endl;
      continue;
    }
    if( norm2 == 0 )
    {
      cout << ptbin << " For this bin, some norm2 = 0" << endl;
      continue;
    }
    if( normB == 0 )
    {
      cout << ptbin << " For this bin, some normB = 0" << endl;
      continue;
    }
    if( normC == 0)
    {
      cout << ptbin << " For this bin, some normC = 0" << endl;
      continue;
    }
    plotbin = ptbin;
    // Init necessary plotting tools
    lbl[ptbin] = new TPaveText(.15,.15,.35,.23,Form("NB NDC%i",ptbin));
    sprintf(textLabel,"%.1f < P_{T,e} < %.1f",lowpt[ptbin],highpt[ptbin]);
    lbl[ptbin]->AddText(textLabel);
    lbl[ptbin]->SetFillColor(kWhite);

    projB[ptbin] = (TH1D*)fT->Get(Form("hdPhiRawbe_%i",ptbin));
    projC[ptbin] = (TH1D*)fT->Get(Form("hdPhiRawce_%i",ptbin));
    projData0[ptbin]= (TH1D*)fD->Get(Form("NPEhDelPhi_0_%i",ptbin));
    projData2[ptbin]= (TH1D*)fD->Get(Form("NPEhDelPhi_2_%i",ptbin));
 
    pileupCorrect[ptbin][0] = (TH1D*)fD->Get(Form("pileupCorrection_%i_0",ptbin));
    pileupCorrect[ptbin][1] = (TH1D*)fD->Get(Form("pileupCorrection_%i_2",ptbin));
    pileupCorrect[ptbin][0]->Sumw2();
    pileupCorrect[ptbin][1]->Sumw2();

    // Do any rebinning
    Int_t RB = 1;
    projB[ptbin]->Rebin(RB);
    projC[ptbin]->Rebin(RB);
    projData0[ptbin]->Rebin(RB);
    projData2[ptbin]->Rebin(RB);

    // Clone to make plots without effecting fits
    plotD0[ptbin] = (TH1D*) projData0[ptbin]->Clone();
    plotD2[ptbin] = (TH1D*) projData2[ptbin]->Clone();
    plotB[ptbin]  = (TH1D*) projB[ptbin]->Clone();
    plotC[ptbin]  = (TH1D*) projC[ptbin]->Clone();

    // Set features that are the same in plots
    projData0[ptbin]->SetLineColor(kBlue);
    projData2[ptbin]->SetLineColor(kGreen+3);
    projB[ptbin]->SetLineColor(kRed);
    projC[ptbin]->SetLineColor(kBlack);
    projC[ptbin]->GetXaxis()->SetRangeUser(-3.5,3.5);
    plotD0[ptbin]->SetLineColor(kBlue);
    plotD2[ptbin]->SetLineColor(kGreen+3);
    plotD0[ptbin]->SetMarkerStyle(20);
    plotD0[ptbin]->SetMarkerColor(kBlue);
    plotD0[ptbin]->SetMarkerSize(0.4);
    plotB[ptbin]->SetLineColor(kRed);
    plotC[ptbin]->SetLineColor(kBlack);
    plotC[ptbin]->GetXaxis()->SetRangeUser(-3.5,3.5);

    combData[ptbin] = (TH1D*) projData0[ptbin]->Clone();
    combData[ptbin] -> Add(projData2[ptbin]);
    combData[ptbin]->SetLineColor(kBlue);
    combData[ptbin]->SetMarkerStyle(20);
    combData[ptbin]->SetMarkerColor(kBlue);
    combData[ptbin]->SetMarkerSize(0.4);
    combData[ptbin]->SetTitle("");

    // Normalize
    projB[ptbin]     -> Scale(1./normB);
    projC[ptbin]     -> Scale(1./normC);
    projData0[ptbin] -> Scale(1./norm0);
    projData2[ptbin] -> Scale(1./norm2);
    plotD0[ptbin]    -> Scale(1./norm0);
    plotD2[ptbin]    -> Scale(1./norm2);
    plotB[ptbin]     -> Scale(1./normB);
    plotC[ptbin]     -> Scale(1./normC);
    combData[ptbin]  -> Scale(1./(norm0+norm2));

    // Subtract Pileup correction (data only)
    projData0[ptbin]->Sumw2();projData2[ptbin]->Sumw2();
    //projData0[ptbin]->Add(pileupCorrect[ptbin][0],-1);
    //projData2[ptbin]->Add(pileupCorrect[ptbin][1],-1);

    // Draw Templates on own plots
    if(ptbin+1 <= 9) deltaPhi->cd(plotbin+1);
    if(ptbin+1 > 9) deltaPhi2->cd(ptbin-8);
    plotC[ptbin]->GetYaxis()->SetRangeUser(-.1,0.8);
    plotC[ptbin]  -> Draw("hist");
    plotB[ptbin]  -> Draw("same hist");
    plotD0[ptbin] -> Draw("same");
    plotD2[ptbin] -> Draw("same");
    lbl[ptbin]    -> Draw("same");

    TLegend* leg = new TLegend(0.65,0.6,0.85,0.85);
    leg->AddEntry(projB[ptbin],"b#bar{b}->NPE","lpe");
    leg->AddEntry(projC[ptbin],"c#bar{c}->NPE","lpe");
    leg->AddEntry(projData0[ptbin],"HT0","lpe");
    leg->AddEntry(projData2[ptbin],"HT2","lpe");
    leg->Draw();

    deltaPhi->cd(1);
    Hdphi[0]->Draw("same");
    deltaPhi->cd(4);
    Hdphi[1]->Draw("same");

      if(ptbin == 1)
      {
        prettyPlot->cd();
        plotC[ptbin]->GetYaxis()->SetRangeUser(0,0.35);
        plotC[ptbin]->SetMarkerStyle(20);
        plotC[ptbin]->SetMarkerSize(0.6);
        plotB[ptbin]->SetMarkerStyle(21);
        plotB[ptbin]->SetMarkerSize(0.6);
        plotB[ptbin]->SetMarkerColor(kRed);
        plotD0[ptbin]->SetMarkerStyle(22);
        plotD0[ptbin]->SetMarkerSize(0.9);
        plotC[ptbin]->GetXaxis()->SetTitle("#Delta#phi_{NPE-h} (rad)");
        plotC[ptbin]->GetYaxis()->SetTitle("#frac{1}{N_{NPE}} #frac{dN}{d(#Delta#phi)}");
        plotC[ptbin]->DrawClone("P");
        plotB[ptbin]->DrawClone("same P");
        plotD0[ptbin]->DrawClone("same P");
        TLegend* legPret = new TLegend(0.65,0.6,0.85,0.85);
        legPret->AddEntry(plotB[ptbin],"B #rightarrow NPE-h, Monte Carlo","LPE");
        legPret->AddEntry(plotC[ptbin],"D #rightarrow NPE-h, Monte Carlo","LPE");
        legPret->AddEntry(plotD0[ptbin],"NPE-h 2012 STAR Data","LPE");
        lbl[ptbin]->Draw("same");
        legPret->Draw("same");
      }

    /*// Draw Scale Check
      scaleCheck->cd(1);
      TH1F* HT0 = (TH1F*) plotD0[0]->Clone();
      HT0->Divide(HT0,Hdphi[0],1,1);
      HT0->Draw();
      scaleCheck->cd(2);
      TH1F* HT2 = (TH1F*) plotD2[3]->Clone();
      HT2->Divide(HT2,Hdphi[1],1,1);
      HT0->GetXaxis()->SetRangeUser(-3.5,3.5);
      HT2->GetXaxis()->SetRangeUser(-3.5,3.5);
      HT2->Draw();
      lbl[ptbin]->Draw("same");
      TLegend* legSC = new TLegend(0.65,0.6,0.85,0.85);
      legSC->AddEntry(HT0,"HT0/prevdata","lpe");
      legSC->AddEntry(HT2,"HT2/prevdata","lpe");
      legSC->Draw();*/

    /////////////////////
    // Do the actual fits
    /////////////////////

    currentPtBin = ptbin;
    cout << "!!!!!!! HT0 ptbin: " << highpt[ptbin] << "-" << lowpt[ptbin] <<" !!!!!!!"<< endl;
    TMinuit* gMinuit = new TMinuit(1);
    gMinuit->SetFCN(chi2_0);
    currentPtBin = ptbin;
    doFit(gMinuit,p01[ptbin],p00[ptbin],e01[ptbin],e00[ptbin]);

    // assign to plotting variables
    if(highpt[ptbin] < 6)
    {
      pT[ptbin] = (lowpt[ptbin]+highpt[ptbin])/2.;
      dx[plotCount0] = 0.;
      ptOFF1[plotCount0] = pT[ptbin];
      Rb0[plotCount0] = p01[ptbin];///(p01[ptbin]+p00[ptbin]);
      eb0[plotCount0] = e01[ptbin];
      plotCount0++;
    }

    // Plot results
    fitResult0->cd(ptbin+1);
    TH1D* dClone = (TH1D*) projData0[ptbin]->Clone();
    TH1D* cClone = (TH1D*) projC[ptbin]->Clone();
    TH1D* bClone = (TH1D*) projB[ptbin]->Clone();
    stat[0][ptbin] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%i",ptbin));
    sprintf(statLabel,"Chi2/NDF: %.2f/%.0f",curChi2,curNDF);
    stat[0][ptbin]->InsertText(statLabel);
    stat[0][ptbin]->SetFillColor(kWhite);
    cClone->Scale((1.-p01[ptbin])*p00[ptbin]); bClone->Scale(p00[ptbin]*p01[ptbin]); // scale by contribution param
    cClone->Add(bClone);
    //cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
    dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
    dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
    dClone->Draw();
    cClone->Draw("same");
    stat[0][ptbin]->Draw("same");
    lbl[ptbin]->Draw("same");


    cout << "!!!!!!! HT2 ptbin: " <<  highpt[ptbin] << "-" << lowpt[ptbin] <<" !!!!!!!"<< endl;
    gMinuit->SetFCN(chi2_2);
    doFit(gMinuit,p21[ptbin],p20[ptbin],e21[ptbin],e20[ptbin]);

    // assign to plotting variables
    if(highpt[ptbin] > 3.6)
    {
      pT[ptbin] = (lowpt[ptbin]+highpt[ptbin])/2.;
      ptOFF2[plotCount2] = pT[ptbin];
      Rb2[plotCount2] = p21[ptbin];///(p21[ptbin]+p20[ptbin]);
      eb2[plotCount2] = e21[ptbin];
      plotCount2++;
    }

    // Plot results
    fitResult2->cd(ptbin+1);
    dClone = (TH1D*) projData2[ptbin]->Clone();
    cClone = (TH1D*) projC[ptbin]->Clone();
    bClone = (TH1D*) projB[ptbin]->Clone();
    stat[2][ptbin] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%i",ptbin));
    sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
    stat[2][ptbin]->InsertText(statLabel);
    stat[2][ptbin]->SetFillColor(kWhite);
    cClone->Scale((1.-p21[ptbin])*p20[ptbin]); bClone->Scale(p20[ptbin]*p21[ptbin]); // scale by contribution param
    cClone->Add(bClone);
    // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
    dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
    dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
    dClone->Draw();
    cClone->Draw("same");
    stat[2][ptbin]->Draw("same");
    lbl[ptbin]->Draw("same");

    cout << "!!!!!!! HTC ptbin: " <<  highpt[ptbin] << "-" << lowpt[ptbin] <<" !!!!!!!"<< endl;
    gMinuit->SetFCN(chi2_C);
    doFit(gMinuit,pC1[ptbin],pC0[ptbin],eC1[ptbin],eC0[ptbin]);
    // assign to plotting variables
    pT[ptbin] = (lowpt[ptbin]+highpt[ptbin])/2.;
    RbC[plotCount] = pC1[ptbin];///(p21[ptbin]+p20[ptbin]);
    ebC[plotCount] = eC1[ptbin];
    plotCount++;
  }

  cout << "!!!!!!! Previous Data: 0"<<" !!!!!!!"<< endl;

  //////////
  // 2.5-3.5 GeV Bin
  //////////

  gMinuit->SetFCN(chi2_P0);
  doFit(gMinuit,RbP[0],SF[0],EbP[0],eSF[0]);

  // assign plotting variables
  pTP[0] = 3.;

  // Plot results
  fitResultP->cd(1);
  /*TH1D* dClone = (TH1D*) Hdphi[0]->Clone();
    TH1D* cClone = (TH1D*) projC[0]->Clone();
    TH1D* bClone = (TH1D*) projB[0]->Clone();*/
  TH1D* dClone = (TH1D*) projData0[0]->Clone();
  TH1D* cClone = (TH1D*) HpphiD[0]->Clone();
  TH1D* bClone = (TH1D*) HpphiB[0]->Clone();
  stat[3][0] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%iP",0));
  sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
  stat[3][0]->InsertText(statLabel);
  stat[3][0]->SetFillColor(kWhite);
  cClone->Scale((1.-RbP[0])*SF[0]); bClone->Scale(RbP[0]*SF[0]); // scale by contribution param
  cClone->Add(bClone);
  // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
  dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
  dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
  cClone->SetLineColor(kRed);
  dClone->Draw();
  cClone->Draw("same");
  stat[3][0]->Draw("same");

  ////////
  // 5.5-6.5 GeV Bin
  ////////

  gMinuit->SetFCN(chi2_P1);
  doFit(gMinuit,RbP[1],SF[1],EbP[1],eSF[1]);

  // assign plotting variables
  pTP[1] = 6.;

  // Plot results
  fitResultP->cd(2);
  /*dClone = (TH1D*) Hdphi[1]->Clone();
    cClone = (TH1D*) projC[3]->Clone();
    bClone = (TH1D*) projB[3]->Clone();*/
  dClone = (TH1D*) projData2[3]->Clone();
  cClone = (TH1D*) HpphiD[1]->Clone();
  bClone = (TH1D*) HpphiB[1]->Clone();
  stat[3][1] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%iP",0));
  sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
  stat[3][1]->InsertText(statLabel);
  stat[3][1]->SetFillColor(kWhite);
  cClone->Scale((1.-RbP[1])*SF[1]); bClone->Scale(RbP[1]*SF[1]); // scale by contribution param
  cClone->Add(bClone);
  // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
  dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
  dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
  cClone->SetLineColor(kRed);
  dClone->Draw();
  cClone->Draw("same");
  stat[3][1]->Draw("same");

  ////////
  // Old Data, Old Template
  ///////
  gMinuit->SetFCN(chi2_PP);
  doFit(gMinuit,RbPP[0],SFPP[0],EbPP[0],eSFPP[0]);

  // assign plotting variables
  pTPP[0] = 3.;

  // Plot results
  fitResultP->cd(3);
  dClone = (TH1D*) Hdphi[0]->Clone();
  cClone = (TH1D*) HpphiD[0]->Clone();
  bClone = (TH1D*) HpphiB[0]->Clone();
  stat[3][2] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%iP",0));
  sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
  stat[3][2]->InsertText(statLabel);
  stat[3][2]->SetFillColor(kWhite);
  cClone->Scale((1.-RbPP[0])*SFPP[0]); bClone->Scale(RbPP[0]*SFPP[0]); // scale by contribution param
  cClone->Add(bClone);
  // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
  dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
  dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
  cClone->SetLineColor(kRed);
  dClone->Draw();
  cClone->Draw("same");
  stat[3][2]->Draw("same");

  // Bin at 6 GeV
  gMinuit->SetFCN(chi2_PP1);
  doFit(gMinuit,RbPP[1],SFPP[1],EbPP[1],eSFPP[1]);

  // assign plotting variables
  pTPP[1] = 6.;

  // Plot results
  fitResultP->cd(4);
  dClone = (TH1D*) Hdphi[1]->Clone();
  cClone = (TH1D*) HpphiD[1]->Clone();
  bClone = (TH1D*) HpphiB[1]->Clone();
  stat[3][3] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%iP",0));
  sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
  stat[3][3]->InsertText(statLabel);
  stat[3][3]->SetFillColor(kWhite);
  cClone->Scale((1.-RbPP[1])*SFPP[1]); bClone->Scale(RbPP[1]*SFPP[1]); // scale by contribution param
  cClone->Add(bClone);
  // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
  dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
  dClone->GetYaxis()->SetRangeUser(-0.1,0.6);
  cClone->SetLineColor(kRed);
  dClone->Draw();
  cClone->Draw("same");
  stat[3][3]->Draw("same");


  // Get FONLL Calc
  Int_t l=0;
  char line[1000];
  Float_t xF[100],yF[100],minF[100],maxF[100];
  ifstream fp("/Users/zach/Research/pythia/200GeVTemplate/FONLL.txt",ios::in);
  while (!fp.eof()){
    fp.getline(line,1000);
    sscanf(line,"%f %f %f %f",&xF[l],&yF[l],&minF[l],&maxF[l]);
    //  printf("L: %f %f\n",xF[l],yF[l]);
    l++;
  }
  fp.close();

  // Get Previous Analysis 
  Int_t p=0;
  Float_t xP[100],yP[100],dyP[100];
  ifstream fp1("/Users/zach/Research/pythia/200GeVTemplate/run5_6.txt",ios::in);
  while (!fp1.eof()){
    fp1.getline(line,1000);
    sscanf(line,"%f %f %f",&xP[p],&yP[p],&dyP[p]);
    // printf("L: %f %f\n",xF[l],yF[l]);
    p++;
  }
  fp1.close();

  //cout << "at bottom contrib plot" << endl;
  TCanvas* c1 = new TCanvas("c1","Bottom Contribution",150,0,1150,1000);
  TGraphErrors *gr0     = new TGraphErrors(plotCount0-1,ptOFF1,Rb0,dx,eb0);
  TGraphErrors *gr2     = new TGraphErrors(plotCount2-1,ptOFF2,Rb2,dx,eb2);
  TGraphErrors *grC     = new TGraphErrors(plotCount-1,pT,RbC,dx,ebC);
  TGraphErrors *grF     = new TGraphErrors(l-1,xF,yF);
  TGraphErrors *grFmax  = new TGraphErrors(l-1,xF,maxF);
  TGraphErrors *grFmin  = new TGraphErrors(l-1,xF,minF);
  TGraphErrors *grP     = new TGraphErrors(p-1,xP,yP,0,dyP);
  TGraphErrors *grPr    = new TGraphErrors(2,pTP,RbP,0,EbP);
  TGraphErrors *grPPr   = new TGraphErrors(2,pTPP,RbPP,0,EbPP);


  c1->cd(1);

  grP->SetTitle("");
  grP->GetXaxis()->SetTitle("NPE p_{T} (GeV/c)");
  grP->GetYaxis()->SetTitle("r_{B}");
  gr0->SetMarkerStyle(20);
  gr0->SetMarkerSize(1);
  gr0->SetLineColor(kBlue);
  gr0->SetMarkerColor(kBlue);
  gr2->SetMarkerStyle(22);
  gr2->SetMarkerSize(1);
  gr2->SetLineColor(kRed);
  gr2->SetMarkerColor(kRed);
  grC->SetMarkerStyle(21);
  grC->SetMarkerSize(1);
  grC->SetLineColor(kRed);
  grC->SetMarkerColor(kRed);
  grP->GetXaxis()->SetLimits(0,10);
  grP->GetYaxis()->SetRangeUser(0,1);
  grF->SetLineStyle(1);
  grFmax->SetLineStyle(2);
  grFmin->SetLineStyle(2);
  grP->SetMarkerStyle(33);
  grP->SetMarkerColor(kBlack);
  grPr->SetMarkerStyle(29);
  grPr->SetMarkerColor(9);
  grPr->SetLineColor(9);
  grPPr->SetMarkerStyle(29);
  grPPr->SetMarkerColor(49);
  grPPr->SetLineColor(49);


  grP->Draw("AP");
  //grC->Draw("same P");
  gr2->Draw("same P");
  grF->Draw("same");
  grFmax->Draw("same");
  grFmin->Draw("same");
  gr0->Draw("same P");
 // grPr->Draw("same P");
  //grPPr->Draw("same P");

  TLegend* leg2 = new TLegend(0.15,0.68,0.48,0.85);
  leg2->AddEntry(gr0,"STAR Run 12 - Low p_{T} Analysis","pe");
  leg2->AddEntry(gr2,"STAR Run 12 - High p_{T} Analysis","pe");
  //leg2->AddEntry(grC,"Combined Trigs","pe");
  leg2->AddEntry(grP,"STAR Run 6 Analysis (Stat. Uncertainty)","pe");
//  leg2->AddEntry(grPr,"Run 12 Data, Run 5/6 Templates)","pe");
  //leg2->AddEntry(grPPr,"Run 5/6 Refit (prev Template)","pe");
  leg2->AddEntry(grF,"FONLL Calculation","l");
  leg2->Draw("same");

  // Write to Root File if open
  if(makeROOT){
    file3->Close();
    file4->Close();
    file->cd();
    grP->Write("PreviousData");
    //grC->Write("same P");
    gr2->Write("HT2");
    grF->Write("FONLL");
    grFmax->Write("FONLLmax");
    grFmin->Write("FONLLmin");
    gr0->Write("HT0");
    // grPr->Write("PrevTempMyData");
    //grPPr->Write("PrevTempPreData");
  }

  // Make PDF with output canvases
  if(makePDF)
  {
    //Set front page
    TCanvas* fp = new TCanvas("fp","Front Page",100,0,1000,900);
    fp->cd();
    TBox *bLabel = new TBox(0.01, 0.88, 0.99, 0.99);
    bLabel->SetFillColor(38);
    bLabel->Draw();
    TLatex tl;
    tl.SetNDC();
    tl.SetTextColor(kWhite);
    tl.SetTextSize(0.033);
    char tlName[100];
    char tlName2[100];

    TString titlename = FileName;
    int found = titlename.Last('/');
    if(found >= 0){
      titlename.Replace(0, found+1, "");
    } 
    sprintf(tlName, "RUN 12 NPE-h   #Delta#phi Correlations");
    tl.SetTextSize(0.05);
    tl.SetTextColor(kWhite);
    tl.DrawLatex(0.05, 0.92,tlName);

    TBox *bFoot = new TBox(0.01, 0.01, 0.99, 0.12);
    bFoot->SetFillColor(38);
    bFoot->Draw();
    tl.SetTextColor(kWhite);
    tl.SetTextSize(0.05);
    tl.DrawLatex(0.05, 0.05, (new TDatime())->AsString());
    tl.SetTextColor(kBlack);
    tl.SetTextSize(0.03);
    tl.DrawLatex(0.1, 0.14, titlename);
    sprintf(tlName,"TEST");
    tl.DrawLatex(0.1, 0.8,tlName);

    // Place canvases in order
    TCanvas* temp = new TCanvas();
    sprintf(name, "FFOutput/%s.pdf[", FileName);
    temp->Print(name);
    sprintf(name, "FFOutput/%s.pdf", FileName);

    temp = deltaPhi; 
    temp->Print(name);
    temp = fitResult0;
    temp->Print(name);
    temp = fitResult2;
    temp->Print(name);
    // temp = fitResultC;
    // temp->Print(name);
    temp = c1;
    temp->Print(name);

    sprintf(name, "FFOutput/%s.pdf]", FileName);
    temp->Print(name);
  }
  if(makeROOT)
  {
    file->Write();
    file->Close();
  }
}
void makePlot(const TString& title, 
	      TGraphAsymmErrors* graph_Data_passed, TF1* fit_Data_passed, const TString& legendEntry_Data_passed,
	      TGraphAsymmErrors* graph_mcSum_passed, TF1* fit_mcSum_passed, const TString& legendEntry_mcSum_passed,
	      TGraphAsymmErrors* graph_Data_failed, TF1* fit_Data_failed, const TString& legendEntry_Data_failed,
	      TGraphAsymmErrors* graph_mcSum_failed, TF1* fit_mcSum_failed, const TString& legendEntry_mcSum_failed,
	      const TString& outputFileName)
{
  TCanvas* canvas = new TCanvas("canvas", "canvas", 800, 900);
  canvas->SetFillColor(10);
  canvas->SetBorderSize(2);
  canvas->SetLeftMargin(0.12);
  canvas->SetBottomMargin(0.12);

  //TPad* topPad = new TPad("topPad", "topPad", 0.00, 0.35, 1.00, 1.00);
  TPad* topPad = new TPad("topPad", "topPad", 0.00, 1.00 - 0.65*(0.93/0.84), 1.00, 1.00);
  topPad->SetFillColor(10);
  topPad->SetTopMargin(0.04);
  topPad->SetLeftMargin(0.15);
  //topPad->SetBottomMargin(0.03);
  topPad->SetBottomMargin(0.12);
  topPad->SetRightMargin(0.05);
  topPad->SetGridx();
  topPad->SetGridy();

  canvas->cd();
  topPad->Draw();
  topPad->cd();

  TH1* dummyHistogram_top = new TH1D("dummyHistogram_top", "dummyHistogram_top", 10, 0., 100.);
  dummyHistogram_top->SetTitle("");
  dummyHistogram_top->SetStats(false);
  dummyHistogram_top->SetMaximum(1.2);
  dummyHistogram_top->SetMinimum(0.);
  
  TAxis* xAxis_top = dummyHistogram_top->GetXaxis();
  xAxis_top->SetTitle("calo-E_{T}^{miss} / GeV");
  xAxis_top->SetTitleOffset(1.15);
  //xAxis_top->SetLabelColor(10);
  //xAxis_top->SetTitleColor(10);

  TAxis* yAxis_top = dummyHistogram_top->GetYaxis();
  yAxis_top->SetTitle("#varepsilon");
  yAxis_top->SetTitleOffset(1.2);

  dummyHistogram_top->Draw();
  //dummyHistogram_top->Draw("axis");

  //graph_Data_passed->SetLineColor(4);
  //graph_Data_passed->SetMarkerColor(4);
  //graph_Data_passed->SetMarkerStyle(20);
  //graph_Data_passed->Draw("p");

  //fit_Data_passed->SetLineColor(graph_Data_passed->GetLineColor());
  //fit_Data_passed->SetLineWidth(2);
  //fit_Data_passed->Draw("same");

  graph_mcSum_passed->SetLineColor(7);
  graph_mcSum_passed->SetMarkerColor(7);
  graph_mcSum_passed->SetMarkerStyle(24);
  graph_mcSum_passed->Draw("p");

  fit_mcSum_passed->SetLineColor(graph_mcSum_passed->GetLineColor());
  fit_mcSum_passed->SetLineWidth(2);
  fit_mcSum_passed->Draw("same");

  graph_Data_failed->SetLineColor(2);
  graph_Data_failed->SetMarkerColor(2);
  graph_Data_failed->SetMarkerStyle(21);
  //graph_Data_failed->Draw("p");

  fit_Data_failed->SetLineColor(graph_Data_failed->GetLineColor());
  fit_Data_failed->SetLineWidth(2);
  //fit_Data_failed->Draw("same");
 
  graph_mcSum_failed->SetLineColor(6);
  graph_mcSum_failed->SetMarkerColor(6);
  graph_mcSum_failed->SetMarkerStyle(25);
  graph_mcSum_failed->Draw("p");

  fit_mcSum_failed->SetLineColor(graph_mcSum_failed->GetLineColor());
  fit_mcSum_failed->SetLineWidth(2);
  fit_mcSum_failed->Draw("same");
 
  TLegend* legend = new TLegend(0.61, 0.16, 0.89, 0.47, "", "brNDC"); 
  legend->SetBorderSize(0);
  legend->SetFillColor(0);
  //legend->AddEntry(graph_Data_passed,  legendEntry_Data_passed.Data(),  "p");
  legend->AddEntry(graph_mcSum_passed, legendEntry_mcSum_passed.Data(), "p");
  //legend->AddEntry(graph_Data_failed,  legendEntry_Data_failed.Data(),  "p");
  legend->AddEntry(graph_mcSum_failed, legendEntry_mcSum_failed.Data(), "p");
  legend->Draw();

  TPaveText* label = 0;
  if ( title.Length() > 0 ) {
    label = new TPaveText(0.175, 0.89, 0.48, 0.94, "NDC");
    label->AddText(title.Data());
    label->SetTextAlign(13);
    label->SetTextSize(0.045);
    label->SetFillStyle(0);
    label->SetBorderSize(0);
    label->Draw();
  }

  TPad* bottomPad = new TPad("bottomPad", "bottomPad", 0.00, 0.00, 1.00, 0.35);
  bottomPad->SetFillColor(10);
  bottomPad->SetTopMargin(0.02);
  bottomPad->SetLeftMargin(0.15);
  bottomPad->SetBottomMargin(0.24);
  bottomPad->SetRightMargin(0.05);
  bottomPad->SetGridx();
  bottomPad->SetGridy();

  canvas->cd();
  bottomPad->Draw();
  bottomPad->cd();

  TH1* dummyHistogram_bottom = new TH1D("dummyHistogram_bottom", "dummyHistogram_bottom", 10, 0., 100.);
  
  dummyHistogram_bottom->SetMinimum(-1.0);
  dummyHistogram_bottom->SetMaximum(+1.0);

  TAxis* xAxis_bottom = dummyHistogram_bottom->GetXaxis();
  xAxis_bottom->SetTitle("calo-E_{T}^{miss} / GeV");
  xAxis_bottom->SetTitleOffset(1.20);
  xAxis_bottom->SetLabelColor(1);
  xAxis_bottom->SetTitleColor(1);
  xAxis_bottom->SetTitleSize(0.08);
  xAxis_bottom->SetLabelOffset(0.02);
  xAxis_bottom->SetLabelSize(0.08);
  xAxis_bottom->SetTickLength(0.055);

  TAxis* yAxis_bottom = dummyHistogram_bottom->GetYaxis();
  yAxis_bottom->SetTitle("#frac{Data-Simulation}{Simulation}");
  yAxis_bottom->SetTitleOffset(0.85);
  yAxis_bottom->SetNdivisions(505);
  yAxis_bottom->CenterTitle();
  yAxis_bottom->SetTitleSize(0.08);
  yAxis_bottom->SetLabelSize(0.08);
  yAxis_bottom->SetTickLength(0.04);

  dummyHistogram_bottom->SetTitle("");
  dummyHistogram_bottom->SetStats(false);
  dummyHistogram_bottom->Draw("axis");
 
  TGraphAsymmErrors* graph_Data_div_mc_passed = makeGraph_data_div_mc(graph_Data_passed, graph_mcSum_passed);
  graph_Data_div_mc_passed->SetLineColor(graph_Data_passed->GetLineColor());
  graph_Data_div_mc_passed->SetMarkerColor(graph_Data_passed->GetMarkerColor());
  graph_Data_div_mc_passed->SetMarkerStyle(graph_Data_passed->GetMarkerStyle());
  graph_Data_div_mc_passed->Draw("p");
  
  TF1* fit_Data_div_mc_passed = 
    new TF1("fit_Data_div_mc_passed", &integralCrystalBall_f_div_f, 
	    fit_mcSum_passed->GetMinimumX(), fit_mcSum_passed->GetMaximumX(), 2*fit_mcSum_passed->GetNpar());
  for ( int iPar = 0; iPar < fit_mcSum_passed->GetNpar(); ++iPar ) {
    fit_Data_div_mc_passed->SetParameter(iPar, fit_Data_passed->GetParameter(iPar));
    fit_Data_div_mc_passed->SetParameter(iPar + fit_mcSum_passed->GetNpar(), fit_mcSum_passed->GetParameter(iPar));
  }
  fit_Data_div_mc_passed->SetLineColor(graph_Data_div_mc_passed->GetLineColor());
  fit_Data_div_mc_passed->SetLineWidth(2);
  fit_Data_div_mc_passed->Draw("same");

  TGraphAsymmErrors* graph_Data_div_mc_failed = makeGraph_data_div_mc(graph_Data_failed, graph_mcSum_failed);
  graph_Data_div_mc_failed->SetLineColor(graph_Data_failed->GetLineColor());
  graph_Data_div_mc_failed->SetMarkerColor(graph_Data_failed->GetMarkerColor());
  graph_Data_div_mc_failed->SetMarkerStyle(graph_Data_failed->GetMarkerStyle());
  graph_Data_div_mc_failed->Draw("p");
  
  TF1* fit_Data_div_mc_failed = 
    new TF1("fit_Data_div_mc_failed", &integralCrystalBall_f_div_f, 
	    fit_mcSum_failed->GetMinimumX(), fit_mcSum_failed->GetMaximumX(), 2*fit_mcSum_failed->GetNpar());
  for ( int iPar = 0; iPar < fit_mcSum_failed->GetNpar(); ++iPar ) {
    fit_Data_div_mc_failed->SetParameter(iPar, fit_Data_failed->GetParameter(iPar));
    fit_Data_div_mc_failed->SetParameter(iPar + fit_mcSum_failed->GetNpar(), fit_mcSum_failed->GetParameter(iPar));
  }
  fit_Data_div_mc_failed->SetLineColor(graph_Data_div_mc_failed->GetLineColor());
  fit_Data_div_mc_failed->SetLineWidth(2);
  fit_Data_div_mc_failed->Draw("same");

  topPad->RedrawAxis();
  bottomPad->RedrawAxis();

  canvas->Update();
  size_t idx = outputFileName.Last('.');
  std::string outputFileName_plot = std::string(outputFileName.Data(), 0, idx);
  if ( idx != std::string::npos ) canvas->Print(std::string(outputFileName_plot).append(std::string(outputFileName.Data(), idx)).data());
  //canvas->Print(std::string(outputFileName_plot).append(".png").data());
  //canvas->Print(std::string(outputFileName_plot).append(".pdf").data());
  topPad->Print(std::string(outputFileName_plot).append(".png").data());
  topPad->Print(std::string(outputFileName_plot).append(".pdf").data());

  delete legend;
  delete label;
  delete dummyHistogram_top;
  delete topPad;
  delete dummyHistogram_bottom;
  delete bottomPad;
  delete canvas;
}
コード例 #15
0
ファイル: qaConfig.C プロジェクト: ktf/AliPhysics
Int_t qaConfig(TTree* tree, TString* returnStrings)
{
  Float_t entryFrac=0.8, nsigmaOutlier=6., nsigmaWarning=3., epsilon=1.0e-6;

  //
  // specify all variables for which the status aliases shall be defined.
  // only for these variables the lines in the trending plots can be computed and plotted.
  //
  TString sTrendVars="meanTPCncl;meanTPCnclF;meanMIP;resolutionMIP;MIPattachSlopeA;MIPattachSlopeC;";
  sTrendVars+=";meanMIPele;resolutionMIPele;electroMIPSeparation;meanVertX;meanVertY;meanVertZ;meanMultPos;meanMultNeg;";
  sTrendVars+=";tpcItsMatchA;tpcItsMatchC;tpcItsMatchHighPtA;tpcItsMatchHighPtC;lambdaPull;ptPull;yPull;zPull;";
  sTrendVars+=";tpcConstrainPhiA;tpcConstrainPhiC;deltaPt;";
  sTrendVars+=";offsetdRA;offsetdZA;offsetdRC;offsetdZC;dcarAP0;dcarAP1;dcarCP0;dcarCP1;";
  sTrendVars+=";dcar_posA_0;dcar_posA_1;dcar_posA_2;dcaz_posA_0;dcaz_posA_1;dcaz_posA_2;";
  sTrendVars+=";dcar_posC_0;dcar_posC_1;dcar_posC_2;dcaz_posC_0;dcaz_posC_1;dcaz_posC_2;";
  sTrendVars+=";dcar_negA_0;dcar_negA_1;dcar_negA_2;dcaz_negA_0;dcaz_negA_1;dcaz_negA_2;";
  sTrendVars+=";dcar_negC_0;dcar_negC_1;dcar_negC_2;dcaz_negC_0;dcaz_negC_1;dcaz_negC_2;";

  //
  // combined variables
  // name them '..._combN' with N being the number of combined variables!
  //
  tree->SetAlias("meanMult_comb2"         , "((meanMultPos+meanMultNeg)/2.)");
  tree->SetAlias("tpcItsMatch_comb4"      , "((tpcItsMatchA+tpcItsMatchC+tpcItsMatchHighPtA+tpcItsMatchHighPtC)/4)"); // mean of all 4.
  tree->SetAlias("itsTpcPulls_comb4"      , "(TMath::Sqrt(lambdaPull**2+ptPull**2+yPull**2+zPull**2))");
  tree->SetAlias("tpcConstrainPhi_comb2"  , "(TMath::Sqrt(tpcConstrainPhiA**2+tpcConstrainPhiC**2))"); // sqrt of quadr. sum ok because it's a bias.
  tree->SetAlias("offsetd_comb4"          , "(TMath::Sqrt(offsetdRA**2+offsetdZA**2+offsetdRC**2+offsetdZC**2))");
  tree->SetAlias("dcarFitpar_comb4"       , "((dcarAP0+dcarAP1+dcarCP0+dcarCP1)/4)"); // mean of 4.
  tree->SetAlias("dcar0_comb4"            , "(TMath::Sqrt(dcar_posA_0**2+dcar_posC_0**2+dcar_negA_0**2+dcar_negC_0**2))");
  tree->SetAlias("dcar1_comb4"            , "(TMath::Sqrt(dcar_posA_1**2+dcar_posC_1**2+dcar_negA_1**2+dcar_negC_1**2))");
  tree->SetAlias("dcar2_comb4"            , "(TMath::Sqrt(dcar_posA_2**2+dcar_posC_2**2+dcar_negA_2**2+dcar_negC_2**2))");
  tree->SetAlias("dcaz0_comb4"            , "(TMath::Sqrt(dcaz_posA_0**2+dcaz_posC_0**2+dcaz_negA_0**2+dcaz_negC_0**2))");
  tree->SetAlias("dcaz1_comb4"            , "(TMath::Sqrt(dcaz_posA_1**2+dcaz_posC_1**2+dcaz_negA_1**2+dcaz_negC_1**2))");
  tree->SetAlias("dcaz2_comb4"            , "(TMath::Sqrt(dcaz_posA_2**2+dcaz_posC_2**2+dcaz_negA_2**2+dcaz_negC_2**2))");
  tree->SetAlias("MIPattachSlope_comb2"   , "((MIPattachSlopeA+MIPattachSlopeC*(-1))/2)");
  tree->SetAlias("PIDSepPow_comb2"        , "(meanMIPele-meanMIP)/(0.5*(resolutionMIP*meanMIP+resolutionMIPele*meanMIPele))");

  //
  // add all combined variables to sTrendVars!
  // only then the statistics aliases will be computed for them as well.
  //
  sTrendVars+=";meanMult_comb2;tpcItsMatch_comb4;itsTpcPulls_comb4;tpcConstrainPhi_comb2;";
  sTrendVars+=";offsetd_comb4;dcarFitpar_comb4;dcar0_comb4;dcar1_comb4;dcar2_comb4;dcaz0_comb4;dcaz1_comb4;dcaz2_comb4;";
  sTrendVars+=";MIPattachSlope_comb2;PIDSepPow_comb2;";

  //
  // specify criterion to mark runs with enough statistics.
  // these runs are the basis for the computation of the outlier criteria.
  // -> robust mean and rms are computed from given entry fraction (EF) of these runs!
  //
  tree->SetAlias("statisticOK", "(meanTPCncl>0)");

  //
  // creation of aliases for Outliers, Warnings, PhysicsAcceptable ...
  // upper and lower limits needed separately to retrieve the numerical values for the line positions.
  // for that reason the aliases are expected to be computable expressions.
  //
  TObjArray* oaTrendVars = sTrendVars.Tokenize(",;");
  for (Int_t vari=0; vari<oaTrendVars->GetEntriesFast(); vari++)
  {
    TString sVar( oaTrendVars->At(vari)->GetName() );

    // outliers, warnings and robust mean are set for all variables identically.
    TStatToolkit::SetStatusAlias(tree, sVar.Data(),    "statisticOK", Form("varname_OutlierMin:(MeanEF-%f*RMSEF-%f):%f", nsigmaOutlier, epsilon, entryFrac));
    TStatToolkit::SetStatusAlias(tree, sVar.Data(),    "statisticOK", Form("varname_OutlierMax:(MeanEF+%f*RMSEF+%f):%f", nsigmaOutlier, epsilon, entryFrac));
    TStatToolkit::SetStatusAlias(tree, sVar.Data(),    "statisticOK", Form("varname_WarningMin:(MeanEF-%f*RMSEF-%f):%f", nsigmaWarning, epsilon, entryFrac));
    TStatToolkit::SetStatusAlias(tree, sVar.Data(),    "statisticOK", Form("varname_WarningMax:(MeanEF+%f*RMSEF+%f):%f", nsigmaWarning, epsilon, entryFrac));
    TStatToolkit::SetStatusAlias(tree, sVar.Data(),    "statisticOK", Form("varname_RobustMean:(MeanEF+0):%f", entryFrac));

    // physics acceptable should be set for each type of variable individually.
    // some sets of variables are already set here, the rest should be set appropriately after the loop!
    Float_t combfac=1.;
    if (sVar.Contains("_comb")) {
      TString last = sVar(sVar.Last('b')+1, sVar.Length());
      combfac = TMath::Sqrt( atoi(last.Data()) );
    }
    if (sVar.Contains("dca")) {
      TStatToolkit::SetStatusAlias(tree, sVar.Data(),    "statisticOK", Form("varname_PhysAccMin:(MeanEF-%f+0)", 0.2*combfac)); // 2 mm around mean
      TStatToolkit::SetStatusAlias(tree, sVar.Data(),    "statisticOK", Form("varname_PhysAccMax:(MeanEF+%f+0)", 0.2*combfac)); // 2 mm around mean
    }
    else if (sVar.Contains("Pull")) {
      TStatToolkit::SetStatusAlias(tree, sVar.Data(),    "statisticOK", Form("varname_PhysAccMin:(MeanEF-%f+0)", 1.0*combfac)); // check them!
      TStatToolkit::SetStatusAlias(tree, sVar.Data(),    "statisticOK", Form("varname_PhysAccMax:(MeanEF+%f+0)", 1.0*combfac));
    }
    else { // other variables set to +- 5% of the mean as default to avoid crashes:
      TStatToolkit::SetStatusAlias(tree, sVar.Data(),    "statisticOK", Form("varname_PhysAccMin:(MeanEF-%f*MeanEF):%f", 0.05*combfac, entryFrac));
      TStatToolkit::SetStatusAlias(tree, sVar.Data(),    "statisticOK", Form("varname_PhysAccMax:(MeanEF+%f*MeanEF):%f", 0.05*combfac, entryFrac));
    }

  }

  //
  // all aliases can just be overwritten here...
  // PhysAcc should be set to relative or absolute values appropriately!
  //
  TStatToolkit::SetStatusAlias(tree, "meanTPCncl",    "statisticOK", Form("varname_PhysAccMin:(MeanEF-%f*MeanEF):%f", 0.05, entryFrac));
  TStatToolkit::SetStatusAlias(tree, "meanTPCncl",    "statisticOK", Form("varname_PhysAccMax:(MeanEF+%f*MeanEF):%f", 0.05, entryFrac));
  TStatToolkit::SetStatusAlias(tree, "meanMIP",       "statisticOK", Form("varname_PhysAccMin:(MeanEF-%f*MeanEF):%f", 0.01, entryFrac));
  TStatToolkit::SetStatusAlias(tree, "meanMIP",       "statisticOK", Form("varname_PhysAccMax:(MeanEF+%f*MeanEF):%f", 0.01, entryFrac));
  TStatToolkit::SetStatusAlias(tree, "resolutionMIP", "statisticOK", Form("varname_PhysAccMin:(MeanEF-%f*MeanEF):%f", 0.10, entryFrac));
  TStatToolkit::SetStatusAlias(tree, "resolutionMIP", "statisticOK", Form("varname_PhysAccMax:(MeanEF+%f*MeanEF):%f", 0.10, entryFrac));
  TStatToolkit::SetStatusAlias(tree, "MIPattachSlopeA",  "statisticOK", Form("varname_PhysAccMin:(MeanEF-%f*MeanEF):%f", 0.005, entryFrac)); // p0 + p1 * tan(theta) // showing p1
  TStatToolkit::SetStatusAlias(tree, "MIPattachSlopeA",  "statisticOK", Form("varname_PhysAccMax:(MeanEF+%f*MeanEF):%f", 0.005, entryFrac));
  TStatToolkit::SetStatusAlias(tree, "MIPattachSlopeC",  "statisticOK", Form("varname_PhysAccMin:(MeanEF-%f*MeanEF):%f", 0.005, entryFrac));
  TStatToolkit::SetStatusAlias(tree, "MIPattachSlopeC",  "statisticOK", Form("varname_PhysAccMax:(MeanEF+%f*MeanEF):%f", 0.005, entryFrac));
  TStatToolkit::SetStatusAlias(tree, "meanMIPele",       "statisticOK", Form("varname_PhysAccMin:(MeanEF-%f*MeanEF):%f", 0.01, entryFrac));
  TStatToolkit::SetStatusAlias(tree, "meanMIPele",       "statisticOK", Form("varname_PhysAccMax:(MeanEF+%f*MeanEF):%f", 0.01, entryFrac));
  TStatToolkit::SetStatusAlias(tree, "resolutionMIPele", "statisticOK", Form("varname_PhysAccMin:(MeanEF-%f*MeanEF):%f", 0.10, entryFrac));
  TStatToolkit::SetStatusAlias(tree, "resolutionMIPele", "statisticOK", Form("varname_PhysAccMax:(MeanEF+%f*MeanEF):%f", 0.10, entryFrac));
  TStatToolkit::SetStatusAlias(tree, "meanVertZ",     "statisticOK", Form("varname_PhysAccMin:(%f+0)",-1.0 ));
  TStatToolkit::SetStatusAlias(tree, "meanVertZ",     "statisticOK", Form("varname_PhysAccMax:(%f+0)", 1.0 ));
//  TStatToolkit::SetStatusAlias(tree, "tpcItsMatchA",  "statisticOK", Form("varname_PhysAccMin:(%f+0)", 0.7 )); // TODO: set to +-3% after multiplicity correction (see wiki)
//  TStatToolkit::SetStatusAlias(tree, "tpcItsMatchA",  "statisticOK", Form("varname_PhysAccMax:(%f+0)", 1.0 ));
//  TStatToolkit::SetStatusAlias(tree, "tpcItsMatchC",  "statisticOK", Form("varname_PhysAccMin:(%f+0)", 0.7 ));
//  TStatToolkit::SetStatusAlias(tree, "tpcItsMatchC",  "statisticOK", Form("varname_PhysAccMax:(%f+0)", 1.0 ));

  //
  // now the actual criteria for each variable are set automatically.
  //
  for (Int_t vari=0; vari<oaTrendVars->GetEntriesFast(); vari++)
  {
    TString sVar( oaTrendVars->At(vari)->GetName() );
    TStatToolkit::SetStatusAlias(tree, sVar.Data(),    "", Form("varname_Outlier:(varname>varname_OutlierMax||varname<varname_OutlierMin)"));
    TStatToolkit::SetStatusAlias(tree, sVar.Data(),    "", Form("varname_Warning:(varname>varname_WarningMax||varname<varname_WarningMin)"));
    TStatToolkit::SetStatusAlias(tree, sVar.Data(),    "", Form("varname_PhysAcc:(varname>varname_PhysAccMin&&varname<varname_PhysAccMax)"));
  }

  // TStatToolkit::SetStatusAlias(tree, sVar.Data(),    "", Form("varname_Outlier:(varname>varname_OutlierMax||varname<varname_OutlierMin)"));


  //
  // COMBINED CRITERIA
  //
  // Adding new subcriteria to the following combined criteria may change the descision based on the individual ones.
  // e.g.: Assume a meanMIP warning that was vetoed by a meanMIP physacc before. It will not be vetoed anymore, if the physacc of MIPattach is very small.
  //

  // combined MIP quality
  // tree->SetAlias("MIPquality_Outlier", "(meanMIP_Outlier||resolutionMIP_Outlier||MIPattachSlopeA_Outlier||MIPattachSlopeC_Outlier||PIDSepPow_comb2_Outlier)");
  // tree->SetAlias("MIPquality_Warning", "(meanMIP_Warning||resolutionMIP_Warning||MIPattachSlopeA_Warning||MIPattachSlopeC_Warning||PIDSepPow_comb2_Warning)");
  // tree->SetAlias("MIPquality_PhysAcc", "(meanMIP_PhysAcc&&resolutionMIP_PhysAcc&&MIPattachSlopeA_PhysAcc&&MIPattachSlopeC_PhysAcc&&PIDSepPow_comb2_PhysAcc)");
  Float_t MeanMip_limitmax = 53.;
  Float_t MeanMip_limitmin = 47.;
  tree->SetAlias("MIPquality_Outlier", Form("(meanMIP_Outlier||resolutionMIP_Outlier||PIDSepPow_comb2_Outlier||meanMIP<%f||meanMIP>%f)", MeanMip_limitmin, MeanMip_limitmax));
  tree->SetAlias("MIPquality_Warning", "(meanMIP_Warning||resolutionMIP_Warning||PIDSepPow_comb2_Warning)");
  tree->SetAlias("MIPquality_PhysAcc", Form("(meanMIP_PhysAcc&&resolutionMIP_PhysAcc&&PIDSepPow_comb2_PhysAcc&&meanMIP>%f&&meanMIP<%f)", MeanMip_limitmin, MeanMip_limitmax));

  // combined matching efficiency
  Float_t TPC_ITS_limit = 0.5;
  tree->SetAlias("tpcItsMatch_Outlier", Form("(tpcItsMatchA_Outlier||tpcItsMatchC_Outlier||tpcItsMatchHighPtA_Outlier||tpcItsMatchHighPtC_Outlier||tpcItsMatchA<%f||tpcItsMatchC<%f)", TPC_ITS_limit, TPC_ITS_limit));
  tree->SetAlias("tpcItsMatch_Warning", "(tpcItsMatchA_Warning||tpcItsMatchC_Warning||tpcItsMatchHighPtA_Warning||tpcItsMatchHighPtC_Warning)");
  tree->SetAlias("tpcItsMatch_PhysAcc", Form("(tpcItsMatchA_PhysAcc&&tpcItsMatchC_PhysAcc&&tpcItsMatchHighPtA_PhysAcc&&tpcItsMatchHighPtC_PhysAcc&&tpcItsMatchA>%f&&tpcItsMatchC>%f)", TPC_ITS_limit, TPC_ITS_limit));

  // combined matching quality (lambdaPull ptPull yPull zPull)
  tree->SetAlias("itsTpcPulls_Outlier", "(lambdaPull_Outlier||ptPull_Outlier||yPull_Outlier||zPull_Outlier)");
  tree->SetAlias("itsTpcPulls_Warning", "(lambdaPull_Warning||ptPull_Warning||yPull_Warning||zPull_Warning)");
  tree->SetAlias("itsTpcPulls_PhysAcc", "(lambdaPull_PhysAcc&&ptPull_PhysAcc&&yPull_PhysAcc&&zPull_PhysAcc)");

  // combined DCA R and Z
  tree->SetAlias("dcar0_Outlier", "(dcar_posA_0_Outlier||dcar_posC_0_Outlier||dcar_negA_0_Outlier||dcar_negC_0_Outlier)");
  tree->SetAlias("dcar1_Outlier", "(dcar_posA_1_Outlier||dcar_posC_1_Outlier||dcar_negA_1_Outlier||dcar_negC_1_Outlier)");
  tree->SetAlias("dcar2_Outlier", "(dcar_posA_2_Outlier||dcar_posC_2_Outlier||dcar_negA_2_Outlier||dcar_negC_2_Outlier)");
  tree->SetAlias("dcar_Outlier" , "(dcar0_Outlier||dcar1_Outlier||dcar2_Outlier)");
  tree->SetAlias("dcaz0_Outlier", "(dcaz_posA_0_Outlier||dcaz_posC_0_Outlier||dcaz_negA_0_Outlier||dcaz_negC_0_Outlier)");
  tree->SetAlias("dcaz1_Outlier", "(dcaz_posA_1_Outlier||dcaz_posC_1_Outlier||dcaz_negA_1_Outlier||dcaz_negC_1_Outlier)");
  tree->SetAlias("dcaz2_Outlier", "(dcaz_posA_2_Outlier||dcaz_posC_2_Outlier||dcaz_negA_2_Outlier||dcaz_negC_2_Outlier)");
  tree->SetAlias("dcaz_Outlier" , "(dcaz0_Outlier||dcaz1_Outlier||dcaz2_Outlier)");

  tree->SetAlias("dcar0_Warning", "(dcar_posA_0_Warning||dcar_posC_0_Warning||dcar_negA_0_Warning||dcar_negC_0_Warning)");
  tree->SetAlias("dcar1_Warning", "(dcar_posA_1_Warning||dcar_posC_1_Warning||dcar_negA_1_Warning||dcar_negC_1_Warning)");
  tree->SetAlias("dcar2_Warning", "(dcar_posA_2_Warning||dcar_posC_2_Warning||dcar_negA_2_Warning||dcar_negC_2_Warning)");
  tree->SetAlias("dcar_Warning" , "(dcar0_Warning||dcar1_Warning||dcar2_Warning)");
  tree->SetAlias("dcaz0_Warning", "(dcaz_posA_0_Warning||dcaz_posC_0_Warning||dcaz_negA_0_Warning||dcaz_negC_0_Warning)");
  tree->SetAlias("dcaz1_Warning", "(dcaz_posA_1_Warning||dcaz_posC_1_Warning||dcaz_negA_1_Warning||dcaz_negC_1_Warning)");
  tree->SetAlias("dcaz2_Warning", "(dcaz_posA_2_Warning||dcaz_posC_2_Warning||dcaz_negA_2_Warning||dcaz_negC_2_Warning)");
  tree->SetAlias("dcaz_Warning" , "(dcaz0_Warning||dcaz1_Warning||dcaz2_Warning)");

  tree->SetAlias("dcar0_PhysAcc", "(dcar_posA_0_PhysAcc&&dcar_posC_0_PhysAcc&&dcar_negA_0_PhysAcc&&dcar_negC_0_PhysAcc)");
  tree->SetAlias("dcar1_PhysAcc", "(dcar_posA_1_PhysAcc&&dcar_posC_1_PhysAcc&&dcar_negA_1_PhysAcc&&dcar_negC_1_PhysAcc)");
  tree->SetAlias("dcar2_PhysAcc", "(dcar_posA_2_PhysAcc&&dcar_posC_2_PhysAcc&&dcar_negA_2_PhysAcc&&dcar_negC_2_PhysAcc)");
  tree->SetAlias("dcar_PhysAcc" , "(dcar0_PhysAcc&&dcar1_PhysAcc&&dcar2_PhysAcc)");
  tree->SetAlias("dcaz0_PhysAcc", "(dcaz_posA_0_PhysAcc&&dcaz_posC_0_PhysAcc&&dcaz_negA_0_PhysAcc&&dcaz_negC_0_PhysAcc)");
  tree->SetAlias("dcaz1_PhysAcc", "(dcaz_posA_1_PhysAcc&&dcaz_posC_1_PhysAcc&&dcaz_negA_1_PhysAcc&&dcaz_negC_1_PhysAcc)");
  tree->SetAlias("dcaz2_PhysAcc", "(dcaz_posA_2_PhysAcc&&dcaz_posC_2_PhysAcc&&dcaz_negA_2_PhysAcc&&dcaz_negC_2_PhysAcc)");
  tree->SetAlias("dcaz_PhysAcc" , "(dcaz0_PhysAcc&&dcaz1_PhysAcc&&dcaz2_PhysAcc)");


  //
  // specify the variables which shall be included in the status bar.
  // give them meaningful names for the y axis of the status bar!
  //
  TString sStatusbarVars ("MIPquality;dcaz;dcar;tpcItsMatch;itsTpcPulls;meanTPCncl;global");
  TString sStatusbarNames("dE/dx (MIP);v_drift (DCAZ);space p.(DCAR);TPC-ITS m.eff.;ITS-TPC m.qual.;mean TPC Ncl;global result");

  //
  // global descision is made automatically from the other entries in the status bar.
  //
  TString sVarsNoGlobal = sStatusbarVars;
  sVarsNoGlobal.Remove(sVarsNoGlobal.Last(';'), sVarsNoGlobal.Length()); // remove last item (';global')
  // global PhysAcc
  TString sGlobalCriterion = sVarsNoGlobal;
  sGlobalCriterion.ReplaceAll(";","_PhysAcc&&"); sGlobalCriterion.Append("_PhysAcc");
  cout << "global PhysAcc:  " << sGlobalCriterion.Data() << endl;
  tree->SetAlias("global_PhysAcc" , sGlobalCriterion.Data());
  // global Outlier
  sGlobalCriterion="";
  TObjArray* oaVarsNoGlobal = sVarsNoGlobal.Tokenize(";");
  for (Int_t vari=0; vari<oaVarsNoGlobal->GetEntriesFast(); vari++)
  {
    TString sVar( oaVarsNoGlobal->At(vari)->GetName() );
    sGlobalCriterion+=Form("(%s_Outlier&&!%s_PhysAcc)", sVar.Data(), sVar.Data());
    if (vari<oaVarsNoGlobal->GetEntriesFast()-1) sGlobalCriterion+="||";
  }
  cout << "global Outlier:  " << sGlobalCriterion.Data() << endl;
  tree->SetAlias("global_Outlier" , sGlobalCriterion.Data());
  // global Warning
  sGlobalCriterion.ReplaceAll("_Outlier","_Warning");
  cout << "global Warning:  " << sGlobalCriterion.Data() << endl;
  tree->SetAlias("global_Warning" , sGlobalCriterion.Data());

  //
  // set Boolean criteria to be checked for the markers in the status bar:
  // separate them by colon ":"   (1) = true --> first marker always plotted
  //
  TString sCriteria("(1):(statisticOK):(varname_Warning):(varname_Outlier):(varname_PhysAcc)"); // or to just show vetos: (varname_PhysAcc&&varname_Warning)

  returnStrings[0] = sStatusbarVars;
  returnStrings[1] = sStatusbarNames;
  returnStrings[2] = sCriteria;

  return 1;
}
コード例 #16
0
ファイル: mergeFiles.C プロジェクト: ekfriis/farmout
void SplitPathName(TString pathname,TString *path,TString *name) {
    int slash = pathname.Last('/');
    *path = pathname(0,slash);
    *name = pathname(slash+1,pathname.Length()-slash-1);
}
コード例 #17
0
ファイル: CreateDatacards.C プロジェクト: UAEDF/vbfHbb
void CreateDatacards(float XMIN, float XMAX, int CAT_MIN,int CAT_MAX,int BRN_ORDER_NOM, int BRN_ORDER_VBF, TString TR, TString OUTPATH, TString CATVETO="", int MASS, float XMAXDIFF=0.)
{
  TString PATH(TString::Format("%s/output/",OUTPATH.Data()).Data());
  const int NCAT = 7;
  const int NF = 6;
  const int NMASS = 5;
  //---- uncertainties -------------------------------------
  const float UNC_BR[NMASS]       = {1.024,1.028,1.032,1.037,1.043};

  const float UNC_UEPS_VBF[NCAT]  = {1.04,1.02,0.97,0.93,1.02,1.03,1.04};
  const float UNC_JES_VBF[NCAT]   = {1.06,1.08,1.09,1.10,1.06,1.08,1.10};
  const float UNC_JER_VBF[NCAT]   = {0.97,0.96,0.97,0.98,0.99,0.98,0.99};
  const float UNC_TRIG_VBF[NCAT]  = {1.03,1.04,1.05,1.06,1.01,1.01,1.02};
  const float UNC_CSV_VBF[NCAT]   = {1.03,0.99,0.97,0.94,1.01,0.94,0.91};
  const float UNC_QGL_VBF[NCAT]   = {1.03,1.01,1.00,0.98,1.03,1.01,0.98};
  const float UNC_SCALE_VBF[NCAT] = {1.00,1.00,1.01,1.02,1.03,1.03,1.05};
  const float UNC_PDF_VBF[NCAT]   = {1.02,1.02,1.02,1.02,1.03,1.03,1.03};
  const float UNC_PDFGlobal_VBF[NMASS]   = {1.028,1.028,1.028,1.027,1.027};
  const float UNC_SCALEGlobal_VBF[NMASS] = {1.002,1.002,1.002,1.002,1.002};

  const float UNC_UEPS_GF[NCAT]   = {1.25,1.10,0.80,0.90,0.65,1.65,1.45};
  const float UNC_JES_GF[NCAT]    = {1.08,1.10,1.12,1.12,1.04,1.09,1.10};
  const float UNC_JER_GF[NCAT]    = {0.99,0.99,0.95,0.96,0.91,0.99,0.95};
  const float UNC_TRIG_GF[NCAT]   = {1.05,1.05,1.10,1.15,1.09,1.09,1.19};
  const float UNC_CSV_GF[NCAT]    = {0.99,0.97,0.93,0.93,0.93,0.97,0.90};
  const float UNC_QGL_GF[NCAT]    = {1.03,1.01,1.00,0.98,1.03,1.01,0.98};
  const float UNC_SCALE_GF[NCAT]  = {1.00,1.00,1.01,1.02,1.03,1.03,1.05};
  const float UNC_PDF_GF[NCAT]    = {1.04,1.04,1.04,1.04,1.05,1.04,1.04};
  const float UNC_PDFGlobal_GF[NMASS]    = {1.076,1.075,1.075,1.075,1.074};
  const float UNC_SCALEGlobal_GF[NMASS]  = {1.081,1.079,1.078,1.077,1.077};

  vector<int> vCATVETO = tokenize(CATVETO);
  TString tCATVETO = tag(CATVETO);

  bool FreeTF=false, TF=false;
  if (TR!="" && TR!="BRN") TF=true; 
  if (TF && (TR(0,5)!="Fixed"&&TR!="EXPO")) FreeTF=true;
  TString sTRF="";
  if (TR(0,5)=="Fixed") sTRF = TR(5,4);
  else sTRF = TR;

  if (XMAXDIFF==0) TFile *fData = TFile::Open(PATH+"data_shapes_workspace_"+TString::Format("BRN%dp%d_B%.f-%.f",BRN_ORDER_NOM,BRN_ORDER_VBF,XMIN,XMAX)+"_Fit"+TR+".root");
  else             TFile *fData = TFile::Open(PATH+"data_shapes_workspace_"+TString::Format("BRN%dp%d_B%.f-%.f%.f",BRN_ORDER_NOM,BRN_ORDER_VBF,XMIN,XMAX,XMAX+XMAXDIFF)+"_Fit"+TR+".root"); 
  if (XMAXDIFF==0) TFile *fSig  = TFile::Open(PATH+"signal_shapes_workspace_"+TString::Format("B%.f-%.f.root",XMIN,XMAX));
  else             TFile *fSig  = TFile::Open(PATH+"signal_shapes_workspace_"+TString::Format("B%.f-%.f%.f.root",XMIN,XMAX,XMAX+XMAXDIFF));
 
  RooWorkspace *wData = (RooWorkspace*)fData->Get("w");
  RooWorkspace *wSig  = (RooWorkspace*)fSig->Get("w");
  
  TString nameData = fData->GetName();
  TString nameDataShort = nameData(nameData.Last('/')+1,nameData.Length());
  TString nameSig  = fSig->GetName();
  TString nameSigShort = nameSig(nameSig.Last('/')+1,nameSig.Length());

  char name[1000];
  int H_MASS[5] = {115,120,125,130,135};
  float nData[NCAT],nZ[NCAT],nTop[NCAT],nSigVBF[5][NCAT],nSigGF[5][NCAT];
  for(int i=CAT_MIN;i<=CAT_MAX;i++) {
    sprintf(name,"yield_data_CAT%d",i);
    nData[i] = float((RooRealVar*)wData->var(name)->getValV());
    sprintf(name,"yield_ZJets_CAT%d",i);
    nZ[i]  = ((RooRealVar*)wData->var(name))->getValV();
    sprintf(name,"yield_Top_CAT%d",i);
    nTop[i]  = ((RooRealVar*)wData->var(name))->getValV(); 
    for(int m=0;m<5;m++) {
      if (H_MASS[m]!=MASS) continue;
      sprintf(name,"yield_signalVBF_mass%d_CAT%d",H_MASS[m],i);
      nSigVBF[m][i] = ((RooRealVar*)wSig->var(name))->getValV();
      sprintf(name,"yield_signalGF_mass%d_CAT%d",H_MASS[m],i);
      nSigGF[m][i]  = ((RooRealVar*)wSig->var(name))->getValV();
    }
  }
  
  makeDirs(OUTPATH);
  makeDirs(OUTPATH+"/output/");
  makeDirs(OUTPATH+"/output/datacards");
  for(int m=0;m<5;m++) {
    if (H_MASS[m]!=MASS) continue;
	 cout << m << endl;
    ofstream datacard;
    if (XMAXDIFF==0) sprintf(name,"%s/output/datacards/datacard_m%d_BRN%dp%d_B%.f-%.f_CAT%d-CAT%d%s_Fit%s.txt",OUTPATH.Data(),H_MASS[m],BRN_ORDER_NOM,BRN_ORDER_VBF,XMIN,XMAX,CAT_MIN,CAT_MAX,tCATVETO.Data(),TR.Data());
	 else             sprintf(name,"%s/output/datacards/datacard_m%d_BRN%dp%d_B%.f-%.f%.f_CAT%d-CAT%d%s_Fit%s.txt",OUTPATH.Data(),H_MASS[m],BRN_ORDER_NOM,BRN_ORDER_VBF,XMIN,XMAX,XMAX+XMAXDIFF,CAT_MIN,CAT_MAX,tCATVETO.Data(),TR.Data());
    cout<<"======================================="<<endl; 
    cout<<"Creating datacard: "<<name<<endl;
    cout<<"======================================="<<endl; 
    datacard.open(name);
    datacard.setf(ios::right);
    datacard<<"imax "<<CAT_MAX-CAT_MIN+1-vCATVETO.size()<<"\n";
    datacard<<"jmax *"<<"\n";
    datacard<<"kmax *"<<"\n";
    datacard<<"----------------"<<"\n";

    datacard<<"shapes data_obs   * "<<nameDataShort<<" w:data_hist_$CHANNEL"<<"\n";
    datacard<<"shapes qcd        * "<<nameDataShort<<" w:qcd_model_Fit"<<TR.Data()<<"_$CHANNEL"<<"\n";
    datacard<<"shapes top        * "<<nameDataShort<<" w:Top_model_$CHANNEL"<<"\n";
    datacard<<"shapes zjets      * "<<nameDataShort<<" w:Z_model_$CHANNEL"<<"\n";
    datacard<<"shapes qqH        * "<<nameSigShort<<" w:signal_model_m"<<H_MASS[m]<<"_$CHANNEL \n";
    datacard<<"shapes ggH        * "<<nameSigShort<<" w:signal_model_m"<<H_MASS[m]<<"_$CHANNEL \n";
    datacard<<"----------------"<<"\n";
    datacard<<"bin         ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) { 
		if (veto(vCATVETO, i)) continue;
      sprintf(name,"CAT%d ",i);
      datacard<<name;
    }
    datacard<<"\n";
    datacard<<"observation ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      datacard<<"-1 ";
    }  
    datacard<<"\n";
    datacard<<"----------------"<<"\n";
    datacard<<"bin  ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      sprintf(name,"CAT%d CAT%d CAT%d CAT%d CAT%d ",i,i,i,i,i);
      datacard<<name;
    }  
    datacard<<"\n";
    datacard<<"process ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      datacard<<"qqH ggH qcd top zjets ";
    }  
    datacard<<"\n";
    datacard<<"process ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      datacard<<"0 -1 1 1 1 ";
    }  
    datacard<<"\n";
    datacard<<"rate       ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      cout<<"cat#"<<i<<setw(8)<<nData[i]<<setw(8)<<nSigVBF[m][i]<<setw(8)<<nSigGF[m][i]<<setw(8)<<nTop[i]<<setw(8)<<nZ[i]<<setw(8)<<", S/B = "<<(nSigVBF[m][i]+nSigGF[m][i])/nData[i]<<endl;
      datacard<<nSigVBF[m][i]<<" "<<nSigGF[m][i]<<" "<<nData[i]<<" "<<nTop[i]<<" "<<nZ[i]<<" ";
    }
    datacard<<"\n";
    datacard<<"----------------"<<"\n";
    datacard<<"BR                     lnN ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      datacard<<setw(NF)<<UNC_BR[m]<<setw(NF)<<UNC_BR[m]<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-";
    }  
    datacard<<"\n";
    datacard<<"QCDscale_qqh           lnN ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      datacard<<setw(NF)<<UNC_SCALEGlobal_VBF[m]<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-";
    } 
    datacard<<"\n";
    datacard<<"QCDscale_ggh           lnN ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      datacard<<setw(NF)<<"-"<<setw(NF)<<UNC_SCALEGlobal_GF[m]<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-";
    } 
    datacard<<"\n";
    datacard<<"pdf_qqbar              lnN ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      datacard<<setw(NF)<<UNC_PDFGlobal_VBF[m]<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-";
    } 
    datacard<<"\n";
    datacard<<"pdf_gg                 lnN ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      datacard<<setw(NF)<<"-"<<setw(NF)<<UNC_PDFGlobal_GF[m]<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-";
    } 
    datacard<<"\n";
    datacard<<"lumi                   lnN ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      datacard<<setw(NF)<<"1.026"<<setw(NF)<<"1.026"<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-";
    }  
    datacard<<"\n";
    datacard<<"CMS_scale_j_ACCEPT     lnN ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      datacard<<setw(NF)<<UNC_JES_VBF[i]<<setw(NF)<<UNC_JES_GF[i]<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-";
    }  
    datacard<<"\n";
    datacard<<"pdf_ACCEPT             lnN ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      datacard<<setw(NF)<<"1.05"<<setw(NF)<<"1.05"<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-";
    }  
    datacard<<"\n";
    datacard<<"CMS_res_j_ACCEPT       lnN ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      datacard<<setw(NF)<<UNC_JER_VBF[i]<<setw(NF)<<UNC_JER_GF[i]<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-";
    }
    datacard<<"\n";
    datacard<<"CMS_qqH_hbb_trigger    lnN ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      datacard<<setw(NF)<<UNC_TRIG_VBF[i]<<setw(NF)<<UNC_TRIG_GF[i]<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-";
    } 
    datacard<<"\n";
    datacard<<"CMS_qqH_hbb_btag       lnN ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      datacard<<setw(NF)<<UNC_CSV_VBF[i]<<setw(NF)<<UNC_CSV_GF[i]<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-";
    } 
    datacard<<"\n";
    datacard<<"CMS_qqH_hbb_qgl        lnN ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      datacard<<setw(NF)<<UNC_QGL_VBF[i]<<setw(NF)<<UNC_QGL_GF[i]<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-";
    }
    datacard<<"\n";
    datacard<<"UEPS                   lnN ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      datacard<<setw(NF)<<UNC_UEPS_VBF[i]<<setw(NF)<<UNC_UEPS_GF[i]<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-";
    }
    datacard<<"\n";
    datacard<<"CMS_qqH_hbb_QCDscale   lnN ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      datacard<<setw(NF)<<UNC_SCALE_VBF[i]<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-";
    } 
    datacard<<"\n";
    datacard<<"CMS_ggH_hbb_QCDscale   lnN ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      datacard<<setw(NF)<<"-"<<setw(NF)<<UNC_SCALE_GF[i]<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-";
    } 
    datacard<<"\n";
    datacard<<"CMS_qqH_hbb_pdf        lnN ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      datacard<<setw(NF)<<UNC_PDF_VBF[i]<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-";
    }
    datacard<<"\n";
    datacard<<"CMS_ggH_hbb_pdf        lnN ";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      datacard<<setw(NF)<<"-"<<setw(NF)<<UNC_PDF_GF[i]<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-";
    }
    datacard<<"\n";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      sprintf(name,"CMS_vbfbb_qcd_norm_CAT%d    lnU ",i);
      datacard<<name<<setw(NF);
      for(int j=CAT_MIN;j<=CAT_MAX;j++) {      
		  if (veto(vCATVETO, j)) continue;
        if (j == i) {
          datacard<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<1.5<<setw(NF)<<"-"<<setw(NF)<<"-";
        }
        else {
          datacard<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-";
        }
      }
      datacard<<"\n";
    }  
    datacard<<"\n";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      sprintf(name,"CMS_vbfbb_zjets_norm_CAT%d  lnN ",i);
      datacard<<name<<setw(NF);
      for(int j=CAT_MIN;j<=CAT_MAX;j++) {
		  if (veto(vCATVETO, j)) continue;
        if (j == i) {
          datacard<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"1.3";
        }
        else {
          datacard<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-";
        }
      }
      datacard<<"\n";
    }
    datacard<<"\n";
    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
      sprintf(name,"CMS_vbfbb_top_norm_CAT%d    lnN ",i);
      datacard<<name<<setw(NF);
      for(int j=CAT_MIN;j<=CAT_MAX;j++) {
		  if (veto(vCATVETO, j)) continue;
        if (j == i) {
          datacard<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"1.3"<<setw(NF)<<"-";
        }
        else {
          datacard<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-"<<setw(NF)<<"-";
        }
      }
      datacard<<"\n";
    }


    datacard<<"\n";
    datacard<<"#--- signal and Z shape parameters ------ \n";
    datacard<<"\n";
    datacard<<"CMS_vbfbb_scale_mbb_selNOM   param 1.0 0.02"<<"\n";
    datacard<<"CMS_vbfbb_scale_mbb_selVBF   param 1.0 0.02"<<"\n";
    datacard<<"CMS_vbfbb_res_mbb_selNOM     param 1.0 0.1"<<"\n";
    datacard<<"CMS_vbfbb_res_mbb_selVBF     param 1.0 0.1"<<"\n";
	 

    for(int i=CAT_MIN;i<=CAT_MAX;i++) {
		if (veto(vCATVETO, i)) continue;
		//cout << "CAT" << i << endl;
      /*
      sprintf(name,"CMS_vbfbb_scale_mbb_CAT%d",i); 
      datacard<<name<<"     param 1.0 0.02"<<"\n";
      sprintf(name,"CMS_vbfbb_res_mbb_CAT%d",i);
      datacard<<name<<"       param 1.0 0.1"<<"\n";
      */      
      sprintf(name,"mean_m%d_CAT%d",H_MASS[m],i);
      RooRealVar *vmass = (RooRealVar*)wSig->var(name);
      double mass  = vmass->getValV();
      double emass = vmass->getError();
      datacard<<name<<"               param "<<mass<<" "<<emass<<"\n";
      sprintf(name,"sigma_m%d_CAT%d",H_MASS[m],i);
      RooRealVar *vsigma = (RooRealVar*)wSig->var(name);
      double sigma  = vsigma->getValV();
      double esigma = vsigma->getError(); 
      datacard<<name<<"              param "<<sigma<<" "<<esigma<<"\n";

      sprintf(name,"Top_mean_CAT%d",i);
      RooRealVar *Tvmass = (RooRealVar*)wData->var(name);
      double Tmass  = Tvmass->getValV();
      double Temass = 0.01*Tmass; //Tvmass->getError();
      datacard<<name<<"               param "<<Tmass<<" "<<Temass<<"\n";
      sprintf(name,"Top_sigma_CAT%d",i);
      RooRealVar *Tvsigma = (RooRealVar*)wData->var(name);
      double Tsigma  = Tvsigma->getValV();
      double Tesigma = 0.05*Tsigma;//Tvsigma->getError(); 
      datacard<<name<<"              param "<<Tsigma<<" "<<Tesigma<<"\n";

      sprintf(name,"Z_mean_CAT%d",i);
      RooRealVar *Zvmass = (RooRealVar*)wData->var(name);
      double Zmass  = Zvmass->getValV();
      double Zemass = Zvmass->getError();
      datacard<<name<<"               param "<<Zmass<<" "<<Zemass<<"\n";
      sprintf(name,"Z_sigma_CAT%d",i);
      RooRealVar *Zvsigma = (RooRealVar*)wData->var(name);
      double Zsigma  = Zvsigma->getValV();
      double Zesigma = Zvsigma->getError(); 
      datacard<<name<<"              param "<<Zsigma<<" "<<Zesigma<<"\n";
      
		for(int j=5; j>=0; j--){
		  if (i>0 && i < 4 && TF && !FreeTF) {
	        sprintf(name,"trans_%s_p%d_CAT%d",sTRF.Data(),j,i); 
			  if (wData->var(name)) {
				  cout << name << endl;
				  datacard<<name<<"                param "<<((RooRealVar*)wData->var(name))->getVal()<<" "<<((RooRealVar*)wData->var(name))->getError()<<"\n";
			  }
		  }
		  if (i > 4 && TF && !FreeTF) { 
	        sprintf(name,"trans_%s_p%d_CAT%d",sTRF.Data(),j,i); 
			  if (wData->var(name)) {
				  cout << name << endl;
				  datacard<<name<<"                param "<<((RooRealVar*)wData->var(name))->getVal()<<" "<<((RooRealVar*)wData->var(name))->getError()<<"\n";
			  }
		  }

		} 
      
    }
    datacard.close();
  }
  fData->Close();
  fSig->Close();
}
コード例 #18
0
void offline(const char* FileName="test")
{
    TH1F::SetDefaultSumw2();
    // Set Style parameters for this macro
    gStyle->SetOptTitle(1); // Show Title (off by default for cleanliness)
    gErrorIgnoreLevel = kError; // Set Verbosity Level (kPrint shows all)

    // Set Output options
    Int_t number;
    Bool_t fPaintAll = checkPaintAllTrigs();
    checkBatchMode();
    Bool_t makePDF = checkMakePDF();
    Bool_t makeROOT= checkMakeRoot();

    // Open ROOT File
    char name[1000];
    sprintf(name,"/Users/zach/Research/rootFiles/run12NPEhPhi/%s.root",FileName);
    TFile *f = new TFile(name,"READ");
    if (f->IsOpen()==kFALSE)
    {   std::cout << "!!! File Not Found !!!" << std::endl;
        exit(1);
    }
    // f->ls(); // - DEBUG by printing all objects in ROOT file

    char fname[100];
    TFile* file;
    if(makeROOT) {
        sprintf(fname,"/Users/zach/Research/rootFiles/run12NPEhPhi/%s_processed.root",FileName);
        file = new TFile(fname,"RECREATE");
        if (file->IsOpen()==kFALSE)
        {
            std::cout << "!!! Outfile Not Opened !!!" << std::endl;
            makeROOT = kFALSE;
        }
    }

    const Int_t numPtBins = anaConst::nPtBins;
    Float_t lowpt[numPtBins],highpt[numPtBins];
    for(Int_t c=0; c< numPtBins; c++) {
        lowpt[c] = anaConst::lpt[c];
        highpt[c] = anaConst::hpt[c];
    }
    Float_t hptCut=anaConst::hptCut;
    const Int_t numTrigs = 4;
    Double_t epsilon[numPtBins] = {0.593164, 0.626663, 0.655916, 0.674654, 0.685596, 0.700600, 0.716682, 0.724638, 0.713977, 0.730550, 0.735204, 0.744336, 0.761323, 0.758423};
    Float_t hptMax=25; // Set max above range to allow overflow
    Float_t lowPhi=anaConst::lowPhi, highPhi=anaConst::highPhi;
    Double_t pu[2][numPtBins][numTrigs]; // To store fit parameters for later use
    Double_t hhNorm, HHScale, hadPur;

    TH1D * LSIM[numPtBins][numTrigs];
    TH1D * USIM[numPtBins][numTrigs];
    TH1D * USIMNP[numPtBins][numTrigs];
    TH1D * LSIMNP[numPtBins][numTrigs];
    TH1D * INCLNP[numPtBins][numTrigs];
    TH1D * INCL[numPtBins][numTrigs];
    TH1D * LSIM2[numPtBins][numTrigs];
    TH1D * USIM2[numPtBins][numTrigs];
    TH1D * INCL2[numPtBins][numTrigs];
    TH1D * LSMM[numPtBins][numTrigs];
    TH1D * USMM[numPtBins][numTrigs];
    TH1D * HHDP[numPtBins][numTrigs];
    TH1D * NSPI[numPtBins][numTrigs];
    TH2F * MON[numTrigs];
    TH1F * AVGTRKS[numTrigs];
    TH2F * MON2[numTrigs];
    TH1F * AVGTRKS2[numTrigs];
    TH2F* mh2PhiQPt[numTrigs];
    TH2F* mh2nSigmaEPt[numTrigs];
    TH2F* mh2nSigmaEPt_eID[numTrigs];
    TH3F* mh3DelPhiIncl[numTrigs];
    TH3F* mh3DelPhiPhotLS[numTrigs];
    TH3F* mh3DelPhiPhotUS[numTrigs];
    TH3F* mh3DelPhiPhotUSNP[numTrigs];
    TH3F* mh3DelPhiPhotLSNP[numTrigs];
    TH3F* mh3DelPhiInclNP[numTrigs];
    TH3F* mh3DelPhiInclWt[numTrigs];
    TH3F* mh3DelPhiPhotLSWt[numTrigs];
    TH3F* mh3DelPhiPhotUSWt[numTrigs];
    TH2F* mh2InvMassPtLS[numTrigs];
    TH2F* mh2InvMassPtUS[numTrigs];
    TH2F* mh2PtEZdcx[numTrigs];
    TH2F* mh2PtEZdcxUS[numTrigs];
    TH2F* mh2PtEZdcxLS[numTrigs];
    TH2F* mh2PtEZdcxHad[numTrigs];
    TH3F* mh3nTracksZdcx[numTrigs];
    TH3F* mh3nTracksZdcxUS[numTrigs];
    TH3F* mh3nTracksZdcxLS[numTrigs];
    TH3F* mh3nTracksZdcxHad[numTrigs];
    TH3F* mh3MixedDelPhi;
    TH3F* mh3MixedDelEta;
    TH3F* mh3MixedEtaPhi;
    TH3F* mh3DelPhiHadHad[numTrigs];
    TH2F* mh2nSigmaPion[numTrigs];
    TH1F* mh1PtHadTracks[numTrigs];
    TH1F* mh1PtETracks[numTrigs];
    TH1D* projHPhi[numPtBins][numTrigs];
    TH1D* projnSigmaE[numPtBins][numTrigs];
    TH1D* projnSigmaE_eID[numPtBins][numTrigs];
    TH1D* projDelPhiIncl[numPtBins][numTrigs];
    TH1D* projDelPhiPhotLS[numPtBins][numTrigs];
    TH1D* projDelPhiPhotUS[numPtBins][numTrigs];
    TH1D* projDelPhiPhotUSNP[numPtBins][numTrigs];
    TH1D* projDelPhiPhotLSNP[numPtBins][numTrigs];
    TH1D* projDelPhiInclNP[numPtBins][numTrigs];
    TH1D* projDelPhiInclWt[numPtBins][numTrigs];
    TH1D* projDelPhiPhotLSWt[numPtBins][numTrigs];
    TH1D* projDelPhiPhotUSWt[numPtBins][numTrigs];
    TH1D* projDelPhiHadHad[numPtBins][numTrigs];
    TH1D* projInvMassLS[numPtBins][numTrigs];
    TH1D* projInvMassUS[numPtBins][numTrigs];
    TH1D* projnSigmaPion[numPtBins][numTrigs];
    TH1D* projEMixedEtaPhi;
    TH1D* projPMixedEtaPhi;
    TH2D* proj2DMixedEtaPhi;
    TH2D* proj2DMixedEvent[numPtBins];
    TH1D* projMixedDelPhi[numPtBins];
    TH1D* projMixedDelEta[numPtBins];
    TH2F* histoNorms;
    TH1D* projZDCxHad[numPtBins][numTrigs];
    TH1D* projZDCxTrig[numPtBins][numTrigs];
    TH1D* projZDCxHadUS[numPtBins][numTrigs];
    TH1D* projZDCxTrigUS[numPtBins][numTrigs];
    TH1D* projZDCxHadLS[numPtBins][numTrigs];
    TH1D* projZDCxTrigLS[numPtBins][numTrigs];
    TH1D* projZDCxHadHad[numPtBins][numTrigs];
    TH1D* projZDCxTrigHad[numPtBins][numTrigs];
    TProfile2D* profileZDCx[numTrigs];
    TCanvas * c[numTrigs];
    TCanvas * c2[numTrigs];
    TCanvas * IN[numTrigs];
    TCanvas * IN2[numTrigs];
    TCanvas * pile[numTrigs];
    TCanvas * pileHad[numTrigs];
    TCanvas * result[numTrigs];
    TCanvas * result2[numTrigs];
    TCanvas * inMass[numTrigs];
    TCanvas * USComp[numTrigs];
    TCanvas * LSComp[numTrigs];
    TCanvas * InclComp[numTrigs];
    TCanvas * cHH[numTrigs];
    TCanvas * nSigPi[numTrigs];
    TCanvas * allDist[numTrigs];
    TCanvas * mixedC;
    TCanvas * mixedCbinEta;
    TCanvas * mixedCbinPhi;
    TCanvas * mixedCbin;
    TCanvas * singlePlot;

    TPaveText* lbl[numPtBins];
    TPaveText* stat[numPtBins];
    char textLabel[100];
    singlePlot =  new TCanvas("singlePlot","Single Plot",150,0,1150,1000);

    // Trigger Independent Hists
    mixedC     = new TCanvas("mixedC","Mixed Events",150,0,1150,1000);
    mixedCbinEta = new TCanvas("mixedCbinEta","Mixed Events Eta",150,0,1150,1000);
    mixedCbinPhi = new TCanvas("mixedCbinPhi","Mixed Events Phi",150,0,1150,1000);
    mixedCbin = new TCanvas("mixedCbin","Mixed Events 2D",150,0,1150,1000);

    mixedC       -> Divide(2,2);
    mixedCbinEta -> Divide(4,3);
    mixedCbinPhi -> Divide(4,3);

    mh3MixedDelPhi = (TH3F*)f->Get("mh3MixedDelPhi");
    mh3MixedDelEta = (TH3F*)f->Get("mh3MixedDelEta");
    mh3MixedEtaPhi = (TH3F*)f->Get("mh3MixedEtaPhi");

    ///////////////////////////
    projPMixedEtaPhi  = mh3MixedEtaPhi -> ProjectionX("projPMixedEtaPhi");
    projEMixedEtaPhi  = mh3MixedEtaPhi -> ProjectionY("projEMixedEtaPhi");
    proj2DMixedEtaPhi = (TH2D*)mh3MixedEtaPhi -> Project3D("yx");
    Int_t RB2 = 2;
    projEMixedEtaPhi->Rebin(RB2);
    projPMixedEtaPhi->Rebin(RB2);

    mixedC->cd(1);
    mh3MixedEtaPhi->GetXaxis()->SetTitle("#Delta#phi");
    mh3MixedEtaPhi->GetXaxis()->SetRangeUser(lowPhi,highPhi);
    mh3MixedEtaPhi->GetYaxis()->SetTitle("#Delta#eta");
    mh3MixedEtaPhi->GetYaxis()->SetRangeUser(-1.5,1.5);
    mh3MixedEtaPhi->GetZaxis()->SetTitle("P_{t,e}");
    mh3MixedEtaPhi->Draw();
    mixedC->cd(2);
    projPMixedEtaPhi->GetXaxis()->SetRangeUser(lowPhi,highPhi);
    projPMixedEtaPhi->GetXaxis()->SetTitle("#Delta#phi");
    projPMixedEtaPhi->GetYaxis()->SetRangeUser(0,20000);
    projPMixedEtaPhi->SetTitle("Mixed Event #Delta#phi");
    projPMixedEtaPhi->Draw();
    mixedC->cd(3);
    projEMixedEtaPhi->GetXaxis()->SetRangeUser(-2.5,2.5);
    projEMixedEtaPhi->GetXaxis()->SetTitle("#Delta#eta");
    projEMixedEtaPhi->SetTitle("Mixed Event #Delta#eta");
    projEMixedEtaPhi->Draw();
    mixedC->cd(4);
    mixedC->SetLogz(1);
    proj2DMixedEtaPhi->GetXaxis()->SetTitle("#Delta#phi");
    proj2DMixedEtaPhi->GetXaxis()->SetRangeUser(lowPhi,highPhi);
    proj2DMixedEtaPhi->GetYaxis()->SetTitle("#Delta#eta");
    proj2DMixedEtaPhi->GetYaxis()->SetRangeUser(-1.5,1.5);
    proj2DMixedEtaPhi->Draw("colz");

    TH3F* temp3D[numPtBins];
    // PtBins for Mixed Event
    for(Int_t ptbin = 0; ptbin < numPtBins; ptbin++) {

        // Init necessary plotting tools
        lbl[ptbin] = new TPaveText(.2,.8,.5,.85,Form("NB NDC%i",ptbin));
        sprintf(textLabel,"%.1f < P_{T,e} < %.1f",lowpt[ptbin],highpt[ptbin]);
        lbl[ptbin]->AddText(textLabel);
        lbl[ptbin]->SetFillColor(kWhite);

        projMixedDelPhi[ptbin] = mh3MixedEtaPhi->ProjectionX(Form("projMixedDelPhi_%i",ptbin),0,-1,mh3MixedEtaPhi->GetZaxis()->FindBin(lowpt[ptbin]),mh3MixedEtaPhi->GetZaxis()->FindBin(highpt[ptbin])-1);
        projMixedDelEta[ptbin] = mh3MixedEtaPhi->ProjectionY(Form("projMixedDelEta_%i",ptbin),0,-1,mh3MixedEtaPhi->GetZaxis()->FindBin(lowpt[ptbin]),mh3MixedEtaPhi->GetZaxis()->FindBin(highpt[ptbin])-1);

        mixedCbinEta->cd(ptbin+1);
        projMixedDelEta[ptbin]->GetXaxis()->SetRangeUser(-2.5,2.5);
        projMixedDelEta[ptbin]->GetXaxis()->SetTitle("#Delta#eta");
        projMixedDelEta[ptbin]->Draw();

        mixedCbinPhi->cd(ptbin+1);
        projMixedDelPhi[ptbin]->GetXaxis()->SetRangeUser(lowPhi-.5,highPhi+.5);
        // projMixedDelPhi[ptbin]->GetYaxis()->SetRangeUser(0,2000);
        projMixedDelPhi[ptbin]->GetXaxis()->SetTitle("#Delta#phi");
        projMixedDelPhi[ptbin]->Draw();

        /*   temp3D[ptbin] = (TH3F*)mh3MixedEtaPhi->Clone(); // make a clone to set axis range on for 3D to 2D projection
        temp3D[ptbin]->GetZaxis()->SetRangeUser(lowpt[ptbin],highpt[ptbin]); // project3d only projects active range
        proj2DMixedEvent[ptbin] = (TH2D*)temp3D[ptbin] -> Project3D("yx");
        proj2DMixedEvent[ptbin]->SetName(Form("proj2DMixedEvent_%i",ptbin));

        mixedCbin->cd(ptbin+1);
        proj2DMixedEvent[ptbin]->GetXaxis()->SetTitle("#Delta#phi");
        proj2DMixedEvent[ptbin]->GetXaxis()->SetRangeUser(lowPhi,highPhi);
        proj2DMixedEvent[ptbin]->GetYaxis()->SetTitle("#Delta#eta");
        proj2DMixedEvent[ptbin]->GetYaxis()->SetRangeUser(-1.5,1.5);
        proj2DMixedEvent[ptbin]->Draw("colz");*/

    }

    /// TRIGGER LOOP
    histoNorms = new TH2F("histoNorms","",4,0,12,20,0,20); // Fill normalization in a single histogram for accessing later

    for(Int_t trig = 0; trig < numTrigs; trig++) {

        if(!fPaintAll && (trig == 1 || trig == 3)) continue;
        // Create and Segment Canvas
        c[trig]        = new TCanvas(Form("c%i",trig),"Photonic Hists",150,0,1150,1000);
        IN[trig]       = new TCanvas(Form("IN%i",trig),"Inclusive Hists",150,0,1150,1000);
        pile[trig]     = new TCanvas(Form("pile%i",trig),"Pileup Monitor",150,0,1150,1000);
        pileHad[trig]  = new TCanvas(Form("pileHad%i",trig),"Pileup Monitor",150,0,1150,1000);
        //  pileTrig[trig] = new TCanvas(Form("pileTrig%i",trig),"Pileup Monitor",150,0,1150,1000);
        inMass[trig]   = new TCanvas(Form("inMass%i",trig),"Invariant Mass",150,0,1150,1000);
        result[trig]   = new TCanvas(Form("result%i",trig),"Inclusive - Photonic",150,0,1150,1000);
        USComp[trig]   = new TCanvas(Form("USComp%i",trig),"Unlike Sign Distributions",150,0,1150,1000);
        LSComp[trig]   = new TCanvas(Form("LSComp%i",trig),"Like Sign Distributions",150,0,1150,1000);
        InclComp[trig] = new TCanvas(Form("InclComp%i",trig),"Inclusive Distributions",150,0,1150,1000);
        cHH[trig]      = new TCanvas(Form("cHH%i",trig),"Hadron-Hadron Distributions",150,0,1150,1000);
        nSigPi[trig]   = new TCanvas(Form("nSigPi_%i",trig),"n#sigma#pi QA",150,0,1150,1000);
        allDist[trig]  = new TCanvas(Form("allDist_%i",trig),"Distribution Comparison",150,0,1150,1000);
        c[trig]        -> Divide(4,3);
        inMass[trig]   -> Divide(4,3);
        IN[trig]       -> Divide(4,3);
        pile[trig]     -> Divide(4,3);
        result[trig]   -> Divide(4,3);
        USComp[trig]   -> Divide(4,3);
        LSComp[trig]   -> Divide(4,3);
        InclComp[trig] -> Divide(4,3);
        cHH[trig]      -> Divide(4,3);
        nSigPi[trig]   -> Divide(4,3);
        allDist[trig]  -> Divide(4,3);

        // Make Projections (first get 2d/3d hists, then project)
        mh2PhiQPt[trig]         = (TH2F*)f->Get(Form("mh2PhiQPt_%i",trig));
        mh2nSigmaEPt[trig]      = (TH2F*)f->Get(Form("mh2nSigmaEPt_%i",trig));
        mh2nSigmaEPt_eID[trig]  = (TH2F*)f->Get(Form("mh2nSigmaEPt_eID_%i",trig));
        mh3DelPhiIncl[trig]     = (TH3F*)f->Get(Form("mh3DelPhiIncl_%i",trig));
        mh3DelPhiPhotLS[trig]   = (TH3F*)f->Get(Form("mh3DelPhiPhotLS_%i",trig));
        mh3DelPhiPhotUS[trig]   = (TH3F*)f->Get(Form("mh3DelPhiPhotUS_%i",trig));
        mh3DelPhiPhotUSNP[trig] = (TH3F*)f->Get(Form("mh3DelPhiPhotUSNP_%i",trig));
        mh3DelPhiPhotLSNP[trig] = (TH3F*)f->Get(Form("mh3DelPhiPhotLSNP_%i",trig));
        mh3DelPhiInclNP[trig]   = (TH3F*)f->Get(Form("mh3DelPhiPhotInclNP_%i",trig));
        mh3DelPhiInclWt[trig]   = (TH3F*)f->Get(Form("mh3DelPhiInclWt_%i",trig));
        mh3DelPhiPhotLSWt[trig] = (TH3F*)f->Get(Form("mh3DelPhiPhotLSWt_%i",trig));
        mh3DelPhiPhotUSWt[trig] = (TH3F*)f->Get(Form("mh3DelPhiPhotUSWt_%i",trig));
        mh2InvMassPtLS[trig]    = (TH2F*)f->Get(Form("mh2InvMassPtLS_%i",trig));
        mh2InvMassPtUS[trig]    = (TH2F*)f->Get(Form("mh2InvMassPtUS_%i",trig));
        mh3DelPhiHadHad[trig]   = (TH3F*)f->Get(Form("mh3DelPhiHadHad_%i",trig));
        mh1PtHadTracks[trig]    = (TH1F*)f->Get(Form("mh1PtHadTracks_%i",trig));
        mh1PtETracks[trig]      = (TH1F*)f->Get(Form("mh1PtETracks_%i",trig));
        mh2nSigmaPion[trig]     = (TH2F*)f->Get(Form("mh2nSigmaPionPt_%i",trig));

        for(Int_t ptbin=0; ptbin<numPtBins; ptbin++)
        {
            // - Make projections into electron ptbins
            projHPhi[ptbin][trig] = mh2PhiQPt[trig]->ProjectionX(Form("projHPhi_%i_%i",ptbin,trig),mh2PhiQPt[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2PhiQPt[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);

            projnSigmaE[ptbin][trig] = mh2nSigmaEPt[trig]->ProjectionX(Form("projnSigmaE_%i_%i",ptbin,trig),mh2nSigmaEPt[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2nSigmaEPt[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);

            projnSigmaE_eID[ptbin][trig] = mh2nSigmaEPt_eID[trig]->ProjectionX(Form("projnSigmaE_eID_%i_%i",ptbin,trig),mh2nSigmaEPt_eID[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2nSigmaEPt_eID[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);

            projDelPhiIncl[ptbin][trig] = mh3DelPhiIncl[trig]->ProjectionX(Form("projDelPhiIncl_%i_%i",ptbin,trig),mh3DelPhiIncl[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiIncl[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiIncl[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiIncl[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotUS[ptbin][trig] = mh3DelPhiPhotUS[trig]->ProjectionX(Form("projDelPhiPhotUS_%i_%i",ptbin,trig),mh3DelPhiPhotUS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotUS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotUS[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotUSNP[ptbin][trig] = mh3DelPhiPhotUSNP[trig]->ProjectionX(Form("projDelPhiPhotUSNP_%i_%i",ptbin,trig),mh3DelPhiPhotUSNP[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotUSNP[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotUSNP[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotLS[ptbin][trig] = mh3DelPhiPhotLS[trig]->ProjectionX(Form("projDelPhiPhotLS_%i_%i",ptbin,trig),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotLS[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotLSNP[ptbin][trig] = mh3DelPhiPhotLSNP[trig]->ProjectionX(Form("projDelPhiPhotLSNP_%i_%i",ptbin,trig),mh3DelPhiPhotLSNP[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotLSNP[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotLSNP[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiInclNP[ptbin][trig] = mh3DelPhiInclNP[trig]->ProjectionX(Form("projDelPhiInclNP_%i_%i",ptbin,trig),mh3DelPhiInclNP[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiInclNP[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotLS[ptbin][trig] = mh3DelPhiPhotLS[trig]->ProjectionX(Form("projDelPhiPhotLS_%i_%i",ptbin,trig),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotLS[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotLS[ptbin][trig] = mh3DelPhiPhotLS[trig]->ProjectionX(Form("projDelPhiPhotLS_%i_%i",ptbin,trig),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotLS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotLS[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiInclWt[ptbin][trig] = mh3DelPhiInclWt[trig]->ProjectionX(Form("projDelPhiInclWt_%i_%i",ptbin,trig),mh3DelPhiInclWt[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiInclWt[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiInclWt[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotUSWt[ptbin][trig] = mh3DelPhiPhotUSWt[trig]->ProjectionX(Form("projDelPhiPhotUSWt_%i_%i",ptbin,trig),mh3DelPhiPhotUSWt[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotUSWt[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotUSWt[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projDelPhiPhotLSWt[ptbin][trig] = mh3DelPhiPhotLSWt[trig]->ProjectionX(Form("projDelPhiPhotLSWt_%i_%i",ptbin,trig),mh3DelPhiPhotLSWt[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiPhotLSWt[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiPhotLSWt[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projInvMassUS[ptbin][trig] = mh2InvMassPtUS[trig]->ProjectionX(Form("projInvMassUS_%i_%i",ptbin,trig),mh2InvMassPtUS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2InvMassPtUS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);

            projInvMassLS[ptbin][trig] = mh2InvMassPtLS[trig]->ProjectionX(Form("projInvMassLS_%i_%i",ptbin,trig),mh2InvMassPtLS[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2InvMassPtLS[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);

            projDelPhiHadHad[ptbin][trig] = mh3DelPhiHadHad[trig]->ProjectionX(Form("projDelPhiHadHad_%i_%i",ptbin,trig),mh3DelPhiHadHad[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh3DelPhiHadHad[trig]->GetYaxis()->FindBin(highpt[ptbin])-1,mh3DelPhiHadHad[trig]->GetZaxis()->FindBin(hptCut),mh3DelPhiInclNP[trig]->GetZaxis()->FindBin(hptMax));

            projnSigmaPion[ptbin][trig] = mh2nSigmaPion[trig]->ProjectionX(Form("projnSigmaPion_%i_%i",ptbin,trig),mh2nSigmaPion[trig]->GetYaxis()->FindBin(lowpt[ptbin]),mh2nSigmaPion[trig]->GetYaxis()->FindBin(highpt[ptbin])-1);
        }

        for(Int_t ptbin = 0; ptbin < numPtBins; ptbin++) {

            // Init necessary plotting tools
            lbl[ptbin] = new TPaveText(.15,.15,.35,.23,Form("NB NDC%i",ptbin));
            sprintf(textLabel,"%.1f < P_{T,e} < %.1f",lowpt[ptbin],highpt[ptbin]);
            lbl[ptbin]->AddText(textLabel);
            lbl[ptbin]->SetFillColor(kWhite);

            // Calculate electron purity from pol3 fit of xiaozhi data
            Float_t ptAv = (lowpt[ptbin]+highpt[ptbin])/2.;
            Float_t p[3] = {0.9743, 0.02128, -0.00438};
            Float_t purity = p[0] + (p[1]*ptAv)+(p[2]*ptAv*ptAv);
            hadPur = 1-purity;

            // Calculate PHe Reconstruction Eff from Xiaozhi embedding (fit)
            Float_t par[5] = {.26214, 4.75137, .526075, .0276979, .00054599};
            Float_t x = ptAv;
            Float_t eps = par[0]*TMath::Log(par[1]*x - par[2]*x*x + par[3]*x*x*x - par[4]*x*x*x*x);
            epsilon[ptbin] = eps;

            // Make stats label with purity and effeciency
            char statLabel[100];
            stat[ptbin] = new TPaveText(.4,.3,.85,.35,Form("NB NDC%i",ptbin));
            sprintf(statLabel,"Eff: %.2f; ePure:%.2f",epsilon[ptbin],purity);
            stat[ptbin]->InsertText(statLabel);
            stat[ptbin]->SetFillColor(kWhite);

            // Calculate Normalization for NPE delPhi
            Int_t inclNorm = mh1PtETracks[trig]->Integral(mh1PtETracks[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh1PtETracks[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);
            Int_t LSNorm   = projInvMassLS[ptbin][trig]->Integral();
            Int_t USNorm   = projInvMassUS[ptbin][trig]->Integral();
            hhNorm   = mh1PtHadTracks[trig]->Integral(mh1PtHadTracks[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh1PtHadTracks[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);
            HHScale = (Float_t)inclNorm/(Float_t)hhNorm; // so the purity comparison is 1:1
            Float_t Norm = (Float_t)inclNorm - (1/epsilon[ptbin] - 1.)*(Float_t)USNorm + (1/epsilon[ptbin])*(Float_t)LSNorm - HHScale*hadPur*hhNorm; // Use the number of "signal" counts
            histoNorms->SetBinContent(histoNorms->GetBin(trig+1,ptbin+1), Norm); // Find the bin and fill with the Normalization
            //cout << trig << "; " << ptbin << ": " << Norm << endl;

            Int_t counter = numPtBins*trig+ptbin;
            // DEBUG cout << counter << endl;
            c[trig]->cd(ptbin+1);
            // Assign to a single, simpler name for manip
            LSIM[ptbin][trig]  = projDelPhiPhotLS[ptbin][trig];
            USIM[ptbin][trig]  = projDelPhiPhotUS[ptbin][trig];
            USIMNP[ptbin][trig]= projDelPhiPhotUSNP[ptbin][trig];
            LSIMNP[ptbin][trig]= projDelPhiPhotLSNP[ptbin][trig];
            INCLNP[ptbin][trig]= projDelPhiInclNP[ptbin][trig];
            INCL[ptbin][trig]  = projDelPhiIncl[ptbin][trig];
            INCL2[ptbin][trig] = projDelPhiInclWt[ptbin][trig];
            LSIM2[ptbin][trig] = projDelPhiPhotLSWt[ptbin][trig];
            USIM2[ptbin][trig] = projDelPhiPhotUSWt[ptbin][trig];
            LSMM[ptbin][trig]  = projInvMassLS[ptbin][trig];
            USMM[ptbin][trig]  = projInvMassUS[ptbin][trig];
            HHDP[ptbin][trig]  = projDelPhiHadHad[ptbin][trig];
            NSPI[ptbin][trig]  = projnSigmaPion[ptbin][trig];
            // Rebin all as necessary
            Int_t RB = 1;
            LSIM[ptbin][trig]  -> Rebin(RB);
            USIM[ptbin][trig]  -> Rebin(RB);
            USIMNP[ptbin][trig]-> Rebin(RB);
            LSIMNP[ptbin][trig]-> Rebin(RB);
            INCLNP[ptbin][trig]-> Rebin(RB);
            INCL[ptbin][trig]  -> Rebin(RB);
            INCL2[ptbin][trig] -> Rebin(RB);
            LSIM2[ptbin][trig] -> Rebin(RB);
            USIM2[ptbin][trig] -> Rebin(RB);
            HHDP[ptbin][trig]  -> Rebin(RB);
            NSPI[ptbin][trig]  -> Rebin(10);

            // Actually manipulate histos and plot (photnic del Phi)

            USIMNP[ptbin][trig]->SetLineColor(kRed);
            USIMNP[ptbin][trig]->SetLineWidth(1);
            USIMNP[ptbin][trig]->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            USIMNP[ptbin][trig]->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                USIMNP[ptbin][trig]->SetTitle("Photonic Electron Reconstruction (No Partner Track)");
            else if (ptbin == 1 && trig !=3)
                USIMNP[ptbin][trig]->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                USIMNP[ptbin][trig]->SetTitle("MB");
            else
                USIMNP[ptbin][trig]->SetTitle("");
            USIMNP[ptbin][trig]->Draw("");

            LSIMNP[ptbin][trig]->SetLineColor(kBlack);
            LSIMNP[ptbin][trig]->SetLineWidth(1);
            LSIMNP[ptbin][trig]->Draw(" same");
            lbl[ptbin]->Draw("same");

            // Subtraction of (USNP-LS)
            TH1F *SUB = (TH1F*)USIMNP[ptbin][trig]->Clone(); //
            SUB->SetName("Subtraction");      // Create SUB as a clone of USIMNP
            SUB->Add(LSIMNP[ptbin][trig],-1);
            SUB->SetLineColor(kBlue);
            SUB->SetLineWidth(1);
            SUB->SetFillStyle(3001);
            SUB->SetFillColor(kBlue);
            SUB->Draw("same");
            lbl[ptbin]->Draw("same");
            TLegend* leg = new TLegend(0.2,0.73,0.55,0.85);
            leg->AddEntry(USIMNP[ptbin][trig],"Unlike Sign","lpe");
            leg->AddEntry(LSIM[ptbin][trig],"Like Sign", "lpe");
            leg->AddEntry(SUB,"Unlike - Like", "lpe");
            leg->Draw();

            // Plot different US (w/wo partner)
            USComp[trig]->cd(ptbin+1);
            TH1F *USwP = (TH1F*)USIM[ptbin][trig]->Clone();
            USwP->SetLineColor(kRed); //with partner tracks
            USwP->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            USwP->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                USwP->SetTitle("Photonic Unlike Sign Distributions");
            else if (ptbin == 1 && trig !=3)
                USwP->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                USwP->SetTitle("MB");
            else
                USwP->SetTitle("");
            USwP->Draw("");
            TH1F *USnP = (TH1F*)USIMNP[ptbin][trig]->Clone();
            USnP->SetLineColor(kBlack);
            USnP->Draw("same");
            lbl[ptbin]->Draw("same");
            TLegend* legUS = new TLegend(0.35,0.8,0.77,0.87);
            legUS->AddEntry(USwP,"With Partner Track","lpe");
            legUS->AddEntry(USnP,"Partner Track Removed", "lpe");
            legUS->Draw();

            // Plot different LS (w/wo partner)
            LSComp[trig]->cd(ptbin+1);
            TH1F *LSwP = (TH1F*)LSIM[ptbin][trig]->Clone();
            LSwP->SetLineColor(kRed); //with partner tracks
            LSwP->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            LSwP->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                LSwP->SetTitle("Photonic Like Sign Distributions");
            else if (ptbin == 1 && trig !=3)
                LSwP->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                LSwP->SetTitle("MB");
            else
                LSwP->SetTitle("");
            LSwP->Draw("");
            TH1F *LSnP = (TH1F*)LSIMNP[ptbin][trig]->Clone();
            LSnP->SetLineColor(kBlack);
            LSnP->Draw("same");
            lbl[ptbin]->Draw("same");
            TLegend* legLS = new TLegend(0.35,0.8,0.77,0.87);
            legLS->AddEntry(LSwP,"With Partner Track","lpe");
            legLS->AddEntry(LSnP,"Partner Track Removed", "lpe");
            legLS->Draw();

            // Plot different Incl (w/wo partner)
            InclComp[trig]->cd(ptbin+1);
            TH1F *InclwP = (TH1F*)INCL[ptbin][trig]->Clone();
            InclwP->SetLineColor(kRed); //with partner tracks
            InclwP->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            InclwP->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                InclwP->SetTitle("Inclusive Distributions");
            else if (ptbin == 1 && trig !=3)
                InclwP->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                InclwP->SetTitle("MB");
            else
                InclwP->SetTitle("");
            InclwP->Draw("");
            TH1F *InclnP = (TH1F*)INCLNP[ptbin][trig]->Clone();
            InclnP->SetLineColor(kBlack);
            InclnP->Draw("same");
            lbl[ptbin]->Draw("same");
            TLegend* legIncl = new TLegend(0.35,0.8,0.77,0.87);
            legIncl->AddEntry(InclwP,"Inclusive","lpe");
            legIncl->AddEntry(InclnP,"Semi-Inclusive", "lpe");
            legIncl->Draw();

            // Actually manipulate histos and plot (photonic InvMass)
            inMass[trig]->cd(ptbin+1);
            USMM[ptbin][trig]->SetLineColor(kRed);
            USMM[ptbin][trig]->SetLineWidth(1);
            USMM[ptbin][trig]->GetXaxis()->SetTitle("InvMass (GeV/c^{2})");
            USMM[ptbin][trig]->GetXaxis()->SetRangeUser(0,0.4);
            if(ptbin == 0)
                USMM[ptbin][trig]->SetTitle("Photonic Electron Reconstruction");
            else if (ptbin == 1 && trig !=3)
                USMM[ptbin][trig]->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                USMM[ptbin][trig]->SetTitle("MB");
            else
                USMM[ptbin][trig]->SetTitle("");
            USMM[ptbin][trig]->Draw("");

            LSMM[ptbin][trig]->SetLineColor(kBlack);
            LSMM[ptbin][trig]->SetLineWidth(1);
            LSMM[ptbin][trig]->Draw("same");
            lbl[ptbin]->Draw("same");

            // Subtraction of (US-LS)
            TH1F *SUB4 = (TH1F*)USMM[ptbin][trig]->Clone(); //
            SUB4->SetName("Subtraction");      // Create SUB as a clone of USIM
            SUB4->Add(LSMM[ptbin][trig],-1);
            SUB4->SetLineColor(kBlue);
            SUB4->SetLineWidth(1);
            SUB4->SetFillStyle(3001);
            SUB4->SetFillColor(kBlue);
            SUB4->Draw("same");
            TLegend* leg2 = new TLegend(0.45,0.6,0.85,0.75);
            leg2->AddEntry(USMM[ptbin][trig],"Unlike Sign","lpe");
            leg2->AddEntry(LSMM[ptbin][trig],"Like Sign", "lpe");
            leg2->AddEntry(SUB4,"Unlike - Like", "lpe");
            leg2->Draw();

            // Handle Inclusive Hists
            IN[trig]->cd(ptbin+1);
            INCL[ptbin][trig]->SetLineColor(kBlue);
            INCL[ptbin][trig]->SetLineWidth(1);
            INCL[ptbin][trig]->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            INCL[ptbin][trig]->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                INCL[ptbin][trig]->SetTitle("Inclusive Electrons");
            else if (ptbin == 1 && trig !=3)
                INCL[ptbin][trig]->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                INCL[ptbin][trig]->SetTitle("MB");
            else
                INCL[ptbin][trig]->SetTitle("");
            INCL[ptbin][trig]->Draw("");
            lbl[ptbin]->Draw("same");

            IN[trig]->Update();

            // Plot Had-Had correlations
            cHH[trig]->cd(ptbin+1);
            HHDP[ptbin][trig]->SetLineColor(kGreen+3);
            HHDP[ptbin][trig]->SetLineWidth(1);
            HHDP[ptbin][trig]->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            HHDP[ptbin][trig]->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            if(ptbin == 0)
                HHDP[ptbin][trig]->SetTitle("Hadron-Hadron Correlations");
            else if (ptbin == 1 && trig !=3)
                HHDP[ptbin][trig]->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                HHDP[ptbin][trig]->SetTitle("MB");
            else
                HHDP[ptbin][trig]->SetTitle("");
            HHDP[ptbin][trig]->Draw("");
            lbl[ptbin]->Draw("same");


            // Subtraction of Inclusive - (1/e - 1)US + (1/e)LS - (1-purity)HadHad
            result[trig]->cd(ptbin+1);
            TH1F *INCDP = (TH1F*)INCLNP[ptbin][trig]->Clone();
            TH1F *ULDP  = (TH1F*)USIMNP[ptbin][trig]->Clone();
            TH1F *LSDP  = (TH1F*)LSIMNP[ptbin][trig]->Clone();
            TH1F *HADDP = (TH1F*)HHDP[ptbin][trig]->Clone();
            INCDP->SetName(Form("scaleNPEhDelPhi_%i_%i",trig,ptbin));
            ULDP->Scale(1./epsilon[ptbin] - 1.); // Scale each distribution by associated factors
            LSDP->Scale(1./epsilon[ptbin]);
            HADDP->Scale(HHScale*hadPur);
            INCDP->Add(ULDP,-1);
            INCDP->Add(LSDP,1);
            INCDP->Add(HADDP,-1);
            TH1F *unscaleINCDP = (TH1F*)INCDP->Clone();   //
            unscaleINCDP->SetName(Form("NPEhDelPhi_%i_%i",trig,ptbin)); // Make a clone before normalization, to pass to fit program
            INCDP->Scale(1./((Double_t)Norm));//*INCDP->GetBinWidth(1)));
            INCDP->SetLineColor(kBlack);
            INCDP->SetLineWidth(1);
            INCDP->SetFillStyle(3001);
            INCDP->SetFillColor(kYellow);
            INCDP->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            INCDP->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            INCDP->GetYaxis()->SetTitle("1/N_{NPE} #upoint dN/d(#Delta)#phi");
            INCDP->GetYaxis()->SetTitleOffset(1.55);
            if(ptbin == 0)
                INCDP->SetTitle("#Delta#phi Non-Photonic Electrons and Hadrons");
            else if (ptbin == 1 && trig !=3)
                INCDP->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                INCDP->SetTitle("MB");
            else
                INCDP->SetTitle("");
            INCDP->Draw("");
            lbl[ptbin]->Draw("same");

            // Setup unscaled for fractionFit (don't normalize here!)
            unscaleINCDP->SetLineColor(kBlack);
            unscaleINCDP->SetLineWidth(1);
            unscaleINCDP->SetFillStyle(3001);
            unscaleINCDP->SetFillColor(kYellow);
            unscaleINCDP->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            unscaleINCDP->GetXaxis()->SetTitle("#Delta#phi_{eh}");
            unscaleINCDP->GetYaxis()->SetTitle("1/N_{NPE} #upoint dN/d(#Delta)#phi");
            unscaleINCDP->GetYaxis()->SetTitleOffset(1.55);
            if(ptbin == 0)
                unscaleINCDP->SetTitle("#Delta#phi Non-Photonic Electrons and Hadrons");
            else if (ptbin == 1 && trig !=3)
                unscaleINCDP->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                unscaleINCDP->SetTitle("MB");
            else
                unscaleINCDP->SetTitle("");

            // nSigmaPion QA
            nSigPi[trig]->cd(ptbin+1);
            NSPI[ptbin][trig]->SetLineColor(kGreen+3);
            NSPI[ptbin][trig]->SetLineWidth(1);
            NSPI[ptbin][trig]->GetXaxis()->SetTitle("n#sigma_{#pi}");
            NSPI[ptbin][trig]->GetXaxis()->SetRangeUser(-2.,2.);
            if(ptbin == 0)
                NSPI[ptbin][trig]->SetTitle("n Sigma Pion (n#sigma_{#pi})");
            else if (ptbin == 1 && trig !=3)
                NSPI[ptbin][trig]->SetTitle(Form("HT%i",trig));
            else if (trig == 3 && ptbin == 1)
                NSPI[ptbin][trig]->SetTitle("MB");
            else
                NSPI[ptbin][trig]->SetTitle("");
            NSPI[ptbin][trig]->Draw("");
            lbl[ptbin]->Draw("same");

            // All Distributions
            allDist[trig]->cd(ptbin+1);
            TH1F *INCLUSIVE = (TH1F*)INCLNP[ptbin][trig]->Clone();
            TH1F *UNLIKE  = (TH1F*)USIMNP[ptbin][trig]->Clone();
            TH1F *LIKE  = (TH1F*)LSIMNP[ptbin][trig]->Clone();
            TH1F *HADRON = (TH1F*)HHDP[ptbin][trig]->Clone();
            TH1F *USmLS  = (TH1F*)USIMNP[ptbin][trig]->Clone();
            USmLS->Add(LIKE,-1);
            USmLS->Scale(1./(USNorm-LSNorm));
            INCLUSIVE->Scale(1./inclNorm);
            UNLIKE->Scale(1./USNorm);
            LIKE->Scale(1./LSNorm);
            HADRON->Scale(1./hhNorm);
            INCLUSIVE->SetLineColor(7);
            LIKE->SetLineColor(kBlue);
            INCLUSIVE->GetYaxis()->SetRangeUser(0.01,2);
            gPad->SetLogy(1);
            INCLUSIVE->GetXaxis()->SetRangeUser(lowPhi,highPhi);
            INCLUSIVE->SetMarkerStyle(20);
            UNLIKE->SetMarkerStyle(21);
            LIKE->SetMarkerStyle(22);
            HADRON->SetMarkerStyle(23);
            USmLS->SetMarkerStyle(34);
            INCLUSIVE->SetMarkerColor(7);
            INCLUSIVE->SetMarkerSize(0.3);
            UNLIKE->SetMarkerSize(0.3);
            LIKE->SetMarkerSize(0.3);
            HADRON->SetMarkerSize(0.3);
            USmLS->SetMarkerSize(0.3);
            INCLUSIVE->SetMarkerColor(7);
            UNLIKE->SetMarkerColor(kRed);
            LIKE->SetMarkerColor(kBlue);
            HADRON->SetMarkerColor(kGreen+3);
            INCLUSIVE->Draw("");
            UNLIKE->Draw("same");
            LIKE->Draw("same");
            HADRON->Draw("same");
            USmLS->Draw("same");
            INCDP->Draw("same");
            lbl[ptbin]->Draw("same");
            stat[ptbin]->Draw("same");
            TLegend* legAll = new TLegend(0.45,0.11,0.85,0.3);
            legAll->AddEntry(INCLUSIVE,"Inclusive","lpe");
            legAll->AddEntry(UNLIKE,"Unlike Sign","lpe");
            legAll->AddEntry(LIKE,"Like Sign", "lpe");
            legAll->AddEntry(HADRON,"Hadron-Hadron", "lpe");
            legAll->AddEntry(USmLS,"Unlike-Like","lpe");
            legAll->AddEntry(INCDP,"NPE-h","lpe");
            legAll->Draw("same");

        }

        // Pileup Calculation (using just the hPtCut in the anaConst.h)
        /* mh3nTracksZdcx[trig]    = (TH3F*)f->Get(Form("mh3nTracksZdcx_%i_%i",trig,0));   // originally filled for various hpT cuts, use 0 which starts at hpt > 0.3
        mh3nTracksZdcxUS[trig]  = (TH3F*)f->Get(Form("mh3nTracksZdcxUS_%i_%i",trig,0)); // These histos are (epT,hpT,ZDCx), get nHadrons vs ZDCx
        mh3nTracksZdcxLS[trig]  = (TH3F*)f->Get(Form("mh3nTracksZdcxLS_%i_%i",trig,0));
        mh3nTracksZdcxHad[trig] = (TH3F*)f->Get(Form("mh3nTracksZdcxHad_%i_%i",trig,0));
        mh3nTracksZdcx[trig]->Sumw2(); mh3nTracksZdcxUS[trig]->Sumw2(); mh3nTracksZdcxLS[trig]->Sumw2();  mh3nTracksZdcxHad[trig]->Sumw2();

        mh2PtEZdcx[trig]       = (TH2F*)f->Get(Form("mh2PtEZdcx_%i",trig));            // Filled (epT,ZDCx). Get nTrigs vs ZDCx
        mh2PtEZdcxUS[trig]     = (TH2F*)f->Get(Form("mh2PtEZdcxUS_%i",trig));
        mh2PtEZdcxLS[trig]     = (TH2F*)f->Get(Form("mh2PtEZdcxLS_%i",trig));
        mh2PtEZdcxHad[trig]     = (TH2F*)f->Get(Form("mh2PtEZdcxHad_%i",trig));
        mh2PtEZdcx[trig]->Sumw2(); mh2PtEZdcxUS[trig]->Sumw2(); mh2PtEZdcxLS[trig]->Sumw2(); mh2PtEZdcxHad[trig]->Sumw2();

        for(Int_t ptbin=0; ptbin<numPtBins; ptbin++)// cut in to trigger pt slices
          {
        projZDCxHad[ptbin][trig] = mh3nTracksZdcx[trig]->ProjectionZ(Form("projZDCxHad_%i_%i",ptbin,trig),mh3nTracksZdcx[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh3nTracksZdcx[trig]->GetXaxis()->FindBin(highpt[ptbin])-1,mh3nTracksZdcx[trig]->GetYaxis()->FindBin(hptCut),mh3nTracksZdcx[trig]->GetYaxis()->FindBin(hptMax));
        projZDCxHadUS[ptbin][trig] = mh3nTracksZdcxUS[trig]->ProjectionZ(Form("projZDCxHadUS_%i_%i",ptbin,trig),mh3nTracksZdcxUS[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh3nTracksZdcxUS[trig]->GetXaxis()->FindBin(highpt[ptbin])-1,mh3nTracksZdcxUS[trig]->GetYaxis()->FindBin(hptCut),mh3nTracksZdcxUS[trig]->GetYaxis()->FindBin(hptMax));
        projZDCxHadLS[ptbin][trig] = mh3nTracksZdcxLS[trig]->ProjectionZ(Form("projZDCxHadLS_%i_%i",ptbin,trig),mh3nTracksZdcxLS[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh3nTracksZdcxLS[trig]->GetXaxis()->FindBin(highpt[ptbin])-1,mh3nTracksZdcxLS[trig]->GetYaxis()->FindBin(hptCut),mh3nTracksZdcxLS[trig]->GetYaxis()->FindBin(hptMax));
        projZDCxHadHad[ptbin][trig] = mh3nTracksZdcxHad[trig]->ProjectionZ(Form("projZDCxHadHad_%i_%i",ptbin,trig),mh3nTracksZdcxHad[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh3nTracksZdcxHad[trig]->GetXaxis()->FindBin(highpt[ptbin])-1,mh3nTracksZdcxHad[trig]->GetYaxis()->FindBin(hptCut),mh3nTracksZdcxHad[trig]->GetYaxis()->FindBin(hptMax));

        projZDCxTrig[ptbin][trig] = mh2PtEZdcx[trig]->ProjectionY(Form("projZDCxTrig_%i_%i",ptbin,trig),mh2PtEZdcx[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh2PtEZdcx[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);
        projZDCxTrigUS[ptbin][trig] = mh2PtEZdcxUS[trig]->ProjectionY(Form("projZDCxTrigUS_%i_%i",ptbin,trig),mh2PtEZdcxUS[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh2PtEZdcxUS[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);
        projZDCxTrigLS[ptbin][trig] = mh2PtEZdcxLS[trig]->ProjectionY(Form("projZDCxTrigLS_%i_%i",ptbin,trig),mh2PtEZdcxLS[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh2PtEZdcxLS[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);
        projZDCxTrigHad[ptbin][trig] = mh2PtEZdcxHad[trig]->ProjectionY(Form("projZDCxTrigHad_%i_%i",ptbin,trig),mh2PtEZdcxHad[trig]->GetXaxis()->FindBin(lowpt[ptbin]),mh2PtEZdcxHad[trig]->GetXaxis()->FindBin(highpt[ptbin])-1);

        // Get Total number of hadrons in pileup (first scale each distribution by efficiency, just like data)
        projZDCxHadUS[ptbin][trig] -> Scale(1./epsilon[ptbin] - 1.);
        projZDCxHadLS[ptbin][trig] -> Scale(1./epsilon[ptbin]);
        projZDCxHadHad[ptbin][trig]-> Scale(HHScale*hadPur);
        projZDCxHad[ptbin][trig] -> Add(projZDCxHadUS[ptbin][trig], -1.);
        projZDCxHad[ptbin][trig] -> Add(projZDCxHadLS[ptbin][trig], 1.);
        projZDCxHad[ptbin][trig] -> Add(projZDCxHadHad[ptbin][trig], -1.);

        // Get Total number of trigs in pileup (first scale each distribution by efficiency, just like data)
        projZDCxTrigUS[ptbin][trig] -> Scale(1./epsilon[ptbin] - 1.);
        projZDCxTrigLS[ptbin][trig] -> Scale(1./epsilon[ptbin]);
        projZDCxTrigHad[ptbin][trig]-> Scale(HHScale*hadPur);
        projZDCxTrig[ptbin][trig] -> Add(projZDCxTrigUS[ptbin][trig], -1.);
        projZDCxTrig[ptbin][trig] -> Add(projZDCxTrigLS[ptbin][trig], 1.);
        projZDCxTrig[ptbin][trig] -> Add(projZDCxTrigHad[ptbin][trig], -1.);

        // Actually do the division of total hadrons/total trigs
        projZDCxHad[ptbin][trig]->Divide(projZDCxTrig[ptbin][trig]);

        // plot projections
        pile[trig]->cd(ptbin+1);
        projZDCxHad[ptbin][trig]->SetLineColor(kBlack);
        projZDCxHad[ptbin][trig]->GetXaxis()->SetTitle("ZDCx");
        projZDCxHad[ptbin][trig]->GetYaxis()->SetTitle("<nHadrons>/<nTracks>");
        projZDCxHad[ptbin][trig]->GetYaxis()->SetRangeUser(0,20);
        //
        gStyle->SetOptFit(1111);
        projZDCxHad[ptbin][trig]->Fit("pol1");
        projZDCxHad[ptbin][trig]->GetFunction("pol1")->SetLineColor(kRed);
        TPaveStats *st = ((TPaveStats*)(projZDCxHad[ptbin][trig]->GetListOfFunctions()->FindObject("stats")));
        if (st) {
          st->SetTextColor(projZDCxHad[ptbin][trig]->GetFunction("pol1")->GetLineColor());
          st->SetX1NDC(0.64); st->SetX2NDC(0.99);
          st->SetY1NDC(0.4); st->SetY2NDC(0.6);
        }
        pile[trig]->Modified();pile[trig]->Update();
        projZDCxHad[ptbin][trig]->Draw("");

        // Get Fit information and store to use in corrections
        TF1 *fitResult = projZDCxHad[ptbin][trig]->GetFunction("pol1");
        pu[0][ptbin][trig] = fitResult->GetParameter(0);
        pu[1][ptbin][trig] = fitResult->GetParameter(1);
           	cout << trig << " " << ptbin << ": " << pu[0][ptbin][trig] << " " << pu[1][ptbin][trig] << endl;
        }*/
    }

    // Draw on "SinglePlot" canvas for saving single plots from grid
    TPad* pNew = (TPad*)result[2]->GetPad(4)->Clone();
    singlePlot->cd();
    pNew->ResizePad();
    pNew->Draw();

    // Make PDF with output canvases
    if(makePDF)
    {
        //Set front page
        TCanvas* fp = new TCanvas("fp","Front Page",100,0,1000,900);
        fp->cd();
        TBox *bLabel = new TBox(0.01, 0.88, 0.99, 0.99);
        bLabel->SetFillColor(38);
        bLabel->Draw();
        TLatex tl;
        tl.SetNDC();
        tl.SetTextColor(kWhite);
        tl.SetTextSize(0.033);
        char tlName[100];
        char tlName2[100];

        TString titlename = FileName;
        int found = titlename.Last('/');
        if(found >= 0) {
            titlename.Replace(0, found+1, "");
        }
        sprintf(tlName, "RUN 12 pp 200 GeV NPE-h    #Delta#phi Analysis");
        tl.SetTextSize(0.05);
        tl.SetTextColor(kWhite);
        tl.DrawLatex(0.05, 0.92,tlName);

        TBox *bFoot = new TBox(0.01, 0.01, 0.99, 0.12);
        bFoot->SetFillColor(38);
        bFoot->Draw();
        tl.SetTextColor(kWhite);
        tl.SetTextSize(0.05);
        tl.DrawLatex(0.05, 0.05, (new TDatime())->AsString());
        tl.SetTextColor(kBlack);
        tl.SetTextSize(0.03);
        tl.DrawLatex(0.1, 0.14, titlename);
        sprintf(tlName,"eID: -1 < n  #sigma_{e TPC} < 3;  #left|gDCA #right| < 1 cm; 0.3 < p/E < 1.5;");
        tl.DrawLatex(0.1, 0.8,tlName);
        sprintf(tlName,"       nHitsFit > 20; nHits   #frac{dE}{dx} > 15; nHitFit/Max > 0.52;    #left|#eta#right| < 0.7;");
        tl.DrawLatex(0.1, 0.75,tlName);
        sprintf(tlName,"       n #phi > 1; n #eta > 1;  #left|dZ#right| < 3 cm;  #left|d#phi#right| < 0.015;");
        tl.DrawLatex(0.1, 0.7,tlName);
        sprintf(tlName,"hID: p_{T} > 0.5;  #left|#eta#right| < 1; nHitsFit > 15; nHits   #frac{dE}{dx} > 10; DCA < 1 cm;");
        tl.DrawLatex(0.1, 0.6,tlName);
        sprintf(tlName,"Event:  #left|V_{z}#right| < 35 cm;");
        tl.DrawLatex(0.1, 0.5,tlName);
        sprintf(tlName,"Triggers:  BHT0; BHT2;");
        tl.DrawLatex(0.1, 0.4,tlName);


        // Place canvases in order
        TCanvas* temp = new TCanvas();
        sprintf(name, "%s.pdf[", FileName);
        temp->Print(name);
        sprintf(name, "%s.pdf", FileName);
        temp = fp; // print front page
        temp->Print(name);
        temp = mixedC;
        temp->Print(name);
        temp = mixedCbinEta;
        temp->Print(name);
        temp = mixedCbinPhi;
        temp->Print(name);
        temp = mixedCbin;
        temp->Print(name);
        for(Int_t ii=0; ii<numTrigs; ii++)
        {
            if(!fPaintAll && (ii==1 || ii==3))
                continue;
            temp = IN[ii];
            temp->Print(name);
            temp = c[ii];
            temp->Print(name);
            temp = cHH[ii];
            temp->Print(name);
            temp = result[ii];
            temp->Print(name);
            temp = pile[ii];
            temp->Print(name);
            /*temp = inMass[ii];
            temp->Print(name);
            temp = USComp[ii];
            temp->Print(name);
            temp = LSComp[ii];
            temp->Print(name);
            temp = InclComp[ii];
            temp->Print(name);*/
            temp = nSigPi[ii];
            temp->Print(name);
            temp = allDist[ii];
            temp->Print(name);

        }
        sprintf(name, "%s.pdf]", FileName);
        temp->Print(name);
    }

    if(makeROOT)
    {
        file->Write();
        file->Close();
    }
}
コード例 #19
0
ファイル: extractPtResolution.C プロジェクト: ktf/AliPhysics
//___________________________________________________________________
Int_t extractPtResolution(TString pathNameData, TString listName,
                          Int_t chargeMode /*kNegCharge = -1, kAllCharged = 0, kPosCharge = 1*/,
                          Double_t lowerCentrality /*= -2*/, Double_t upperCentrality /*= -2*/,
                          Double_t lowerJetPt /*= -1*/ , Double_t upperJetPt/* = -1*/)
{
  if (listName == "") {
    listName = pathNameData;
    listName.Replace(0, listName.Last('/') + 1, "");
    listName.ReplaceAll(".root", "");
  }
  
  TString pathData = pathNameData;
  pathData.Replace(pathData.Last('/'), pathData.Length(), "");
  
  TH1D* hPtResolutionFit[AliPID::kSPECIES] = {0x0, };
  TH2D* hPtResolution[AliPID::kSPECIES] = {0x0, };
  THnSparse* hPtResolutionRaw[AliPID::kSPECIES] = {0x0, };

  TFile* fileData = TFile::Open(pathNameData.Data());
  if (!fileData) {
    printf("Failed to open data file \"%s\"\n", pathNameData.Data());
    return -1;
  }
  
  TObjArray* histList = (TObjArray*)(fileData->Get(listName.Data()));
  
  if (!histList) {
    printf("Failed to load list!\n");
    return -1;
  }
  
  Double_t actualLowerCentrality = -2;
  Double_t actualUpperCentrality = -2;
  
  Double_t actualLowerJetPt = -1.;
  Double_t actualUpperJetPt = -1.;
  
  Bool_t restrictJetPtAxis = (lowerJetPt >= 0 && upperJetPt >= 0);
  const Bool_t restrictCentrality = ((lowerCentrality >= -1) && (upperCentrality >= -1));
  
  for (Int_t species = 0; species < AliPID::kSPECIES; species++) {
    const TString sparseName = Form("fPtResolution_%s", AliPID::ParticleShortName(species));
    hPtResolutionRaw[species] = (THnSparse*)histList->FindObject(sparseName.Data());
    
    if (!hPtResolutionRaw[species]) {
      printf("Failed to load THnSparse for %s: %s!\n", AliPID::ParticleShortName(species), sparseName.Data());
      return -1;
    }
    
    // Set proper errors, if not yet calculated
    if (!hPtResolutionRaw[species]->GetCalculateErrors()) {
      std::cout << "Re-calculating errors of " << hPtResolutionRaw[species]->GetName() << "..." << std::endl;
      
      hPtResolutionRaw[species]->Sumw2();
      
      Long64_t nBinsPtResolutionRaw = hPtResolutionRaw[species]->GetNbins();
      Double_t binContent = 0;
      for (Long64_t bin = 0; bin < nBinsPtResolutionRaw; bin++) {
        binContent = hPtResolutionRaw[species]->GetBinContent(bin);
        hPtResolutionRaw[species]->SetBinError(bin, TMath::Sqrt(binContent));
      }
    }
    
    // Integral(lowerCentBinLimit, uppCentBinLimit) will not be restricted if these values are kept
    const Int_t lowerCentralityBinLimit = restrictCentrality ? hPtResolutionRaw[species]->GetAxis(kPtResCentrality)->FindBin(lowerCentrality + 0.001) 
                                                                    : -1;
    const Int_t upperCentralityBinLimit = restrictCentrality ? hPtResolutionRaw[species]->GetAxis(kPtResCentrality)->FindBin(upperCentrality - 0.001) 
                                                                    : -2;
    
    
    if (restrictCentrality) {
      actualLowerCentrality = hPtResolutionRaw[species]->GetAxis(kPtResCentrality)->GetBinLowEdge(lowerCentralityBinLimit);
      actualUpperCentrality = hPtResolutionRaw[species]->GetAxis(kPtResCentrality)->GetBinLowEdge(upperCentralityBinLimit);
      
      hPtResolutionRaw[species]->GetAxis(kPtResCentrality)->SetRange(lowerCentralityBinLimit, upperCentralityBinLimit);
    }
    
    const Bool_t restrictCharge = (chargeMode != kAllCharged);
    
    Int_t lowerChargeBinLimit = -1;
    Int_t upperChargeBinLimit = -2;
      
    if (restrictCharge) {
      // Add subtract a very small number to avoid problems with values right on the border between to bins
      if (chargeMode == kNegCharge) {
        lowerChargeBinLimit = hPtResolutionRaw[species]->GetAxis(kPtResCharge)->FindBin(-1. + 0.001);
        upperChargeBinLimit = hPtResolutionRaw[species]->GetAxis(kPtResCharge)->FindBin(0. - 0.001);
      }
      else if (chargeMode == kPosCharge) {
        lowerChargeBinLimit = hPtResolutionRaw[species]->GetAxis(kPtResCharge)->FindBin(0. + 0.001);
        upperChargeBinLimit = hPtResolutionRaw[species]->GetAxis(kPtResCharge)->FindBin(1. - 0.001);
      }
      
      // Check if the values look reasonable
      if (lowerChargeBinLimit <= upperChargeBinLimit && lowerChargeBinLimit >= 1
          && upperChargeBinLimit <= hPtResolutionRaw[species]->GetAxis(kPtResCharge)->GetNbins()) {
        // OK
      }
      else {
        std::cout << std::endl;
        std::cout << "Requested charge range out of limits or upper and lower limit are switched!" << std::endl;
        return -1;
      }
      
      hPtResolutionRaw[species]->GetAxis(kPtResCharge)->SetRange(lowerChargeBinLimit, upperChargeBinLimit);
    }
    
    // If desired, restrict jetPt axis
    Int_t lowerJetPtBinLimit = -1;
    Int_t upperJetPtBinLimit = -1;
    
    if (restrictJetPtAxis) {
      // Add subtract a very small number to avoid problems with values right on the border between to bins
      lowerJetPtBinLimit = hPtResolutionRaw[species]->GetAxis(kPtResJetPt)->FindBin(lowerJetPt + 0.001);
      upperJetPtBinLimit = hPtResolutionRaw[species]->GetAxis(kPtResJetPt)->FindBin(upperJetPt - 0.001);
      
      // Check if the values look reasonable
      if (lowerJetPtBinLimit <= upperJetPtBinLimit && lowerJetPtBinLimit >= 1 &&
          upperJetPtBinLimit <= hPtResolutionRaw[species]->GetAxis(kPtResJetPt)->GetNbins()) {
        actualLowerJetPt = hPtResolutionRaw[species]->GetAxis(kPtResJetPt)->GetBinLowEdge(lowerJetPtBinLimit);
        actualUpperJetPt = hPtResolutionRaw[species]->GetAxis(kPtResJetPt)->GetBinUpEdge(upperJetPtBinLimit);

        restrictJetPtAxis = kTRUE;
      }
      else {
        std::cout << std::endl;
        std::cout << "Requested jet pT range out of limits or upper and lower limit are switched!" << std::endl;
        return -1;
      }
    }
    
    std::cout << "jet pT: ";
    if (restrictJetPtAxis) {
      std::cout << actualLowerJetPt << " - " << actualUpperJetPt << std::endl;
      hPtResolutionRaw[species]->GetAxis(kPtResJetPt)->SetRange(lowerJetPtBinLimit, upperJetPtBinLimit);
    }
    else {
      std::cout << "All" << std::endl;
    }
    
    hPtResolution[species] = hPtResolutionRaw[species]->Projection(kPtResGenPt, kPtResRecPt, "e");
    hPtResolution[species]->SetName(Form("hPtResolution_%s", AliPID::ParticleShortName(species)));
    hPtResolution[species]->SetTitle(Form("%s", AliPID::ParticleLatexName(species)));
    hPtResolution[species]->SetStats(kFALSE);
    hPtResolution[species]->SetLineColor(getLineColorAliPID(species));
    hPtResolution[species]->SetMarkerColor(getLineColorAliPID(species));
    
    normaliseHist(hPtResolution[species]);
    
    TObjArray aSlices;
    hPtResolution[species]->FitSlicesY(0, 0, -1, 0, "QNR", &aSlices);
    TH1D* hMean = (TH1D*)(aSlices.At(1));
    TH1D* hSigma = (TH1D*)(aSlices.At(2));
    
    hPtResolutionFit[species] = new TH1D(*hSigma);
    hPtResolutionFit[species]->SetName(Form("hPtResolutionFit_%s", AliPID::ParticleShortName(species)));
    hPtResolutionFit[species]->SetTitle(Form("%s", AliPID::ParticleLatexName(species)));
    hPtResolutionFit[species]->SetLineColor(getLineColorAliPID(species));
    hPtResolutionFit[species]->SetMarkerColor(getLineColorAliPID(species));
    
    hPtResolutionFit[species]->Divide(hSigma, hMean);
  }
  
  
  
  // Save results to file
  TString chargeString = "";
  if (chargeMode == kPosCharge)
    chargeString = "_posCharge";
  else if (chargeMode == kNegCharge)
    chargeString = "_negCharge";
  
  TString saveFileName = pathNameData;
  saveFileName.Replace(0, pathNameData.Last('/') + 1, "");
  
  TString savePath = pathNameData;
  savePath.ReplaceAll(Form("/%s", saveFileName.Data()), "");
  
  saveFileName.Prepend("output_extractedPTResolution_");
  TString centralityString = restrictCentrality ? Form("_centrality_%.0f_%.0f.root", actualLowerCentrality,
                                                       actualUpperCentrality)
                                                    : "_centrality_all";
  TString jetPtString = restrictJetPtAxis ? Form("_jetPt_%.0f_%.0f.root", actualLowerJetPt, actualUpperJetPt)
                                          : "";  
  saveFileName.ReplaceAll(".root", Form("%s%s%s.root", centralityString.Data(), jetPtString.Data(), chargeString.Data()));
  
  TString saveFilePathName = Form("%s/%s", savePath.Data(), saveFileName.Data());
  TFile* saveFile = TFile::Open(saveFilePathName.Data(), "RECREATE");
  
  if (!saveFile) {
    printf("Failed to save results to file \"%s\"!\n", saveFilePathName.Data());
    return -1;
  }
  
  saveFile->cd();
  
  for (Int_t species = 0; species < AliPID::kSPECIES; species++) {
    if (hPtResolution[species])
      hPtResolution[species]->Write();
    
    if (hPtResolutionFit[species])
      hPtResolutionFit[species]->Write();
  }
  
  TNamed* settings = new TNamed(
      Form("Settings: Data file \"%s\", lowerCentrality %.3f, upperCentrality %.3f, lowerJetPt %.1f, upperJetPt %.1f\n",
           pathNameData.Data(), lowerCentrality, upperCentrality, lowerJetPt, upperJetPt), "");
  settings->Write();
  
  saveFile->Close();
  
  
  return 0;
}
コード例 #20
0
ファイル: bfields.C プロジェクト: schuetzepaul/Testbeam
int bfields(const char* runlistinput, const char* bdirinput){
    
    cout << "Wohoo -.- Ganz grosser Sport" << endl;

    TString runlistname;
    runlistname += gSystem->pwd();
    if( !runlistname.EndsWith("/") ) runlistname += "/";
    runlistname += runlistinput;

    cout << "Your runlist is at " << runlistname << endl;

    // Find the right folder.
    TString foldername;
    foldername += runlistname;

    foldername.Remove(foldername.Last('/')+1, foldername.Length()-foldername.Last('/')-1);

    // Some Parameters

    double bfield;
    enum direction {x,y};
    direction bdir;

    if(strcmp(bdirinput,"x")){
        bdir = x;
    }else if(strcmp(bdirinput,"y")){
        bdir = y;
    }else{
        cout << "Usage: bfields(runlist, Bdirection(x,y))" << endl;
        cout << "You did: bfields(" << runlistinput << ", " << bdirinput <<")" << endl;
        return 0;
    }




    ifstream runlist;
    runlist.open(runlistname);

    vector<double> bfieldvaluesX;
    vector<double> bfieldvaluesY;
    vector<int> runnrvalues;
    string str;
    double strval;
    string line;

    int counter=0;

    if(bdir)
    int colBfields = 5;

    while (!runlist.eof()) {

//        runlist >> str;
        getline(runlist, line);

        //cout << line << endl;

        counter=0;

        while(line.length()>0){

            stringstream linestream(line);
            linestream >> str;

            line.erase(0,str.length()+1);

//            cout << str << endl;

            if(counter==4){
                try{
                    bfieldvaluesX.push_back(stod(str, NULL));
                }catch(std::exception& e)
                {
//                    cout << "Could not convert string to double: " << str << endl;
                }
//                if(bfieldvalues.size()>0)cout << "Bfield is " << bfieldvalues.at(bfieldvalues.size()-1) << endl;
            }else if(counter==5){
                try{
                    bfieldvaluesY.push_back(stod(str, NULL));
                }catch(std::exception& e)
                {
//                    cout << "Could not convert string to double: " << str << endl;
                }
            }else if(counter==0){
                try{
                    runnrvalues.push_back(stoi(str, NULL));
                }catch(std::exception& e)
                {
//                    cout << "Could not convert string to int: " << str << endl;
                }
            }
            //cout << counter << ". " << str << endl;

            counter++;
        }

    }

    runlist.close();
    

    // Now go through the runfiles.

    unsigned int nruns;
    nruns = runnrvalues.size();

    int runnr;

    cout << "Found " << nruns << " runs. Reading them..." << endl;


    // Create Histograms and plots here




    for(unsigned int i=0; i<nruns; i++){

        runnr = runnrvalues.at(i);

        TString filename;
        filename+=foldername;
        char buffer[100];
        sprintf(buffer, "pixelav-r%04i.out.root", runnr);

        filename+=buffer;

        TFile *source = new TFile(filename);


        // Open Histograms from Evrd here and fill values to your histos


        TH1D* hncol = (TH1D*)gDirectory->Get("hncol");
        hncol->SetName("hncol");


        TH1D* hnrow = (TH1D*)gDirectory->Get("hnrow");
        hnrow->SetName("hnrow");




    }
    
//    TCanvas* can = new TCanvas("Momentum vs. current", "Momentum vs. current", 800,600);
//    GcurrmomMeas->SetTitle("Momentum vs. current");
//    GcurrmomMeas->GetXaxis()->SetTitle("Current [A]");
//    GcurrmomMeas->GetYaxis()->SetRangeUser(0,6.6);
//    GcurrmomMeas->GetYaxis()->SetTitle("Momentum [GeV]");
//    GcurrmomMeas->SetMarkerStyle(5);
//    GcurrmomMeas->SetMarkerColor(kBlue);
//    GcurrmomTab->SetMarkerStyle(5);
//    GcurrmomTab->SetMarkerColor(kRed);
    
//    // Linear fit:
//    TF1* linfit = new TF1("Linear Fit","[0]+[1]*x",0,200);
//    linfit->SetLineColor(kBlack);
//    linfit->SetLineWidth(1);
//    GcurrmomMeas->Fit(linfit);
    
    
//    //Legend:
//    TLegend* leg = new TLegend(0.13,0.78,0.43,0.93);
//    //leg->SetBorderSize(0);
//    //leg->SetTextSize(0.07);
//    //leg->SetFillColor(10);
//    //leg->SetLineColor(1);
//    leg->AddEntry(GcurrmomMeas,"Measurement","pe");
//    leg->AddEntry(GcurrmomTab,"Table at TB21","p");
//    leg->AddEntry(linfit,"Linear Fit to measurement","l");
    
    
//    GcurrmomMeas->DrawClone("APE");
//    GcurrmomTab->DrawClone("SameP");
//    leg->DrawClone("Same");
    
    
//    //linfit->DrawClone("Same");
    
//    can->SaveAs("MomCurr.pdf");
//    can->Close();
    
//    resultcalc(val0, val1, val2, val3, val4, val5, GcurrmomTab);
    
//    //deflection(p,I,thetaout, xout, thetain, xin, dx);
    
    
    
    return 0;
        
}
コード例 #21
0
int DiagnosisMacro(int Nbins = 10, int Nsigma = 10, int CPUused = 1, TString Filename = "FIT_DATA_Psi2SJpsi_PPPrompt_Bkg_SecondOrderChebychev_pt65300_rap016_cent0200_262620_263757.root", TString Outputdir = "./")
//Nbins: Number of points for which to calculate profile likelihood. Time required is about (1/CPU) minutes per point per parameter. 0 means do plain likelihood only
//Nsigma: The range in which the scan is performed (value-Nsigma*sigma, value+Nsigma*sigma)
//CPUused: anything larger than 1 causes weird fit results on my laptop, runs fine on lxplus with more (16)

{
    // R e a d   w o r k s p a c e   f r o m   f i l e
    // -----------------------------------------------
    // Open input file with workspace

    //Filename = "FIT_DATA_Psi2SJpsi_PP_Jpsi_DoubleCrystalBall_Psi2S_DoubleCrystalBall_Bkg_Chebychev2_pt6590_rap016_cent0200.root";
    //Filename = "FIT_DATA_Psi2SJpsi_PbPb_Jpsi_DoubleCrystalBall_Psi2S_DoubleCrystalBall_Bkg_Chebychev1_pt6590_rap016_cent0200.root";

    TFile *f = new TFile(Filename);
    // Retrieve workspace from file
    RooWorkspace* w = (RooWorkspace*)f->Get("workspace");

    // Retrieve x,model and data from workspace
    RooRealVar* x = w->var("invMass");
    RooAbsPdf* model = w->pdf("simPdf_syst");
    if (model == 0) {
        model = w->pdf("simPdf");
    }
    if (model == 0) {
        model = w->pdf("pdfMASS_Tot_PP");
    }
    if (model == 0) {
        model = w->pdf("pdfMASS_Tot_PbPb");
    }
    if (model == 0) {
        cout << "[ERROR] pdf failed to load from the workspace" << endl;
        return false;
    }

    RooAbsData* data = w->data("dOS_DATA");
    if (data == 0) {
        data = w->data("dOS_DATA_PP");
    }
    if (data == 0) {
        data = w->data("dOS_DATA_PbPb");
    }
    if (data == 0) {
        cout << "[ERROR] data failed to load from the workspace" << endl;
        return false;
    }

    // Print structure of composite p.d.f.
    model->Print("t");

    /*
    // P l o t   m o d e l
    // ---------------------------------------------------------
    // Plot data and PDF overlaid
    RooPlot* xframe = x->frame(Title("J/psi Model and Data"));
    data->plotOn(xframe);
    model->plotOn(xframe);

    // Draw the frame on the canvas
    TCanvas* c2 = new TCanvas("PlotModel", "PlotModel", 1000, 1000);
    gPad->SetLeftMargin(0.15);
    xframe->GetYaxis()->SetTitleOffset(2.0);
    xframe->Draw();//*/

    ///// Check parameters

    RooArgSet* paramSet1 = model->getDependents(data);
    paramSet1->Print("v");  // Just check
    RooArgSet* paramSet2 = model->getParameters(data);
    paramSet2->Print("v");
    int Nparams = paramSet2->getSize();
    cout << "Number of parameters: " << Nparams<<endl<<endl;


    // C o n s t r u c t   p l a i n   l i k e l i h o o d
    // ---------------------------------------------------
    // Construct unbinned likelihood
    RooAbsReal* nll = model->createNLL(*data, NumCPU(CPUused));
    // Minimize likelihood w.r.t all parameters before making plots
    RooMinuit(*nll).migrad();


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

    ///////////////////   L O O P   O V E R   P A R A M E T E R S

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

    /// Set up loop over parameters
    TString ParamName;
    double ParamValue;
    double ParamError;
    double ParamLimitLow;
    double ParamLimitHigh;
    double FitRangeLow;
    double FitRangeHigh;
    RooRealVar* vParam;
    int counter = 0;

    // Loop start
    TIterator* iter = paramSet2->createIterator();
    TObject* var = iter->Next();
    while (var != 0) {
        counter++;
        ParamName = var->GetName();
        vParam = w->var(ParamName);
        ParamValue = vParam->getVal();
        ParamError = vParam->getError();
        ParamLimitLow = vParam->getMin();
        ParamLimitHigh = vParam->getMax();
        cout << ParamName << " has value " << ParamValue << " with error: " << ParamError << " and limits: " << ParamLimitLow << " to " << ParamLimitHigh << endl << endl;

        if (ParamError == 0) {  //Skipping fixed parameters
            cout << "Parameter was fixed, skipping its fitting" << endl;
            cout << endl << "DONE WITH " << counter << " PARAMETER OUT OF " << Nparams << endl << endl;
            var = iter->Next();
            continue;
        }

        // determining fit range: Nsigma sigma on each side unless it would be outside of parameter limits
        if ((ParamValue - Nsigma * ParamError) > ParamLimitLow) {
            FitRangeLow = (ParamValue - Nsigma * ParamError);
        }
        else {
            FitRangeLow = ParamLimitLow;
        }

        if ((ParamValue + Nsigma * ParamError) < ParamLimitHigh) {
            FitRangeHigh = (ParamValue + Nsigma * ParamError);
        }
        else {
            FitRangeHigh = ParamLimitHigh;
        }


        // P l o t    p l a i n   l i k e l i h o o d   a n d   C o n s t r u c t   p r o f i l e   l i k e l i h o o d
        // ---------------------------------------------------
        RooPlot* frame1;
        RooAbsReal* pll=NULL;

        if (Nbins != 0) {
            frame1 = vParam->frame(Bins(Nbins), Range(FitRangeLow, FitRangeHigh), Title(TString::Format("LL and profileLL in %s", ParamName.Data())));
            nll->plotOn(frame1, ShiftToZero());

            pll = nll->createProfile(*vParam);
            // Plot the profile likelihood
            pll->plotOn(frame1, LineColor(kRed), RooFit::Precision(-1));
        }
        else { //Skip profile likelihood
            frame1 = vParam->frame(Bins(10), Range(FitRangeLow, FitRangeHigh), Title(TString::Format("LL and profileLL in %s", ParamName.Data())));
            nll->plotOn(frame1, ShiftToZero());
        }

        // D r a w   a n d   s a v e   p l o t s
        // -----------------------------------------------------------------------

        // Adjust frame maximum for visual clarity
        frame1->SetMinimum(0);
        frame1->SetMaximum(20);

        TCanvas* c = new TCanvas("CLikelihoodResult", "CLikelihoodResult", 800, 600);
        c->cd(1);
        gPad->SetLeftMargin(0.15);
        frame1->GetYaxis()->SetTitleOffset(1.4);
        frame1->Draw();
        TLegend* leg = new TLegend(0.70, 0.70, 0.95, 0.88, "");
        leg->SetFillColor(kWhite);
        leg->SetBorderSize(0);
        leg->SetTextSize(0.035);
        TLegendEntry *le1 = leg->AddEntry(nll, "Plain likelihood", "l");
        le1->SetLineColor(kBlue);
        le1->SetLineWidth(3);
        TLegendEntry *le2 = leg->AddEntry(pll, "Profile likelihood", "l");
        le2->SetLineColor(kRed);
        le2->SetLineWidth(3);
        leg->Draw("same");

        //Save plot
        TString StrippedName = TString(Filename(Filename.Last('/')+1,Filename.Length()));
        StrippedName = StrippedName.ReplaceAll(".root","");
        cout << StrippedName << endl;
        gSystem->mkdir(Form("%s/root/%s", Outputdir.Data(), StrippedName.Data()), kTRUE);
        c->SaveAs(Form("%s/root/%s/Likelihood_scan_%s.root", Outputdir.Data(), StrippedName.Data(), ParamName.Data()));
        gSystem->mkdir(Form("%s/pdf/%s", Outputdir.Data(), StrippedName.Data()), kTRUE);
        c->SaveAs(Form("%s/pdf/%s/Likelihood_scan_%s.pdf", Outputdir.Data(), StrippedName.Data(), ParamName.Data()));
        gSystem->mkdir(Form("%s/png/%s", Outputdir.Data(), StrippedName.Data()), kTRUE);
        c->SaveAs(Form("%s/png/%s/Likelihood_scan_%s.png", Outputdir.Data(), StrippedName.Data(), ParamName.Data()));


        delete c;
        delete frame1;
        if (pll) delete pll;

        cout << endl << "DONE WITH " << counter << " PARAMETER OUT OF " << Nparams << endl << endl;
        //if (counter == 2){ break; } //Exit - for testing
        var = iter->Next();
    }  // End of the loop

    return true;
}
コード例 #22
0
ファイル: checkDbTable.C プロジェクト: kocolosk/mapping-db
bool checkDbTable(char* fileSource, char* MAXENTRY = "2030-01-01 00:00:00",char* flavor = "ofl")
{  
  bool equal=true;  
  TFile* tableFile=new TFile(fileSource);    
  
  TString tempString = fileSource;
  char slash = "/";
  int index = tempString.Last(slash);
  TString fileName = tempString(index+1,tempString.Length()-index);
  
  int index2 = fileName.Index(".");
  
  TString tableName = fileName(0,index2);
  TString date = fileName(index2+1,4) + "-" +
                 fileName(index2+5,2) + "-" +
                 fileName(index2+7,2);

  TString time = fileName(index2+10,2) + ":" +
                 fileName(index2+12,2) + ":" +
                 fileName(index2+14,2);

  TString timeStamp = date + " " + time;  

  StEmcDbHandler* dbHandler = new StEmcDbHandler();
  dbHandler->setTableName(tableName.Data());
  dbHandler->setTimeStamp(timeStamp.Data());
  dbHandler->setMaxEntryTime(MAXENTRY);    
  dbHandler->setFlavor(flavor);    

  StDbTable *table =  dbHandler->getDbTable();  
  DBTIME = dbHandler->timeToSqlTime(table->getBeginDateTime());
  if (tableName=="bemcCalib" || tableName=="bprsCalib" )
  {
    emcCalib_st* tableInFile = (emcCalib_st*) ((St_emcCalib*)tableFile->Get(tableName.Data()))->GetTable();
    emcCalib_st* tableInDb   = (emcCalib_st*) table->GetTable();
    equal=compare(tableInFile,tableInDb);
  }
  
  if (tableName=="bsmdeCalib" || tableName=="bsmdpCalib" )
  {
    smdCalib_st* tableInFile = (smdCalib_st*) ((St_smdCalib*)tableFile->Get(tableName.Data()))->GetTable();
    smdCalib_st* tableInDb   = (smdCalib_st*) table->GetTable();
    equal=compare(tableInFile,tableInDb);
  }
  
  if (tableName=="bemcGain" || tableName=="bprsGain" )
  {
    emcGain_st* tableInFile = (emcGain_st*) ((St_emcGain*)tableFile->Get(tableName.Data()))->GetTable();
    emcGain_st* tableInDb   = (emcGain_st*) table->GetTable();
    equal=compare(tableInFile,tableInDb);
  }
  
  if (tableName=="bsmdeGain" || tableName=="bsmdpGain" )
  {
    smdGain_st* tableInFile = (smdGain_st*) ((St_smdGain*)tableFile->Get(tableName.Data()))->GetTable();
    smdGain_st* tableInDb   = (smdGain_st*) table->GetTable();
    equal=compare(tableInFile,tableInDb);
  } 
  
  if (tableName=="bemcPed" || tableName=="bprsPed" )
  {
    emcPed_st* tableInFile = (emcPed_st*) ((St_emcPed*)tableFile->Get(tableName.Data()))->GetTable();
    emcPed_st* tableInDb   = (emcPed_st*) table->GetTable();
    equal=compare(tableInFile,tableInDb);
  }
 
  if (tableName=="bsmdePed" || tableName=="bsmdpPed" )
  {
    smdPed_st* tableInFile = (smdPed_st*) ((St_smdPed*)tableFile->Get(tableName.Data()))->GetTable();
    smdPed_st* tableInDb   = (smdPed_st*) table->GetTable();
    equal=compare(tableInFile,tableInDb);
  }

  if (tableName=="bemcStatus" || tableName=="bprsStatus" )
  {
    emcStatus_st* tableInFile = (emcStatus_st*) ((St_emcStatus*)tableFile->Get(tableName.Data()))->GetTable();
    emcStatus_st* tableInDb   = (emcStatus_st*) table->GetTable();
    equal=compare(tableInFile,tableInDb);
  }

  if (tableName=="bsmdeStatus" || tableName=="bsmdpStatus" )
  {
    smdStatus_st* tableInFile = (smdStatus_st*) ((St_smdStatus*)tableFile->Get(tableName.Data()))->GetTable();
    smdStatus_st* tableInDb   = (smdStatus_st*) table->GetTable();
    equal=compare(tableInFile,tableInDb);
  }
  
  if (tableName=="emcTriggerPed")
  {
    emcTriggerPed_st* tableInFile = (emcTriggerPed_st*) ((St_emcTriggerPed*)tableFile->Get(tableName.Data()))->GetTable();
    emcTriggerPed_st* tableInDb   = (emcTriggerPed_st*) table->GetTable();
    equal=compare(tableInFile,tableInDb);
  }
      
  if (tableName=="emcTriggerStatus")
  {
    emcTriggerStatus_st* tableInFile = (emcTriggerStatus_st*) ((St_emcTriggerStatus*)tableFile->Get(tableName.Data()))->GetTable();
    emcTriggerStatus_st* tableInDb   = (emcTriggerStatus_st*) table->GetTable();
    equal=compare(tableInFile,tableInDb);
  }

  if (tableName=="emcTriggerLUT")
  {
    emcTriggerLUT_st* tableInFile = (emcTriggerLUT_st*) ((St_emcTRiggerLUT*)tableFile->Get(tableName.Data()))->GetTable();
    emcTriggerLUT_st* tableInDb   = (emcTriggerLUT_st*) table->GetTable();
    equal=compare(tableInFile,tableInDb);
  }
  tableFile->Close();
  delete tableInFile;
  delete dbHandler;
  return equal;

}
コード例 #23
0
void
RooStats::HypoTestInvTool::AnalyzeResult( HypoTestInverterResult * r,
                                          int calculatorType,
                                          int testStatType, 
                                          bool useCLs,  
                                          int npoints,
                                          const char * fileNameBase ){

   // analyze result produced by the inverter, optionally save it in a file 
   
  
   double lowerLimit = 0;
   double llError = 0;
#if defined ROOT_SVN_VERSION &&  ROOT_SVN_VERSION >= 44126
   if (r->IsTwoSided()) {
      lowerLimit = r->LowerLimit();
      llError = r->LowerLimitEstimatedError();
   }
#else
   lowerLimit = r->LowerLimit();
   llError = r->LowerLimitEstimatedError();
#endif

   double upperLimit = r->UpperLimit();
   double ulError = r->UpperLimitEstimatedError();

   //std::cout << "DEBUG : [ " << lowerLimit << " , " << upperLimit << "  ] " << std::endl;
      
   if (lowerLimit < upperLimit*(1.- 1.E-4) && lowerLimit != 0) 
      std::cout << "The computed lower limit is: " << lowerLimit << " +/- " << llError << std::endl;
   std::cout << "The computed upper limit is: " << upperLimit << " +/- " << ulError << std::endl;
  

   // compute expected limit
   std::cout << "Expected upper limits, using the B (alternate) model : " << std::endl;
   std::cout << " expected limit (median) " << r->GetExpectedUpperLimit(0) << std::endl;
   std::cout << " expected limit (-1 sig) " << r->GetExpectedUpperLimit(-1) << std::endl;
   std::cout << " expected limit (+1 sig) " << r->GetExpectedUpperLimit(1) << std::endl;
   std::cout << " expected limit (-2 sig) " << r->GetExpectedUpperLimit(-2) << std::endl;
   std::cout << " expected limit (+2 sig) " << r->GetExpectedUpperLimit(2) << std::endl;
  

   printf("\n\n  owen: (-2s,-1s,m,1s,2s)  %5.2f   %5.2f   %5.2f   %5.2f   %5.2f\n\n",
      r->GetExpectedUpperLimit(-2),
      r->GetExpectedUpperLimit(-1),
      r->GetExpectedUpperLimit(0),
      r->GetExpectedUpperLimit(1),
      r->GetExpectedUpperLimit(2) ) ;
  
   // write result in a file 
   if (r != NULL && mWriteResult) {
    
      // write to a file the results
      const char *  calcType = (calculatorType == 0) ? "Freq" : (calculatorType == 1) ? "Hybr" : "Asym";
      const char *  limitType = (useCLs) ? "CLs" : "Cls+b";
      const char * scanType = (npoints < 0) ? "auto" : "grid";
      if (mResultFileName.IsNull()) {
         mResultFileName = TString::Format("%s_%s_%s_ts%d_",calcType,limitType,scanType,testStatType);      
         //strip the / from the filename
         if (mMassValue.size()>0) {
            mResultFileName += mMassValue.c_str();
            mResultFileName += "_";
         }
    
         TString name = fileNameBase; 
         name.Replace(0, name.Last('/')+1, "");
         mResultFileName += name;
      }

      TFile * fileOut = new TFile(mResultFileName,"RECREATE");
      r->Write();
      fileOut->Close();                                                                     
   }   
  
  
   // plot the result ( p values vs scan points) 
   std::string typeName = "";
   if (calculatorType == 0 )
      typeName = "Frequentist";
   if (calculatorType == 1 )
      typeName = "Hybrid";   
   else if (calculatorType == 2 || calculatorType == 3) { 
      typeName = "Asymptotic";
      mPlotHypoTestResult = false; 
   }
  
   const char * resultName = r->GetName();
   TString plotTitle = TString::Format("%s CL Scan for workspace %s",typeName.c_str(),resultName);
   HypoTestInverterPlot *plot = new HypoTestInverterPlot("HTI_Result_Plot",plotTitle,r);

   // plot in a new canvas with style
   TString c1Name = TString::Format("%s_Scan",typeName.c_str());
   TCanvas * c1 = new TCanvas(c1Name); 
   c1->SetLogy(false);

   plot->Draw("CLb 2CL");  // plot all and Clb

   // if (useCLs) 
   //    plot->Draw("CLb 2CL");  // plot all and Clb
   // else 
   //    plot->Draw("");  // plot all and Clb
  
   const int nEntries = r->ArraySize();
  
   // plot test statistics distributions for the two hypothesis 
   if (mPlotHypoTestResult) { 
      TCanvas * c2 = new TCanvas();
      if (nEntries > 1) { 
         int ny = TMath::CeilNint(TMath::Sqrt(nEntries));
         int nx = TMath::CeilNint(double(nEntries)/ny);
         c2->Divide( nx,ny);
      }
      for (int i=0; i<nEntries; i++) {
         if (nEntries > 1) c2->cd(i+1);
         SamplingDistPlot * pl = plot->MakeTestStatPlot(i);
         pl->SetLogYaxis(true);
         pl->Draw();
      }
   }
}
コード例 #24
0
void
RooStats::HypoTestInvTool::AnalyzeResult( HypoTestInverterResult * r,
                                          int calculatorType,
                                          int testStatType, 
                                          bool useCLs,  
                                          int npoints,
                                          const char * fileNameBase ){

   // analyize result produced by the inverter, optionally save it in a file 
   
   double upperLimit = r->UpperLimit();
   double ulError = r->UpperLimitEstimatedError();
  
   std::cout << "The computed upper limit is: " << upperLimit << " +/- " << ulError << std::endl;
  
   // compute expected limit
   std::cout << " expected limit (median) " << r->GetExpectedUpperLimit(0) << std::endl;
   std::cout << " expected limit (-1 sig) " << r->GetExpectedUpperLimit(-1) << std::endl;
   std::cout << " expected limit (+1 sig) " << r->GetExpectedUpperLimit(1) << std::endl;
   std::cout << " expected limit (-2 sig) " << r->GetExpectedUpperLimit(-2) << std::endl;
   std::cout << " expected limit (+2 sig) " << r->GetExpectedUpperLimit(2) << std::endl;
  
  
   // write result in a file 
   if (r != NULL && mWriteResult) {
    
      // write to a file the results
      const char *  calcType = (calculatorType == 0) ? "Freq" : (calculatorType == 1) ? "Hybr" : "Asym";
      const char *  limitType = (useCLs) ? "CLs" : "Cls+b";
      const char * scanType = (npoints < 0) ? "auto" : "grid";
      TString resultFileName = TString::Format("%s_%s_%s_ts%d_",calcType,limitType,scanType,testStatType);      
      //strip the / from the filename
      if (mMassValue.size()>0) {
         resultFileName += mMassValue.c_str();
         resultFileName += "_";
      }
    
      TString name = fileNameBase; 
      name.Replace(0, name.Last('/')+1, "");
      resultFileName += name;
    
      TFile * fileOut = new TFile(resultFileName,"RECREATE");
      r->Write();
      fileOut->Close();                                                                     
   }   
  
  
   // plot the result ( p values vs scan points) 
   std::string typeName = "";
   if (calculatorType == 0 )
      typeName = "Frequentist";
   if (calculatorType == 1 )
      typeName = "Hybrid";   
   else if (calculatorType == 2 ) { 
      typeName = "Asymptotic";
      mPlotHypoTestResult = false; 
   }
  
   const char * resultName = r->GetName();
   TString plotTitle = TString::Format("%s CL Scan for workspace %s",typeName.c_str(),resultName);
   HypoTestInverterPlot *plot = new HypoTestInverterPlot("HTI_Result_Plot",plotTitle,r);
   plot->Draw("CLb 2CL");  // plot all and Clb
  
   const int nEntries = r->ArraySize();
  
   // plot test statistics distributions for the two hypothesis 
   if (mPlotHypoTestResult) { 
      TCanvas * c2 = new TCanvas();
      if (nEntries > 1) { 
         int ny = TMath::CeilNint( sqrt(nEntries) );
         int nx = TMath::CeilNint(double(nEntries)/ny);
         c2->Divide( nx,ny);
      }
      for (int i=0; i<nEntries; i++) {
         if (nEntries > 1) c2->cd(i+1);
         SamplingDistPlot * pl = plot->MakeTestStatPlot(i);
         pl->SetLogYaxis(true);
         pl->Draw();
      }
   }
}
コード例 #25
0
ファイル: runAna.C プロジェクト: hebda/ggAnalysis
void runAna( int ijob = 0, 
	     string inputfile  = "root://eoscms//eos/cms/store/caf/user/fcouderc/gghSkims/8TeV/MC/v1_CMSSW53//job_summer12_ggH_125.root",
	     string configFile = "configFilesDir/mvaAnalysisTest.config",
	     string outputDir  = "notdefined",
	     string fileListForNorm = "unknown" ) {

  bool correctEnergy = true;
  
  bool setRho0 = false;
  bool correctVertex = true;

  ConfigReader config(configFile);


  TString jobName       = inputfile.c_str(); 
  jobName.Remove(0,jobName.Last('/')+1);  /// this is the fileName
  TString inputFileName = inputfile.c_str(); 
  TString outDir        = config.outDir().c_str();
  if( outputDir != "notdefined" ) outDir = outputDir;
  TString outFileBase   = jobName + "_" + itostr(ijob) + ".root";
  TString outFileName   = outDir + outFileBase;

  cout << " ----- overwrite output directory ---------  " << endl;
  cout << " ----- new dir (from cmd line): " << outDir << endl;
  gSystem->Exec( "mkdir -p " + outDir );
    
  /// FC: add xsec finder for MC (Data xsec = -1 by default)
  int enLHC = 2; /// ==> 14TeV!!!
  if( config.setup().find("2011") != string::npos ) enLHC = 0;
  if( config.setup().find("2012") != string::npos ) enLHC = 1;
  CrossSection xsec = FindXsec( inputfile, enLHC );
  Double_t lumi = config.luminosity();

  /// FC: change the logic to manage weights
  WeightManager weight_manager( inputfile, fileListForNorm);
  weight_manager.setCrossSection(xsec);
  weight_manager.setLumi(lumi);
  Int_t   nEvtsGen = weight_manager.getNevts();


  TFile* f = TFile::Open(inputFileName);   
  cout << "Opened file: " << inputFileName << endl;
  f->cd("ggNtuplizer");
    
  TTree* tree = (TTree*) gDirectory->Get("EventTree");
  cout <<"ggNtuplizer opened  "<<endl;
  xAna* gg_dijet = new xAna(tree); 
  gg_dijet->SetWeightManager(&weight_manager);
  gg_dijet->SetConfigReader(config);

  cout << " --- Cross Section (pb): " << xsec.getXsec() << endl;
  cout << " --- Lumi        (pb-1): " << lumi << endl;
  cout << " --- Nevts             : " << nEvtsGen << endl;
  cout <<"     ====== MODE  "<< xsec.mode()  <<endl;
  
  int nevtpass = gg_dijet->HggTreeWriteLoop(outFileName, ijob, correctVertex,correctEnergy,setRho0);
  cout << "============= job ending ===========" << endl;
  cout <<"outFileName:  "<< outFileName <<endl; 
  if( nevtpass > 0 && config.doSkimming() ) {
    TH1F* h[3]= { 0, 0, 0 };
    h[0] = (TH1F*) TFile::Open(inputFileName)->Get("ggNtuplizer/hEvents");   
    h[1] = (TH1F*) TFile::Open(inputFileName)->Get("ggNtuplizer/hPU");   
    h[2] = (TH1F*) TFile::Open(inputFileName)->Get("ggNtuplizer/hPUTrue");   
    
    TFile *fout = TFile::Open(outFileName,"update");
    fout->cd();
    for( int ih = 0 ; ih < 3; ih++ ) 
      if( h[ih] != 0 ) h[ih]->Write();
    fout->Close();
    
    //// store skimmed file of SE
    string dirSE = config.storageElementDir();
    if( dirSE != "unknown" ) {
      cout << " --- trying to store on storage element (must be on eos!!!): " << dirSE << endl;
      TString mkdir  = "cmsMkdir " + TString( dirSE.c_str() );
      TString rmfile = "cmsRm "    + TString( dirSE.c_str() ) + outFileBase;
      TString mvfile = "cmsStage " + outFileName + " " + TString( dirSE.c_str() );
      TString rmloc  = "rm -f " + outFileName;
      cout << mkdir  << endl; gSystem->Exec( mkdir  );
      cout << rmfile << endl; gSystem->Exec( rmfile );
      cout << mvfile << endl; int out = gSystem->Exec( mvfile );
      cout << "  output com = " << out << endl;
      if( out == 0 ) {
	/// rm file only is stored command exit properly
	cout << rmloc  << endl; gSystem->Exec( rmloc  );
      }
    }
  }

  delete gg_dijet;
}
コード例 #26
0
void createDataVsMC(TString folderName,TString histoName,int rebin,double xMin,double xMax,TString xName, TString yName, vector<TString> MCFileNames, vector<TString> MCNames, vector<int> MCColors, vector<bool> AddToBkg,vector<TString> DataFileNames,vector<TString> dataNames,vector<int> dataColors,vector<TString> SystNames,vector<int> SystColors, TCanvas *cCanvas, int padNr, bool UseLog,GlobalParameterSet Parameters) {
					 
  // CREATE ALL HISTOGRAMS ========================================================

  TString lumi = "";
  lumi+=Parameters.intLumi;
  if(Parameters.GlobalLog) {
    UseLog = true;  
  }
       
  // SM background histo
  TH1D *hSM0=0; 
  // Create MC histos and add them SM0
  vector<TH1D*> MChistos;
  bool noneAdded = true;

  float eventsMC=0;
  if(Parameters.MuPred){
    for(unsigned int i =0;i<3;i++) {
      TFile* fhh = TFile::Open(MCFileNames[i],"READONLY");
      TH1D *hTemp = (TH1D*)fhh->Get(folderName+"/CounterCtrl_tot");
      eventsMC += hTemp->GetBinContent(1);
      cout << "eventsMC " <<eventsMC<< endl;
      //delete hTemp;
      // delete fhh;
    }
    
    TFile* fdata_test = TFile::Open(DataFileNames[0],"READONLY");
    TH1D *hTempddd = (TH1D*)fdata_test->Get(folderName+"/CounterCtrl_tot");
    cout << "eventsMC " << eventsMC<< " "<<hTempddd->GetBinContent(1) << endl;
    Parameters.intLumi =  100*hTempddd->GetBinContent(1)/eventsMC;
  }
  
  // delete fdata_test;
  // delete hTempddd;

  for(unsigned int i =0;i<MCFileNames.size();i++) {
    MChistos.push_back(plot1Dhisto(Parameters.intLumi,TFile::Open(MCFileNames[i],"READONLY"),folderName,histoName,MCColors[i],rebin,xMin,xMax,xName,yName,"MC",true));
    if(noneAdded&&AddToBkg[i]) {
      hSM0 = (TH1D *) MChistos[i]->Clone();
      noneAdded = false;
    }
    else {
      if(AddToBkg[i]) {
	hSM0->Add(MChistos[i],1);
      }	  
    }
  }
  hSM0->SetLineColor(2);
   
  // Create Histograms with the different systematics
  vector<TH1D*> SystHistos;
  if(Parameters.UseSystematics) {
    for(unsigned int i=0; i<SystNames.size(); i++) {
      noneAdded = true;
      for(unsigned int j=0; j<MCFileNames.size(); j++) {
	if(AddToBkg[j]) {
	  TString SystFileName = MCFileNames[j];
	  SystFileName.Insert(SystFileName.Last('/'),"_"+SystNames[i]);
	  TFile *SystMCFile = TFile::Open(SystFileName,"READONLY");
	  TH1D *SystHistoTemp = plot1Dhisto(Parameters.intLumi,SystMCFile,folderName,histoName,SystColors[i],rebin,xMin,xMax,xName,yName,"MC",true);
	  SystHistoTemp->SetLineStyle(2);
	  if(noneAdded) {
	    SystHistos.push_back((TH1D *) SystHistoTemp->Clone());
	    noneAdded = false;
	  }
	  else {
	    SystHistos.back()->Add(SystHistoTemp,1);
	  }
	}
      }
    }
  }

  // Create Histograms for error band
  TH1D* hSM0allErrors = (TH1D *) hSM0->Clone();
  TH1D* hSM0systErrors = (TH1D *) hSM0->Clone();
  if(Parameters.UseSystematics) {
    for(int j = hSM0->FindBin(xMin); j<=hSM0->FindBin(xMax); j++) {
      double downerror=0;
      double uperror=0;
      for(unsigned int i=0; i<SystHistos.size(); i++) {
	double diff = SystHistos[i]->GetBinContent(j) - hSM0->GetBinContent(j);
	if(diff>0)
	  uperror += diff*diff;
	else
	  downerror += diff*diff;
      }
      downerror = TMath::Sqrt(downerror);
      uperror = TMath::Sqrt(uperror);
      double maxerror = TMath::Max(downerror,uperror);
      double staterror = hSM0->GetBinError(j);
      hSM0systErrors->SetBinError(j,maxerror);
      hSM0allErrors->SetBinError(j,TMath::Sqrt(maxerror*maxerror+staterror*staterror));
      hSM0systErrors->SetFillColor(5);
      hSM0systErrors->SetLineColor(5);
      hSM0allErrors->SetLineColor(3);
      hSM0allErrors->SetFillColor(3);
    }
  }
  
  // Create Data Histograms
  vector<TH1D *> dataHistos; 
  for(unsigned int i=0; i<DataFileNames.size();i++) {
    dataHistos.push_back(plot1Dhisto(Parameters.intLumi,TFile::Open(DataFileNames[i],"READONLY"),folderName,histoName,dataColors[i],rebin,xMin,xMax,xName,yName,"Data",false));
    dataHistos[i]->SetMarkerSize(1.2); 
    dataHistos[i]->SetMarkerColor(dataColors[i]); 
    dataHistos[i]->SetMarkerStyle(20);
    // remove error manually  
    if(!Parameters.ShowStatErrorbars){
      NoError(dataHistos[i],xMin,xMax);
    }
    // y-axis range
    if (UseLog){ 
      dataHistos[i]->GetYaxis()->SetRangeUser(1.,3.5*(dataHistos[i]->GetBinContent(dataHistos[i]->GetMaximumBin()))); 
    }
    else{ 
      float maximum =  hSM0->GetMaximum();
      if(maximum<dataHistos[i]->GetMaximum())maximum=dataHistos[i]->GetMaximum();
      dataHistos[i]->GetYaxis()->SetRangeUser(0.,maximum*1.8);
    }

  }
  
  cCanvas->SetName(folderName+histoName);
  cCanvas->cd(2*padNr+1);  

  if(UseLog) {
    gPad->SetLogy(); 
  }
  dataHistos[0]->Draw("P E0");

  //DRAW ALL HISTOGRAMS =====================================================    
  
  if(Parameters.ShowMCComposition){
    for(unsigned int i=1; Parameters.StackMCComposition&&i<MChistos.size();i++) {
      MChistos[i]->Add(MChistos[i],MChistos[i-1]);
      MChistos[i]->SetFillColor(MCColors[i]);
      MChistos[i]->SetLineStyle(1);
      MChistos[i]->SetFillStyle(3004);
      MChistos[i-1]->SetFillStyle(3004);
      MChistos[i-1]->SetFillColor(MCColors[i-1]); 	  	  
      
    }  	
    for(int i=MChistos.size()-1;i>=0;i--) {
      if(Parameters.ShowMCStatErrorbars)
	MChistos[i]->Draw("HIST E0 same");
      else
	MChistos[i]->Draw("HIST same");
    }
  }
  
  hSM0->SetLineColor(kRed);

  if(Parameters.ShowErrorBand) {
    hSM0allErrors->Draw("E2 same");
    hSM0systErrors->Draw("E2 same");
  }

  if(!Parameters.ShowMCStatErrorbars&&!Parameters.StackMCComposition)
    hSM0->Draw("HIST same"); 
  	
  if(Parameters.ShowSystematicsDetails) {
    for(unsigned int i=0; i<SystHistos.size();i++) {
      SystHistos[i]->Draw("HIST same");
    }
  } 
  
  for(int i=dataHistos.size()-1;i>=0;i--) {
    dataHistos[i]->Draw("P E0 same");
  }
  if(Parameters.ShowMCStatErrorbars&&!Parameters.StackMCComposition) {
    hSM0->Draw("HIST same E0");
  }
  // Draw Legend
  TLegend *lSamples = legendRAW(0.77,0.58,0.95,0.89);
  if(!Parameters.StackMCComposition)
    lSamples->AddEntry(hSM0,"Total MC","FL");
  if(Parameters.ShowErrorBand) {
    lSamples->AddEntry(hSM0systErrors,"Systematic Error","FL");
    lSamples->AddEntry(hSM0allErrors,"MC Syst. #oplus Stat. Error","FL");
  }
  for(unsigned int i=0; i<dataHistos.size(); i++) { 
    lSamples->AddEntry(dataHistos[i],dataNames[i],"PL");
  }
  for(unsigned int i =0;i<MChistos.size()&&Parameters.ShowMCComposition;i++) {
    lSamples->AddEntry(MChistos[i],MCNames[i],"FL");
  }
  for(unsigned int i =0;i<SystHistos.size()&&Parameters.ShowSystematicsDetails;i++) {
    lSamples->AddEntry(SystHistos[i],SystNames[i],"FL");
  }
  
  lSamples->Draw("same");

  TLatex *lWhichLepton;
  if (Parameters.electrons) { lWhichLepton = new TLatex(0.73,0.9,"Electrons"); }
  else { lWhichLepton = new TLatex(0.73,0.9,"Muons"); }
  lWhichLepton->SetNDC();
  lWhichLepton->Draw("same");
  

  TLatex *lPreliminary = new TLatex(0.19,0.96,"CMS Preliminary 2011");

  //  TLatex *lIntLumi = new TLatex(0.15,0.89,"#scale[0.8]{#int L dt = "+lumi+" pb^{-1}, #sqrt{s} = 7 TeV}");
  TLatex *lIntLumi  = new TLatex(0.22,0.88,"#scale[1.]{4.7 fb^{-1}, #sqrt{s} = 7 TeV}");
  TLatex *lIntLumiB = new TLatex(0.22,0.79,"#scale[1.]{#sqrt{s} = 7 TeV}");
  lPreliminary->SetNDC();
  lIntLumi->SetNDC();
  lIntLumiB->SetNDC();
  lPreliminary->Draw("same");
  lIntLumi->Draw("same"); 
  gPad->SetFillColor(0);
  //  lIntLumiB->Draw("same"); 
  //  gPad->SetGridx(); 
  //  gPad->SetGridy();
  

  // --- create HT and STlep legends
  //"ANplots150_NOLPsecondD500" folderNames
  
  TString HT500 = "secondD500";
  TString HT750 = "secondD750";
  TString HT1000 = "secondD1000";
  
  TString ST150 = "plots150";
  TString ST250 = "plots250";
  TString ST350 = "plots350";
  TString ST450 = "plots450";

  TString tmpLegendHT, tmpLegendST;

  if (((folderName.SubString(HT500)).Length())>0)       { if (Parameters.htBins) { tmpLegendHT = "H_{T}#in[500,750]"; }  else { tmpLegendHT = "H_{T}>500";}  } 
  else if (((folderName.SubString(HT750)).Length())>0)  { if (Parameters.htBins) { tmpLegendHT = "H_{T}#in[750,1000]"; } else { tmpLegendHT = "H_{T}>750";}  } 
  else if (((folderName.SubString(HT1000)).Length())>0) { if (Parameters.htBins) { tmpLegendHT = "H_{T}>1000"; }         else { tmpLegendHT = "H_{T}>1000";} } 
  else { tmpLegendHT = "error"; }

  if (((folderName.SubString(ST150)).Length())>0)      { tmpLegendST = "S^{lep}_{T}#in[150,250]"; }
  else if (((folderName.SubString(ST250)).Length())>0) { tmpLegendST = "S^{lep}_{T}#in[250,350]"; }
  else if (((folderName.SubString(ST350)).Length())>0) { tmpLegendST = "S^{lep}_{T}#in[350,450]"; }
  else if (((folderName.SubString(ST450)).Length())>0) { tmpLegendST = "S^{lep}_{T}>450"; }
  else { tmpLegendST = "error"; }

  TString legendHTandST = tmpLegendHT+" , "+tmpLegendST; 
  TLatex *lHTandST = new TLatex(0.22,0.8,legendHTandST);
  lHTandST->SetNDC();
  //  lHTandST->Draw("same");
  
  TLatex *lHT = new TLatex(0.22,0.8,tmpLegendHT);
  lHT->SetNDC();
  lHT->Draw("same");

  TLatex *lST = new TLatex(0.22,0.7,tmpLegendST);
  lST->SetNDC();
  lST->Draw("same");



  // DRAW RATIO PLOTS ============================================================================
  if (Parameters.ratioplot)
    {
      vector<TH1D*> hRatio;
      for(unsigned int i=0; i<dataHistos.size()&&MChistos.size()>0; i++) {
	hRatio.push_back((TH1D*)dataHistos[i]->Clone(""));
	hRatio.back()->Divide(dataHistos[i],hSM0);
	hRatio.back()->GetYaxis()->SetTitle("Data / MC");
	hRatio.back()->GetYaxis()->SetTitleSize(0.16);
	hRatio.back()->GetXaxis()->SetTitle("");
	hRatio.back()->GetYaxis()->SetNdivisions(409);
	hRatio.back()->GetYaxis()->SetRangeUser(0.,2.);
	hRatio.back()->SetTitleSize(0.16, "XY");
	hRatio.back()->SetTitleOffset(0.5, "Y");
	hRatio.back()->SetLabelSize(0.165,"XY");
	
      }
      
      for(unsigned int i=0; Parameters.UseSystematics&&Parameters.ShowSystematicsDetails&&i<SystHistos.size(); i++) {
	hRatio.push_back((TH1D*)SystHistos[i]->Clone(""));
	hRatio.back()->Divide(SystHistos[i],hSM0);
	hRatio.back()->GetYaxis()->SetTitle("Data&Syst/MC");
	hRatio.back()->GetYaxis()->SetRangeUser(0.5,1.5);
	hRatio.back()->GetXaxis()->SetTitle("");
	hRatio.back()->SetTitleSize(0.06, "XY");
	hRatio.back()->SetTitleOffset(0.8, "Y");
	hRatio.back()->SetLabelSize(0.08,"XY");
	NoError(hRatio.back(),xMin,xMax);
      }
      
      cCanvas->cd(2*padNr+2);
      //  TBox *unity = new TBox(xMin-0.1,0.95,xMax+0.15, 1.05); // LP
      TBox *unity = new TBox(xMin-0.1,0.95,xMax+0.15, 1.05);
      
      unity->SetLineWidth(2);
      //unity.SetLineStyle(Root.kDashed);
      unity->SetLineColor(2);
      unity->SetFillColor(2);
      unity->SetFillStyle(3002);
      //  unity->Draw();
      //  gPad->SetGridx(); 
      //  gPad->SetGridy();
      for(unsigned int i=hRatio.size()-1; i<hRatio.size(); i--) {
	if(i==hRatio.size()-1) {
	  hRatio[i]->Draw();
	  //      unity->Draw("same");
	  hRatio[i]->Draw("same");
	}
	else
	  {
	    hRatio[i]->GetYaxis()->SetTitleSize(0.055);
	    hRatio[i]->Draw("same"); 
	  }
      }
    } // ratio stuff close

}
コード例 #27
0
ファイル: Example_tags.C プロジェクト: star-bnl/star-macros
void Example_tags(TString topDir = "/star/rcf/GC/daq/tags")
{
//////////////////////////////////////////////////////////////////////////
//                                                                      //
// Example_tags.C                                                       //
//                                                                      //
// shows how to use the STAR tags files                                 //
// Input: top level directory                                           //
//                                                                      //
// what it does:                                                        //
// 1. creates TChain from all tags files down from the topDir           //
// 2. loops over all events in the chain                                //
//                                                                      //
// owner: Alexandre V. Vaniachine <*****@*****.**>                //
//////////////////////////////////////////////////////////////////////////

  gSystem->Load("libTable");
  gSystem->Load("St_base");
  // start benchmarks
  gBenchmark = new TBenchmark();
  gBenchmark->Start("total");
   
  // set loop optimization level
  gROOT->ProcessLine(".O4");
  // gather all files from the same top directory into one chain
  // topDir must end with "/"
  topDir +='/';
  St_FileSet dirs(topDir);
  St_DataSetIter next(&dirs,0);
  St_DataSet *set = 0; 
  TChain chain("Tag");
  while ( (set = next()) ) {           
    if (strcmp(set->GetTitle(),"file") || 
	!(strstr(set->GetName(),".tags.root"))) continue;
    chain.Add(gSystem->ConcatFileName(topDir,set->Path()));
  }
  UInt_t nEvents = chain->GetEntries();
  cout<<"chained "<<nEvents<<" events "<<endl;

  TObjArray *files = chain.GetListOfFiles();
  UInt_t nFiles = files->GetEntriesFast();
  cout << "chained " << nFiles << " files from " << topDir << endl;

  TObjArray *leaves = chain.GetListOfLeaves();
  Int_t nleaves = leaves->GetEntriesFast();

  TString tableName = " ";
  TObjArray *tagTable = new TObjArray;

  Int_t tableCount = 0;
  Int_t *tableIndex = new Int_t[nleaves];
  Int_t tagCount = 0;

  // decode tag table names
  for (Int_t l=0;l<nleaves;l++) {
    TLeaf *leaf = (TLeaf*)leaves->UncheckedAt(l);
    tagCount+=leaf->GetNdata();
    TBranch *branch = leaf->GetBranch();
    // new tag table name
    if ( strstr(branch->GetName(), tableName.Data()) == 0 ) {
      tableName = branch->GetName();
      // the tableName is encoded in the branch Name before the "."
      tableName.Resize(tableName->Last('.'));
      tagTable->AddLast(new TObjString(tableName.Data()));
      tableCount++;
    }
    tableIndex[l]=tableCount-1;
  }
  cout << " tot num tables, tags = " << tableCount << "   " 
       << tagCount << endl << endl;

  //EXAMPLE 1: how to print out names of all tags and values for first event
  for (l=0;l<nleaves;l++) {
    leaf = (TLeaf*)leaves->UncheckedAt(l);
    branch = leaf->GetBranch();
    branch->GetEntry();
    // tag comment is in the title
    TString Title = leaf->GetTitle();
    Int_t dim = leaf->GetNdata();
    if (dim==1) {
      Title.ReplaceAll('['," '"); 
      Title.ReplaceAll(']',"'"); 
    }
    cout << "\n Table: ";
    cout.width(10);
    cout << ((TObjString*)tagTable->UncheckedAt(tableIndex[l]))->GetString()
	 <<" -- has tag: " << Title << endl;
    for (Int_t i=0;i<dim;i++) {
      cout <<"                               "<< leaf->GetName();
      if (dim>1) cout << '['<<i<<']';
      cout << " = " << leaf->GetValue(i) << endl; 
    }
  }

  // EXAMPLE 2: how to make a plot
  c1 = new TCanvas("c1","Beam-Gas Rejection",600,1000);
  gStyle->SetMarkerStyle(8);
  chain->Draw("n_trk_tpc[0]:n_trk_tpc[1]");

  // EXAMPLE 3: how to make a selection (write selected event numbers on the plot)
  Int_t ncoll=0;
  char aevent[10];
  TText t(0,0,"a");
  t.SetTextFont(52);
  t.SetTextSize(0.02);
  Float_t cut = 0.35;
  cout <<"\n Events with ntrk>400 and |asim|<"<<cut<<endl;
  //loop over all events: READ ONLY n_trk_tpc AND mEventNumber BRANCHES!
  gBenchmark->Start("loop");
  for (Int_t i=0;i<nFiles;i++) {
    chain.LoadTree(*(chain.GetTreeOffset()+i));
    TTree *T = chain.GetTree();
    //must renew leaf pointer for each tree
    TLeaf *ntrk = T->GetLeaf("n_trk_tpc");
    TLeaf *run = T->GetLeaf("mRunNumber");
    TLeaf *event = T->GetLeaf("mEventNumber");
    for (Int_t j=0; j<T->GetEntries(); j++){
      ntrk->GetBranch()->GetEntry(j);
      event->GetBranch()->GetEntry(j);
      run->GetBranch()->GetEntry(j);
      Int_t Nm=ntrk->GetValue(0);
      Int_t Np=ntrk->GetValue(1);
      Int_t Ntrk = Np+Nm;
      // avoid division by 0
      Float_t asim = Np-Nm;
      if (Ntrk>0) asim /= Ntrk;
      if (-cut < asim&&asim < cut && Ntrk>400) {
	cout<<"   Run "<<(UInt_t)run->GetValue()
	    <<", Event "<<event->GetValue() <<endl;
	ncoll++;
	sprintf(aevent,"%d",event->GetValue());
	t.DrawText(Np+10,Nm+10,aevent);
      }
    }
  }
  gBenchmark->Stop("loop");
  t.SetTextSize(0.05);
  t.DrawText(50,2550,"ntrk>400 and |(Np-Nm)/(Np+Nm)| < 0.35 ");
  t.DrawText(500,-300,"Ntrk with tanl<0 ");
  cout << " Selected " << ncoll << " collision candidates out of "
       << nEvents << " events" << endl;
  // stop timer and print benchmarks
  gBenchmark->Print("loop");  
  gBenchmark->Stop("total");
  gBenchmark->Print("total");  
}
コード例 #28
0
ファイル: minuitFit.C プロジェクト: zaglamir/ptHatOffline
void minuitFit()
{
  
  gStyle->SetOptFit(1111);
  gStyle->SetOptStat(0);

  Bool_t makePDF = checkMakePDF();
  
  char name[1000];
  sprintf(name,"/Users/zach/Research/pythia/ptHatTemplate/outputs/currentB.root");
  TFile *fB = new TFile(name,"READ");
  sprintf(name,"/Users/zach/Research/pythia/ptHatTemplate/outputs/currentC.root");
  TFile *fC = new TFile(name,"READ");
  sprintf(name,"/Users/zach/Research/rootFiles/run12NPEhPhi/currentData.root");
  TFile *fD = new TFile(name,"READ");
  if (fB->IsOpen()==kFALSE || fC->IsOpen()==kFALSE)
    { std::cout << "!!!!!! Either B,C, or Data File not found !!!!!!" << std::endl
		<< "Looking for currentB.root, currentC.root, and currentData.root" << std::endl;
      exit(1); }
  
  // Set constants and projection bins (from header file anaConst, analysis constants)
  
  Float_t lowpt[numPtBins],highpt[numPtBins];
  for(Int_t c=0; c< numPtBins; c++){
    lowpt[c] = anaConst::lpt[c];
    highpt[c] = anaConst::hpt[c];
  }
  Float_t hptCut=anaConst::hptCut;
  Double_t p00[numPtBins],p01[numPtBins],p20[numPtBins],p21[numPtBins];
  Double_t e00[numPtBins],e01[numPtBins],e20[numPtBins],e21[numPtBins];
  Double_t pC0[numPtBins],pC1[numPtBins],eC0[numPtBins],eC1[numPtBins];
  Double_t Rb0[numPtBins],Rb2[numPtBins],RbC[numPtBins],pT[numPtBins];
  Double_t eb0[numPtBins],eb2[numPtBins],ebC[numPtBins],dx[numPtBins];
  Double_t ptOFF1[numPtBins],ptOFF2[numPtBins];
  Int_t plotCount0 = 0, plotCount2 = 0, plotCount = 0;
  
  // Make Canvases
  TCanvas* deltaPhi  = new TCanvas("deltaPhi","Pythia Delta Phi",150,0,1150,1000);
  TCanvas* deltaPhi2  = new TCanvas("deltaPhi2","Pythia Delta Phi",150,0,1150,1000);
  TCanvas* fitResult0 = new TCanvas("fitResult0","RB Extraction HT0",150,0,1150,1000);
  TCanvas* fitResult2 = new TCanvas("fitResult2","RB Extraction HT2",150,0,1150,1000);
  TCanvas* fitResultC = new TCanvas("fitResultC","RB Extraction Combined Trigs",150,0,1150,1000);
  deltaPhi  ->Divide(3,3);
  deltaPhi2 ->Divide(3,3);
  fitResult0->Divide(3,4);
  fitResult2->Divide(3,4);
  fitResultC->Divide(3,4);

  // Get and Draw histos
  TPaveText* lbl[numPtBins];
  TPaveText* stat[3][numPtBins];
  char statLabel[100];
  char textLabel[100];
  Int_t plotbin;
  Float_t norm0,norm2,normB,normC;

  // Get ptbin independent hists
  histoNorms = (TH1F*)fD->Get("histoNorms");
  bPtNorms   = (TH1F*)fB->Get("ptNorm");
  cPtNorms   = (TH1F*)fC->Get("ptNorm");
  
  for(Int_t ptbin=0; ptbin<numPtBins; ptbin++)
    {
      norm0 = histoNorms->GetBinContent(histoNorms->GetBin(1,ptbin+1));
      norm2 = histoNorms->GetBinContent(histoNorms->GetBin(3,ptbin+1));
      normB = bPtNorms->GetBinContent(bPtNorms->GetBin(ptbin+1));
      normC = cPtNorms->GetBinContent(cPtNorms->GetBin(ptbin+1));

      if(norm0 == 0)
	{
	  cout << ptbin << " For this bin, some norm0 = 0" << endl;
	  continue;
	}
      if( norm2 == 0 )
	{
	  cout << ptbin << " For this bin, some norm2 = 0" << endl;
	  continue;
	}
      if( normB == 0 )
	{
	  cout << ptbin << " For this bin, some normB = 0" << endl;
	  continue;
	}
      if(normC == 0)
	{
	  cout << ptbin << " For this bin, some normC = 0" << endl;
	  continue;
	}
      plotbin = ptbin;
      // Init necessary plotting tools
      lbl[ptbin] = new TPaveText(.15,.15,.35,.23,Form("NB NDC%i",ptbin));
      sprintf(textLabel,"%.1f < P_{T,e} < %.1f",lowpt[ptbin],highpt[ptbin]);
      lbl[ptbin]->AddText(textLabel);
      lbl[ptbin]->SetFillColor(kWhite);

      projB[ptbin] = (TH1D*)fB->Get(Form("delPhi_%i",ptbin));
      projC[ptbin] = (TH1D*)fC->Get(Form("delPhi_%i",ptbin));
      projData0[ptbin]= (TH1D*)fD->Get(Form("NPEhDelPhi_0_%i",ptbin));
      projData2[ptbin]= (TH1D*)fD->Get(Form("NPEhDelPhi_2_%i",ptbin));
      // Do any rebinning
      Int_t RB = 1;
      projB[ptbin]->Rebin(RB);
      projC[ptbin]->Rebin(RB);
      projData0[ptbin]->Rebin(RB);
      projData2[ptbin]->Rebin(RB);

      // Clone to make plots without effecting fits
      plotD0[ptbin] = (TH1D*) projData0[ptbin]->Clone();
      plotD2[ptbin] = (TH1D*) projData2[ptbin]->Clone();
      plotB[ptbin]  = (TH1D*) projB[ptbin]->Clone();
      plotC[ptbin]  = (TH1D*) projC[ptbin]->Clone();

      // Set features that are the same in plots
      projData0[ptbin]->SetLineColor(kBlue);
      projData2[ptbin]->SetLineColor(kGreen+3);
      projB[ptbin]->SetLineColor(kRed);
      projC[ptbin]->SetLineColor(kBlack);
      projC[ptbin]->GetXaxis()->SetRangeUser(-3.5,3.5);
      plotD0[ptbin]->SetLineColor(kBlue);
      plotD2[ptbin]->SetLineColor(kGreen+3);
      plotD0[ptbin]->SetMarkerStyle(20);
      plotD0[ptbin]->SetMarkerColor(kBlue);
      plotD0[ptbin]->SetMarkerSize(0.4);
      plotB[ptbin]->SetLineColor(kRed);
      plotC[ptbin]->SetLineColor(kBlack);
      plotC[ptbin]->GetXaxis()->SetRangeUser(-3.5,3.5);

      combData[ptbin] = (TH1D*) projData0[ptbin]->Clone();
      combData[ptbin] -> Add(projData2[ptbin]);
      combData[ptbin]->SetLineColor(kBlue);
      combData[ptbin]->SetMarkerStyle(20);
      combData[ptbin]->SetMarkerColor(kBlue);
      combData[ptbin]->SetMarkerSize(0.4);
      combData[ptbin]->SetTitle("");
      
      // Normalize
      projB[ptbin]     -> Scale(1/normB);
      projC[ptbin]     -> Scale(1/normC);
      projData0[ptbin] -> Scale(1/norm0);
      projData2[ptbin] -> Scale(1/norm2);
      plotD0[ptbin]    -> Scale(1/norm0);
      plotD2[ptbin]    -> Scale(1/norm2);
      plotB[ptbin]     -> Scale(1/(normB));
      plotC[ptbin]     -> Scale(1/(normC));
      combData[ptbin]  -> Scale(1/(norm0+norm2));
    /*projB[ptbin]     -> Scale(projData0[ptbin]->GetBinContent(70)/projB[ptbin]->GetBinContent(70));
      projC[ptbin]     -> Scale(projData0[ptbin]->GetBinContent(70)/projC[ptbin]->GetBinContent(70));
      plotB[ptbin]     -> Scale(projData0[ptbin]->GetBinContent(70)/plotB[ptbin]->GetBinContent(70));
      plotC[ptbin]     -> Scale(projData0[ptbin]->GetBinContent(70)/plotC[ptbin]->GetBinContent(70));
      */
      
      // Draw Templates on own plots
      if(ptbin+1 <= 9) deltaPhi->cd(plotbin+1);
      if(ptbin+1 > 9) deltaPhi2->cd(ptbin-8);
      plotC[ptbin]->GetYaxis()->SetRangeUser(-.1,0.5);
      plotC[ptbin]  -> Draw("hist");
      plotB[ptbin]  -> Draw("same hist");
      plotD0[ptbin] -> Draw("same");
      plotD2[ptbin] -> Draw("same");
      lbl[ptbin]    -> Draw("same");

      TLegend* leg = new TLegend(0.65,0.6,0.85,0.85);
      leg->AddEntry(projB[ptbin],"b#bar{b}->NPE","lpe");
      leg->AddEntry(projC[ptbin],"c#bar{c}->NPE","lpe");
      leg->AddEntry(projData0[ptbin],"HT0","lpe");
      leg->AddEntry(projData2[ptbin],"HT2","lpe");
      leg->Draw();

      /////////////////////
      // Do the actual fits
      /////////////////////

      cout << "!!!!!!! HT0 ptbin: " << highpt[ptbin] << "-" << lowpt[ptbin] <<" !!!!!!!"<< endl;
      currentPtBin = ptbin;
      double arglist[10];int ierflg=0;
      TMinuit *gMinuit=new TMinuit(2); //initialize TMinuit with a maximum of 3 params
      gMinuit->SetMaxIterations(50000);
      gMinuit->SetFCN(chi2_0);
      arglist[0]=1; //error definition: chi^2 change by 1 to get 1 sigma
      gMinuit->mnexcm("SET ERR",arglist,1,ierflg);

      //starting values
      double vstart[2]={0.3,1}; //frac
      double step[2]={0.01,0.01}; //starting step
      gMinuit->mnparm(0,"BtoNPE frac",vstart[0],step[0],0.000,2,ierflg);
      gMinuit->mnparm(1,"Scale Factor",vstart[1],step[1],0.000,2,ierflg);
      //simple scan to get better start values
      gMinuit->mnexcm("SCAN",arglist,0,ierflg); 
      cout<<"done with first scan!"<<endl;

      //minimization
      arglist[0]=5000; //maxcalls
      arglist[1]=0.5; // tolerance = 0.001*[this value]*[error def] //5.0 before
      gMinuit->mnexcm("MINIMIZE",arglist,2,ierflg);

      cout<< "done with fit! Error Flag: " << ierflg << endl;

       //fit results
      double dum1,dum2;
      TString *str0 = new TString("BtoNPE frac");
      TString *str1 = new TString("Scale Factor");
      gMinuit->mnpout(0,*str0,p01[ptbin],e01[ptbin],dum1,dum2,ierflg);
      gMinuit->mnpout(1,*str1,p00[ptbin],e00[ptbin],dum1,dum2,ierflg);

      cout << endl << endl << "HT0 PT Bin: " << lowpt[ptbin] << "-" << highpt[ptbin] << endl
	   << "rB: " << p01[ptbin] << " rC: " << p00[ptbin] << endl
	   << "erB: " << e01[ptbin] << " erC: " << e00[ptbin] << endl << endl;
      
      //Print results
      double amin,edm,errdef;
      int nvpar,nparx,icstat;
      gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
      gMinuit->mnprin(4,amin);
      
      // assign to plotting variables
      if(highpt[ptbin] < 6)
	{
	  pT[ptbin] = (lowpt[ptbin]+highpt[ptbin])/2.;
	  dx[plotCount0] = 0.;
	  ptOFF1[plotCount0] = pT[ptbin];
	  Rb0[plotCount0] = p01[ptbin];///(p01[ptbin]+p00[ptbin]);
	  eb0[plotCount0] = e01[ptbin];
	  plotCount0++;
	}
    
      // Plot results
      fitResult0->cd(ptbin+1);
      TH1D* dClone = (TH1D*) projData0[ptbin]->Clone();
      TH1D* cClone = (TH1D*) projC[ptbin]->Clone();
      TH1D* bClone = (TH1D*) projB[ptbin]->Clone();
      stat[0][ptbin] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%i",ptbin));
      sprintf(statLabel,"Chi2/NDF: %.2f/%.0f",curChi2,curNDF);
      stat[0][ptbin]->InsertText(statLabel);
      stat[0][ptbin]->SetFillColor(kWhite);
      cClone->Scale((1.-p01[ptbin])*p00[ptbin]); bClone->Scale(p00[ptbin]*p01[ptbin]); // scale by contribution param
      cClone->Add(bClone);
      //cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
      dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
      dClone->GetYaxis()->SetRangeUser(-0.1,0.4);
      dClone->Draw();
      cClone->Draw("same");
      stat[0][ptbin]->Draw("same");
      lbl[ptbin]->Draw("same");
            

      cout << "!!!!!!! HT2 ptbin: " <<  highpt[ptbin] << "-" << lowpt[ptbin] <<" !!!!!!!"<< endl;
      fitResult2->cd(ptbin+1);
      currentPtBin = ptbin;
      TMinuit *g2Minuit=new TMinuit(2); //initialize TMinuit with a maximum of 3 params
      g2Minuit->SetMaxIterations(50000);
      g2Minuit->SetFCN(chi2_2);
      arglist[0]=1; //error definition: chi^2 change by 1 to get 1 sigma
      g2Minuit->mnexcm("SET ERR",arglist,1,ierflg);

      //starting values
      double vstart2[2]={0.3,1}; //frac
      double step2[2]={0.01,0.01}; //starting step
      g2Minuit->mnparm(0,"BtoNPE frac",vstart2[0],step2[0],0.000,2,ierflg);
      g2Minuit->mnparm(1,"Scale Factor",vstart2[1],step2[1],0.000,2,ierflg);
      //simple scan to get better start values
      g2Minuit->mnexcm("SCAN",arglist,0,ierflg); 
      cout<<"done with first scan!"<<endl;

      //minimization
      arglist[0]=5000; //maxcalls
      arglist[1]=0.5; // tolerance = 0.001*[this value]*[error def] //5.0 before
      g2Minuit->mnexcm("MINIMIZE",arglist,2,ierflg);

      cout<< "done with fit! Error Flag: " << ierflg << endl;

       //fit results
      TString *str2 = new TString("BtoNPE frac");
      TString *str3 = new TString("Scale Factor");
      g2Minuit->mnpout(0,*str2,p21[ptbin],e21[ptbin],dum1,dum2,ierflg);
      g2Minuit->mnpout(1,*str3,p20[ptbin],e20[ptbin],dum1,dum2,ierflg);

      cout << endl << endl << "HT2 PT Bin: " << lowpt[ptbin] << "-" << highpt[ptbin] << endl
	   << "rB: " << p21[ptbin] << " rC: " << p20[ptbin] << endl
	   << "erB: " << e21[ptbin] << " erC: " << e20[ptbin] << endl << endl;
      
      //Print results
      g2Minuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
      g2Minuit->mnprin(4,amin);
      
      // assign to plotting variables
      if(highpt[ptbin] > 3.6)
	{
	  pT[ptbin] = (lowpt[ptbin]+highpt[ptbin])/2.;
	  ptOFF2[plotCount2] = pT[ptbin];
	  Rb2[plotCount2] = p21[ptbin];///(p21[ptbin]+p20[ptbin]);
	  eb2[plotCount2] = e21[ptbin];
	  plotCount2++;
	}

      // Plot results
      fitResult2->cd(ptbin+1);
      dClone = (TH1D*) projData2[ptbin]->Clone();
      cClone = (TH1D*) projC[ptbin]->Clone();
      bClone = (TH1D*) projB[ptbin]->Clone();
      stat[2][ptbin] = new TPaveText(.4,.75,.85,.85,Form("NB NDC%i",ptbin));
      sprintf(statLabel,"Chi2/NDF: %.2f/%.2f",curChi2,curNDF);
      stat[2][ptbin]->InsertText(statLabel);
      stat[2][ptbin]->SetFillColor(kWhite);
      cClone->Scale((1.-p21[ptbin])*p20[ptbin]); bClone->Scale(p20[ptbin]*p21[ptbin]); // scale by contribution param
      cClone->Add(bClone);
      // cClone->Scale(dClone->GetMaximum()/cClone->GetMaximum());
      dClone->GetXaxis()->SetRangeUser(anaConst::lowPhi,anaConst::highPhi);
      dClone->GetYaxis()->SetRangeUser(-0.1,0.4);
      dClone->Draw();
      cClone->Draw("same");
      stat[2][ptbin]->Draw("same");
      lbl[ptbin]->Draw("same");

      cout << "!!!!!!! HT0&2 ptbin: " <<  highpt[ptbin] << "-" << lowpt[ptbin] <<" !!!!!!!"<< endl;
      fitResultC->cd(ptbin+1);
      currentPtBin = ptbin;
      TMinuit *gCMinuit=new TMinuit(2); //initialize TMinuit with a maximum of 3 params
      gCMinuit->SetMaxIterations(50000);
      gCMinuit->SetFCN(chi2_C);
      arglist[0]=1; //error definition: chi^2 change by 1 to get 1 sigma
      gCMinuit->mnexcm("SET ERR",arglist,1,ierflg);

      //starting values
      double vstartC[2]={0.3,1}; //frac
      double stepC[2]={0.01,0.01}; //starting step
      gCMinuit->mnparm(0,"BtoNPE frac",vstartC[0],stepC[0],0.000,2,ierflg);
      gCMinuit->mnparm(1,"Scale Factor",vstartC[1],stepC[1],0.000,2,ierflg);
      //simple scan to get better start values
      gCMinuit->mnexcm("SCAN",arglist,0,ierflg); 
      cout<<"done with first scan!"<<endl;

      //minimization
      arglist[0]=5000; //maxcalls
      arglist[1]=0.5; // tolerance = 0.001*[this value]*[error def] //5.0 before
      gCMinuit->mnexcm("MINIMIZE",arglist,2,ierflg);

      cout<< "done with fit! Error Flag: " << ierflg << endl;

       //fit results
      TString *str4 = new TString("BtoNPE frac");
      TString *str5 = new TString("Scale Factor");
      gCMinuit->mnpout(0,*str4,pC1[ptbin],eC1[ptbin],dum1,dum2,ierflg);
      gCMinuit->mnpout(1,*str5,pC0[ptbin],eC0[ptbin],dum1,dum2,ierflg);

      cout << endl << endl << "HTC PT Bin: " << lowpt[ptbin] << "-" << highpt[ptbin] << endl
	   << "rB: " << pC1[ptbin] << " rC: " << pC0[ptbin] << endl
	   << "erB: " << eC1[ptbin] << " erC: " << eC0[ptbin] << endl << endl;

      //Print results
      gCMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
      gCMinuit->mnprin(4,amin);
      
      // assign to plotting variables
      pT[ptbin] = (lowpt[ptbin]+highpt[ptbin])/2.;
      RbC[plotCount] = pC1[ptbin];///(p21[ptbin]+p20[ptbin]);
      ebC[plotCount] = eC1[ptbin];
      plotCount++;
    }

  // Get FONLL Calc
  Int_t l=0;
  char line[1000];
  Float_t xF[100],yF[100],minF[100],maxF[100];
  ifstream fp("/Users/zach/Research/pythia/ptHatTemplate/FONLL.txt",ios::in);
  while (!fp.eof()){
    fp.getline(line,1000);
    sscanf(line,"%f %f %f %f",&xF[l],&yF[l],&minF[l],&maxF[l]);
    //  printf("L: %f %f\n",xF[l],yF[l]);
    l++;
  }
  fp.close();

  // Get Previous Analysis 
  Int_t p=0;
  Float_t xP[100],yP[100],dyP[100];
  ifstream fp1("/Users/zach/Research/pythia/ptHatTemplate/run5_6.txt",ios::in);
  while (!fp1.eof()){
    fp1.getline(line,1000);
    sscanf(line,"%f %f %f",&xP[p],&yP[p],&dyP[p]);
    // printf("L: %f %f\n",xF[l],yF[l]);
    p++;
  }
  fp1.close();

  //cout << "at bottom contrib plot" << endl;
  TCanvas* c1 = new TCanvas("c1","Bottom Contribution",150,0,1150,1000);
  TGraphErrors *gr0     = new TGraphErrors(plotCount0-1,ptOFF1,Rb0,dx,eb0);
  TGraphErrors *gr2     = new TGraphErrors(plotCount2-1,ptOFF2,Rb2,dx,eb2);
  TGraphErrors *grC     = new TGraphErrors(plotCount-1,pT,RbC,dx,ebC);
  TGraphErrors *grF     = new TGraphErrors(l-1,xF,yF);
  TGraphErrors *grFmax  = new TGraphErrors(l-1,xF,maxF);
  TGraphErrors *grFmin  = new TGraphErrors(l-1,xF,minF);
  TGraphErrors *grP     = new TGraphErrors(p-1,xP,yP,0,dyP);

  c1->cd(1);

  gr0->SetTitle("Bottom Contribution");
  gr0->GetXaxis()->SetTitle("p_{T,e}");
  gr0->GetYaxis()->SetTitle("#frac{r_{B}}{(r_{B}+r_{C})}");
  gr0->SetMarkerStyle(20);
  gr0->SetMarkerSize(1);
  gr0->SetLineColor(kBlue);
  gr0->SetMarkerColor(kBlue);
  gr2->SetMarkerStyle(22);
  gr2->SetMarkerSize(1);
  gr2->SetLineColor(kRed);
  gr2->SetMarkerColor(kRed);
  grC->SetMarkerStyle(21);
  grC->SetMarkerSize(1);
  grC->SetLineColor(kRed);
  grC->SetMarkerColor(kRed);
  gr0->GetXaxis()->SetLimits(1,14);
  gr0->GetYaxis()->SetRangeUser(0,1);
  grF->SetLineStyle(1);
  grFmax->SetLineStyle(2);
  grFmin->SetLineStyle(2);
  grP->SetMarkerStyle(33);
  grP->SetMarkerColor(kBlack);
  
  
  gr0->Draw("AP");
  // grC->Draw("same P");
  gr2->Draw("same P");
  grF->Draw("same");
  grFmax->Draw("same");
  grFmin->Draw("same");
  grP->Draw("same P");

  TLegend* leg2 = new TLegend(0.15,0.68,0.4,0.85);
  leg2->AddEntry(gr0,"High Tower 0 Trigs","pe");
  leg2->AddEntry(gr2,"High Tower 2 Trigs","pe");
  // leg2->AddEntry(grC,"Combined Trigs","pe");
  leg2->AddEntry(grF,"FONLL (Uncertainty: Scale Only)","l");
  leg2->AddEntry(grP,"Run 5/6 Analysis (Stat Uncertainty)","pe");
  leg2->Draw("same");
  
   // Make PDF with output canvases
  if(makePDF)
    {
      //Set front page
      TCanvas* fp = new TCanvas("fp","Front Page",100,0,1000,900);
      fp->cd();
      TBox *bLabel = new TBox(0.01, 0.88, 0.99, 0.99);
      bLabel->SetFillColor(38);
      bLabel->Draw();
      TLatex tl;
      tl.SetNDC();
      tl.SetTextColor(kWhite);
      tl.SetTextSize(0.033);
      char tlName[100];
      char tlName2[100];
      
      TString titlename = FileName;
      int found = titlename.Last('/');
      if(found >= 0){
	titlename.Replace(0, found+1, "");
      } 
      sprintf(tlName, "RUN 12 NPE-h   #Delta#phi Correlations");
      tl.SetTextSize(0.05);
      tl.SetTextColor(kWhite);
      tl.DrawLatex(0.05, 0.92,tlName);
      
      TBox *bFoot = new TBox(0.01, 0.01, 0.99, 0.12);
      bFoot->SetFillColor(38);
      bFoot->Draw();
      tl.SetTextColor(kWhite);
      tl.SetTextSize(0.05);
      tl.DrawLatex(0.05, 0.05, (new TDatime())->AsString());
      tl.SetTextColor(kBlack);
      tl.SetTextSize(0.03);
      tl.DrawLatex(0.1, 0.14, titlename);
      sprintf(tlName,"TEST");
      tl.DrawLatex(0.1, 0.8,tlName);
      
      // Place canvases in order
      TCanvas* temp = new TCanvas();
      sprintf(name, "FFOutput/%s.pdf[", FileName);
      temp->Print(name);
      sprintf(name, "FFOutput/%s.pdf", FileName);

      temp = deltaPhi; 
      temp->Print(name);
      temp = fitResult0;
      temp->Print(name);
      temp = fitResult2;
      temp->Print(name);
      temp = fitResultC;
      temp->Print(name);
      temp = c1;
      temp->Print(name);
      
      sprintf(name, "FFOutput/%s.pdf]", FileName);
      temp->Print(name);
    }
}
コード例 #29
0
ファイル: paracoor.C プロジェクト: CMSAachen3B/RWTH3b
void paracoor( TString fin = "TMVA.root", Bool_t useTMVAStyle = kTRUE )
{
   // set style and remove existing canvas'
   TMVAGlob::Initialize( useTMVAStyle );

   // checks if file with name "fin" is already open, and if not opens one
   TFile* file = TMVAGlob::OpenFile( fin );  
   TTree* tree = (TTree*)file->Get("TestTree");
   if(!tree) {
      cout << "--- No TestTree saved in ROOT file. Parallel coordinates will not be plotted" << endl;
      return;
   }

   // first get list of leaves in tree
   TObjArray* leafList = tree->GetListOfLeaves();
   vector<TString> vars;
   vector<TString> mvas;   
   for (Int_t iar=0; iar<leafList->GetSize(); iar++) {
      TLeaf* leaf = (TLeaf*)leafList->At(iar);
      if (leaf != 0) {
         TString leafName = leaf->GetName();
         if (leafName != "type" && leafName != "weight"  && leafName != "boostweight" &&
             leafName != "class" && leafName != "className" && leafName != "classID" && 
             !leafName.Contains("prob_")) {
            // is MVA ?
            if (TMVAGlob::ExistMethodName( leafName )) {
               mvas.push_back( leafName );
            }
            else {
               vars.push_back( leafName );
            }
         }
      }
   }

   cout << "--- Found: " << vars.size() << " variables" << endl;
   cout << "--- Found: " << mvas.size() << " MVA(s)" << endl;
   

   TString type[2] = { "Signal", "Background" };
   const Int_t nmva = mvas.size();
   TCanvas* csig[nmva];
   TCanvas* cbkg[nmva];
   for (Int_t imva=0; imva<mvas.size(); imva++) {
      cout << "--- Plotting parallel coordinates for : " << mvas[imva] << " & input variables" << endl;

      for (Int_t itype=0; itype<2; itype++) {

         // create draw option
         TString varstr = mvas[imva] + ":";
         for (Int_t ivar=0; ivar<vars.size(); ivar++) varstr += vars[ivar] + ":";
         varstr.Resize( varstr.Last( ':' ) );

         // create canvas
         TString mvashort = mvas[imva]; mvashort.ReplaceAll("MVA_","");
         TCanvas* c1 = (itype == 0) ? csig[imva] : cbkg[imva];
         c1 = new TCanvas( Form( "c1_%i",itype ), 
                           Form( "Parallel coordinate representation for %s and input variables (%s events)", 
                                 mvashort.Data(), type[itype].Data() ), 
                           50*(itype), 50*(itype), 750, 500 );      
         tree->Draw( varstr.Data(), Form("classID==%i",1-itype) , "para" );
         c1->ToggleEditor();
         gStyle->SetOptTitle(0);

         TParallelCoord*    para   = (TParallelCoord*)gPad->GetListOfPrimitives()->FindObject( "ParaCoord" );
         TParallelCoordVar* mvavar = (TParallelCoordVar*)para->GetVarList()->FindObject( mvas[imva] );
         Double_t minrange = tree->GetMinimum( mvavar->GetName() );
         Double_t maxrange = tree->GetMaximum( mvavar->GetName() );
         Double_t width    = 0.2*(maxrange - minrange);
         Double_t x1 = minrange, x2 = x1 + width;
         TParallelCoordRange* parrange = new TParallelCoordRange( mvavar, x1, x2 );
         parrange->SetLineColor(4);
         mvavar->AddRange( parrange );

         para->AddSelection("-1");

         for (Int_t ivar=1; ivar<TMath::Min(Int_t(vars.size()) + 1,3); ivar++) {
            TParallelCoordVar* var = (TParallelCoordVar*)para->GetVarList()->FindObject( vars[ivar] );
            minrange = tree->GetMinimum( var->GetName() );
            maxrange = tree->GetMaximum( var->GetName() );
            width    = 0.2*(maxrange - minrange);

            switch (ivar) {
            case 0: { x1 = minrange; x2 = x1 + width; break; }
            case 1: { x1 = 0.5*(maxrange + minrange - width)*0.02; x2 = x1 + width*0.02; break; }
            case 2: { x1 = maxrange - width; x2 = x1 + width; break; }
            }

            parrange = new TParallelCoordRange( var, x1, x2 );
            parrange->SetLineColor( ivar == 0 ? 2 : ivar == 1 ? 5 : 6 );
            var->AddRange( parrange );

            para->AddSelection( Form("%i",ivar) );
         }

         c1->Update();

         TString fname = Form( "plots/paracoor_c%i_%s", imva, itype == 0 ? "S" : "B" );
         TMVAGlob::imgconv( c1, fname );
      }
   }
}
コード例 #30
0
ファイル: MERGE.C プロジェクト: aashaqshah/cmssw-1
void merge(TString outfile, TString firstfile, TString pat=defaultPattern)
{
        TList   decayModes;
	bool    save=false;
        TString dir=".";
	TString first="";
	long    flags=0,id=0,size=0,modtime=0;
	if(firstfile.Contains("~"))
	{
		cout<<"ERROR: input path cannot contain '~' character."<<endl;
		return;
	}
	// Check pattern
	TRegexp pattern(pat,true);
	if(pattern.Status()!=0)
	{
		cout<<"ERROR: Wrong regular expression."<<endl;
		return;
	}
	// Load libraries
        loadLibs();
	gSystem->GetPathInfo(firstfile, &id, &size, &flags, &modtime);
	bool isDirectory = flags&2;
	if(isDirectory)
	{
		dir=firstfile;
		first="";
	}
	else
	{
		//Separate directory from filename
		int separator=firstfile.Last('/');
		if(separator!=-1) dir=firstfile(0,separator+1);
		first=firstfile(separator+1,firstfile.Length());
	}
	cout<<"Output file: "<<outfile<<endl;
	cout<<"Input  dir:  "<<dir<<endl;
	if(!isDirectory) cout<<"First  file: "<<first<<endl;
	cout<<endl;
	// Get file list and add first file if present
        TList *files = getFileList(first,dir,pattern);
	if(!isDirectory)
	{
		TFile *ff = new TFile(firstfile,"READ");
		files->AddBefore(files->First(),ff);
	}
	// Merge files
	TIter next(files);
	TFile *file;
        while(file = (TFile*)next())
        {
		if(!file->IsOpen()) continue;
                ReadFile(file,decayModes);
                cout<<"=============================="<<endl;
                save=true;
        }
	// Save output
        if(save)
	{
		cout<<"Saving..."<<endl;
		SaveOutput(outfile,decayModes);
		cout<<"Output saved to "<<outfile<<endl<<endl;
	}
	else    cout<<"Nothing to save."<<endl<<endl;
	// Closing files
	cout<<"Closing files..."<<endl;
	TIter cl(files);
        while(file = (TFile*)cl()) { file->Close(); delete file; }
	delete files;
	gSystem->Exit(0);
}