Ejemplo n.º 1
0
void cmpLRD(TFile* f1, TFile* f2, const char* dName, const char* patt = 0, unsigned int logmod=0, unsigned int dOpt=1){
  //  std::cout<<"cmpLRD In "<< dName<<std::endl;
  TDirectory* td = gROOT->GetDirectory(dName);
  if (td){
    TList* tkl = td->GetListOfKeys();
    unsigned int tklSize = tkl->GetEntries();
    //    std::cout<<"\t size "<<tklSize<<std::endl;
    for (unsigned int iK=0; iK< tklSize; ++iK){
      //      std::cout<<"at "<<iK<<"\t " <<tkl->At(iK)->GetName()<<std::endl;
      if (TClass(((TKey*)tkl->At(iK))->GetClassName()).InheritsFrom("TDirectory")){
	TDirectory* tdc = (TDirectory*)((TKey*)tkl->At(iK))->ReadObj();
	if (tdc ==0) continue;
	TString tdcPFull(tdc->GetPath());
	TString pRel(tdcPFull.Tokenize(":")->At(1)->GetName());
	//	std::cout<<tdcPFull.Data()<<std::endl;
	
	//now execute compare 
	//	if(pRel.Index("/SiStrip/")>=0) continue; //this takes a huge time in alcareco and is irrelevant
	///DQMData/Run 1/Btag
	if (patt==0 || (patt!=0 && pRel.Index(patt)>=0)){
	  //	  std::cout<<"Comparing in " <<pRel.Data()<<std::endl;
	  compareInDir(f1, f2, pRel.Data(),logmod,dOpt);
	}
	cmpLRD(f1, f2, tdcPFull.Data(), patt,logmod,dOpt);
      }
    }
  }
}
Ejemplo n.º 2
0
void
Pick(Int_t canvas_index)
{
  TObject *o;
  TCanvas* c = ((TCanvas*) gROOT->GetListOfCanvases()->At(canvas_index));
  c->cd();
  // std::cout << "______PICKED______\n\t" 
  // 	  << c->GetName() << " canvas_index=" << canvas_index << std::endl;
  //  ((TCanvas*) gROOT->GetListOfCanvases()->At(canvas_index))->cd();
  

  TList *ll = toolcanvas->GetListOfPrimitives();
  // std::cout << ll->GetEntries() << std::endl;
  for (Int_t ii=ll->GetEntries()-1; ii>=0; ii--)
    {
      o = ll->At(ii);
      // std::cout << ii << " removing " << ll->At(ii)->GetName() << std::endl;
      ll->Remove(o);
    }

  toolcanvas->cd();
  toolcanvas->SetWindowSize(toolw-28, toolh-8);
  //  toolcanvas->SetCanvasSize(toolw, toolh);
  pt->Draw();
  toolcanvas->Modified();
  toolcanvas->Update();
  canvas = ((TCanvas*) gROOT->GetListOfCanvases()->At(canvas_index));
  //Enlarge();
  SelectPad();
}
Ejemplo n.º 3
0
void rdphi::Terminate()
{
//cout << "total event: " << NevtAll << "rejected: " << rejected_events << endl; 

  TFile *f = new TFile("output.root","RECREATE");

  //Write output Histograms
  TList *tl = GetOutputList();
  int l = tl->GetEntries();
  for ( int i = 0 ; i < l ; i++ )
  {
    TObject *o = tl->At(i);

    if ( o->InheritsFrom("TH1") )
    {
      cout << "TresChorros: Saving Histogram: "
          << "  Class: " << o->ClassName()  
          << "  Name: "<< o->GetName() 
          << "  Title: " << o->GetTitle()
          << " " 
          << endl << flush;
      o->Write();
    }
    }
  f->Flush();
  f->Close();  

}
Ejemplo n.º 4
0
void
SelectPad()
{
  notDeleted = kTRUE;

  toolcanvas->cd();
  // Clear buttons from toolcanvas
  TObject *o;
  TList *ll = toolcanvas->GetListOfPrimitives();
  for (Int_t ii=ll->GetEntries()-1; ii>=0; ii--)
    {
      o = ll->At(ii);
      ll->Remove(o);
    }

  Double_t buttonheight = 50;
  TList *li = canvas->GetListOfPrimitives();
  Int_t nentries = li->GetEntries();

  if (nentries==1)
    return;

  toolcanvas->SetWindowSize(toolw,(nentries+1)*buttonheight);
  toolcanvas->Modified();
  toolcanvas->Update();

  pt->SetY1NDC(1.0-1.0/(nentries+1));
  pt->Draw();

  toolcanvas->Update();


  //  toolcanvas->cd();
  if (b) {delete b;}
  
  Int_t count=0;
  b = new TObjArray(nentries);
  for (Int_t i=0; i<nentries; i++)
    {
      b->Add(new TButton(Form("pad%i",i+1),Form("Enlarge(%i);",i),0,(1-(count+1.)/(nentries+1)),1,(1-(count+2.)/(nentries+1))));
      b->At(i)->Draw();
      count++;
    }
  toolcanvas->Modified();
  toolcanvas->Update();
  //  if (display) {display->Modified(); display->Update();}
}
Ejemplo n.º 5
0
void MakeCutLog(const char *inputRootFile = "AnalysisResults",const char *path = "./", const char* outputDir="./Output/"){

  fstream outputFile(Form("%sCutSelection.log",outputDir),ios::out);
  if(!outputFile.is_open()){
    cout<<"Problem opening file"<<endl;
    return;
  }

  //  Char_t filename_input1[200] = (Form("%s%s",path,input1));	
  TString filename = Form("%s%s.root",path,inputRootFile);	
  TFile f(filename.Data());  

  TList *directories = f.GetListOfKeys(); // get the list of directories in the file
  
  for(Int_t entFile=0;entFile<directories->GetEntries();entFile++){

    TObject * o = f.Get(directories->At(entFile)->GetName()); // get the object in the base directory

    if(TString(o->IsA()->GetName())=="TDirectoryFile"){ // means that this is a directory (PWGGA......)
      
      TDirectory *pwg4dir =(TDirectory*)o;
 
      TString baseDirName = pwg4dir->GetName();
      
      TString reconstructionFlagString = ""; // this is for new scheme where also the flags are coded in numbers in the PWGGA.... name

      if(baseDirName.Length()>31){
	reconstructionFlagString = baseDirName(baseDirName.Index("GammaConversion_")+16,8);
      }
      
      TList *pwg4list = pwg4dir->GetListOfKeys(); // list of the yeys inside the base directory

      for(Int_t entHist=0;entHist<pwg4list->GetEntries();entHist++){
	TString name = pwg4list->At(entHist)->GetName();

	if(name.Contains("container")==0){ // does not try to read the container (get errors if tried)
	  TObject * oHist = pwg4dir->Get(pwg4list->At(entHist)->GetName()); // get the object 
	  
	  if(TString(oHist->IsA()->GetName())=="TList"){ // check if the object is a TList
	    
	    TString listname = oHist->GetName();
	    cout<<"Reading: "<<listname.Data()<<endl;
	    
	    TString cutString = listname(listname.Index("_")+1,listname.Length()) + "\n";// get the Cut string from the name


	    outputFile << cutString.Data();
	  }
	}
      }
    }
  }
  outputFile.close();
}
Ejemplo n.º 6
0
void RootWImage::saveSummaryLoop(TPad* basePad, std::string baseName, TFile* myTargetFile) {
  TList* aList;
  TObject* anObject;
  TPad* myPad;
  std::string myClass;
  std::string myName;

  TNamed* aNamed;

  // TSystemFile* aFile;
  // string aFileName;
  // string aFileNameTail;
  // TFile* myRootFile;

  aList = basePad->GetListOfPrimitives();
  for (int i=0; i<aList->GetEntries(); ++i) {
    anObject = aList->At(i);
    myClass = anObject->ClassName();
    if (myClass=="TPad") { // Go one step inside
      myPad = (TPad*) anObject;
      saveSummaryLoop(myPad, baseName, myTargetFile);
    } else if (
	       (myClass=="TProfile") ||
	       (myClass=="TGraph") ||
	       (myClass=="TH1D") ||
	       (myClass=="TH2C") ||
	       (myClass=="TH2D") ||
	       (myClass=="THStack") 
	       ) {
      aNamed = (TNamed*) anObject;
      myTargetFile->cd();
      myName = Form("%s.%s", baseName.c_str(), aNamed->GetName());
      myName = RootWeb::cleanUpObjectName(myName);
      aNamed->SetName(myName.c_str());
      aNamed->Write();
    } else if (
	       (myClass=="TEllipse") ||
	       (myClass=="TFrame") ||
	       (myClass=="TLatex") ||
	       (myClass=="TLegend") ||
	       (myClass=="TLine") ||
	       (myClass=="TPaveText") ||
	       (myClass=="TPolyLine") ||
	       (myClass=="TText") 
	       ) {
    } else {
      std::cerr << Form("Unhandled class %s", myClass.c_str()) << std::endl;
    }
  }
}
Ejemplo n.º 7
0
// A macro to print out a TLegend - can be considered a smarter TLegend::ls().
// If no TLegend pointer is passed, it loops over the TLegends drawn on current TPad.
void PrintLegend(TLegend *leg=0) {
  if ( leg==0 ) {
    if (gROOT->GetListOfCanvases()->GetEntries()==0) return;
    TList *padprim = gPad->GetListOfPrimitives();
    for (int i=0; i<padprim->GetEntries(); i++) {
      TObject *myobj = gROOT->FindObject(padprim->At(i)->GetName());
      if ( myobj != 0 && myobj->InheritsFrom("TLegend") )
	PrintLegend((TLegend*)myobj); }
    return;
  }
  TList *ents = leg->GetListOfPrimitives();
  for (int i=0; i<ents->GetEntries(); i++) {
    TLegendEntry *le = (TLegendEntry*)ents->At(i);
    TString s( le->GetLabel() );
    TObject *obj = le->GetObject();
    if (!obj) continue;  // if no object, this can be the title line, so skip
    TString color = "???";
    if ( obj->InheritsFrom("TH1") )
      color = gROOT->GetListOfColors()->At(((TH1*)obj)->GetLineColor())->GetName();
    cout << "Item ";  cout.width(2); cout.fill('0'); cout << i << " plotted in ";
    cout.width(7); cout.fill(' '); cout << color << " : " << s << endl;
  }
  //leg->ls();
}
Ejemplo n.º 8
0
///////////////////////////////
// Return matching key names
SEXP namesMatchingClass(SEXP fileForHists, SEXP directoryR, SEXP classTypeR)
{
  TFile* f = checkForFileForHistsWrapper(fileForHists);

  const char* oldDirectory = setFileDirectory(f, directoryR);

  // Get the class type
	std::string classType = CHAR( STRING_ELT(classTypeR, 0) );
  
  // Keep track of the ones we want
  std::vector<const char*> names;
  std::vector<int> cycles;
  
  // Loop over keys in this directory -- pull out names and cycles for classes
  // that match the ones we want.
  TList* l = gDirectory->GetListOfKeys();
  for ( unsigned int i = 0; i < l->GetEntries(); ++i ) {
    TKey* k = (TKey*) l->At(i);
    if ( strcmp( k->GetClassName(), classType.c_str() ) == 0 ) {
      names.push_back( k->GetName() );
      cycles.push_back( k->GetCycle() );
    }
  }

  // Now we loop over the vectors to get the list of names
  SEXP rNames;
  PROTECT( rNames = NEW_CHARACTER( names.size() ) );

  for ( unsigned int i = 0; i < names.size(); ++i ) {
    // Form the string
    char buf[BUFSIZE];
    snprintf(buf, BUFSIZE, "%s;%d", names[i], cycles[i]);
    
    // Save this away
    SET_STRING_ELT( rNames, i, mkChar( buf ) );
  }

  UNPROTECT(1);

  // Restore the old directory
  if ( ! f->cd(oldDirectory) ) {
    error("namesMatchingClass: cd to old directory failed");
  }
  
  return rNames;
}
Ejemplo n.º 9
0
void KVNameValueList::ClearSelection(TRegexp& sel)
{
   // Remove from list all parameters whose name matches the regular expression
   // Examples:
   //  remove all parameters starting with "toto": TRegexp sel("^toto")
   //  remove all parameters with "toto" in name:  TRegexp sel("toto")

   TList toBeRemoved;
   Int_t np1 = GetNpar();
   for (Int_t ii = 0; ii < np1; ii += 1) {
      TString name = GetParameter(ii)->GetName();
      if (name.Contains(sel)) toBeRemoved.Add(new TNamed(name.Data(), ""));
   }
   if (toBeRemoved.GetEntries()) {
      TIter next(&toBeRemoved);
      TNamed* tbr;
      while ((tbr = (TNamed*)next())) RemoveParameter(tbr->GetName());
      toBeRemoved.Delete();
   }
}
void AnalyzeClipping(TString inputWaveName = "sum trigger input ch5 960mV",
TString outputWaveName = "sum trigger output ch5 - 2V clip - 960mV input", 
Double_t inputDelay = 1.1E-8, Double_t lowerCut = 16E-9, Double_t upperCut = 23E-9,
const char *inFile = "Data.root",const char *WaveformsFile = "Waveforms.root") {
	
	//try to access data file and in case of failure return
	if(gSystem->AccessPathName(inFile,kFileExists)) {
		cout << "Error: file " << inFile << " does not exsist. Run .x DataParse.C to create it" << endl;
		return;
	}

	TFile *f = TFile::Open(inFile);
	TFolder *dataSet;
	
	TString dataFolderS = "SumTriggerBoardData";
	dataFolderS.Append(";1");

	dataSet = (TFolder*)f->Get(dataFolderS);
	
	cout << dataSet << endl;

	cout << dataSet->GetName() << endl;
	
	Int_t nScope = 150; // number of measurements done by the scope evey time
	
	//try to access waveforms file and in case of failure return
	if(gSystem->AccessPathName(WaveformsFile,kFileExists)) {
		cout << "Error: file " << WaveformsFile << " does not exsist. Run .x WaveformsFileMaker.C to create it" << endl;
		return;
	}
	
	TFile *f = TFile::Open(WaveformsFile);
	TList *listOfKeys = f->GetListOfKeys();
	Int_t numberOfKeys = listOfKeys->GetEntries();
	TList *listOfGraphs = new TList();
	
	// if the waveform file name begins with the string "comparator" it goes in this list
	TList *listOfCompWaves = new TList();
	// if the waveform file name begins with the string "sum output" it goes in this list
	TList *listOfAdderWaves = new TList();

	for(Int_t i = 0; i < numberOfKeys; i++) {
		TString *keyName = new TString(listOfKeys->At(i)->GetName());
		TTree *tree = (TTree*)f->Get(keyName->Data());
		Float_t x = 0;
		Float_t y = 0;
		tree->SetBranchAddress("x",&x);
		tree->SetBranchAddress("y",&y);
		Int_t nentries = tree->GetEntries();

		TString *gName = new TString(keyName->Data());
		gName->Append(" graph");
		TGraphErrors *gWave = new TGraphErrors(nentries);
		gWave->SetName(gName->Data());
		gWave->SetTitle(gName->Data());
		gWave->GetXaxis()->SetTitle("Time");
		gWave->GetYaxis()->SetTitle("Voltage");

		for (Int_t j = 0; j < nentries; j++) {
			tree->GetEntry(j);
			gWave->SetPoint(j,x,y);
		}

		listOfGraphs->Add(gWave);
	}
	
	// Global variables
	
	Double_t *xInput, *xOutput, *yInput, *yOutput;
	
	// V input 960 mV
	
	TString path = "Clipping/Output width analysis/Channel 5/V input 960mV/";
	
	TGraphErrors *gClip960mV = TBGraphErrors(dataSet,path,"V clip","Output FWHM",1,nScope);
	
	gClip960mV->SetMarkerStyle(20);
	gClip960mV->SetMarkerSize(0.8);
	gClip960mV->GetXaxis()->SetTitle("V clipping (mV)");
	gClip960mV->GetYaxis()->SetTitle("Output FWHM (ns)");
	
	TCanvas *cClip960mV = new TCanvas("cClip960mV","Output FWHM in function of V clipping",800,600);
	gClip960mV->Draw("APEL");
	
	// Expected output FWHM
	
	TGraphErrors *gInput960mV = listOfGraphs->FindObject("sum trigger input ch5 960mV graph");
	
	Double_t *xClip = gClip960mV->GetX();
	Int_t nClip = gClip960mV->GetN();
	cout << "nClip = " << nClip << endl;
	Long64_t graphPoints = gInput960mV->GetN();
	yInput = gInput960mV->GetY();
	xInput = gInput960mV->GetX();
	
	vector<double> xFirst(nClip);
	vector<double> xLast(nClip);
	Double_t half;
	
	Int_t flag = 0;
	
	vector<double> yConv(graphPoints);
	for(Int_t i = 0; i < graphPoints; i++) {
		yConv[i] = -(yInput[i]);
		yConv[i] *= 1000;
		if(xInput[i] + inputDelay < lowerCut || xInput[i] + inputDelay > upperCut) 
			yConv[i] = 0;
	}
	
	Double_t yInput960mVMax = TMath::MaxElement(graphPoints,&yConv[0]);
	
	for(Int_t i = 0; i < nClip; i++) {
		if(xClip[i] > yInput960mVMax) half = yInput960mVMax;
		else half = xClip[i];
		
		half /=2;
		cout << half << endl;
		
		flag = 0;
		
		for(Int_t j = 0; j < graphPoints - 3; j++) {
			if((yConv[j + 1] - half)*(yConv[j] - half) < 0 && flag == 0) {
				xFirst[i] = xInput[j];
				flag = 1;
				cout << "found first point! " << xFirst[i] << endl;
				continue;
			}
			if((yConv[j + 1] - half)*(yConv[j] - half) < 0 && flag == 1) {
				xLast[i] = xInput[j];
				cout << "found last point! " << xLast[i] << endl;
				break;
			}
		}
	}
	
	vector<double> expectedFWHM960mV(nClip);
	for(Int_t i = 0; i < expectedFWHM960mV.size(); i++) {
		expectedFWHM960mV[i] = xLast[i] - xFirst[i];
		// convert from seconds to nanoseconds
		expectedFWHM960mV[i] *= 10E8;
		cout << "expectedFWHM960mV[" << i << "] = " << expectedFWHM960mV[i] << endl;
	}
	
	// expected FWHM 960 mV graph
	
	TGraphErrors *gExpClip960mV = new TGraphErrors(nClip,xClip,&expectedFWHM960mV[0],0,0);
	gExpClip960mV->SetLineStyle(7);
	gExpClip960mV->SetMarkerStyle(20);
	gExpClip960mV->SetMarkerSize(0.8);
	
	// V input 1.9 V
	
	path = "Clipping/Output width analysis/Channel 5/V input 1.9V/";
	
	TGraphErrors *gClip1Point9V = TBGraphErrors(dataSet,path,"V clip","Output FWHM",1,nScope);
	
	gClip1Point9V->SetMarkerStyle(20);
	gClip1Point9V->SetMarkerSize(0.8);
	gClip1Point9V->SetLineColor(kRed);
	gClip1Point9V->GetXaxis()->SetTitle("V clipping (mV)");
	gClip1Point9V->GetYaxis()->SetTitle("Output FWHM (ns)");
	TCanvas *cClip1Point9V = new TCanvas("cClip1Point9V","Output FWHM in function of V clipping",800,600);
	gClip1Point9V->Draw("APEL");
	
	// Expected output FWHM
	
	TGraphErrors *gInput1Point9V = listOfGraphs->FindObject("sum trigger input ch5 1900mV graph");
	
	xClip = gClip1Point9V->GetX();
	nClip = gClip1Point9V->GetN();
	cout << "nClip = " << nClip << endl;
	graphPoints = gInput1Point9V->GetN();
	yInput = gInput1Point9V->GetY();
	xInput = gInput1Point9V->GetX();
	
	vector<double> xFirst(nClip);
	vector<double> xLast(nClip);
	
	flag = 0;
	
	vector<double> yConv(graphPoints);
	for(Int_t i = 0; i < graphPoints; i++) {
		yConv[i] = -(yInput[i]);
		yConv[i] *= 1000;
		if(xInput[i] + inputDelay < lowerCut || xInput[i] + inputDelay > upperCut) yConv[i] = 0;
	}
	
	Double_t yInput1Point9VMax = TMath::MaxElement(graphPoints,&yConv[0]);
	
	for(Int_t i = 0; i < nClip; i++) {
		if(xClip[i] > yInput1Point9VMax) half = yInput1Point9VMax;
		else half = xClip[i];
		
		half /= 2;
		cout << half << endl;
		
		flag = 0;
		
		for(Int_t j = 0; j < graphPoints - 3; j++) {
			if((yConv[j + 1] - half)*(yConv[j] - half) < 0 && flag == 0) {
				xFirst[i] = xInput[j];
				flag = 1;
				cout << "found first point! " << xFirst[i] << endl;
				continue;
			}
			if((yConv[j + 1] - half)*(yConv[j] - half) < 0 && flag == 1) {
				xLast[i] = xInput[j];
				cout << "found last point! " << xLast[i] << endl;
				break;
			}
		}
	}
	
	vector<double> expectedFWHM1Point9V(nClip);
	for(Int_t i = 0; i < expectedFWHM1Point9V.size(); i++) {
		expectedFWHM1Point9V[i] = xLast[i] - xFirst[i];
		// convert from seconds to nanoseconds
		expectedFWHM1Point9V[i] *= 10E8;
		cout << "expectedFWHM1Point9V[" << i << "] = " << expectedFWHM1Point9V[i] << endl;
	}
	
	// expected FWHM 960 mV graph
	
	TGraphErrors *gExpClip1Point9V = new TGraphErrors(nClip,xClip,&expectedFWHM1Point9V[0],0,0);
	gExpClip1Point9V->SetLineStyle(7);
	gExpClip1Point9V->SetLineColor(kRed);
	gExpClip1Point9V->SetMarkerStyle(20);
	gExpClip1Point9V->SetMarkerSize(0.8);
	
	// Collection of Output FWHM graphs, 2 amplitudes, serveral V clipping
	
	TMultiGraph *mgClipOutputFWHM = new TMultiGraph();
	mgClipOutputFWHM->SetTitle("Collection of Output FWHM graphs, 2 amplitudes, serveral V clipping");
	
	mgClipOutputFWHM->Add(gClip1Point9V);
	mgClipOutputFWHM->Add(gClip960mV);
	mgClipOutputFWHM->Add(gExpClip960mV);
	mgClipOutputFWHM->Add(gExpClip1Point9V);
	
	
	TCanvas *cmgClipOutputFWHM = new TCanvas("cmgClipOutputFWHM","Collection of Output FWHM graphs, 2 amplitudes, serveral V clipping");
	mgClipOutputFWHM->Draw("APEL");
	
	cmgClipOutputFWHM->Modified();
	mgClipOutputFWHM->GetXaxis()->SetTitle("V clipping (mV)");
	mgClipOutputFWHM->GetYaxis()->SetTitle("Output FWHM (ns)");
	cmgClipOutputFWHM->Update();
		
	legend = new TLegend(0.6,0.67,0.89,0.86,"V input");
	legend->AddEntry(gClip1Point9V, "1.9 V", "lp");
	legend->AddEntry(gClip960mV, "960 mV", "lp");
	legend->AddEntry(gExpClip960mV, "Exp 960 mV", "lp");
	legend->AddEntry(gExpClip1Point9V, "Exp 1.9 V", "lp");
	legend->SetTextSize(0.04);
	legend->SetMargin(0.5);
	legend->Draw();
	
	// Hysteresis plot: V output (t) in function of V input (t) for several clipping values
	
	// variables used in the analysis
	
	Long64_t iInputMax, iOutputMax;
	Float_t xInputMax, xOutputMax, xInputHalf, xOutputHalf;
	Double_t InputMax, OutputMax, InputHalf, OutputHalf;
	
	Long64_t firstIndex = 0;
	Long64_t lastIndex = 0;
	Long64_t inputGraphPoints = 0;
	Long64_t outputGraphPoints = 0;
	
	// hard coded values to cut the x axis of both waves
	// Input wave
	
	inputWaveName += " graph";
	
	TGraphErrors *gInput = listOfGraphs->FindObject(inputWaveName);
	gInput->SetLineColor(kRed);
	gInput->SetLineWidth(2);
	
	xInput = gInput->GetX();
	yInput = gInput->GetY();
	inputGraphPoints = gInput->GetN();
	
	cout << inputGraphPoints << endl;
	
	// Invert the input wave
	
	for(Int_t i = 0; i < inputGraphPoints; i++) {
		yInput[i] = -(yInput[i]);
	}
	
	// find the x at which the graph reaches the max value
	
	iInputMax = TMath::LocMax(inputGraphPoints, yInput);
	xInputMax = xInput[iInputMax];
	cout << "iInputMax = " << iInputMax << endl;
	cout << "xInputMax = " << xInputMax << endl;
	InputMax = gInput->Eval(xInput[iInputMax]);
	cout << "InputMax = " << InputMax << endl;
	
	// Output wave
	
	outputWaveName += " graph";
	
	TGraphErrors *gOutput = listOfGraphs->FindObject(outputWaveName);
	gOutput->SetLineWidth(2);
	
	xOutput = gOutput->GetX();
	yOutput = gOutput->GetY();
	outputGraphPoints = gOutput->GetN();
	
	// find the x at which the graph reaches the max value
	
	iOutputMax = TMath::LocMax(outputGraphPoints, yOutput);
	xOutputMax = xOutput[iOutputMax];
	cout << "iOutputMax = " << iOutputMax << endl;
	cout << "xOutputMax = " << xOutputMax << endl;
	OutputMax = gOutput->Eval(xOutput[iOutputMax]);
	cout << "OutputMax = " << OutputMax << endl;
	
	// compute x delay between max points
	
	Double_t delay = xOutputMax - xInputMax;
	cout << "delay = " << delay << endl;
	
	// Shift the x axis of the input graph and create a new graph with only a portion of the first graph
	
	for(Int_t i = 0; i < inputGraphPoints; i++) {
		xInput[i] += inputDelay;
		
		if(xInput[i] >= lowerCut) {
			if(firstIndex == 0) firstIndex = i;
		}

		if(xInput[i] <= upperCut)
			lastIndex = i;
	}
	
	cout << "firstIndex = " << firstIndex << endl;
	cout << "lastIndex = " << lastIndex << endl;
	cout << "xInput[firstIndex] = " << xInput[firstIndex] << endl;
	cout << lastIndex - firstIndex << endl;
	
	Long64_t input2GraphPoints = lastIndex - firstIndex;
	
	TGraphErrors *gInput2 = new TGraphErrors(input2GraphPoints);
	gInput2->SetTitle(inputWaveName);
	
	for(Int_t i = firstIndex; i <= lastIndex; i++) {
		gInput2->SetPoint(i - firstIndex,xInput[i],yInput[i]);
	}
	
	TCanvas *cgInput2 = new TCanvas("cgInput2", "cgInput2", 1200,800);
	gInput2->Draw("AL");
	
	// create a new graph with only a portion of the first graph
	
	firstIndex = 0;
	lastIndex = 0;
	
	for(Int_t i = 0; i < outputGraphPoints; i++) {
		if(xOutput[i] >= lowerCut) {
			if(firstIndex == 0) firstIndex = i;
		}

		if(xOutput[i] <= upperCut)
			lastIndex = i;
	}
	
	cout << "firstIndex = " << firstIndex << endl;
	cout << "lastIndex = " << lastIndex << endl;
	cout << "xOutput[firstIndex] = " << xOutput[firstIndex] << endl;
	cout << lastIndex - firstIndex << endl;
	
	Long64_t output2GraphPoints = lastIndex - firstIndex;
	
	TGraphErrors *gOutput2 = new TGraphErrors(output2GraphPoints);
	gOutput2->SetTitle(outputWaveName);
	
	for(Int_t i = firstIndex; i <= lastIndex; i++) {
		gOutput2->SetPoint(i - firstIndex,xOutput[i],yOutput[i]);
	}
	
	TCanvas *cgOutput2 = new TCanvas("cgOutput2", "cgOutput2", 1200,800);
	gOutput2->Draw("AL");
	
	// first hysteresis plot
	
	Double_t step;
	
	Double_t *xInput2;
	xInput2 = gInput2->GetX();
	
	cout << "xInput2[input2GraphPoints - 1] = " << xInput2[input2GraphPoints - 1] << endl;
	cout << "xInput2[0] = " << xInput2[0] << endl;
	
	step = (xInput2[input2GraphPoints - 1] - xInput2[0])/output2GraphPoints;
	
	cout << "step = " << step << endl;
	
	// in case gInput2 and gOutput2 contain a different number of points create the hysteresis plot with gOutput2 points
	// and modify the yInput2 to match the number of points of yOutput2
	
	vector<double> yInput2;
	
	for(Int_t i = 0; i < output2GraphPoints; i++) {
		yInput2.push_back(gInput2->Eval(xInput2[0] + i*step));
	}
	
	Double_t *yOutput2;
	yOutput2 = gOutput2->GetY();
	
	TGraphErrors *gHyst = new TGraphErrors(output2GraphPoints, &yInput2.at(0),yOutput2);
	gHyst->SetTitle("Hysteresis plot");
	
	gHyst->GetXaxis()->SetTitle("Vin(t) [mV]");
	gHyst->GetYaxis()->SetTitle("Vout(t) [mV]");
	gHyst->GetYaxis()->SetTitleOffset(1.4);
	
	TCanvas *cgHyst = new TCanvas("cgHyst", "cgHyst", 1200,800);
	cgHyst->SetLeftMargin(0.12);
	gHyst->Draw("AL");
	
	// collection of graphs
	
	TMultiGraph *mgInputOutput = new TMultiGraph();
	mgInputOutput->Add(gInput);
	mgInputOutput->Add(gOutput);
	mgInputOutput->SetTitle("Input and output");
	
	TCanvas *cmgInputOutput = new TCanvas("cmgInputOutput", "Input and output", 1200,800);
	mgInputOutput->Draw("AL");
	cmgInputOutput->Update();
	legend = new TLegend(0.65,0.68,0.86,0.86);
	legend->AddEntry(gInput, "Input", "lp");
	legend->AddEntry(gOutput, "Output", "lp");
	legend->SetMargin(0.4);
	legend->SetTextSize(0.04);
	legend->Draw();
	cmgInputOutput->Modified();

	
}
Ejemplo n.º 11
0
void addhistoEmc(const char* list="list.txt", char *newname=0)
{
    // Add histograms from a set of files listed in file list
    // and write the result into a new file.

    char SumName[20];

    if (!newname) {
        sprintf(SumName,"Sum_All_Emc.root");
        newname=SumName;
        printf("\n  === Default output file name is %s ===\n",newname);
    }

    TFile *f=NULL;
    TH1F* hst[5][64][56];
    TH1F* hadd=NULL;
    char hnam[80];
    char htit[80];
    TList* hlist = 0;

    char fpath[80];
    int ifscanf=0;
    Int_t ifile=0;

    for(Int_t iMod=0; iMod<5; iMod++) {
        for(Int_t iX=0; iX<64; iX++) {
            for(Int_t iZ=0; iZ<56; iZ++) {
                sprintf(hnam,"%d_%d_%d",iMod,iX,iZ);
                sprintf(htit,"Two-gamma inv. mass for mod %d, cell (%d,%d)",iMod,iX,iZ);
                hst[iMod][iX][iZ] = new TH1F(hnam,htit,100,0.,300.);
            }
        }
    }

    TH1F*  hmgg = new TH1F("hmgg","2-cluster invariant mass",100,0.,300.);

    FILE* fd = fopen(list,"r");
    while( ifscanf = fscanf(fd,"%s",fpath) != EOF) {
        f=new TFile(fpath);
        hlist = (TList*)f->Get("histos");

        for(Int_t iList=0; iList<hlist->GetEntries(); iList++) {
            hadd = (TH1F*)hlist->At(iList);
            const char* str = hadd->GetName();
            int md,X,Z;
            if (sscanf(str,"%d_%d_%d",&md,&X,&Z)) {
                hst[md][X][Z]->Add(hadd);
                //printf("Added hst[%d][%d][%d]\n",md,X,Z);
            }
            else {
                printf("Trying to add histogram %s to hmgg.\n",hadd->GetName());
                hmgg->Add(hadd);
            }
        }

        printf("Deleting list..\n");
        hlist->Delete();
        printf("OK!\n");
        ifile++;

        printf("File %s processed.\n",fpath);
        if(f) delete f;
    }

    printf("%d processed.\n",ifile);

    TFile outfile(newname,"recreate");

    for(Int_t iMod=0; iMod<5; iMod++) {
        for(Int_t iX=0; iX<64; iX++) {
            for(Int_t iZ=0; iZ<56; iZ++) {
                if(hst[iMod][iX][iZ]->GetEntries()) hst[iMod][iX][iZ]->Print();
                hst[iMod][iX][iZ]->Write();
            }
        }
    }

    hmgg->Write();
    outfile.Close();
}
Ejemplo n.º 12
0
void add_periods(const char *newname, const char *perioddir)
{
	int i, j, K, N, L;
	char str[1024];
	TList *keys;
	TFile *fIn;
	TFile *f0;
	TSystemFile *fSys;
	char prefix[128];
	char *ptr;
	TNamed *obj;
	TH1D *h;
	TH1D *hist[MAXHIST];
	
	TSystemDirectory *dir = new TSystemDirectory("MyDir", perioddir);
	TList *files = dir->GetListOfFiles();
	if (!files) {
		printf("%s - nothing to do(files)\n", perioddir);
		delete dir;
		return;
	}
	N = files->GetEntries() - 2;
	if (N <= 1) {
		printf("%s - nothing to do\n", perioddir);
		delete dir;
		return;
	}
	
	TFile *fNew = new TFile(newname, "RECREATE");
	if (!fNew->IsOpen()) {
	    delete dir;
	    delete files;
	    return;
	}
	
	fSys = (TSystemFile *) files->At(2);
	if (!fSys) {
		printf("Can not open the first file\n");
		delete dir;
		delete files;
		return;
	}
	sprintf(str, "%s/%s", perioddir, fSys->GetName());
	f0 = new TFile(str);
	if (!f0->IsOpen()) {
		printf("Can not open the first file\n");
		delete dir;
		delete files;
		return;
	}
	keys = f0->GetListOfKeys();
	K = keys->GetEntries();
	if (K <= 0) {
		printf("Nothing to do: K=0\n");
		delete dir;
		delete files;
		return;
	}
	L = 0;
	for (j=0; j<K; j++) {
		obj = (TNamed *) keys->At(j);
		if (!obj) continue;
		obj = (TNamed *) f0->Get(obj->GetName());
		if (!obj) continue;
		if (strcmp(obj->ClassName(), "TH1D")) continue;
		hist[L] = (TH1D *)obj;
		L++;
	}
	if (!L) {
		printf("Nothing to do: L=0\n");
		f0->Close();
		delete dir;
		delete files;
		return;
	}
	
	for (i=1; i<N; i++) {
		fSys = (TSystemFile *) files->At(i+2);	// skip . and ..
		if (!fSys) continue;
		sprintf(str, "%s/%s", perioddir, fSys->GetName());
		fIn = new TFile(str);
		if (!fIn->IsOpen()) continue;
		for (j=0; j<L; j++) {
			h = (TH1D *) fIn->Get(hist[j]->GetName());
			if (!h) continue;
			hist[j]->Add(h);
		}
//		printf("%s\n", fSys->GetName());
		fIn->Close();
	}

	fNew->cd();
	for (j=0; j<L; j++) hist[j]->Write();
	fNew->Close();
	
	f0->Close();
	delete files;
	delete dir;
}
Ejemplo n.º 13
0
void MakePlots(TString filename, float zmax=30, int nSmooth=10, TString opt="", TString energy="8TeV", TString lumi=""){
  TString outDir=filename; outDir.Remove(outDir.Last('/')); outDir+="/img/"+opt;
  //outDir="tmp/k5b/";
  //std::map<TString, TH2F *> deltaNLL_map;
  
  /*------------------------------ Plotto */
  TCanvas *c = new TCanvas("c","c");
  
  TFile f_in(filename, "read");
  if(f_in.IsZombie()){
    std::cerr << "File opening error: " << filename << std::endl;
    return;
  }
  
  TList *KeyList = f_in.GetListOfKeys();
  std::cout << KeyList->GetEntries() << std::endl;
  for(int i =0; i <  KeyList->GetEntries(); i++){
    c->Clear();
    TKey *key = (TKey *)KeyList->At(i);
    if(TString(key->GetClassName())!="RooDataSet") continue;
    RooDataSet *dataset = (RooDataSet *) key->ReadObj();
    if(dataset==NULL){
      std::cerr << "[WARNING] No dataset for " << key->GetName() << "\t" << key->GetTitle() << std::endl;
      continue;
    }
    TString constTermName = dataset->GetName();
    TString alphaName=constTermName; alphaName.ReplaceAll("constTerm","alpha");

    if(constTermName.Contains("absEta_1_1.4442-gold")) continue;
    if(constTermName.Contains("rho") || constTermName.Contains("phi")) continue;
        if(constTermName.Contains("scale")) continue;
    TTree *tree = dataset2tree(dataset);
    TGraphErrors bestFit_ = bestFit(tree, alphaName, constTermName);
    //    TString binning="(241,-0.0005,0.2405,60,0.00025,0.03025)"; 
    TString binning="(241,-0.0005,0.2405,301,-0.00005,0.03005)"; 
    
    TH2F *hist = prof2d(tree, constTermName, alphaName, "nll", binning, true,nSmooth, opt);
//     std::cout << "Bin width = " << hist->GetXaxis()->GetBinWidth(10) << "\t" << hist->GetYaxis()->GetBinWidth(10) << std::endl; 
//     std::cout << "Bin 1 center = " << hist->GetXaxis()->GetBinCenter(1) << "\t" << hist->GetYaxis()->GetBinCenter(1) << std::endl; 
//     std::cout << "Bin 10 center = " << hist->GetXaxis()->GetBinCenter(10) << "\t" << hist->GetYaxis()->GetBinCenter(10) << std::endl; 
//     return;
    hist->Draw("colz");
    hist->GetZaxis()->SetRangeUser(0,zmax);
    hist->GetXaxis()->SetRangeUser(0,0.15);
    hist->GetYaxis()->SetRangeUser(0,0.018);

    hist->GetXaxis()->SetTitle("#Delta S");
    hist->GetYaxis()->SetTitle("#Delta C");

    Int_t iBinX, iBinY;
    Double_t x,y;
    hist->GetBinWithContent2(0.0002,iBinX,iBinY,1,-1,1,-1,0.0000001);
    x= hist->GetXaxis()->GetBinCenter(iBinX);
    y= hist->GetYaxis()->GetBinCenter(iBinY);
    std::cout << "Best Fit: " << x << "\t" << y << std::endl;
    TGraph nllBestFit(1,&x,&y);

    TString fileName=outDir+"/"+constTermName;
    fileName+="-"; fileName+=nSmooth;
    
    nllBestFit.SetMarkerStyle(3);
    nllBestFit.SetMarkerColor(kRed);
    nllBestFit.Draw("P same");

    std::cout << fileName << std::endl;
    ofstream fout(fileName+".dat", ios_base::app);
    fout << constTermName << "\t" << x << "\t" << y << std::endl;


    c->SaveAs(fileName+".png");
    c->SaveAs(fileName+".eps");
    if(fileName.Contains("constTerm")) c->SaveAs(fileName+".C");

    fileName+="-zoom";
    hist->GetZaxis()->SetRangeUser(0,1);
    //hist->GetXaxis()->SetRangeUser(0.00,0.12);
    //hist->GetYaxis()->SetRangeUser(0,0.005);
    c->SaveAs(fileName+".png");
    c->SaveAs(fileName+".eps");


//     hist->SaveAs(outDir+"/deltaNLL-"+constTermName+".root");
//     hist->Draw("colz");
//     bestFit_.Draw("P same");
//     bestFit_.SetMarkerSize(2);


    
//     nllBestFit.SetMarkerStyle(3);
//     nllBestFit.SetMarkerColor(kRed);
//     TList* contour68 = contourFromTH2(hist, 0.68);

//     hist->Draw("colz");
//     hist->GetZaxis()->SetRangeUser(0,zmax);
//     //bestFit_.Draw("P same");
//     nllBestFit.Draw("P same");
//     //contour68->Draw("same");
    delete hist;
    RooAbsPdf *histPdf = NULL;
    if(!opt.Contains("keys")){
      hist = prof2d(tree, alphaName, constTermName, "nll", 
		    binning, false, nSmooth, opt);
      histPdf = nllToL(hist);
    }else{
      hist = prof2d(tree, alphaName, constTermName, "nll", 
		    binning, false,nSmooth);
      histPdf = Smooth(hist,1,"keys");
    }
    delete hist;


//     RooDataSet *gen_dataset=histPdf->generate(*histPdf->getVariables(),1000000,kTRUE,kFALSE);
//     TTree *genTree = dataset2tree(gen_dataset);
//     genTree->SaveAs(fileName+"-genTree.root");
//     delete gen_dataset;
//     delete histPdf;
    
//     TGraphErrors toyGraph = g(genTree, constTermName);
//     TGraphErrors bestFitGraph = g(tree,alphaName, constTermName);
//     TGraphErrors bestFitScanGraph = g(y, x);
//     delete genTree;
//     delete tree;
//     toyGraph.SetFillColor(kGreen);
//     toyGraph.SetLineColor(kBlue);
//     toyGraph.SetLineStyle(2);
//     bestFitGraph.SetLineColor(kBlack);
//     bestFitScanGraph.SetLineColor(kRed);
//     bestFitScanGraph.SetLineWidth(2);


    
//     TMultiGraph g_multi("multigraph","");
//     g_multi.Add(&toyGraph,"L3");
//     g_multi.Add(&toyGraph,"L");
//     g_multi.Add(&bestFitGraph, "L");
//     g_multi.Add(&bestFitScanGraph, "L");
   
//     g_multi.Draw("A");

//     c->Clear();
//     g_multi.Draw("A");
//     c->SaveAs(outDir+"/smearing_vs_energy-"+constTermName+".png");
//     c->SaveAs(outDir+"/smearing_vs_energy-"+constTermName+".eps");
//     //    TPaveText *pv = new TPaveText(0.7,0.7,1, 0.8);    
// //     TLegend *legend = new TLegend(0.7,0.8,0.95,0.92);
// //     legend->SetFillStyle(3001);
// //     legend->SetFillColor(1);
// //     legend->SetTextFont(22); // 132
// //     legend->SetTextSize(0.04); // l'ho preso mettendo i punti con l'editor e poi ho ricavato il valore con il metodo GetTextSize()
// //   //  legend->SetFillColor(0); // colore di riempimento bianco
// //     legend->SetMargin(0.4);  // percentuale della larghezza del simbolo
//     //    SetLegendStyle(legend);
	
//     //Plot(c, data,mc,mcSmeared,legend, region, filename, energy, lumi);
  }
  
  f_in.Close();
  
  return;
}
Ejemplo n.º 14
0
void addn2() {

  // open existing f1:

  char* fn[99];
  int ni;

  // SR90 maps, mod D003

  ni = -1;
  ni++; fn[ni] = "SR90-map-00a.root";
  ni++; fn[ni] = "SR90-map-00b.root";
  ni++; fn[ni] = "SR90-map-01a.root";
  ni++; fn[ni] = "SR90-map-01b.root";
  ni++; fn[ni] = "SR90-map-02.root";
  ni++; fn[ni] = "SR90-map-03.root";
  ni++; fn[ni] = "SR90-map-05a.root";
  ni++; fn[ni] = "SR90-map-05b.root";
  ni++; fn[ni] = "SR90-map-07a.root";
  ni++; fn[ni] = "SR90-map-07b.root";
  ni++; fn[ni] = "SR90-map-07c.root";
  ni++; fn[ni] = "SR90-map-07d.root";

  // direct X-rays 9.4.2014 module D0003

  ni = -1;
  ni++; fn[ni] = "X-ray-20-modtd40000.root";
  ni++; fn[ni] = "X-ray-20-vthr60-modtd1000.root";
  ni++; fn[ni] = "X-ray-27-vthr60-modtd1000.root";
  ni++; fn[ni] = "X-ray-35-modtd40000.root";
  ni++; fn[ni] = "X-ray-35-vthr60-close-modtd65000.root";
  ni++; fn[ni] = "X-ray-35-vthr60-midpos-0p1mA-modtd10000.root";
  ni++; fn[ni] = "X-ray-35-vthr60-midpos-halfcur-modtd40000.root";
  ni++; fn[ni] = "X-ray-35-vthr60-modtd40000.root";

  int nmax = ni;

  TFile f1(fn[0]);

  if( f1.IsZombie() ) {
    cout << "Error opening " << fn[0] << endl;
    return;
  }
  cout << "opened " << fn[0] << endl;

  //--------------------------------------------------------------------
  // create f0:

  TFile f0("fileA.root", "RECREATE");
  cout << "created ";
  gDirectory->pwd();

  /*
  TFile options:  
  NEW or CREATE   create a new file and open it for writing,
                  if the file already exists the file is
                  not opened.
  RECREATE        create a new file, if the file already
                  exists it will be overwritten.
  UPDATE          open an existing file for writing.
                  if no file exists, it is created.
  READ            open an existing file for reading (default).
  NET             used by derived remote file access
                  classes, not a user callable option
  WEB             used by derived remote http access
                  class, not a user callable option
  "" (default), READ is assumed.
  */

  //--------------------------------------------------------------------
  // copy f1 to f0:

  f1.cd();

  cout << "keys:\n";
  f1.GetListOfKeys()->Print();

  cout << "pwd: ";
  f1.pwd();

  cout << "ls: \n";
  f1.ls();

  // f1 has sub-dir:

  cout << "First: " << f1.GetListOfKeys()->First()->GetName() << endl;
  cout << "First: " << f1.GetListOfKeys()->First()->ClassName() << endl;
  char* dir1 = f1.GetListOfKeys()->First()->GetName();
  cout << "cd to " << dir1 << endl;
  f1.cd( dir1 );
  cout << "we are in ";
  gDirectory->pwd();

  gDirectory->ReadAll(); // load histos

  TList * lst = gDirectory->GetList();
  cout << lst->GetName() << endl;
  cout << lst->GetTitle() << endl;
  cout << "size    " << lst->GetSize() << endl;
  cout << "entries " << lst->GetEntries() << endl;
  cout << "last    " << lst->LastIndex() << endl;

  TIterator *iter = lst->MakeIterator();
  int ii = 0;
  TObject *obj;
  TH1D *h;
  TH1D *h0;
  TH2D *H;
  TH2D *H0;

  while( obj = iter->Next() ){
    ii++;
    cout << setw(4) << ii << ": ";
    cout << obj->ClassName() << " ";
    cout << obj->InheritsFrom("TH1D") << " ";
    cout << obj->GetName() << " \"";
    cout << obj->GetTitle() << "\"";
    cout << endl;
    //    if( obj->ClassName() == "TH1D" ){
    if( obj->InheritsFrom("TH1D") ){
      h = (TH1D*) obj;
      cout << "       1D";
      cout << h->GetNbinsX() << " bins, ";
      cout << h->GetEntries() << " entries, ";
      cout << h->GetSumOfWeights() << " inside, ";
      cout << h->GetBinContent(0) << " under, ";
      cout << h->GetBinContent(h->GetNbinsX()+1) << " over";
      cout << endl;

      f0.cd(); // output file

      //      TH1D* h0 = (TH1D*) h->Clone();
      h0 = h; // copy
      h0->Write(); // write to file f0
      
      f1.cd(); // back to file 1 for the loop
    }
    else{

      if( obj->InheritsFrom("TH2D") ){

	H = (TH2D*) obj;
	cout << "       2D";
	cout << H->GetNbinsX() << " bins, ";
	cout << H->GetEntries() << " entries, ";
	cout << H->GetSumOfWeights() << " inside, ";
	cout << H->GetBinContent(0) << " under, ";
	cout << H->GetBinContent(H->GetNbinsX()+1) << " over";
	cout << endl;
	
	f0.cd(); // output file
	
	H0 = H; // copy
	H0->Write(); // write to file f0
	
	f1.cd(); // back to file 1 for the loop
      }
      else cout << "other class " << obj->ClassName() << endl;
    }
  }
  cout << "copied " << ii << endl;
  cout << "f1 " << f1.GetName() << " close = " << f1.Close() << endl;
    
  f0.cd();
  cout << "we are in ";
  gDirectory->pwd();

  cout << "f0 " << f0.GetName() << " size  = " << f0.GetSize() << endl;

  cout << "f0 " << f0.GetName() << " write = " << f0.Write() << endl;

  cout << "f0 " << f0.GetName() << " size  = " << f0.GetSize() << endl;

  cout << "f0 " << f0.GetName() << " close = " << f0.Close() << endl;

  f0.Delete();

  //--------------------------------------------------------------------
  // list of files 2:

  bool lAB = true;

  for( int nn = 1; nn <= nmax; ++nn ){

    cout << "\n\n";
    cout << "loop " << nn << ": fn = " << fn[nn] << endl;
    cout << "lAB = " << lAB << endl;

    if( lAB ) { // A+2 -> B
      char* fn3 = "fileA.root";
      char* fn4 = "fileB.root";
    }
    else{ // B+2 -> A
      char* fn3 = "fileB.root";
      char* fn4 = "fileA.root";
    }

    // create f4:

    TFile f4( fn4, "recreate" );
    if( f4.IsZombie() ) {
      cout << "Error creating f4\n";
      return;
    }
    cout << "created f4   = " << f4.GetName() << endl;

    // re-open as f3:

    TFile f3( fn3 );
    if( f3.IsZombie() ) {
      cout << "Error opening f3\n";
      return;
    }
    cout << "re-opened f3 = " << f3.GetName() << endl;

    lAB = !lAB;
    cout << "lAB = " << lAB << " for next loop\n";

    cout << "f4 = " << f4.GetName() << endl;
    cout << "f3 = " << f3.GetName() << endl;

    f3.cd();
    gDirectory->ReadAll(); // load histos into f3 memory

    //    cout << "f3 list size = " << gDirectory->GetList()->GetSize() << endl;
    cout << "f3 list size = " << gDirectory->GetList()->GetSize() << endl;

    TFile f2(fn[nn]);
    //    TFile *f2 = new TFile(fn[nn]);

    if( f2.IsZombie() ) {
    //    if( f2 == NULL ) {
      cout << "Error opening " << fn[nn] << endl;
      return;
    }
    cout << "opened " << fn[nn] << endl;

    // f2 has sub-dir:

    f2.cd( f2.GetListOfKeys()->First()->GetName() );
    cout << "we are in ";
    gDirectory->pwd();

    gDirectory->ReadAll(); // load histos into f2 memory

    // loop over f2:

    cout << "f2 list size = " << gDirectory->GetList()->GetSize() << endl;

    int jj = 0;
    TObject *ob2;
    TH1D *h2;
    TH1D *h3;
    TH2D *H2;
    TH2D *H3;

    TIterator *ite2 = gDirectory->GetList()->MakeIterator();

    while( ob2 = ite2->Next() ){

      jj++;

      //      if( jj > 9 ) continue;

      cout << jj << ". ";
      cout << "ob2 is ";
      cout << ob2->GetName() << " ";
      cout << ob2->ClassName() << " ";
      cout << ob2->GetTitle();
      cout << endl;

      if( ob2->InheritsFrom("TH1D") ) {

	h2 = (TH1D*) ob2;
	cout << "h2 " << h2->GetName() << "  " << h2->GetNbinsX() << " bins\n";
	cout << "h2 " << h2->GetName() << "  " << h2->GetEntries() << " entries\n";
	char* hnm2 = h2->GetName();

	// search in f3:

	cout << "search for " << hnm2 << " in f3\n";
	f3.cd();
	cout << "we are in ";
	gDirectory->pwd();
	
	h3 = (TH1D*) gDirectory->GetList()->FindObject(hnm2);
	if( h3 == NULL ) {
	  cout << "h3 is null\n" ;
	  continue;
	}
	
	cout << "found h3 = ";
	cout << h3->GetName() << "  ";
	cout << h3->ClassName() << "  ";
	cout << h3->GetTitle();
	cout << endl;
	cout << "h3  " << h3->GetName() << "  " << h3->GetNbinsX() << " bins\n";
	cout << "h3  " << h3->GetName() << "  " << h3->GetEntries() << " entries\n";

	// add:

	f4.cd();
	cout << "we are in ";
	gDirectory->pwd();
	//TH1D h4 = *h3 + *h2;
	TH1D* h4 = (TH1D*) h3->Clone();
	h4->Add(h2);
	
	cout << "h4  " << h4->GetEntries() << " entries\n";
	cout << "h4  ";
	cout << h4->GetName() << " ";
	cout << h4->ClassName() << " ";
	cout << h4->GetTitle();
	cout << endl;
	cout << "h4 dir " << h4->GetDirectory()->GetName() << endl;
	cout << "f4 size " << f4.GetSize() << endl;

	// back to f2 for next iter:

	f2.cd( f2.GetListOfKeys()->First()->GetName() );

      }//1D

      if( ob2->InheritsFrom("TH2D") ) {

	H2 = (TH2D*) ob2;
	cout << "H2 " << H2->GetName() << "  " << H2->GetNbinsX() << " bins\n";
	cout << "H2 " << H2->GetName() << "  " << H2->GetEntries() << " entries\n";
	char* Hnm2 = H2->GetName();

	// search in f3:

	cout << "search for " << Hnm2 << " in f3\n";
	f3.cd();
	cout << "we are in ";
	gDirectory->pwd();
	
	H3 = (TH2D*) gDirectory->GetList()->FindObject(Hnm2);
	if( H3 == NULL ) {
	  cout << "H3 is null\n" ;
	  continue;
	}
	
	cout << "found H3 = ";
	cout << H3->GetName() << "  ";
	cout << H3->ClassName() << "  ";
	cout << H3->GetTitle();
	cout << endl;
	cout << "H3  " << H3->GetName() << "  " << H3->GetNbinsX() << " bins\n";
	cout << "H3  " << H3->GetName() << "  " << H3->GetEntries() << " entries\n";

	// add:

	f4.cd();
	cout << "we are in ";
	gDirectory->pwd();

	TH2D* H4 = (TH2D*) H3->Clone();
	H4->Add(H2);
	
	cout << "H4  " << H4->GetEntries() << " entries\n";
	cout << "H4  ";
	cout << H4->GetName() << " ";
	cout << H4->ClassName() << " ";
	cout << H4->GetTitle();
	cout << endl;
	cout << "H4 dir " << H4->GetDirectory()->GetName() << endl;
	cout << "f4 size " << f4.GetSize() << endl;

	// back to f2 for next iter:

	f2.cd( f2.GetListOfKeys()->First()->GetName() );
      }//2D

    } //while

    cout << "processed " << jj << endl;
    cout << "f4 " << f4.GetName() << " size " << f4.GetSize() << endl;

    //  cout << "f4 map:\n";
    //  f4.Map();

    cout << "f4 " << f4.GetName() << " write = " << f4.Write() << endl;

    cout << "f4 " << f4.GetName() << " size  = " << f4.GetSize() << endl;
    
  }// loop over files 2

  cout << endl;
  cout << "combined " << nmax + 1 << " files\n";
  cout << "Final file is " << f4.GetName() << endl;

  f2.Close();
  f3.Close();
  f4.Close();

}
Ejemplo n.º 15
0
void AnaPi0Select(const char* dataset="minbias_LHC09a4_81040_81050.xml")
{
    
    gSystem->Load("libTree");
    gSystem->Load("libGeom");
    gSystem->Load("libVMC");
    gSystem->Load("libPhysics");

    //load analysis framework
    gSystem->Load("libANALYSIS");
    gSystem->Load("libANALYSISalice"); //AliAnalysisTaskSE

    //Set local DB for PHOS
    gROOT->ProcessLine(".! tar xzvf PHOS.tgz") ;
    AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
    AliCDBManager::Instance()->SetSpecificStorage("PHOS/*","local://./");

    // A task can be compiled dynamically with AClic
    gROOT->LoadMacro("AliAnalysisTaskPi0CalibSelection.cxx+g");

    // Connect to alien
    TString token = gSystem->Getenv("GRID_TOKEN") ;
    if ( token == "OK" ) 
     TGrid::Connect("alien://");
    else 
     AliInfo("You are not connected to the GRID") ; 

    // Create the chain
    TChain* chain = new TChain("esdTree");
    TGridCollection * collection = dynamic_cast<TGridCollection*>(TAlienCollection::Open(dataset));
   
    TAlienResult* result = collection->GetGridResult("",0 ,0);
    TList* rawFileList = result->GetFileInfoList();

    for (Int_t counter=0 ; counter < rawFileList->GetEntries() ; counter++) {
     TFileInfo * fi =  static_cast<TFileInfo*>(rawFileList->At(counter)) ; 
     const char * rawFile = fi->GetCurrentUrl()->GetUrl() ;  
     printf("Processing %s\n", rawFile) ;
     chain->Add(rawFile);
     printf("Chain: %d entries.\n",chain->GetEntries()); 
    }

    // Make the analysis manager
    AliAnalysisManager *mgr = new AliAnalysisManager("Pi0CalibSelect","Pi0CalibSelection");

    // ESD input handler
    AliESDInputHandler* esdH = new AliESDInputHandler();
    mgr->SetInputEventHandler(esdH);

    // Debug level
    mgr->SetDebugLevel(10);

    // Add task
    AliAnalysisTaskPi0CalibSelection *task = new AliAnalysisTaskPi0CalibSelection("Pi0CalibSelection");
    task->SetClusterMinEnergy(0.4);
    mgr->AddTask(task);

    // Create containers for input/output
    AliAnalysisDataContainer *cinput  = mgr->GetCommonInputContainer();
    AliAnalysisDataContainer *coutput = mgr->CreateContainer("histos",TList::Class(),AliAnalysisManager::kOutputContainer,"histos.root");

    // Connect input/output
    mgr->ConnectInput(task, 0, cinput);
    mgr->ConnectOutput(task, 1, coutput);

    if (mgr->InitAnalysis()) {
	     mgr->PrintStatus();
	     mgr->StartAnalysis("local", chain);
    }

}
Ejemplo n.º 16
0
void MakePlots(TString filename, TString energy="8TeV", TString lumi=""){
  TString outDir=filename; outDir.ReplaceAll("fitres","img");
  outDir="tmp/";
  //std::map<TString, TH2F *> deltaNLL_map;
  
  /*------------------------------ Plotto */
  TCanvas *c = new TCanvas("c","c");
  
  TFile f_in(filename, "read");
  if(f_in.IsZombie()){
    std::cerr << "File opening error: " << filename << std::endl;
    return;
  }
  
  TList *KeyList = f_in.GetListOfKeys();
  std::cout << KeyList->GetEntries() << std::endl;
  for(int i =0; i <  KeyList->GetEntries(); i++){
    c->Clear();
    TKey *key = (TKey *)KeyList->At(i);
    if(TString(key->GetClassName())!="RooDataSet") continue;
    RooDataSet *dataset = (RooDataSet *) key->ReadObj();
    
    TString constTermName = dataset->GetName();
    TString alphaName=constTermName; alphaName.ReplaceAll("constTerm","alpha");

    TTree *tree = dataset2tree(dataset);
    TGraphErrors bestFit_ = bestFit(tree, alphaName, constTermName);
    TH2F *hist = prof2d(tree, alphaName, constTermName, "nll", "(12,-0.0005,0.0115,29,-0.0025,0.1425)",true);

//     //    deltaNLL_map.insert(std::pair <TString, TH2F *>(keyName,hist));
    hist->SaveAs(outDir+"/deltaNLL-"+constTermName+".root");
    hist->Draw("colz");
    bestFit_.Draw("P same");
    bestFit_.SetMarkerSize(2);

    Int_t iBinX, iBinY;
    Double_t x,y;
    hist->GetBinWithContent2(0,iBinX,iBinY);
    x= hist->GetXaxis()->GetBinCenter(iBinX);
    y= hist->GetYaxis()->GetBinCenter(iBinY);
    TGraph nllBestFit(1,&x,&y);

    nllBestFit.SetMarkerStyle(3);
    nllBestFit.SetMarkerColor(kRed);
    TList* contour68 = contourFromTH2(hist, 0.68);

    hist->Draw("colz");
    hist->GetZaxis()->SetRangeUser(0,50);
    bestFit_.Draw("P same");
    nllBestFit.Draw("P same");
    //contour68->Draw("same");
    c->SaveAs(outDir+"/deltaNLL-"+constTermName+".png");
    hist->SaveAs("tmp/hist-"+constTermName+".root");
    nllBestFit.SaveAs("tmp/nllBestFit.root");
    contour68->SaveAs("tmp/contour68.root");
    delete hist;
    hist = prof2d(tree, alphaName, constTermName, "nll", "(12,-0.0005,0.0115,29,-0.0025,0.1425)");
    RooHistPdf *histPdf = nllToL(hist);
    delete hist;
    RooDataSet *gen_dataset=histPdf->generate(*histPdf->getVariables(),1000000,kTRUE,kFALSE);
    TTree *genTree = dataset2tree(gen_dataset);
    genTree->SaveAs("tmp/genTree-"+constTermName+".root");
    delete gen_dataset;
    delete histPdf;
    
    TGraphErrors toyGraph = g(genTree, constTermName);
    TGraphErrors bestFitGraph = g(tree,alphaName, constTermName);
    TGraphErrors bestFitScanGraph = g(y, x);
    delete genTree;
    delete tree;
    toyGraph.SetFillColor(kGreen);
    toyGraph.SetLineColor(kBlue);
    toyGraph.SetLineStyle(2);
    bestFitGraph.SetLineColor(kBlack);
    bestFitScanGraph.SetLineColor(kRed);
    bestFitScanGraph.SetLineWidth(2);


    
    TMultiGraph g_multi("multigraph","");
    g_multi.Add(&toyGraph,"L3");
    g_multi.Add(&toyGraph,"L");
    g_multi.Add(&bestFitGraph, "L");
    g_multi.Add(&bestFitScanGraph, "L");
   
    g_multi.Draw("A");

    c->Clear();
    g_multi.Draw("A");
    c->SaveAs(outDir+"/smearing_vs_energy-"+constTermName+".png");

    //    TPaveText *pv = new TPaveText(0.7,0.7,1, 0.8);    
//     TLegend *legend = new TLegend(0.7,0.8,0.95,0.92);
//     legend->SetFillStyle(3001);
//     legend->SetFillColor(1);
//     legend->SetTextFont(22); // 132
//     legend->SetTextSize(0.04); // l'ho preso mettendo i punti con l'editor e poi ho ricavato il valore con il metodo GetTextSize()
//   //  legend->SetFillColor(0); // colore di riempimento bianco
//     legend->SetMargin(0.4);  // percentuale della larghezza del simbolo
    //    SetLegendStyle(legend);
	
    //Plot(c, data,mc,mcSmeared,legend, region, filename, energy, lumi);
  }
  
  f_in.Close();
  
  return;
}
void OCDBRPCRunStatisticsCreatorMerge(TString inputFileName){
    TFile *inputFile=new TFile(inputFileName.Data());

    inputFileName.ReplaceAll(".root", "");
    TFile *output=new TFile(Form("Run_Statistics_%s.root",inputFileName.Data()),"RECREATE");

    //definizione degli array usati per la nomenclatura
    const Int_t nSides=2;
    TString sides[2];
    sides[0]="INSIDE";
    sides[1]="OUTSIDE";

    const Int_t nPlanes=4;
    Int_t planes[4];
    planes[0]=11;
    planes[1]=12;
    planes[2]=21;
    planes[3]=22;
    
    const Int_t nRPC=9;

    const Int_t nLocalBoards=234;

    const Int_t nCathodes=2;
    TString cathodes[nCathodes];
    cathodes[0]="BENDING";
    cathodes[1]="NOT_BENDING";
    
    Double_t Areas[nRPC][nPlanes];
    for(Int_t iRPC=0;iRPC<nRPC;iRPC++){
        for(Int_t iPlane=0;iPlane<nPlanes;iPlane++){
            if(iRPC==5){
                if(iPlane<2){
                    Areas[iRPC][iPlane]=16056.;
                } else {
                    Areas[iRPC][iPlane]=18176.;
                }
            }else if(iRPC==4 || iRPC==6){
                if(iPlane<2){
                    Areas[iRPC][iPlane]=19728./28.*27.;
                } else {
                    Areas[iRPC][iPlane]=22338./28.*27.;
                }
            }else {
                if(iPlane<2){
                    Areas[iRPC][iPlane]=19728.;
                } else {
                    Areas[iRPC][iPlane]=22338.;
                }
            }
        }
    }

    TList *sortedListRunStatistics[nSides][nPlanes][nRPC];
    TList *sortedListData;
    TList *sortedListScalers;
    for (Int_t side=0; side<nSides; side++) {
        for (Int_t plane=0; plane<nPlanes; plane++) {
            for (Int_t RPC=1; RPC<=nRPC; RPC++) {
            	sortedListRunStatistics[side][plane][RPC-1]=new TList();
                sortedListRunStatistics[side][plane][RPC-1]->SetName(Form("Run_Stati_MTR_%s_MT%d_RPC%d",(sides[side]).Data(),planes[plane],RPC));
   				printf("getting Data_MTR_%s_MT%d_RPC%d\n",(sides[side]).Data(),planes[plane],RPC);
                inputFile->GetObject(Form("Data_MTR_%s_MT%d_RPC%d",(sides[side]).Data(),planes[plane],RPC),sortedListData);
   				//cout<<sortedListData->GetEntries()<<endl;
                //sortedListData->Sort();

                UInt_t actualRunNumber=0;
                UInt_t previousRunNumber=0;
			    ULong64_t timeStampStart=0;
			    ULong64_t timeStampStop=0;
			    Bool_t isCalib=kFALSE;
			    Double_t meanDarkCurrent=0.;
			    UInt_t nDarkCurrent=0;
			    Double_t meanTotalCurrent=0.;
			    UInt_t nTotalCurrent=0;
			    Double_t meanHV=0.;
			    UInt_t nHV=0;
			    ULong64_t totalScalerCounts[2]={0,0};
			    Int_t scalersIndex[2]={0,0};

				AliRPCValueDCS *defaultValueDCS = ((AliRPCValueDCS*)sortedListData->At(0));
            	previousRunNumber=defaultValueDCS->GetRunNumber();
            	timeStampStart=defaultValueDCS->GetTimeStamp();
            	isCalib=defaultValueDCS->GetIsCalib();
            	defaultValueDCS=0x0;

			    for(Int_t iDataList=0; iDataList<sortedListData->GetEntries(); iDataList++){
			    	//generica entry della sorted list
                    AliRPCValueDCS *valueDCS = ((AliRPCValueDCS*)sortedListData->At(iDataList));

                    actualRunNumber=valueDCS->GetRunNumber();
                    if(actualRunNumber==previousRunNumber){
	                    if (valueDCS->IsVoltage()){
	                        //cast a tensione
	                        AliRPCValueVoltage *voltageBuffer=(AliRPCValueVoltage*)valueDCS;
	                        meanHV+=voltageBuffer->GetVSupp();
	                        nHV++;
	                    } else if(valueDCS->IsCurrent()){
	                        //cast a corrente
	                        AliRPCValueCurrent *currentBuffer=(AliRPCValueCurrent*)valueDCS;
	                        meanTotalCurrent+=currentBuffer->GetITot();
	                        nTotalCurrent++;
	                        meanDarkCurrent+=currentBuffer->GetIDark();
	                        nDarkCurrent++;
	                    } else continue;                   	
                    } else {
                    	//cout<<"run data "<<previousRunNumber<<" ended."<<endl;
   						for(Int_t cathode=0;cathode<nCathodes;cathode++){
			                //printf("getting Scalers_MTR_%s_%s_MT%d_RPC%d\n",(sides[side]).Data(),(cathodes[cathode]).Data(),planes[plane],RPC);
			                inputFile->GetObject(Form("Scalers_MTR_%s_%s_MT%d_RPC%d",(sides[side]).Data(),(cathodes[cathode]).Data(),planes[plane],RPC),sortedListScalers);
			                //sortedListScalers->Sort();
			                //cout<<sortedListScalers->GetEntries()<<endl;
			                for(Int_t iScalersList=scalersIndex[cathode]; iScalersList<sortedListScalers->GetEntries(); iScalersList++){
			                	//cout<<iScalersList<<endl;
			                	AliRPCValueScaler* scalerData=(AliRPCValueScaler*)sortedListScalers->At(iScalersList);
			                	//skipping not interesting run numbers
			                	if(scalerData->GetRunNumber()<previousRunNumber) continue;
			                	//getting data from scalers belonging to the analyzed run number
			                	else if(scalerData->GetRunNumber()==previousRunNumber){
									totalScalerCounts[cathode]+=((AliRPCValueScaler*)sortedListScalers->At(iScalersList))->GetScalerCounts();
									timeStampStop=scalerData->GetTimeStamp();
								//once a new run is found break the cycle but keep track of the reached index (limits first if occurrences)
			                	} else {
			                		scalersIndex[cathode]=iScalersList;
			                		break;
			                	}
		                    }
		                    //cout<<"run scalers "<<previousRunNumber<<" ended."<<endl;
			            }
			            if(nDarkCurrent!=0)meanDarkCurrent=meanDarkCurrent/(Double_t)nDarkCurrent;
			            if(nTotalCurrent!=0)meanTotalCurrent=meanTotalCurrent/(Double_t)nTotalCurrent;
			            if(nHV!=0)meanHV=meanHV/(Double_t)nHV;
			            cout<<"setting "<<previousRunNumber<<" complete"<<endl;
			            AliRPCRunStatistics *runStats=new AliRPCRunStatistics(previousRunNumber, timeStampStart, timeStampStop, isCalib, meanDarkCurrent, meanTotalCurrent, meanHV, totalScalerCounts[0], totalScalerCounts[1]);
			            sortedListRunStatistics[side][plane][RPC-1]->Add(runStats);

			            /*cout<<runStats->GetRunNumber()<<endl;
		        		cout<<runStats->GetTimeStampStart()<<endl;
		        		cout<<runStats->GetTimeStampStop()<<endl;
		        		cout<<runStats->GetElapsedTime()<<endl;
		        		cout<<runStats->GetIsCalib()<<endl;
		        		cout<<runStats->GetMeanDarkCurrent()<<endl;
		        		cout<<runStats->GetMeanTotalCurrent()<<endl;
		        		cout<<runStats->GetMeanNetCurrent()<<endl;
		        		cout<<runStats->GetMeanHV()<<endl;
		        		cout<<runStats->GetTotalScalerCountsBending()<<endl;
		        		cout<<runStats->GetTotalScalerCountsNotBending()<<endl;
		        		cout<<runStats->GetMeanRateBending()<<endl;
		        		cout<<runStats->GetMeanRateNotBending()<<endl<<endl<<endl;*/

			            //runStats->Dump();
			            //printf("Written run %d \tMTR %s \t\tMT%d \tRPC%d\n",previousRunNumber, (sides[side]).Data(),planes[plane],RPC);
			            actualRunNumber=0;
					    timeStampStart=0;
					    timeStampStop=0;
					    isCalib=kFALSE;
					    meanDarkCurrent=0.;
					    nDarkCurrent=0;
					    meanTotalCurrent=0.;
					    nTotalCurrent=0;
					    meanHV=0.;
					    nHV=0;
					    totalScalerCounts[0]=0;
					    totalScalerCounts[1]=0;
			            //runStats=0x0;
			            //force reset of previous and start timestamp
			            previousRunNumber=0;
			            previousRunNumber=valueDCS->GetRunNumber();
                    	timeStampStart=valueDCS->GetTimeStamp();
                    	isCalib=valueDCS->GetIsCalib();
                    }  
			    }
			    output->cd();
			    sortedListRunStatistics[side][plane][RPC-1]->Sort();
			    sortedListRunStatistics[side][plane][RPC-1]->Write(Form("Run_Stati_MTR_%s_MT%d_RPC%d",(sides[side]).Data(),planes[plane],RPC),TObject::kSingleKey);
            }
        }
    }
}
Ejemplo n.º 18
0
void misalignmentDependence(TCanvas *c1old,
                            Int_t nFiles,TString *names,TString misalignment,Double_t *values,Double_t *phases,TString xvar,TString yvar,
                            TF1 *function,Int_t parameter,TString parametername = "",TString functionname = "",
                            Bool_t resolution = false,
                            TString saveas = "")
{
    cout << saveas << endl;
    if (c1old == 0) return;
    c1old = (TCanvas*)c1old->Clone("c1old");
    if (misalignment == "" || yvar == "") return;
    Bool_t drawfits = (parameter < 0);
    if (parameter < 0)
        parameter = -parameter - 1;   //-1 --> 0, -2 --> 1, -3 --> 2, ...
    TString yaxislabel = nPart(1,parametername);
    TString parameterunits = nPart(2,parametername);
    if (parameterunits != "")
        yaxislabel.Append(" (").Append(parameterunits).Append(")");
    TList *list = c1old->GetListOfPrimitives();
    int n = list->GetEntries() - 2 - (xvar == "");

    setTDRStyle();
    gStyle->SetOptStat(0);
    gStyle->SetOptFit(0);
    gStyle->SetFitFormat("5.4g");
    gStyle->SetFuncColor(2);
    gStyle->SetFuncStyle(1);
    gStyle->SetFuncWidth(1);
    if (!drawfits)
    {
        gStyle->SetCanvasDefW(678);
        gStyle->SetPadRightMargin(0.115);
    }

    TH1 **p = new TH1*[n];
    TF1 **f = new TF1*[n];
    Bool_t used[n];
    for (Int_t i = 0; i < n; i++)
    {
        stringstream s0;
        s0 << "p" << i;
        TString pname = s0.str();
        p[i] = (TH1*)list->/*At(i+1+(xvar == ""))*/FindObject(pname);
        used[i] = (p[i] != 0);
        if (used[i])
            p[i]->SetDirectory(0);
        if (xvar == "" && function == 0)
            continue;
        stringstream s;
        s << function->GetName() << i;
        TString newname = s.str();
        f[i] = (TF1*)function->Clone(newname);
        stufftodelete->Add(f[i]);
    }

    Double_t *result = new Double_t[nFiles];
    Double_t *error  = new Double_t[nFiles];
    if (xvar == "" && function == 0)
    {
        yaxislabel = axislabel(yvar,'y',resolution);
        for (Int_t i = 0; i < nFiles; i++)
        {
            if (!used[i]) continue;
            if (!resolution)
            {
                result[i] = p[i]->GetMean();
                error[i]  = p[i]->GetMeanError();
            }
            else
            {
                result[i] = p[i]->GetRMS();
                error[i]  = p[i]->GetRMSError();
            }
            cout << result[i] << " +/- " << error[i] << endl;
        }
    }
    else
    {
        for (int i = 0; i < n; i++)
        {
            if (!used[i]) continue;
            f[i]->SetLineColor(colors[i]);
            f[i]->SetLineStyle(styles[i]);
            f[i]->SetLineWidth(1);
            p[i]->SetMarkerColor(colors[i]);
            p[i]->SetMarkerStyle(20+i);
            p[i]->SetLineColor(colors[i]);
            p[i]->SetLineStyle(styles[i]);
            p[i]->Fit(f[i],"IM");
            error[i]  = f[i]->GetParError (parameter);
            if (function->GetName() == TString("sine"))
            {
                if (f[i]->GetParameter(0) < 0)
                {
                    f[i]->SetParameter(0,-f[i]->GetParameter(0));
                    f[i]->SetParameter(2,f[i]->GetParameter(2)+pi);
                }
                while(f[i]->GetParameter(2) >= 2*pi)
                    f[i]->SetParameter(2,f[i]->GetParameter(2)-2*pi);
                while(f[i]->GetParameter(2) < 0)
                    f[i]->SetParameter(2,f[i]->GetParameter(2)+2*pi);
            }
            result[i] = f[i]->GetParameter(parameter);
        }
    }


    TCanvas *c1 = TCanvas::MakeDefCanvas();

    if (drawfits && !(xvar == "" && function == 0) && yvar != "")
    {
        TString legendtitle = "[";
        legendtitle.Append(functionname);
        legendtitle.Append("]");
        TLegend *legend = new TLegend(.7,.7,.9,.9,legendtitle,"br");
        stufftodelete->Add(legend);
        TString drawoption = "";
        TH1 *maxp = (TH1*)list->FindObject("maxp");
        if (maxp != 0)
        {
            maxp->Draw();
            drawoption = "same";
        }
        for (int i = 0; i < n; i++)
        {
            if (!used[i]) continue;
            p[i]->Draw(drawoption);
            f[i]->Draw("same");
            drawoption = "same";

            stringstream s;
            s.precision(3);
            s << nPart(1,parametername) << " = " <<  result[i] << " #pm " << error[i];
            if (parameterunits != "") s << " " << parameterunits;
            TString str = s.str();
            legend->AddEntry(p[i],names[i],"pl");
            legend->AddEntry(f[i],str,"l");
        }
        c1->Update();
        Double_t x1min  = .98*gPad->GetUxmin() + .02*gPad->GetUxmax();
        Double_t x2max  = .02*gPad->GetUxmin() + .98*gPad->GetUxmax();
        Double_t y1min  = .98*gPad->GetUymin() + .02*gPad->GetUymax();
        Double_t y2max  = .02*gPad->GetUymin() + .98*gPad->GetUymax();
        Double_t width  = .4*(x2max-x1min);
        Double_t height = (1./20)*legend->GetListOfPrimitives()->GetEntries()*(y2max-y1min);
        width *= 2;
        height /= 2;
        legend->SetNColumns(2);

        Double_t newy2max = placeLegend(legend,width,height,x1min,y1min,x2max,y2max);
        p[0]->GetYaxis()->SetRangeUser(gPad->GetUymin(),(newy2max-.02*gPad->GetUymin())/.98);
        if (maxp != 0)
            maxp->GetYaxis()->SetRangeUser(gPad->GetUymin(),(newy2max-.02*gPad->GetUymin())/.98);

        legend->SetFillStyle(0);
        legend->Draw();
    }
    else
    {
        if (values == 0) return;

        Bool_t phasesmatter = false;
        if (misalignment == "elliptical" || misalignment == "sagitta" || misalignment == "skew")
        {
            if (phases == 0)
            {
                cout << "This misalignment has a phase, but you didn't supply the phases!" << endl
                     << "Can't produce plots depending on the misalignment value." << endl;
                return;
            }
            int firstnonzero = -1;
            for (Int_t i = 0; i < nFiles; i++)
            {
                if (values[i] == 0) continue;                    //if the amplitude is 0 the phase is arbitrary
                if (firstnonzero == -1) firstnonzero = i;
                if (phases[i] != phases[firstnonzero])
                    phasesmatter = true;
            }
        }

        if (!phasesmatter)
        {
            TGraphErrors *g = new TGraphErrors(nFiles,values,result,(Double_t*)0,error);
            g->SetName("");
            stufftodelete->Add(g);

            TString xaxislabel = "#epsilon_{";
            xaxislabel.Append(misalignment);
            xaxislabel.Append("}");
            g->GetXaxis()->SetTitle(xaxislabel);
            if (xvar != "")
            {
                yaxislabel.Append("   [");
                yaxislabel.Append(functionname);
                yaxislabel.Append("]");
            }
            g->GetYaxis()->SetTitle(yaxislabel);

            g->SetMarkerColor(colors[0]);
            g->SetMarkerStyle(20);

            g->Draw("AP");
            Double_t yaxismax = g->GetYaxis()->GetXmax();
            Double_t yaxismin = g->GetYaxis()->GetXmin();
            if (yaxismin > 0)
            {
                yaxismax += yaxismin;
                yaxismin = 0;
            }
            g->GetYaxis()->SetRangeUser(yaxismin,yaxismax);
            g->Draw("AP");
        }
        else
        {
            double *xvalues = new double[nFiles];
            double *yvalues = new double[nFiles];      //these are not physically x and y (except in the case of skew)
            for (int i = 0; i < nFiles; i++)
            {
                xvalues[i] = values[i] * cos(phases[i]);
                yvalues[i] = values[i] * sin(phases[i]);
            }
            TGraph2DErrors *g = new TGraph2DErrors(nFiles,xvalues,yvalues,result,(Double_t*)0,(Double_t*)0,error);
            g->SetName("");
            stufftodelete->Add(g);
            delete[] xvalues;        //A TGraph2DErrors has its own copy of xvalues and yvalues, so it's ok to delete these copies.
            delete[] yvalues;
            
            TString xaxislabel = "#epsilon_{";
            xaxislabel.Append(misalignment);
            xaxislabel.Append("}cos(#delta)");
            TString realyaxislabel = xaxislabel;
            realyaxislabel.ReplaceAll("cos(#delta)","sin(#delta)");
            g->GetXaxis()->SetTitle(xaxislabel);
            g->GetYaxis()->SetTitle(realyaxislabel);
            TString zaxislabel = /*"fake"*/yaxislabel;         //yaxislabel is defined earlier
            if (xvar != "")
            {
                zaxislabel.Append("   [");
                zaxislabel.Append(functionname);
                zaxislabel.Append("]");
            }
            g->GetZaxis()->SetTitle(zaxislabel);
            g->SetMarkerStyle(20);
            g->Draw("pcolerr");
        }
    }

    if (saveas != "")
    {
        saveplot(c1,saveas);
        delete[] p;
        delete[] f;
        delete[] result;
        delete[] error;
        delete c1old;
    }
}
Ejemplo n.º 19
0
void RecoMuonValHistoPublisher(const char* newFile="NEW_FILE",const char* refFile="REF_FILE") {
  cout << ">> Starting RecoMuonValHistoPublisher(" << newFile << "," << refFile << ")..." << endl;

  //====  To be replaced from python ====================
  
  const char* dataType = "DATATYPE";
  const char* refLabel("REF_LABEL, REF_RELEASE REFSELECTION");
  const char* newLabel("NEW_LABEL, NEW_RELEASE NEWSELECTION");
  const char* fastSim = "IS_FSIM";


  // ==== Initial settings and loads
  //gROOT->ProcessLine(".x HistoCompare_Tracks.C");
  //gROOT ->Reset();
  gROOT ->SetBatch();
  gErrorIgnoreLevel = kWarning; // Get rid of the info messages


  SetGlobalStyle();


  // ==== Some cleaning... is this needed?  
  delete gROOT->GetListOfFiles()->FindObject(refFile);
  delete gROOT->GetListOfFiles()->FindObject(newFile); 
  


  // ==== Opening files, moving to the right branch and getting the list of sub-branches
  cout << ">> Openning file, moving to the right branch and getting sub-branches..." << endl;

  cout << ">> Finding sources..." << endl;
  TFile* sfile = new TFile(newFile);
  TList* sl = getListOfBranches(dataType, sfile, "RecoMuonV");
  if (!sl) {
    cout << "ERROR: Could not find keys!!!" << endl;
    cerr << "ERROR: Could not find keys!!!" << endl;
    return;
  }
  TDirectory*  sdir  = gDirectory;
  for (unsigned int i = 0; i < sl->GetEntries(); i++)
    cout << "   + " << sl->At(i)->GetName() << endl;
    
  cout << ">> Finding references..." << endl;
  TFile* rfile = new TFile(refFile);
  TList* rl = getListOfBranches(dataType, rfile, "RecoMuonV");
  if (!rl) {
    cout << "ERROR: Could not find keys!!!" << endl;
    cerr << "ERROR: Could not find keys!!!" << endl;
    return;
  }
  TDirectory* rdir  = gDirectory;
  for (unsigned int i = 0; i < sl->GetEntries(); i++)
    cout << "   + " << sl->At(i)->GetName() << endl;

  Float_t maxPT;
  TString File = newFile;
  if (File.Contains("SingleMuPt1000") ||File.Contains("WpM")||File.Contains("ZpMM")   ) maxPT=1400.;
  else if(File.Contains("SingleMuPt10")) {maxPT = 70.;}
  else if (File.Contains("SingleMuPt100")) {maxPT = 400.;}
  else maxPT = 400.;

  TIter iter_r( rl );
  TIter iter_s( sl );
  TKey* rKey = 0;
  TKey* sKey = 0;
  TString rcollname;
  TString scollname;

  while ( (rKey = (TKey*)iter_r()) ) {
    TString myName = rKey->GetName();
#ifdef DEBUG
    cout << "DEBUG: Checking key " << myName << endl;
#endif
    rcollname = myName;
    sKey = (TKey*)iter_s();
    if (!sKey) continue;
    scollname = sKey->GetName();
    if ( (rcollname != scollname) && (rcollname+"FS" != scollname) && (rcollname != scollname+"FS") ) {
      cerr << "ERROR: Different collection names, please check: " << rcollname << " : " << scollname << endl;
      cout << "ERROR: Different collection names, please check: " << rcollname << " : " << scollname << endl;
      continue;
    }

    // ==== Now let's go for the plotting...
    cout << ">> Comparing plots in " << myName << "..." << endl;    
    cerr << ">> Comparing plots in " << myName << "..." << endl;    
    TString newDir("NEW_RELEASE/NEWSELECTION/NEW_LABEL/");
    newDir+=myName;
    gSystem->mkdir(newDir,kTRUE);
    bool resolx = false;
    bool *resol = &resolx;
    bool    logy    [] = {false,   false,  false,      false    };
    bool    doKolmo [] = {true,    true,   true,       true     };
    Double_t minx   [] = {-1E100, -1E100,    -1E100,   5.,    -1E100, -1E100 };
    Double_t maxx   [] = {-1E100, -1E100,-1E100, maxPT,  -1E100, -1E100 };
 
    Double_t norm   [] = {0.,0.,-999.,-999.,0.,0.}; //Normalize to first histogram

 
   //===== reco muon distributions: GLB
    //TString baseh     = Form("RecoMuon_MuonAssoc_Glb%s/",fastSim);

    const char* plots1[] = {"RecoMuon_MuonAssoc_Glb/ErrPt", 
    			    "RecoMuon_MuonAssoc_Glb/ErrP", 
    			    "RecoMuon_MuonAssoc_Glb/ErrPt_vs_Eta_Sigma", 
    			    "RecoMuon_MuonAssoc_Glb/ErrPt_vs_Pt_Sigma"};
    const char* plotst1[] = {"GlobalMuon(GLB) #Delta p_{T}/p_{T}", 
			     "GlobalMuon(GLB) #Delta p/p", 
			     "GlobalMuon(GLB) #Delta p_{T}/p_{T} vs #sigma(#eta)", 
			     "GlobalMuon(GLB) #Delta p_{T}/p_{T} vs #sigma(p_{T})"};
    Plot4Histograms(newDir + "/muonRecoGlb.pdf",
		    rdir, sdir, 
		    rcollname, scollname,
		    "RecHistosGlb", "Distributions for GlobalMuons (GLB)",
		    refLabel, newLabel,
		    plots1, plotst1,
		    logy, doKolmo, norm,resol,minx,maxx);
    
    
    //==== efficiencies and fractions GLB
    const char* plots2 [] = {"RecoMuon_MuonAssoc_Glb/EffP", 
			     "RecoMuon_MuonAssoc_Glb/EffEta", 
			     "RecoMuon_MuonAssoc_Glb/FractP", 
			     "RecoMuon_MuonAssoc_Glb/FractEta"};   
    const char* plotst2[] = {"GlobalMuon(GLB) #epsilon vs. p", 
			     "GlobalMuon(GLB) #epsilon vs. #eta", 
			     "GlobalMuon(GLB) fraction vs. p", 
			     "GlobalMuon(GLB) fraction vs. #eta"};
    Double_t minx1   [] = {5., -1E100,    5.,   -1E100,    -1E100, -1E100 };
    Double_t maxx1   [] = {maxPT, -1E100,maxPT, -1E100,  -1E100, -1E100 };
    Double_t norm2   [] = {-999.,-999.,-999.,-999.,-999.,-999.}; //Normalize to first histogram 
    Plot4Histograms(newDir + "/muonRecoGlbEff.pdf",
		    rdir, sdir, 
		    rcollname, scollname,
		    "RecEffHistosGlb", "Distributions for GlobalMuons (GLB), efficiencies and fractions",
		    refLabel, newLabel,
		    plots2, plotst2,
		    logy, doKolmo,norm2,resol,minx1,maxx1);
    
    /*
    //===== reco muon distributions: GLBPF
    baseh             = Form("RecoMuon_MuonAssoc_GlbPF%s/",fastSim);
    const char* plots3[]  = {(baseh + "ErrPt").Data(), (baseh + "ErrP").Data(), 
			     (baseh + "ErrPt_vs_Eta_Sigma").Data(), (baseh + "ErrPt_vs_Pt_Sigma").Data()};   
    const char* plotst3[] = {"PFGlobalMuon(GLBPF) #Delta p_{T}/p_{T}", "PFGlobalMuon(GLBPF) #Delta p/p", 
			     "PFGlobalMuon(GLBPF) #Delta p_{T}/p_{T} vs #sigma(#eta)", "PFGlobalMuon(GLBPF) #Delta p_{T}/p_{T} vs #sigma(p_{T})"};
    Plot4Histograms(newDir + "/muonRecoGlbPF.pdf",
		    rdir, sdir, 
		    rcollname, scollname,
		    "RecHistosGlbPF", "Distributions for PFGlobalMuons (GLBPF)",
		    refLabel, newLabel,
		    plots3, plotst3,
		    logy, doKolmo, norm);
    
    
    //==== efficiencies and fractions GLBPF
    const char* plots4 [] = {(baseh + "EffP").Data(), (baseh + "EffEta").Data(), 
			     (baseh + "FractP").Data(), (baseh + "FractEta").Data()};   
    const char* plotst4[] = {"PFGlobalMuon(GLBPF) #epsilon vs. p", "PFGlobalMuon(GLBPF) #epsilon vs. #eta", 
			     "PFGlobalMuon(GLBPF) fraction vs. p", "PFGlobalMuon(GLBPF) fraction vs. #eta"};
    Plot4Histograms(newDir + "/muonRecoGlbPFEff.pdf",
		    rdir, sdir, 
		    rcollname, scollname,
		    "RecEffHistosGlbPF", "Distributions for PFGlobalMuons (GLBPF), efficiencies and fractions",
		    refLabel, newLabel,
		    plots4, plotst4,
		    logy, doKolmo, norm);
    */
    
    //===== reco muon distributions: STA
    //baseh             = Form("RecoMuon_MuonAssoc_Sta%s/",fastSim);
    const char* plots5 [] = {"RecoMuon_MuonAssoc_Sta/ErrPt", 
			     "RecoMuon_MuonAssoc_Sta/ErrP", 
			     "RecoMuon_MuonAssoc_Sta/ErrPt_vs_Eta_Sigma", 
			     "RecoMuon_MuonAssoc_Sta/ErrPt_vs_Pt_Sigma"};   
    const char* plotst5[] = {"StandAloneMuon(STA) #Delta p_{T}/p_{T}", 
			     "StandAloneMuon(STA) #Delta p/p", 
			     "StandAloneMuon(STA) #Delta p_{T}/p_{T} vs #sigma(#eta)", 
			     "StandAloneMuon(STA) #Delta p_{T}/p_{T} vs #sigma(p_{T})"};
    Plot4Histograms(newDir + "/muonRecoSta.pdf",
		    rdir, sdir, 
		    rcollname, scollname,
		    "RecHistosSta", "Distributions for StandAloneMuons (STA)",
		    refLabel, newLabel,
		    plots5, plotst5,
		    logy, doKolmo, norm,resol, minx,maxx);
    
    
    
    //==== efficiencies and fractions STA
    const char* plots6 [] = {"RecoMuon_MuonAssoc_Sta/EffP", 
			     "RecoMuon_MuonAssoc_Sta/EffEta", 
			     "RecoMuon_MuonAssoc_Sta/FractP", 
			     "RecoMuon_MuonAssoc_Sta/FractEta"};   
    const char* plotst6[] = {"StandAloneMuon(STA) #epsilon vs. p", 
			     "StandAloneMuon(STA) #epsilon vs. #eta", 
			     "StandAloneMuon(STA) fraction vs. p", 
			     "StandAloneMuon(STA) fraction vs. #eta"};
    Plot4Histograms(newDir + "/muonRecoStaEff.pdf",
		    rdir, sdir, 
		    rcollname, scollname,
		    "RecEffHistosSta", "Distributions for StandAloneMuons (STA), efficiencies and fractions",
		    refLabel, newLabel,
		    plots6, plotst6,
		    logy, doKolmo, norm2,resol,minx1,maxx1);



   //===== reco muon distributions: TRK
    //baseh             = Form("RecoMuon_MuonAssoc_Trk%s/",fastSim);
    const char* plots7 [] = {"RecoMuon_MuonAssoc_Trk/ErrPt", 
			     "RecoMuon_MuonAssoc_Trk/ErrP", 
			     "RecoMuon_MuonAssoc_Trk/ErrPt_vs_Eta_Sigma", 
			     "RecoMuon_MuonAssoc_Trk/ErrPt_vs_Pt_Sigma"};   
    const char* plotst7[] = {"TrackerMuon(TRK) #Delta p_{T}/p_{T}", 
			     "TrackerMuon(TRK) #Delta p/p", 
			     "TrackerMuon(TRK) #Delta p_{T}/p_{T} vs #sigma(#eta)", 
			     "TrackerMuon(TRK) #Delta p_{T}/p_{T} vs #sigma(p_{T})"};
    Plot4Histograms(newDir + "/muonRecoTrk.pdf",
		    rdir, sdir, 
		    rcollname, scollname,
		    "RecHistosTrk", "Distributions for TrackerMuons (TRK)",
		    refLabel, newLabel,
		    plots7, plotst7,
		    logy, doKolmo, norm,resol,minx,maxx);



   //==== efficiencies and fractions TRK
    const char* plots8 [] = {"RecoMuon_MuonAssoc_Trk/EffP", 
			     "RecoMuon_MuonAssoc_Trk/EffEta", 
			     "RecoMuon_MuonAssoc_Trk/FractP", 
			     "RecoMuon_MuonAssoc_Trk/FractEta"};   
    const char* plotst8[] = {"TrackerMuon(TRK) #epsilon vs. p", 
			     "TrackerMuon(TRK) #epsilon vs. #eta", 
			     "TrackerMuon(TRK) fraction vs. p", 
			     "TrackerMuon(TRK) fraction vs. #eta"};
    Plot4Histograms(newDir + "/muonRecoTrkEff.pdf",
		    rdir, sdir, 
		    rcollname, scollname,
		    "RecEffHistosTrk", "Distributions for TrackerMuons (TRK), efficiencies and fractions",
		    refLabel, newLabel,
		    plots8, plotst8,
		    logy, doKolmo, norm2,resol,minx1,maxx1);

    
    //
    //===== reco muon distributions: Tight Muons
    //
    //baseh             = Form("RecoMuon_MuonAssoc_Tgt%s/",fastSim);
    const char* plots9 [] = {"RecoMuon_MuonAssoc_Tgt/ErrPt", 
			     "RecoMuon_MuonAssoc_Tgt/ErrP", 
			     "RecoMuon_MuonAssoc_Tgt/ErrPt_vs_Eta_Sigma", 
			     "RecoMuon_MuonAssoc_Tgt/ErrPt_vs_Pt_Sigma"};   
    const char* plotst9[] = {"Tight Muon #Delta p_{T}/p_{T}", 
			     "Tight Muon #Delta p/p", 
			     "Tight Muon #Delta p_{T}/p_{T} vs #sigma(#eta)", 
			     "Tight Muon #Delta p_{T}/p_{T} vs #sigma(p_{T})"};
    Plot4Histograms(newDir + "/muonRecoTgt.pdf",
		    rdir, sdir, 
		    rcollname, scollname,
		    "RecHistosTgt", "Distributions for Tight Muons",
		    refLabel, newLabel,
		    plots9, plotst9,
		    logy, doKolmo, norm,resol,minx,maxx);



   //==== efficiencies and fractions Tight Muons
    const char* plots10 [] = {"RecoMuon_MuonAssoc_Tgt/EffP", 
			      "RecoMuon_MuonAssoc_Tgt/EffEta", 
			      "RecoMuon_MuonAssoc_Tgt/FractP", 
			      "RecoMuon_MuonAssoc_Tgt/FractEta"};   
    const char* plotst10[] = {"Tight Muon #epsilon vs. p", 
			      "Tight Muon #epsilon vs. #eta", 
			      "Tight Muon fraction vs. p", 
			      "Tight Muon fraction vs. #eta"};
    Plot4Histograms(newDir + "/muonRecoTgtEff.pdf",
		    rdir, sdir, 
		    rcollname, scollname,
		    "RecEffHistosTgt", "Distributions for Tight Muons, efficiencies and fractions",
		    refLabel, newLabel,
		    plots10, plotst10,
		    logy, doKolmo, norm2,resol,minx1,maxx1);
    
    
    
    //
    // Merge pdf histograms together into larger files, and name them based on the collection names
    //
    TString mergefile = "merged_recomuonval.pdf"; // File name where partial pdfs will be merged
    TString destfile  = newDir + "/../" + myName + ".pdf"; // Destination file name
    TString gscommand = "gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile="+ mergefile + " "
      +newDir+"/muonRecoGlb.pdf "
      +newDir+"/muonRecoGlbEff.pdf "
      //      +newDir+"/muonRecoGlbPF.pdf "
      //      +newDir+"/muonRecoGlbPFEff.pdf "
      +newDir+"/muonRecoSta.pdf "
      +newDir+"/muonRecoStaEff.pdf "
      +newDir+"/muonRecoTrk.pdf "
      +newDir+"/muonRecoTrkEff.pdf "
      +newDir+"/muonRecoTgt.pdf "
      +newDir+"/muonRecoTgtEff.pdf ";

    cout << ">> Merging partial pdfs to " << mergefile << "..." << endl;
#ifdef DEBUG
    cout << "DEBUG: ...with command \"" << gscommand << "\"" << endl;
#endif
    gSystem->Exec(gscommand);
    cout << ">> Moving " << mergefile << " to " << destfile << "..." << endl;
    gSystem->Rename(mergefile, destfile);
    cout << "   ... Done" << endl;
   
    cout << ">> Deleting partial pdf files" << endl;
    gSystem->Exec("rm -r "+newDir);
    
  }  // end of "while loop"
  
  cout << ">> Removing the relval files from ROOT before closing..." << endl;
  gROOT->GetListOfFiles()->Remove(sfile);
  gROOT->GetListOfFiles()->Remove(rfile);
  
#ifdef DEBUG
  cout << "DEBUG: Exiting!" << endl;
  cerr << "DEBUG: Exiting!" << endl;
#endif
}
Ejemplo n.º 20
0
void new_TrackValHistoPublisher(const char* newFile="NEW_FILE",const char* refFile="REF_FILE") {

  cout << ">> Starting new_TrackValHistoPublisher(" 
       << newFile << "," << refFile << ")..." << endl;

  //====  To be replaced from python ====================
  
  const char* dataType = "DATATYPE";
  const char* refLabel("REF_LABEL, REF_RELEASE REFSELECTION");
  const char* newLabel("NEW_LABEL, NEW_RELEASE NEWSELECTION");


  // ==== Initial settings and loads
  gROOT ->SetBatch();
  gErrorIgnoreLevel = kWarning; // Get rid of the info messages
  SetGlobalStyle();

  // ==== Some cleaning... is this needed?  
  delete gROOT->GetListOfFiles()->FindObject(refFile);
  delete gROOT->GetListOfFiles()->FindObject(newFile); 
  
  // ==== Opening files, moving to the right branch and getting the list of sub-branches
  cout << ">> Opening files, moving to the right branch and getting the list of sub-branches..." << endl;

  cout << ">> Finding new DQM file ..." << endl;
  TFile * sfile = new TFile(newFile);
  TList* sl = GetListOfBranches(dataType, sfile);

  if (!sl) {
    cout << "ERROR: Could not find keys!!!" << endl;
    cerr << "ERROR: Could not find keys!!!" << endl;
    return;
  }
  TDirectory*  sdir  = gDirectory;

  if (DEBUG) {
    for (unsigned int i = 0; i < sl->GetEntries(); i++)
      cout << "   + " << sl->At(i)->GetName() << endl;
  }
  
  cout << ">> Finding reference DQM file ..." << endl;
  TFile * rfile = new TFile(refFile);
  TList* rl = GetListOfBranches(dataType, rfile);

  if (!rl) {
    cout << "ERROR: Could not find keys!!!" << endl;
    cerr << "ERROR: Could not find keys!!!" << endl;
    return;
  }
  TDirectory* rdir  = gDirectory;

  if (DEBUG) {
    for (unsigned int i = 0; i < rl->GetEntries(); i++)
      cout << "   + " << rl->At(i)->GetName() << endl;
  }

  //==== Iterate now over histograms and collections
  cout << ">> Iterating over histograms and collections..." << endl;

  bool logy[6]     = {false,  false,  false,  false,   false,  false  };
  bool logx[6]     = {false,  false,  false,  false,   false,  false  };
  bool doKolmo[6]  = {true,   true,   true,   true,    true,   true };
  Double_t norm[6] =  {-1.,-1.,-1.,-1.,-1.,-1.};  // initial default: do not normalize
  Double_t minx[6] = {0, 0, 0, 0, 0, 0};
  Double_t maxx[6] = {0, 0, 0, 0, 0, 0};
  Double_t miny[6] = {0, 0, 0, 0, 0, 0};
  Double_t maxy[6] = {0, 0, 0, 0, 0, 0};
  const char* drawopt[6] = {"", "", "", "", "", ""};
  TString plots[6]       = {"", "", "", "", "", ""};
  TString titles[6]      = {"", "", "", "", "", ""};

  TString rcollname;
  TString scollname;
  TIter iter_r( rl );
  TIter iter_s( sl );
  TString newDirBase("NEW_RELEASE/NEWSELECTION/NEW_LABEL/");
  TKey* rKey = 0;

  // before CMSSW_10_1_0_pre1 a few collection names were different
  bool NEWcollNames = false;
  TString Ref_CMSSW_Release("REF_RELEASE");
  if (Ref_CMSSW_Release.Contains("CMSSW_9") || Ref_CMSSW_Release.Contains("CMSSW_10_0")) NEWcollNames=true;

  while ( (rKey = (TKey*)iter_r()) ) {
    TString myName = rKey->GetName();
    rcollname = myName;
    if (DEBUG) {
      cout << " Checking collection: " << myName << endl;
      cerr << " Checking collection: " << myName << endl;
    }

    TString myName2 = myName;
    if (NEWcollNames) {
      if (myName=="NEWprobeTrks") myName2="probeTrks";
      else if (myName=="NEWprobeTrks_TkAsso") myName2="probeTrks_TkAsso";
      else if (myName=="NEWseedsOfSTAmuons") myName2="seedsOfSTAmuons";
      else if (myName=="NEWseedsOfDisplacedSTAmuons") myName2="seedsOfDisplacedSTAmuons";
      else if (myName=="NEWcutsRecoTrkMuons") myName2="cutsRecoTrkMuons";
      else if (myName=="NEWextractGemMuons") myName2="extractGemMuons";
      else if (myName=="NEWextractMe0Muons") myName2="extractMe0Muons";
    }
    scollname = myName2;
    
    if (DEBUG) {
      cout << " Comparing " << rcollname << " and " << scollname << endl;
      cerr << " Comparing " << rcollname << " and " << scollname << endl;
    }

    // ==== Now let's go for the plotting...
    TString newDir = newDirBase+myName2;
    cout<<"creating directory: "<<newDir<<endl;
    gSystem->mkdir(newDir,kTRUE);
   
    // efficiency and fake rate Vs eta and phi
    plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
    plots[0]="effic_vs_eta"    ; titles[0]="Efficiency vs #eta";
    plots[1]="fakerate_vs_eta" ; titles[1]="Fake rate vs #eta" ;
    plots[2]="effic_vs_phi"    ; titles[2]="Efficiency vs #phi" ;
    plots[3]="fakerate_vs_phi" ; titles[3]="Fake rate vs #phi" ;
    
    miny[0]=-0.0001;
    miny[1]=-0.0001;
    miny[2]=-0.0001;
    miny[3]=-0.0001;
    
    maxy[0]=1.09;
    maxy[1]=0.;
    maxy[2]=1.09;
    maxy[3]=0.;
    
    Plot4Histograms(newDir + "/eff_eta_phi",
		    rdir, sdir, 
		    rcollname, scollname,
		    "eff_eta_phi", "Efficiency vs eta and Vs phi",
		    refLabel, newLabel,
		    plots, titles, drawopt,
		    logy, logx, doKolmo, norm, minx, maxx, miny, maxy);     
    

    // efficiency and fake rate Vs pt
    plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
    plots[0]="effic_vs_pt"    ; titles[0]="Efficiency vs pt";
    plots[1]="fakerate_vs_pt" ; titles[1]="Fake rate vs pt" ;
    plots[2]="num_simul_pT"   ; titles[2]="N of simulated tracks vs pt" ;
    plots[3]="num_reco_pT"    ; titles[3]="N of reco track vs pt" ;

    logx[0]=true;
    logx[1]=true;
    logx[2]=true;
    logx[3]=true;

    drawopt[0]="";
    drawopt[1]="";
    drawopt[2]="hist";
    drawopt[3]="hist";

    norm[0]= -1.;
    norm[1]= -1.;
    norm[2]= 2.;
    norm[3]= 2.;

    miny[0]= -0.0001;
    miny[1]= -0.0001;
    miny[2]= 0.;
    miny[3]= 0.;

    maxy[0]= 1.09;
    maxy[1]= 0.;
    maxy[2]= 0.;
    maxy[3]= 0.;

    Plot4Histograms(newDir + "/eff_pt",
		    rdir, sdir, 
		    rcollname, scollname,
		    "eff_pt", "Efficiency vs pt and sim,reco distributions",
		    refLabel, newLabel,
		    plots, titles, drawopt,
		    logy, logx, doKolmo, norm, minx, maxx, miny, maxy);     
 

    // efficiency and fake rate vs Number of Hits; Hit multiplicity per track; Ave.N.hits vs eta
    plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
    plots[0]="effic_vs_hit"      ; titles[0]="Efficiency vs Number of hits";
    plots[1]="fakerate_vs_hit"   ; titles[1]="Fake rate vs Number of hits" ;
    plots[2]="nhits"             ; titles[2]="number of hits per track" ;
    plots[3]="nhits_vs_eta_prof" ; titles[3]="mean number of Hits vs eta" ;

    drawopt[0]="";
    drawopt[1]="";
    drawopt[2]="hist";
    drawopt[3]="";

    norm[0]= -1.;
    norm[1]= -1.;
    norm[2]=  0.;
    norm[3]= -1.;

    miny[0]= -0.0001;
    miny[1]= -0.0001;
    miny[2]= 0.;
    miny[3]= 0.;

    maxy[0]= 1.09;
    maxy[1]= 0.;
    maxy[2]= 0.;
    maxy[3]= 0.;

    Plot4Histograms(newDir + "/eff_hits",
		    rdir, sdir, 
		    rcollname, scollname,
		    "eff_hits", "Efficiency vs Number of hits and hit multiplicity per track",
		    refLabel, newLabel,
		    plots, titles, drawopt,
		    logy, logx, doKolmo, norm, minx, maxx, miny, maxy);
    
    // efficiency and fake rate vs PU
    plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
    plots[0]="effic_vs_pu"      ; titles[0]="Efficiency vs n.PU interactions";
    plots[1]="fakerate_vs_pu"   ; titles[1]="Fake rate vs n.PU interactions" ;

    //maxx[0]= 100.;
    //maxx[1]= 100.;

    miny[0]= -0.0001;
    miny[1]=  0.;

    maxy[0]= 1.09;
    maxy[1]= 0.;

    Plot4Histograms(newDir + "/eff_pu",
		    rdir, sdir, 
		    rcollname, scollname,
		    "eff_pu", "Efficiency vs n.PU interactions",
		    refLabel, newLabel,
		    plots, titles, drawopt,
		    logy, logx, doKolmo, norm, minx, maxx, miny, maxy);     
    
    // skip other plots for seeds
    if (!scollname.Contains("seeds")) {

    //===== normalized chi2, chi2 probability, ave. norm. chi2 vs eta; ave. pt bias vs eta
    plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
    plots[0]="chi2"              ; titles[0]="Track #chi^{2}";
    plots[1]="chi2prob"          ; titles[1]="Probability of track #chi^{2}";
    plots[2]="chi2_vs_eta_prof"  ; titles[2]="Mean normalized #chi^{2} vs #eta" ;

    drawopt[0]="hist";
    drawopt[1]="hist";
    drawopt[2]="";

    norm[0]= -1.;
    norm[1]=  2.;
    norm[2]= -1.;

    logy[0]=true;
    logy[1]=false;
    logy[2]=false;
    
    Plot4Histograms(newDir + "/chi2",
		    rdir, sdir, 
		    rcollname, scollname,
		    "chi2", "chi2 distributions",
		    refLabel, newLabel,
		    plots, titles, drawopt,
		    logy, logx, doKolmo, norm, minx, maxx, miny, maxy);
    
    //===== pull distributions
    plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
    plots[0]="ptpull"     ; titles[0]="p_{T} Pull";
    plots[1]="qoverppull" ; titles[1]="q/p Pull" ;
    plots[2]="phipull"    ; titles[2]="#phi Pull" ;
    plots[3]="thetapull"  ; titles[3]="#theta Pull" ;
    plots[4]="dxypull"    ; titles[4]="dxy Pull" ;
    plots[5]="dzpull"     ; titles[5]="dz Pull" ;

    logy[0]=true;
    logy[1]=true;
    logy[2]=true;
    logy[3]=true;
    logy[4]=true;
    logy[5]=true;

    drawopt[0]="hist";
    drawopt[1]="hist";
    drawopt[2]="hist";
    drawopt[3]="hist";
    drawopt[4]="hist";
    drawopt[5]="hist";

    norm[0]= 2.;
    norm[1]= 2.;
    norm[2]= 2.;
    norm[3]= 2.;
    norm[4]= 2.;
    norm[5]= 2.;

    Plot6Histograms(newDir + "/pulls",
		    rdir, sdir, 
		    rcollname, scollname,
		    "pulls", "pull distributions",
		    refLabel, newLabel,
		    plots, titles, drawopt,
		    logy, logx, doKolmo, norm, minx, maxx, miny, maxy);     
    
    
    //===== residual distributions (projected on Y-axis from the 2D histos with residuals vs eta)
    plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
    plots[0]="ptres_vs_eta"       ; titles[0]="p_{T} Relative Residual";
    plots[1]="etares_vs_eta"      ; titles[1]="#eta Residual" ;
    plots[2]="phires_vs_eta"      ; titles[2]="#phi Residual" ;
    plots[3]="thetaCotres_vs_eta" ; titles[3]="cot(#theta) Residual" ;
    plots[4]="dxyres_vs_eta"      ; titles[4]="dxy Residual" ;
    plots[5]="dzres_vs_eta"       ; titles[5]="dz Residual" ;

    logy[0]=true;
    logy[1]=true;
    logy[2]=true;
    logy[3]=true;
    logy[4]=true;
    logy[5]=true;

    drawopt[0]="hist";
    drawopt[1]="hist";
    drawopt[2]="hist";
    drawopt[3]="hist";
    drawopt[4]="hist";
    drawopt[5]="hist";

    norm[0]= 2.;
    norm[1]= 2.;
    norm[2]= 2.;
    norm[3]= 2.;
    norm[4]= 2.;
    norm[5]= 2.;

    Plot6Histograms(newDir + "/residuals",
		    rdir, sdir, 
		    rcollname, scollname,
		    "residuals", "residual distributions",
		    refLabel, newLabel,
		    plots, titles, drawopt,
		    logy, logx, doKolmo, norm, minx, maxx, miny, maxy);      
    
      
    //===== resolutions vs eta; pt relative bias vs eta
    plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
    plots[0]="phires_vs_eta_Sigma"      ; titles[0]="width #phi Residual vs #eta";
    plots[1]="thetaCotres_vs_eta_Sigma" ; titles[1]="width cot(#theta) Residual vs #eta" ;
    plots[2]="dxyres_vs_eta_Sigma"      ; titles[2]="width dxy Residual vs #eta" ;
    plots[3]="dzres_vs_eta_Sigma"       ; titles[3]="width dz Residual vs #eta" ;
    plots[4]="ptres_vs_eta_Sigma"       ; titles[4]="width p_{T} Relative Residual vs #eta" ;
    plots[5]="ptres_vs_eta_Mean"        ; titles[5]="mean p_{T} Relative Residual vs #eta" ;

    logy[0]=true;
    logy[1]=true;
    logy[2]=true;
    logy[3]=true;
    logy[4]=true;
    logy[5]=false;
    
    Plot6Histograms(newDir + "/resol_eta",
		    rdir, sdir, 
		    rcollname, scollname,
		    "resol_eta", "resolutions vs eta",
		    refLabel, newLabel,
		    plots, titles, drawopt,
		    logy, logx, doKolmo, norm, minx, maxx, miny, maxy);     

    //===== resolutions vs pt; pt relative bias vs eta
    plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
    plots[0]="phires_vs_pt_Sigma"      ; titles[0]="width #phi Residual vs p_{T}";
    plots[1]="thetaCotres_vs_pt_Sigma" ; titles[1]="width cot(#theta) Residual vs p_{T}" ;
    plots[2]="dxyres_vs_pt_Sigma"      ; titles[2]="width dxy Residual vs p_{T}" ;
    plots[3]="dzres_vs_pt_Sigma"       ; titles[3]="width dz Residual vs p_{T}" ;
    plots[4]="ptres_vs_pt_Sigma"       ; titles[4]="width p_{T} Relative Residual vs p_{T}" ;
    plots[5]="ptres_vs_pt_Mean"        ; titles[5]="mean p_{T} Relative Residual vs p_{T}" ;

    logx[0]=true;
    logx[1]=true;
    logx[2]=true;
    logx[3]=true;
    logx[4]=true;
    logx[5]=true;

    logy[0]=true;
    logy[1]=true;
    logy[2]=true;
    logy[3]=true;
    logy[4]=true;
    logy[5]=false;
    
    Plot6Histograms(newDir + "/resol_pt",
		    rdir, sdir, 
		    rcollname, scollname,
		    "resol_pt", "resolutions vs pt",
		    refLabel, newLabel,
		    plots, titles, drawopt,
		    logy, logx, doKolmo, norm, minx, maxx, miny, maxy);     
    

    // ================= charge misid rate vs eta, pt, n.hits, PU
    plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
    plots[0]="chargeMisId_vs_eta" ; titles[0]="Charge MisId rate vs #eta";
    plots[1]="chargeMisId_vs_pt"  ; titles[1]="Charge MisID rate vs p_{T}" ;
    plots[2]="chargeMisId_vs_hit" ; titles[2]="Charge MisID rate vs number of RecHits" ;
    plots[3]="chargeMisId_vs_pu"  ; titles[3]="Charge MisID rate vs n.PU interactions" ;

    logx[0]=false;
    logx[1]=true;
    logx[2]=false;
    logx[3]=false;

    //maxx[0]= 0.;
    //maxx[1]= 0.;
    //maxx[2]= 0.;
    //maxx[3]= 100.;

    miny[0]= -0.0001;
    miny[1]=  0.;
    miny[2]= -0.0001;
    miny[3]=  0.;

    maxy[0]= 0.;
    maxy[1]= 0.;
    maxy[2]= 0.;
    maxy[3]= 0.;

    Plot4Histograms(newDir + "/chargeMisId",
		    rdir, sdir, 
		    rcollname, scollname,
		    "chargeMisId", "charge misId rate vs eta, pt, nhits, PU",
		    refLabel, newLabel,
		    plots, titles, drawopt,
		    logy, logx, doKolmo, norm, minx, maxx, miny, maxy);     

    } // if (!scollname.Contains("seeds"))

    //// Merge pdf files together and rename the merged pdf after the collection name
    TString mergefile = "merged_plots.pdf"; // File name where partial pdfs will be merged
    TString destfile  = newDir + "/../" + myName + ".pdf"; // Destination file name
    TString gscommand = "gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile="  + mergefile + " "
      + newDir + "/eff_eta_phi.pdf "
      + newDir + "/eff_pt.pdf "
      + newDir + "/eff_hits.pdf "
      + newDir + "/eff_pu.pdf "
      + newDir + "/chi2.pdf "
      + newDir + "/pulls.pdf "
      + newDir + "/residuals.pdf "
      + newDir + "/resol_eta.pdf "
      + newDir + "/resol_pt.pdf "
      + newDir + "/chargeMisId.pdf ";

    if (scollname.Contains("seeds"))
      gscommand = "gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile="  + mergefile + " "
	+ newDir + "/eff_eta_phi.pdf "
	+ newDir + "/eff_pt.pdf "
	+ newDir + "/eff_hits.pdf "
	+ newDir + "/eff_pu.pdf ";
  
    cout << ">> Merging partial pdfs to " << mergefile << "..." << endl;
    if (DEBUG) cout << " ...with command \"" << gscommand << "\"" << endl;

    gSystem->Exec(gscommand);
    cout << ">> Moving " << mergefile << " to " << destfile << "..." << endl;
    gSystem->Rename(mergefile, destfile);

    cout << ">> Deleting partial pdf files" << endl;
    gSystem->Exec("rm -rf "+newDir+"/*.pdf"); 
    cout << "   ... Done" << endl;
    
    }  // end of "while loop"

  ///////////////////////////////////////////////////////////////////////////////
  // comparison plots of Muon and Track associators on the probeTracks

  TString dir_MABH_vs_TABH = newDirBase + "probeTrks_MABH_vs_TABH";
  gSystem->mkdir(dir_MABH_vs_TABH, kTRUE);

  // in case of HLT or HeavyIons skip the following
  TString new_Sample_Name("NEW_LABEL");

  if (TString(dataType) == "HLT" || new_Sample_Name.Contains("_HI")) {
    cout << ">> Removing the relval files from ROOT before closing..." << endl;
    gROOT->GetListOfFiles()->Remove(sfile);
    gROOT->GetListOfFiles()->Remove(rfile);

    if (DEBUG) {
      cout << " Exiting!" << endl;
      cerr << " Exiting!" << endl;
    }

    return;
  }

  if (DEBUG) {
    cout << " Comparing MuonAssociatorByHits with quickTrackAssociatorByHits on probeTracks (for the new release)" << endl;
    cerr << " Comparing MuonAssociatorByHits with quickTrackAssociatorByHits on probeTracks (for the new release)" << endl;
  }
  
  sfile->cd("DQMData/Run 1/Muons/Run summary/RecoMuonV/MuonTrack");
  sdir = gDirectory;
  rcollname = "probeTrks_TkAsso";
  scollname = "probeTrks";

  // for releases before CMSSW_10_1_0_pre1 and New Muon Validation
  TString New_CMSSW_Release("NEW_RELEASE");
  bool NEWprobeTrksNames = false;
  if (New_CMSSW_Release.Contains("CMSSW_9") || New_CMSSW_Release.Contains("CMSSW_10_0")) NEWprobeTrksNames=true;
  if (NEWprobeTrksNames) {
    rcollname = "NEWprobeTrks_TkAsso";
    scollname = "NEWprobeTrks";
  }

  const char* _refLabel("NEW_LABEL, NEW_RELEASE NEWSELECTION quickTrackAssociatorByHits");
  const char* _newLabel("NEW_LABEL, NEW_RELEASE NEWSELECTION MuonAssociatorByHits");

  // efficiency and fake rate Vs eta and phi
  plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
  plots[0]="effic_vs_eta"    ; titles[0]="Efficiency vs #eta";
  plots[1]="fakerate_vs_eta" ; titles[1]="Fake rate vs #eta" ;
  plots[2]="effic_vs_pt"     ; titles[2]="Efficiency vs pt" ;
  plots[3]="fakerate_vs_pt"  ; titles[3]="Fake rate vs pt" ;

  logx[0]=false;
  logx[1]=false;
  logx[2]=true;
  logx[3]=true;

  miny[0]=-0.0001;
  miny[1]=-0.0001;
  miny[2]=-0.0001;
  miny[3]=-0.0001;
  
  maxy[0]=1.09;
  maxy[1]=0.;
  maxy[2]=1.09;
  maxy[3]=0.;

  Plot4Histograms(dir_MABH_vs_TABH + "/eff_pt_eta",
		  sdir, sdir,
		  rcollname, scollname,
		  "eff_pt_eta_MABHvsTABH", "Efficiency vs eta and pt - Muon vs Track Associator",
		  _refLabel, _newLabel,
		  plots, titles, drawopt,
		  logy, logx, doKolmo, norm, minx, maxx, miny, maxy);

  // efficiency and fake rate Vs N.hits and phi
  plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
  plots[0]="effic_vs_hit"    ; titles[0]="Efficiency vs Number of hits";
  plots[1]="fakerate_vs_hit" ; titles[1]="Fake rate vs Number of hits" ;
  plots[2]="effic_vs_phi"    ; titles[2]="Efficiency vs #phi" ;
  plots[3]="fakerate_vs_phi" ; titles[3]="Fake rate vs #phi" ;

  miny[0]=-0.0001;
  miny[1]=-0.0001;
  miny[2]=-0.0001;
  miny[3]=-0.0001;
  
  maxy[0]=1.09;
  maxy[1]=0.;
  maxy[2]=1.09;
  maxy[3]=0.;
  
  Plot4Histograms(dir_MABH_vs_TABH + "/eff_phi_hits",
		  sdir, sdir,
		  rcollname, scollname,
		  "eff_phi_hits_MABHvsTABH", "Efficiency vs phi and N. hits - Muon vs Track Associator",
		  _refLabel, _newLabel,
		  plots, titles, drawopt,
		  logy, logx, doKolmo, norm, minx, maxx, miny, maxy);
  
  // efficiency and fake rate Vs PU
  plotOptReset(logx,logy,doKolmo,norm,minx,maxx,miny,maxy,drawopt,plots,titles);
  plots[0]="effic_vs_pu"    ; titles[0]="Efficiency vs n.PU interactions";
  plots[1]="fakerate_vs_pu" ; titles[1]="Fake rate vs  n.PU interactions" ;
  
  //maxx[0]= 100.;
  //maxx[1]= 100.;
  
  miny[0]= -0.0001;
  miny[1]=  0.;
  
  maxy[0]= 1.09;
  maxy[1]= 0.;
  
  PlotNHistograms(dir_MABH_vs_TABH + "/eff_pu",
		  sdir, sdir,
		  rcollname, scollname,
		  "eff_pu_MABHvsTABH", "Efficiency vs N.PU interactions - Muon vs Track Associator",
		  _refLabel, _newLabel,
		  4, plots, titles, drawopt,
		  logy, logx, doKolmo, norm, minx, maxx, miny, maxy);
  
  //// Merge pdf files together and rename the merged pdf after the 
  TString _destfile  = newDirBase + "probeTrks_MABH_vs_TABH" + ".pdf"; // Destination file name
  TString _gscommand = "gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile="  + _destfile + " "
    + dir_MABH_vs_TABH + "/eff_pt_eta.pdf "
    + dir_MABH_vs_TABH + "/eff_phi_hits.pdf "
    + dir_MABH_vs_TABH + "/eff_pu.pdf ";
  
  cout << ">> Merging partial pdfs to " << _destfile << "..." << endl;
  if (DEBUG) cout << " ...with command \"" << _gscommand << "\"" << endl;
  gSystem->Exec(_gscommand);
  
  cout << ">> Deleting partial pdf files" << endl;
  gSystem->Exec("rm -rf "+ dir_MABH_vs_TABH +"/eff_*.pdf"); 
  cout << "   ... Done" << endl;
  
  cout << ">> Removing the relval files from ROOT before closing..." << endl;
  gROOT->GetListOfFiles()->Remove(sfile);
  gROOT->GetListOfFiles()->Remove(rfile);
  
  if (DEBUG) {
    cout << " Exiting!" << endl;
    cerr << " Exiting!" << endl;
  }
}
Ejemplo n.º 21
0
TTree *ToyTree(TString dirname="test/dato/fitres/Hgg_Et-toys/0.01-0.00", TString fname="outProfile-scaleStep2smearing_7-Et_25-trigger-noPF-EB.root", TString opt="", int nSmooth=10){
  TString outDir=dirname; outDir.ReplaceAll("fitres","img");
  outDir="tmp/";
  //std::map<TString, TH2F *> deltaNLL_map;

  //bool smooth=false;
  //if(opt.Contains("smooth")) smooth=true;
  

  /*------------------------------ Plotto */
  TCanvas c("ctoy","c");
  
  
  TTree *toys = new TTree("toys","");
  toys->SetDirectory(0);
  Double_t constTerm_tree, constTermTrue_tree;
  Double_t alpha_tree, alphaTrue_tree;
  char catName[100]; 
  Int_t catIndex;
  toys->Branch("constTerm", &constTerm_tree, "constTerm/D");
  toys->Branch("alpha", &alpha_tree, "alpha/D");
  toys->Branch("constTermTrue", &constTermTrue_tree, "constTermTrue/D");
  toys->Branch("alphaTrue", &alphaTrue_tree, "alphaTrue/D");

  toys->Branch("catName", catName, "catName/C");
  toys->Branch("catIndex", &catIndex, "catIndex/I");
  std::map<TString, Int_t> catIndexMap;

  ///1/
  for(int itoy =2; itoy <= 50; itoy++){
    TString filename=dirname+"/"; filename+=itoy; filename+="/"+fname;
    TString fout=dirname+"/"; fout+=itoy; fout+="/";    
    TFile f_in(filename, "read");
    if(f_in.IsZombie()){
      std::cerr << "File opening error: " << filename << std::endl;
      continue; //return NULL;
    }
    //std::cout << filename << std::endl;
    TList *KeyList = f_in.GetListOfKeys();
    //std::cout << KeyList->GetEntries() << std::endl;
    for(int i =0; i <  KeyList->GetEntries(); i++){
      c.Clear();
      TKey *key = (TKey *)KeyList->At(i);
      if(TString(key->GetClassName())!="RooDataSet") continue;
      RooDataSet *dataset = (RooDataSet *) key->ReadObj();
    
      TString constTermName = dataset->GetName();
      TString alphaName=constTermName; alphaName.ReplaceAll("constTerm","alpha");
      if(constTermName.Contains("scale")) continue;
      if(constTermName.Contains("alpha")) continue;
      if(constTermName.Contains("1.4442-gold")) continue;
      TTree *tree = dataset2tree(dataset);

      TGraph *rhoGraph = GetRho(tree, alphaName, constTermName);

      rhoGraph->SaveAs(fout+"rhoGraph-"+constTermName+".root");


      TGraphErrors bestFit_ = bestFit(tree, alphaName, constTermName);
      //TString binning="(241,-0.0005,0.2405,61,-0.00025,0.03025)"; //"(40,0.00025,0.02025,61,-0.0022975,0.1401475)";
      TString binning="(241,-0.0005,0.2405,301,-0.00005,0.03005)"; 

      TH2F *hist = prof2d(tree, constTermName, alphaName, "nll", binning, true, nSmooth, opt);
      //hist->SaveAs("myhist.root");
      
      Int_t iBinX, iBinY;
      hist->GetBinWithContent2(0.0002,iBinX,iBinY,1,-1,1,-1,0.0000001);
	
      //      if(iBinX!=0 && iBinY!=0 && iBinX < 41 && iBinY < 62){
      {
	TString catName_=constTermName; catName_.ReplaceAll("constTerm_",""); catName_.ReplaceAll("-","_");
	if(catIndexMap.count(catName_)==0) catIndexMap.insert(std::pair<TString,Int_t>(catName_,catIndexMap.size()));
	catIndex=catIndexMap[catName_];	
	constTerm_tree =  hist->GetYaxis()->GetBinCenter(iBinY);
	alpha_tree = hist->GetXaxis()->GetBinCenter(iBinX);
	sprintf(catName,"%s", catName_.Data());
	bestFit_.GetPoint(0, constTermTrue_tree,alphaTrue_tree);
// 	std::cout << constTerm_tree << " " << constTermTrue_tree 
// 		  << "\t" << alpha_tree << " " << alphaTrue_tree 
// 		  << std::endl;

	if(opt.Contains("scandiff")){
	  constTermTrue_tree = getMinimumFromTree(tree, "nll",TString(constTermName).ReplaceAll("-","_"));
	} else       if(opt.Contains("scan")){
	  constTerm_tree = getMinimumFromTree(tree, "nll",TString(constTermName).ReplaceAll("-","_"));
	}
	//std::cout << iBinX << "\t" << iBinY << "\t" << constTerm_tree - getMinimumFromTree(tree, "nll",TString(constTermName).ReplaceAll("-","_")) << std::endl;
	
	toys->Fill();
//       }else{
// 	hist->SaveAs("myhist.root");
// 	exit(0);
      }

      
      delete tree;
      delete hist;
    
    }
    f_in.Close();
  }
  //toys->SaveAs("tmp/toysTree.root");
  

  return toys;
}
Ejemplo n.º 22
0
TTree * InitTrees(const char * detector,  const char *referenceDet){
  //
  // Init tree for given period
  //  all  trees stored in qaMap
  //  FriendTree added to the master treeQADet
  // Currentrly in the code we assume ID="run";
  // Bug in root tree ?  - in case more than one friend tree set - indeces looks corrupted 
  //    0.) QA tree per detector Raw+MC (if exist)
  //    1.) QA trees per refernce detectors specified by string refDet e.g "TPC;TRD;TOF"
  //    2.) Logbook tree per run
  //    3.) Logbook tree per run/detector
  //    3.) RCT table
  //    4.) CPass table 
  // 
  //  tree is created with addition of friend trees which can be used in queries
  //  queries as analog to the SQL statement

  /* 
    period="LHC15o"; pass="******"
  */
  ::Info("qaTrending::InitTrees::Begin","Detector %s, RefDet=%s",detector, referenceDet);
  AliExternalInfo info;
  Int_t treeCounter=0;
  // Load trees
  TObjArray * detArray=TString(referenceDet).Tokenize(";");
  Int_t nrefDets=detArray->GetEntries();
  TVectorF runCounter(5+nrefDets*2);  // <QADet>, <Logbook>, <Logbook.Det>, <MonAlisa>, <CPass>, <QA.RefDet>xnrefDets, <Logbook.RefDet>xnrefDets
  //
  ::Info("qaTrending::InitTrees::End","Laoding trees");
  treeQADet = info.GetTreeDataQA(detector,period, pass);
  if (!treeQADet){
    ::Error("qaTrending.InitTrees", "Input QA tree %s not available", detector); 
    return 0;
  }
  runCounter[treeCounter++]=treeQADet->Draw("run","1","goff");
  qaMap[TString::Format("QA.%s",detector).Data()]=treeQADet;
  //
  qaMap["Logbook"]=info.GetTree("Logbook",period,"");
  qaMap["Logbook"]->AddFriend(treeQADet,"QADet");
  treeQADet->AddFriend(qaMap["Logbook"],"Logbook");
  runCounter[treeCounter++]=treeQADet->Draw("run","1","goff");
  //
  qaMap["MonALISA.RCT"]=info.GetTree("MonALISA.RCT",period,pass);
  qaMap["MonALISA.RCT"]->AddFriend(treeQADet,"QADet");
  treeQADet->AddFriend(qaMap["MonALISA.RCT"],"MonALISA.RCT");
  runCounter[treeCounter++]=treeQADet->Draw("run","1","goff");
  //
  TTree *treeLogbookDetector =info.GetTree("Logbook.detector",period,"");
  if (treeLogbookDetector){
    if (detArray->GetEntries()>0){
      for (Int_t idet=0; idet<detArray->GetEntries(); idet++){
	// Load Logbook.RefDet
	const char *detName=detArray->At(idet)->GetName();	
	TTree * treeLog =treeLogbookDetector->CopyTree(TString::Format("detector==\"%s\"",detName).Data());
	if (treeLog->GetEntries()<=0){
	  ::Error("qaTrending.InitTrees","Missing Tree Logbook. %s - check the syntax",detName);
	}else{
	  treeLog->BuildIndex("run");
	  qaMap[TString::Format("Logbook.%s",detName).Data()]=treeLog;
	  treeLog->AddFriend(treeQADet, "QADet");
	  treeQADet->AddFriend(treeLog,  TString::Format("Logbook.%s",detName).Data());
	  runCounter[treeCounter++]=treeQADet->Draw("run","1","goff");
	}
	// Load QA.RefDet
	TTree * treeQARefDet = info.GetTreeDataQA(detName,period, pass);
	if (treeQARefDet){
	  qaMap[TString::Format("QA.%s",detName).Data()]=treeQARefDet;
	  treeQARefDet->AddFriend(treeQADet, "QADet");
	  treeQADet->AddFriend(treeQARefDet,  TString::Format("QA.%s",detName).Data());
	  runCounter[treeCounter++]=treeQADet->Draw("run","1","goff");
	}else{
	  ::Error("qaTrending.InitTrees","Missing Tree QA.%s - check the syntax",detName);
	}
      }
    }
  }
  //
  // Check consistency of data
  // 
  ::Info("qaTrending::InitTrees::End","Checking trees");
  TList *arrFriends = treeQADet->GetListOfFriends();
  for (Int_t ifriend=0; ifriend<arrFriends->GetEntries(); ifriend++){
    Int_t entries = treeQADet->Draw(TString::Format("run-%s.run", arrFriends->At(ifriend)->GetName()).Data(),"1","goff");
    Double_t mean=0;
    if (entries>0) {
      mean=TMath::Mean(entries, treeQADet->GetV1());
    }
    if (mean==0){
      ::Info("qaTrending::InitTrees", "Friend:\t%s\t%d\t%f", arrFriends->At(ifriend)->GetName(), entries,mean);
    }else{
      ::Error("qaTrending::InitTrees", "Friend:\t%s\t%d\t%f", arrFriends->At(ifriend)->GetName(), entries,mean);
    }
  }
  delete detArray;
  ::Info("qaTrending::InitTrees::End","Detector %s, RefDet=%s",detector, referenceDet);

  return treeQADet;  
}
Ejemplo n.º 23
0
void Hyperon(const char* dataset="collection.xml")
{
  /* $Id$ */
  TStopwatch timer;
  timer.Start();


    TStringToken libs("Core,Tree,Geom,VMC,Physics,Minuit,Gui,XMLParser,Minuit2,Proof,STEERBase,ESD,AOD,OADB,ANALYSIS,ANALYSISalice,CDB,RAWDatabase,STEER,CORRFW,PHOSUtils,PHOSbase,PHOSpi0Calib,PHOSrec,PHOSshuttle,PHOSsim", ",");
  while( libs.NextToken() )
    gSystem->Load( Form("lib%s", libs.Data()) );

  gSystem->Load("libTree");
  gSystem->Load("libGeom");
  gSystem->Load("libVMC");
  gSystem->Load("libPhysics");
  gSystem->Load("libPWGGAGammaConv");
  gSystem->Load("libPWGGAHyperon");
  
  //load analysis framework
  gSystem->Load("libANALYSIS");
  gSystem->Load("libANALYSISalice"); //AliAnalysisTaskSE
  
  // Connect to alien
  TString token = gSystem->Getenv("GRID_TOKEN") ;
  if (1) // token == "OK" ) 
    TGrid::Connect("alien://");
  else 
    AliInfo("You are not connected to the GRID") ; 

  cout << "Pi0Analysis: processing collection " << dataset << endl;

  // Create the chain
  TChain* chain = new TChain("aodTree");

  TGridCollection * collection = dynamic_cast<TGridCollection*>(TAlienCollection::Open(dataset));
  
  TAlienResult* result = collection->GetGridResult("",0 ,0);
  TList* rawFileList = result->GetFileInfoList();
  
  for (Int_t counter=0 ; counter < rawFileList->GetEntries() ; counter++) {
    TFileInfo * fi =  static_cast<TFileInfo*>(rawFileList->At(counter)) ; 
    const char * rawFile = fi->GetCurrentUrl()->GetUrl() ;  
    printf("Processing %s\n", rawFile) ;
    chain->Add(rawFile);
    printf("Chain: %d entries.\n",chain->GetEntriesFast()); 
  }

  // Make the analysis manager
  AliAnalysisManager *mgr = new AliAnalysisManager("Hyperon");
  mgr->SetCommonFileName("histos.root");
  
  // AOD input handler
  AliAODInputHandler* aodH = new AliAODInputHandler();
  mgr->SetInputEventHandler(aodH);

  
  // Debug level
  mgr->SetDebugLevel(2);

   gROOT->LoadMacro("$ALICE_PHYSICS/OADB/macros/AddTaskCentrality.C"); 
   AliCentralitySelectionTask* taskCentrality = AddTaskCentrality(); 
   if (analysisMC) 
    taskCentrality->SetMCInput(); 

  // // Update it for Hyperon (YK 22.01.2015)
  // gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskEventplane.C");
  // AliEPSelectionTask *taskEP = AddTaskEventplane() ; 

  // gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskVZEROEPSelection.C");
  // AliVZEROEPSelectionTask *selTask = AddTaskVZEROEPSelection();  

  // Add my task
  AliAnalysisHyperon* task = new AliAnalysisHyperon();
  // gROOT->LoadMacro("$ALICE_ROOT/PWGGA/PHOSTasks/PHOS_PbPb/AddTaskPHOSPi0Flow.C"); // Update it for Hyperon (YK 22.01.2015)
  // task = AddTaskPHOSPi0Flow();

  
  // // Create containers for input/output
  AliAnalysisDataContainer *cinput   = mgr->GetCommonInputContainer(); 
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("Hyperon",TList::Class(),AliAnalysisManager::kOutputContainer,"HyperonHist.root");
  
  // // Connect input/output
  mgr->ConnectInput(task , 0, cinput);
  mgr->ConnectOutput(task, 1, coutput1);
 
  if (mgr->InitAnalysis()) {
    mgr->PrintStatus();
    mgr->StartAnalysis("local", chain);
  }

  timer.Stop();
  timer.Print();
}
void AnalyzeWaveforms(char *WaveformsFile = "Waveforms.root", const int nAddedChannels = 5) {
	
	//try to access waveforms file and in case of failure return
	if(gSystem->AccessPathName(WaveformsFile,kFileExists)) {
		cout << "Error: file " << WaveformsFile << " does not exsist. Run .x WaveformsFileMaker.C to create it" << endl;
		return;
	}
	//	gStyle->SetOptFit(111);
	//	gStyle->SetStatFormat("1.3E");
	//	gStyle->SetFitFormat("1.3E");
	
	// fetch the list of trees contained in the waveforms file
	// for every tree generate a waveform graph

	TFile *f = TFile::Open(WaveformsFile);
	TList *listOfKeys = f->GetListOfKeys();
	Int_t numberOfKeys = listOfKeys->GetEntries();
	TList *listOfGraphs = new TList();
	
	// if the waveform file name begins with the string "comparator" it goes in this list
	TList *listOfCompWaves = new TList();
	// if the waveform file name begins with the string "sum output" it goes in this list
	TList *listOfAdderWaves = new TList();

	for(Int_t i = 0; i < numberOfKeys; i++) {
		TString *keyName = new TString(listOfKeys->At(i)->GetName());
		TTree *tree = (TTree*)f->Get(keyName->Data());
		Float_t x = 0;
		Float_t y = 0;
		tree->SetBranchAddress("x",&x);
		tree->SetBranchAddress("y",&y);
		Int_t nentries = tree->GetEntries();

		TString *gName = new TString(keyName->Data());
		gName->Append(" graph");
		TGraphErrors *gWave = new TGraphErrors(nentries);
		gWave->SetName(gName->Data());
		gWave->SetTitle(gName->Data());
		gWave->GetXaxis()->SetTitle("Time");
		gWave->GetYaxis()->SetTitle("Voltage");
	//	gWave->SetBit(TH1::kCanRebin);

		for (Int_t j = 0; j < nentries; j++) {
			tree->GetEntry(j);
			gWave->SetPoint(j,x,y);
		}

		listOfGraphs->Add(gWave);

		if(keyName->BeginsWith("comparator"))
			listOfCompWaves->Add(gWave);

		if(keyName->BeginsWith("sum output"))
			listOfAdderWaves->Add(gWave);

	/*	TString *cName = new TString(keyName->Data());
		cName->Append(" canvas");
		TCanvas *cy = new TCanvas(cName->Data(),cName->Data(),800,600);
		gWave->Draw("AL"); */
	}
	
	cout << listOfAdderWaves->GetEntries() << endl;

	// analysis for waves with no delay

	// global variables

	Double_t xMin,xMax,yStart,yEnd;
	Int_t graphPoints;
	Double_t step;

	// comparator outputs waves sum

	TGraphErrors *gFirstCompWave = (TGraphErrors *)listOfCompWaves->First();

	graphPoints = gFirstCompWave->GetN();
	gFirstCompWave->GetPoint(0,xMin,yStart);
	gFirstCompWave->GetPoint(graphPoints - 1,xMax,yEnd); 

	step = (xMax - xMin)/graphPoints;
	cout << gFirstCompWave->GetName() << endl;
	cout << "xMin = " << xMin << "  xMax = " << xMax << "  graphPoints = " << graphPoints << endl;

	TGraphErrors *gCompSum = new TGraphErrors(graphPoints);
	gCompSum->SetLineColor(kBlue);
	gCompSum->SetLineWidth(2);
	gCompSum->SetName("Comparator Outputs Sum");
	gCompSum->SetTitle("Comparator Outputs Sum");
	Int_t nCompWaves = listOfCompWaves->GetEntries();
	Float_t gx,gy = 0;
	
	// Alpha coefficiens are now written "hard coded" here
	Float_t alphaArray[3] = {0.199,0.201,0.197};
	
	// Deleays coming from the multiplexer are written "hard coded" here
	Float_t muxDelayArray[3] = {0,77.14E-12,192.01E-12};

	for(Int_t i = 0; i < graphPoints; i++) {
		for(Int_t j = 0; j < nCompWaves; j++) {
			TGraphErrors *gCompWave = (TGraphErrors *)listOfCompWaves->At(j);
			gy += (gCompWave->Eval(xMin + i*step + muxDelayArray[j]))*alphaArray[j];
		}
		gCompSum->SetPoint(i,xMin + i*step,gy);
		gy = 0;
	}
	
	// note that there is a manual correction on the x axis for the comparator waves sum to compare them better in the multigraph
	
	Double_t *xArray = gCompSum->GetX();
	for(Int_t i = 0; i < graphPoints; i++) {
		xArray[i] += 5.6E-9;
	}

//	TCanvas *cCompSum = new TCanvas("cCompSum","Comparator Outputs Sum",800,600);
//	gCompSum->Draw("AL");

	// adder outputs waves sum
	
	// THE ANALYSIS FOR THE ADDER OUTPUT WITH NOT DELAY AND 3 CHANNELS ADDED IS DEPRECATED.
	// THERE WAS A MISTAKE IN THE DATA TAKING
	// I'LL KEEP THE CODE HERE FOR FURTHER REFERENCE

/*
	TGraphErrors *gFirstAdderWave = (TGraphErrors *)listOfAdderWaves->First();

	graphPoints = gFirstAdderWave->GetN();
	gFirstAdderWave->GetPoint(0,xMin,yStart);
	gFirstAdderWave->GetPoint(graphPoints - 1,xMax,yEnd);

	step = (xMax - xMin)/graphPoints;
	cout << gFirstAdderWave->GetName() << endl;
	cout << "xMin : " << xMin << "  xMax : " << xMax << endl;

	TGraphErrors *gAdderSum = new TGraphErrors(graphPoints);
	gAdderSum->SetLineWidth(2);
//	gAdderSum->SetLineColor(kGreen);
	gAdderSum->SetLineStyle(9);
	gAdderSum->SetName("Sum of the adder outputs with no delay");
	gAdderSum->SetTitle("Sum of the adder outputs with no delay");
	Int_t nAdderWaves = listOfAdderWaves->GetEntries();
	gy = 0;

	for(Int_t i = 0; i < graphPoints; i++) {
		for(Int_t j = 0; j < nAdderWaves; j++) {
			TGraphErrors *gAdderWave = (TGraphErrors *)listOfAdderWaves->At(j);
			gy += gAdderWave->Eval(xMin + i*step);
		} 
		gAdderSum->SetPoint(i,xMin + i*step,gy);
		gy = 0;
	}

//	TCanvas *cAdderSum = new TCanvas("cAdderSum","Sum of the adder outputs",800,600);
//	gAdderSum->Draw("AL"); 
	
	TGraphErrors *g3ChannelsSumNoDelay = listOfGraphs->FindObject("sum_output_3_channels_(3) graph");
	g3ChannelsSumNoDelay->SetLineColor(kRed);
	g3ChannelsSumNoDelay->SetLineWidth(2);
	
	// note that there is a manual correction on the x axis for the adder output to compare it better in the multigraph
	
	Double_t *xArray = g3ChannelsSumNoDelay->GetX();
	graphPoints = g3ChannelsSumNoDelay->GetN();
	
	for(Int_t i = 0; i < graphPoints; i++) {
		xArray[i] -= 600E-12;
	}
	
	// comparison among the computed adder output ,the real one and the sum of the comparator outputs with alpha coefficients correction
	
	TMultiGraph *mgSumNoDelay = new TMultiGraph();
	mgSumNoDelay->Add(g3ChannelsSumNoDelay);
	mgSumNoDelay->Add(gAdderSum);
	mgSumNoDelay->Add(gCompSum);
	mgSumNoDelay->SetTitle("Collection of graphs for 3 channels sum with no delay");
	
	TCanvas *cmgSumNoDelay = new TCanvas("cmgSumNoDelay", "Collection of graphs for 3 channels sum with no delay", 1200,800);
	cmgSumNoDelay->Update();
	mgSumNoDelay->Draw("AL");
	
	legend = new TLegend(0.6,0.78,0.99,0.99);
	legend->AddEntry(g3ChannelsSumNoDelay, "Actual sum done by the adder", "lp");
	legend->AddEntry(gAdderSum, "Sum of the adder outputs", "lp");
	legend->AddEntry(gCompSum, "Sum of the comparator outputs","lp");
	legend->Draw();
	
	mgSumNoDelay->GetXaxis()->SetTitle("Seconds");
	mgSumNoDelay->GetYaxis()->SetTitle("Volts");
	TPaveText *title = (TPaveText*)cmgSumNoDelay->GetPrimitive("title");
	title->SetX1NDC(0.009);
	title->SetY1NDC(0.94);
	title->SetX2NDC(0.56);
	title->SetY2NDC(0.99);
	cmgSumNoDelay->Modified();
*/
	
	
	// analysis for delayed adder outputs
	
	Int_t nAdderWaves = listOfAdderWaves->GetEntries();

	TGraphErrors *g3ChannelsSumDelay = listOfGraphs->FindObject("sum_output_3_channels_(1-1-1) graph");
	g3ChannelsSumDelay->SetLineColor(kRed);
	g3ChannelsSumDelay->SetLineWidth(2);

	// Delay coming from cables are written "hard coded" here
	Float_t cablesDelayArray[3] = {0,1.45E-9,3.21E-9};
	
	graphPoints = g3ChannelsSumDelay->GetN();
	//g3ChannelsSumDelay->GetPoint(0,xMin,yStart);
	//g3ChannelsSumDelay->GetPoint(graphPoints - 1,xMax,yEnd);
	xMin = 6E-9;
	xMax = 16E-9;
	step = (xMax - xMin)/graphPoints;
	cout << "Sum of the adder outputs with delay" << endl;
	cout << "xMin : " << xMin << "  xMax : " << xMax << endl;

	TGraphErrors *gAdderSumDelay = new TGraphErrors(graphPoints);
	gAdderSumDelay->SetLineColor(kBlue);
	gAdderSumDelay->SetLineWidth(2);
	gAdderSumDelay->SetName("Sum of the adder outputs with delay");
	gAdderSumDelay->SetTitle("Sum of the adder outputs with delay");

	gy = 0;
	
	// note that there is a manual correction on the delay of 500E-12 to compare the adder output better in the multigraph

	for(Int_t i = 0; i < graphPoints; i++) {
		for(Int_t j = 0; j < nAdderWaves; j++) {
			TGraphErrors *gAdderWave = (TGraphErrors *)listOfAdderWaves->At(j);
			gy += gAdderWave->Eval(xMin + i*step + cablesDelayArray[j] - 500E-12);
		} 
		gAdderSumDelay->SetPoint(i,xMin + i*step,gy);
		gy = 0;
	}

	//	TCanvas *cSumSumDelay = new TCanvas("cSumSumDelay","Sum of the sum outputs with delay",800,600);
	//	gAdderSumDelay->Draw("APEL");

	TMultiGraph *mg3ChannelsSumDelay = new TMultiGraph();
	mg3ChannelsSumDelay->Add(gAdderSumDelay);
	mg3ChannelsSumDelay->Add(g3ChannelsSumDelay);
	mg3ChannelsSumDelay->SetTitle("Collection of graphs for 3 channels sum with delay");

	TCanvas *cmg3ChannelsSumDelay = new TCanvas("cmg3ChannelsSumDelay", "Collection of graphs for 3 channels sum with delay", 1200, 800);
	cmg3ChannelsSumDelay->Update();
	
	legend = new TLegend(0.6,0.78,0.99,0.99);
	legend->AddEntry(g3ChannelsSumDelay, "Actual sum done by the adder", "lp");
	legend->AddEntry(gAdderSumDelay, "Sum of the delayed adder outputs", "lp");
	mg3ChannelsSumDelay->Draw("AL");
	legend->Draw();
	
	mg3ChannelsSumDelay->GetXaxis()->SetTitle("Seconds");
	mg3ChannelsSumDelay->GetYaxis()->SetTitle("Volts");
	
	TPaveText *title = (TPaveText*)cmg3ChannelsSumDelay->GetPrimitive("title");
	title->SetX1NDC(0.009);
	title->SetY1NDC(0.94);
	title->SetX2NDC(0.56);
	title->SetY2NDC(0.99);
	
	cmg3ChannelsSumDelay->Modified();

/*
	// delay test just to try a different method

	TMultiGraph *mgDelayTest = new TMultiGraph();
	Double_t gxTest,gyTest;

	TGraphErrors *gDelayTest0 = new TGraphErrors(((TGraphErrors *)listOfAdderWaves->At(0))->GetN());
	for(Int_t j = 0; j < gDelayTest0->GetN(); j++) {
		((TGraphErrors *)listOfAdderWaves->At(0))->GetPoint(j,gxTest,gyTest);
		gDelayTest0->SetPoint(j,gxTest - cablesDelayArray[0],gyTest);
	}
	mgDelayTest->Add(gDelayTest0);

	TGraphErrors *gDelayTest1 = new TGraphErrors(((TGraphErrors *)listOfAdderWaves->At(1))->GetN());
	for(Int_t j = 0; j < gDelayTest1->GetN(); j++) {
		((TGraphErrors *)listOfAdderWaves->At(1))->GetPoint(j,gxTest,gyTest);
		gDelayTest1->SetPoint(j,gxTest - cablesDelayArray[1],gyTest);
	}
	mgDelayTest->Add(gDelayTest1);

	TGraphErrors *gDelayTest2 = new TGraphErrors(((TGraphErrors *)listOfAdderWaves->At(2))->GetN());
	for(Int_t j = 0; j < gDelayTest2->GetN(); j++) {
		((TGraphErrors *)listOfAdderWaves->At(2))->GetPoint(j,gxTest,gyTest);
		gDelayTest2->SetPoint(j,gxTest - cablesDelayArray[2],gyTest);
	}
	mgDelayTest->Add(gDelayTest2);

//	TCanvas *cmgDelayTest = new TCanvas("cmgDelayTest", "cmgDelayTest", 800,600);
//	mgDelayTest->Draw("APEL");

	graphPoints = 12000;
	xMin = 2E-9;
	xMax = 22E-9;
	step = (xMax - xMin)/graphPoints;
	cout << "xMin : " << xMin << "  xMax : " << xMax << endl;

	Double_t delayTest0xMin,delayTest0xMax,delayTest1xMin,delayTest1xMax,delayTest2xMin,delayTest2xMax;
	gDelayTest0->GetPoint(0,delayTest0xMin,gyTest);
	gDelayTest0->GetPoint(gDelayTest0->GetN() - 1,delayTest0xMax,gyTest);
	gDelayTest1->GetPoint(0,delayTest1xMin,gyTest);
	gDelayTest1->GetPoint(gDelayTest1->GetN() - 1,delayTest1xMax,gyTest);
	gDelayTest2->GetPoint(0,delayTest2xMin,gyTest);
	gDelayTest2->GetPoint(gDelayTest2->GetN() - 1,delayTest2xMax,gyTest);

	cout << delayTest0xMin << endl;

	TGraphErrors *gAdderSumDelayV2 = new TGraphErrors(graphPoints);
	for(Int_t i = 0; i < graphPoints; i++) {
		gyTest = gDelayTest0->Eval(xMin + i*step);
		gyTest += gDelayTest1->Eval(xMin + i*step);
		gyTest += gDelayTest2->Eval(xMin + i*step);
		gAdderSumDelayV2->SetPoint(i,xMin + i*step+ 500E-12,gyTest);
	} 
	
	gAdderSumDelayV2->SetLineColor(kGreen);
	gAdderSumDelayV2->SetLineWidth(2);
	mg3ChannelsSumDelay->Add(gAdderSumDelayV2);
	c3ChannelsSumDelay->Modified();

	TCanvas *cAdderSumDelayV2 = new TCanvas("cAdderSumDelayV2","cAdderSumDelayV2",800,600);
	gAdderSumDelayV2->Draw("APL");
*/

	// List of waves representing the adder output with 5,4,3,2,1 channels in input

	TGraphErrors *gAdder5Channels = listOfGraphs->FindObject("adder output 5 channels v2 graph");
	TGraphErrors *gAdder4Channels = listOfGraphs->FindObject("adder output 4 channels v2 graph");
	TGraphErrors *gAdder3Channels = listOfGraphs->FindObject("adder output 3 channels v2 graph");
	TGraphErrors *gAdder2Channels = listOfGraphs->FindObject("adder output 2 channels v2 graph");
	TGraphErrors *gAdder1Channel = listOfGraphs->FindObject("adder output 1 channel v2 graph");
	
	TGraphErrors *gAdderSingleCh0 = listOfGraphs->FindObject("single sum output ch 0 input 500 mV DT 100 mV graph");
	TGraphErrors *gAdderSingleCh1 = listOfGraphs->FindObject("single sum output ch 1 input 500 mV DT 100 mV graph");
	TGraphErrors *gAdderSingleCh4 = listOfGraphs->FindObject("single sum output ch 4 input 500 mV DT 100 mV graph");
	TGraphErrors *gAdderSingleCh5 = listOfGraphs->FindObject("single sum output ch 5 input 500 mV DT 100 mV graph");
	TGraphErrors *gAdderSingleCh7 = listOfGraphs->FindObject("single sum output ch 7 input 500 mV DT 100 mV graph");
	
	TMultiGraph *mgAdder54321Channels = new TMultiGraph();
	mgAdder54321Channels->SetTitle("Collection of graphs for different numbers of added channels");
	mgAdder54321Channels->Add(gAdder5Channels);
	mgAdder54321Channels->Add(gAdder4Channels);
	mgAdder54321Channels->Add(gAdder3Channels);
	mgAdder54321Channels->Add(gAdder2Channels);
	mgAdder54321Channels->Add(gAdder1Channel);
	
	TCanvas *cmgAdder54321Channels = new TCanvas("cmgAdder54321Channels", "Collection of graphs for different numbers of added channels",1200,800);
	mgAdder54321Channels->Draw("AL");
	cmgAdder54321Channels->Update();
	mgAdder54321Channels->GetXaxis()->SetTitle("seconds");
	mgAdder54321Channels->GetYaxis()->SetTitle("Volts");	
	cmgAdder54321Channels->Modified();
	
	// analysis of the linearity of the adder
	
	Double_t addedVMax[nAddedChannels];
	addedVMax[0] = TMath::MaxElement(gAdder1Channel->GetN(), gAdder1Channel->GetY());
	addedVMax[1] = TMath::MaxElement(gAdder2Channels->GetN(), gAdder2Channels->GetY());
	addedVMax[2] = TMath::MaxElement(gAdder3Channels->GetN(), gAdder3Channels->GetY());
	addedVMax[3] = TMath::MaxElement(gAdder4Channels->GetN(), gAdder4Channels->GetY());
	addedVMax[4] = TMath::MaxElement(gAdder5Channels->GetN(), gAdder5Channels->GetY());
	
	Double_t singleVMax[nAddedChannels];
	singleVMax[0] = TMath::MaxElement(gAdderSingleCh0->GetN(), gAdderSingleCh0->GetY());
	singleVMax[1] = TMath::MaxElement(gAdderSingleCh1->GetN(), gAdderSingleCh1->GetY());
	singleVMax[2] = TMath::MaxElement(gAdderSingleCh4->GetN(), gAdderSingleCh4->GetY());
	singleVMax[3] = TMath::MaxElement(gAdderSingleCh5->GetN(), gAdderSingleCh5->GetY());
	singleVMax[4] = TMath::MaxElement(gAdderSingleCh7->GetN(), gAdderSingleCh7->GetY());
	
	vector<double> expectedVMax(nAddedChannels);
	Double_t previousVmax = 0;
	for(Int_t i = 0; i < expectedVMax.size(); i++) {
		expectedVMax[i] = singleVMax[i] + previousVmax;
		previousVmax = expectedVMax[i];
		cout << "singleVMax[" <<i <<"] = " << singleVMax[i] <<  endl;
		cout << "addedVMax[" <<i <<"] = " << addedVMax[i] <<  endl;
		cout << "expectedVMax[" <<i <<"] = " << expectedVMax[i] <<  endl;
	}
	
	TGraph *gAdderLinearity = new TGraph(expectedVMax.size(),&expectedVMax[0],addedVMax);
	gAdderLinearity->SetTitle("Linearity of the adder");
	gAdderLinearity->GetXaxis()->SetTitle("Expected amplitude value (V)");
	gAdderLinearity->GetYaxis()->SetTitle("Actual amplitude value (V)");
	gAdderLinearity->GetYaxis()->SetTitleOffset(1.3);
	
	TCanvas *cgAdderLinearity = new TCanvas("cgAdderLinearity","Linearity of the adder",800,600);
	cgAdderLinearity->SetGrid();
	cgAdderLinearity->Update();
	gAdderLinearity->SetMarkerStyle(20);
	gAdderLinearity->SetMarkerSize(0.8);
	//gAdderLinearity->Fit("pol1","Q+","",expectedVMax[0],expectedVMax[2]);
	TF1 *line = new TF1("line","x",expectedVMax.back(),expectedVMax.front());
	gAdderLinearity->Draw("APEL");
	line->Draw("SAME");
	//gAdderLinearity->GetFunction("pol1")->SetRange(expectedVMax.back(),expectedVMax.front());;
	cgAdderLinearity->SetLeftMargin(0.13);
	cgAdderLinearity->Modified();
	
	f->Close();


}
Ejemplo n.º 25
0
void KVINDRAReconEvent::SecondaryAnalyseGroup(KVGroup* grp)
{
	// Perform identifications and calibrations of particles not included
   // in first round (methods IdentifyEvent() and CalibrateEvent()).
   //
   // Here we treat particles with GetStatus()==KVReconstructedNucleus::kStatusOKafterSub
   // after subtracting the energy losses of all previously calibrated particles in group from the
   // measured energy losses in the detectors they crossed.
   
   // loop over al identified & calibrated particles in group and subtract calculated
   // energy losses from all detectors
   KVINDRAReconNuc* nuc;
   TList sixparts;
   TIter parts(grp->GetParticles());
   while( (nuc = (KVINDRAReconNuc*)parts()) ){
   	if(nuc->IsIdentified() && nuc->IsCalibrated()){
   		nuc->SubtractEnergyFromAllDetectors();
        // reconstruct particles from pile-up in silicon detectors revealed by coherency CsIR/L - SiCsI
        if(nuc->IsSiPileup() && nuc->GetSi()->GetEnergy()>0.1){
            KVINDRAReconNuc* SIX = AddParticle();
            SIX->Reconstruct(nuc->GetSi());
            sixparts.Add(SIX);
        }
        // reconstruct particles from pile-up in si75 detectors revealed by coherency
        if(nuc->IsSi75Pileup()){
            KVINDRAReconNuc* SIX = AddParticle();
            SIX->Reconstruct(nuc->GetSi75());
            sixparts.Add(SIX);
        }
        // reconstruct particles from pile-up in sili detectors revealed by coherency
        if(nuc->IsSiLiPileup()){
            KVINDRAReconNuc* SIX = AddParticle();
            SIX->Reconstruct(nuc->GetSiLi());
            sixparts.Add(SIX);
        }

        // reconstruct particles from pile-up in ChIo detectors revealed by coherency CsIR/L - ChIoCsI
        if(nuc->IsChIoPileup() && nuc->GetChIo()->GetEnergy()>1.0){
            KVINDRAReconNuc* SIX = AddParticle();
            SIX->Reconstruct(nuc->GetChIo());
            sixparts.Add(SIX);
        }
    }
   }
   // reanalyse group
   KVReconstructedNucleus::AnalyseParticlesInGroup(grp);
   
   Int_t nident=0;//number of particles identified in each step
   if(sixparts.GetEntries()){   // identify any particles added by coherency CsIR/L - SiCsI
   	KVINDRAReconNuc* SIX;
   	TIter nextsix(&sixparts);
   	while( (SIX = (KVINDRAReconNuc*)nextsix()) ){
   		if( SIX->GetStatus() == KVReconstructedNucleus::kStatusOK ){
   			SIX->Identify();
   			if(SIX->IsIdentified()) {
   				nident++;
   				if(SIX->GetCodes().TestIDCode( kIDCode5 )) SIX->SetIDCode( kIDCode7 );
   				else SIX->SetIDCode( kIDCode6 );
   				SIX->Calibrate();
   				if(SIX->IsCalibrated()) SIX->SubtractEnergyFromAllDetectors();
   			}
   			else {
                // failure of ChIo-Si identification: particle stopped in ChIo ?
                // estimation of Z (minimum) from energy loss (if detector is calibrated)
                UInt_t zmin = ((KVDetector*)SIX->GetDetectorList()->Last())->FindZmin(-1., SIX->GetMassFormula());
                if( zmin ){
                    SIX->SetZ( zmin );
                    SIX->SetIsIdentified();
                    SIX->SetIDCode( kIDCode7 );
                    // "Identifying" telescope is taken from list of ID telescopes
                    // to which stopping detector belongs
                    SIX->SetIdentifyingTelescope( (KVIDTelescope*)SIX->GetStoppingDetector()->GetIDTelescopes()->Last() );
                    SIX->Calibrate();
                }
            }
   		}
   	}
   }
   if(nident){ // newly-identified particles may change status of others in group
   	// reanalyse group
        KVReconstructedNucleus::AnalyseParticlesInGroup(grp);
   	nident=0;
   }
   
   TIter parts2(grp->GetParticles()); // list may have changed if we have added particles
   // identify & calibrate any remaining particles with status=KVReconstructedNucleus::kStatusOK
   while( (nuc = (KVINDRAReconNuc*)parts2()) ){
   	if(!nuc->IsIdentified() && nuc->GetStatus()==KVReconstructedNucleus::kStatusOK && !nuc->IsIdentified()){
   		nuc->ResetNSegDet();
   		nuc->Identify();
   		if(nuc->IsIdentified()) {
   			nident++;
   			nuc->Calibrate();
   			if(nuc->IsCalibrated()) nuc->SubtractEnergyFromAllDetectors();
   		}
   	}
   }
   if(nident){ // newly-identified particles may change status of others in group
   	// reanalyse group
        KVReconstructedNucleus::AnalyseParticlesInGroup(grp);
   	nident=0;
   }
   
   // any kStatusOKafterShare particles ?
   TList shareChIo;
   parts2.Reset();
   while( (nuc = (KVINDRAReconNuc*)parts2()) ){
   	if(!nuc->IsIdentified() && nuc->GetStatus()==KVReconstructedNucleus::kStatusOKafterShare){
   		shareChIo.Add(nuc);
   	}
   }
   Int_t nshares = shareChIo.GetEntries();
   if(nshares){
   	KVChIo* theChIo = ((KVINDRAReconNuc*)shareChIo.At(0))->GetChIo();
   	if(theChIo && nshares>1){
   		// divide chio energy equally
   		Double_t Eshare = theChIo->GetEnergyLoss()/nshares;
   		theChIo->SetEnergyLoss(Eshare);
   		// modify PG and GG of ChIo according to new energy loss
   		Double_t volts = theChIo->GetVoltsFromEnergy(Eshare);
   		Double_t GG = theChIo->GetCanalGGFromVolts(volts);	
   		Double_t PG = theChIo->GetCanalPGFromVolts(volts);
			theChIo->GetACQParam("PG")->SetData(TMath::Min(4095,(Int_t)PG));
			theChIo->GetACQParam("GG")->SetData(TMath::Min(4095,(Int_t)GG));
		}
   	// now try to identify
   	TIter nextSh(&shareChIo);
   	while( (nuc = (KVINDRAReconNuc*)nextSh()) ){
   		nuc->SetNSegDet(10);
   		nuc->Identify();
   		if(nuc->IsIdentified()) {
   			nuc->SetIDCode( kIDCode8 );
   			nuc->Calibrate();
   		}
   	}
   }
   
   // any remaining stopped in first stage particles ?
   parts2.Reset();
   while( (nuc = (KVINDRAReconNuc*)parts2()) ){
       if(!nuc->IsIdentified() && nuc->GetStatus()==KVReconstructedNucleus::kStatusStopFirstStage){
           // estimation of Z (minimum) from energy loss (if detector is calibrated)
           UInt_t zmin = ((KVDetector*)nuc->GetDetectorList()->Last())->FindZmin(-1., nuc->GetMassFormula());
           if( zmin ){
               nuc->SetZ( zmin );
               nuc->SetIsIdentified();
               nuc->SetIDCode( kIDCode5 );
               // "Identifying" telescope is taken from list of ID telescopes
               // to which stopping detector belongs
               nuc->SetIdentifyingTelescope( (KVIDTelescope*)nuc->GetStoppingDetector()->GetIDTelescopes()->Last() );
               nuc->Calibrate();
           }
       }
   }
}
Ejemplo n.º 26
0
TChain* CreateESDChain(const char* aDataDir = "ESDfiles.txt", Int_t aRuns = 20, Int_t offset = 0, Bool_t addFileName = kFALSE, Bool_t addFriend = kFALSE, const char* check = 0)
{
  // creates chain of files in a given directory or file containing a list.
  // In case of directory the structure is expected as:
  // <aDataDir>/<dir0>/AliESDs.root
  // <aDataDir>/<dir1>/AliESDs.root
  // ...
  //
  // if addFileName is true the list only needs to contain the directories that contain the AliESDs.root files
  // if addFriend is true a file AliESDfriends.root is expected in the same directory and added to the chain as friend
  // if check is != 0 the files that work are written back into the textfile with the name check

  if (!aDataDir)
    return 0;

  Long_t id, size, flags, modtime;
  if (gSystem->GetPathInfo(aDataDir, &id, &size, &flags, &modtime))
  {
    printf("%s not found.\n", aDataDir);
    return 0;
  }

  TChain* chain = new TChain("esdTree");
  TChain* chainFriend = 0;
  
  if (addFriend)
    chainFriend = new TChain("esdFriendTree");

  if (flags & 2)
  {
    TString execDir(gSystem->pwd());
    TSystemDirectory* baseDir = new TSystemDirectory(".", aDataDir);
    TList* dirList            = baseDir->GetListOfFiles();
    Int_t nDirs               = dirList->GetEntries();
    gSystem->cd(execDir);

    Int_t count = 0;

    for (Int_t iDir=0; iDir<nDirs; ++iDir)
    {
      TSystemFile* presentDir = (TSystemFile*) dirList->At(iDir);
      if (!presentDir || !presentDir->IsDirectory() || strcmp(presentDir->GetName(), ".") == 0 || strcmp(presentDir->GetName(), "..") == 0)
        continue;

      if (offset > 0)
      {
        --offset;
        continue;
      }

      if (count++ == aRuns)
        break;

      TString presentDirName(aDataDir);
      presentDirName += "/";
      presentDirName += presentDir->GetName();

      chain->Add(presentDirName + "/AliESDs.root/esdTree");
    }
  }
  else
  {
    // Open the input stream
    ifstream in;
    in.open(aDataDir);

    ofstream outfile;
    if (check)
      outfile.open(check);

    Int_t count = 0;

    // Read the input list of files and add them to the chain
    TString line;
    while (in.good())
    {
      in >> line;

      if (line.Length() == 0)
        continue;

      if (offset > 0)
      {
        offset--;
        continue;
      }

      if (count++ == aRuns)
        break;

      TString esdFile(line);

      if (addFileName)
        esdFile += "/AliESDs.root";
        
      TString esdFileFriend(esdFile);
      esdFileFriend.ReplaceAll("AliESDs.root", "AliESDfriends.root");
        
      if (check)
      {
        TFile* file = TFile::Open(esdFile);
        if (!file)
          continue;
        file->Close();
        
        if (chainFriend)
        {
          TFile* file = TFile::Open(esdFileFriend);
          if (!file)
            continue;
          file->Close();
        }
        
        outfile << line.Data() << endl;
        printf("%s\n", line.Data());
      }        
        
        // add esd file
      chain->Add(esdFile);

        // add file
      if (chainFriend)
        chainFriend->Add(esdFileFriend);
    }

    in.close();
    
    if (check)
      outfile.close();
  }
  
  if (chainFriend)
    chain->AddFriend(chainFriend);

  return chain;
}
Ejemplo n.º 27
0
void printCalibStat(Int_t run, const char * fname,  TTreeSRedirector * pcstream){

  //
  // Dump the statistical information about all histograms in the calibration files 
  //    into the statistical tree, print on the screen (log files) as well 
  //
  //
  // 1. Default dump for all histograms
  //    Information to dump:
  //    stat =Entries, Mean, MeanError,  RMS, MaxBin
  //    Branch naming convention:
  //    <detName>_<hisName><statName>
  //
  // 2. Detector statistical information  - to be implemented by expert
  //                                      - First version implemented by MI 
  //  
  // 

  TFile *fin = TFile::Open(fname);
  if (!fin) return;
  const Double_t kMaxHis=10000;
  
  TList * keyList = fin->GetListOfKeys();
  Int_t nkeys=keyList->GetEntries();
  Double_t *hisEntries = new Double_t[kMaxHis];
  Double_t *hisMean = new Double_t[kMaxHis];
  Double_t *hisMeanError = new Double_t[kMaxHis];
  Double_t *hisRMS = new Double_t[kMaxHis];
  Double_t *hisMaxBin = new Double_t[kMaxHis];
  Int_t counter=0;
  
  if (pcstream) (*pcstream)<<"calibStatAll"<<"run="<<run;
  for (Int_t ikey=0; ikey<nkeys; ikey++){
    TObject * object = fin->Get(keyList->At(ikey)->GetName());
    if (!object) continue;
    if (object->InheritsFrom("TCollection")==0) continue;
    TSeqCollection *collection  = (TSeqCollection*)object; 
    Int_t nentries= collection->GetEntries();
    for (Int_t ihis=0; ihis<nentries; ihis++){
      TObject * ohis = collection->At(ihis);
      if (!ohis) continue;
      if (ohis->InheritsFrom("TH1")==0) continue;
      TH1* phis = (TH1*)ohis;
      hisEntries[counter]=phis->GetEntries();	
      Int_t idim=1;
      if (ohis->InheritsFrom("TH2")) idim=2;
      if (ohis->InheritsFrom("TH3")) idim=3;        
      hisMean[counter]=phis->GetMean(idim);	
      hisMeanError[counter]=phis->GetMeanError(idim);	
      hisRMS[counter]=phis->GetRMS(idim);	
      hisMaxBin[counter]=phis->GetBinCenter(phis->GetMaximumBin());	
      if (pcstream) (*pcstream)<<"calibStatAll"<<
		      Form("%s_%sEntries=",keyList->At(ikey)->GetName(), phis->GetName())<<hisEntries[counter]<<	
		      Form("%s_%sMean=",keyList->At(ikey)->GetName(), phis->GetName())<<hisMean[counter]<<	
		      Form("%s_%sMeanError=",keyList->At(ikey)->GetName(), phis->GetName())<<hisMeanError[counter]<<	
		      Form("%s_%sRMS=",keyList->At(ikey)->GetName(), phis->GetName())<<hisRMS[counter]<<	
		      Form("%s_%sMaxBin=",keyList->At(ikey)->GetName(), phis->GetName())<<hisMaxBin[counter];	
      //printf("Histo:\t%s_%s\t%f\t%d\n",keyList->At(ikey)->GetName(), phis->GetName(), hisEntries[counter],idim);
      counter++;
    }
    delete object;
  }    
  
  //
  // Expert dump example (MI first iteration):
  //
  // 0.)  TOF dump
  //

  Int_t tofEvents=0;
  Int_t tofTracks=0;
  TList * TOFCalib = (TList*)fin->Get("TOFHistos");      
  if (TOFCalib) {
    TH1 *histoEvents = (TH1*)TOFCalib->FindObject("hHistoVertexTimestamp");
    TH1 *histoTracks = (TH1*)TOFCalib->FindObject("hHistoDeltatTimestamp");
    if (histoEvents && histoTracks){
      tofEvents = TMath::Nint(histoEvents->GetEntries());
      tofTracks = TMath::Nint(histoTracks->GetEntries());
    }
    delete TOFCalib;
  }
  printf("Monalisa TOFevents\t%d\n",tofEvents);
  if (pcstream) (*pcstream)<<"calibStatAll"<<"TOFevents="<<tofEvents;
  printf("Monalisa TOFtracks\t%d\n",tofTracks);
  if (pcstream) (*pcstream)<<"calibStatAll"<<"TOFtracks="<<tofTracks;

  //
  // 1.)  TPC  dump - usefull events/tracks  for the calibration
  //
  Int_t tpcEvents=0;
  Int_t tpcTracks=0;
  TObject* obj = dynamic_cast<TObject*>(fin->Get("TPCCalib"));
  TObjArray* array = dynamic_cast<TObjArray*>(obj);
  TDirectory* dir = dynamic_cast<TDirectory*>(obj);
  AliTPCcalibTime  * calibTime = NULL;
  if (dir) {
    calibTime = dynamic_cast<AliTPCcalibTime*>(dir->Get("calibTime"));
  }
  else if (array){
    calibTime = (AliTPCcalibTime *)array->FindObject("calibTime");
  }
  if (calibTime) {
      tpcEvents = TMath::Nint(calibTime->GetTPCVertexHisto(0)->GetEntries());
      tpcTracks = TMath::Nint(calibTime->GetResHistoTPCITS(0)->GetEntries());
  }
  printf("Monalisa TPCevents\t%d\n",tpcEvents);
  if (pcstream) (*pcstream)<<"calibStatAll"<<"TPCevents="<<tpcEvents;
  printf("Monalisa TPCtracks\t%d\n",tpcTracks);
  if (pcstream) (*pcstream)<<"calibStatAll"<<"TPCtracks="<<tpcTracks;

  //
  // 2. TRD dump 
  //
  Int_t trdEvents=0;
  Int_t trdTracks=0;
  TList * TRDCalib = (TList*)fin->Get("TRDCalib");      
  if (TRDCalib) {
    TH1  *histoEvents = (TH1*)TRDCalib->FindObject("NEventsInput_AliTRDCalibTask");
    TH1  *histoTracks = (TH1*)TRDCalib->FindObject("AbsoluteGain_AliTRDCalibTask");
    if (histoEvents && histoTracks){
      trdEvents= TMath::Nint(histoEvents->GetEntries());
      trdTracks= TMath::Nint(histoTracks->GetEntries());
    }
    delete TRDCalib;
  }
  printf("Monalisa TRDevents\t%d\n",trdEvents);
  if (pcstream) (*pcstream)<<"calibStatAll"<<"TRDevents="<<trdEvents;
  printf("Monalisa TRDtracks\t%d\n",trdTracks);
  if (pcstream) (*pcstream)<<"calibStatAll"<<"TRDtracks="<<trdTracks;

  //
  // 3. T0 dump 
  //
  Int_t T0Events=0;
  TList * T0Calib = (TList*)fin->Get("T0Calib");      
  if (T0Calib) {
    TH1  *histoEvents = (TH1*) T0Calib->FindObject("fTzeroORAplusORC");
    if (histoEvents){
      T0Events= TMath::Nint(histoEvents->GetEntries());
    }
    delete T0Calib;
  }
  printf("Monalisa T0events\t%d\n",T0Events);
  if (pcstream) (*pcstream)<<"calibStatAll"<<"T0events="<<T0Events;

  //
  // 4. Mean vertex -   dump 
  // Not present in CPass1
  /*
    Int_t meanVertexEvents=0;
  TList * meanVertexCalib = (TList*)fin->Get("MeanVertex");      
  if (meanVertexCalib) {
    TH1  *histoEvents = (TH1*) meanVertexCalib->FindObject("hTRKVertexX");
    if (histoEvents){
      meanVertexEvents = TMath::Nint(histoEvents->GetEntries());
    }
    delete meanVertexCalib;
  }
  printf("Monalisa MeanVertexevents\t%d\n",meanVertexEvents);
  if (pcstream) (*pcstream)<<"calibStatAll"<<"MeanVertexevents="<<meanVertexEvents;
  */

  //
  // 5. SDD dump 
  //
  Int_t sddEvents=0;
  Int_t sddTracks=0;
  TList * SDDCalib = (TList*)fin->Get("clistSDDCalib");      
  if (SDDCalib) {
    TH1  *histoEvents = (TH1*) SDDCalib->FindObject("hNEvents");
    if (histoEvents ){
      sddEvents = TMath::Nint(histoEvents->GetBinContent(4));
      sddTracks = TMath::Nint(histoEvents->GetBinContent(5));
    }
    delete SDDCalib;
  }
  printf("Monalisa SDDevents\t%d\n",sddEvents);
  if (pcstream) (*pcstream)<<"calibStatAll"<<"SDDevents="<<sddEvents;
  printf("Monalisa SDDtracks\t%d\n",sddTracks);
  if (pcstream) (*pcstream)<<"calibStatAll"<<"SDDtracks="<<sddTracks;

  //
  // 6. AD dump
  //
  Int_t adEvents=0;
  TDirectory *adDir = (TDirectory*)fin->Get("ADCalib");
  if (adDir) {
    TList  *adList = (TList*) adDir->Get("ADCalibListHist");
    if (adList) {
      TH2* adHistInt0 = (TH2*) adList->FindObject("hCh00_bc10_int0");
      if (adHistInt0)
       adEvents += TMath::Nint(adHistInt0->GetEntries());
      TH2* adHistInt1 = (TH2*) adList->FindObject("hCh00_bc10_int1");
      if (adHistInt1)
       adEvents += TMath::Nint(adHistInt1->GetEntries());
      delete adList;
    }
  }
  printf("Monalisa ADevents\t%d\n",adEvents);
  if (pcstream) (*pcstream)<<"calibStatAll"<<"ADevents="<<adEvents;
  
  //
  if (pcstream) (*pcstream)<<"calibStatAll"<<"\n";
  delete fin;

}
Ejemplo n.º 28
0
//-------------------------------------------------------------------------------------------------
void makeHeaderFile(TFile *f, const string& treeName, bool paranoid, const string& Classname, const string& nameSpace, const string& objName) {
	
  
  
    headerf << "// -*- C++ -*-" << endl;
    headerf << "#ifndef " << Classname << "_H" << endl;
    headerf << "#define " << Classname << "_H" << endl;
    headerf << "#include \"Math/LorentzVector.h\"" << endl;
    headerf << "#include \"Math/Point3D.h\"" << endl;
    headerf << "#include \"TMath.h\"" << endl;
    headerf << "#include \"TBranch.h\"" << endl;
    headerf << "#include \"TTree.h\"" << endl;
    headerf << "#include \"TH1F.h\""  << endl;
    headerf << "#include \"TFile.h\"" << endl;
    headerf << "#include \"TBits.h\"" << endl;
    headerf << "#include <vector>" << endl;
    headerf << "#include <unistd.h>" << endl;
    headerf << "typedef ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > LorentzVector;" << endl << endl;
    if (paranoid)
        headerf << "#define PARANOIA" << endl << endl;
    headerf << "using namespace std; " << endl;
    headerf << "class " << Classname << " {" << endl;
    headerf << "private: " << endl;
    headerf << "protected: " << endl;
    headerf << "\tunsigned int index;" << endl;
    // TTree *ev = (TTree*)f->Get("Events");
    TList* list_of_keys = f->GetListOfKeys();
    std::string tree_name = "";
    if (treeName.empty()) {
        unsigned int ntrees = 0;
        for (unsigned int idx = 0; idx < (unsigned int)list_of_keys->GetSize(); idx++) {
            const char* obj_name = list_of_keys->At(idx)->GetName();
            TObject* obj = f->Get(obj_name);
            if (obj->InheritsFrom("TTree")) {
                ++ntrees;
                tree_name = obj_name;
            }
        }
        if (ntrees == 0) {
            std::cout << "Did not find a tree. Exiting." << std::endl;
            return;
        }
        if (ntrees > 1) {
            std::cout << "Found more than one tree.  Please specify a tree to use." << std::endl;
            return;
        }
    }
    else
        tree_name = treeName;

    TTree *ev = (TTree*)f->Get(tree_name.c_str());

    TSeqCollection *fullarray = ev->GetListOfAliases();  
    bool have_aliases = true;
    if (!fullarray) {
        have_aliases = false;   
        fullarray = ev->GetListOfBranches();
    }

    // if (have_aliases && fullarray->GetSize() != ev->GetListOfBranches()->GetSize()) {
    //     std::cout << "Tree has " << fullarray->GetSize() << " aliases and " << ev->GetListOfBranches()->GetSize() << " branches. Exiting." << std::endl;
    //     return;
    // }

    TList *aliasarray = new TList();
    
    for(Int_t i = 0; i < fullarray->GetEntries(); ++i) {
        TString aliasname(fullarray->At(i)->GetName());
        // TBranch *branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        TBranch *branch = 0;
        if (have_aliases)
            branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        else
            branch = (TBranch*)fullarray->At(i);

        TString branchname(branch->GetName());
        TString branchtitle(branch->GetTitle());
        TString branchclass(branch->GetClassName());
        if(!branchname.BeginsWith("int") && 
           !branchname.BeginsWith("uint") && 
           !branchname.BeginsWith("bool") && 
           !branchname.BeginsWith("float") &&
           !branchname.BeginsWith("double") &&
           !branchtitle.EndsWith("/F") && 
           !branchtitle.EndsWith("/I") &&
           !branchtitle.EndsWith("/i") &&
           !branchtitle.EndsWith("/O") &&
           !branchtitle.BeginsWith("TString") &&
           !branchtitle.BeginsWith("TBits") &&
           !branchclass.Contains("LorentzVector") &&
           !branchclass.Contains("int") &&   
           !branchclass.Contains("uint") &&  
           !branchclass.Contains("bool") &&  
           !branchclass.Contains("float") && 
           !branchclass.Contains("double") &&
           !branchclass.Contains("TString"))
            continue;

        // if (branchclass.Contains("TString"))
        // {
        //     std::cout << "Adding branch " << branchtitle.Data() << " to list." << std::endl;
        //     std::cout.flush();
        // }

        aliasarray->Add(fullarray->At(i));
    }
  
    for(Int_t i = 0; i< aliasarray->GetEntries(); ++i) {
    
        //Class name is blank for a int of float
        TString aliasname(aliasarray->At(i)->GetName());
        // TBranch *branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        TBranch *branch = 0;
        if (have_aliases)
            branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        else
            branch = (TBranch*)aliasarray->At(i);
    
        TString classname = branch->GetClassName();
        TString title     = branch->GetTitle();
        if ( classname.Contains("vector") ) {
            if(classname.Contains("edm::Wrapper<") ) {
                classname = classname(0,classname.Length()-2);
                classname.ReplaceAll("edm::Wrapper<","");
                headerf << "\t" << classname << " " << aliasname << "_;" << endl;
            } 
            //else if (classname.Contains("TString") || classname.Contains("vector<float>")) {
            else if (classname.Contains("TString")) {
                headerf << "\t" << classname << " " << aliasname << "_;" << endl;
            }
            else {
                headerf << "\t" << classname << " *" << aliasname << "_;" << endl;
            }
        } else {
      
            if(classname != "" ) { //LorentzVector
                if(classname.Contains("edm::Wrapper<") ) {
                    classname = classname(0,classname.Length()-1);
                    classname.ReplaceAll("edm::Wrapper<","");
                    headerf << "\t" << classname << " " << aliasname << "_;" << endl;
                }
                //else if (classname.Contains("TString") || classname.Contains("vector<float>")) {
                else if (classname.Contains("TString")) {
                    headerf << "\t" << classname << " " << aliasname << "_;" << endl;
                } 
                else {
                    headerf << "\t" << classname << " *" << aliasname << "_;" << endl;
                }
            } else {
                if(title.EndsWith("/i"))
                    headerf << "\tunsigned int" << "\t" << aliasname << "_;" << endl;
                if(title.EndsWith("/F"))
                    headerf << "\tfloat" << "\t" << aliasname << "_;" << endl;
                if(title.EndsWith("/I"))
                    headerf << "\tint" << "\t" << aliasname << "_;" << endl;
                if(title.EndsWith("/O"))
                    headerf << "\tbool" << "\t" << aliasname << "_;" << endl;
            }
        }
        headerf << "\tTBranch *" << Form("%s_branch",aliasname.Data()) << ";" << endl;
        headerf << "\tbool " << Form("%s_isLoaded",aliasname.Data()) << ";" << endl;
    }
  
  
    headerf << "public: " << endl;
    headerf << "void Init(TTree *tree) {" << endl;
    

    // SetBranchAddresses for LorentzVectors
    // TBits also needs SetMakeClass(0)...
    for(Int_t i = 0; i< aliasarray->GetEntries(); i++) {
        TString aliasname(aliasarray->At(i)->GetName());
        // TBranch *branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        TBranch *branch = 0;
        if (have_aliases)
            branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        else
            branch = (TBranch*)aliasarray->At(i);

        TString classname = branch->GetClassName();
        TString branch_ptr = Form("%s_branch",aliasname.Data());
        if ( !classname.Contains("vector<vector") ) {
            if ( classname.Contains("Lorentz") || classname.Contains("PositionVector") || classname.Contains("TBits")) {
                headerf << "\t" << Form("%s_branch",aliasname.Data()) << " = 0;" << endl;
                if (have_aliases) {
                    headerf << "\t" << "if (tree->GetAlias(\"" << aliasname << "\") != 0) {" << endl;
                    headerf << "\t\t" << Form("%s_branch",aliasname.Data()) << " = tree->GetBranch(tree->GetAlias(\"" << aliasname << "\"));" << endl;
                    //headerf << "\t\t" << Form("%s_branch",aliasname.Data()) << "->SetAddress(&" << aliasname << "_);" << endl << "\t}" << endl;
                    headerf << Form("\t\tif (%s) {%s->SetAddress(&%s_);}\n\t}", branch_ptr.Data(), branch_ptr.Data(), aliasname.Data()) << endl;
                }
                else {
                    headerf << "\t" << "if (tree->GetBranch(\"" << aliasname << "\") != 0) {" << endl;
                    headerf << "\t\t" << Form("%s_branch",aliasname.Data()) << " = tree->GetBranch(\"" << aliasname << "\");" << endl;
                    //headerf << "\t\t" << Form("%s_branch",aliasname.Data()) << "->SetAddress(&" << aliasname << "_);" << endl << "\t}" << endl;
                    headerf << Form("\t\tif (%s) {%s->SetAddress(&%s_);}\n\t}", branch_ptr.Data(), branch_ptr.Data(), aliasname.Data()) << endl;
                }
            }
        }
    }


    // SetBranchAddresses for everything else
    headerf << "  tree->SetMakeClass(1);" << endl;
    for(Int_t i = 0; i< aliasarray->GetEntries(); i++) {
        TString aliasname(aliasarray->At(i)->GetName());
        // TBranch *branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        TBranch *branch = 0;
        if (have_aliases)
            branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        else
            branch = (TBranch*)aliasarray->At(i);

        TString classname = branch->GetClassName();
        TString branch_ptr = Form("%s_branch",aliasname.Data());
        if ( ! (classname.Contains("Lorentz") || classname.Contains("PositionVector") || classname.Contains("TBits")) || classname.Contains("vector<vector") ) {
            headerf << "\t" << Form("%s_branch",aliasname.Data()) << " = 0;" << endl;
            if (have_aliases) {
                headerf << "\t" << "if (tree->GetAlias(\"" << aliasname << "\") != 0) {" << endl;
                headerf << "\t\t" << Form("%s_branch",aliasname.Data()) << " = tree->GetBranch(tree->GetAlias(\"" << aliasname << "\"));" << endl;
                //headerf << "\t\t" << Form("%s_branch",aliasname.Data()) << "->SetAddress(&" << aliasname << "_);" << endl << "\t}" << endl;
                headerf << Form("\t\tif (%s) {%s->SetAddress(&%s_);}\n\t}", branch_ptr.Data(), branch_ptr.Data(), aliasname.Data()) << endl;
            }
                else {
                    headerf << "\t" << "if (tree->GetBranch(\"" << aliasname << "\") != 0) {" << endl;
                    headerf << "\t\t" << Form("%s_branch",aliasname.Data()) << " = tree->GetBranch(\"" << aliasname << "\");" << endl;
                    //headerf << "\t\t" << Form("%s_branch",aliasname.Data()) << "->SetAddress(&" << aliasname << "_);" << endl << "\t}" << endl;
                    headerf << Form("\t\tif (%s) {%s->SetAddress(&%s_);}\n\t}", branch_ptr.Data(), branch_ptr.Data(), aliasname.Data()) << endl;
                }
        }
    }

    headerf << "  tree->SetMakeClass(0);" << endl;
    headerf << "}" << endl;

    // GetEntry
    headerf << "void GetEntry(unsigned int idx) " << endl;
    headerf << "\t// this only marks branches as not loaded, saving a lot of time" << endl << "\t{" << endl;
    headerf << "\t\tindex = idx;" << endl;
    for(Int_t i = 0; i< aliasarray->GetEntries(); i++) {
        TString aliasname(aliasarray->At(i)->GetName());
        headerf << "\t\t" << Form("%s_isLoaded",aliasname.Data()) << " = false;" << endl;
    }
    headerf << "\t}" << endl << endl;

    // LoadAllBranches
    headerf << "void LoadAllBranches() " << endl;
    headerf << "\t// load all branches" << endl << "{" << endl;
    for(Int_t i = 0; i< aliasarray->GetEntries(); i++) {
        TString aliasname(aliasarray->At(i)->GetName());
        headerf << "\t" << "if (" << aliasname.Data() <<  "_branch != 0) " << Form("%s();",aliasname.Data()) << endl;
    }
    headerf << "}" << endl << endl;

    // accessor functions
    for (Int_t i = 0; i< aliasarray->GetEntries(); i++) {
        TString aliasname(aliasarray->At(i)->GetName());
        // TBranch *branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        TBranch *branch = 0;
        if (have_aliases)
            branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        else
            branch = (TBranch*)aliasarray->At(i);

        TString classname = branch->GetClassName();
        TString title = branch->GetTitle();
        bool isSkimmedNtuple = false;
        if(!classname.Contains("edm::Wrapper<") &&
           (classname.Contains("vector") || classname.Contains("LorentzVector") ) )
            isSkimmedNtuple = true;
        if ( classname.Contains("vector") ) {
            if(classname.Contains("edm::Wrapper<") ) {
                classname = classname(0,classname.Length()-2);
                classname.ReplaceAll("edm::Wrapper<","");
            }
            headerf << "\tconst " << classname << " &" << aliasname << "()" << endl;
        } else {
            if(classname.Contains("edm::Wrapper<") ) {
                classname = classname(0,classname.Length()-1);
                classname.ReplaceAll("edm::Wrapper<","");
            }
            if(classname != "" ) {
                headerf << "\t" << classname << " &" << aliasname << "()" << endl;
            } else {
                if(title.EndsWith("/i"))
                    headerf << "\tunsigned int &" << aliasname << "()" << endl;
                if(title.EndsWith("/F"))
                    headerf << "\tfloat &" << aliasname << "()" << endl;
                if(title.EndsWith("/I"))
                    headerf << "\tint &" << aliasname << "()" << endl;
                if(title.EndsWith("/O"))
                    headerf << "\tbool &" << "\t" << aliasname << "()" << endl;
            }
        }
        aliasname = aliasarray->At(i)->GetName();
        headerf << "\t{" << endl;
        headerf << "\t\t" << "if (not " << Form("%s_isLoaded) {",aliasname.Data()) << endl;
        headerf << "\t\t\t" << "if (" << Form("%s_branch",aliasname.Data()) << " != 0) {" << endl;
        headerf << "\t\t\t\t" << Form("%s_branch",aliasname.Data()) << "->GetEntry(index);" << endl;
        if (paranoid) {
            headerf << "\t\t\t\t#ifdef PARANOIA" << endl;
            if (classname == "vector<vector<float> >") {
                if(isSkimmedNtuple) {
                    headerf << "\t\t\t\t" << "for (vector<vector<float> >::const_iterator i = " 
                            << aliasname << "_->begin(); i != "<< aliasname << "_->end(); ++i) {" << endl;
                } else {
                    headerf << "\t\t\t\t" << "for (vector<vector<float> >::const_iterator i = " 
                            << aliasname << "_.begin(); i != "<< aliasname << "_.end(); ++i) {" << endl;
                }
                headerf << "\t\t\t\t\t" << "for (vector<float>::const_iterator j = i->begin(); " 
                    "j != i->end(); ++j) {" << endl;
                headerf << "\t\t\t\t\t\t" << "if (not isfinite(*j)) {" << endl;
                headerf << "\t\t\t\t\t\t\t" << "printf(\"branch " << Form("%s_branch",aliasname.Data()) 
                        << " contains a bad float: %f\\n\", *j);" << endl << "\t\t\t\t\t\t\t" << "exit(1);"
                        << endl;
                headerf << "\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}" << endl;
            } else if (classname == "vector<float>") {
                if(isSkimmedNtuple) {
                    headerf << "\t\t\t\t" << "for (vector<float>::const_iterator i = " 
                            << aliasname << "_->begin(); i != "<< aliasname << "_->end(); ++i) {" << endl;
                } else {
                    headerf << "\t\t\t\t" << "for (vector<float>::const_iterator i = " 
                            << aliasname << "_.begin(); i != "<< aliasname << "_.end(); ++i) {" << endl;
                }
                headerf << "\t\t\t\t\t" << "if (not isfinite(*i)) {" << endl;
                headerf << "\t\t\t\t\t\t" << "printf(\"branch " << Form("%s_branch",aliasname.Data()) 
                        << " contains a bad float: %f\\n\", *i);" << endl << "\t\t\t\t\t\t" << "exit(1);"
                        << endl;
                headerf << "\t\t\t\t\t}\n\t\t\t\t}" << endl;
            } else if (classname == "float") {
                headerf << "\t\t\t\t" << "if (not isfinite(" << aliasname << "_)) {" << endl;
                headerf << "\t\t\t\t\t" << "printf(\"branch " << Form("%s_branch",aliasname.Data()) 
                        << " contains a bad float: %f\\n\", " << aliasname << "_);" << endl 
                        << "\t\t\t\t\t" << "exit(1);"
                        << endl;
                headerf << "\t\t\t\t}" << endl;
            } else if (classname.BeginsWith("vector<vector<ROOT::Math::LorentzVector")) {
                if(isSkimmedNtuple) {
                    headerf << "\t\t\t\t" << "for (" << classname.Data() <<"::const_iterator i = " 
                            << aliasname << "_->begin(); i != "<< aliasname << "_->end(); ++i) {" << endl;
                } else {
                    headerf << "\t\t\t\t" << "for (" << classname.Data() <<"::const_iterator i = " 
                            << aliasname << "_.begin(); i != "<< aliasname << "_.end(); ++i) {" << endl;
                }
                // this is a slightly hacky way to get rid of the outer vector< > ...
                std::string str = classname.Data() + 7;
                str[str.length() - 2] = 0;
                headerf << "\t\t\t\t\t" << "for (" << str.c_str() << "::const_iterator j = i->begin(); " 
                    "j != i->end(); ++j) {" << endl;
                headerf << "\t\t\t\t\t\t" << "int e;" << endl;
                headerf << "\t\t\t\t\t\t" << "frexp(j->pt(), &e);" << endl;
                headerf << "\t\t\t\t\t\t" << "if (not isfinite(j->pt()) || e > 30) {" << endl;
                headerf << "\t\t\t\t\t\t\t" << "printf(\"branch " << Form("%s_branch",aliasname.Data()) 
                        << " contains a bad float: %f\\n\", j->pt());" << endl << "\t\t\t\t\t\t\t" << "exit(1);"
                        << endl;
                headerf << "\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}" << endl;
            } else if (classname.BeginsWith("vector<ROOT::Math::LorentzVector")) {
                if(isSkimmedNtuple) {
                    headerf << "\t\t\t\t" << "for (" << classname.Data() << "::const_iterator i = " 
                            << aliasname << "_->begin(); i != "<< aliasname << "_->end(); ++i) {" << endl;
                } else {
                    headerf << "\t\t\t\t" << "for (" << classname.Data() << "::const_iterator i = " 
                            << aliasname << "_.begin(); i != "<< aliasname << "_.end(); ++i) {" << endl;
                }
                headerf << "\t\t\t\t\t" << "int e;" << endl;
                headerf << "\t\t\t\t\t" << "frexp(i->pt(), &e);" << endl;
                headerf << "\t\t\t\t\t" << "if (not isfinite(i->pt()) || e > 30) {" << endl;
                headerf << "\t\t\t\t\t\t" << "printf(\"branch " << Form("%s_branch",aliasname.Data()) 
                        << " contains a bad float: %f\\n\", i->pt());" << endl << "\t\t\t\t\t\t" << "exit(1);"
                        << endl;
                headerf << "\t\t\t\t\t}\n\t\t\t\t}" << endl;
            } else if (classname.BeginsWith("ROOT::Math::LorentzVector")) {
                headerf << "\t\t\t\t" << "int e;" << endl;
                if(isSkimmedNtuple) {
                    headerf << "\t\t\t\t" << "frexp(" << aliasname << "_->pt(), &e);" << endl;
                    headerf << "\t\t\t\t" << "if (not isfinite(" << aliasname << "_->pt()) || e > 30) {" << endl;
                    headerf << "\t\t\t\t\t" << "printf(\"branch " << Form("%s_branch",aliasname.Data()) 
                            << " contains a bad float: %f\\n\", " << aliasname << "_->pt());" << endl 
                            << "\t\t\t\t\t" << "exit(1);"
                            << endl;
                } else {
                    headerf << "\t\t\t\t" << "frexp(" << aliasname << "_.pt(), &e);" << endl;
                    headerf << "\t\t\t\t" << "if (not isfinite(" << aliasname << "_.pt()) || e > 30) {" << endl;
                    headerf << "\t\t\t\t\t" << "printf(\"branch " << Form("%s_branch",aliasname.Data()) 
                            << " contains a bad float: %f\\n\", " << aliasname << "_.pt());" << endl 
                            << "\t\t\t\t\t" << "exit(1);"
                            << endl;
                }
                headerf << "\t\t\t\t}" << endl;
            }
            headerf << "\t\t\t\t#endif // #ifdef PARANOIA" << endl;
        }
        headerf << "\t\t\t" << "} else { " << endl;
        headerf << "\t\t\t\t" << "printf(\"branch " << Form("%s_branch",aliasname.Data()) 
                << " does not exist!\\n\");" << endl;
        headerf << "\t\t\t\t" << "exit(1);" << endl << "\t\t\t}" << endl;
        headerf << "\t\t\t" << Form("%s_isLoaded",aliasname.Data()) << " = true;" << endl;
        headerf << "\t\t" << "}" << endl;
        if(isSkimmedNtuple) {
            headerf << "\t\t" << "return *" << aliasname << "_;" << endl << "\t}" << endl;
        }
        else if(classname.Contains("vector<TString>") || classname.Contains("vector<float>")) {
            headerf << "\t\t" << "return " << aliasname << "_;" << endl << "\t}" << endl;
        }
        else if(classname == "TString") {
            headerf << "\t\t" << "return *" << aliasname << "_;" << endl << "\t}" << endl;
        }
        else {
            headerf << "\t\t" << "return " << aliasname << "_;" << endl << "\t}" << endl;
        }
    }

    bool haveHLTInfo = false;
    bool haveL1Info  = false;
    bool haveHLT8E29Info = false;
    for(int i = 0; i < aliasarray->GetEntries(); i++) {
        TString aliasname(aliasarray->At(i)->GetName());
        if(aliasname=="hlt_trigNames") 
            haveHLTInfo = true;
        if(aliasname=="l1_trigNames") 
            haveL1Info = true;
        if(aliasname=="hlt8e29_trigNames") 
            haveHLT8E29Info = true;
    }
   
    if(haveHLTInfo) {
        //functions to return whether or not trigger fired - HLT
        headerf << "\t" << "bool passHLTTrigger(TString trigName) {" << endl;
        headerf << "\t\t" << "int trigIndx;" << endl;
        headerf << "\t\t" << "vector<TString>::const_iterator begin_it = hlt_trigNames().begin();" << endl;
        headerf << "\t\t" << "vector<TString>::const_iterator end_it = hlt_trigNames().end();" << endl;
        headerf << "\t\t" << "vector<TString>::const_iterator found_it = find(begin_it, end_it, trigName);" << endl;
        headerf << "\t\t" << "if(found_it != end_it)" << endl;
        headerf << "\t\t\t" << "trigIndx = found_it - begin_it;" << endl;
        headerf << "\t\t" << "else {" << endl;
        headerf << "\t\t\t" << "cout << \"Cannot find Trigger \" << trigName << endl; " << endl;
        headerf << "\t\t\t" << "return 0;" << endl;
        headerf << "\t\t"   << "}" << endl << endl;
        headerf << "\t" << "return hlt_bits().TestBitNumber(trigIndx);" << endl;
        headerf << "\t" << "}" << endl;
    }//if(haveHLTInfo) 

    if(haveHLT8E29Info) {
        //functions to return whether or not trigger fired - HLT
        headerf << "\t" << "bool passHLT8E29Trigger(TString trigName) {" << endl;
        headerf << "\t\t" << "int trigIndx;" << endl;
        headerf << "\t\t" << "vector<TString>::const_iterator begin_it = hlt8e29_trigNames().begin();" << endl;
        headerf << "\t\t" << "vector<TString>::const_iterator end_it = hlt8e29_trigNames().end();" << endl;
        headerf << "\t\t" << "vector<TString>::const_iterator found_it = find(begin_it, end_it, trigName);" << endl;
        headerf << "\t\t" << "if(found_it != end_it)" << endl;
        headerf << "\t\t\t" << "trigIndx = found_it - begin_it;" << endl;
        headerf << "\t\t" << "else {" << endl;
        headerf << "\t\t\t" << "cout << \"Cannot find Trigger \" << trigName << endl; " << endl;
        headerf << "\t\t\t" << "return 0;" << endl;
        headerf << "\t\t"   << "}" << endl << endl;
        headerf << "\t" << "return hlt8e29_bits().TestBitNumber(trigIndx);" << endl;
        headerf << "\t" << "}" << endl;
    }//if(haveHLT8E29Info) 


    if(haveL1Info) {
        //functions to return whether or not trigger fired - L1
        headerf << "\t" << "bool passL1Trigger(TString trigName) {" << endl;
        headerf << "\t\t" << "int trigIndx;" << endl;
        headerf << "\t\t" << "vector<TString>::const_iterator begin_it = l1_trigNames().begin();" << endl;
        headerf << "\t\t" << "vector<TString>::const_iterator end_it = l1_trigNames().end();" << endl;
        headerf << "\t\t" << "vector<TString>::const_iterator found_it = find(begin_it, end_it, trigName);" << endl;
        headerf << "\t\t" << "if(found_it != end_it)" << endl;
        headerf << "\t\t\t" << "trigIndx = found_it - begin_it;" << endl;
        headerf << "\t\t" << "else {" << endl;
        headerf << "\t\t\t" << "cout << \"Cannot find Trigger \" << trigName << endl; " << endl;
        headerf << "\t\t\t" << "return 0;" << endl;
        headerf << "\t\t"   << "}" << endl << endl;
        //get the list of branches that hold the L1 bitmasks
        //store in a set 'cause its automatically sorted
        set<TString> s_L1bitmasks;
        for(int j = 0; j < aliasarray->GetEntries(); j++) {
            TString aliasname(aliasarray->At(j)->GetName());
            // TBranch *branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
            TBranch *branch = 0;
            if (have_aliases)
                branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
            else
                branch = (TBranch*)aliasarray->At(j);

            TString classname = branch->GetClassName();
            if(aliasname.Contains("l1_bits") && classname.Contains("int")) {
                s_L1bitmasks.insert(aliasname);
            }
     
        }
        int i = 0;
        for(set<TString>::const_iterator s_it = s_L1bitmasks.begin();
            s_it != s_L1bitmasks.end(); s_it++, i++) {
      
            if(i==0) {
                headerf << "\t\t" << "if(trigIndx <= 31) {" << endl;
                headerf << "\t\t\t" << "unsigned int bitmask = 1;" << endl;
                headerf << "\t\t\t" << "bitmask <<= trigIndx;" << endl;	
                headerf << "\t\t\t" << "return " << *s_it << "() & bitmask;" << endl;
                headerf << "\t\t" << "}" << endl;
                continue;
            }
            headerf << "\t\t" << "if(trigIndx >= " << Form("%d && trigIndx <= %d", 32*i, 32*i+31) << ") {" << endl;
            headerf << "\t\t\t" << "unsigned int bitmask = 1;" << endl;
            headerf << "\t\t\t" << "bitmask <<= (trigIndx - " << Form("%d",32*i) << "); " << endl;	
            headerf << "\t\t\t" << "return " << *s_it << "() & bitmask;" << endl;
            headerf << "\t\t" << "}" << endl;
        }
        headerf << "\t" << "return 0;" << endl;
        headerf << "\t" << "}" << endl;
    }//if(haveL1Info)
    
    headerf << endl;
    headerf << "  static void progress( int nEventsTotal, int nEventsChain ){" << endl;
    headerf << "    int period = 1000;" << endl;
    headerf << "    if(nEventsTotal%1000 == 0) {" << endl;
    headerf << "      // xterm magic from L. Vacavant and A. Cerri" << endl;
    headerf << "      if (isatty(1)) {" << endl;
    headerf << "        if( ( nEventsChain - nEventsTotal ) > period ){" << endl;
    headerf << "          float frac = (float)nEventsTotal/(nEventsChain*0.01);" << endl;
    headerf << "          printf(\"\\015\\033[32m ---> \\033[1m\\033[31m%4.1f%%\"" << endl;
    headerf << "               \"\\033[0m\\033[32m <---\\033[0m\\015\", frac);" << endl;
    headerf << "          fflush(stdout);" << endl;
    headerf << "        }" << endl;
    headerf << "        else {" << endl;
    headerf << "          printf(\"\\015\\033[32m ---> \\033[1m\\033[31m%4.1f%%\"" << endl;
    headerf << "                 \"\\033[0m\\033[32m <---\\033[0m\\015\", 100.);" << endl;
    headerf << "          cout << endl;" << endl;
    headerf << "        }" << endl;
    headerf << "      }" << endl;
    headerf << "    }" << endl;
    headerf << "  }" << endl;
    headerf << "  " << endl;

    headerf << "};" << endl << endl;
    
    headerf << "#ifndef __CINT__" << endl;
    headerf << "extern " << Classname << " " << objName << ";" << endl;
    headerf << "#endif" << endl << endl;

    // Create namespace that can be used to access the extern'd cms2
    // object methods without having to type cms2. everywhere.
    // Does not include cms2.Init and cms2.GetEntry because I think
    // it is healthy to leave those methods as they are
    headerf << "namespace " << nameSpace << " {" << endl;
    implf   << "namespace " << nameSpace << " {" << endl;
    for (Int_t i = 0; i< aliasarray->GetEntries(); i++) {
        TString aliasname(aliasarray->At(i)->GetName());
        // TBranch *branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        TBranch *branch = 0;
        if (have_aliases)
            branch = ev->GetBranch(ev->GetAlias(aliasname.Data()));
        else
            branch = (TBranch*)aliasarray->At(i);

        TString classname = branch->GetClassName();
        TString title = branch->GetTitle();
        if ( classname.Contains("vector") ) {
            if(classname.Contains("edm::Wrapper") ) {
                classname = classname(0,classname.Length()-2);
                classname.ReplaceAll("edm::Wrapper<","");
            }
            headerf << "\tconst " << classname << " &" << aliasname << "()";
            implf   << "\tconst " << classname << " &" << aliasname << "()";
        } else {
            if(classname.Contains("edm::Wrapper<") ) {
                classname = classname(0,classname.Length()-1);
                classname.ReplaceAll("edm::Wrapper<","");
            }
            if(classname != "" ) {
                headerf << "\tconst " << classname << " &" << aliasname << "()";
                implf   << "\tconst " << classname << " &" << aliasname << "()";
            } else {
                if(title.EndsWith("/i")){
                    headerf << "\tconst unsigned int &" << aliasname << "()";
                    implf   << "\tconst unsigned int &" << aliasname << "()";
                }
                if(title.EndsWith("/F")){
                    headerf << "\tconst float &" << aliasname << "()";
                    implf   << "\tconst float &" << aliasname << "()";
                }
                if(title.EndsWith("/I")){
                    headerf << "\tconst int &" << aliasname << "()";
                    implf   << "\tconst int &" << aliasname << "()";
                }
                if(title.EndsWith("/O")){
                    headerf << "\tconst bool &" << aliasname << "()";
                    implf   << "\tconst bool &" << aliasname << "()";
                }
            }
        }
        headerf << ";" << endl;
        implf   << " { return " << objName << "." << aliasname << "(); }" << endl;
    }
    if(haveHLTInfo) {
        //functions to return whether or not trigger fired - HLT
        headerf << "\t" << "bool passHLTTrigger(TString trigName);" << endl;
        implf   << "\t" << "bool passHLTTrigger(TString trigName) { return " << objName << ".passHLTTrigger(trigName); }" << endl;
    }//if(haveHLTInfo) 
    if(haveHLT8E29Info) {
        //functions to return whether or not trigger fired - HLT
        headerf << "\t" << "bool passHLT8E29Trigger(TString trigName);" << endl;
        implf   << "\t" << "bool passHLT8E29Trigger(TString trigName) { return " << objName << ".passHLT8E29Trigger(trigName); }" << endl;
    }//if(haveHLT8E29Info) 
    if(haveL1Info) {
        //functions to return whether or not trigger fired - L1
        headerf << "\t" << "bool passL1Trigger(TString trigName);" << endl;
        implf   << "\t" << "bool passL1Trigger(TString trigName) { return " << objName << ".passL1Trigger(trigName); }" << endl;
    }//if(haveL1Info)
 
}
Ejemplo n.º 29
0
void
Enlarge(Int_t i)
{
  
  //  toolcanvas->cd();
  TObject *o;
  TList *ll = toolcanvas->GetListOfPrimitives();
  for (Int_t ii=ll->GetEntries()-1; ii>=0; ii--)
    {
      o = ll->At(ii);
      ll->Remove(o);
    }
  toolcanvas->SetWindowSize(toolw-28, toolh-8);
  toolcanvas->cd();
  bclose->Draw();

  //  canvas->cd();
  vp = (TPad*)canvas->GetListOfPrimitives()->At(i);
  if (!vp) return;
  // else
  //   cout << "selected pad name " << vp->GetName() << endl;

  TList *alist;
  if (vp->GetListOfPrimitives()->GetEntries() > 1)
    {
      graph0 = (TH1*) vp->GetListOfPrimitives()->At(1);
      //      graph1 = (TH1*) graph0->Clone("graph1");
      alist = vp->GetListOfPrimitives();
    }
  else
    return;
  
  Char_t opt[50];
  strcpy(opt,graph0->GetDrawOption());

  //  display->Draw();
  display = SafeConstructCanvas("display");
  display->Draw();
  display->cd();
  gROOT->SetSelectedPad(display);

  // std::cout << "______Drawing Pad______\n\t" 
  // 	  << gPad->GetName() << std::endl;

  TString option;
  TH1* anh, *anhh;
  TObject *oo;
  for (Int_t i=1; i<alist->GetEntries(); i++)
    {
      oo = alist->At(i);

      if (oo->InheritsFrom(TH1::Class()))
        {
	anh = static_cast<TH1*>(oo);
	option = anh->GetDrawOption();
	option += "HE";
	if (i>1)
	  option += "same";

	if (oo->InheritsFrom(TH2::Class()))
	  anhh = anh->DrawCopy("colz");
	else
	  anhh = anh->DrawCopy(option.Data());
	anhh->SetFillStyle(0);
	anhh->SetLineColor(anh->GetLineColor());
	cout << anhh->GetName() << " with option=\"" 
	     << option.Data() << "\"" 
	     << " lcolor=" << anhh->GetLineColor()
	     << " fcolor=" << anhh->GetFillColor()
	     << " fstyle=" << anhh->GetFillStyle()
	     << flush << endl;
	display->Modified();
	display->Update();
	//	gSystem->Sleep(5000);
	
	//	anhh->SetFillColor(anh->GetFillColor());
	//	anhh->SetFillStyle(anh->GetFillStyle());
        }
      else if (i<alist->GetEntries()-1)
        oo->Draw();
    }
  display->Modified();
  display->Update();

  
}
Ejemplo n.º 30
0
void Embedding(const char* dataset="collection.xml")
{
    
  gSystem->Load("libTree");
  gSystem->Load("libGeom");
  gSystem->Load("libVMC");
  gSystem->Load("libPhysics");
  
  //load analysis framework
  gSystem->Load("libSTEERBase");
  gSystem->Load("libANALYSIS");
  gSystem->Load("libANALYSISalice"); //AliAnalysisTaskSE
  
  gSystem->AddIncludePath("-I$ALICE_ROOT/include -I$ALICE_ROOT/PHOS");

  // A task can be compiled dynamically with AClic
  gROOT->LoadMacro("AliPHOSEmbedding.cxx+g");
  
  // Connect to alien
  TString token = gSystem->Getenv("GRID_TOKEN") ;
  if (1) // token == "OK" ) 
    TGrid::Connect("alien://");
  else 
    AliInfo("You are not connected to the GRID") ; 
  cout << "Pi0Analysis: processing collection " << dataset << endl;
  
  // Create the chain
  TChain* chain = new TChain("esdTree");

  TGridCollection * collection = dynamic_cast<TGridCollection*>(TAlienCollection::Open(dataset));
  
  TAlienResult* result = collection->GetGridResult("",0 ,0);
  TList* rawFileList = result->GetFileInfoList();
  for (Int_t counter=0 ; counter < rawFileList->GetEntries() ; counter++) {
    TFileInfo * fi =  static_cast<TFileInfo*>(rawFileList->At(counter)) ; 
    const char * rawFile = fi->GetCurrentUrl()->GetUrl() ;  
    printf("Processing %s\n", rawFile) ;
    chain->Add(rawFile);
    printf("Chain: %d entries.\n",chain->GetEntries()); 
  }
  TFileInfo * fi =  static_cast<TFileInfo*>(rawFileList->At(0));
  const char * fn = fi->GetCurrentUrl()->GetUrl() ;

  char runNum[7]; 
  for(Int_t i=0;i<6;i++)runNum[i]=fn[35+i] ;

  runNum[6]=0 ;
  Int_t iRunNum=atoi(runNum) ;
  printf("Run number=%d \n",iRunNum) ;

  //Run AOD simulation
  int nrun = atoi(runNum);
  int nevent = 0;
  int seed = 0;

  char sseed[1024];
  char sevent[1024];
  char sprocess[1024];
  char sfield[1024];
  char senergy[1024];

  sprintf(sevent,"");
  sprintf(sprocess,"");
  sprintf(sfield,"");
  sprintf(senergy,"");

  seed = 0;
  sprintf(sseed,"%d",seed);

  if (seed==0) {
    fprintf(stderr,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
    fprintf(stderr,"!!!!  WARNING! Seeding variable for MC is 0          !!!!\n");
    fprintf(stderr,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
  } else {
    fprintf(stdout,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
    fprintf(stdout,"!!!  MC Seed is %d \n",seed);
    fprintf(stdout,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
  }
  
// set the seed environment variable
  gSystem->Setenv("CONFIG_SEED",sseed);
  gSystem->Setenv("CONFIG_RUN_TYPE","kPythia6"); // kPythia6 or kPhojet^M
  gSystem->Setenv("CONFIG_FIELD","k5kG");      // kNoField or k5kG^M
  gSystem->Setenv("CONFIG_ENERGY","2760");    // 900 or 10000 (GeV)
  gSystem->Setenv("DC_RUN",runNum);    //run number 
  

  char nSimEvents[55] ;
  sprintf(nSimEvents,"%d",chain->GetEntries());
  gSystem->Setenv("SIM_EVENTS",nSimEvents); 
  gSystem->Exec("mv geometry.root geometry_PHOS.root") ;
  gSystem->Exec("aliroot -b -q simrun.C > simrun.log 2>&1");
  gSystem->Exec("mv geometry_PHOS.root geometry.root") ;

  // Make the analysis manager
  AliAnalysisManager *mgr = new AliAnalysisManager("Pi0EmbeddingManager");
  
  // ESD input handler
  AliESDInputHandler* esdH = new AliESDInputHandler();
  esdH->SetReadFriends(kFALSE);
  mgr->SetInputEventHandler(esdH);

  // Output
  AliAODHandler* aodHandler   = new AliAODHandler();
  aodHandler->SetOutputFileName("AliAODout.root");
  mgr->SetOutputEventHandler(aodHandler);

  
  // Debug level
  mgr->SetDebugLevel(0);


  // Add physics selection
  gROOT->LoadMacro("$ALICE_ROOT/OADB/macros/AddTaskPhysicsSelection.C");
  AliPhysicsSelectionTask* physSelTask = AddTaskPhysicsSelection(kFALSE);

  gROOT->LoadMacro("$ALICE_ROOT/OADB/macros/AddTaskCentrality.C");
  AliCentralitySelectionTask *taskCentrality = AddTaskCentrality() ;

  gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskEventplane.C");
  AliEPSelectionTask *taskEP = AddTaskEventplane() ;

  // Add my task
  AliPHOSEmbedding *task1 = new AliPHOSEmbedding("Embedding");

  TChain* chainAOD = new TChain("aodTree");
  chainAOD->AddFile("AliAOD.root") ;
  task1->SetSignalChain(chainAOD) ;
  task1->SelectCollisionCandidates();


  TFile *fOldCalib = TFile::Open("OldCalibration.root");
  if(fOldCalib->IsOpen()){
    printf("\n\n...Adding PHOS calibration used in ESD production \n") ;
    char key[55] ;
    TH2F * hCalib[5] ;
    for(Int_t mod=0;mod<5; mod++){
      sprintf(key,"calibrationMod%d",mod) ;
      hCalib[mod] = (TH2F*)fOldCalib->Get(key) ;
    }
    task1->SetOldCalibration(hCalib) ;
    fOldCalib->Close() ;
  }

  mgr->AddTask(task1);
  
  // Create containers for input/output
  AliAnalysisDataContainer *cinput   = mgr->GetCommonInputContainer(); 
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("output0",
                      TTree::Class(), AliAnalysisManager::kOutputContainer);


  // Connect input/output
  mgr->ConnectInput(task1 , 0, cinput);
  mgr->ConnectOutput(task1, 0,coutput1);

  AliLog::SetClassDebugLevel("AliGeomManager", 10) ;

  AliCDBManager::Instance()->SetRun(iRunNum) ;
//  AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT/OCDB") ;
//  AliCDBManager::Instance()->SetDefaultStorage("raw://") ;
  AliCDBManager::Instance()->SetDefaultStorage("alien://folder=/alice/data/2010/OCDB") ;
  AliCDBManager::Instance()->SetSpecificStorage("PHOS/*/*",
                                                "local://OCDB");
printf("RunNunm===%d \n",iRunNum) ;
  

  if (mgr->InitAnalysis()) {
    mgr->PrintStatus();
    mgr->StartAnalysis("local", chain);
  }
  
  if(iRunNum<=137848){ //period 1
    gSystem->Exec("mv BadMap_LHC10h_period1.root BadMap_LHC10h.root") ;
  }
  else{
    gSystem->Exec("mv BadMap_LHC10h_period234.root BadMap_LHC10h.root") ;
  }
  gSystem->Exec("aliroot -b -q AnalyzeDiff.C> analyze3.log 2>&1");

}