示例#1
0
//to run in ROOT: .x runD3PDSelector.C
void runGangaTTreeCache() {

   cout << "Grid run, TTreeCache Enabled" <<endl;
   
   char *rpath  = getenv( "PWD" );
   std::string filename = "./input.txt";

   if (!( rpath == 0 )) { // if ENV-var not set use default
     std::string path(rpath);
     filename =  path+"/input.txt";
   }

  cout << "Reading input file "<<filename<<endl;
  
  
  TChain *c = new TChain("susy");

//  TFileCollection* fc = new TFileCollection("mylist", "mylist",filename);
//  c->AddFileInfoList((TCollection*)fc->GetList());
  

  std::string argStr;

  char *filechar = filename.c_str(); 
   
  std::ifstream ifs(filechar);

  std::vector<std::string> fileList;

  // split by '\n'
  int nfiles = 0;
  while (std::getline(ifs,argStr)) {
    for (size_t i=0,n; i <= argStr.length(); i=n+1) {
      n = argStr.find_first_of('\n',i);
      if (n == std::string::npos)
        n = argStr.length();
      TString tmp = argStr.substr(i,n-i);//std::string
      nfiles++;
      cout << "Adding file "<<tmp<<" nb "<<nfiles<<endl;
      c->Add(tmp);
    }
  }

   int nentries = c->GetEntries();
   std::cout << "Total number of entries in chain (after all the files) " <<  c->GetEntries() << std::endl;

  //  GD use TTreeCache (disabled by default in ROOT5.28)
  //c->SetCacheSize(100000000);

  //  GD DO NOT use TTreeCache (enabled by default in ROOT5.26)
  c->SetCacheSize(0);

  //c->SetProof();
  c->Process("D3PDSelector.C+O");
 
  // Create AthSummary.txt for the pilot
  ofstream outf("AthSummary.txt"); 
//  outf << "Files read: " << fc->GetNFiles() << std::endl; 
  outf << "Files read: " << nfiles << std::endl; 
  outf << "Events Read: " << nentries << std::endl; 
  outf << "{ \"events\":{\"read\":" << nentries << "} "  << "}" << std::endl;
  outf.close();
  system("cp AthSummary.txt ..");
  
  c->Delete();

  cout << "All done, quitting ROOT..."<<endl;
  
  //quit root
  gApplication->Terminate();

  } 
示例#2
0
//*******MAIN*******************************************************************
int main (int argc, char** argv)
{  
    std::cout<<"--------DUMPER TEMPLATE FIT: READ RAW DATA AND PRODUCE RECO TREE--------"<<std::endl;

    //-----this map tells how the MCPs will be order in the output tree. The names should match the cfg file----
    Fill_MCPList();  //look into the MCPMap.h class
    
    //--------Read Options--------------------------------
    ifstream inputCfg (argv[1], ios::in);

    std::string inputFolder = argv[2];
    int nChannels = atoi (argv[3]);
    std::string outputFile = argv[4];
    std::string ProMedioFile = argv[5];

    TProfile** wf_promed = new TProfile*[10];
    TH1F** templateHisto = new TH1F*[10];
    double pro_medio_CF[10] = {0., 0., 0., 0., 0., 0., 0., 0., 0., 0.};
    double pro_medio_Charge[10] = {0., 0., 0., 0., 0., 0., 0., 0., 0., 0.};
    TFile* inF = TFile::Open(ProMedioFile.c_str(),"read");                                                                
    for(int iCh=0; iCh<10; ++iCh) {
      wf_promed[iCh] = (TProfile*)inF->Get(Form("wf_promed_%d",iCh));                                                        
      wf_promed[iCh]->SetDirectory(0);                                                                                       
    }
    inF->Close();
    inF->Delete();                       
    for(int iCh=0; iCh<10; ++iCh) {                                                                                       
      templateHisto[iCh] = new TH1F(Form("templateHisto_%d",iCh), "", 1024, 0., 1024.);                                      
      for(int iBins=1; iBins<=1024; ++iBins) {
	if(iBins <= 100) templateHisto[iCh]->SetBinContent(iBins, wf_promed[iCh]->GetBinContent(iBins+150));  
	else if(iBins > 100 && iBins < 250) templateHisto[iCh]->SetBinContent(iBins, templateHisto[iCh]->GetBinContent(iBins-100));  
	else templateHisto[iCh]->SetBinContent(iBins, wf_promed[iCh]->GetBinContent(iBins));
      }
      double amp = 0.5;
      TimeConstFrac_ProMedio(templateHisto[iCh], amp, pro_medio_CF[iCh]);
      pro_medio_Charge[iCh] = templateHisto[iCh]->Integral(pro_medio_CF[iCh]-5, pro_medio_CF[iCh]+20);
      wf_promed[iCh]->Delete();                                                                                              
      //            std::cout << " iCh = " << iCh << " pro_medio_CF[iCh] = " << pro_medio_CF[iCh] << " pro_medio_Charge[iCh] = " << pro_medio_Charge[iCh] << std::endl;
    }                                                                                                                     


    // for(int iCh=0; iCh<10; ++iCh) std::cout << " templateHisto[iCh]->GetEntries() = " << templateHisto[iCh]->GetEntries() << std::endl;
    //    return 500;                                                                                            


    //---------output tree----------------
    TFile* outROOT = TFile::Open(("ntuples/reco_"+outputFile+".root").c_str(),"recreate");  
    outROOT->cd();
    
    TTree* outTree = new TTree("reco_tree", "reco_tree");
    outTree->SetDirectory(0);
    SetOutTree(outTree);
    
   
    int run=0, chNumber=0, HVtemp=0, PC=0;
    float X0temp=0.;
    std::string name, trig1, trig2;

    //---------definitions-----------
    std::map<int, int> PCOn;
    std::map<int, int> HVVal; 
    std::map<int, std::string> MCPName; 

    int start=0;
    //-------start to read the cfg file--------
    while(!inputCfg.eof())  
    {
      PCOn.clear();
      HVVal.clear();
      MCPName.clear();

      if (start==0) {   //read trigger chambers
	inputCfg >> trig1 >> trig2;
	start=1;
      }

      //-----fill maps--------
      for (int count=0; count<nChannels; count++)   //read exactly nChannels lines of the cfg file -> be careful to give the right number in input!!!!
	{
	  inputCfg >> run >> chNumber >> HVtemp >> X0temp >> PC >> name;

	  PCOn.insert(std::make_pair(chNumber,PC)); 
	  HVVal.insert(std::make_pair(chNumber,HVtemp)); 
	  MCPName.insert(std::make_pair(chNumber,name)); 
	}

      //-----Definitions
      vector<float> digiCh[10];
      float timeCF[10], timeCFcorr[10];
      float timeOT[10];
      float timeMax[10];
      float intBase[10], intSignal[10], intSignalcorr[10], ampMax[10];
      ///int fibreX[8], hodoYchannels[8];
      
      TH1F** wfHisto = new TH1F*[10];
      TF1** f_templateFit = new TF1*[10];      

      //--reading wire chamber from other tree --
      TChain* t1 = new TChain("outputTree");
      InitTree2(t1);

      //---Chain
      TChain* chain = new TChain("H4tree");
      InitTree(chain);

      char command1[300];
      sprintf(command1, "find  %s/%d/*/dqmPlotstotal.root > listTemp_%s_%d.txt", (inputFolder).c_str(), run, outputFile.c_str(), run);
      system(command1);
      char command2[300];
      sprintf(command2, "find  %s/%d/[0-9]*.root > listTemp2_%s_%d.txt", (inputFolder).c_str(), run, outputFile.c_str(), run);
      system(command2);

      char list1[200];
      char list2[200];
      sprintf (list1, "listTemp_%s_%d.txt", outputFile.c_str(), run);
      sprintf (list2, "listTemp2_%s_%d.txt", outputFile.c_str(), run);

      ifstream rootList (list1);
      ifstream rootList2 (list2);

      while (!rootList.eof() && !rootList2.eof())
	{
	  char iRun_tW[70];
	  rootList >> iRun_tW;
	  char iRun_str[70];
	  rootList2 >> iRun_str;
	  
	  TChain* tTemp = new TChain("outputTree");
	  tTemp->Add(iRun_tW);
	  TChain* tTempH4 = new TChain("H4tree");
	  tTempH4->Add(iRun_str);
	  
	  if (tTemp->GetEntries() == tTempH4->GetEntries())
	    {
	      t1->Add(iRun_tW);	
	      chain->Add(iRun_str);	
	    }
	  else
	    std::cout<<"Bad spill found.. Skipped"<<std::endl;
	  tTemp->Delete();
	  tTempH4->Delete();
	}

      char command3[300];
      sprintf(command3, "rm listTemp_%s_%d.txt", outputFile.c_str(), run);
      char command4[300];
      sprintf(command4, "rm listTemp2_%s_%d.txt", outputFile.c_str(), run);
      
      system(command3);
      system(command4);
      
      std::cout<<"start reading run: "<<run<<std::endl;
      
      //-----Data loop--------------------------------------------------------
      for(int iEntry=0; iEntry<chain->GetEntries(); iEntry++){
	//      for(int iEntry=7; iEntry<8; iEntry++){    //RA
	if(iEntry % 1000 == 0)	cout << "read entry: " << iEntry << endl;
            //-----Unpack data--------------------------------------------------
            for(int iCh=0; iCh<nChannels; iCh++)
            {
                digiCh[iCh].clear();
		wfHisto[iCh] = new TH1F(Form("wfHisto_%d", iCh), "", 1024, 0., 1024.);
            }

            //---Read the entry
            chain->GetEntry(iEntry);
 
	    unsigned int spill=spillNumber;
	    unsigned int event=evtNumber;

	    /*	    for(unsigned int iCh=0; iCh<nAdcChannels; iCh++)
		{
                    if(adcBoard[iCh] == 1 && adcChannel[iCh] == 0) 
                        sci_front_adc = adcData[iCh];
		    if(adcBoard[iCh] == 1 && adcChannel[iCh] >= HODOX_ADC_START_CHANNEL &&
		       adcChannel[iCh] <= HODOX_ADC_END_CHANNEL)
			fibreX[(adcChannel[iCh]-HODOX_ADC_START_CHANNEL)] = adcData[iCh];
		    if(adcBoard[iCh] == 1 && adcChannel[iCh] >= HODOY_ADC_START_CHANNEL &&
		       adcChannel[iCh] <= HODOY_ADC_END_CHANNEL)
			fibreY[(adcChannel[iCh]-HODOY_ADC_START_CHANNEL)] = adcData[iCh];
		}
	    */
	    int tStart[10] = {0,0,0,0,0,0,0,0,0,0};
	    int tStop[10] = {0,0,0,0,0,0,0,0,0,0};
	    int tMax[10] = {0,0,0,0,0,0,0,0,0,0};
	    float aMax[10] = {10000., 10000., 10000., 10000., 10000., 10000., 10000., 10000., 10000., 10000.};
	    float bLine[10] = {0.,0.,0.,0.,0., 0.,0.,0.,0.,0.};
	    //---Read digitizer samples
	    for(unsigned int iSample=0; iSample<nDigiSamples; iSample++){
	      if(iSample > 1024*10 - 1) break;
	      if (digiGroup[iSample] == 1 && digiChannel[iSample] == 0){
		digiCh[9].push_back(digiSampleValue[iSample]);
		wfHisto[9]->SetBinContent((iSample%1024) + 1, digiSampleValue[iSample]);

		int iBin = (iSample%1024) + 1;
		float value = digiSampleValue[iSample];
		if((iBin >= 10 && iBin < 30) || (iBin >= 500 && iBin < 1000)) bLine[9] += value/520;
		//		if(digiChannel[iSample] == 9) std::cout << " value = " << value << std::endl;
		if(value < aMax[9]) { aMax[9] = value; tMax[9] = iBin; }
		if(iBin > 50 && value < 500. && tStart[9] == 0) tStart[9] = iBin;
		if(iBin > 50 && value > 500. && tStart[9] != 0 && tStop[9] == 0) tStop[9] = iBin;		
	      }
	      else{
		digiCh[digiChannel[iSample]].push_back(digiSampleValue[iSample]);
		wfHisto[digiChannel[iSample]]->SetBinContent((iSample%1024) + 1, digiSampleValue[iSample]); 

		int iBin = (iSample%1024) + 1;
		float value = digiSampleValue[iSample];
		if((iBin >= 10 && iBin < 30) || (iBin >= 500 && iBin < 1000)) bLine[digiChannel[iSample]] += value/520;
		if(digiChannel[iSample] == 9) std::cout << " value = " << value << std::endl;
		if(value < aMax[digiChannel[iSample]]) { aMax[digiChannel[iSample]] = value; tMax[digiChannel[iSample]] = iBin;}
		if(iBin > 50 && value < 500. && tStart[digiChannel[iSample]] == 0) tStart[digiChannel[iSample]] = iBin;
		if(iBin > 50 && value > 500. && tStart[digiChannel[iSample]] != 0 && 
		   tStop[digiChannel[iSample]] == 0) tStop[digiChannel[iSample]] = iBin;
	      }
	    }

	    //---loop over MPC's channels  
            for(int iCh=0; iCh<nChannels; iCh++){
	      if(iCh < 4) continue;
	      if(iCh == 8) continue;

	      // std::cout << " loop over MCP iCh = " << iCh  << std::endl;
	      // std::cout << " bLine[iCh] = " << bLine[iCh] << std::endl;
	      // std::cout << " aMax[iCh] = " << aMax[iCh] << std::endl;
	      // std::cout << " tMax[iCh] = " << tMax[iCh] << std::endl;
	      // std::cout << " tStart[iCh] = " << tStart[iCh] << std::endl;
	      // std::cout << " tStop[iCh] = " << tStop[iCh] << std::endl;

	      tMax[iCh] -= 300;

	      double scale = 0.;
	      double scaleErr = 0.;
	      double baseL = 0.;
	      double baseLErr = 0.;
	      double xTime = 0.;
	      double xTimeErr = 0.;
	      
	      FindTemplateFit(scale, scaleErr, baseL, baseLErr, xTime, xTimeErr, tStart[iCh], tStop[iCh], tMax[iCh], aMax[iCh], bLine[iCh], templateHisto[iCh], wfHisto[iCh], &(f_templateFit[iCh]));

	      float par0 = f_templateFit[iCh]->GetParameter(0);
	      float par1 = f_templateFit[iCh]->GetParameter(1);
	      float par2 = f_templateFit[iCh]->GetParameter(2);
	      float par3 = f_templateFit[iCh]->GetParameter(3);

	      ampMax[iCh] = par0;
	      //tMax
	      timeMax[iCh] = (300. / par1) + par2;
	      timeCF[iCh] = (pro_medio_CF[iCh] / par1) + par2;
	      intSignal[iCh] = pro_medio_Charge[iCh] * par0/par1 + par3/par1 * 25;
	      intBase[iCh] = par3;

	      timeOT[iCh] = par2;
	      intSignalcorr[iCh] = par1;
	      timeCFcorr[iCh] = timeCF[iCh];

	      // std::cout << " >> timeMax[iCh] = " << timeMax[iCh] << std::endl;
	      // std::cout << " >> timeCF[iCh] = " << timeCF[iCh] << std::endl;
	      // std::cout << " >> f_templateFit[iCh]->GetParameter(0) = " << f_templateFit[iCh]->GetParameter(0) << std::endl;

	      /*
	      if(iCh == 4){
		TCanvas* c1 = new TCanvas();
		templateHisto[iCh]->Draw();
		f_templateFit[iCh]->Draw("same");
		c1->Print("pippo.png", "png");

		TCanvas* c2 = new TCanvas();
		wfHisto[iCh]->Draw();
		f_templateFit[iCh]->Draw("same");
		c2->Print("pippo2.png", "png");
		
		TFile outFile_template("outFile_template.root", "recreate");
		outFile_template.cd();
		iCh = 4;
		templateHisto[iCh]->Write(Form("promedio_%d", iCh));
		wfHisto[iCh]->Write(Form("wfHisto_%d", iCh));
		f_templateFit[iCh]->Write(Form("func_%d", iCh));
		outFile_template.Close();
	      }
	      */
	    }

	    /*	    
	    TFile outFile_template("outFile_template.root", "recreate");
	    outFile_template.cd();
	    for(int iCh=0; iCh<nChannels; iCh++){
	      if(iCh < 4) continue;
	      if(iCh == 8) continue;

	      templateHisto[iCh]->Write(Form("promedio_%d", iCh));
	      wfHisto[iCh]->Write(Form("wfHisto_%d", iCh));
	      f_templateFit[iCh]->Write(Form("func_%d", iCh));
	    }
	    outFile_template.Close();
	    return 100;
	    */

	    //--------dump ntuple - impulses are negative, invert the sign
	    for (int iCh=0; iCh<nChannels; iCh++)
	      {
		    time_CF[MCPList.at(MCPName.at(iCh))]   = timeCF[iCh];
		    time_CF_corr[MCPList.at(MCPName.at(iCh))]   = timeCFcorr[iCh];
		    time_OT[MCPList.at(MCPName.at(iCh))]   = timeOT[iCh];
		    time_Max[MCPList.at(MCPName.at(iCh))]   = timeMax[iCh];
		    amp_max[MCPList.at(MCPName.at(iCh))]   = ampMax[iCh];
		    amp_max_corr[MCPList.at(MCPName.at(iCh))]   = ampMax[iCh];
		    charge[MCPList.at(MCPName.at(iCh))]    = -intSignal[iCh];
		    charge_corr[MCPList.at(MCPName.at(iCh))]    = -intSignalcorr[iCh];
		    baseline[MCPList.at(MCPName.at(iCh))]  = intBase[iCh];

		    isPCOn[MCPList.at(MCPName.at(iCh))]      = PCOn.at(iCh);
		    HV[MCPList.at(MCPName.at(iCh))]          = HVVal.at(iCh);
		    if (strcmp((MCPName.at(iCh)).c_str(),trig1.c_str())==0)          isTrigger[MCPList.at(MCPName.at(iCh))] = 1;
		    //		    else if (strcmp((MCPName.at(iCh)).c_str(),trig2.c_str())==0)     isTrigger[MCPList.at(MCPName.at(iCh))] = 2;
		    else                                           isTrigger[MCPList.at(MCPName.at(iCh))] = 0;
		      
		    wfHisto[iCh]->Delete();
		  }
	    
      	     run_id = run;
	     X0     = X0temp;

	     t1->GetEntry(iEntry);
	     tdcX = (*TDCreco)[0];
	     tdcY = (*TDCreco)[1];

	     if (spill!=spillNumber || event!=evtNumber) {
	       std::cout<<"PROBLEM: non-coherent read"<<std::endl;
	       continue;
	     }

	     outTree->Fill();    
	     
      }
 
       //---Get ready for next run
        chain->Delete();
	t1->Delete();
    }
示例#3
0
int main(int argc, char* argv[])
{
  if( argc<2 ) 
  {
    std::cout << argv[0] << " config_file " << std::endl;
    return 0;
  }

  // open steering file names
  config  steer(argv[1]);
 

  mode = steer.getInt("mode");

  rootfile_in = steer.getString("rootfile_in"); 
  rootfile_out = steer.getString("rootfile_out"); 

  signalFraction = steer.getDouble("signalFraction"); 
  
  method = steer.getInt("method");
  
  gaus_reso = steer.getDouble("gaus_reso");

  RegVersion = steer.getString("RegVersion");

  debug = steer.getInt("debug");

  doEvenOdd = steer.getInt("doEvenOdd");

 
  // check 
  if (mode==73||mode==75||mode==77)
  {
    parfile_ref = steer.getString("parfile_ref");
    if (parfile_ref=="") 
    {
      std::cout << "Missing parameters reference file. Please run " << argv[0] << " to print usage information. " << std::endl;  
      return 1;
    } 
  }
  
  if (mode==782) 
  { 
    calibtable_filename = steer.getString("calibtable_filename");
    // fitscale is a stupid control to tell FillAllEvent 
    // if you want it to store all hits information, false is to store.
    fitscale = false; 
  }
 
  std::cout << argv[0] << std::endl;
  std::cout << "  mode = " << mode << std::endl;
  std::cout << "  method = " << method << std::endl;
  std::cout << "  rootfile_in = " << rootfile_in << std::endl;
  std::cout << "  rootfile_out = " << rootfile_out << std::endl;
  std::cout << "  signalFraction = " << signalFraction << std::endl;
  std::cout << "  GaussianResolution = " << gaus_reso << std::endl;
  std::cout << "  RegVersion = " << RegVersion << std::endl;
  std::cout << "  doEvenOdd = " << doEvenOdd << std::endl;
  if (mode==73||mode==75||mode==77) std::cout << "  Parameter Reference File = " << parfile_ref << std::endl;
  if (mode==782) std::cout << "  calibtable_filename = " << calibtable_filename << std::endl;
  
  std::cout << " Start program. " << std::endl;
  
  // reading data
  TChain* tree = new TChain("selected", "selected");
  tree->Add(rootfile_in.c_str());
  // Set the branches for the TChain/TTree
  SetTreeBranch(tree);

  // reading extra tree
  TChain* extree = new TChain("extraCalibTree", "extraCalibTree");
  extree->Add(rootfile_in.c_str());
  // Set the branches for the extra TTree
  SetExtraTreeBranch(extree);
  
  // output root file
  TFile* fout = TFile::Open(rootfile_out.c_str(), "recreate");
  


  // all events
  nEvents = tree->GetEntries();
  nSignals = nEvents;

  // Fill all events into vectors
  FillAllEvents(tree, extree, 2, RegVersion, fitscale, doEvenOdd);
  if (debug>0) std::cout << " Step 1: fill all events: " << nEvents << std::endl;
  
  // delete the chain no more need it
  tree->Delete();
  extree->Delete();
  
  // define the fitting function
  BWGSLikelihoodFCN fcn;

  fcn.setdebug(debug);

  if (debug>0) std::cout << " Step 1: Initialize PDF overall " << std::endl;
  // initialize PDF
  fcn.initBWGSParameters(_FitWindowHigh, // windowHigh
                         _FitWindowLow, // windowLow
                         _Zmass, //voigtMass
                         gaus_reso, //voightResolution
                         2.4952, //voigtWidth
                         nSignals,
                         nEvents);
  
  // define the energy scales as parameters
  MnUserParameters scales;
  
  // reference scales 
  std::vector<double> scalesref;

  if (mode==73) 
  {
    // read reference scales
    std::ifstream reffile(parfile_ref.c_str());
    if (reffile.is_open())
    {
      std::string line;
      double s, e;
      while (getline(reffile,line))
      {
        std::stringstream sline(line);
        sline >> s >> e;
        scalesref.push_back(s);
      }
      reffile.close();
    } 
示例#4
0
int main (int argc, char** argv)
{  
    // get run number
    std::string inputName = std::string(argv[1]);
    char split_char = '/';
    std::vector<std::string> tokens;
    std::istringstream split(inputName);
    for(std::string each; getline(split, each, split_char); 
        tokens.push_back(each));
    
    split_char = '_';
    std::vector<std::string> tokens_name;
    std::istringstream split_name(tokens.at(1));
    for(std::string each; getline(split_name, each, split_char); 
        tokens_name.push_back(each));

    const int Ch_ref1 = atoi((tokens_name.at(1)).c_str());
    const int Ch_ref2 = atoi((tokens_name.at(3)).c_str());
    const int Ch_1 = atoi((tokens_name.at(5)).c_str());
    const int Ch_2 = atoi((tokens_name.at(7)).c_str());
    const int Ch_3 = atoi((tokens_name.at(9)).c_str());

    std::vector<std::string> nameMCP;
    nameMCP.push_back("MiB1");
    nameMCP.push_back("MiB2");
    nameMCP.push_back("ScB");
    nameMCP.push_back("Planacon");
    nameMCP.push_back("MiB3");
    nameMCP.push_back("Roma2");
    if(tokens_name.at(0) == "Scan3") nameMCP.at(1) = "Roma1";

    std::vector<std::string> pcMCP;                                     
    for(unsigned int ii=0; ii<nameMCP.size(); ++ii) pcMCP.push_back("");
    pcMCP.at(Ch_ref1) = tokens_name.at(2);
    pcMCP.at(Ch_ref2) = tokens_name.at(4);
    pcMCP.at(Ch_1) = tokens_name.at(6);
    pcMCP.at(Ch_2) = tokens_name.at(8);
    pcMCP.at(Ch_3) = tokens_name.at(10);

    //---treshold setup Scan-dependent 
    init();
    const int iScanTh = atoi(argv[2])-1;
    float Ch_th[6]={0,0,0,0,0,0};
    Ch_th[Ch_ref1] = _th[iScanTh][Ch_ref1];
    Ch_th[Ch_ref2] = _th[iScanTh][Ch_ref2];
    Ch_th[Ch_1] = _th[iScanTh][Ch_1];
    Ch_th[Ch_2] = _th[iScanTh][Ch_2];
    Ch_th[Ch_3] = _th[iScanTh][Ch_3];


    TFile* out = TFile::Open((tokens_name.at(0)+"_outHistos.root").c_str(),"recreate");  
    out->cd();
    
    //Output dat
    std::ofstream data1(("analized_data/"+tokens_name.at(0)+"_"+nameMCP.at(Ch_1)+"_pc_"+pcMCP.at(Ch_1)+".dat").data());
    std::ofstream data2(("analized_data/"+tokens_name.at(0)+"_"+nameMCP.at(Ch_2)+"_pc_"+pcMCP.at(Ch_2)+".dat").data());
    std::ofstream data3(("analized_data/"+tokens_name.at(0)+"_"+nameMCP.at(Ch_3)+"_pc_"+pcMCP.at(Ch_3)+".dat").data());

    int nFiles = 1, iRun = 0, goodEvt = 0;
    int iScan = 0;
    
    //---usefull histos
    TH1F* chHistoBase_All[9];
    TH1F* chHistoSignal_All[9];
    TH1F* timeDiffHisto[9];
    TH1F* timeDiffHisto_Double = new TH1F("timeDiffHisto_Double", "timeDiffHisto_Double",5000,-10,10);
    //---histos initialization
    for(int iCh=0; iCh<6; ++iCh)
      {
	char h1[30], h2[30], h3[30];
	sprintf(h1, "histoBase_All_Ch%d", iCh);
	sprintf(h2, "histoSignal_All_Ch%d", iCh);
	sprintf(h3, "histoTime_Ch%d", iCh);
	chHistoBase_All[iCh] = new TH1F(h1,h1,30000,-30000,1000);
	chHistoSignal_All[iCh] = new TH1F(h2, h2,30000,-30000,1000);
	timeDiffHisto[iCh] = new TH1F(h3, h3,1024,0,1024);
      } 

    
    //---do runs loop
    ifstream log (argv[1], ios::in);
    while(log >> nFiles)
    {
      ++iScan;
      vector<float> digiCh[9];
      float timeCF[9];
      float baseline[9];
      float intSignal[9],  intBase[9];
      int count[5]={0,0,0,0,0}, spare[5]={0,0,0,0,0}, spare2[5]={0,0,0,0,0};
      int tot_tr1 = 0, tot_tr0 = 0, trig = 0;
      int HV1=0, HV2=0, HV3=0;
      
      TH1F* chHistoWF_Ch[9];
      TH1F* chHistoBase_Ch[9];
      TH1F* chHistoSignal_Ch[9];
      TH1F* timeDiffHisto_Triple_Ch1 = new TH1F(Form("timeDiffHisto_Triple_Ch1_Scan%d",iScan), "", 5000,-100,100);
      TH1F* timeDiffHisto_Triple_Ch2 = new TH1F(Form("timeDiffHisto_Triple_Ch2_Scan%d",iScan), "", 5000,-100,100);
      TH1F* timeDiffHisto_Triple_Ch3 = new TH1F(Form("timeDiffHisto_Triple_Ch3_Scan%d",iScan), "", 5000,-100,100);
      
      char ha[10];
      for (int iiw=0;iiw<9;++iiw){
	sprintf (ha,"histoWF_Ch%d_Scan_%d",iiw, iScan);
	chHistoWF_Ch[iiw] = new TH1F( ha, "", 1024,0.,1024);
	chHistoWF_Ch[iiw]->SetXTitle("Waveform");
	
	sprintf (ha,"histoBase_Ch%d_Scan_%d",iiw, iScan);
	chHistoBase_Ch[iiw] = new TH1F( ha, "", 30000,-30000,1000);
	chHistoBase_Ch[iiw] -> SetXTitle ("Integral BaseLine Ch(ADC)");
	
	sprintf (ha,"histoSignal_Ch%d_Scan_%d",iiw, iScan);
	chHistoSignal_Ch[iiw] = new TH1F( ha, "", 30000,-30000,1000);
	chHistoSignal_Ch[iiw] -> SetXTitle ("Integral Signal Ch(ADC)");
      }
      
      //---data chain
      TChain* chain = new TChain("eventRawData");
      InitTree(chain);
      for(int iFiles=0; iFiles<nFiles; iFiles++){
	log >> iRun;
	char iRun_str[30];
	sprintf(iRun_str, "../Analysis_TB/DATA/run_IMCP_%d_*.root", iRun);
	chain->Add(iRun_str);
	cout << "Reading:  ../Analysis_TB/DATA/run_IMCP_" << iRun << endl;
      }
      log >> HV1 >> HV2 >> HV3;
      
      for(int iEntry=0; iEntry<chain->GetEntries(); iEntry++) {
	
	//---always clear the std::vector !!!
	for(int iCh=0; iCh<9; iCh++) digiCh[iCh].clear();
	
	//---Read the entry
	chain->GetEntry(iEntry);
	
	//---DAQ bug workaround
	if(iRun < 145) goodEvt = 10;
	else goodEvt = 1;
	
	if(evtNumber % goodEvt == 0){
	  //---Read SciFront ADC value and set the e- multiplicity 
	  //---(default = 1)
	  trig = 1;
	  for(int iCh=0; iCh<nAdcChannels; iCh++)
	    {
	      if(adcData[iCh] > 1500 && adcBoard[iCh] == 1 && adcChannel[iCh] == 0) trig=2;
	      if(adcData[iCh] < 500 && adcBoard[iCh] == 1 && adcChannel[iCh] == 0) trig=0;
	    }
	  if(trig > 1) continue; 
	  
	  //---Read digitizer samples
	  for(int iSample=0; iSample<nDigiSamples; iSample++){
	    if(digiChannel[iSample] == 3){
	      digiCh[digiChannel[iSample]].push_back(-digiSampleValue[iSample]);
	      chHistoWF_Ch[digiChannel[iSample]]->SetBinContent(digiSampleIndex[iSample]+1, -digiSampleValue[iSample]);
	    }
	    else{
	      digiCh[digiChannel[iSample]].push_back(digiSampleValue[iSample]);
	      chHistoWF_Ch[digiChannel[iSample]]->SetBinContent(digiSampleIndex[iSample]+1, digiSampleValue[iSample]);
	    }
	    
	  }
	  for(int iCh=0; iCh<6; iCh++){
	    //	    baseline[iCh] = SubtractBaseline(5, 25, &digiCh[iCh]);
	    baseline[iCh] = SubtractBaseline(26, 46, &digiCh[iCh]);
	    intBase[iCh] = ComputeIntegral(26, 46, &digiCh[iCh]);
	    if(trig == 0) {
	      chHistoBase_All[iCh]->Fill(ComputeIntegral(26, 46, &digiCh[iCh]));
	      chHistoBase_Ch[iCh]->Fill(ComputeIntegral(26, 46, &digiCh[iCh]));
	      // 		    chHistoBase_All[iCh]->Fill(ComputeIntegral(0, 150, &digiCh[iCh]));
	      // 		    chHistoBase_Ch[iCh]->Fill(ComputeIntegral(0, 150, &digiCh[iCh]));
	    }
	    timeCF[iCh]=TimeConstFrac(30, 500, &digiCh[iCh], 0.5);
	    //		  timeDiffHisto[iCh]->Fill(timeCF[iCh]*0.2-timeCF[0]*0.2); 
	    timeDiffHisto[iCh]->Fill(timeCF[iCh]); 
	    
	    int t1 = (int)(timeCF[iCh]/0.2) - 3;
	    int t2 = (int)(timeCF[iCh]/0.2) + 17;
	    //---Fill the signal integral histo only if the e- multiplicity is 1
	    if(t1 > 30 && t1 < 1024 && t2 > 30 && t2 < 1024 && trig == 1)
	      {
		chHistoSignal_All[iCh]->Fill(ComputeIntegral(t1, t2, &digiCh[iCh]));
		chHistoSignal_Ch[iCh]->Fill(ComputeIntegral(t1, t2, &digiCh[iCh]));
		intSignal[iCh] = ComputeIntegral(t1, t2, &digiCh[iCh]);
	      }
	    else intSignal[iCh] = ComputeIntegral(50, 70, &digiCh[iCh]);
	  }// loop over Ch
	  //---Multiplicity == 1 --> compute efficency, fake rate and timing                                                                          
	  if(intSignal[Ch_ref1] < Ch_th[Ch_ref1] && intSignal[Ch_ref2] < Ch_th[Ch_ref2] && trig == 1){
	    ++tot_tr1;
	    float tDiff = (timeCF[Ch_ref1] - timeCF[Ch_ref2]);
	    float tMean = (timeCF[Ch_ref1] + timeCF[Ch_ref2])*0.5;
	    timeDiffHisto_Double->Fill(tDiff);
	    timeDiffHisto_Triple_Ch1->Fill(tMean - timeCF[Ch_1]);
	    timeDiffHisto_Triple_Ch2->Fill(tMean - timeCF[Ch_2]);
	    timeDiffHisto_Triple_Ch3->Fill(tMean - timeCF[Ch_3]);
	    
	    if(intSignal[Ch_1] < Ch_th[Ch_1]) ++count[1];
	    if(intSignal[Ch_2] < Ch_th[Ch_2]) ++count[2];
	    if(intSignal[Ch_3] < Ch_th[Ch_3]) ++count[3];
	    
	    if(intBase[Ch_1] < Ch_th[Ch_1])  ++spare[1];
	    if(intBase[Ch_2] < Ch_th[Ch_2])  ++spare[2];
	    if(intBase[Ch_3] < Ch_th[Ch_3])  ++spare[3];
	  }
	}// good Event
      }// loop over entries
    
      std::cout << "HV1 = " << HV1 << " HV2 = " << HV2 << " HV3 = " << HV3 << std::endl;
      double eff1 = ((double)count[1]-(double)spare[1])/(double)tot_tr1;
      double eff2 = ((double)count[2]-(double)spare[2])/(double)tot_tr1;
      double eff3 = ((double)count[3]-(double)spare[3])/(double)tot_tr1;
    
      double eff1Err = TMath::Sqrt((eff1*(1-eff1))/tot_tr1);
      double eff2Err = TMath::Sqrt((eff2*(1-eff2))/tot_tr1);
      double eff3Err = TMath::Sqrt((eff3*(1-eff3))/tot_tr1);

      std::cout << "Ch_1 eff = " << eff1 << " +/- " << eff1Err << std::endl;
      std::cout << "Ch_2 eff = " << eff2 << " +/- " << eff2Err << std::endl;
      std::cout << "Ch_3 eff = " << eff3 << " +/- " << eff3Err << std::endl;
     
      /*
	data1 << HV1 << " " <<  eff1 << " " << 0 << " " << eff1Err << std::endl;
	data1 << HV2 << " " <<  eff2 << " " << 0 << " " << eff2Err << std::endl;
	data1 << HV3 << " " <<  eff3 << " " << 0 << " " << eff3Err << std::endl;
      */
  
      for(int iw=0; iw<6; ++iw){
	if(iw == 2) continue;
	chHistoBase_Ch[iw]->Write();
	chHistoSignal_Ch[iw]->Write();
	chHistoWF_Ch[iw]->Write();
      }
      timeDiffHisto_Triple_Ch1->Write();
      timeDiffHisto_Triple_Ch2->Write();
      timeDiffHisto_Triple_Ch3->Write();
      chain->Delete();
    }

    for(int iw=0; iw<6; ++iw){
      if(iw == 2) continue;
      chHistoBase_All[iw]->Write();
      chHistoSignal_All[iw]->Write();
      timeDiffHisto[iw]->Write();
    }

    data1.close();
    data2.close();
    data3.close();

    timeDiffHisto_Double->Write();
    out->Close();
    return 0;
}
//int data_MC_Pt_Comparison_entries(int EndCaps = 0, int r9sup = 1, int log = 0)
int main(int argc, char *argv[])
{

	for(int iarg = 0 ; iarg < argc; iarg++)
        {
                cout << "argv[" << iarg << "]= " << argv[iarg] << endl;
        }

        if( argc == 1 ) 
        {
                cerr << "arguments should be passed : directoryName, eta, r9, xVariable, log" <<endl; 
                return 1;

        }    

	string directoryName = "Data_MC_Mmumugamma_Comparison_ScaleAndSmearing/smearingFactors";
	string eta = "Barrel_1";
	string r9 = "all";
	string ptCut = "25"; // "30" "35"

	if( argc > 1 ) directoryName = argv[1];
	if( argc > 2 ) eta = argv[2];
        if( argc > 3 ) r9 = argv[3];	
	if( argc > 4 ) ptCut = argv[4];	

	


	int nBins = 50; //FIXME
	double xMin, xMax;
	xMin = 0.9; //FIXME
	xMax = 1.1; //FIXME
	
	string xVariableName, yVariableName;

	gROOT->Reset();
        TGaxis::SetMaxDigits(3);
        setTDRStyle();
	//setEgammaStyle();

	string directoryName_2 = directoryName;
	string fileName = directoryName;

	cout<<endl<<"fileName = "<<fileName<<endl;
	cout<<endl<<"directoryName = "<<directoryName<<endl;
	directoryName += Form("/%s_%sR9/",eta.c_str(), r9.c_str());
	
	TString cut = Form("(Photon_Et > %s && isJanLooseMMG == 1",ptCut.c_str());

	if(r9 == "low" && eta == "Barrel_1") cut += " && Photon_isEB == 1 && Photon_r9 < 0.94 && abs(Photon_SC_Eta) < 1";
        if(r9 == "low" && eta == "Barrel_2") cut += " && Photon_isEB == 1 && Photon_r9 < 0.94 && abs(Photon_SC_Eta) > 1";
	if(r9 == "high" && eta == "Barrel_1") cut += " && Photon_isEB == 1 && Photon_r9 > 0.94 && abs(Photon_SC_Eta) < 1";
	if(r9 == "high" && eta == "Barrel_2") cut += " && Photon_isEB == 1 && Photon_r9 > 0.94 && abs(Photon_SC_Eta) > 1";
        if(r9 == "low" && eta == "Endcaps_1") cut += " && Photon_isEE == 1 && Photon_r9 < 0.95 && abs(Photon_SC_Eta) < 2";
	if(r9 == "low" && eta == "Endcaps_2") cut += " && Photon_isEE == 1 && Photon_r9 < 0.95 && abs(Photon_SC_Eta) > 2";
        if(r9 == "high" && eta == "Endcaps_1") cut += " && Photon_isEE == 1 && Photon_r9 > 0.95 && abs(Photon_SC_Eta) < 2";
	if(r9 == "high" && eta == "Endcaps_2") cut += " && Photon_isEE == 1 && Photon_r9 > 0.95 && abs(Photon_SC_Eta) > 2";
        if(r9 == "all" && eta == "Barrel_1") cut += " && Photon_isEB == 1 && abs(Photon_SC_Eta) < 1";
	if(r9 == "all" && eta == "Barrel_2") cut += " && Photon_isEB == 1 && abs(Photon_SC_Eta) > 1";
        if(r9 == "all" && eta == "Endcaps_1") cut += " && Photon_isEE == 1 && abs(Photon_SC_Eta) < 2";
	if(r9 == "all" && eta == "Endcaps_2") cut += " && Photon_isEE == 1 && abs(Photon_SC_Eta) > 2";
	if(r9 == "all" && eta == "all") cut += " && (Photon_isEE == 1 || Photon_isEB == 1)";

	cut += ")*weight_pileUp"; 

	cout<<endl<<"cut = "<<cut<<endl;

        TChain * dYToMuMuFSRChainNew = new TChain("miniTree");
        TChain * dYToMuMuNonFSRChainNew = new TChain("miniTree");
        TChain * ttJetsChainNew = new TChain("miniTree");
        TChain * wJetsChainNew = new TChain("miniTree");

        dYToMuMuFSRChainNew->Add("/sps/cms/sgandurr/CMSSW_4_2_8_patch7/src/Zmumugamma_miniTrees_rereco_2011_lastTag/miniTree_DYToMuMu_M-20_CT10_TuneZ2_7TeV-powheg-pythia_Fall11-PU_S6_START42_V14B-v1_September12_NewSelection_1_scaleAndsmearing_v4_partALL.root");
        dYToMuMuNonFSRChainNew->Add("/sps/cms/sgandurr/CMSSW_4_2_8_patch7/src/Zmumugamma_miniTrees_rereco_2011_lastTag/miniTree_DYToMuMu_M-20_CT10_TuneZ2_7TeV-powheg-pythia_Fall11-PU_S6_START42_V14B-v1_September12_NewSelection_2_scaleAndsmearing_v4_partALL.root");
        ttJetsChainNew->Add("/sps/cms/sgandurr/CMSSW_4_2_8_patch7/src/Zmumugamma_miniTrees_rereco_2011_lastTag/miniTree_TTJets_TuneZ2_7TeV-madgraph-tauola_NewSelection_3_scaleAndsmearing_v4_partALL.root");
        wJetsChainNew->Add("/sps/cms/sgandurr/CMSSW_4_2_8_patch7/src/Zmumugamma_miniTrees_rereco_2011_lastTag/miniTree_WJetsToLNu_TuneZ2_7TeV-madgraph-tauola_NewSelection_3_scaleAndsmearing_v4_partALL.root");
	

	TCanvas *c1 = new TCanvas("c1", "c1",0,0,600,600);

        TH1D *dYToMuMuFSRNew = new TH1D("dYToMuMuFSRNew","dYToMuMuFSRNew", nBins, xMin, xMax);
        TH1D *dYToMuMuNonFSRNew = new TH1D("dYToMuMuNonFSRNew","dYToMuMuNonFSRNew", nBins, xMin, xMax);
        TH1D *ttJetsNew = new TH1D("ttJetsNew","ttJetsNew", nBins, xMin, xMax);
        TH1D *wJetsNew = new TH1D("wJetsNew","wJetsNew", nBins, xMin, xMax);

        dYToMuMuFSRChainNew->Draw("shervinSmearing>>dYToMuMuFSRNew",cut);
        dYToMuMuNonFSRChainNew->Draw("shervinSmearing>>dYToMuMuNonFSRNew",cut);
        ttJetsChainNew->Draw("shervinSmearing>>ttJetsNew",cut);
        wJetsChainNew->Draw("shervinSmearing>>wJetsNew",cut);


	// --- 2012 Lumi --- //
        //double lumidata = 808.472 + 82.136 + 4429.0 + 495.003 + 134.242 + 6397.0 + 7274.0;
        //double lumiDY = 48819386.0 / 1914.894;
        //double lumiTtJets = 6736135.0 / 234.0;
        //double lumiwJets = 57709905.0 / 37509.25;	

	// --- 2011 Lumi --- //
	double lumidata = (0.706370 + 0.385819 + 2.741 + 1.099) * 1000;
	double lumiDY = 29743564.0 / 1665.835;
	double lumiTtJets = 3701947.0 / 165.0;
	double lumiwJets = 81345381.0 / 31314.0;	

	// --- 2011 Lumi old --- //
	//double lumiDY = 29743564.0 / 1626.0;
        //double lumiTtJets = 3701947.0 / 94.76;
        //double lumiwJets = 81345381.0 / 27770.0;

	ttJetsNew->Scale(lumiDY / lumiTtJets);
	wJetsNew->Scale(lumiDY / lumiwJets);
		
	dYToMuMuFSRNew->Add(dYToMuMuNonFSRNew);
	dYToMuMuFSRNew->Add(ttJetsNew);
	dYToMuMuFSRNew->Add(wJetsNew);

	dYToMuMuNonFSRNew->Add(ttJetsNew);
	dYToMuMuNonFSRNew->Add(wJetsNew);

	ttJetsNew->Add(wJetsNew);

	c1->Clear();


	dYToMuMuFSRNew->GetYaxis()->SetTitle("Events / 0.004"); //FIXME
       	dYToMuMuFSRNew->GetXaxis()->SetTitle("smearing factors");	

	/*
	dYToMuMuFSR->GetXaxis()->SetLabelFont(42);
	dYToMuMuFSR->GetXaxis()->SetTitleFont(42);
	dYToMuMuFSR->GetYaxis()->SetLabelFont(42);
	dYToMuMuFSR->GetYaxis()->SetTitleFont(42);
	dYToMuMuFSR->GetYaxis()->SetTitleOffset(1.65);
	*/

	dYToMuMuFSRNew->SetFillColor(kGreen-7);
        dYToMuMuNonFSRNew->SetFillColor(kAzure-5);
        ttJetsNew->SetFillColor(kBlue-1);
        wJetsNew->SetFillColor(kCyan+2);

	dYToMuMuFSRNew->Draw("");


	// --- Fit --- //

        TF1 * f1 = new TF1("f1","gaus",xMin,xMax);
	//TF1 * f1 = new TF1("f1","gaus",0.96,1.04);
	//f1->FixParameter(1,1.0); //FIXME
        //f1->FixParameter(2,1.0); //FIXME
        dYToMuMuFSRNew->Fit(f1);
        f1->SetLineColor(kBlue);
        f1->SetLineWidth(2);
        f1->Draw("SAMES");

        c1->Clear();
        dYToMuMuFSRNew->Draw("E");
        f1->Draw("SAMES");

        dYToMuMuFSRNew->SetMarkerStyle(20);
        dYToMuMuFSRNew->SetMarkerSize(0.5);
	
	TLatex latexLabel;
	latexLabel.SetTextFont(42);
	latexLabel.SetTextSize(0.028);
	latexLabel.SetNDC();
	//latexLabel.DrawLatex(0.25, 0.96, "CMS Preliminary 2011               #sqrt{s} = 7 TeV               L = 4.93 fb^{-1}");
	
	//double Ymin = 0;
	//double Ymax = max(dYToMuMuFSR->GetMaximum(),data->GetMaximum()) + max(dYToMuMuFSR->GetMaximum(),data->GetMaximum()) * 0.1;	
	//cout << "Ymax = "<<Ymax<<endl;

	//dYToMuMuFSRNew->GetYaxis()->SetRangeUser(Ymin,Ymax);

	plotsRecording(directoryName, fileName, c1);

	c1->Clear();

	f1->Delete();
	f1 = 0;
        dYToMuMuFSRNew->Delete();
        dYToMuMuFSRNew = 0;
        dYToMuMuNonFSRNew->Delete();
        dYToMuMuNonFSRNew = 0;
        ttJetsNew->Delete();
        ttJetsNew = 0;
        wJetsNew->Delete();
        wJetsNew = 0;
        dYToMuMuFSRChainNew->Delete();
        dYToMuMuFSRChainNew = 0;
        dYToMuMuNonFSRChainNew->Delete();
        dYToMuMuNonFSRChainNew = 0;
        ttJetsChainNew->Delete();
        ttJetsChainNew = 0;
        wJetsChainNew->Delete();
        wJetsChainNew = 0;


	
	delete c1;
	c1 = 0;	
	
	return 0;

}
示例#6
0
int main(int argc, char** argv) {
  
  gROOT->SetStyle("Plain");
  gStyle->SetPalette(1);

  // load ntuple
  TChain *chain = new TChain ("myanalysis/EcalAnalysisTree","EcalAnalysisTree") ;

  chain->Add("/tmp/malberti/EcalTree_EG_Run2010A-WZEG-Nov4Skim_v1_RAW-RECO.root");  
  chain->Add("/tmp/malberti/EcalTree_Electron_Run2010B-WZEG-Nov4Skim_v1_RAW-RECO.root");  

  int nEntries = (int)chain->GetEntries() ;
  cout << "FOUND " << nEntries  << " ENTRIES\n" << endl;;

 
  //ecalVariables variables
  unsigned int runId;
  unsigned int eventId;
  unsigned int eventNaiveId;
 
  int nEcalRecHits;
  float ecalRecHitType[3300];
  float ecalRecHitEnergy[3300];
  float ecalRecHitIEta[3300];
  float ecalRecHitIPhi[3300];
  float ecalRecHitTime[3300];
  float ecalRecHitChi2[3300];
  int ecalRecHitRecoFlag[3300];
  float ecalRecHitMatrixFlag[3300][5][5];
  float ecalRecHitMatrix[3300][5][5];
  float ecalRecHitS4oS1[3300];
  int ecalDigis[3300][10];
  int ecalGainId[3300][10];

  // Set branch addresses.
  chain -> SetBranchAddress("runId",                     &runId);
  chain -> SetBranchAddress("eventId",                   &eventId);
  chain -> SetBranchAddress("eventNaiveId",              &eventNaiveId);
  chain -> SetBranchAddress("nEcalRecHits",              &nEcalRecHits);
  chain -> SetBranchAddress("ecalRecHitType",            ecalRecHitType);
  chain -> SetBranchAddress("ecalRecHitEnergy",          ecalRecHitEnergy);
  chain -> SetBranchAddress("ecalRecHitIEta",            ecalRecHitIEta);
  chain -> SetBranchAddress("ecalRecHitIPhi",            ecalRecHitIPhi);
  chain -> SetBranchAddress("ecalRecHitTime",            ecalRecHitTime);
  chain -> SetBranchAddress("ecalRecHitChi2",            ecalRecHitChi2);
  chain -> SetBranchAddress("ecalRecHitRecoFlag",        ecalRecHitRecoFlag);
  chain -> SetBranchAddress("ecalRecHitMatrixFlag",      ecalRecHitMatrixFlag);
  chain -> SetBranchAddress("ecalRecHitMatrix",          ecalRecHitMatrix);
  chain -> SetBranchAddress("ecalRecHitS4oS1",           ecalRecHitS4oS1);
  chain -> SetBranchAddress("ecalDigis",                 ecalDigis);
  chain -> SetBranchAddress("ecalGainId",                ecalGainId);
   
   
  // output file
  char outfileName[100];
  sprintf(outfileName,"HistosSlewRate.root");
  cout << "Saving histograms on file " << outfileName  <<endl;

  TFile saving (outfileName,"recreate") ;
  

  // histos 
  TH1F *hGainSwitch = new TH1F("hGainSwitch","hGainSwitch",10,-5,5);
  hGainSwitch->GetXaxis()->SetTitle("Gain(max) - Gain(max-1)");

  TH1F *hSlewRate = new TH1F("hSlewRate","hSlewRate", 5000, 0, 5000); 
  hSlewRate ->SetFillStyle(1);
  hSlewRate ->SetFillColor(kRed);
  hSlewRate ->GetXaxis()->SetTitle("Slew Rate (ADC/ns)");

  TH2F *hAmplitude = new TH2F("hAmplitude","hAmplitude", 1000, 0, 10000, 500, 0, 5000); 
  hAmplitude -> SetMarkerColor(kRed);
  hAmplitude -> SetMarkerStyle(20);
  hAmplitude -> SetMarkerSize(0.35);
  hAmplitude -> GetXaxis() -> SetTitle("Expected Amplitude (ADC)");
  hAmplitude -> GetYaxis() -> SetTitle("Observed Amplitude (ADC)");

  TH2F *hAmplitude2 = new TH2F("hAmplitude2","hAmplitude2", 1000, 0, 10000, 500, 0, 5000); 
  hAmplitude2 -> SetMarkerColor(kBlue);
  hAmplitude2 -> SetMarkerStyle(20);
  hAmplitude2 -> SetMarkerSize(0.35);
  hAmplitude2 -> GetXaxis() -> SetTitle("Expected Amplitude (ADC)");
  hAmplitude2 -> GetYaxis() -> SetTitle("Observed Amplitude (ADC)");


  TH2F *hAmpl_vs_Time = new TH2F("hAmpl_vs_Time","hAmpl_vs_Time", 800, -100, 100, 1000, 0, 10000); 
  hAmpl_vs_Time -> SetMarkerColor(kRed);
  hAmpl_vs_Time -> SetMarkerStyle(20);
  hAmpl_vs_Time -> SetMarkerSize(0.3);
  hAmpl_vs_Time -> GetXaxis() -> SetTitle("Time (ns)");
  hAmpl_vs_Time -> GetYaxis() -> SetTitle("Expected Amplitude (ADC)");

  TH2F *hRatio_vs_Time = new TH2F("hRatio_vs_Time","hRatio_vs_Time", 800, -100, 100, 200, 0, 2); 
  hRatio_vs_Time -> SetMarkerColor(kRed);
  hRatio_vs_Time -> SetMarkerStyle(20);
  hRatio_vs_Time -> SetMarkerSize(0.3);
  hRatio_vs_Time -> GetXaxis() -> SetTitle("Time (ns)");
  hRatio_vs_Time -> GetYaxis() -> SetTitle("Ratio");

  TH1F *hr1 = new TH1F("hr1","hr1",200,0,2);
  TH1F *hr2 = new TH1F("hr2","hr2",200,0,2);

  TH1F *hTfit1 = new TH1F("hTfit1","hTfit1 (expected Amplitude < 3000 ADC)",400,-50,50);
  hTfit1 -> SetFillStyle(3001);
  hTfit1 -> SetFillColor(kRed+2);
  hTfit1 -> GetXaxis() -> SetTitle("T_{fit} (ns)");

  TH1F *hTfit2 = new TH1F("hTfit2","hTfit2 (expected Amplitude > 3000 ADC)",400,-50,50);
  hTfit2 -> SetFillStyle(3001);
  hTfit2 -> SetFillColor(kBlue+2);
  hTfit2 -> GetXaxis() -> SetTitle("T_{fit} (ns)");

  TH1F *hAmax1 = new TH1F("hAmax1","hTAmax1 (expected Amplitude < 3000 ADC)",1000,0,10000);
  hAmax1 -> SetFillStyle(3001);
  hAmax1 -> SetFillColor(kRed+2);
  hAmax1 -> GetXaxis() -> SetTitle("A_{max} (ADC counts)");

  TH1F *hAmax2 = new TH1F("hAmax2","hTAmax2 (expected Amplitude > 3000 ADC)",1000,0,10000);
  hAmax2 -> SetFillStyle(3001);
  hAmax2 -> SetFillColor(kBlue+2);
  hAmax2 -> GetXaxis() -> SetTitle("A_{max} (ADC counts)");


  TGraphErrors* gsample;
  char gname[100];
  char gtitle[100];
  int ievt=0;  

  float A[3300][10];
  float G[3] = {1.,2.,12.}; // gain ratios

  //loop over the events
  for (int entry = 0 ; entry < nEntries; ++entry) {
      
    chain -> GetEntry(entry) ;
    if (entry%10000==0) cout << "    Analyzing entry " << entry << endl;
        
    for (int ihit =0 ; ihit < nEcalRecHits; ihit++) {
      
      // barrel only
      if ( ecalRecHitType[ihit]!=0) continue; 

      float energy = ecalRecHitEnergy[ihit];
      float eta = ecalRecHitIEta[ihit]*0.0175;
      float theta = 2. * atan(exp(-eta));
      float et = energy*sin(theta); 
      
      //if ( energy < 100. ) continue;      // E>10 GeV
      
      //cerco il sample max
      float ped = (ecalDigis[ihit][0] + ecalDigis[ihit][1] + ecalDigis[ihit][2])/3;
      int imax = 0;
      int maxAmpl = 0;
      for (int isample = 0; isample < 10 ; isample++)
	{
	  if (ecalGainId[ihit][isample]!=0) A[ihit][isample] = (ecalDigis[ihit][isample] - ped) * G[ ecalGainId[ihit][isample] - 1]; 
	  
	  if ( A[ihit][isample] >= maxAmpl) 
	    {
	      imax = isample;
	      maxAmpl = A[ihit][isample] ;
	    }
	} // end loop over 10 samples
      


      // check gain switch
      bool gainSwitch = false;
      if (ecalGainId[ihit][imax-1]==1 && ecalGainId[ihit][imax] != ecalGainId[ihit][imax-1])   gainSwitch = true;
      
      //Seleziono eventi con gain switch
      if (!gainSwitch) continue;
      hGainSwitch -> Fill( ecalGainId[ihit][imax]-ecalGainId[ihit][imax-1]);

      //cout << "MAX sample = "<< imax << "   MAX amplitude = "<< A[ihit][imax] << "   MAX gain Id =" << ecalGainId[ihit][imax]<< endl;
      //cout << "MAX-1 sample = "<< imax-1 << "   MAX-1 amplitude = "<< A[ihit][imax-1] << "   MAX-1 gain Id =" << ecalGainId[ihit][imax-1] << endl;
      //cout << endl;   
      
     
      float slewRate = A[ihit][imax-1];
      hSlewRate -> Fill(slewRate); 

      // graphs
      gsample = new TGraphErrors();
      sprintf(gtitle,"shape_Run%d_Evt%d",runId,eventId);
      sprintf(gname,"shape_%d",ievt);
      gsample->SetName(gname);
      gsample->SetTitle(gtitle);
      gsample->GetXaxis()->SetTitle("Time (ns)");
      gsample->GetYaxis()->SetTitle("ADC counts");
      
      for (int isample = 0; isample < 10 ; isample++)
      	{
      	  gsample->SetPoint(isample, double(isample)*25., A[ihit][isample]);      
      	  gsample->SetPointError(isample,0.,0.9);      
      	}



      
      // fit function            
      TF1 *fpulseShape = new TF1("fpulseShape", pulseShape,0.,240.,3);
      fpulseShape->SetLineColor(kBlue);
      fpulseShape->SetParName(0,"Ped");
      fpulseShape->SetParName(1,"A");
      fpulseShape->SetParName(2,"T0");
      fpulseShape->FixParameter(0,0); // ped
      fpulseShape->SetParameter(1,A[ihit][imax]); // ampl
      fpulseShape->SetParameter(2,imax*25.); // T0
      gsample->RemovePoint(imax-1);
      gsample->Fit("fpulseShape","QSR+") ;
      //re-set dei punti, altrimenti root non li plotta!
      for (int isample = 0; isample < 10 ; isample++)
      	{
      	  gsample->SetPoint(isample, double(isample)*25., A[ihit][isample]);      
      	  gsample->SetPointError(isample,0.,0.9);      
      	}
      ievt++;
      

      float measuredAmpl = A[ihit][imax-1] ;
      float expectedAmpl = A[ihit][imax] * fpulseShape->Eval((imax-1)*25.)/fpulseShape->Eval(imax*25.);
                  
      hAmplitude  -> Fill(expectedAmpl,measuredAmpl);
      hAmplitude2 -> Fill( A[ihit][imax] * 0.774,measuredAmpl);
 

      float t0 = fpulseShape->GetParameter(2);
      
      hAmpl_vs_Time -> Fill(t0-125.,expectedAmpl);
      hRatio_vs_Time -> Fill(t0-125., fpulseShape->Eval((imax-1)*25.)/fpulseShape->Eval(imax*25.));
      
      if (expectedAmpl > 3000) {
	hr2->Fill( fpulseShape->Eval((imax-1)*25.)/fpulseShape->Eval(imax*25.));
	hTfit2->Fill(t0-125.);
	hAmax2->Fill(A[ihit][imax]);
      }
      else {
	hr1->Fill( fpulseShape->Eval((imax-1)*25.)/fpulseShape->Eval(imax*25.));
	hTfit1->Fill(t0-125.);
	hAmax1->Fill(A[ihit][imax]);
      }

      if ( expectedAmpl < 3000 )
	//if (ievt<10)
	gsample->Write();

    } // end loop over recHits
    
  }//end loop over events
 
 
  chain->Delete();

  saving.cd () ;

  hGainSwitch ->Write();
  hSlewRate   -> Write();
  hAmplitude  ->Write();
  hAmplitude2 ->Write();
  hAmpl_vs_Time ->Write();
  hRatio_vs_Time ->Write();
  hTfit1->Write();
  hTfit2->Write();
  hAmax1->Write();
  hAmax2->Write();

  hr1->Write();
  hr2->Write();

  saving.Close () ;
  
  return 0;
  
  
}