Beispiel #1
0
RooDataHist * genHistFromModelPdf(const char * name, RooAbsPdf *model,  RooRealVar *var,    double ScaleLumi,  int range, int rebin, int seed ) {
  double genEvents =  model->expectedEvents(*var);
  TRandom3 *rndm = new TRandom3();
  rndm->SetSeed(seed);
  double nEvt = rndm->PoissonD( genEvents) ;
  int intEvt = ( (nEvt- (int)nEvt) >= 0.5) ? (int)nEvt +1 : int(nEvt);
  RooDataSet * data = model->generate(*var ,   intEvt   );
  cout<< " expected events for " << name << " = "<< genEvents << endl; 
  cout<< " data->numEntries() for name " << name << " == " << data->numEntries()<< endl;
  // cout<< " nEvt from PoissonD for" << name << " == " << nEvt<< endl;
  //cout<< " cast of nEvt  for" << name << " == " << intEvt<< endl; 
  RooAbsData *binned_data = data->binnedClone();
  TH1 * toy_hist = binned_data->createHistogram( name, *var, Binning(range/rebin )  );
  for(int i = 1; i <= toy_hist->GetNbinsX(); ++i) {
    toy_hist->SetBinError( i,  sqrt( toy_hist->GetBinContent(i)) );
    if(toy_hist->GetBinContent(i) == 0.00) {
      cout<< " WARNING: histo " << name << " has 0 enter in bin number " << i << endl;   
    }
    if(toy_hist->GetBinContent(i) < 0.1) {
      toy_hist->SetBinContent(i, 0.0);
      toy_hist->SetBinError(i, 0.0);
      cout<< " WARNING: setting value 0.0 to histo " << name << " for bin number " << i << endl;   
    }  
  }
  RooDataHist * toy_rooHist = new RooDataHist(name, name , RooArgList(*var), toy_hist );
  return toy_rooHist; 
}
Beispiel #2
0
Datei: fit.C Projekt: dcraik/lhcb
int main(int argc, char** argv)
{
    file = TFile::Open("~/lhcb/rd/Kll/tuples/fromPatrick/Kmm_Q17_reduced.root");
    DecayTree = dynamic_cast<TTree*>(file->Get("finalTree_KMuMu"));
    cosTheta = new RooRealVar("cosThetaL", "cosThetaL", -1., 1.);
    sWeight  = new RooRealVar("sWeight",   "sWeight",   -5., 5.);
    data = new RooDataSet("data", "", DecayTree, RooArgList(*cosTheta,*sWeight), 0, "sWeight");

    fout.open("results.txt",std::ofstream::out);

    r.SetSeed(123456);

    Double_t a(0.), b(0.);
    for(Int_t j=-2; j<3; ++j) {
        for(Int_t k=0; k<10; ++k) {
            for(Int_t i=0; i<20; ++i) {
                a = k/-10.;
                b = j/10.;
                fit(i,a,b);
            }
        }
    }

    fout.close();

    return 0;
}
void plot_distortion(){
    
    TRandom3* rand = new TRandom3();

//    TF1 *func = new TF1("func","TMath::Abs([0]+[1]*x)",0,12);
//
//    rand->SetSeed(0);
//    Double_t slope=0.2*rand->Gaus(0,1);
//    Double_t anchor_point=3.5;
//    //want offset to be set by requiring func at anchor point to be 1
//    Double_t offset=(1-slope*anchor_point);
//    func->SetParameter(0,offset);
//    func->SetParameter(1,slope);
    
    //FN distortion
    TF1 *func = new TF1("func","[0]/(0.2*pow(x,0.1))+[1]",0,12);
    rand->SetSeed(0);
    Double_t scaling =0.2*rand->Gaus(0,1);
    func->SetParameter(0,scaling);
    func->SetParameter(1,0);
    //set offset so that func(FinalEnergy)=1;
    func->SetParameter(1,1-1*func->Eval(12));
    
    func->Draw();
    
    
   }
Beispiel #4
0
int decroissance_pi(float _p_pi = 1.0){

  //	random.seed(60934386)
  TRandom3 rand;
  rand.SetSeed();
  //float _p_pi;
  //cout << "Entrez l'impulsion des pions (en GeV) : p = ";
  //cin >> _p_pi;

  double x[1000] = {0.0};
  double y[1000] = {0.0};

  for (int i=0;i<1000;i++){
    //double _theta_cm_mu = rand.Uniform(TMath::Pi());
    double _theta_cm_mu = TMath::ACos(gRandom->Uniform(2.0)-1.0);
    double _phi_cm_mu = rand.Uniform(2*TMath::Pi());
    if (i < 10){
      cout << "i: " << i <<  " th_cm_mu = " << _theta_cm_mu << endl;
    }
    double _theta_lab_mu = 0.0, _p_lab_mu = 0.0;
    ThetaLab_mu(_p_pi, _theta_cm_mu, _theta_lab_mu, _p_lab_mu);
    cout << "th_lab_mu= " << _theta_lab_mu << " _p_lab_mu= " << _p_lab_mu << endl;
    x[i] = 1000*_theta_lab_mu;
    y[i] = _p_lab_mu;
  }

  TGraph *graph = new TGraph(1000, x, y);
  graph->SetTitle("Theta vs p_{LAB}");

  graph->Draw("A*");

  return 0;

}
Beispiel #5
0
void histo_graph(TH1D *histo,TGraph *graph,Int_t N_to_fill) {
  Int_t N_Points=graph->GetN();
  Double_t x,y;

  Double_t y_min=0.0;
  Double_t y_max=0.0;
  Double_t x_min=0.0;
  Double_t x_max=0.0;

  for (Int_t i=0;i<N_Points;i++) {
    graph->GetPoint(i,x,y);
    if (y>y_max) y_max=y;
    if (x>x_max) x_max=x;
    if (y<y_min) y_min=y;
    if (x<x_min) x_min=x;
  }
  Double_t histo_x_min=histo->GetXaxis()->GetXmin();
  Double_t histo_x_max=histo->GetXaxis()->GetXmax();
  if (histo_x_min>x_min) x_min=histo_x_min;
  if (histo_x_max<x_max) x_max=histo_x_max;

  //reverse graph order if necessary
  TGraph graph2(N_Points);
  Double_t x0,xNm1;
  graph->GetPoint(0,x0,y);
  graph->GetPoint(N_Points-1,xNm1,y);
  if (xNm1<x0) {
    for (Int_t iPoint=0;iPoint<N_Points;iPoint++) {
      Double_t x,y;
      graph->GetPoint(N_Points-iPoint,x,y);
      graph2.SetPoint(iPoint,x,y);
    }
    graph=&graph2;
  }

  TRandom3 r;
  r.SetSeed(0);

  Int_t N_tried=0;
  Int_t N_filled=0;
  while (N_filled<N_to_fill) {
    N_tried++;
    //rejection method
    x=r.Uniform(x_min,x_max);
    y=r.Uniform(0.0,y_max);
    
    if (y<graph->Eval(x)) {
      histo->Fill(x);
      N_filled++;
    }
  }
  printf("x_max=%8.6g; x_min=%8.6g; y_max=%8.6g; N_filled=%d; N_tried=%d\n",x_max,x_min,y_max,N_filled,N_tried);
  Double_t norm=(x_max-x_min)*y_max*N_filled/N_tried;
  histo->Scale(norm/histo->Integral("width"));

}
Beispiel #6
0
void randomize(TH1F* hist, unsigned int seed, unsigned int debug=0.)
{
  TRandom3* rnd = new TRandom3(seed); rnd->SetSeed();
  for(int idx=0; idx<hist->GetNbinsX(); ++idx){
    if(debug>0){
      std::cerr << "[" << idx+1 << "] : " << "mean=" << hist->GetBinContent(idx+1) << "  rnd=" << rnd->Poisson(hist->GetBinContent(idx+1)) << std::endl;  
    }
    float value = rnd->Poisson(hist->GetBinContent(idx+1));
    hist->SetBinContent(idx+1, value); hist->SetBinError(idx+1, TMath::Sqrt(value));
  }
  // Make sure there is no rounding error, and the total is truly an integer.
  hist->Scale(TMath::Nint(hist->Integral())/hist->Integral());
  delete rnd;
}
void createTBevents(int input){

  printf("Starting Simulation of data\n");

  //creating the output file
  char outputFileName[100] = {"OutputFile.root"};

  printf("Creating output file: %s \n",outputFileName);
  TFile * outputFile = new TFile(outputFileName,"RECREATE");


  //Counter for event number
  unsigned int eventNr;

  //Counter for total number of hits
  unsigned int hitsTotal = 0;

  
  short int col, row, adc;
  short int ladder = 2;
  short int mod = 3;
  short int disk = 2;
  short int blade = 2;
  short int panel = 2;
  
  //create the tree to store the data
  TTree *bpixTree[3];

  char title[30];
  for (int i=1; i<4; i++){
    sprintf(title,"BPIX_Digis_Layer%1d",i);
    bpixTree[i-1]= new TTree(title,title);
    bpixTree[i-1]->Branch("Event", &eventNr, "Event/i");           
    bpixTree[i-1]->Branch("Ladder", &ladder, "Ladder/S");      
    bpixTree[i-1]->Branch("Module", &mod, "Module/S");      
    bpixTree[i-1]->Branch("adc", &adc, "adc/S");       
    bpixTree[i-1]->Branch("col", &col, "col/S");       
    bpixTree[i-1]->Branch("row", &row, "row/S");
  }

  

  //Maximum number of events. Events does not correspond with Hits
  unsigned int maxEventNr = input;

  //Number of Hits per Event
  //This should be randomized later and be dependant on the rate
  double meanHitsPerEvent = 2;

  //Maximum particle flux [MHz cm^-2]
  int maxParticleFlux = 500;

  //number of hits in current event
  int hitsInEvent = -1; 

  //create a random number generator
  TRandom3 * random = new TRandom3();
  TRandom3 * randomrow = new TRandom3();
  TRandom3 * randomcol = new TRandom3();
  TRandom3 * randomadc = new TRandom3();

  //using custom function to distribute values
  //values used from http://ntucms1.cern.ch/pixel_dev/flux/v8/016031/fitspot_bin_11.pdf
  
  TF1 * fx = new TF1("xfunc", "[0]*exp(2.59349*exp(-0.5*((-x+3.24273/.15+[1]/.15)/7.07486*.15)**2)+2.07765*exp(-0.5*((-x+9.33060e-01/.15+[1]/.15)/2.24067*.15)**2)-4.21847)",0, 52);
  
  fx->SetParameters(1,337.0);
  fx->SetParameters(2,1.74);
  
  TF1 * fy = new TF1("yfunc", AsyGaus,0,80,4);
  
  fy->SetParNames("mean","sigma1","sigma2","amplitude");
  fy->SetParameter("mean",43);
  fy->SetParameter("sigma1",11.4);
  fy->SetParameter("sigma2",15.0);
  fy->SetParameter("amplitude",347.0);
  
  TF1 * fadc = new TF1("adcfunc", langaufun,0,400,4);
  fadc->SetParNames("scale","mpv","area","sigma");
  fadc->SetParameter("scale",19);
  fadc->SetParameter("mvp",220);
  fadc->SetParameter("area",10000);
  fadc->SetParameter("sigma",30);




  while (eventNr < maxEventNr){
    //printf("eventNr: %d \n",eventNr);
    //Function used for fitting according to Xin an Stefano
    
    //Start by generating the number of hits per event
    //following a poisson distribution
    random->SetSeed(0);
    hitsInEvent = random->Poisson(meanHitsPerEvent);
    //printf("hitsInEvent %d \n", hitsInEvent);

    hitsTotal += hitsInEvent;

    if(hitsInEvent < 0){
      printf("ERROR: Number of hits in event is negative!!!\n");
      break;
    }

    //distribute the hits in the event over the roc accorsing to gaus distribution
    /*
    for(int i = 0; i < hitsInEvent; ++i){

      //random row value
      randomrow->SetSeed(0);
      row = randomrow->Gaus(40,10);
      
      //random column value
      randomcol->SetSeed(0);
      col = randomcol->Gaus(25,8);

      //printf("row: %d | col: %d | adc: %d\n",row,col,adc);

      bpixTree[2]->Fill();

    }
    */


    for(int i = 0; i < hitsInEvent; ++i){

      //random row value
      row = fy->GetRandom();
      
      //random column value
      col = fx->GetRandom();

      //random adc value
      adc = fadc->GetRandom();

      //printf("row: %d | col: %d | adc: %d\n",row,col,adc);


      bpixTree[1]->Fill();

    }


    ++ eventNr;
  }


  printf("Total number of Hits: %d\n",hitsTotal);
  printf("Writing output file: %s \n", outputFileName);

  outputFile->cd();
  outputFile->Write();
  outputFile->Close();

  printf("DONE!\n");

}
void RAA_read_data_pbpb(int startfile = 0,
			int endfile = 1,
			int radius = 4,
			std::string algo = "Vs",
			std::string jet_type = "PF",
			std::string kFoname="test_output.root"){
  
  TStopwatch timer;
  timer.Start();
  
  TH1::SetDefaultSumw2();
  TH2::SetDefaultSumw2();

  gStyle->SetOptStat(0);

  bool printDebug = false;
  if(printDebug)cout<<"radius = "<<radius<<endl;
  
  TDatime date;

  std::string infile_Forest;

  infile_Forest = "jetRAA_PbPb_data_forests.txt";
  std::ifstream instr_Forest(infile_Forest.c_str(),std::ifstream::in);
  std::string filename_Forest;
  
  if(printDebug)cout<<"reading from "<<startfile<<" to "<<endfile<<endl;
  
  for(int ifile = 0;ifile<startfile;ifile++){
    instr_Forest>>filename_Forest;
  }

  const int N = 4; //6

  TChain * jetpbpb[N];

  // Float_t ScaleFactor_55_NeqScale[nbins_cent] = {53.6 * 1e6, 53.6 * 1e6, 214.4 * 1e6, 214.4 * 1e6, 214.4 * 1e6, 214.4 * 1e6}; 
  // Float_t ScaleFactor_65_NeqScale[nbins_cent] = {53.6 * 1e6, 53.6 * 1e6, 214.4 * 1e6, 214.4 * 1e6, 214.4 * 1e6, 214.4 * 1e6}; 
  // Float_t ScaleFactor_80_NeqScale[nbins_cent] = {53.6 * 1e6, 53.6 * 1e6, 214.4 * 1e6, 214.4 * 1e6, 214.4 * 1e6, 214.4 * 1e6};   
  
  string dir[N];
  dir[0] = "hltanalysis";
  dir[1] = "skimanalysis";
  dir[2] = Form("ak%s%d%sJetAnalyzer",algo.c_str(),radius,jet_type.c_str());
  dir[3] = "hiEvtAnalyzer";
  // dir[4] = "hltobject";

  string trees[N] = {
    "HltTree",
    "HltTree",
    "t",
    "HiTree"
    // , "jetObjTree"
  };

  for(int t = 0;t<N;t++){
    jetpbpb[t] = new TChain(string(dir[t]+"/"+trees[t]).data());
  }//tree loop ends

  for(int ifile = startfile; ifile<endfile; ++ifile){

    instr_Forest>>filename_Forest;

    if(printDebug)cout<<"HiForest filename = "<<filename_Forest.c_str()<<endl;

    jetpbpb[0]->Add(filename_Forest.c_str());
    jetpbpb[1]->Add(filename_Forest.c_str());
    jetpbpb[2]->Add(filename_Forest.c_str());
    jetpbpb[3]->Add(filename_Forest.c_str());
    
    if(printDebug)cout << "Tree loaded  " << string(dir[0]+"/"+trees[0]).data() << endl;
    if(printDebug)cout << "Entries : " << jetpbpb[0]->GetEntries() << endl;
    if(printDebug)cout << "Tree loaded  " << string(dir[1]+"/"+trees[1]).data() << endl;
    if(printDebug)cout << "Entries : " << jetpbpb[1]->GetEntries() << endl;
    if(printDebug)cout << "Tree loaded  " << string(dir[2]+"/"+trees[2]).data() << endl;
    if(printDebug)cout << "Entries : " << jetpbpb[2]->GetEntries() << endl;
    if(printDebug)cout << "Tree loaded  " << string(dir[3]+"/"+trees[3]).data() << endl;
    if(printDebug)cout << "Entries : " << jetpbpb[3]->GetEntries() << endl;
  }
  
  jetpbpb[2]->AddFriend(jetpbpb[0]);
  jetpbpb[2]->AddFriend(jetpbpb[1]);
  jetpbpb[2]->AddFriend(jetpbpb[3]);
  
  // Forest files 
  int nref_F;
  float pt_F[1000];
  float rawpt_F[1000];
  float eta_F[1000];
  float phi_F[1000];
  float chMax_F[1000];
  float trkMax_F[1000];
  float chSum_F[1000];
  int chN_F[1000];
  float phSum_F[1000];
  float neSum_F[1000];
  float trkSum_F[1000];
  float phMax_F[1000];
  float neMax_F[1000];
  float eMax_F[1000];
  float muMax_F[1000];
  float eSum_F[1000];
  float muSum_F[1000];
  float jtpu_F[1000];
  float chHardMax_F[1000];
  float trkHardMax_F[1000];
  float chHardSum_F[1000];
  float phHardSum_F[1000];
  float trkHardSum_F[1000];
  float phHardMax_F[1000];
  int jet40_F;
  int jet60_F;
  int jet80_F;
  int L1_sj36_F;
  int L1_sj52_F;
  int L1_sj36_p_F;
  int L1_sj52_p_F;
  int jet40_p_F;
  int jet60_p_F;
  int jet80_p_F;
  float vz_F;
  int evt_F;
  int run_F;
  int lumi_F;
  int hiNpix_F;
  int hiNpixelTracks_F;
  int hiBin_F;
  float hiHF_F;
  float hiZDC_F;
  float hiZDCplus_F;
  float hiZDCminus_F;
  int hiNtracks_F;
  int hiNtracksPtCut_F;
  int hiNtracksEtaCut_F;
  int hiNtracksEtaPtCut_F;
  int pcollisionEventSelection_F;
  int pHBHENoiseFilter_F;
  
  jetpbpb[3]->SetBranchAddress("evt",&evt_F);
  jetpbpb[3]->SetBranchAddress("run",&run_F);
  jetpbpb[3]->SetBranchAddress("lumi",&lumi_F);
  jetpbpb[3]->SetBranchAddress("hiBin",&hiBin_F);
  jetpbpb[3]->SetBranchAddress("hiHF", &hiHF_F);
  jetpbpb[3]->SetBranchAddress("hiNpix",&hiNpix_F);
  jetpbpb[3]->SetBranchAddress("hiNpixelTracks",&hiNpixelTracks_F);
  jetpbpb[3]->SetBranchAddress("hiNtracks",&hiNtracks_F);
  jetpbpb[3]->SetBranchAddress("hiNtracksPtCut",&hiNtracksPtCut_F);
  jetpbpb[3]->SetBranchAddress("hiNtracksEtaCut",&hiNtracksEtaCut_F);
  jetpbpb[3]->SetBranchAddress("hiNtracksEtaPtCut",&hiNtracksEtaPtCut_F);
  jetpbpb[3]->SetBranchAddress("hiZDC", &hiZDC_F);
  jetpbpb[3]->SetBranchAddress("hiZDCplus", &hiZDCplus_F);
  jetpbpb[3]->SetBranchAddress("hiZDCminus", &hiZDCminus_F);
  jetpbpb[3]->SetBranchAddress("vz",&vz_F);
  jetpbpb[1]->SetBranchAddress("pcollisionEventSelection",&pcollisionEventSelection_F);
  jetpbpb[1]->SetBranchAddress("pHBHENoiseFilter",&pHBHENoiseFilter_F);
  //jetpbpb[0]->SetBranchAddress("pprimaryvertexFilter",&pprimaryvertexFilter_F);
  //jetpbpb[0]->SetBranchAddress("pVertexFilterCutGplus",&pVertexFilterCutGplus_F);
  jetpbpb[2]->SetBranchAddress("nref",&nref_F);
  jetpbpb[2]->SetBranchAddress("jtpt",pt_F);
  jetpbpb[2]->SetBranchAddress("jteta",eta_F);
  jetpbpb[2]->SetBranchAddress("jtphi",phi_F);
  jetpbpb[2]->SetBranchAddress("rawpt",rawpt_F);
  jetpbpb[2]->SetBranchAddress("jtpu",jtpu_F);
  
  jetpbpb[2]->SetBranchAddress("chargedMax",&chMax_F);
  jetpbpb[2]->SetBranchAddress("chargedSum",&chSum_F);
  jetpbpb[2]->SetBranchAddress("chargedN",&chN_F);
  //jetpbpb[2]->SetBranchAddress("chargedHardMax",&chMax_F);
  jetpbpb[2]->SetBranchAddress("chargedHardSum",&chSum_F);
  jetpbpb[2]->SetBranchAddress("trackMax",&trkMax_F);
  jetpbpb[2]->SetBranchAddress("trackSum",&trkSum_F);
  //jetpbpb[2]->SetBranchAddress("trackHardMax",&trkMax_F);
  jetpbpb[2]->SetBranchAddress("trackHardSum",&trkSum_F);
  jetpbpb[2]->SetBranchAddress("photonMax",&phMax_F);
  jetpbpb[2]->SetBranchAddress("photonSum",&phSum_F);
  //jetpbpb[2]->SetBranchAddress("photonHardMax",&phMax_F);
  jetpbpb[2]->SetBranchAddress("photonHardSum",&phSum_F);
  jetpbpb[2]->SetBranchAddress("neutralMax",&neMax_F);
  jetpbpb[2]->SetBranchAddress("neutralSum",&neSum_F);
  
  jetpbpb[2]->SetBranchAddress("eSum",eSum_F);
  jetpbpb[2]->SetBranchAddress("eMax",eMax_F);
  jetpbpb[2]->SetBranchAddress("muSum",muSum_F);
  jetpbpb[2]->SetBranchAddress("muMax",muMax_F);
  jetpbpb[0]->SetBranchAddress("HLT_HIJet40_v1",&jet40_F);
  jetpbpb[0]->SetBranchAddress("HLT_HIJet40_v1_Prescl",&jet40_p_F);
  jetpbpb[0]->SetBranchAddress("HLT_HIJet60_v1",&jet60_F);
  jetpbpb[0]->SetBranchAddress("HLT_HIJet60_v1_Prescl",&jet60_p_F);
  jetpbpb[0]->SetBranchAddress("HLT_HIJet80_v1",&jet80_F);
  jetpbpb[0]->SetBranchAddress("HLT_HIJet80_v1_Prescl",&jet80_p_F);
  jetpbpb[0]->SetBranchAddress("L1_SingleJet36_BptxAND",&L1_sj36_F);
  jetpbpb[0]->SetBranchAddress("L1_SingleJet36_BptxAND_Prescl",&L1_sj36_p_F);
  jetpbpb[0]->SetBranchAddress("L1_SingleJet52_BptxAND",&L1_sj52_F);
  jetpbpb[0]->SetBranchAddress("L1_SingleJet52_BptxAND_Prescl",&L1_sj52_p_F);

  // TFile * fJERJES = TFile::Open("JERJES_PF_PbPb_pp.root");

  // TH1F * hJES_mean[nbins_cent];
  // hJES_mean[0] = (TH1F*)fJERJES->Get(Form("ak%dJetAnalyzer/hMean_PbPb_R%d_PuPF_05",radius, radius));
  // hJES_mean[1] = (TH1F*)fJERJES->Get(Form("ak%dJetAnalyzer/hMean_PbPb_R%d_PuPF_510",radius, radius));
  // hJES_mean[2] = (TH1F*)fJERJES->Get(Form("ak%dJetAnalyzer/hMean_PbPb_R%d_PuPF_1030",radius, radius));
  // hJES_mean[3] = (TH1F*)fJERJES->Get(Form("ak%dJetAnalyzer/hMean_PbPb_R%d_PuPF_3050",radius, radius));
  // hJES_mean[4] = (TH1F*)fJERJES->Get(Form("ak%dJetAnalyzer/hMean_PbPb_R%d_PuPF_5070",radius, radius));
  // hJES_mean[5] = (TH1F*)fJERJES->Get(Form("ak%dJetAnalyzer/hMean_PbPb_R%d_PuPF_7090",radius, radius));  
  
  // Declare the output File and the necessary histograms after that:
  // std::string outdir="";
  // std::string outfile=outdir+kFoname;
  TFile *fout = new TFile(kFoname.c_str(),"RECREATE");
  fout->cd();

  // TH1F * hpbpb_Jet80[nbins_cent];
  // TH1F * hpbpb_Jet60[nbins_cent];
  // TH1F * hpbpb_Jet40[nbins_cent];
  // TH1F * hpbpb_JetComb[nbins_cent];

  // TH1F * hpbpb_JEC_Jet80[nbins_cent];
  // TH1F * hpbpb_JEC_Jet60[nbins_cent];
  // TH1F * hpbpb_JEC_Jet40[nbins_cent];
  // TH1F * hpbpb_JEC_JetComb[nbins_cent];

  // TH1F * hpbpb_JEC_minus_Jet80[nbins_cent];
  // TH1F * hpbpb_JEC_minus_Jet60[nbins_cent];
  // TH1F * hpbpb_JEC_minus_Jet40[nbins_cent];
  // TH1F * hpbpb_JEC_minus_JetComb[nbins_cent];


  // TH1F * hpbpb_JEC_gaus_Jet80[nbins_cent];
  // TH1F * hpbpb_JEC_gaus_Jet60[nbins_cent];
  // TH1F * hpbpb_JEC_gaus_Jet40[nbins_cent];
  // TH1F * hpbpb_JEC_gaus_JetComb[nbins_cent];
  
  // TH1F * hpbpb_Smear_Jet80[nbins_cent];
  // TH1F * hpbpb_Smear_Jet60[nbins_cent];
  // TH1F * hpbpb_Smear_Jet40[nbins_cent];
  // TH1F * hpbpb_Smear_JetComb[nbins_cent];

  std::string var[19] = {"jtpt" ,"rawpt", "jteta", "jtphi", "trkMax", "trkSum", "trkHardSum", "chMax", "chSum", "chHardSum","phMax", "phSum", "phHardSum", "neMax", "neSum", "eMax", "eSum", "muMax", "muSum" };
  TH1F * hJetQA[2][19][nbins_cent];
  
  for(int i = 0;i<nbins_cent;++i){

    /*
    hpbpb_Jet80[i] = new TH1F(Form("hpbpb_HLT80_R%d_%s_cent%d",radius,etaWidth,i),Form("Spectra from  Jet 80 R%d %s %2.0f - %2.0f cent",radius,etaWidth,5*boundaries_cent[i],5*boundaries_cent[i+1]),1000, 0, 1000);
    hpbpb_Jet60[i] = new TH1F(Form("hpbpb_HLT65_R%d_%s_cent%d",radius,etaWidth,i),Form("Spectra from  Jet 65 && !jet80 R%d %s %2.0f - %2.0f cent",radius,etaWidth,5*boundaries_cent[i],5*boundaries_cent[i+1]),1000, 0, 1000);
    hpbpb_Jet40[i] = new TH1F(Form("hpbpb_HLT55_R%d_%s_cent%d",radius,etaWidth,i),Form("Spectra from Jet 55 && !jet60 && !jet80 R%d %s %2.0f - %2.0f cent",radius,etaWidth,5*boundaries_cent[i],5*boundaries_cent[i+1]),1000, 0, 1000);
    hpbpb_JetComb[i] = new TH1F(Form("hpbpb_HLTComb_R%d_%s_cent%d",radius,etaWidth,i),Form("Trig Combined Spectra R%d %s %2.0f - %2.0f cent",radius,etaWidth,5*boundaries_cent[i],5*boundaries_cent[i+1]),1000, 0, 1000);

    hpbpb_JEC_Jet80[i] = new TH1F(Form("hpbpb_JEC_HLT80_R%d_%s_cent%d",radius,etaWidth,i),Form("Spectra from  Jet 80 R%d %s %2.0f - %2.0f cent",radius,etaWidth,5*boundaries_cent[i],5*boundaries_cent[i+1]),1000, 0, 1000);
    hpbpb_JEC_Jet60[i] = new TH1F(Form("hpbpb_JEC_HLT65_R%d_%s_cent%d",radius,etaWidth,i),Form("Spectra from  Jet 65 && !jet80 R%d %s %2.0f - %2.0f cent",radius,etaWidth,5*boundaries_cent[i],5*boundaries_cent[i+1]),1000, 0, 1000);
    hpbpb_JEC_Jet40[i] = new TH1F(Form("hpbpb_JEC_HLT55_R%d_%s_cent%d",radius,etaWidth,i),Form("Spectra from Jet 55 && !jet60 && !jet80 R%d %s %2.0f - %2.0f cent",radius,etaWidth,5*boundaries_cent[i],5*boundaries_cent[i+1]),1000, 0, 1000);
    hpbpb_JEC_JetComb[i] = new TH1F(Form("hpbpb_JEC_HLTComb_R%d_%s_cent%d",radius,etaWidth,i),Form("Trig Combined Spectra R%d %s %2.0f - %2.0f cent",radius,etaWidth,5*boundaries_cent[i],5*boundaries_cent[i+1]),1000, 0, 1000);

    hpbpb_JEC_minus_Jet80[i] = new TH1F(Form("hpbpb_JEC_minus_HLT80_R%d_%s_cent%d",radius,etaWidth,i),Form("Spectra from  Jet 80 R%d %s %2.0f - %2.0f cent",radius,etaWidth,5*boundaries_cent[i],5*boundaries_cent[i+1]),1000, 0, 1000);
    hpbpb_JEC_minus_Jet60[i] = new TH1F(Form("hpbpb_JEC_minus_HLT65_R%d_%s_cent%d",radius,etaWidth,i),Form("Spectra from  Jet 65 && !jet80 R%d %s %2.0f - %2.0f cent",radius,etaWidth,5*boundaries_cent[i],5*boundaries_cent[i+1]),1000, 0, 1000);
    hpbpb_JEC_minus_Jet40[i] = new TH1F(Form("hpbpb_JEC_minus_HLT55_R%d_%s_cent%d",radius,etaWidth,i),Form("Spectra from Jet 55 && !jet60 && !jet80 R%d %s %2.0f - %2.0f cent",radius,etaWidth,5*boundaries_cent[i],5*boundaries_cent[i+1]),1000, 0, 1000);
    hpbpb_JEC_minus_JetComb[i] = new TH1F(Form("hpbpb_JEC_minus_HLTComb_R%d_%s_cent%d",radius,etaWidth,i),Form("Trig Combined Spectra R%d %s %2.0f - %2.0f cent",radius,etaWidth,5*boundaries_cent[i],5*boundaries_cent[i+1]),1000, 0, 1000);

    hpbpb_JEC_gaus_Jet80[i] = new TH1F(Form("hpbpb_JEC_gaus_HLT80_R%d_%s_cent%d",radius,etaWidth,i),Form("Spectra from  Jet 80 R%d %s %2.0f - %2.0f cent",radius,etaWidth,5*boundaries_cent[i],5*boundaries_cent[i+1]),1000, 0, 1000);
    hpbpb_JEC_gaus_Jet60[i] = new TH1F(Form("hpbpb_JEC_gaus_HLT65_R%d_%s_cent%d",radius,etaWidth,i),Form("Spectra from  Jet 65 && !jet80 R%d %s %2.0f - %2.0f cent",radius,etaWidth,5*boundaries_cent[i],5*boundaries_cent[i+1]),1000, 0, 1000);
    hpbpb_JEC_gaus_Jet40[i] = new TH1F(Form("hpbpb_JEC_gaus_HLT55_R%d_%s_cent%d",radius,etaWidth,i),Form("Spectra from Jet 55 && !jet60 && !jet80 R%d %s %2.0f - %2.0f cent",radius,etaWidth,5*boundaries_cent[i],5*boundaries_cent[i+1]),1000, 0, 1000);
    hpbpb_JEC_gaus_JetComb[i] = new TH1F(Form("hpbpb_JEC_gaus_HLTComb_R%d_%s_cent%d",radius,etaWidth,i),Form("Trig Combined Spectra R%d %s %2.0f - %2.0f cent",radius,etaWidth,5*boundaries_cent[i],5*boundaries_cent[i+1]),1000, 0, 1000);

    
    hpbpb_Smear_Jet80[i] = new TH1F(Form("hpbpb_Smear_HLT80_R%d_%s_cent%d",radius,etaWidth,i),Form("Spectra from  Jet 80 R%d %s %2.0f - %2.0f cent",radius,etaWidth,5*boundaries_cent[i],5*boundaries_cent[i+1]),1000, 0, 1000);
    hpbpb_Smear_Jet60[i] = new TH1F(Form("hpbpb_Smear_HLT65_R%d_%s_cent%d",radius,etaWidth,i),Form("Spectra from  Jet 65 && !jet80 R%d %s %2.0f - %2.0f cent",radius,etaWidth,5*boundaries_cent[i],5*boundaries_cent[i+1]),1000, 0, 1000);
    hpbpb_Smear_Jet40[i] = new TH1F(Form("hpbpb_Smear_HLT55_R%d_%s_cent%d",radius,etaWidth,i),Form("Spectra from Jet 55 && !jet60 && !jet80 R%d %s %2.0f - %2.0f cent",radius,etaWidth,5*boundaries_cent[i],5*boundaries_cent[i+1]),1000, 0, 1000);
    hpbpb_Smear_JetComb[i] = new TH1F(Form("hpbpb_Smear_HLTComb_R%d_%s_cent%d",radius,etaWidth,i),Form("Trig Combined Spectra R%d %s %2.0f - %2.0f cent",radius,etaWidth,5*boundaries_cent[i],5*boundaries_cent[i+1]),1000, 0, 1000);
    */
    
    for(int k = 0; k<2; ++k){
      for(int j = 0; j<19; ++j){
	if(j==2) hJetQA[k][j][i] = new TH1F(Form("hJetQA_%dwJetID_%s_cent%d",k,var[j].c_str(),i),Form(";%s;",var[j].c_str()),100, -5, +5);
	else if(j==3) hJetQA[k][j][i] = new TH1F(Form("hJetQA_%dwJetID_%s_cent%d",k,var[j].c_str(),i),Form(";%s;",var[j].c_str()),100, -4, +4);
	else if(j<=1)hJetQA[k][j][i] = new TH1F(Form("hJetQA_%dwJetID_%s_cent%d",k,var[j].c_str(),i),Form(";%s;",var[j].c_str()),500, 0, 500);
	else if(j>=4)hJetQA[k][j][i] = new TH1F(Form("hJetQA_%dwJetID_%s_cent%d",k,var[j].c_str(),i),Form(";%s;",var[j].c_str()),200, 0, 2);
      }
    }
    
  }


  
  // float ue_fluctuation[nbins_cent] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
  // if(radius == 4) {
  //   ue_fluctuation[0] = 5.0;
  //   ue_fluctuation[1] = 1.5;
  //   ue_fluctuation[2] = 0.3;
  //   ue_fluctuation[3] = 0.1;
  //   ue_fluctuation[4] = 0.1;
  //   ue_fluctuation[5] = 0.01;
  // }
  // if(radius == 3) {
  //   ue_fluctuation[0] = 3.17;
  //   ue_fluctuation[1] = 0.7;
  //   ue_fluctuation[2] = 0.1;
  //   ue_fluctuation[3] = 0.1;
  //   ue_fluctuation[4] = 0.1;
  //   ue_fluctuation[5] = 0.01;
  // }
  // if(radius == 2) {
  //   ue_fluctuation[0] = 1.5;
  //   ue_fluctuation[1] = 0.4;
  //   ue_fluctuation[2] = 0.2;
  //   ue_fluctuation[3] = 0.1;
  //   ue_fluctuation[4] = 0.1;
  //   ue_fluctuation[5] = 0.01;
  // }

  // float  ue_fluctuation = 6.0;
  // if(radius == 4) ue_fluctuation = 6.0;
  // if(radius == 3) ue_fluctuation = 4.0;
  // if(radius == 2) ue_fluctuation = 2.0;

  // the UE Smear corresponds to doing recpt = recpt * (1 + rnd.Gaus(0, (float)ue_fluctuation[cBin]/recpt);
  
  // now start the event loop for each file. 
  if(printDebug) cout<<"Running through all the events now"<<endl;
  Long64_t nentries = jetpbpb[0]->GetEntries();
  if(printDebug) nentries = 10;
  TRandom3 rnd;
  rnd.SetSeed(endfile);

  for(int nEvt = 0; nEvt < nentries; ++ nEvt) {

    if(nEvt%10000 == 0)cout<<nEvt<<"/"<<nentries<<endl;
    if(printDebug)cout<<"nEvt = "<<nEvt<<endl;
    
    jetpbpb[0]->GetEntry(nEvt);
    jetpbpb[1]->GetEntry(nEvt);
    jetpbpb[2]->GetEntry(nEvt);
    jetpbpb[3]->GetEntry(nEvt);

    if(printDebug) cout<<"forest values = "<<hiBin_F<<", "<<evt_F<<", "<<run_F<<", "<<lumi_F<<", "<<vz_F<<endl;
    
    if(pHBHENoiseFilter_F == 0) continue; 
    if(pcollisionEventSelection_F == 0) continue; 
    if(fabs(vz_F)>15) continue;
    // if(!isGoodEvent_eS) continue; 

    int cBin = findBin(hiBin_F);//tells us the centrality of the event.
    if(cBin == -1) continue;

    // int jetCounter = 0;
    
    // for(int g = 0;g<nref_F;g++){
      
    //   if(eta_F[g]>=-2 && eta_F[g]<2){ //to select inside 
	
    // 	if(pt_F[g]>=50) jetCounter++;
	
    //   }//eta selection cut
      
    // }// jet loop

    
    // jet_select->GetEntry(nGoodEvt);
    // ++nGoodEvt;
    Float_t weight_eS = 1.0; 

    //if(cBin == nbins_cent) continue;
    // // apply the correct supernova selection cut rejection here: 
    // if(hiNpix_F >= (38000 - 500*jetCounter)){
    //   if(printDebug) cout<<"removed this supernova event"<<endl;
    //   continue;
    // }

    // if((float)hiZDCminus_F/1350 >= (90 - 0.0204 * hiHF_F)) continue;

    // //! Sort the jetTree jets according to pT
    // std::vector < Jet > vJet;
    // for(int jet2 = 0; jet2<nref_jS; ++jet2){
    //   //cout <<"\t \t jetTree *** "<< jet2 <<  ", pT " << pt_jS[jet2] <<  ", chSum : "<< chSum_jS[jet2] << endl;
    //   Jet ijet;
    //   ijet.id = jet2;
    //   ijet.pt = pt_jS[jet2];
    //   vJet.push_back(ijet);
    // }
    // std::sort (vJet.begin(), vJet.end(), compare_pt);
    // std::vector < Jet >::const_iterator itr;

    // int jet=0;
    // for(itr=vJet.begin(); itr!=vJet.end(); ++itr, ++jet){

    //   int jetLoc = (*itr).id;
    //   if(isMultiMatch_jS[jetLoc]) {
    // 	++itr;
    // 	jetLoc = (*itr).id;
    // 	if(itr == vJet.end())  break;
    //   }
    //   if(fabs(eta_jS[jetLoc]) > 2) continue;
    //   //if(isPFElecCut_eS[jet] != 1) continue;
    //   // if(isMiMatch_eS[jet]) continue;
    //   if(pt_jS[jetLoc] <15) continue;

    //   bool PFElecCut = false;

    //   Float_t Sumcand = chSum_jS[jetLoc] + phSum_jS[jetLoc] + neSum_jS[jetLoc] + muSum_jS[jetLoc];
    //   if(isCaloMatch_jS[jetLoc] == 1){
    // 	if(calopt_jS[jetLoc]/pt_jS[jetLoc] > 0.5 && calopt_jS[jetLoc]/pt_jS[jetLoc] <= 0.85 && eMax_jS[jetLoc]/Sumcand < ((Float_t)18/7 *(Float_t)calopt_jS[jetLoc]/pt_jS[jetLoc] - (Float_t)9/7)) PFElecCut = true;
    // 	if(calopt_jS[jetLoc]/pt_jS[jetLoc] > 0.85) PFElecCut = true;
    // 	if(calopt_jS[jetLoc]/pt_jS[jetLoc] <= 0.5 && eMax_jS[jetLoc]/Sumcand < 0.05) PFElecCut = true;
    //   }
    //   if(isCaloMatch_jS[jetLoc] == 0)
    // 	if(eMax_jS[jetLoc]/Sumcand < 0.05 ) PFElecCut = true;

    //   // if(!PFElecCut) continue;
      
    //   // if(printDebug && (fabs(eta_jS[jet] > 2))) cout<<"jets with |eta| > 2 in jetTree"<<endl;
    //   // if(printDebug && (fabs(eta_F[jet] > 2)))  cout<<"jets with |eta| > 2 in Forest"<<endl;

      
    //   if(printDebug && index_eS[jet] >= 0 )cout<<jet<<", hiForest pT = "<<pt_F[jet]<<", jetTree pT = "<<pt_jS[jetLoc]<<", electronCut = "<<isPFElecCut_eS[jetLoc]<<", Calo pT = "<<calopt_F[index_eS[jet]]<<", onFly flag calculation = "<<PFElecCut<<", eMax from hiForest = "<<eMax_F[jet]<<", eMax from jet Tree = "<<eMax_jS[jetLoc]<<endl;      // if(printDebug)cout<<jet<<", hiForest pT = "<<pt_F[jet]<<", jetTree pT = "<<pt_jS[jetLoc]<<", electronCut = "<<isPFElecCut_eS[jetLoc]<<", eMax from hiForest = "<<eMax_F[jet]<<", eMax from jet Tree = "<<eMax_jS[jetLoc]<<endl;

    for( int jet = 0; jet<nref_F; jet++ ){

      if( fabs(eta_F[jet]) > 2.0 ) continue;
      //if( isPFElecCut_eS[jet] != 1 ) continue;

      //if( chMax_F[jet] < 7 && trkMax_F[jet] < 7 && neMax_F[jet] < 8 ) continue;
      // if( trkMax_F[jet] < 7 && neMax_F[jet] < 8 ) continue;

      // bool PFElecCut = false;
      // Float_t calopfpt = (float) calopt_eS[jet]/pt_F[jet];
      // Float_t Sumcand = chSum_F[jet] + phSum_F[jet] + neSum_F[jet] + muSum_F[jet];
      float recpt     = pt_F[jet];
      float rawpt = rawpt_F[jet];
      if(recpt<=30) continue;

// #if 0
//       int recpt_loc = 0;      
//       for(int j = 0; j<ptSelection; ++j)
// 	if(recpt > ptBoundary[j]) recpt_loc = j;      
//       if(isClMatch_eS[jet] == 1) heMaxSumcand_vs_calopfpt_RecopTSelection[recpt_loc][cBin]->Fill(calopfpt, (float)eMax_F[jet]/Sumcand);
//       else heMaxSumcand_vs_calopfpt_RecopTSelection[recpt_loc][cBin]->Fill(0.0, (float)eMax_F[jet]/Sumcand);
// #endif
      
//       if(isClMatch_eS[jet] == 1){
//     	if(calopfpt > 0.5 && calopfpt <= 0.85 && eMax_F[jet]/Sumcand < ((Float_t)18/7 *(Float_t)calopfpt - (Float_t)9/7)) PFElecCut = true;
//     	if(calopfpt > 0.85) PFElecCut = true;
//     	if(calopfpt <= 0.5 && eMax_F[jet]/Sumcand < 0.05) PFElecCut = true;
//       }
//       if(isClMatch_eS[jet] == 0)
//     	if(eMax_F[jet]/Sumcand < 0.05 ) PFElecCut = true;

//       if(isPFElecCut_eS[jet] != PFElecCut && printDebug) 
// 	cout<<" pf e cut not same, run = "<<run_F<<" "<<run_eS<<", event = "<<evt_F<<" "<<evt_eS<<" , lumi = "<<lumi_F<<" "<<lumi_eS<<endl;
	  
//       if(!PFElecCut) continue;

      // also need to cut on the high pT jets from the Jet 55 sample. unmatched PF jets with pfpt > 110 and calopt < 30 including -999, check on their high track content. at the moment dont worry about this.  

      // float JEC_Smear = recpt;
      // float JEC_minus_Smear = recpt;
      // float JEC_gaus_Smear = recpt;
      // float UE_Smear = recpt;
      // // this is some percentage (+ or -) from 0 to 1-JES
      // //float RanJES = (float)(rnd.Gaus(0.0,fabs(1.-hJES_mean[cBin]->GetBinContent(hJES_mean[cBin]->FindBin(recpt)))));
      // // this is some scale up and down (+ or -) from 0 to ue_fluct, so if ue_fluct is 10, the jet can change by 1sigma -10 or +10
      // float RanUE =  (float)(rnd.Gaus(0.0,(float)ue_fluctuation[cBin]));
      // UE_Smear = recpt+RanUE;
      // float JEC_5pcent_Smear = (float)recpt * (1. + (float)0.05/nbins_cent*(nbins_cent-cBin));
      // if(radius == 2 )JEC_Smear = (float)recpt * (1. + (float)0.01/nbins_cent*(nbins_cent-cBin));
      // if(radius == 3 )JEC_Smear = (float)recpt * (1. + (float)0.01/nbins_cent*(nbins_cent-cBin));
      // if(radius == 4 )JEC_Smear = (float)recpt * (1. + (float)0.01/nbins_cent*(nbins_cent-cBin));

      // float Shift = 0.0;
      // for(int bin = 0; bin<nbins_jec; ++bin)
      // 	if(recpt > ptbins_jec[bin])
      // 	  Shift = jec_shift[bin];
      
      // JEC_Smear = (float)recpt * (1.0 + Shift);
      // JEC_minus_Smear = (float)recpt * (1.0 - Shift);
      
      // JEC_gaus_Smear = (float)recpt * (rnd.Gaus(1, Shift));

      //JEC_Smear = recpt*(1 + RanJES);      
      // if(recpt >= 105 && recpt < 106){	
      // 	hJet_100GeV_input[cBin]->Fill(recpt);
      // 	hJet_100GeV_JECSmear[cBin]->Fill(JEC_Smear);
      // 	hJet_100GeV_JEC_5pcentSmear[cBin]->Fill(JEC_5pcent_Smear);
      // 	hJet_100GeV_UESmear[cBin]->Fill(UE_Smear);
      // }
 
      // float recpt     = pt_F[jet];
      // float JEC_Smear = recpt;
      // float UE_Smear = recpt;
      // float pm = (float)(rnd.Gaus(0.0, 1.0));
      // if(pm > 0) {
      // 	JEC_Smear = (float)(recpt * (1. + (float)(rnd.Gaus(0.0, (float)fabs(1. - hJES_mean[cBin]->GetBinContent(hJES_mean[cBin]->FindBin(recpt)))))));
      // 	UE_Smear  = (float)(recpt * (1. + (float)(rnd.Gaus(0.0, (float)ue_fluctuation[cBin]/recpt))));
      // }
      // if(pm < 0){
      // 	JEC_Smear = (float)(recpt * (1. - (float)(rnd.Gaus(0.0, (float)fabs(1. - hJES_mean[cBin]->GetBinContent(hJES_mean[cBin]->FindBin(recpt)))))));
      // 	UE_Smear  = (float)(recpt * (1. - (float)(rnd.Gaus(0.0, (float)ue_fluctuation[cBin]/recpt))));
      // }
      
      // if(jet60_F == 1) hpbpb_HLT65[cBin]->Fill(recpt);
      // if(jet40_F == 1) hpbpb_HLT55[cBin]->Fill(recpt);
      
      // if(jet40_F == 1 && jet60_F == 0 && jet80_F == 0){
      // 	//if(recpt > 140) continue;
      // 	hpbpb_Jet40[cBin]->Fill(recpt, jet40_p_F* wght);
      // 	hpbpb_Smear_Jet40[cBin]->Fill(UE_Smear, jet40_p_F* wght);
      // 	hpbpb_JEC_Jet40[cBin]->Fill(JEC_Smear, jet40_p_F* wght);
      // 	hpbpb_JEC_minus_Jet40[cBin]->Fill(JEC_minus_Smear, jet40_p_F* wght);
      // 	hpbpb_JEC_gaus_Jet40[cBin]->Fill(JEC_gaus_Smear, jet40_p_F* wght);

      // 	// hpbpb_TrgObj55[cBin]->Fill(recpt, jet40_p_F* wght);
      // 	// hpbpb_raw_TrgObj55[cBin]->Fill(rawpt_F[jet], jet40_p_F* wght);
      // 	// hpbpb_anaBin_TrgObj55[cBin]->Fill(recpt, jet40_p_F* wght);
      // 	// hpbpb_JEC_TrgObj55[cBin]->Fill(JEC_Smear, jet40_p_F* wght);
      // 	// hpbpb_JEC_5pcent_TrgObj55[cBin]->Fill(JEC_5pcent_Smear, jet40_p_F* wght);
      // 	// hpbpb_Smear_TrgObj55[cBin]->Fill(UE_Smear, jet40_p_F* wght);
      // }
      // if(jet60_F == 1 && jet80_F == 0){
      // 	//if(recpt > 140) continue;
      // 	hpbpb_Jet60[cBin]->Fill(recpt,wght);
      // 	hpbpb_Smear_Jet60[cBin]->Fill(UE_Smear, wght);
      // 	hpbpb_JEC_Jet60[cBin]->Fill(JEC_Smear, wght);
      // 	hpbpb_JEC_minus_Jet60[cBin]->Fill(JEC_minus_Smear, wght);
      // 	hpbpb_JEC_gaus_Jet60[cBin]->Fill(JEC_gaus_Smear, wght);

      // 	// hpbpb_TrgObj65[cBin]->Fill(recpt, wght);
      // 	// hpbpb_raw_TrgObj65[cBin]->Fill(rawpt_F[jet], wght);
      // 	// hpbpb_anaBin_TrgObj65[cBin]->Fill(recpt, wght);
      // 	// hpbpb_JEC_TrgObj65[cBin]->Fill(JEC_Smear, wght);
      // 	// hpbpb_JEC_5pcent_TrgObj65[cBin]->Fill(JEC_5pcent_Smear, wght);
      // 	// hpbpb_Smear_TrgObj65[cBin]->Fill(UE_Smear, wght);
      // }
      // if(jet80_F == 1){
      // 	hpbpb_Jet80[cBin]->Fill(recpt, wght);
      // 	hpbpb_Smear_Jet80[cBin]->Fill(UE_Smear,wght);
      // 	hpbpb_JEC_Jet80[cBin]->Fill(JEC_Smear, wght);
      // 	hpbpb_JEC_minus_Jet80[cBin]->Fill(JEC_minus_Smear, wght);
      // 	hpbpb_JEC_gaus_Jet80[cBin]->Fill(JEC_gaus_Smear, wght);

      // 	// hpbpb_TrgObj80[cBin]->Fill(recpt, wght);
      // 	// hpbpb_raw_TrgObj80[cBin]->Fill(rawpt_F[jet], wght);
      // 	// hpbpb_anaBin_TrgObj80[cBin]->Fill(recpt, wght);
      // 	// hpbpb_JEC_TrgObj80[cBin]->Fill(JEC_Smear, wght);
      // 	// hpbpb_JEC_5pcent_TrgObj80[cBin]->Fill(JEC_5pcent_Smear, wght);
      // 	// hpbpb_Smear_TrgObj80[cBin]->Fill(UE_Smear, wght);
      // }


      if(1){
	hJetQA[0][0][cBin]->Fill(recpt, weight_eS);
	hJetQA[0][1][cBin]->Fill(rawpt_F[jet], weight_eS);
	hJetQA[0][2][cBin]->Fill(eta_F[jet], weight_eS);
	hJetQA[0][3][cBin]->Fill(phi_F[jet], weight_eS);
	hJetQA[0][4][cBin]->Fill(trkMax_F[jet]/recpt, weight_eS);
	hJetQA[0][5][cBin]->Fill(trkSum_F[jet]/recpt, weight_eS);
	hJetQA[0][6][cBin]->Fill(trkHardSum_F[jet]/recpt, weight_eS);
	hJetQA[0][7][cBin]->Fill(chMax_F[jet]/recpt, weight_eS);
	hJetQA[0][8][cBin]->Fill(chSum_F[jet]/recpt, weight_eS);
	hJetQA[0][9][cBin]->Fill(chHardSum_F[jet]/recpt, weight_eS);
	hJetQA[0][10][cBin]->Fill(phMax_F[jet]/recpt, weight_eS);
	hJetQA[0][11][cBin]->Fill(phSum_F[jet]/recpt, weight_eS);
	hJetQA[0][12][cBin]->Fill(phHardSum_F[jet]/recpt, weight_eS);
	hJetQA[0][13][cBin]->Fill(neMax_F[jet]/recpt, weight_eS);
	hJetQA[0][14][cBin]->Fill(neSum_F[jet]/recpt, weight_eS);
	hJetQA[0][15][cBin]->Fill(eMax_F[jet]/recpt, weight_eS);
	hJetQA[0][16][cBin]->Fill(eSum_F[jet]/recpt, weight_eS);
	hJetQA[0][17][cBin]->Fill(muMax_F[jet]/recpt, weight_eS);
	hJetQA[0][18][cBin]->Fill(muSum_F[jet]/recpt, weight_eS);

	// apply JetID
	// charged hadron fraction > 0
	// charged hadron multiplicity > 0
	// charged EM fraction < 0.99 
	
	if(chSum_F[jet]/recpt<0.99 && chSum_F[jet]/recpt>0 && neSum_F[jet]/recpt<0.99 && chN_F[jet]>0 && eSum_F[jet]/recpt<0.99){
	  hJetQA[1][0][cBin]->Fill(recpt, weight_eS);
	  hJetQA[1][1][cBin]->Fill(rawpt_F[jet], weight_eS);
	  hJetQA[1][2][cBin]->Fill(eta_F[jet], weight_eS);
	  hJetQA[1][3][cBin]->Fill(phi_F[jet], weight_eS);
	  hJetQA[1][4][cBin]->Fill(trkMax_F[jet]/recpt, weight_eS);
	  hJetQA[1][5][cBin]->Fill(trkSum_F[jet]/recpt, weight_eS);
	  hJetQA[1][6][cBin]->Fill(trkHardSum_F[jet]/recpt, weight_eS);
	  hJetQA[1][7][cBin]->Fill(chMax_F[jet]/recpt, weight_eS);
	  hJetQA[1][8][cBin]->Fill(chSum_F[jet]/recpt, weight_eS);
	  hJetQA[1][9][cBin]->Fill(chHardSum_F[jet]/recpt, weight_eS);
	  hJetQA[1][10][cBin]->Fill(phMax_F[jet]/recpt, weight_eS);
	  hJetQA[1][11][cBin]->Fill(phSum_F[jet]/recpt, weight_eS);
	  hJetQA[1][12][cBin]->Fill(phHardSum_F[jet]/recpt, weight_eS);
	  hJetQA[1][13][cBin]->Fill(neMax_F[jet]/recpt, weight_eS);
	  hJetQA[1][14][cBin]->Fill(neSum_F[jet]/recpt, weight_eS);
	  hJetQA[1][15][cBin]->Fill(eMax_F[jet]/recpt, weight_eS);
	  hJetQA[1][16][cBin]->Fill(eSum_F[jet]/recpt, weight_eS);
	  hJetQA[1][17][cBin]->Fill(muMax_F[jet]/recpt, weight_eS);
	  hJetQA[1][18][cBin]->Fill(muSum_F[jet]/recpt, weight_eS);
	}
	
      }

      
    }// jet loop
    if(printDebug)cout<<endl;


  }// event loop


  /*
  for(int i = 0; i<nbins_cent; ++i){


    hpbpb_Jet80[i]->Scale(1./ScaleFactor_80_NeqScale[i]);
    hpbpb_Jet60[i]->Scale(1./ScaleFactor_65_NeqScale[i]);
    hpbpb_Jet40[i]->Scale(1./ScaleFactor_55_NeqScale[i]);
    hpbpb_JetComb[i]->Add(hpbpb_Jet80[i]);
    hpbpb_JetComb[i]->Add(hpbpb_Jet60[i]);
    hpbpb_JetComb[i]->Add(hpbpb_Jet40[i]);
    
    divideBinWidth(hpbpb_JetComb[i]);
    divideBinWidth(hpbpb_Jet80[i]);
    divideBinWidth(hpbpb_Jet60[i]);
    divideBinWidth(hpbpb_Jet40[i]);

    hpbpb_JEC_Jet80[i]->Scale(1./ScaleFactor_80_NeqScale[i]);
    hpbpb_JEC_Jet60[i]->Scale(1./ScaleFactor_65_NeqScale[i]);
    hpbpb_JEC_Jet40[i]->Scale(1./ScaleFactor_55_NeqScale[i]);
    hpbpb_JEC_JetComb[i]->Add(hpbpb_JEC_Jet80[i]);
    hpbpb_JEC_JetComb[i]->Add(hpbpb_JEC_Jet60[i]);
    hpbpb_JEC_JetComb[i]->Add(hpbpb_JEC_Jet40[i]);
    
    divideBinWidth(hpbpb_JEC_JetComb[i]);
    divideBinWidth(hpbpb_JEC_Jet80[i]);
    divideBinWidth(hpbpb_JEC_Jet60[i]);
    divideBinWidth(hpbpb_JEC_Jet40[i]);

    hpbpb_JEC_minus_Jet80[i]->Scale(1./ScaleFactor_80_NeqScale[i]);
    hpbpb_JEC_minus_Jet60[i]->Scale(1./ScaleFactor_65_NeqScale[i]);
    hpbpb_JEC_minus_Jet40[i]->Scale(1./ScaleFactor_55_NeqScale[i]);
    hpbpb_JEC_minus_JetComb[i]->Add(hpbpb_JEC_minus_Jet80[i]);
    hpbpb_JEC_minus_JetComb[i]->Add(hpbpb_JEC_minus_Jet60[i]);
    hpbpb_JEC_minus_JetComb[i]->Add(hpbpb_JEC_minus_Jet40[i]);
    
    divideBinWidth(hpbpb_JEC_minus_JetComb[i]);
    divideBinWidth(hpbpb_JEC_minus_Jet80[i]);
    divideBinWidth(hpbpb_JEC_minus_Jet60[i]);
    divideBinWidth(hpbpb_JEC_minus_Jet40[i]);

    hpbpb_JEC_gaus_Jet80[i]->Scale(1./ScaleFactor_80_NeqScale[i]);
    hpbpb_JEC_gaus_Jet60[i]->Scale(1./ScaleFactor_65_NeqScale[i]);
    hpbpb_JEC_gaus_Jet40[i]->Scale(1./ScaleFactor_55_NeqScale[i]);
    hpbpb_JEC_gaus_JetComb[i]->Add(hpbpb_JEC_gaus_Jet80[i]);
    hpbpb_JEC_gaus_JetComb[i]->Add(hpbpb_JEC_gaus_Jet60[i]);
    hpbpb_JEC_gaus_JetComb[i]->Add(hpbpb_JEC_gaus_Jet40[i]);
    
    divideBinWidth(hpbpb_JEC_gaus_JetComb[i]);
    divideBinWidth(hpbpb_JEC_gaus_Jet80[i]);
    divideBinWidth(hpbpb_JEC_gaus_Jet60[i]);
    divideBinWidth(hpbpb_JEC_gaus_Jet40[i]);
    
    hpbpb_Smear_Jet80[i]->Scale(1./ScaleFactor_80_NeqScale[i]);
    hpbpb_Smear_Jet60[i]->Scale(1./ScaleFactor_65_NeqScale[i]);
    hpbpb_Smear_Jet40[i]->Scale(1./ScaleFactor_55_NeqScale[i]);
    hpbpb_Smear_JetComb[i]->Add(hpbpb_Smear_Jet80[i]);
    hpbpb_Smear_JetComb[i]->Add(hpbpb_Smear_Jet60[i]);
    hpbpb_Smear_JetComb[i]->Add(hpbpb_Smear_Jet40[i]);
    
    divideBinWidth(hpbpb_Smear_JetComb[i]);
    divideBinWidth(hpbpb_Smear_Jet80[i]);
    divideBinWidth(hpbpb_Smear_Jet60[i]);
    divideBinWidth(hpbpb_Smear_Jet40[i]);

    
    // hpbpb_TrgObjComb[i]->Add(hpbpb_TrgObj80[i]);
    // hpbpb_TrgObjComb[i]->Add(hpbpb_TrgObj65[i]);
    // hpbpb_TrgObjComb[i]->Add(hpbpb_TrgObj55[i]);
    
    // divideBinWidth(hpbpb_TrgObjComb[i]);
    // divideBinWidth(hpbpb_TrgObj80[i]);
    // divideBinWidth(hpbpb_TrgObj65[i]);
    // divideBinWidth(hpbpb_TrgObj55[i]);
    
    
    // hpbpb_NoPileup_TrgObjComb[i]->Add(hpbpb_NoPileup_TrgObj80[i]);
    // hpbpb_NoPileup_TrgObjComb[i]->Add(hpbpb_NoPileup_TrgObj65[i]);
    // hpbpb_NoPileup_TrgObjComb[i]->Add(hpbpb_NoPileup_TrgObj55[i]);
    
    // divideBinWidth(hpbpb_NoPileup_TrgObjComb[i]);
    // divideBinWidth(hpbpb_NoPileup_TrgObj80[i]);
    // divideBinWidth(hpbpb_NoPileup_TrgObj65[i]);
    // divideBinWidth(hpbpb_NoPileup_TrgObj55[i]);
    
    // hpbpb_944Scale_TrgObj80[i] = (TH1F*)hpbpb_TrgObj80[i]->Clone(Form("hpbpb_HLT80_944Scale_R%d_20_eta_20_cent%d", radius, i));
    // hpbpb_944Scale_TrgObj65[i] = (TH1F*)hpbpb_TrgObj65[i]->Clone(Form("hpbpb_HLT65_944Scale_R%d_20_eta_20_cent%d", radius, i));
    // hpbpb_944Scale_TrgObj55[i] = (TH1F*)hpbpb_TrgObj55[i]->Clone(Form("hpbpb_HLT55_944Scale_R%d_20_eta_20_cent%d", radius, i));

    // hpbpb_944Scale_TrgObj80[i]->Scale(1./ScaleFactor_944Scale[i]);
    // hpbpb_944Scale_TrgObj65[i]->Scale(1./ScaleFactor_944Scale[i]);
    // hpbpb_944Scale_TrgObj55[i]->Scale(1./ScaleFactor_944Scale[i]);
    // hpbpb_944Scale_TrgObjComb[i] = (TH1F*)hpbpb_944Scale_TrgObj80[i]->Clone(Form("hpbpb_HLTComb_944Scale_R%d_20_eta_20_cent%d",radius, i));
    // hpbpb_944Scale_TrgObjComb[i]->Add(hpbpb_944Scale_TrgObj65[i]);
    // hpbpb_944Scale_TrgObjComb[i]->Add(hpbpb_944Scale_TrgObj55[i]);
    
    // hpbpb_NeqScalePerCent_TrgObj80[i] = (TH1F*)hpbpb_TrgObj80[i]->Clone(Form("hpbpb_HLT80_NeqScalePerCent_R%d_20_eta_20_cent%d", radius, i));
    // hpbpb_NeqScalePerCent_TrgObj65[i] = (TH1F*)hpbpb_TrgObj65[i]->Clone(Form("hpbpb_HLT65_NeqScalePerCent_R%d_20_eta_20_cent%d", radius, i));
    // hpbpb_NeqScalePerCent_TrgObj55[i] = (TH1F*)hpbpb_TrgObj55[i]->Clone(Form("hpbpb_HLT55_NeqScalePerCent_R%d_20_eta_20_cent%d", radius, i));
    // hpbpb_NeqScalePerCent_TrgObj80[i]->Scale(1./ScaleFactor_80_NeqScalePerCent[i]);
    // hpbpb_NeqScalePerCent_TrgObj65[i]->Scale(1./ScaleFactor_65_NeqScalePerCent[i]);
    // hpbpb_NeqScalePerCent_TrgObj55[i]->Scale(1./ScaleFactor_55_NeqScalePerCent[i]);
    // hpbpb_NeqScalePerCent_TrgObjComb[i] = (TH1F*)hpbpb_NeqScalePerCent_TrgObj80[i]->Clone(Form("hpbpb_HLTComb_NeqScalePerCent_R%d_20_eta_20_cent%d",radius, i));
    // hpbpb_NeqScalePerCent_TrgObjComb[i]->Add(hpbpb_NeqScalePerCent_TrgObj65[i]);
    // hpbpb_NeqScalePerCent_TrgObjComb[i]->Add(hpbpb_NeqScalePerCent_TrgObj55[i]);

    
    // hpbpb_NeqScale_TrgObj80[i] = (TH1F*)hpbpb_TrgObj80[i]->Clone(Form("hpbpb_HLT80_NeqScale_R%d_20_eta_20_cent%d", radius, i));
    // hpbpb_NeqScale_TrgObj65[i] = (TH1F*)hpbpb_TrgObj65[i]->Clone(Form("hpbpb_HLT65_NeqScale_R%d_20_eta_20_cent%d", radius, i));
    // hpbpb_NeqScale_TrgObj55[i] = (TH1F*)hpbpb_TrgObj55[i]->Clone(Form("hpbpb_HLT55_NeqScale_R%d_20_eta_20_cent%d", radius, i));
    // hpbpb_NeqScale_TrgObj80[i]->Scale(1./ScaleFactor_80_NeqScale[i]);
    // hpbpb_NeqScale_TrgObj65[i]->Scale(1./ScaleFactor_65_NeqScale[i]);
    // hpbpb_NeqScale_TrgObj55[i]->Scale(1./ScaleFactor_55_NeqScale[i]);
    // hpbpb_NeqScale_TrgObjComb[i] = (TH1F*)hpbpb_NeqScale_TrgObj80[i]->Clone(Form("hpbpb_HLTComb_NeqScale_R%d_20_eta_20_cent%d",radius, i));
    // hpbpb_NeqScale_TrgObjComb[i]->Add(hpbpb_NeqScale_TrgObj65[i]);
    // hpbpb_NeqScale_TrgObjComb[i]->Add(hpbpb_NeqScale_TrgObj55[i]);

    
    // hpbpb_raw_TrgObj80[i]->Scale(1./ScaleFactor_80_NeqScale[i]);
    // hpbpb_raw_TrgObj65[i]->Scale(1./ScaleFactor_65_NeqScale[i]);
    // hpbpb_raw_TrgObj55[i]->Scale(1./ScaleFactor_55_NeqScale[i]);
    
    // hpbpb_raw_TrgObjComb[i]->Add(hpbpb_raw_TrgObj80[i]);
    // hpbpb_raw_TrgObjComb[i]->Add(hpbpb_raw_TrgObj65[i]);
    // hpbpb_raw_TrgObjComb[i]->Add(hpbpb_raw_TrgObj55[i]);

    // divideBinWidth(hpbpb_raw_TrgObjComb[i]);
    // divideBinWidth(hpbpb_raw_TrgObj80[i]);
    // divideBinWidth(hpbpb_raw_TrgObj65[i]);
    // divideBinWidth(hpbpb_raw_TrgObj55[i]);

    // hpbpb_anaBin_TrgObj80[i]->Scale(1./ScaleFactor_80_NeqScale[i]);
    // hpbpb_anaBin_TrgObj65[i]->Scale(1./ScaleFactor_65_NeqScale[i]);
    // hpbpb_anaBin_TrgObj55[i]->Scale(1./ScaleFactor_55_NeqScale[i]);

    // hpbpb_anaBin_TrgObjComb[i]->Add(hpbpb_anaBin_TrgObj80[i]);
    // hpbpb_anaBin_TrgObjComb[i]->Add(hpbpb_anaBin_TrgObj65[i]);
    // hpbpb_anaBin_TrgObjComb[i]->Add(hpbpb_anaBin_TrgObj55[i]);

    // divideBinWidth(hpbpb_anaBin_TrgObjComb[i]);
    // divideBinWidth(hpbpb_anaBin_TrgObj80[i]);
    // divideBinWidth(hpbpb_anaBin_TrgObj65[i]);
    // divideBinWidth(hpbpb_anaBin_TrgObj55[i]);

    // hpbpb_Smear_TrgObj80[i]->Scale(1./ScaleFactor_80_NeqScale[i]);
    // hpbpb_Smear_TrgObj65[i]->Scale(1./ScaleFactor_65_NeqScale[i]);
    // hpbpb_Smear_TrgObj55[i]->Scale(1./ScaleFactor_55_NeqScale[i]);

    // hpbpb_Smear_TrgObjComb[i]->Add(hpbpb_Smear_TrgObj80[i]);
    // hpbpb_Smear_TrgObjComb[i]->Add(hpbpb_Smear_TrgObj65[i]);
    // hpbpb_Smear_TrgObjComb[i]->Add(hpbpb_Smear_TrgObj55[i]);

    // divideBinWidth(hpbpb_Smear_TrgObjComb[i]);

    // hpbpb_JEC_TrgObj80[i]->Scale(1./ScaleFactor_80_NeqScale[i]);
    // hpbpb_JEC_TrgObj65[i]->Scale(1./ScaleFactor_65_NeqScale[i]);
    // hpbpb_JEC_TrgObj55[i]->Scale(1./ScaleFactor_55_NeqScale[i]);

    // hpbpb_JEC_TrgObjComb[i]->Add(hpbpb_JEC_TrgObj80[i]);
    // hpbpb_JEC_TrgObjComb[i]->Add(hpbpb_JEC_TrgObj65[i]);
    // hpbpb_JEC_TrgObjComb[i]->Add(hpbpb_JEC_TrgObj55[i]);

    // divideBinWidth(hpbpb_JEC_TrgObjComb[i]);

    // hpbpb_JEC_5pcent_TrgObj80[i]->Scale(1./ScaleFactor_80_NeqScale[i]);
    // hpbpb_JEC_5pcent_TrgObj65[i]->Scale(1./ScaleFactor_65_NeqScale[i]);
    // hpbpb_JEC_5pcent_TrgObj55[i]->Scale(1./ScaleFactor_55_NeqScale[i]);

    // hpbpb_JEC_5pcent_TrgObjComb[i]->Add(hpbpb_JEC_5pcent_TrgObj80[i]);
    // hpbpb_JEC_5pcent_TrgObjComb[i]->Add(hpbpb_JEC_5pcent_TrgObj65[i]);
    // hpbpb_JEC_5pcent_TrgObjComb[i]->Add(hpbpb_JEC_5pcent_TrgObj55[i]);

    // divideBinWidth(hpbpb_JEC_5pcent_TrgObjComb[i]);

    
  }
  */
  
  
  fout->Write();

  // myfile1.close();
  // myfile2.close();
  
  
  timer.Stop();
  cout<<"Macro finished: "<<endl;
  cout<<"CPU time (min)  = "<<(Float_t)timer.CpuTime()/60<<endl;
  cout<<"Real time (min) = "<<(Float_t)timer.RealTime()/60<<endl;
  
}//macro end
int main(int argc, char * argv[])
{
  if (argc!=3) {
    cerr << "Usage: " << argv[0] << " input_file output_file." << endl;
    return 1;
  }
  // variables in tree
  int run_id;
  int event_id;
  string * parent = 0;
  double t0;
  double t1;
  double energy;
  double maxDx;
  double maxDy;
  double maxDz;
  double maxDd;
  double primaryX;
  double primaryY;
  double primaryZ;

  // open the file for read
  TFile f(argv[1], "READ");
  TTree * tree = (TTree *) f.Get("simple_out");
  TBranch * b_parent;
  // mapping
  tree->SetMakeClass(1);
  tree->SetBranchAddress("runId", &run_id);
  tree->SetBranchAddress("eventId", &event_id);
  tree->SetBranchAddress("parent", &parent, &b_parent);
  tree->SetBranchAddress("t0", &t0);
  tree->SetBranchAddress("t1", &t1);
  tree->SetBranchAddress("energy", &energy);
  tree->SetBranchAddress("maxDx", &maxDx);
  tree->SetBranchAddress("maxDy", &maxDy);
  tree->SetBranchAddress("maxDz", &maxDz);
  tree->SetBranchAddress("maxDd", &maxDd);
  tree->SetBranchAddress("primaryX", &primaryX);
  tree->SetBranchAddress("primaryY", &primaryY);
  tree->SetBranchAddress("primaryZ", &primaryZ);

  // ROI
  double fwhm_0_5 = 0.005 * Q_value;
  double fwhm_1 = 0.01 * Q_value;
  double fwhm_3 = 0.03 * Q_value;

  double sigma_0_5 = getSigma(fwhm_0_5);
  double sigma_1 = getSigma(fwhm_1);
  double sigma_3 = getSigma(fwhm_3);

  double l_edge_0_5 = Q_value - 2 * sigma_0_5;
  double u_edge_0_5 = Q_value + 2 * sigma_0_5;
  double l_edge_1 = Q_value - 2 * sigma_1;
  double u_edge_1 = Q_value + 2 * sigma_1;
  double l_edge_3 = Q_value - 2 * sigma_3;
  double u_edge_3 = Q_value + 2 * sigma_3;
  cout << "0.5% FHWM " << fwhm_0_5 << " - sigma " << sigma_0_5 << endl;
  cout << "1.0% FHWM " << fwhm_1 << " - sigma " << sigma_1 << endl;
  cout << "3.0% FHWM " << fwhm_3 << " - sigma " << sigma_3 << endl;

  cout << "0.5% FHWM - (" << l_edge_0_5 << ", " << u_edge_0_5 << ")." << endl;
  cout << "1.0% FHWM - (" << l_edge_1 << ", " << u_edge_1 << ")." << endl;
  cout << "3.0% FHWM - (" << l_edge_3 << ", " << u_edge_3 << ")." << endl;

  // output file, only with the smeared energy.
  TFile fo(argv[2], "RECREATE");
  TTree * out_tree = new TTree ("smear_e", "smeared energy");
  // output variables
  double e_smear_0_5, e_smear_1, e_smear_3;
  string pparent;
  out_tree->Branch("runId", &run_id, "runId/I");
  out_tree->Branch("eventId", &event_id, "eventId/I");
  out_tree->Branch("parent", &pparent);
  out_tree->Branch("energy", &energy, "energy/D");
  out_tree->Branch("e_smear_0_5", &e_smear_0_5, "e_smear_0_5/D");
  out_tree->Branch("e_smear_1", &e_smear_1, "e_smear_1/D");
  out_tree->Branch("e_smear_3", &e_smear_3, "e_smear_3/D");
  out_tree->Branch("maxDx", &maxDx, "maxDx/D");
  out_tree->Branch("maxDy", &maxDy, "maxDy/D");
  out_tree->Branch("maxDz", &maxDz, "maxDz/D");
  out_tree->Branch("maxDd", &maxDd, "maxDd/D");
  out_tree->Branch("primaryX", &primaryX, "primaryX/D");
  out_tree->Branch("primaryY", &primaryY, "primaryY/D");
  out_tree->Branch("primaryZ", &primaryZ, "primaryZ/D");

  long nEntries = tree->GetEntries();
  cout << nEntries << endl;
  // loop over entries and smear the energy

  tr.SetSeed(0);
  // TCanvas c1("c1", "c1", 800, 600);
  // TH1D * th_esm = new TH1D("th_esm", "smeared energy", 500, 2200, 2700);
  // for (int i=0; i<1000; ++i) {
  //   double esm = smearEnergy(Q_value, sigma_3);
  //   th_esm->Fill(esm);
  // }
  // th_esm->Draw();
  // c1.Print("esm.png");
  vector<double> es;		// selected energy
  int n_0_5(0), ns_0_5(0);
  int n_1(0), ns_1(0);
  int n_3(0), ns_3(0);
  double dn_0_5(0), dn_1(1), dn_3(2); // variable for n calculated from integration

  TTree * count_tree = new TTree ("count_tree", "tree of counts");
  count_tree->Branch("ns_0_5", &ns_0_5, "ns_0_5/I");
  count_tree->Branch("ns_1", &ns_1, "ns_1/I");
  count_tree->Branch("ns_3", &ns_3, "ns_3/I");
  double times = 6.0;
  TF1 * f1 = new TF1("gaus_smear", smearFunc, 2200, 2700, 2);
  for (long i=0; i<nEntries; ++i) {
    tree->GetEntry(i);
    e_smear_0_5 = 0;
    e_smear_1 = 0;
    e_smear_3 = 0;
    // calculate the integration of n
    if (energy > 2200 && energy < 2700) {
      f1->SetParameter(0, sigma_0_5);
      f1->SetParameter(1, energy);
      dn_0_5 += f1->Integral(Q_value-2*sigma_0_5, Q_value+2*sigma_0_5);
      f1->SetParameter(0, sigma_1);
      dn_1 += f1->Integral(Q_value-2*sigma_1, Q_value+2*sigma_1);
      f1->SetParameter(0, sigma_3);
      dn_3 += f1->Integral(Q_value-2*sigma_3, Q_value+2*sigma_3);
    }
    // end the calculation of integration
    if (energy>Q_value-times*sigma_0_5 && energy<Q_value+times*sigma_0_5) {
      e_smear_0_5 = smearEnergy(energy, sigma_0_5);
      if (energy>Q_value-2*sigma_0_5 && energy<Q_value+2*sigma_0_5) {
	n_0_5++;
      }
      if (e_smear_0_5>Q_value-2*sigma_0_5&&e_smear_0_5<Q_value+2*sigma_0_5) {
	ns_0_5++;
      }
    }
    if (energy>Q_value-times*sigma_1 && energy<Q_value+times*sigma_1) {
      e_smear_1 = smearEnergy(energy, sigma_1);
      if (energy>Q_value-2*sigma_1 && energy<Q_value+2*sigma_1) {
	n_1++;
      }
      if (e_smear_1>Q_value-2*sigma_1&&e_smear_1<Q_value+2*sigma_1) {
	ns_1++;
      }
    }
    if (energy>Q_value-times*sigma_3 && energy<Q_value+times*sigma_3) {
      e_smear_3 = smearEnergy(energy, sigma_3);
      if (energy>Q_value-2*sigma_3 && energy<Q_value+2*sigma_3) {
	n_3++;
      }
      if (e_smear_3>Q_value-2*sigma_3&&e_smear_3<Q_value+2*sigma_3) {
	ns_3++;
      }
      es.push_back(energy);
      pparent = * parent;
      //      cout << event_id << " " << * parent << endl;
      out_tree->Fill();
    }
  }
  // print out the values
  cout << "0.5%: " << n_0_5 << " (original), " << ns_0_5 << " (smeared), " << dn_0_5 << "(smeared with integration)." << endl;
  cout << "1.0%: " << n_1 << " (original), " << ns_1 << " (smeared), " << dn_1 << "(smeared with integration)." << endl;
  cout << "3.0%: " << n_3 << " (original), " << ns_3 << " (smeared), " << dn_3 << "(smeared with integration)." << endl;
  out_tree->Write();
  // further simulation
  for (int i=0; i<500; ++i) {
    ns_0_5 = 0;
    ns_1 = 0;
    ns_3 = 0;
    for (size_t j=0; j<es.size(); ++j) {
      double e = es[j];
      if (e>Q_value-times*sigma_0_5&&e<Q_value+times*sigma_0_5) {
	double ex = smearEnergy(e, sigma_0_5);
	if (ex>Q_value-2*sigma_0_5&&e<Q_value+2*sigma_0_5) {
	  ns_0_5++;
	}
      }
      if (e>Q_value-times*sigma_1&&e<Q_value+times*sigma_1) {
	double ex = smearEnergy(e, sigma_1);
	if (ex>Q_value-2*sigma_1&&e<Q_value+2*sigma_1) {
	  ns_1++;
	}
      }
      if (e>Q_value-times*sigma_3&&e<Q_value+times*sigma_3) {
	double ex = smearEnergy(e, sigma_3);
	if (ex>Q_value-2*sigma_3&&e<Q_value+2*sigma_3) {
	  ns_3++;
	}
      }
    }
    count_tree->Fill();
  }
  count_tree->Write();
  fo.Close();
  f.Close();
}
Beispiel #10
0
void kdTreeBinning() {

   // -----------------------------------------------------------------------------------------------
   //  C r e a t e  r a n d o m  s a m p l e  w i t h  r e g u l a r  b i n n i n g  p l o t t i n g
   // -----------------------------------------------------------------------------------------------

   const UInt_t DATASZ = 10000;
   const UInt_t DATADIM = 2;
   const UInt_t NBINS = 50;

   Double_t smp[DATASZ * DATADIM];

   double mu[2] = {0,2};
   double sig[2] = {2,3};
   TRandom3 r;
   r.SetSeed(1);
   for (UInt_t i = 0; i < DATADIM; ++i)
      for (UInt_t j = 0; j < DATASZ; ++j)
         smp[DATASZ * i + j] = r.Gaus(mu[i], sig[i]);

   UInt_t h1bins = (UInt_t) sqrt(NBINS);

   TH2D* h1 = new TH2D("h1BinTest", "Regular binning", h1bins, -5., 5., h1bins, -5., 5.);
   for (UInt_t j = 0; j < DATASZ; ++j)
      h1->Fill(smp[j], smp[DATASZ + j]);


   // ---------------------------------------------------------------------------------------------
   // C r e a t e  K D T r e e B i n n i n g  o b j e c t  w i t h  T H 2 P o l y  p l o t t i n g
   // ---------------------------------------------------------------------------------------------

   TKDTreeBinning* kdBins = new TKDTreeBinning(DATASZ, DATADIM, smp, NBINS);

   UInt_t nbins = kdBins->GetNBins();
   UInt_t dim   = kdBins->GetDim();

   const Double_t* binsMinEdges = kdBins->GetBinsMinEdges();
   const Double_t* binsMaxEdges = kdBins->GetBinsMaxEdges();

   TH2Poly* h2pol = new TH2Poly("h2PolyBinTest", "KDTree binning", kdBins->GetDataMin(0), kdBins->GetDataMax(0), kdBins->GetDataMin(1), kdBins->GetDataMax(1));

   for (UInt_t i = 0; i < nbins; ++i) {
      UInt_t edgeDim = i * dim;
      h2pol->AddBin(binsMinEdges[edgeDim], binsMinEdges[edgeDim + 1], binsMaxEdges[edgeDim], binsMaxEdges[edgeDim + 1]);
   }

   for (UInt_t i = 1; i <= kdBins->GetNBins(); ++i)
      h2pol->SetBinContent(i, kdBins->GetBinDensity(i - 1));

   std::cout << "Bin with minimum density: " << kdBins->GetBinMinDensity() << std::endl;
   std::cout << "Bin with maximum density: " << kdBins->GetBinMaxDensity() << std::endl;

   TCanvas* c1 = new TCanvas("glc1", "TH2Poly from a kdTree",0,0,600,800);
   c1->Divide(1,3);
   c1->cd(1);
   h1->Draw("lego");

   c1->cd(2);
   h2pol->Draw("COLZ L");
   c1->Update();


   /* Draw an equivalent plot showing the data points */
   /*-------------------------------------------------*/

   std::vector<Double_t> z = std::vector<Double_t>(DATASZ, 0.);
   for (UInt_t i = 0; i < DATASZ; ++i)
      z[i] = (Double_t) h2pol->GetBinContent(h2pol->FindBin(smp[i], smp[DATASZ + i]));

   TGraph2D *g = new TGraph2D(DATASZ, smp, &smp[DATASZ], &z[0]);
   gStyle->SetPalette(1);
   g->SetMarkerStyle(20);

   c1->cd(3);
   g->Draw("pcol");
   c1->Update();

   // ---------------------------------------------------------
   // make a new TH2Poly where bins are ordered by the density
   // ---------------------------------------------------------

   TH2Poly* h2polrebin = new TH2Poly("h2PolyBinTest", "KDTree binning", kdBins->GetDataMin(0), kdBins->GetDataMax(0), kdBins->GetDataMin(1), kdBins->GetDataMax(1));
   h2polrebin->SetFloat();

   /*---------------------------------*/
   /* Sort the bins by their density  */
   /*---------------------------------*/

   kdBins->SortBinsByDensity();

   for (UInt_t i = 0; i < kdBins->GetNBins(); ++i) {
      const Double_t* binMinEdges = kdBins->GetBinMinEdges(i);
      const Double_t* binMaxEdges = kdBins->GetBinMaxEdges(i);
      h2polrebin->AddBin(binMinEdges[0], binMinEdges[1], binMaxEdges[0], binMaxEdges[1]);
   }

   for (UInt_t i = 1; i <= kdBins->GetNBins(); ++i){
      h2polrebin->SetBinContent(i, kdBins->GetBinDensity(i - 1));}

   std::cout << "Bin with minimum density: " << kdBins->GetBinMinDensity() << std::endl;
   std::cout << "Bin with maximum density: " << kdBins->GetBinMaxDensity() << std::endl;

   // now make a vector with bin number vs position
   for (UInt_t i = 0; i < DATASZ; ++i)
     z[i] = (Double_t) h2polrebin->FindBin(smp[i], smp[DATASZ + i]);

   TGraph2D *g2 = new TGraph2D(DATASZ, smp, &smp[DATASZ], &z[0]);
   g2->SetMarkerStyle(20);


   // plot new TH2Poly (ordered one) and TGraph2D
   // The new TH2Poly has to be same as old one and the TGraph2D should be similar to
   // the previous one. It is now made using as z value the bin number

   TCanvas* c4 = new TCanvas("glc4", "TH2Poly from a kdTree (Ordered)",50,50,800,800);

   c4->Divide(2,2);
   c4->cd(1);
   h2polrebin->Draw("COLZ L");  // draw as scatter plot

   c4->cd(2);
   g2->Draw("pcol");

   c4->Update();

   // make also the 1D binned histograms

   TKDTreeBinning* kdX = new TKDTreeBinning(DATASZ, 1, &smp[0], 20);
   TKDTreeBinning* kdY = new TKDTreeBinning(DATASZ, 1, &smp[DATASZ], 40);


  kdX->SortOneDimBinEdges();
  kdY->SortOneDimBinEdges();

  TH1* hX=new TH1F("hX", "X projection", kdX->GetNBins(), kdX->GetOneDimBinEdges());
  for(int i=0; i<kdX->GetNBins(); ++i){
    hX->SetBinContent(i+1, kdX->GetBinDensity(i));
  }

  TH1* hY=new TH1F("hY", "Y Projection", kdY->GetNBins(), kdY->GetOneDimBinEdges());
  for(int i=0; i<kdY->GetNBins(); ++i){
    hY->SetBinContent(i+1, kdY->GetBinDensity(i));
  }

  c4->cd(3);
  hX->Draw();
  c4->cd(4);
  hY->Draw();
}
void SimRC_eventisuareatotale(int seed)
{
	double x[N_events], y[N_events], z[N_events], zfin[N_events], x1final[N_events], y1final[N_events], xfin[N_events], yfin[N_events], phi[N_events], theta[N_events], x1[N_events], y1[N_events], z1[N_events], phi1[N_events], theta1[N_events]; // all the necessary array
	double uniform, u;
	TRandom3 *rand = new TRandom();
	rand->SetSeed(seed); // to set the seed
	int counterge = 0;		//to count good events
	int k = 0;		//dynamic counter 
	for (int i = 0; i < N_events; i++) {
		//rand->SetSeed(0);		//forget about this, it's wrong; I kept it only to remember not to use it
		x[i] = rand->Uniform(-square,L+square);		//generates N_events values along X
		y[i] = rand->Uniform(-square, D+square);
		phi[i] = rand->Uniform(0, 2*PI);
		uniform = 0;
		u = 2;
		while (M*u > M*cos(uniform)*cos(uniform)*sin(uniform)) {		//rejection condition
			u = rand->Uniform(0, 1);
			uniform = rand->Uniform(0, PI / 2);
		};
		theta[i] = uniform;
		if (x[i] >= 0 && x[i] <= L && y[i] >= 0 && y[i] <= D) {
			z[i] = 0;
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			x1final[counterge] = x[i];
			y1final[counterge] = y[i];
			counterge++; 
			k++;
			//cout << k << endl;
		}
		else if (x[i] < 0 && phi[i] >PI / 2 && phi[i] < PI && (y[i] - x[i] * tan(phi[i])) > 0 && (y[i] - x[i] * tan(phi[i])) < D && theta[i] > atan(x[i] / (cos(phi[i]) * sp))) {
			z[i] = -x[i] / (cos(phi[i]) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			x1final[counterge] = 0;
			y1final[counterge] = (y[i] - x[i] * tan(phi[i]));
			counterge++;
			k++;
			//cout << k << endl;			
		}
		else if (x[i] < 0 && phi[i] >PI / 2 && phi[i] < PI && (y[i] + x[i] * tan(PI-phi[i])) > D && x[i]-(D-y[i])/ tan(PI-phi[i]) > 0 && x[i] - (D - y[i]) / tan(PI-phi[i]) <L && theta[i] > atan((y[i]-D) / (sin(PI-phi[i]) * sp))) {
			z[i] = -(y[i] - D) / (sin(PI - phi[i]) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			y1final[counterge] = D;
			x1final[counterge] = x[i] - (D - y[i]) / tan(PI - phi[i]);
			counterge++;
			k++;
			//cout << k << endl;
		}
		else if (x[i] < 0 && phi[i] >PI && phi[i] < 3*PI/2 && (y[i] - x[i] * tan(phi[i])) > 0 && (y[i] - x[i] * tan(phi[i])) < D && theta[i] > atan(-x[i] / (cos(PI-phi[i]) * sp))) {
			z[i] = -x[i] / (cos(phi[i]) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			x1final[counterge] = 0;
			y1final[counterge] = (y[i] - x[i] * tan(phi[i]));
			counterge++;
			k++;
			//cout << k << endl;
		}
		else if (x[i] < 0 && phi[i] >PI && phi[i] < 3 * PI / 2 && x[i] - y[i] / tan(phi[i]) > 0 && x[i] - y[i] / tan(phi[i]) < L&& (y[i] - x[i] * tan(phi[i])) < 0 && theta[i] > atan(-y[i] / (sin(phi[i]-PI) * sp))) {
			z[i] = y[i] / (sin(phi[i] - PI) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			y1final[counterge] = 0;
			x1final[counterge] = x[i] - y[i] / tan(phi[i]);
			counterge++;
			k++;
			//cout << k << endl;
		}
		else if (x[i] > L && phi[i] > 0 && phi[i] < PI / 2 && (y[i] - (x[i] - L) * tan(phi[i])) > 0 && (y[i] - (x[i] - L) * tan(phi[i])) < D && theta[i] > atan((x[i] - L) / (cos(phi[i]) * sp))) {
			z[i] = -(x[i] - L) / (cos(phi[i]) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			x1final[counterge] = L;
			y1final[counterge] = y[i] - (x[i] - L) * tan(phi[i]);
			counterge++;
			k++;
			//cout << k << endl;
		}
		else if (x[i] > L && phi[i] > 0 && phi[i] < PI / 2 && (y[i] - (x[i] - L) * tan(phi[i])) > D && x[i] - (y[i] - D) / tan(phi[i]) > 0 && x[i] - (y[i] - D) / tan(phi[i]) < L && theta[i] > atan((y[i]-D) / (sin(phi[i]) * sp))) {
			z[i] = -(y[i] - D) / (sin(phi[i]) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			y1final[counterge] = D;
			x1final[counterge] = x[i] - (y[i] - D) / tan(phi[i]);
			counterge++;
			k++;
			//cout << k << endl;
		}
		else if (x[i] > L && phi[i] > 3 * PI / 2 && (y[i] + (x[i]-L) / tan(phi[i] - 3 * PI / 2)) > 0  && (y[i] + (x[i]-L) / tan(phi[i] - 3 * PI / 2)) < D && theta[i] > atan((x[i]-L) / (sin(phi[i] - 3 * PI / 2) * sp))) {
			z[i]  = -(x[i] - L) / (sin(phi[i] - 3 * PI / 2) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			x1final[counterge] = L;
			y1final[counterge] = y[i] + (x[i] - L) / tan(phi[i] - 3 * PI / 2);
			counterge++;
			k++;
			//cout << k << endl;
		}
		else if (x[i] > L && phi[i] > 3 * PI / 2 && x[i] + y[i] * tan(phi[i] - 3 * PI / 2) > 0 && x[i] + y[i] * tan(phi[i] - 3 * PI / 2) < L && (y[i] + (x[i] - L) / tan(phi[i] - 3 * PI / 2)) < 0 && theta[i] > atan(-y[i] / (sin(2*PI-phi[i]) * sp))) {
			z[i] = y[i] / (sin(2 * PI - phi[i]) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			y1final[counterge] = 0;
			x1final[counterge] = x[i] + y[i] * tan(phi[i] - 3 * PI / 2);
			counterge++;
			k++;
			//cout << k << endl;
		}
		else if (y[i] < 0 && phi[i] > PI && phi[i] < 3 * PI/2 && (x[i] - y[i] / tan(phi[i]-PI)) > 0 && (x[i] - y[i] / tan(phi[i]-PI)) < L && theta[i] > atan(-y[i] / (sin(phi[i]-PI) * sp))) {
			z[i] = y[i] / (sin(phi[i]-PI) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			x1final[counterge] = x [i] - y[i] / tan(phi[i] - PI);
			y1final[counterge] = 0;
			counterge++;
			k++;
			//cout << k << endl;
			}
		//else if (y[i] < 0 && phi[i] > PI && phi[i] < 3 * PI / 2 && (x[i] - y[i] / tan(phi[i] - PI)) > 0 - D / (tan(phi[i] - PI)) && (x[i] - y[i] / tan(phi[i] - PI)) < 0 && theta[i] > atan(-x[i] / (cos(phi[i]-PI) * sp))) {
		//counterge++;
		//z[i] = -x[i] / (cos(phi[i] - PI) * tan(theta[i]));
		//xfinal[i] = 0;
		//yfinal[i] = -x[i]*tan(phi[i]-PI)+y[i];//correggere
		//k++;
		//cout << k << endl;
		//i++;
		//}
		else if (y[i] < 0 && phi[i] > 3 * PI / 2 && phi[i] < 2 * PI && (x[i] + y[i] / tan(2 * PI - phi[i])) > 0 && (x[i] + y[i] / tan(2*PI-phi[i])) < L && theta[i] > atan(-y[i] / (sin(2*PI-phi[i]) * sp))) {
			z[i] = y[i] / (sin(2*PI-phi[i]) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			x1final[counterge] = x[i] + y[i] / tan(2 * PI - phi[i]);
			y1final[counterge] = 0;
			counterge++;
			k++;
			//cout << k << endl;
		}
		//else if (y[i] < 0 && phi[i] > 3 * PI / 2 && (x[i] + y[i] / tan(2 * PI - phi[i])) > L && (x[i] + y[i] / tan(phi[i])) < L + D / (tan(2 * PI - phi[i])) && theta[i] > atan((x[i] - L) / (cos(2 * PI - phi[i]) * sp))) {
		//counterge++;
		//z[i] = (x[i] - L) / (cos(2 * PI - phi[i]) * tan(theta[i]));
		//xfinal[i] = L;		
		//yfinal[i] = (x[i] - L) * tan(2 * PI - phi[i]) + y[i];//correggere
		//k++;
		//cout << k << endl;
		//i++;
		//}
		else if (y[i] > D && phi[i] > 0 && phi[i]  < PI / 2 && (x[i] - (y[i] - D) / tan(phi[i])) > 0 && (x[i] - (y[i] - D) / tan(phi[i])) < L && theta[i] > atan((y[i] - D) / (sin(phi[i]) * sp))) {
			z[i] = -(y[i] - D) / (sin(phi[i]) * tan(theta[i]));
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			x1final[counterge] = x[i] - (y[i] - D) / tan(phi[i]);
			y1final[counterge] = D;
			counterge++;
			k++;
			//cout << k << endl;
		}
		//else if (y[i] > D && phi[i] > 0 && phi[i]  < PI / 2 && (x[i] - (y[i] - D) / tan(phi[i])) > L && (x[i] - (y[i] - D) / tan(phi[i])) < L + D / (tan(phi[i])) && theta[i] > atan((x[i]-L) / (cos(phi[i]) * sp))) {
		//counterge++;
		//z[i] = (x[i] - L) / (cos(phi[i]) * tan(theta[i]));
		//xfinal[i] = L;		//correggere
		//yfinal[i] = y[i] - (x[i]-L)/tan(phi[i]);
		//k++;
		//cout << k << endl;
		//i++;
		//}
		else if (y[i] > D && phi[i] > PI / 2 && phi[i] < PI && (x[i] + (y[i] - D) / tan(PI - phi[i])) > 0 && (x[i] + (y[i] - D) / tan(PI - phi[i])) < L  && theta[i] > atan ( (y[i] - D) / (sin(PI-phi[i]) * sp))) {
			z[i] = -(y[i] - D) / (sin(PI-phi[i]) * tan(theta[i])); 
			x1[counterge] = x[i];
			y1[counterge] = y[i];
			z1[counterge] = z[i];
			theta1[counterge] = theta[i];
			phi1[counterge] = phi[i];
			x1final[counterge] = x[i] + (y[i] - D) / tan(PI - phi[i]);
			y1final[counterge] = D;
			counterge++;
			k++;
			//cout << k << endl;
		}
		//else if (y[i] > D && phi[i] > PI / 2 && phi[i] < PI && (x[i] + (y[i] - D) / tan(PI - phi[i])) > 0 - D / (tan(PI - phi[i])) && (x[i] + (y[i] - D) / tan(PI - phi[i])) < 0  && theta[i] > atan(-x[i] / (cos(PI-phi[i]) * sp))) {
		//counterge++;
		//z[i] = -x[i] / (cos(PI - phi[i]) * tan(theta[i]));
		//xfinal[i] = 0;
		//yfinal[i] = y[i]+x[i]/tan(PI-phi[i]);//correggere
		//k++;
		//cout << k << endl;
		//i++;
		//}
		else continue;		//calculations need to be checked

	}
	
	double counter = 0;		// counter for coincidence events
	double counterz = 0;
	double counterzcoin = 0;
	for (int i = 0; i < counterge; i++) {
		xfin[i] = x1[i] - (H + z1[i]) * tan(theta1[i]) * cos(phi1[i]);		// these should be correct
		yfin[i] = y1[i] - (H + z1[i]) * tan(theta1[i]) * sin(phi1[i]);
		if (0 <= xfin[i] && xfin[i] <= L && yfin[i] >= 0 && yfin[i] <= D) counter++;
		if (z1[i] != 0) counterz++;		//counts the event fallen on the sp thick side
		if (0 <= xfin[i] && xfin[i] <= L && yfin[i] >= 0 && yfin[i] <= D && z[i] != 0) counterzcoin++;
	}
	
	cout << "Il numero di eventi e': " << counterge << endl << "Il numero di eventi in coincidenza e': " << counter << endl << "La percentuale in coincidenza e': " << counter/counterge * 100  << "%" << endl << "Il numero di eventi totali controllato e': " << N_events << endl << "Il numero totale buono di eventi e': " << counterge << endl << "Il numero totale di eventi passato lateralmente e': " << counterz << endl << "Il numero totale di eventi passati lateralmente e in coincidenza e' : " << counterzcoin << endl;		// this ends the program
	
	/*const int n1 = 2*counterge;		//I write the files all in one file to plot in the end
	double xfinal1[n1];
	double yfinal1[n1];
	double zfinal1[n1];
	for (int i = 0; i < counterge; i++) {
		xfinal1[i] = x1final[i];
		yfinal1[i] = y1final[i];
		zfinal1[i] = z1[i];
		xfinal1[i + counterge] = xfin[i];
		yfinal1[i + counterge] = yfin[i];
		zfinal1[i + counterge] = -H;
	}
		
	TCanvas *c1 = new TCanvas("c1", "", 200, 10, 600, 400);		//finally the plot
	c1->SetFillColor(10);
	c1->SetGrid();
	TGraph2D *grafico = new TGraph2D(n1, xfinal1, yfinal1, zfinal1);
	grafico->SetTitle("Slabs coincidence 3D, H = 0.08 m, square = 10 m");
	grafico->SetMarkerColor(2);
	grafico->GetXaxis()->SetTitle("X-Axis [m]");
	grafico->GetYaxis()->SetTitle("Y-Axis [m]");
	grafico->GetZaxis()->SetTitle("Z-Axis [m]");
	grafico->Draw("PCOL");*/
	return;
} 
Beispiel #12
0
void sqrtByFill(){


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

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

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

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

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

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

	gAsymVsFill->Write();

}
Beispiel #13
0
int main(int argc, char * argv[]) {
    
    TStopwatch watch;
    gRandom = new TRandom3(0); // set random seed
    gROOT->ProcessLine(".L loader.c+"); // Initialize struct objects (see dictionaries)
    
    // Gas setup
    TString gasmixt[6] = { "C5H12", "CF4", "", "60", "40", "" };
    TString output = gasmixt[0] + "-" + gasmixt[1] + "-" + gasmixt[2] + "-" + gasmixt[3] + "-" + gasmixt[4] + "-" + gasmixt[5];
    
    std::string workingdir = "includes/";
    workingdir.append("GEM5"); // Name of the working directory which contains the GEM files
    workingdir.append("/");

    std::string particleType = "mu";
    Double_t particleEnergy = 100.e9;
    bool debug = true;
    Int_t it = 100;

    // Load GEM dimensions
    GEMconfig g;
    loadGEMconfig(workingdir, g);
    
    // Load the field map
    ComponentAnsys123* fm = new ComponentAnsys123();
    std::string efile = workingdir + "ELIST.lis";
    std::string nfile = workingdir + "NLIST.lis";
    std::string mfile = workingdir + "MPLIST.lis";
    std::string sfile = workingdir + "PRNSOL.lis";
    std::string wfile = workingdir + "WSOL.lis";
    std::string dfile = workingdir + "WSOLD.lis";
    if(!fm->Initialise(efile, nfile, mfile, sfile, "mm")) {
        std::cout << "Error while loading the ANSYS field map files." << std::endl;
    }
    fm->EnableMirrorPeriodicityX();
    fm->EnableMirrorPeriodicityY();
    if(debug) {
        fm->PrintRange();
    }
    fm->SetWeightingField(wfile, "readout");
    fm->SetWeightingField(dfile, "ions");
	
    // Gas setup
    MediumMagboltz* gas = new MediumMagboltz();
    gas->SetComposition((std::string)gasmixt[0], atof(gasmixt[3]), (std::string)gasmixt[1], atof(gasmixt[4]), (std::string)gasmixt[2], atof(gasmixt[5]));
    gas->SetTemperature(293.15);
    gas->SetPressure(760.0);	
    //gas->SetMaxElectronEnergy(200.);
    gas->EnableDebugging();
    gas->Initialise();
    gas->DisableDebugging();
    //const double rPenning = 0.57;
    //const double lambdaPenning = 0.;
    //gas->EnablePenningTransfer(rPenning, lambdaPenning, "ar");
    gas->LoadIonMobility(GARFIELD + "Data/IonMobility_Ar+_Ar.txt");
    //gas->LoadIonMobility(GARFIELD + "Data/IonMobility_CO2+_CO2");
     
    //Associate the gas with the corresponding field map material.
    const int nMaterials = fm->GetNumberOfMaterials();
    for(int i=0; i<nMaterials; ++i) {
 	
        const double eps = fm->GetPermittivity(i);
        if(fabs(eps - 1.) < 1.e-3) fm->SetMedium(i, gas);
    }
    if(debug) {
        fm->PrintMaterials();
    }
    
    // Sensor setup
    Sensor* sensor = new Sensor();
    sensor->AddComponent(fm);
    sensor->SetArea(-5.*(g.pitch), -5.*(g.pitch), 0.0, 5.*(g.pitch), 5.*(g.pitch), g.totalT);
    
    // Setup HEED
    TrackHeed* heed = new TrackHeed();
    heed->SetSensor(sensor);
    //heed->DisableDeltaElectronTransport();
    heed->SetParticle(particleType);
    heed->SetMomentum(particleEnergy);
    if(debug) {
        heed->EnableDebugging();
    }
	
    // Setup electron transport
    AvalancheMicroscopic* aval = new AvalancheMicroscopic();
    aval->SetSensor(sensor);
    //aval->EnableAvalancheSizeLimit(1000);
    
    sensor->AddElectrode(fm, "readout");
    sensor->AddElectrode(fm, "ions");
    const double tMin = 0.;
    const double tMax = 75.;
    const double tStep = 0.2;
    const int nTimeBins = int((tMax - tMin)/tStep);
    sensor->SetTimeWindow(0., tStep, nTimeBins);
    aval->EnableSignalCalculation();
    
    ViewSignal* signalView = new ViewSignal();
    signalView->SetSensor(sensor);
    TH1D* h; // tmp storage of timing histogram

    // Setup ion transport
    AvalancheMC* iondrift = new AvalancheMC();
    iondrift->SetSensor(sensor);
    iondrift->EnableSignalCalculation();
    iondrift->SetDistanceSteps(2e-4);

    // Calculate avalanche
    int ne, ni, np, status, nc;
    double ec, extra;
    double x0, y0, z0, t0, e0, x1, y1, z1, t1, e1, x2, y2, z2, t2, e2, x3, y3, z3, t3, e3;
    double vx0, vy0, vz0, vx1, vy1, vz1;
	
    TRandom3 r;
    r.SetSeed(0);

    TString savefile = workingdir + "output/" + output + ".root";
    TFile f(savefile, "recreate");
    TDirectory *dir = f.mkdir("signals");
    dir->cd();
    
    // Prepare tree for charged particle and clusters
    particle p;
    TTree *pTree = new TTree("pTree", "Charged particle");
    pTree->Branch("x0", &p.x0);
    pTree->Branch("y0", &p.y0);
    pTree->Branch("z0", &p.z0);
    pTree->Branch("vx0", &p.vx0);
    pTree->Branch("vy0", &p.vy0);
    pTree->Branch("vz0", &p.vz0);
    pTree->Branch("t0", &p.t0);
    pTree->Branch("e0", &p.e0);
    pTree->Branch("type", "TString", &p.type);
    pTree->Branch("noClusters", &p.noClusters);
    pTree->Branch("stoppingpower", &p.stoppingPower);
    pTree->Branch("lambda", &p.lambda);
    pTree->Branch("clusters", "std::vector<cluster>", &p.clusters);
  
    // Prepare tree for electrons
    avalancheE aE;
    TTree *ETree = new TTree("eTree", "Avalanche electrons");
    ETree->Branch("x0", &aE.x0);
    ETree->Branch("y0", &aE.y0);
    ETree->Branch("z0", &aE.z0);
    ETree->Branch("vx0", &aE.vx0);
    ETree->Branch("vy0", &aE.vy0);
    ETree->Branch("vz0", &aE.vz0);
    ETree->Branch("t0", &aE.t0);
    ETree->Branch("e0", &aE.e0);
    ETree->Branch("ne", &aE.ne);
    ETree->Branch("x1", &aE.x1);
    ETree->Branch("y1", &aE.y1);
    ETree->Branch("z1", &aE.z1);
    ETree->Branch("t1", &aE.t1);
    ETree->Branch("e1", &aE.e1);
    ETree->Branch("x2", &aE.x2);
    ETree->Branch("y2", &aE.y2);
    ETree->Branch("z2", &aE.z2);
    ETree->Branch("t2", &aE.t2);
    ETree->Branch("e2", &aE.e2);
    ETree->Branch("status", &aE.status);
    
    // Prepare tree for ions
    avalancheI aI;
    TTree *ITree = new TTree("iTree", "Avalanche ions");
    ITree->Branch("x0", &aI.x0);
    ITree->Branch("y0", &aI.y0);
    ITree->Branch("z0", &aI.z0);
    ITree->Branch("t0", &aI.t0);
    ITree->Branch("ni", &aI.ni);
    ITree->Branch("x1", &aI.x1);
    ITree->Branch("y1", &aI.y1);
    ITree->Branch("z1", &aI.z1);
    ITree->Branch("t1", &aI.t1);
    ITree->Branch("x2", &aI.x2);
    ITree->Branch("y2", &aI.y2);
    ITree->Branch("z2", &aI.z2);
    ITree->Branch("t2", &aI.t2);
    ITree->Branch("status", &aI.status);
    
    // Start iteration
    std::cout << "---------------------------------------------------------------" << std::endl;
    for(int i=0; i<it; i++) {
        
        if(debug) {
            std::cout << "Progress: " << 100.*(i+1)/it << "%" << std::endl;
        }

	system("mail -s 'timeResolution10' [email protected] <<< 'Progress: " + int2str(i) + "' ");
        
        // Set random velocity direction, in positive hemisphere
        const double ctheta = 1. - r.Uniform();
        const double stheta = sqrt(1. - ctheta*ctheta);
        const double phi = TwoPi*r.Uniform();
        vx0 = cos(phi)*stheta;
        vy0 = sin(phi)*stheta;
        vz0 = ctheta;
  
        // Set initial time
        t0 = 0.0;

        // Generate random (x,y) position in unit cell
        x0 = r.Uniform()*g.pitch/2; 
        y0 = r.Uniform()*g.pitch*TMath::Sqrt(3)/2;
        z0 = 0.;
        
        // Set muon perpendicular in midpoint of GEM
        x0 = 0.;
        y0 = 0.;
        vx0 = 0.;
        vy0 = 0.;
        vz0 = 1.;
        
        heed->NewTrack(x0, y0, z0, t0, vx0, vy0, vz0); // generate particle track
        
        // Storage of TRACK coordinates and primary ionization properties
        p.x0 = x0;
        p.y0 = y0;
        p.z0 = z0;
        p.vx0 = vx0;
        p.vy0 = vy0;
        p.vz0 = vz0;
        p.t0 = t0;
        p.e0 = particleEnergy;
        p.type = particleType;
        p.noClusters = 0;
        p.lambda = 1/heed->GetClusterDensity();
        p.stoppingPower = heed->GetStoppingPower();

        // Loop over clusters
        int l=0;
        while(heed->GetCluster(x0, y0, z0, t0, nc, ec, extra)) {
            
            // Skip the clusters which are not in the drift region
            if(z0 > g.driftT) {
                continue;
            }
            
            if(debug) {
                std::cout << "  cluster " << l << " (# electrons = " << nc << ", ec = " << ec <<" )" << std::endl;
            } 

            cluster c;
            // Storage of cluster information
            p.noClusters++;
            c.x0 = x0;
            c.y0 = y0;
            c.z0 = z0;
            c.t0 = t0;
            c.nc = nc; // amount of primary electrons
            c.ec = ec; // energy transferred to gas
            
            // Loop over electrons in cluster
            for(int j=0; j<nc; j++) {

                heed->GetElectron(j, x1, y1, z1, t1, e1, vx1, vy1, vz1);
                
                c.x1.push_back(x1);
                c.y1.push_back(y1);
                c.z1.push_back(z1);
                c.t1.push_back(t1);
                c.e1.push_back(e1);
                c.vx1.push_back(vx1);
                c.vy1.push_back(vy1);
                c.vz1.push_back(vz1);

                // Calculate the drift of electrons and ions
                aval->AvalancheElectron(x1, y1, z1, t1, e1, vx1, vy1, vz1);
                aval->GetAvalancheSize(ne, ni);
                np = aval->GetNumberOfElectronEndpoints();
        
                if(debug) {
                    std::cout << "    avalanche electrons = " << np << std::endl;
                }
                
                aE.ne = ne;
                aE.x0 = x1;
                aE.y0 = y1;
                aE.z0 = z1;
                aE.vx0 = vx1;
                aE.vy0 = vy1;
                aE.vz0 = vz1;
                aE.t0 = t1;
                aE.e0 = e1;
                aI.ni = ni;
                aI.x0 = x1;
                aI.y0 = y1;
                aI.z0 = z1;
                aI.t0 = t1;
                       
                // Loop over all electrons in avalanche
                for(int k=0; k<np; k++) {

                    aval->GetElectronEndpoint(k, x2, y2, z2, t2, e2, x3, y3, z3, t3, e3, status);
                    aE.x1.push_back(x2);
                    aE.y1.push_back(y2);
                    aE.z1.push_back(z2);
                    aE.t1.push_back(t2);
                    aE.e1.push_back(e2);
                    aE.x2.push_back(x3);
                    aE.y2.push_back(y3);
                    aE.z2.push_back(z3);
                    aE.t2.push_back(t3);
                    aE.e2.push_back(e3);
                    aE.status.push_back(status);  

                    iondrift->DriftIon(x2, y2, z2, t2);
                    iondrift->GetIonEndpoint(0, x2, y2, z2, t2, x3, y3, z3, t3, status);
                    aI.x1.push_back(x2);
                    aI.y1.push_back(y2);
                    aI.z1.push_back(z2);
                    aI.t1.push_back(t2);
                    aI.x2.push_back(x3);
                    aI.y2.push_back(y3);
                    aI.z2.push_back(z3);
                    aI.t2.push_back(t3);
                    aI.status.push_back(status);
                    
                    
                }
        
                ETree->Fill();
                ITree->Fill();
        
                // Reset vectors
                aE.x1.clear();
                aE.y1.clear();
                aE.z1.clear();
                aE.t1.clear();
                aE.e1.clear();
                aE.x2.clear();
                aE.y2.clear();
                aE.z2.clear();
                aE.t2.clear();
                aE.e2.clear();
                aE.status.clear();

                aI.x1.clear();
                aI.y1.clear();
                aI.z1.clear();
                aI.t1.clear();
                aI.e1.clear();
                aI.x2.clear();
                aI.y2.clear();
                aI.z2.clear();
                aI.t2.clear();
                aI.e2.clear();
                aI.status.clear();    
            }     
            
            p.clusters.push_back(c);
            l++;
        }

        pTree->Fill();
        p.clusters.clear();
        
        signalView->PlotSignal("readout");
        h = signalView->GetHistogram();
        h->Write("signal");

        sensor->SetTransferFunction(transferf);
        sensor->ConvoluteSignal();
        signalView->PlotSignal("readout");
        h = signalView->GetHistogram();
        h->Write("signalT");    
        sensor->ClearSignal();
    }
    
    f.cd(); // go to top directory
    ETree->Write();
    ITree->Write();
    pTree->Write();
    f.Close();
    
    std::cout << "--------------- TIMING ---------------" << std::endl;
    std::cout << watch.CpuTime() << std::endl;

    return 0;
}
void estimate_uncertainty(int N=1000)
{
  double a,b,c,d;
  TRandom3 rand;
  double mean = 0.0;
  double sigma = 0.25;
  double sigma1 = 0.22;

  TH1F *hA = new TH1F("hA","numerator 1;A;counts", 200,0,2);
  TH1F *hB = new TH1F("hB","denominator 1;B;counts", 200,0,2);
  TH1F *hC = new TH1F("hC","numerator 2;C;counts", 200,0,2);
  TH1F *hD = new TH1F("hD","denominator 2;D;counts", 200,0,2);
  TH1F *hR1 = new TH1F("hR1","ratio 1;single ratio;counts",200,0,2);
  TH1F *hR2 = new TH1F("hR2","ratio 2;single raito;counts",200,0,2);
  TH1F *hDR = new TH1F("hDR","double ratio;double ratio;counts",200,0,2);

  hA->Sumw2();
  hB->Sumw2();
  hC->Sumw2();
  hD->Sumw2();
  hR1->Sumw2();
  hR2->Sumw2();
  hDR->Sumw2();

  hA->SetMarkerColor(kBlack);
  hB->SetMarkerColor(kRed);
  hC->SetMarkerColor(kBlue);
  hD->SetMarkerColor(kGreen+2);

  hB->SetMarkerStyle(21);
  hC->SetMarkerStyle(24);
  hD->SetMarkerStyle(25);

  hR2->SetMarkerColor(kRed);
  hR2->SetMarkerStyle(24);

  hA->GetXaxis()->CenterTitle(1);
  hR1->GetXaxis()->CenterTitle(1);
  hDR->GetXaxis()->CenterTitle(1);

  rand.SetSeed(0);

  for (int i=0; i<N; ++i) {
    // a = rand.Gaus(mean, sigma1);
    // b = a;
    a = rand.Gaus(mean, sigma1);
    a *= rand.Gaus(mean, sigma);
    b = rand.Gaus(mean, sigma1);
    b *= rand.Gaus(mean, sigma);

    // c = rand.Gaus(mean, sigma1);
    // d = c;
    c = rand.Gaus(mean, sigma1);
    c *= rand.Gaus(mean, sigma);
    d = rand.Gaus(mean, sigma1);
    d *= rand.Gaus(mean, sigma);

    a += 1;
    b += 1;
    c += 1;
    d += 1;

    hA->Fill(a);
    hB->Fill(b);
    hC->Fill(c);
    hD->Fill(d);

    hR1->Fill( (a/b) );
    hR2->Fill( (c/d) );

    hDR->Fill( (a/b) / (c/d) );
  }

  TCanvas *c1 = new TCanvas("c1","c1",1200,600);
  c1->Divide(3,1);
  c1->cd(1);
  hA->Draw();
  hB->Draw("same");
  hC->Draw("same");
  hD->Draw("same");
  c1->cd(2);
  hR1->Draw();
  hR2->Draw("same");
  c1->cd(3);
  hDR->Draw();

  cout << "Mean = " << hDR->GetMean() << " RMS = " << hDR->GetRMS() << endl;

  return;
}
void sqrtMethodSameSign(int ptBin, double ptCutLo, double ptCutHi, int massBin, double mCutLo, double mCutHi, int etaBin, double etaCutLo, double etaCutHi){
	
	//OPTIONS AND CUTS------------
	bool useBlueBeam = true;
	bool useYellowBeam = true;
	bool randomizeSpin = false;
	
	double PI = 3.14159265359;
	
	cout << "\n";
	if (useBlueBeam && useYellowBeam){cout << "using both beams-----" << endl;}
	if (useBlueBeam && !useYellowBeam){cout << "using blue beam------" << endl;}
	if (!useBlueBeam && useYellowBeam){cout << "using yellow beam----" << endl;}
	cout << "\n";
	if (randomizeSpin){cout << "randomizing spin-----" << endl;}
	
	
	
	//PION PAIR CUTS:
	/*
	 double ptCutLo = 4;
	 double ptCutHi = 10;
	 double mCutLo = .4;
	 double mCutHi = 1;
	 double etaCutLo = -1.4;
	 double etaCutHi = 1.4;
	 //*/
	//double phiCutLo = -.5;
	//double phiCutHi = .5;
	
	//----------------------------	
	
	
	//LOAD LIBS
	cout << "\n";
	gROOT->Macro("StRoot/LoadLibs.C");
	gSystem->Load("sameSignPair");
	cout << " loading of sameSignPair library done" << endl;

	
	
	//SET UP INPUT FILE	
	TFile* infile = new TFile("/star/u/klandry/ucladisk/2012IFF/schedOut_samesign_4_14/allSameSign_4_14.root");
	
	
	
	//SET UP TREE TO RECEIVE INPUT
	sameSignPair* pair1 = new sameSignPair();
	TTree* pairTree = infile->Get("sameSignTree");
	pairTree->SetBranchAddress("sameSignPair", &pair1);
	
	
	//SET UP HISTOGRAMS
	
	//event variable histograms
	TH1D* hInvarM    = new TH1D("invarM","invarM",80,0,2);
	TH1D* hEtaTot	   = new TH1D("etaTot","etaTot",60,-1.5,1.5);
	TH1D* hPhiR      = new TH1D("hPhiR","hPhiR",60,-4,4);
	TH1D* hPhiS      = new TH1D("hPhiS","hPhiS",60,-4,4);
	TH1D* hPhiSR     = new TH1D("hPhiSR","hPhiSR",60,-4,4);
	TH1D* hTheta     = new TH1D("hTheta","hTheta",30,-0.85,4);
	TH1D* hCosTheta  = new TH1D("hCosTheta","hCosTheta",80,-1,1);
	TH1D* hZ         = new TH1D("hZ","hZ",80,0,1);
	TH1D* hPtot      = new TH1D("hPtot","hPtot",80,0,20);
	TH1D* hPtTOT     = new TH1D("hPt","hPt",80,0,15);
	
	//histos for asym analysis	
	double histMin = -PI;
	double histMax =  PI;
	const int binNumber = 16;
	
	TH1D * hNumberUp   = new TH1D("hNumberUp","hNumberUp",binNumber,histMin,histMax);
	TH1D * hNumberDown = new TH1D("hNumberDown","hNumberDown",binNumber,histMin,histMax);
	
	TH1D * hDiff  = new TH1D("hNumberSum","hNumberSum",binNumber,histMin,histMax);
	TH1D * hAut = new TH1D("Aut","Aut",binNumber,histMin,histMax);
	
	
	//BEAM POLARIZATION
	
	ifstream polFile;
	polFile.open("/star/u/klandry/ucladisk/2012IFF/BeamPolarization2012.txt");
	
	
	map<int, double> polarizationOfFill_Y;
	map<int, double> polErrOfFill_Y;
	
	map<int, double> polarizationOfFill_B;
	map<int, double> polErrOfFill_B;
	
	
	
	int    fill;
	int    beamE;
	int    startT;
	string plusminus;
	
	double pAvrgBlue;
	double pErrAvrgBlue;
	
	double pInitialBlue;
	double pErrInitialBlue;
	double dPdTBlue;
	double dPdTErrBlue;
	
	double pAvrgYellow;
	double pErrAvrgYellow;
	
	double pInitialYellow;
	double pErrInitialYellow;
	double dPdTYellow;
	double dPdTErrYellow;
	
	string header;
	
	for (int i=0; i<19; i++){polFile >> header;}
	
	while (!polFile.eof())
	{
		
		polFile >> fill;
		polFile >> beamE;
		polFile >> startT;
		
		polFile >> pAvrgBlue;
		polFile >> plusminus;
		polFile >> pErrAvrgBlue;
		
		polFile >> pInitialBlue;
		polFile >> plusminus;
		polFile >> pErrInitialBlue;
		
		polFile >> dPdTBlue;
		polFile >> plusminus;
		polFile >> dPdTErrBlue;
		
		polFile >> pAvrgYellow;
		polFile >> plusminus;
		polFile >> pErrAvrgYellow;
		
		polFile >> pInitialYellow;
		polFile >> plusminus;
		polFile >> pErrInitialYellow;
		
		polFile >> dPdTYellow;
		polFile >> plusminus;
		polFile >> dPdTErrYellow;
		
		
		polarizationOfFill_B[fill] = pAvrgBlue/100.;
		polErrOfFill_B[fill] = pErrAvrgBlue/100.;
		
		polarizationOfFill_Y[fill] = pAvrgYellow/100.;
		polErrOfFill_Y[fill] = pErrAvrgYellow/100.;
		
		
		
	}
	
	double avgPolOfBinUp[binNumber];
	double polOfBinSumUp[binNumber];
	
	double avgPerrorOfBinUp[binNumber];
	double pErrorOfBinUp[binNumber];
	
	double avgPolOfBinDown[binNumber];
	double polOfBinSumDown[binNumber];
	
	double avgPerrorOfBinDown[binNumber];
	double pErrorOfBinDown[binNumber];
	
	for (int i=0; i<binNumber; i++)
	{
		avgPolOfBinUp[i] = 0;
		polOfBinSumUp[i] = 0;
		
		avgPerrorOfBinUp[i] = 0;
		pErrorOfBinUp[i] = 0;
		
		avgPolOfBinDown[i] = 0;
		polOfBinSumDown[i] = 0;
		
		avgPerrorOfBinDown[i] = 0;
		pErrorOfBinDown[i] = 0;
		
	}
	
	
	//   ======================================================================
	//============================================================================
	//START ANALYSIS==============================================================
	//============================================================================
	//   ======================================================================
	
	cout << pairTree->GetEntries() << endl;
	
	cout << "\n";
	cout << "<----STARTING ANALYSIS---->" << endl;
  cout << "\n";
	
	
	double blueFillNo;
	double yellowFillNo;
	
	int bin;
	
	TLorentzVector sum;
	TLorentzVector sumY;
	TLorentzVector sumB;
	
	//random number for randomizing spin.
	//set seed to zero to gaurenty unique numbers each time.
	TRandom3 r;
	r.SetSeed(0);
	
	int rand5 = 0;
	int rand6 = 0;
	int rand9 = 0;
	int rand10 = 0;
	
	
	int totalPairsFinal = 0;
	int blueD = 0;
	int blueU = 0;
	int yellowD = 0;
	int yellowU = 0;
	
	int pionStarNumber = 0;
	
	
	for (int iPair = pionStarNumber; iPair < pairTree->GetEntries(); iPair++)
	{
		if (iPair%10000 == 0) {cout << "processing pair number " << iPair << endl;}
		
		//if (iPair == pionStarNumber+2000000){break;}
		
		pairTree->GetEntry(iPair);
				
		
		if (pair1->withinRadius(0.05, 0.3))
		{
			
			
			bool triggerFired = false;
			bool fromKaon = false;
			
			StTriggerId trigId = pair1->triggerIds();
			
			
			//JP0,JP1,JP2,AJP
			if (trigId.isTrigger(370601) || trigId.isTrigger(370611) || trigId.isTrigger(370621) || trigId.isTrigger(370641))
			{
				triggerFired = true;
			}
			
			//BHT0VPD,BHT1VPD,BHT2BBC,BHT2
			if (trigId.isTrigger(370501) || trigId.isTrigger(370511) || trigId.isTrigger(370522) || trigId.isTrigger(370531))
			{
				triggerFired = true;
			}
			
			
			if (pair1->invarientMass() > .4921 && pair1->invarientMass() < .4990)
			{
				fromKaon = true;
			}
			
			
			
			if (triggerFired)
			{
				
				
				blueFillNo   = pair1->runInfo().beamFillNumber(1); //1 = blue beam
				yellowFillNo = pair1->runInfo().beamFillNumber(0); //0 = yellow beam 
				
				//cout << blueFillNo << "  " << yellowFillNo << endl;
				
				
				if (polarizationOfFill_B[blueFillNo] == 0 || polarizationOfFill_Y[yellowFillNo] == 0) //0 is gap
				{
					continue;
				}
				
				
				hInvarM->Fill(pair1->invarientMass());
				
				
				sum = pair1->pion1LV() + pair1->pion2LV();
				sumB = sum; //blue beam.
				
				
				//yellow beam must rotate around y axis by pi so the eta cut can be the same for both beams. 				
				sumY = sum;
				sumY.RotateY(PI);
				
				//cout << pair1->phiS('y')-pair1->phiR('y') << "   " << pair1->phiSR('y') << endl;
				
				//option for randomizing spin
				if (randomizeSpin)
				{
					
					int origSpinBit = pair1->spinBit();
					
					double randomSpin = r.Uniform(0, 1);
					
					int randomSpinBit;
					
					if (randomSpin >=0 && randomSpin <0.25)  {randomSpinBit = 5; rand5++;}
					if (randomSpin >=0.25 && randomSpin <0.5){randomSpinBit = 6; rand6++;}
					if (randomSpin >=0.5 && randomSpin <0.75){randomSpinBit = 9; rand9++;}
					if (randomSpin >=0.75 && randomSpin <1.0){randomSpinBit = 10; rand10++;}
					
					
					
					pair1->setSpinBit(randomSpinBit);
					
					
					
				}
				
				
				//cout << pair1->sinPhiSR('b') << "   " << pair1->cosPhiSR('b') << "   " << pair1->phiSR('b') << endl;
				
				
				//MANUALLY ALTER ANGLES FOR TESTING-----
				/*
				 double testPhiS_y = -pair1->phiS('y');
				 double testPhiR_y = pair1->phiR('y');
				 
				 double testPhiS_b = -pair1->phiS('b');
				 double testPhiR_b = pair1->phiR('b');
				 
				 
				 
				 double testPhiSR_y = testPhiS_y - testPhiR_y;
				 
				 double testPhiSR_b = testPhiS_b - testPhiR_b;
				 
				 //cout << testPhiS_b << " " << testPhiR_b << "  " << testPhiS_y << " " << testPhiR_y << endl;
				 
				 
				 if (testPhiSR_y > PI)
				 {
				 testPhiSR_y -= 2*PI;
				 }
				 
				 if (testPhiSR_y < -PI)
				 {
				 testPhiSR_y += 2*PI;
				 }
				 
				 if (testPhiSR_b > PI)
				 {
				 testPhiSR_b -= 2*PI;
				 }
				 
				 if (testPhiSR_b < -PI)
				 {
				 testPhiSR_b += 2*PI;
				 }
				 
				 //cout << testPhiSR_b << "   " << testPhiSR_y << endl;
				 //*/
				
				//CHECK CUTS
				if (sumB.Pt() > ptCutLo && sumB.Pt() < ptCutHi && sumB.M() > mCutLo && sumB.M() < mCutHi && sumB.Eta() > etaCutLo && sumB.Eta() < etaCutHi && useBlueBeam == true)
				{
					
					//BLUE BEAM SPIN UP: spin bin 9 and 10
					if (pair1->spinBit() == 9 || pair1->spinBit() == 10)
					{
						blueU++;
						
						
						//make sure to set it back if you randomized it for up/down.
						//still need origional spin bit to calc anlge.
						if (randomizeSpin){pair1->setSpinBit(origSpinBit);}
						
						bin = hNumberUp->FindBin(pair1->phiSR('b'));
						hNumberUp->Fill(pair1->phiSR('b'));
						
						//bin = hNumberUp->FindBin(testPhiSR_b);
						//hNumberUp->Fill(testPhiSR_b);
						
						
						
						polOfBinSumUp[bin] += polarizationOfFill_B[blueFillNo];
						pErrorOfBinUp[bin] += polErrOfFill_B[blueFillNo];
						
						
						//If rondomized spin, have to set the spin bit back to random
						//for next spin bit check
						if (randomizeSpin){pair1->setSpinBit(randomSpinBit);}
					}
					
					//BLUE BEAM SPIN DOWN: spin bin 5 and 6
					if (pair1->spinBit() == 5 || pair1->spinBit() == 6)
					{
						blueD++;
						
						if (randomizeSpin){pair1->setSpinBit(origSpinBit);}
						
						bin = hNumberDown->FindBin(pair1->phiSR('b'));
						hNumberDown->Fill(pair1->phiSR('b'));
						
						//bin = hNumberDown->FindBin(testPhiSR_b);
						//hNumberDown->Fill(testPhiSR_b);
						
						
						polOfBinSumDown[bin] += polarizationOfFill_B[blueFillNo];
						pErrorOfBinDown[bin] += polErrOfFill_B[blueFillNo];		
						
						if (randomizeSpin){pair1->setSpinBit(randomSpinBit);}
					}
					
				}//end blue cuts
				
				
				
				if (sumY.Pt()>ptCutLo && sumY.Pt() < ptCutHi && sumY.M() > mCutLo && sumY.M() < mCutHi && sumY.Eta() > etaCutLo && sumY.Eta() < etaCutHi && useYellowBeam == true)
				{
					
					//YELLOW BEAM SPIN UP: spin bin 6 and 10
					if (pair1->spinBit() == 6 || pair1->spinBit() == 10)
					{
						
						yellowU++;
						
						if (randomizeSpin){pair1->setSpinBit(origSpinBit);}
						
						bin = hNumberUp->FindBin(pair1->phiSR('y'));
						hNumberUp->Fill(pair1->phiSR('y'));
						
						
						//bin = hNumberUp->FindBin(testPhiSR_y);
						//hNumberUp->Fill(testPhiSR_y);
						
						
						
						polOfBinSumUp[bin] += polarizationOfFill_Y[yellowFillNo];
						pErrorOfBinUp[bin] += polErrOfFill_Y[yellowFillNo];
						
						if (randomizeSpin){pair1->setSpinBit(randomSpinBit);}
					}	
					//YELLOW BEAM SPIN DOWN: spin bit 5 and 9
					if (pair1->spinBit() == 5 || pair1->spinBit() == 9)
					{
						
						yellowD++;
						
						if (randomizeSpin){pair1->setSpinBit(origSpinBit);}
						
						bin = hNumberDown->FindBin(pair1->phiSR('y'));
						hNumberDown->Fill(pair1->phiSR('y'));
						
						//bin = hNumberDown->FindBin(testPhiSR_y);
						//hNumberDown->Fill(testPhiSR_y);
						
						
						polOfBinSumDown[bin] += polarizationOfFill_Y[yellowFillNo];
						pErrorOfBinDown[bin] += polErrOfFill_Y[yellowFillNo];
						
						if (randomizeSpin){pair1->setSpinBit(randomSpinBit);}
					}
				}//end yellow cuts
			}//end triger check
		}//end radius check
	}//end pairTree loop
	
	
	//CALCULATE ASYMMETRY BIN BY BIN
	cout << "\n";
	cout << "<----CALCULATING ASYMMETRY---->" << endl;
	cout << "\n";
	
	for (int ibin=1; ibin<=binNumber; ibin++)
	{
		
		if (ibin <= binNumber*0.5)
		{
			double nUp   = hNumberUp->GetBinContent(ibin);
			double nUpPi = hNumberUp->GetBinContent(ibin+binNumber*0.5);
			
			double nDown   = hNumberDown->GetBinContent(ibin);
			double nDownPi = hNumberDown->GetBinContent(ibin+binNumber*0.5);
			
			
			int binIndexPi = ibin+binNumber*0.5;
			
			double avgPolA = (polOfBinSumUp[ibin]+polOfBinSumDown[binIndexPi])/(nUp+nDownPi);
			double avgPolB = (polOfBinSumUp[binIndexPi]+polOfBinSumDown[ibin])/(nUpPi+nDown);
			
			double realAvgPol = (polOfBinSumUp[ibin]+polOfBinSumDown[binIndexPi]+polOfBinSumUp[binIndexPi]+polOfBinSumDown[ibin])/(nUp+nUpPi+nDown+nDownPi);
			
		}
		else
		{
			double nUp   = hNumberUp->GetBinContent(ibin);
			double nUpPi = hNumberUp->GetBinContent(ibin-binNumber*0.5);
			
			double nDown   = hNumberDown->GetBinContent(ibin);
			double nDownPi = hNumberDown->GetBinContent(ibin-binNumber*0.5);
			
			int binIndexPi = ibin-binNumber*0.5;
			
			double avgPolA = (polOfBinSumUp[ibin]+polOfBinSumDown[binIndexPi])/(nUp+nDownPi);
			double avgPolB = (polOfBinSumUp[binIndexPi]+polOfBinSumDown[ibin])/(nUpPi+nDown);
			
			double realAvgPol = (polOfBinSumUp[ibin]+polOfBinSumDown[binIndexPi]+polOfBinSumUp[binIndexPi]+polOfBinSumDown[ibin])/(nUp+nUpPi+nDown+nDownPi);
			
			double realAvgPolE = (pErrorOfBinUp[ibin]+pErrorOfBinDown[binIndexPi]+pErrorOfBinUp[binIndexPi]+pErrorOfBinDown[ibin])/(nUp+nUpPi+nDown+nDownPi);
			
		}
		
		
		cout << avgPolA << "   " << avgPolB << endl;
		
		
		
		
		hDiff->SetBinContent(ibin, sqrt(nUp*nDownPi) - sqrt(nDown*nUpPi));
		
		//hAut->SetBinContent(ibin, (1/avgPolA * sqrt(nUp*nDownPi) - 1/avgPolB * sqrt(nDown*nUpPi)) / (sqrt(nUp*nDownPi) + sqrt(nDown*nUpPi))    );
		
		
		hAut->SetBinContent(ibin, 1/realAvgPol * (sqrt(nUp*nDownPi) - sqrt(nDown*nUpPi)) / (sqrt(nUp*nDownPi) + sqrt(nDown*nUpPi))    );
		
		
		
		
		//error
		if (realAvgPol*pow(sqrt(nUp*nDownPi)+sqrt(nDown*nUpPi), 2) != 0)
		{
			
			double a = sqrt(nUp*nDownPi);
			double b = sqrt(nUpPi*nDown);
			
			
			double firstTerm = realAvgPol**2 * (nUpPi*nDown*(nUp+nDownPi) + nDownPi*nUp*(nUpPi+nDown));
			
			//double secondTerm = ((nUp*nDownPi)**2 +(nUpPi*nDown)**2 - 2*nUp*nDown*nUpPi*nDownPi)*realAvgPolE**2;
			
			double secondTerm = 0;
			
			
			double binError = 1/realAvgPol**2 * 1/(a+b)**2 * sqrt(firstTerm + secondTerm);
			
			
		}	
		else
		{
			double binError = 0.01;
			cout << "bin " << ibin << " Has problem with error" << endl;
		}
		
		hAut->SetBinError(ibin, binError);
		
	}//end Asym calc
	
	
	
	//DRAW HISTOGRAMS
	
	hInvarM->Draw();
	
	TCanvas* cNup = new TCanvas();
	hNumberUp->Draw();
	
	TCanvas* cNdown = new TCanvas();
	hNumberDown->Draw();
	
	TCanvas* cAut = new TCanvas();
	cAut->SetName("cAut");
	
	TF1* fitFunc = new TF1("fitFunc","[0]*cos(x)+[1]",-PI,PI);
	hAut->Fit("fitFunc","R");
	hAut->Draw();
	
	hAut->GetXaxis()->SetTitle("#phi_{S} - #phi_{R}");
	
	char title[150];
	sprintf(title, "%.1f < P_{T}^{#pi^{1}#pi^{2}} < %.1f  %.1f < M_{inv}^{#pi^{1}#pi^{2}} < %.1f  %.1f < #eta^{#pi^{1}#pi^{2}} < %.1f", ptCutLo, ptCutHi, mCutLo, mCutHi, etaCutLo, etaCutHi);
	
	hAut->SetTitle(title);
	
	
	cout << "Asym  = " << hAut->GetFunction("fitFunc")->GetParameter(0) << endl;
	cout << "error = " << hAut->GetFunction("fitFunc")->GetParError(0) << endl;
	cout << "chi2  = " << hAut->GetFunction("fitFunc")->GetChisquare() << endl;
	cout << "Nup   = " << hNumberUp->GetEntries() << endl;
	cout << "Ndown = " << hNumberDown->GetEntries() << endl;
  cout << "ran5  = " << rand5 << endl;
  cout << "ran6  = " << rand6 << endl;
  cout << "ran9  = " << rand9 << endl;
  cout << "ran10 = " << rand10 << endl;
	cout << "blueU = " << blueU << endl;
	cout << "blueD = " << blueD << endl;
	cout << "yellowU = " << yellowU << endl;
	cout << "yellowD = " << yellowD << endl;
	
	
	
	
	//SAVE CANVAS	
	
	
	stringstream pt;
	stringstream eta;
	stringstream mass;
	
	string part1 = "_ptBin";
	string part2 = "_massBin";
	string part3 = "_etaBin";
	
	string ptBinStr;
	string etaBinStr;
	string massBinStr;
	
	pt << ptBin;
	
	eta << etaBin;
	
	mass << massBin;
	
	if (ptBin == 9){ptBinStr = "All";}
	else{	ptBinStr = pt.str();}
	
	if (massBin == 9){massBinStr = "All";}
	else{	massBinStr = mass.str();}
	
	if (etaBin == 9){etaBinStr = "All";}
	else{	etaBinStr = eta.str();}
	
	cout << "total pairs " << totalPairsFinal << endl;
	
	
	stringstream pionNum;
	pionNum << pionStarNumber; 
	string pionNumStr = pionNum.str();
	
	
	string outFileName = "./results_samesign_4_14/sameSign"+part1+ptBinStr+part2+massBinStr+part3+etaBinStr+".root";
	TFile* outFile = new TFile(outFileName.c_str(),"Recreate");
	
	
	cout << "---WRITING FILE---" << endl; 
	//cAut->SaveAs(outFileName.c_str());
	hAut->Write();
	hNumberUp->Write();
	hNumberDown->Write();
	
	cout << "---END---" << endl; 
}
void sqrtBins(){


	//OPTIONS AND CUTS______________
	bool useBlueBeam = false;
	bool useYellowBeam = true;
	bool randomizeSpin = false;
	bool fullEta = false;

	double PI = 3.14159265359;
	
	
	
	
	cout << "\n";
	if (useBlueBeam && useYellowBeam){cout << "using both beams-----" << endl;}
	if (useBlueBeam && !useYellowBeam){cout << "using blue beam------" << endl;}
	if (!useBlueBeam && useYellowBeam){cout << "using yellow beam----" << endl;}
	cout << "\n";
	if (randomizeSpin){cout << "randomizing spin-----" << endl;}
	//______________________________


  
	//LOAD LIBS_____________________
	cout << "\n";
	gROOT->Macro("StRoot/LoadLibs.C");
	gSystem->Load("pionPair");
	cout << " loading of pionPair library done" << endl;
	//______________________________


	//SET UP INPUT FILE_____________
	TFile* infile = new TFile("/star/u/klandry/ucladisk/2012IFF/schedOut_Full_4_2/allPairs_4_2.root");

	string outFileName = "./resultsNew_4_22/yellowEtaGT0_pairs_4_2.root"; 

	
	
  //______________________________

	
	//SET UP TREE TO RECEIVE INPUT__
	pionPair* pair1 = new pionPair();
	TTree* pairTree = infile->Get("pionPairTree");
	pairTree->SetBranchAddress("pionPair", &pair1);
	//______________________________
	
	
	//SET UP HISTOGRAMS_____________
	//event variable histograms
	/*
	TH1D* hInvarM    = new TH1D("invarM","invarM",80,0,2);
	TH1D* hEtaTot	   = new TH1D("etaTot","etaTot",60,-1.5,1.5);
	TH1D* hPhiR      = new TH1D("hPhiR","hPhiR",60,-4,4);
	TH1D* hPhiS      = new TH1D("hPhiS","hPhiS",60,-4,4);
	TH1D* hPhiSR     = new TH1D("hPhiSR","hPhiSR",60,-4,4);
	TH1D* hTheta     = new TH1D("hTheta","hTheta",30,-0.85,4);
	TH1D* hCosTheta  = new TH1D("hCosTheta","hCosTheta",80,-1,1);
	TH1D* hZ         = new TH1D("hZ","hZ",80,0,1);
	TH1D* hPtot      = new TH1D("hPtot","hPtot",80,0,20);
	TH1D* hPtTOT     = new TH1D("hPt","hPt",80,0,15);
	*/
	
	//histos for asym analysis	
	double histMin = -PI;
	double histMax =  PI;
	
	TH1D * hNumberUp   = new TH1D("hNumberUp","hNumberUp",nPhisrBins,histMin,histMax);
	TH1D * hNumberDown = new TH1D("hNumberDown","hNumberDown",nPhisrBins,histMin,histMax);
	
	TH1D * hNumberUp_Pt[nPtBins];
	TH1D * hNumberDown_Pt[nPtBins];
	
	TH1D * hNumberUp_Mass[nMassBins]; 
	TH1D * hNumberDown_Mass[nMassBins];

	TH1D * hNumberUp_Eta[nEtaBins];   
	TH1D * hNumberDown_Eta[nEtaBins];
	
	createFiveBins(hNumberUp_Pt,nPhisrBins,histMin,histMax,"hNumUp_Ptbin_");
	createFiveBins(hNumberDown_Pt,nPhisrBins,histMin,histMax,"hNumDwn_Ptbin_");
	createFiveBins(hNumberUp_Mass,nPhisrBins,histMin,histMax,"hNumUp_Massbin_");
	createFiveBins(hNumberDown_Mass,nPhisrBins,histMin,histMax,"hNumDwn_Massbin_");
	createFourBins(hNumberUp_Eta,nPhisrBins,histMin,histMax,"hNumUp_Etabin_");
	createFourBins(hNumberDown_Eta,nPhisrBins,histMin,histMax,"hNumDwn_Etabin_");
	
	TH1D* hAut_Pt[nPtBins];
	TH1D* hAut_Mass[nMassBins];
	TH1D* hAut_Eta[nEtaBins];

	createFiveBins(hAut_Pt, nPhisrBins, histMin, histMax, "hAut_Ptbin_");
	createFiveBins(hAut_Mass, nPhisrBins, histMin, histMax, "hAut_Massbin_");
	createFourBins(hAut_Eta, nPhisrBins, histMin, histMax, "hAut_Etabin_");
	
	
	/*
	TH1D* polOfBinUp_Pt[nPtBins][binNumber];
	TH1D* polOfBinDown_Pt[nPtBins][binNumber];
	TH1D* polOfBinUp_Mass[nMassBins][binNumber];
	TH1D* polOfBinDown_Mass[nMassBins][binNumber];
	TH1D* polOfBinUp_Eta[nEtaBins][binNumber];
	TH1D* polOfBinDown_Eta[nEtaBins][binNumber];
	createPolHists(polOfBinUp_Pt, 25, 0, 1, "hPolOfBinUp_Ptbin_");
	createPolHists(polOfBinDown_Pt, 25, 0, 1, "hPolOfBinDown_Ptbin_");
	createPolHists(polOfBinUp_Mass, 25, 0, 1, "hPolOfBinUp_Massbin_");
	createPolHists(polOfBinDown_Mass, 25, 0, 1, "hPolOfBinDown_Massbin_");
	createPolHists(polOfBinUp_Eta, 25, 0, 1, "hPolOfBinUp_Etabin_");
	createPolHists(polOfBinDown_Eta, 25, 0, 1, "hPolOfBinDown_Etabin_");
  */
	
	TH1D* polOfBin_Pt[nPtBins][nPhisrBins];
	TH1D* polOfBin_Mass[nMassBins][nPhisrBins];
	TH1D* polOfBin_Eta[nEtaBins][nPhisrBins];
	createPolHists(polOfBin_Pt, 25, 0, 1, "hPolOfBin_Ptbin_");
	createPolHists(polOfBin_Mass, 25, 0, 1, "hPolOfBin_Massbin_");
	createPolHistsEta(polOfBin_Eta, 25, 0, 1, "hPolOfBin_Etabin_");
	
	
	//HISTOGRAMS TO HOLD PT MASS AND ETA VALES
	TH1D* hPt[nPtBins];
	TH1D* hMass[nMassBins];
	TH1D* hEta[nEtaBins];
	createFiveBins(hPt, 500, 3.0, 50, "hPt_Ptbin_");
	createFiveBins(hMass, 1000, 0.0, 100, "hMass_Massbin_");
	createFourBins(hEta, 20, -1.4, 1.4, "hEta_Etabin_");
	
	
	//TH1D * hDiff  = new TH1D("hNumberSum","hNumberSum",binNumber,histMin,histMax);
	//TH1D * hAut = new TH1D("Aut","Aut",binNumber,histMin,histMax);
	//______________________________
	
	
	
	//BEAM POLARIZATION_____________
	ifstream polFile;
	polFile.open("/star/u/klandry/ucladisk/2012IFF/BeamPolarization2012.txt");
	

	map<int, double> polarizationOfFill_Y;
	map<int, double> polErrOfFill_Y;
	
	map<int, double> polarizationOfFill_B;
	map<int, double> polErrOfFill_B;
	
	
	
	int    fill;
	int    beamE;
	int    startT;
	string plusminus;
	
	double pAvrgBlue;
	double pErrAvrgBlue;
	
	double pInitialBlue;
	double pErrInitialBlue;
	double dPdTBlue;
	double dPdTErrBlue;
	
	double pAvrgYellow;
	double pErrAvrgYellow;
	
	double pInitialYellow;
	double pErrInitialYellow;
	double dPdTYellow;
	double dPdTErrYellow;
	
	string header;
	
	for (int i=0; i<19; i++){polFile >> header;}
	
	while (!polFile.eof())
	{
		
		polFile >> fill;
		polFile >> beamE;
		polFile >> startT;
		
		polFile >> pAvrgBlue;
		polFile >> plusminus;
		polFile >> pErrAvrgBlue;
		
		polFile >> pInitialBlue;
		polFile >> plusminus;
		polFile >> pErrInitialBlue;
		
		polFile >> dPdTBlue;
		polFile >> plusminus;
		polFile >> dPdTErrBlue;
		
		polFile >> pAvrgYellow;
		polFile >> plusminus;
		polFile >> pErrAvrgYellow;
		
		polFile >> pInitialYellow;
		polFile >> plusminus;
		polFile >> pErrInitialYellow;
		
		polFile >> dPdTYellow;
		polFile >> plusminus;
		polFile >> dPdTErrYellow;
		
		
		polarizationOfFill_B[fill] = pAvrgBlue/100.;
		polErrOfFill_B[fill] = pErrAvrgBlue/100.;
		
		polarizationOfFill_Y[fill] = pAvrgYellow/100.;
		polErrOfFill_Y[fill] = pErrAvrgYellow/100.;
		
	}
	
	double avgPolOfBinUp[nPhisrBins];
	double polOfBinSumUp[nPhisrBins];
	
	double avgPerrorOfBinUp[nPhisrBins];
	double pErrorOfBinUp[nPhisrBins];
	
	double avgPolOfBinDown[nPhisrBins];
	double polOfBinSumDown[nPhisrBins];
	
	double avgPerrorOfBinDown[nPhisrBins];
	double pErrorOfBinDown[nPhisrBins];
	
	for (int i=0; i<nPhisrBins; i++)
	{
		avgPolOfBinUp[i] = 0;
		polOfBinSumUp[i] = 0;
		
		avgPerrorOfBinUp[i] = 0;
		pErrorOfBinUp[i] = 0;
		
		avgPolOfBinDown[i] = 0;
		polOfBinSumDown[i] = 0;
		
		avgPerrorOfBinDown[i] = 0;
		pErrorOfBinDown[i] = 0;
		
	}
	//______________________________
	
	
	
	//CUTS__________________________
	double lowLimitPt    = ptBinStart[0];
	double hiLimitPt     = ptBinEnd[4];
	double lowLimitEta   = etaBinStart[0];
	double hiLimitEta    = etaBinEnd[3];
	double lowLimitMass  = massBinStart[0];
	double hiLimitMass   = massBinEnd[4];
	
	double blueLowLimitEta  = 0;
	double yellowLowLimitEta = 0;  //this is for testing individual beams
	
	
	//hiLimitEta = 0;
	
	if (fullEta)
	{
		assert(hiLimitEta > 0);
		assert(lowLimitEta < 0);
	}
	
	cout << "Pt  between " << lowLimitPt << " and " << hiLimitPt << endl;
	cout << "M   between " << lowLimitMass << " and " << hiLimitMass << endl;
	cout << "Eta between " << lowLimitEta << " and " << hiLimitEta << endl;
	//______________________________
	
	//*
	
	//   ======================================================================
	//============================================================================
	//START ANALYSIS==============================================================
	//============================================================================
	//   ======================================================================
		//*
	cout << "\n";
	cout << "<----STARTING ANALYSIS---->" << endl;
  cout << "\n";
	cout << pairTree->GetEntries() << " pairs to analyze" << endl;
	
	
	
	int blueFillNo;
	int yellowFillNo;
	
	int phiSRbin;
	
	TLorentzVector sum;
	TLorentzVector sumY;
	TLorentzVector sumB;
	
	//random number for randomizing spin.
	//set seed to zero to gaurenty unique numbers each time.
	TRandom3 r;
	r.SetSeed(0);
	
	int rand5 = 0;
	int rand6 = 0;
	int rand9 = 0;
	int rand10 = 0;
	
	
	int totalPairsFinal = 0;
	int blueD = 0;
	int blueU = 0;
	int yellowD = 0;
	int yellowU = 0;
	
	int pionStarNumber = 0;
	int test = 0;
	
	for (int iPair = pionStarNumber; iPair < pairTree->GetEntries(); iPair++)
	{
		
		if (iPair%10000 == 0) {cout << "processing pair number " << iPair << endl;}
		//if (iPair == pionStarNumber+100000){break;}

		pairTree->GetEntry(iPair);

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

			bool triggerFired = false;
			bool fromKaon = false;
			bool passInitialCut_B = false;
			bool passInitialCut_Y = false;
			bool passDCAcut = false;

			StTriggerId trigId = pair1->triggerIds();
						
			//JP0,JP1,JP2,AJP
			if (trigId.isTrigger(370601) || trigId.isTrigger(370611) || trigId.isTrigger(370621) || trigId.isTrigger(370641))
			{
				triggerFired = true;
			}
			
			//BHT0VPD,BHT1VPD,BHT2BBC,BHT2
			if (trigId.isTrigger(370501) || trigId.isTrigger(370511) || trigId.isTrigger(370522) || trigId.isTrigger(370531))
			{
				triggerFired = true;
			}
			
			
			if (triggerFired)
			{
				
				blueFillNo   = pair1->runInfo().beamFillNumber(1); //1 = blue beam
				yellowFillNo = pair1->runInfo().beamFillNumber(0); //0 = yellow beam 

				sum = pair1->piPlusLV() + pair1->piMinusLV();
				sumB = sum; //blue beam.
				
				
				//yellow beam must rotate around y axis by pi so the eta cut can be the same for both beams. 				
				sumY = sum;
				sumY.RotateY(PI);

				//blue low limit eta is 0 yellow high limit eta is 0 this is a test
				if (sumB.Pt() >= lowLimitPt && sumB.Pt() <= hiLimitPt && sumB.M() >= lowLimitMass && sumB.M() <= hiLimitMass && sumB.Eta() >= lowLimitEta && sumB.Eta() <= hiLimitEta)
				{
					passInitialCut_B = true;
				}
				if (sumY.Pt() >= lowLimitPt && sumY.Pt() <= hiLimitPt && sumY.M() >= lowLimitMass && sumY.M() <= hiLimitMass && sumY.Eta() >= yellowLowLimitEta && sumY.Eta() <= hiLimitEta)
				{
					passInitialCut_Y = true;
				}
				
				if (passInitialCut_B && useBlueBeam)
				{
					//BLUE BEAM SPIN UP: spin bin 9 and 10
					if (pair1->spinBit() == 9 || pair1->spinBit() == 10)
					{						
						fillCorrectPtBin(hNumberUp_Pt, sumB, pair1->phiSR('b'), polOfBin_Pt, polarizationOfFill_B[blueFillNo],hPt);
						fillCorrectMassBin(hNumberUp_Mass, sumB, pair1->phiSR('b'), polOfBin_Mass, polarizationOfFill_B[blueFillNo],hMass);
						if(fullEta){fillCorrectEtaBin(hNumberUp_Eta, sumB, pair1->phiSR('b'), polOfBin_Eta, polarizationOfFill_B[blueFillNo],hEta);}
						
					}
					
					//BLUE BEAM SPIN DOWN: spin bin 5 and 6
					if (pair1->spinBit() == 5 || pair1->spinBit() == 6)
					{
						fillCorrectPtBin(hNumberDown_Pt, sumB, pair1->phiSR('b'), polOfBin_Pt, polarizationOfFill_B[blueFillNo],hPt);
						fillCorrectMassBin(hNumberDown_Mass, sumB, pair1->phiSR('b'), polOfBin_Mass, polarizationOfFill_B[blueFillNo],hMass);
						if(fullEta){fillCorrectEtaBin(hNumberDown_Eta, sumB, pair1->phiSR('b'), polOfBin_Eta, polarizationOfFill_B[blueFillNo],hEta);}
			
					}
				}//done with blue beam
				
				if (passInitialCut_Y && useYellowBeam)
				{
					//YELLOW BEAM SPIN UP: spin bin 6 and 10
					if (pair1->spinBit() == 6 || pair1->spinBit() == 10)
					{
						fillCorrectPtBin(hNumberUp_Pt, sumY, pair1->phiSR('y'), polOfBin_Pt, polarizationOfFill_Y[yellowFillNo],hPt);
						fillCorrectMassBin(hNumberUp_Mass, sumY, pair1->phiSR('y'), polOfBin_Mass, polarizationOfFill_Y[yellowFillNo],hMass);
						if(fullEta){fillCorrectEtaBin(hNumberUp_Eta, sumY, pair1->phiSR('y'), polOfBin_Eta, polarizationOfFill_Y[yellowFillNo],hEta);}
					
					}						
					
					//YELLOW BEAM SPIN DOWN: spin bit 5 and 9
					if (pair1->spinBit() == 5 || pair1->spinBit() == 9)
					{
						fillCorrectPtBin(hNumberDown_Pt, sumY, pair1->phiSR('y'), polOfBin_Pt, polarizationOfFill_Y[yellowFillNo],hPt);
						fillCorrectMassBin(hNumberDown_Mass, sumY, pair1->phiSR('y'), polOfBin_Mass, polarizationOfFill_Y[yellowFillNo],hMass);
						if(fullEta){fillCorrectEtaBin(hNumberDown_Eta, sumY, pair1->phiSR('y'), polOfBin_Eta, polarizationOfFill_Y[yellowFillNo],hEta);}
					}
				}//done with yellow beam
			}//end trigger check
		}//end radius check
	}//end pion tree loop
	

	
	
	//CALCULATE ASYMMETRY BIN BY BIN
	cout << "\n";
	cout << "<----CALCULATING ASYMMETRY---->" << endl;
	cout << "\n";
	
	
	
	double asymsPt[5]; 
	double asymsMass[5];
	double asymsEta[4];

	double asymsPtE[5];
	double asymsMassE[5];
	double asymsEtaE[4];
	
	cout << "\n";
	cout << "\n";

	cout << "\n \n calcing pt asym " << endl;
	calcAsym(hAut_Pt, hNumberUp_Pt, hNumberDown_Pt, polOfBin_Pt, asymsPt, asymsPtE);
	cout << "\n";
	cout << "\n";
	cout << "\n \n calcing mass asym " << endl;
	calcAsym(hAut_Mass, hNumberUp_Mass, hNumberDown_Mass, polOfBin_Mass, asymsMass, asymsMassE);
	cout << "\n";
	cout << "\n";
	if (fullEta)
	{
		cout << "\n \n calcing eta asym " << endl;	
		calcAsymEta(hAut_Eta, hNumberUp_Eta, hNumberDown_Eta, polOfBin_Eta, asymsEta, asymsEtaE);
	}

	
	
	
	//PLOT ASYMMETRIES
	cout << "\n";
	cout << "<----PLOTTING ASYMMETRIES---->" << endl;
	cout << "\n";
	
	double ptPoints[5];
	double ptPointsErr[5];
	double massPoints[5];
	double massPointsErr[5];
	double etaPoints[5];
	double etaPointsErr[5];
	
	
	getPtPoints(hPt, ptPoints, ptPointsErr);
	getMassPoints(hMass, massPoints, massPointsErr);
	if(fullEta){getEtaPoints(hEta, etaPoints, etaPointsErr);}
	
	
	TCanvas* cAsymPt = new TCanvas();
	TGraphErrors* gAsymPt = new TGraphErrors(nPtBins,ptPoints,asymsPt,ptPointsErr,asymsPtE);
	
	gAsymPt->Draw("AP");
	
	TCanvas* cAsymMass = new TCanvas();	
	TGraphErrors* gAsymMass = new TGraphErrors(nMassBins,massPoints,asymsMass,massPointsErr,asymsMassE);
	
	gAsymMass->Draw("AP");
	
	if (fullEta)
	{
		TCanvas* cAsymEta = new TCanvas();
		TGraphErrors* gAsymEta = new TGraphErrors(nEtaBins,etaPoints,asymsEta,etaPointsErr,asymsEtaE);
		gAsymEta->Draw("AP");
		
	}
	
	
	
	
	
	//DRAW HISTOGRAMS
	cout << "\n";
	cout << "<----DRAWING HISTOGRAMS---->" << endl;
	cout << "\n";
	
	
	
	
	TCanvas* cPt   = new TCanvas("cPt","cPt",1200,600);
	TCanvas* cMass = new TCanvas("cMass","cMass",1200,600);
	if(fullEta){TCanvas* cEta  = new TCanvas("cEta","cEta",800,600);}
	
	//drawAllBins(hPt, cPt);
	//drawAllBins(hMass, cMass);
	
	drawFiveBins(hAut_Pt, cPt);
	drawFiveBins(hAut_Mass, cMass);
  if(fullEta){drawFourBins(hAut_Eta, cEta);}
	
	TFile* outFile = new TFile(outFileName.c_str(),"recreate");
	
	writeFiveBins(hPt);
	writeFiveBins(hMass);
	writeFourBins(hEta);
	writeFiveBins(hAut_Pt);
	writeFiveBins(hAut_Mass);
	if(fullEta){writeFourBins(hAut_Eta);}
	gAsymPt->Write();
	gAsymMass->Write();
	if(fullEta){gAsymEta->Write();}
	/*
	cPt->SaveAs("./resultsNew_4_22/ptCanvasFullrangeLoEta.png");
	cPt->SaveAs("./resultsNew_4_22/ptCanvasFullrangeLoEta.pdf");
	cMass->SaveAs("./resultsNew_4_22/massCanvasFullrangeLoEta.png");
	cMass->SaveAs("./resultsNew_4_22/massCanvasFullrangeLoEta.pdf");
	
	if(fullEta)
	{
		cEta->SaveAs("./resultsNew_4_22/etaCanvasFullrangeHiEta.png");
		cEta->SaveAs("./resultsNew_4_22/etaCanvasFullrangeHiEta.pdf");
	}
	*/
	
	
	for (int ibin = 1; ibin <= 16; ibin++)
	{
		
		cout << "bin " << ibin << endl;
		cout << "Nup   = " << hNumberUp_Mass[0]->GetBinContent(ibin) << endl;
		cout << "Ndown = " << hNumberDown_Mass[0]->GetBinContent(ibin) << endl;

	}
	
	

	cout << "<----END---->" << endl; 


}
Beispiel #17
0
int main() {

TRandom3 u;
u.SetSeed(0);


vector <double> s_vec;
vector <double> mu_vec;


//Starting values for the param
//----------------------------
double  start_s, start_mu;
start_s=10;
start_mu=1;
s_vec.push_back(start_s); mu_vec.push_back(start_mu); 

// Read the data		data are the observables, fdata the density evaluated at data
//-------------
vector<double> data;
vector<double> fdata;
double temp_data,temp_fdata;
ifstream file("data.txt");
while (!file.eof()) {
file >> temp_data >> temp_fdata;
data.push_back(temp_data); fdata.push_back(temp_fdata);
}
data.pop_back(); fdata.pop_back();

//Function for likelihood
//---------------------
TF1* f1 = new TF1("density",density,-20,20,2);



const int nMCmax=1000;
//MCMC running
//-----------
for (int nMC=0; nMC<nMCmax; nMC++){
        double width=.1;
	s_vec.push_back(s_vec[nMC]+width*u.Gaus(0,1));
	mu_vec.push_back(mu_vec[nMC]+width*u.Gaus(0,1));

	double like_i=0; double like_f=0;
	for (int k=0; k<data.size(); k++){
	//initial likelihood
	//------------------ 
	f1->SetParameter(0,s_vec[nMC]);    f1->SetParameter(1,mu_vec[nMC]);
	like_i=like_i+log(f1->Eval(data[k]));
	//cout << k << "    " << like_i<< "    " <<data[k] << endl;
	//final likelihood
	//------------------ 
	f1->SetParameter(0,s_vec[nMC+1]);    f1->SetParameter(1,mu_vec[nMC+1]);
	like_f=like_f+log(f1->Eval(data[k]));
	}
	//cout << like_i<<"   "<<like_f<<"   "  <<s_vec[nMC]<<"   " << s_vec[nMC+1]<<"   " <<mu_vec[nMC]<<"   " << mu_vec[nMC+1]<< endl;
	//Acceptance probability
	//----------------------
	double prob_ratio=exp(like_f-like_i);
	double accept=TMath::Min(1.,prob_ratio);
	if (u.Binomial(1,accept)==0) {
	s_vec.pop_back(); mu_vec.pop_back(); 
	s_vec.push_back(s_vec[nMC]); mu_vec.push_back(mu_vec[nMC]);
	}
	cout <<accept << "    " << prob_ratio<<"    " << like_i<<"   "<<like_f<< "   " <<s_vec[nMC]<<"   " << s_vec[nMC+1]<<"   " <<mu_vec[nMC]<<"   " << mu_vec[nMC+1]<< endl;
	//cout << like_i<<"   "<<like_f<<"   "  <<s_vec[nMC]<<"   " << s_vec[nMC+1]<<"   " <<mu_vec[nMC]<<"   " << mu_vec[nMC+1]<< endl;
}
//End of MCMC running
//-----------

double s_tabl[nMCmax+1]; double mu_tabl[nMCmax+1];
double nMC_tabl[nMCmax+1]; 
for (int k=0; k<=nMCmax; k++) {
   nMC_tabl[k]=k;
   s_tabl[k]=s_vec[k]; mu_tabl[k]=mu_vec[k];
}



TGraph *gr_s = new TGraph (nMCmax, nMC_tabl, s_tabl);
gr_s->SetLineColor(kRed);
gr_s->SetLineWidth(2);
gr_s->SetName("Sigma");

TGraph *gr_mu = new TGraph (nMCmax, nMC_tabl, mu_tabl);
gr_mu->SetLineColor(kBlue);
gr_mu->SetLineWidth(2);
gr_mu->SetName("Mean");


TFile f("graph_MCMC_simplified.root","recreate");
 gr_s->Write(); gr_mu->Write();
f.Close();

return 0;
}
void flagMultCands( TString fname, TString tname ) {

  TFile *inFile = new TFile( fname, "UPDATE" );
  TTree *tree = (TTree*)inFile->Get( tname );

  if ( tree->FindBranch( "pass_multcand" ) ) {
    cout << "pass_multcand branch already exists so I won't add it" << endl;
    delete inFile;
    return;
  }

  ULong64_t  eventNumber;
  int        itype;
  bool       pass_bdt;
  bool       pass_pid;
  bool       pass_rhokst;
  bool       pass_massveto;
  UInt_t     nCandidate;
  ULong64_t  totCandidates;
  tree->SetBranchAddress(  "eventNumber"                 , &eventNumber                 );
  tree->SetBranchAddress(  "itype"                       , &itype                       );
  tree->SetBranchAddress(  "pass_bdt"                    , &pass_bdt                    );
  tree->SetBranchAddress(  "pass_pid"                    , &pass_pid                    );
  tree->SetBranchAddress(  "pass_rhokst"                 , &pass_rhokst                 );
  tree->SetBranchAddress(  "pass_massveto"               , &pass_massveto               );
  tree->SetBranchAddress(  "totCandidates"               , &totCandidates               );
  tree->SetBranchAddress(  "nCandidate"                  , &nCandidate                  );

  map< ULong64_t, ULong64_t > multCandEventNumbers;

  cout << "Finding multiple candidates" << endl;
  // first loop tree and save number of all multiple candidates
  for ( int ev=0; ev<tree->GetEntries(); ev++ ) {
    tree->GetEntry(ev);
    if ( ev%10000==0 ) cout << ev << "/" << tree->GetEntries() << endl;
    //if ( itype>0 && pass_bdt && pass_pid && (!pass_rhokst) && (!pass_massveto) && totCandidates > 1 ) {
    if ( itype>0 && pass_bdt && pass_pid && (!pass_massveto) && totCandidates > 1 ) {
      multCandEventNumbers[eventNumber] = totCandidates;
    }
  }

  // now randomly select which one to keep
  map< ULong64_t, UInt_t > eventToKeep;
  TRandom3 rand;
  rand.SetSeed(2016);
  for ( map<ULong64_t,ULong64_t>::iterator it=multCandEventNumbers.begin(); it!=multCandEventNumbers.end(); it++) {
    UInt_t keep = rand.Integer( it->second );
    eventToKeep[it->first] = keep;
  }

  cout << "Adding flag pass_multcand to tree" << endl;
  // then loop again and write the random choice back in
  bool pass_multcand;
  TBranch *bpt = tree->Branch( "pass_multcand", &pass_multcand, "pass_multcand/O" );

  for ( int ev=0; ev<tree->GetEntries(); ev++ ) {
    tree->GetEntry(ev);
    if ( ev%10000==0 ) cout << ev << "/" << tree->GetEntries() << endl;
    pass_multcand = true;
    if ( totCandidates > 1 && eventToKeep[eventNumber] != nCandidate ) pass_multcand = false;
    bpt->Fill();
  }
  tree->Write();
  delete inFile;
}
Beispiel #19
0
int xAna::HggTreeWriteLoop(const char* filename, int ijob, 
					  bool correctVertex, bool correctEnergy, 
					  bool setRho0
					  ) {

  //bool invDRtoTrk = false;


  if( _config == 0 ) {
    cout << " config file was not set properly... bail out" << endl;
    return -1;
  }

  if (fChain == 0) return -1;
  
  Long64_t nentries = fChain->GetEntriesFast();
  //  nentries = 10000;
  cout << "nentries: " << nentries << endl;  
  Long64_t entry_start = ijob    *_config->nEvtsPerJob();
  Long64_t entry_stop  = (ijob+1)*_config->nEvtsPerJob();
  if( _config->nEvtsPerJob() < 0 ) {
    entry_stop = nentries;
  }
  if( entry_stop  > nentries ) entry_stop = nentries;
  cout << "   *** doing entries from: " << entry_start << " -> " << entry_stop << endl;
  if( entry_start > entry_stop ) return -1;

  
  EnergyScaleReader enScaleSkimEOS; /// skim EOS bugged so need to undo the energy scale in the skim
  EnergyScaleReader enScale;
  //  enScaleSkimEOS.setup( "ecalCalibFiles/EnergyScale2012_Lisbon_9fb.txt" );
  enScale.setup( _config->energyScaleFile() );


  Float_t HiggsMCMass =  _weight_manager->getCrossSection()->getHiggsMass();
  Float_t HiggsMCPt   = -1;
  bool isHiggsSignal = false;
  if( HiggsMCMass > 0 ) isHiggsSignal = true;

  mode_ = _weight_manager->getCrossSection()->mode();
  isData = false;
  if(mode_==-1) isData = true;        

//  mode_ = ijob; //  

  DoCorrectVertex_ = correctVertex;
  DoCorrectEnergy_ = correctEnergy;
  DoSetRho0_ = setRho0;

  doJetRegression = _config->getDoJetRegression();
  doControlSample = _config->getDoControlSample();
  
  phoID_2011[0] = new TMVA::Reader("!Color:Silent");
  phoID_2011[1] = new TMVA::Reader("!Color:Silent");
  phoID_2012[0] = new TMVA::Reader("!Color:Silent");
  phoID_2012[1] = new TMVA::Reader("!Color:Silent");
  DiscriDiPho_2011 = new TMVA::Reader("!Color:Silent");
  DiscriDiPho_2012 = new TMVA::Reader("!Color:Silent");
  if(doJetRegression!=0) jetRegres = new TMVA::Reader("!Color:Silent");
  Setup_MVA();
  
  if( _config->setup() == "ReReco2011" )  for( int i = 0 ; i < 2; i++ ) phoID_mva[i] = phoID_2011[i];
  else                                    for( int i = 0 ; i < 2; i++ ) phoID_mva[i] = phoID_2012[i];

  MassResolution massResoCalc;
  massResoCalc.addSmearingTerm();
  if( _config->setup() == "ReReco2011" )  Ddipho_mva = DiscriDiPho_2011;
  else                                    Ddipho_mva = DiscriDiPho_2012;

  float Ddipho_cat[5]; Ddipho_cat[4] = -1; 
  if( _config->setup() == "ReReco2011" ) { Ddipho_cat[0] = 0.89; Ddipho_cat[1] = 0.72; Ddipho_cat[2] = 0.55; Ddipho_cat[3] = +0.05; }
  else                                   { Ddipho_cat[0] = 0.91; Ddipho_cat[1] = 0.79; Ddipho_cat[2] = 0.49; Ddipho_cat[3] = -0.05; }
  //  else                                   { Ddipho_cat[0] = 0.88; Ddipho_cat[1] = 0.71; Ddipho_cat[2] = 0.50; Ddipho_cat[3] = -0.05; }

  DiscriVBF_UseDiPhoPt = true;
  DiscriVBF_UsePhoPt   = true;
  DiscriVBF_cat.resize(2); DiscriVBF_cat[0] = 0.985; DiscriVBF_cat[1] = 0.93;
  DiscriVBF_useMvaSel  = _config->doVBFmvaCat();


  


  /// depending on the selection veto or not on electrons (can do muele, elemu,eleele)
  bool vetoElec[2] = {true,true};
  if( _config->invertElectronVeto() ) { vetoElec[0] = false; vetoElec[1] = false; }
  if( _config->isEleGamma()         ) { vetoElec[0] = false; vetoElec[1] = true ; }
  if( _config->isGammaEle()         ) { vetoElec[0] = true ; vetoElec[1] = false; }
  cout << " --------- veto electron config -----------" << endl;
  cout << " Leading  Pho VetoElec: " << vetoElec[0] << endl;
  cout << " Trailing Pho VetoElec: " << vetoElec[1] << endl;
  

  DoDebugEvent = true;
  
  bool DoPreselection = true;
  //  bool DoPrint = true;
  
  
  TString VertexFileNamePrefix;
  
  TRandom3 *rnd = new TRandom3();
  rnd->SetSeed(0);
  
  /// output tree and cross check file
   _xcheckTextFile.open(TString(filename)+".xcheck.txt");
   // _xcheckTextFile = cout;

  _minitree = new MiniTree( filename );
  TTree * tSkim = 0;
  if( _config->doSkimming() ) tSkim = (TTree*) fChain->CloneTree(0);

  InitHists();
  _minitree->mc_wXsec = _weight_manager->xSecW();
  _minitree->mc_wNgen = 100000./_weight_manager->getNevts();
  if( isData ) {
    _minitree->mc_wXsec = 1;
    _minitree->mc_wNgen = 1;
  }
    
  Int_t isprompt0 = -1;
  Int_t isprompt1 = -1;
  
  set<Long64_t> syncEvt;

  cout <<" ================ mode  "  << mode_   <<" ===============================  "<<endl;
  /// setupType has to be passed via config file
  //  photonOverSmearing overSmearICHEP("Test52_ichep");
  photonOverSmearing overSmearHCP( "oversmear_hcp2012" );
  photonOverSmearing overSmear(    _config->setup()    );
  int overSmearSyst = _config->getEnergyOverSmearingSyst();

  Long64_t nbytes = 0, nb = 0;
  ////////////////////////////////////////////////////////////////////////////
  //////////////////////////// Start the loop ////////////////////////////////
  ////////////////////////////////////////////////////////////////////////////
  vector<int>    nEvts;
  vector<string> nCutName;
  nCutName.push_back("TOTAL          :"); nEvts.push_back(0);
  nCutName.push_back("2 gammas       :"); nEvts.push_back(0);
  nCutName.push_back("triggers       :"); nEvts.push_back(0);
  nCutName.push_back("nan weight     :"); nEvts.push_back(0);
  nCutName.push_back("presel kin cuts:"); nEvts.push_back(0);
  nCutName.push_back("pass 2 gam incl:"); nEvts.push_back(0);
  nCutName.push_back("pass all       :"); nEvts.push_back(0);
  nCutName.push_back("   --> pass 2 gam lep: "); nEvts.push_back(0);
  nCutName.push_back("   --> pass 2 gam vbf: "); nEvts.push_back(0);

  vector<int> selVtxSumPt2(3);  selVtxSumPt2[0] = 0; selVtxSumPt2[1] = -1;   selVtxSumPt2[2] = -1;

  for (Long64_t jentry=entry_start; jentry< entry_stop ; ++jentry) {
    Long64_t ientry = LoadTree(jentry);

    if (ientry < -9999) break;
    if( jentry % 10000 == 0) cout<<"processing event "<<jentry<<endl;
    nb = fChain->GetEntry(jentry);   nbytes += nb;

    /// reset minitree variables
    _minitree->initEvent();

    // study mc truth block
    if( !isData ) {
      fillMCtruthInfo_HiggsSignal();
      _minitree->fillMCtrueOnly();
    }

    /// reco analysis
    unsigned icutlevel = 0;
    nEvts[icutlevel++]++;
    if( nPho < 2 ) continue; 
    nEvts[icutlevel++]++;
    
    /// set synchronisation flag
    if( syncEvt.find(event) != syncEvt.end() ) DoDebugEvent = true;
    else                                       DoDebugEvent = false;
    if( DoDebugEvent ) _xcheckTextFile << "==========================================================" << endl;
    if( DoDebugEvent ) _xcheckTextFile << "================= debugging event: " << event << endl;
    
    /// PU & BSz reweightings
    if( !isData ) {
      int itpu = 1;  /// 0 without OOT PU - 1 with OOT PU
      _minitree->mc_wPU  = _weight_manager->puW( nPU[itpu] );
     // PUwei  = _weight_manager->puWTrue( puTrue[itpu] );      
    }
    hTotEvents->Fill(1,_minitree->mc_wPU);


    
    bool sigWH = false ;
    bool sigZH = false ;    
    int  mc_whzh_type = 0;
    _minitree->mc_wHQT = 1;
    if( isHiggsSignal ) {
      if ( _weight_manager->getCrossSection()->getMCType() == "vh" ) 
      for( Int_t i=0; i < nMC && i <= 1; ++i ) { 
	  if( abs(mcPID[i]) == 24 ) sigWH=true;
	  if( abs(mcPID[i]) == 23 ) sigZH=true;
	}
      if( sigWH ) mc_whzh_type = 1;
      if( sigZH ) mc_whzh_type = 2;
      
      for( Int_t i=0; i<nMC; ++i)
      if ( abs(mcPID[i]) == 25 ) HiggsMCPt   = mcPt[i];

      if( _weight_manager->getCrossSection()->getMCType() == "ggh" && 
	  _config->setup().find( "ReReco2011" ) != string::npos )
	_minitree->mc_wHQT = getHqTWeight(HiggsMCMass, HiggsMCPt);      
    }
    


    
    if ((mode_ == 2 || mode_ ==1 ||  mode_ == 18 || mode_ == 19) && processID==18) continue;      
    
    // Remove double counting in gamma+jets and QCDjets
    
    Int_t mcIFSR_pho = 0;
    Int_t mcPartonic_pho = 0;
    if (mode_ == 1 || mode_ == 2 || mode_ == 3  ||  mode_ == 18 ||  mode_ == 19 ) {
      for (Int_t i=0; i<nMC; ++i) {    
	if (mcPID[i] == 22 && (fabs(mcMomPID[i]) < 6 || mcMomPID[i] == 21)) mcIFSR_pho++;
	if (mcPID[i] == 22 && mcMomPID[i] == 22) mcPartonic_pho++;
      }
    }
    
    // if pythia is used for diphoton.. no IFSR removing from QCD and Gjets!!!!!!      
    if ((mode_==1 || mode_ == 2  ||   mode_ == 18 ) && mcIFSR_pho >= 1 && mcPartonic_pho >=1) continue;
    if ((mode_ == 3 ||  mode_ == 19 )&& mcIFSR_pho == 2) continue;   

 
    bool prompt2= false;
    bool prompt1= false;
    bool prompt0= false;
    vertProb = -1;
    
    if (mode_ == 2  || mode_ == 1    ||   mode_ == 18     ){
      if      ( mcPartonic_pho >= 1 &&  mcIFSR_pho >= 1 ) prompt2 = true;
      else if ( mcPartonic_pho >= 1 &&  mcIFSR_pho == 0 ) prompt1 = true;
      else if ( mcPartonic_pho == 0 &&  mcIFSR_pho == 0 ) prompt0 = true;
    } else if(mode_ == 3 ||  mode_ == 19   ){
      if      ( mcIFSR_pho >= 2 ) prompt2 = true;
      else if ( mcIFSR_pho == 1 ) prompt1 = true;
      else if ( mcIFSR_pho == 0 ) prompt0 = true;
      if( prompt1 ) _minitree->mc_wXsec = 1.3*_weight_manager->xSecW();
    }
    
    if(mode_==1 || mode_==2 || mode_==3 || mode_==18 || mode_==19){
      if(prompt0)isprompt0=1;
      else isprompt0=0;
      if(prompt1)isprompt1=1;
      else isprompt1=0;
    }
    
    if( mode_ == 20 && isZgamma() ) continue;

    /// wei weight is just temporary and may not contain all info.
    float wei = _minitree->mc_wXsec * _minitree->mc_wPU  
      * _minitree->mc_wNgen * _minitree->mc_wHQT;

    if( isData && !PassTriggerSelection() ) continue;      nEvts[icutlevel++]++;
    if( std::isinf( wei ) || std::isnan( wei ) )continue;  nEvts[icutlevel++]++;
    
    
    
    //// ********************* define S4 variable **********************////
    for( int i=0; i<nPho; ++i){
      if( _config->setup() == "ReReco2011" ) phoS4ratio[i] = 1;
      else                                   phoS4ratio[i] = phoE2x2[i] / phoE5x5[i];
    }
    //// ************************************************************* ////

    if( !isData ) {
      //// ************** MC corrections (mostly MC) ******************* //// 
      // 1. energy shifting / smearing
      for( int i=0; i<nPho; ++i)
	if( fabs(phoSCEta[i]) <= 2.5 ) {
	  float smearing = overSmear.randOverSmearing(phoSCEta[i],phoR9[i],isInGAP_EB(i),overSmearSyst);
	  phoRegrE[i] *= (1 + smearing); 
	  phoE[i]     *= (1 + smearing); 
	  /// from MassFactorized in gglobe:   energyCorrectedError[ipho] *=(l.pho_isEB[ipho]) ? 1.07 : 1.045 ;
	  float smearFactor = 1;
	  if( _config->setup() == "ReReco2011" ) smearFactor = fabs(phoSCEta[i]) < 1.45 ? 1.07: 1.045;
	  phoRegrErr[i] *= smearFactor;
	}  
      
      
      // 2. reweighting of photon id variables (R9...)
      for (int i=0; i<nPho; ++i) ReweightMC_phoIdVar(i);
      //// ************************************************************* ////
    }
    
    //// ********** Apply regression energy ************* ////
    float phoStdE[500];
    for( int i=0; i<nPho; ++i)
      if( fabs(phoSCEta[i]) <= 2.5 ) {
	if( isData ){
	  float enCorrSkim = 1;//enScaleSkimEOS.energyScale( phoR9[i], phoSCEta[i], run);
	  float phoEnScale = enScale.energyScale( phoR9[i], phoSCEta[i], run)/enCorrSkim;
	  phoRegrE[i]  *= phoEnScale;
	  phoE[i]      *= phoEnScale;
	}
	phoStdE[i] = phoE[i];
	phoE[i]   = phoRegrE[i];
	
	/// transform calo position abd etaVtx, phiVtx with SC position
	for( int x = 0 ; x < 3; x++ )  phoCaloPos[i][x] = phoSCPos[i][x];
	for( int ivtx = 0 ; ivtx < nVtxBS; ivtx++ ) {
	  TVector3 xxi = getCorPhotonTVector3(i,ivtx);
	  phoEtaVtx[i][ivtx] = xxi.Eta();
	  phoPhiVtx[i][ivtx] = xxi.Phi();
	}
	
	/// additionnal smearing to go to data energy resolution
	phoRegrSmear[i] = phoE[i]*overSmearHCP.meanOverSmearing(phoSCEta[i],phoR9[i],isInGAP_EB(i),0);
	phoEt[i] = phoE[i] / cosh(phoEta[i]);  
      }    
    //// ************************************************* ////
     

    /// lepton selection
    int iElecVtx(-1), iMuonVtx(-1);
    vector<int> elecIndex = selectElectronsHCP2012( wei, iElecVtx );
    vector<int> muonIndex = selectMuonsHCP2012(     wei, iMuonVtx );

    vector<int>             event_vtx; 
    vector<int>             event_ilead ;
    vector<int>             event_itrail;
    vector<TLorentzVector>  event_plead ;
    vector<TLorentzVector>  event_ptrail;
    TLorentzVector leptag;
    
    int lepCat = -1;
    bool exitLoop = false;
    for( int ii = 0     ; ii < nPho ; ++ii ) {
      for( int jj = (ii+1); jj < nPho ; ++jj ) {
	// Preselection 2nd leg
	if (DoPreselection && !preselectPhoton(ii,phoEt[ii])) continue;
	if (DoPreselection && !preselectPhoton(jj,phoEt[jj])) continue;
	
	/// define i, j locally, so when they are inverted this does not mess up the loop
	int i = ii; 
	int j = jj;
	if(phoEt[j] > phoEt[i]){ i = jj; j = ii; }	  
	
	// Select vertex
	int selVtx  = 0;
	TLorentzVector gi,gj;
	double mij(-1);
	
	vector<int> selVtxIncl;      
	if(_config->vtxSelType()==0)
	  selVtxIncl = getSelectedVertex(i,j,true,true );
	else //use sumpt2 ranking
	  selVtxIncl = selVtxSumPt2;
	selVtx = selVtxIncl[0];
	if( selVtx < 0 ) continue;

	/// check lepton tag
	if( muonIndex.size() > 0 ) {
	  //selVtx = iMuonVtx;	  
	  leptag.SetPtEtaPhiM( muPt[muonIndex[0]], muEta[muonIndex[0]], muPhi[muonIndex[0]],0);
	  if( selectTwoPhotons(i,j,selVtx,gi,gj,vetoElec) ) {
	    lepCat = 0;
	  }
	}
	
	/// check electron tag only if muon tag failed
	if( elecIndex.size() > 0 && lepCat == -1 ) {
	  //selVtx = iElecVtx;
	  leptag.SetPtEtaPhiM( elePt[elecIndex[0]], eleEta[elecIndex[0]], elePhi[elecIndex[0]],0);
	  if( selectTwoPhotons(i,j,selVtx,gi,gj,vetoElec) ) {
	    lepCat = 1;
	    if( fabs( (leptag+gi).M() - 91.19 ) < 10 || fabs( (leptag+gj).M() - 91.19 ) < 10 ) lepCat = -1;
	    /// this is not actually the cut, but it should be but ok (dR(pho,eleTrk) > 1 no dR(pho,anyTrk) > 1 )
	    if(phoCiCdRtoTrk[i] < 1 || phoCiCdRtoTrk[j] <1 ) lepCat = -1;
	  }
	}
	

	if( lepCat >= 0 ) {
	  mij = (gi+gj).M();
          if( _config->analysisType() == "MVA" )
	        if( gi.Pt() / mij < 45./120. || gj.Pt() / mij < 30./120. ) lepCat = -1;
          if( _config->analysisType() == "baselineCiC4PF" )
	        if( gi.Pt() / mij < 45./120. || gj.Pt() < 25. ) lepCat = -1;
	  if( leptag.DeltaR(gi) < 1.0  || leptag.DeltaR(gj) < 1.0  ) lepCat = -1;
	}
	if( lepCat >= 0 ) {
	  cout << " ****** keep leptag event pts[photons] i: " << i << " j: " << j << "   -> event: " << ientry <<  endl;
	  cout << "        leptonCat: " << lepCat << endl;
	  /// if one pair passes lepton tag then no need to go further
	  /// fill in variables
	  event_vtx.resize(   1); event_vtx[0]    = selVtx;
	  event_ilead.resize( 1); event_ilead[0]  = i;
	  event_itrail.resize(1); event_itrail[0] = j;
	  event_plead.resize( 1); event_plead[0]  = gi;
	  event_ptrail.resize(1); event_ptrail[0] = gj;
	  exitLoop = true;
	  break;	
	} else {
	  /// inclusive + VBF + MetTag preselection
	  
	  /// apply kinematic cuts
	  if( !selectTwoPhotons(i,j,selVtx,gi,gj,vetoElec) ) continue;
	  /// drop photon pt cuts from inclusive cuts (add them in categorisation only)
	  mij = (gi+gj).M();	
	  if( ! _config->doSkimming() && 
	      ( gi.Pt()     < _config->pt1Cut() || gi.Pt() < _config->pt2Cut() ||
		gi.Pt()/mij < _config->loosePt1MCut() ||
		gj.Pt()/mij < _config->loosePt2MCut() ) ) continue;
	}
	
	/// here i = lead; j = trail (selectTwoPhotons does that)
	/// fill in variables
	event_vtx.push_back( selVtx );
	event_ilead.push_back(   i  );
	event_itrail.push_back(  j  );
	event_plead.push_back(  gi  );
	event_ptrail.push_back( gj  );   	  
      }
      if( exitLoop ) break;
    }
      
    if(event_ilead.size()==0 || event_itrail.size()==0)continue;
    if(event_vtx.size() == 0 ) continue;  // no pairs selected
    nEvts[icutlevel++]++;

    // Now decide which photon-photon pair in the event to select
    // for lepton tag (size of arrays is 1, so dummy selection)
    unsigned int selectedPair = 0;
    float sumEt = -1;
    for (unsigned int p=0; p < event_vtx.size(); p++) {
      float tempSumEt = event_plead[p].Pt() + event_ptrail[p].Pt();
      if( tempSumEt > sumEt) {
	sumEt = tempSumEt;
      selectedPair = p;
      }
    } 
    

    int ilead  = event_ilead[  selectedPair ];
    int itrail = event_itrail[ selectedPair ];
    int selVtx = event_vtx[    selectedPair ];
    TLorentzVector glead  = event_plead[selectedPair];
    TLorentzVector gtrail = event_ptrail[selectedPair];
    TLorentzVector hcand  = glead + gtrail;

    int CAT4 = cat4(phoR9[ilead], phoR9[itrail], phoSCEta[ilead], phoSCEta[itrail]);
    
    if( glead.Pt()  < _config->pt1Cut() ) continue;
    if( gtrail.Pt() < _config->pt2Cut() ) continue;
    if( hcand.M()   < _config->mggCut() ) continue;
    nEvts[icutlevel++]++;

    _minitree->mtree_runNum = run;
    _minitree->mtree_evtNum = event;
    _minitree->mtree_lumiSec = lumis;

    //    TLorentzVector g1,g2;
    //    g1.SetPtEtaPhiM(phoE[ilead ]/cosh(phoEta[ilead]),phoEta[ilead ], phoPhi[ilead ], 0);
    //    g2.SetPtEtaPhiM(phoE[itrail]/cosh(phoEta[ilead]),phoEta[itrail], phoPhi[itrail], 0);
    //    TLorentzVector lgg = g1 + g2;
    //_minitree->mtree_massDefVtx = lgg.M();
    _minitree->mtree_massDefVtx = hcand.M()/sqrt(phoE[ilead]*phoE[itrail])*sqrt(phoStdE[ilead]*phoStdE[itrail]);

    // calc again vertex to get correct vertex probability (can be different from last one in loop)
    vector<int> sortedVertex;
    if(_config->vtxSelType()==0)
      sortedVertex = getSelectedVertex( ilead, itrail, true, true );
    else //use sumpt2 ranking
      sortedVertex = selVtxSumPt2;

    if( sortedVertex.size() < 2 ) sortedVertex.push_back(-1);
    if( sortedVertex.size() < 3 ) sortedVertex.push_back(-1);

    if( lepCat >= 0 ) {
      /// lepton tag
      sortedVertex[0] = selVtx;  
      sortedVertex[1] = -1; 
      sortedVertex[2] = -1; 
      //      vertProb = 1;
    } 

    _minitree->mtree_rho   = rho2012;
    _minitree->mtree_rho25 = rho25;    
    _minitree->mtree_zVtx  = vtxbs[selVtx][2];
    _minitree->mtree_nVtx  = nVtxBS;
    _minitree->mtree_ivtx1 = selVtx;
    _minitree->mtree_ivtx2 = sortedVertex[1];
    _minitree->mtree_ivtx3 = sortedVertex[2];
    _minitree->mtree_vtxProb = vertProb;
    _minitree->mtree_vtxMva  = vertMVA;

    _minitree->mtree_mass  = hcand.M();
    _minitree->mtree_pt    = hcand.Pt();
    _minitree->mtree_piT   = hcand.Pt()/hcand.M();
    _minitree->mtree_y     = hcand.Rapidity();

    /// spin variables
    TLorentzVector gtmp1 = glead;  gtmp1.Boost( -hcand.BoostVector() );
    TLorentzVector gtmp2 = gtrail; gtmp2.Boost( -hcand.BoostVector() );
    _minitree->mtree_cThetaLead_heli  = cos( gtmp1.Angle(hcand.BoostVector()) );
    _minitree->mtree_cThetaTrail_heli = cos( gtmp2.Angle(hcand.BoostVector()) );
    _minitree->mtree_cThetaStar_CS    = 2*(glead.E()*gtrail.Pz() - gtrail.E()*glead.Pz())/(hcand.M()*sqrt(hcand.M2()+hcand.Pt()*hcand.Pt()));
    
    /// fill photon id variables in main tree
    _minitree->mtree_minR9      = +999;
    _minitree->mtree_minPhoIdEB = +999;
    _minitree->mtree_minPhoIdEE = +999;
    _minitree->mtree_maxSCEta   =   -1;
    _minitree->mtree_minSCEta   = +999;
    for( int i = 0 ; i < 2; i++ ) {
      int ipho = -1;
      if( i == 0 ) ipho = ilead;
      if( i == 1 ) ipho = itrail;
      fillPhotonVariablesToMiniTree( ipho, selVtx, i );      
      if( _minitree->mtree_r9[i] < _minitree->mtree_minR9 ) _minitree->mtree_minR9 = _minitree->mtree_r9[i];
      if( fabs( _minitree->mtree_sceta[i] ) <  1.5 &&  _minitree->mtree_mvaid[i] <  _minitree->mtree_minPhoIdEB ) _minitree->mtree_minPhoIdEB = _minitree->mtree_mvaid[i];
      if( fabs( _minitree->mtree_sceta[i] ) >= 1.5 &&  _minitree->mtree_mvaid[i] <  _minitree->mtree_minPhoIdEE ) _minitree->mtree_minPhoIdEE = _minitree->mtree_mvaid[i];
      if( fabs( _minitree->mtree_sceta[i] ) > _minitree->mtree_maxSCEta ) _minitree->mtree_maxSCEta =  fabs(_minitree->mtree_sceta[i]);
      if( fabs( _minitree->mtree_sceta[i] ) < _minitree->mtree_minSCEta ) _minitree->mtree_minSCEta =  fabs(_minitree->mtree_sceta[i]);
    }
    
    //------------ compute diphoton mva (add var to minitree inside function) ----------------//
    massResoCalc.setP4CalPosVtxResoSmear( glead,gtrail, 
					  TVector3(phoCaloPos[ilead ][0], phoCaloPos[ilead ][1],phoCaloPos[ilead ][2]),
					  TVector3(phoCaloPos[itrail][0], phoCaloPos[itrail][1],phoCaloPos[itrail][2]),
					  TVector3(vtxbs[selVtx][0], vtxbs[selVtx][1], vtxbs[selVtx][2]),
					  _minitree->mtree_relResOverE, _minitree->mtree_relSmearing );

    
    _minitree->mtree_massResoTot = massResoCalc.relativeMassResolutionFab_total( vertProb );    
    _minitree->mtree_massResoEng = massResoCalc.relativeMassResolutionFab_energy( );    
    _minitree->mtree_massResoAng = massResoCalc.relativeMassResolutionFab_angular();    
   
    float diphotonmva = DiPhoID_MVA( glead, gtrail, hcand, massResoCalc, vertProb, 
				     _minitree->mtree_mvaid[0],_minitree->mtree_mvaid[1] );

    
    // ---- Start categorisation ---- //
    _minitree->mtree_lepTag  = 0;
    _minitree->mtree_metTag  = 0;
    _minitree->mtree_vbfTag  = 0;
    _minitree->mtree_hvjjTag = 0;

    // 1. lepton tag
    if( lepCat >= 0 ) {
      _minitree->mtree_lepTag = 1;
      _minitree->mtree_lepCat = lepCat;
      _minitree->mtree_fillLepTree  = true;
      // if( lepCat == 0 ) fillMuonTagVariables(lepTag,glead,gtrail,elecIndex[0],selVtx);
      // if( lepCat == 1 ) fillElecTagVariables(lepTag,glead,gtrail,muonIndex[0],selVtx);
    }

    // 3. met tag (For the jet energy regression, MET needs to be corrected first.)
    _minitree->mtree_rawMet    = recoPfMET;
    _minitree->mtree_rawMetPhi = recoPfMETPhi;
    //    if( !isData ) {
      /// bug in data skim, met correction already applied
      //3.1 Soft Jet correction (FC?)    
      applyJEC4SoftJets();
      //3.2 smearing
      if( !isData ) METSmearCorrection(ilead, itrail);
      //3.3 shifting (even in data? but different in data and MC)
      METPhiShiftCorrection();
      //3.4 scaling
      if( isData) METScaleCorrection(ilead, itrail);
      //    }
    _minitree->mtree_corMet    = recoPfMET;
    _minitree->mtree_corMetPhi = recoPfMETPhi;
    
    // 2. dijet tag
    Int_t nVtxJetID = -1;
    if( _config->doPUJetID() ) nVtxJetID = nVtxBS;
    //vector<int> goodJetsIndex = selectJets( ilead, itrail, nVtxJetID, wei, selVtx );
    vector<int> goodJetsIndex = selectJetsJEC(  ilead, itrail, nVtxJetID, wei, selVtx );
    int vbftag(-1),hstratag(-1),catjet(-1);
    dijetSelection( glead, gtrail, goodJetsIndex, wei, selVtx, vbftag, hstratag, catjet);
    _minitree->mtree_vbfTag  = vbftag;
    _minitree->mtree_hvjjTag = hstratag;
    _minitree->mtree_vbfCat  = catjet;      

    // 2x. radion analysis

    // take the very same photon candidates as in the H->GG analysis above
    _minitree->radion_evtNum = event;
    *(_minitree->radion_gamma1) = glead;
    *(_minitree->radion_gamma2) = gtrail;

    vector<int> goodJetsIndexRadion = selectJetsRadion(nVtxJetID, selVtx);
    _minitree->radion_bJetTags->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_genJetPt        ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_eta             ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_cef		  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_nef		  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_mef		  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_nconstituents	  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_chf		  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_JECUnc	  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_ptLeadTrack	  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_vtxPt		  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_vtx3dL	  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_SoftLeptPtCut	  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_dPhiMETJet	  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_nch		  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_vtx3deL	  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_vtxMass	  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_ptRaw		  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_EnRaw		  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_SoftLeptptRelCut->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_SoftLeptdRCut	  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_partonID	  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_dRJetGenJet         ->Set(goodJetsIndexRadion.size());
    _minitree->radion_MET = recoPfMET;
    _minitree->radion_rho25 = rho25;

    for (unsigned i = 0; i < goodJetsIndexRadion.size(); i++) {
      int iJet = goodJetsIndexRadion[i];

      //_minitree->radion_bJetTags->AddAt(jetCombinedSecondaryVtxMVABJetTags[iJet], i);
      _minitree->radion_bJetTags->AddAt(jetCombinedSecondaryVtxBJetTags[iJet], i);
      _minitree->radion_jet_genJetPt         ->AddAt(jetGenJetPt[iJet], i);
      _minitree->radion_jet_eta              ->AddAt(jetEta[iJet], i);
      _minitree->radion_jet_cef		     ->AddAt(jetCEF[iJet], i);
      _minitree->radion_jet_nef		     ->AddAt(jetNEF[iJet], i);
      _minitree->radion_jet_mef		     ->AddAt(jetMEF[iJet], i);
      _minitree->radion_jet_nconstituents    ->AddAt(jetNConstituents[iJet], i);
      _minitree->radion_jet_chf		     ->AddAt(jetCHF[iJet], i);
      _minitree->radion_jet_JECUnc	     ->AddAt(jetJECUnc[iJet], i);
      _minitree->radion_jet_ptLeadTrack	     ->AddAt(jetLeadTrackPt[iJet], i);
      _minitree->radion_jet_vtxPt	     ->AddAt(jetVtxPt[iJet], i);
      _minitree->radion_jet_vtx3dL	     ->AddAt(jetVtx3dL[iJet], i);
      _minitree->radion_jet_SoftLeptPtCut    ->AddAt(jetSoftLeptPt[iJet], i);
      _minitree->radion_jet_nch		     ->AddAt(jetNCH[iJet], i);
      _minitree->radion_jet_vtx3deL	     ->AddAt(jetVtx3deL[iJet], i);
      _minitree->radion_jet_vtxMass	     ->AddAt(jetVtxMass[iJet], i);
      _minitree->radion_jet_ptRaw	     ->AddAt(jetRawPt[iJet], i);
      _minitree->radion_jet_EnRaw	     ->AddAt(jetRawEn[iJet], i);
      _minitree->radion_jet_SoftLeptptRelCut ->AddAt(jetSoftLeptPtRel[iJet], i);
      _minitree->radion_jet_SoftLeptdRCut    ->AddAt(jetSoftLeptdR[iJet], i);
      _minitree->radion_jet_partonID	     ->AddAt(jetPartonID[iJet], i);
      _minitree->radion_jet_dRJetGenJet      ->AddAt(sqrt(pow(jetEta[iJet]-jetGenEta[iJet],2)+pow(jetPhi[iJet]-jetGenPhi[iJet],2)), i);
      float tmpPi = 3.1415927, tmpDPhi=fabs(jetPhi[iJet]-recoPfMETPhi);
      if(tmpDPhi>tmpPi) tmpDPhi=2*tmpPi-tmpDPhi;
      _minitree->radion_jet_dPhiMETJet	     ->AddAt(tmpDPhi, i);

      TLorentzVector* jet = new((*(_minitree->radion_jets))[_minitree->radion_jets->GetEntriesFast()]) TLorentzVector();
      jet->SetPtEtaPhiE(jetPt[iJet], jetEta[iJet], jetPhi[iJet], jetEn[iJet]);
    }

    // Continue step 3.
    if (  MetTagSelection(glead,gtrail,goodJetsIndex) && _minitree->mtree_vbfTag == 0 && _minitree->mtree_lepTag == 0   && 
	 _minitree->mtree_corMet > 70.  &&	 
	 fabs( phoSCEta[ilead] ) < 1.45 && fabs( phoSCEta[itrail]) < 1.45 ) _minitree->mtree_metTag = 1;

    //----------- categorisation (for now incl + vbf + lep + met) -----------//
    _minitree->mtree_catBase = CAT4;
    _minitree->mtree_catMva  = -1;
    for( int icat_mva = 0 ; icat_mva < 4; icat_mva++ )
      if( diphotonmva >= Ddipho_cat[icat_mva] ) { _minitree->mtree_catMva = icat_mva; break; }
    if       ( _minitree->mtree_lepTag == 1 ) {
      _minitree->mtree_catBase = _minitree->mtree_lepCat + 6;
      _minitree->mtree_catMva  = _minitree->mtree_lepCat + 6;
    } else if( _minitree->mtree_vbfTag == 1 ) {
      _minitree->mtree_catBase = _minitree->mtree_vbfCat + 4;
      _minitree->mtree_catMva  = _minitree->mtree_vbfCat + 4;
    } else if( _minitree->mtree_metTag == 1 ) {
      _minitree->mtree_catBase = 8;
      _minitree->mtree_catMva  = 8;
    }
    if( diphotonmva < Ddipho_cat[3] )  _minitree->mtree_catMva  = -1;
    
    /// photon pt cut was dropped from the inclusive cuts
    if(  _minitree->mtree_catMva  < 4 && (glead.Pt()/hcand.M() < 1./3. || gtrail.Pt()/hcand.M() < 1./4.) ) 
       _minitree->mtree_catMva  = -1;

    if(  _minitree->mtree_catBase < 4 && (glead.Pt()/hcand.M() < 1./3. || gtrail.Pt()/hcand.M() < 1./4.) ) 
       _minitree->mtree_catBase  = -1;
    
    //------------ MC weighting factors and corrections    
    if( !isData ) {
      /// needs to be recomputed for each event (because reinit var for each event)
      _minitree->mc_wNgen = 100000./_weight_manager->getNevts();
      _minitree->mc_wXsec  = _weight_manager->xSecW(mc_whzh_type);      
      if( ( mode_ == 3 ||  mode_ == 19 ) && isprompt1 == 1 ) _minitree->mc_wXsec  *= 1.3;
      _minitree->mc_wBSz   = _weight_manager->bszW(vtxbs[selVtx][2]-mcVtx[0][2]);
      _minitree->mc_wVtxId = _weight_manager->vtxPtCorrW( hcand.Pt() );
      
      /// photon identification
      float wPhoId[] = { 1., 1.};
      for( int i = 0 ; i < 2; i++ ) {
	wPhoId[i] = 1;
	int index = -1;
	if( i == 0 ) index = ilead;
	if( i == 1 ) index = itrail;
	wPhoId[i] *= _weight_manager->phoIdPresel(phoR9[index],phoSCEta[index]);
	if( _config->analysisType() == "baselineCiC4PF" ) wPhoId[i] *= _weight_manager->phoIdCiC(phoR9[index],phoSCEta[index]);
	if( _config->analysisType() == "MVA"            ) wPhoId[i] *= _weight_manager->phoIdMVA(phoR9[index],phoSCEta[index]);
	if( vetoElec[i] ) wPhoId[i] *= _weight_manager->phoIdEleVeto(phoR9[index],phoSCEta[index]);	      
      }
      _minitree->mc_wPhoEffi   = wPhoId[0]*wPhoId[1];
      
      /// trigger efficiency
      _minitree->mc_wTrigEffi = 0.9968; /// FIX ME

      /// cross section volontary not included in total weight
      _minitree->mc_wei = 
	_minitree->mc_wPU       *
	_minitree->mc_wBSz      *
	_minitree->mc_wHQT      *  /// = 1 but in 2011
	_minitree->mc_wVtxId    *
	_minitree->mc_wPhoEffi  *
	_minitree->mc_wTrigEffi *
	_minitree->mc_wNgen;

      wei =  _minitree->mc_wei;
    }
    nEvts[icutlevel++]++;
    if( _minitree->mtree_lepTag ) nEvts[icutlevel+0]++;
    if( _minitree->mtree_vbfTag ) nEvts[icutlevel+1]++;
    
    //// following crap can be removed when the synchornization will be successfull. 
    if( DoDebugEvent ) {
      _minitree->setSynchVariables();
      _xcheckTextFile << " pho1 pos: " << phoPos[ilead]  << endl;
      _xcheckTextFile << " ieta1 : " << phoSeedDetId1[ilead] << " iphi1: " << phoSeedDetId2[ilead] << endl;
      _xcheckTextFile << " pho2 pos: " << phoPos[itrail] << endl;
      _xcheckTextFile << " ieta1 : " << phoSeedDetId1[itrail] << " iphi1: " << phoSeedDetId2[itrail] << endl;

      _xcheckTextFile << " oversmear 1: " << overSmear.meanOverSmearing(phoSCEta[ilead],phoR9[ilead]  ,isInGAP_EB(ilead),0) << endl;
      _xcheckTextFile << " oversmear 2: " << overSmear.meanOverSmearing(phoSCEta[itrail],phoR9[itrail],isInGAP_EB(itrail),0) << endl;
      _xcheckTextFile << " mass reso (eng only): " << _minitree->mtree_massResoEng << endl;
      _xcheckTextFile << " mass reso (ang only): " << _minitree->mtree_massResoAng << endl;

      for( unsigned i = 0 ; i < _minitree->sync_iName.size(); i++ )
	cout  << _minitree->sync_iName[i] << ":" << *_minitree->sync_iVal[i]  << "  ";
      for( unsigned i = 0 ; i < _minitree->sync_lName.size(); i++ )
	cout << _minitree->sync_lName[i] << ":" << *_minitree->sync_lVal[i]  << "  ";
      for( unsigned i = 0 ; i < _minitree->sync_fName.size(); i++ )
	cout << _minitree->sync_fName[i] << ":" << *_minitree->sync_fVal[i]  << "  ";
      cout << endl;	
      

      cout << "  myVtx = " << selVtx << "; 1=" << sortedVertex[1] << " 2= " << sortedVertex[2] << endl;
      for( int ivtx = 0; ivtx < nVtxBS; ivtx++ ) {
	cout << " etas[ ivtx = " << ivtx << "] = " << phoEtaVtx[ilead][ivtx] << " - " << phoEtaVtx[itrail][ivtx] << "  - zVtx = " << vtxbs[ivtx][2] << endl;

      }
    }

    _minitree->fill();    
    if( _config->doSkimming() && tSkim ) {
      /// undo all modifs before filling the skim
      fChain->GetEntry(jentry);
      tSkim->Fill();
    }
    //---------------      
    
  //   }    
  }// end for entry
  if( _config->doSkimming() ) {
    _minitree->mtree_file->cd();
    TH1F *hEvents = new TH1F("hEvents","hEvents",2,0,2);
    hEvents->SetBinContent(1,_weight_manager->getNevts());
    hEvents->SetBinContent(2,nEvts[nEvts.size()-1]);
    hEvents->Write();
    tSkim->Write();
    _minitree->mtree_file->Close();
  } else  _minitree->end();

  for( unsigned icut = 0 ; icut < nEvts.size(); icut++ )
    cout << nCutName[icut] << nEvts[icut] << endl;
  
  delete rnd;  

  return nEvts[nEvts.size()-1];
}
Beispiel #20
0
int main() 
{
#ifndef NO_ROOT
	TRandom3 r;r.SetSeed( (unsigned)time(NULL) ) ;
	FindMatch A;
	A.SetMaxWindow(1); 
	// create a basic spill random time distributions
	vector<uint64_t> t;	
	uint64_t lastTime=100;
	for(int i=0;i<200; ++i) // ~ eventInSPill
	{
		lastTime +=  TMath::Floor(r.Uniform(5,30.) );
		t.push_back(lastTime);
	}
	vector<uint64_t> time1,time2;

	// with a certain probability k, accept time1, time2. Smear time2 guas + a constant diff
	uint64_t delta=TMath::Floor(r.Uniform(10,100) );
	for(unsigned int i=0; i<t.size(); ++i)
		{
			// 0.0005 for 2000
		if (r.Uniform() > 0.05) time1.push_back(t[i]);
		if (r.Uniform() > 0.05) time2.push_back(
				TMath::Floor( r.Gaus(t[i],1.1) ) + delta
				);
		}
	// 
	A.SetTimes(time1,time2);
	printf("------- START -------\n");
	printf("-- >  t.size = %lu\n",t.size());
	printf("-- >  t1.size = %lu\n",time1.size());
	printf("-- >  t2.size = %lu\n",time2.size());
	long max=TMath::Max(time1.size(),time2.size());
	long diff=TMath::Abs(long(time1.size()) -long(time2.size()) ) + A.GetMaxWindow() ;
	double time = pow(max,diff) * 0.11/220.; // 116 ms -- ad hoc factors
	string timeStr="";
	if (time > 3600 ) 
		{
		long h=TMath::Floor(time/3600.);
		timeStr += Form("%ld h  ",h);
		time -= 3600*h;
		}
	if(time >60 ) 
		{
		long m=TMath::Floor(time/60.);
		timeStr += Form("%ld m  ",m);
		time -= 60*m;
		}
	timeStr += Form("%lf s",time);
	printf("-- >  time unit estimation = %s\n", timeStr.c_str());
	//uint64_t myStart=(uint64_t)time(NULL);
	timeval tv_start; 
	gettimeofday(&tv_start,NULL);
	int status=A.Run();
	//uint64_t myStop=(uint64_t)time(NULL);
	timeval tv_stop;
	gettimeofday(&tv_stop,NULL);
	//printf("USER TIME: %u\n",(unsigned int)(myStop-myStart));
	printf("USER TIME: %ld usec\n", Utility::timevaldiff( &tv_start, &tv_stop) );
	printf("     status=%d == 0\n", status ) ;
	printf("     alpha=%lf\n", A.GetAlpha() ) ;
	printf("     Window (If SLOW REDUCE)=%d\n", A.GetMaxWindow() ) ;
	printf("     Converged=%d\n", int(A.Converged()) ) ;
	// PLOT
	{
		TCanvas *c=new TCanvas("c","c",800,800);
		TH1D *h0 =new TH1D("time" ,"time;time;time" ,1000,0,2000.);
		TH1D *h1 =new TH1D("time1","time1;time;time1",1000,0,2000.);
		TH1D *h2 =new TH1D("time2","time2;time;time2",1000,0,2000.);
		TH1D *h2_shifted =new TH1D("time2_shift","time2;time;time2",2000,0,2000.) ; h2_shifted->SetLineColor(kRed);
		TPad *p0= new TPad("p0","p0",0,0,1,0.35); p0->SetTopMargin(0); p0->SetBottomMargin(.05/.35);
		TPad *p1= new TPad("p1","p1",0,0.35,1,.65);p1->SetTopMargin(0); p1->SetBottomMargin(0);
		TPad *p2= new TPad("p2","p2",0,0.65,1,1);p2->SetTopMargin(.05/.35); p2->SetBottomMargin(0);
		p0->Draw();
		p1->Draw();
		p2->Draw();
		// fill and draw time, time1,time2
		for(unsigned int i=0;i<t.size();++i) h0->Fill( t[i] );
		for(unsigned int i=0;i<time1.size();++i) h1->Fill( time1[i] ,0.5);
		for(unsigned int i=0;i<time2.size();++i) h2->Fill( time2[i] ,0.5);
		p2->cd(); h0->Draw("HIST"); h0->GetYaxis()->SetRangeUser(0,1.2);
		p1->cd(); h1->Draw("HIST"); h1->GetYaxis()->SetRangeUser(0,1.2);
		p0->cd(); h2->Draw("HIST"); h2->GetYaxis()->SetRangeUser(0,1.2);
		c->cd();
		vector<pair<uint_t,uint_t> > matched=A.GetMatch(); // positions in time1/time2
		// compute delta
		double delta=0;
		for(uint_t i=0;i<matched.size();++i)
			delta += int64_t(time1[matched[i].first])-int64_t(time2[matched[i].second]);
		delta /= matched.size();
		for(unsigned int i=0;i< matched.size() ;i++ ) 
			{
			TLine *l=new TLine();	
			//l->SetName( Form("Line_%u",i) );
			l->SetLineWidth(2);
			uint64_t x1=time1[matched[i].first];
			uint64_t x2=time2[matched[i].second];
			h2_shifted->Fill(int64_t(x2)+delta,1);
			double max=h0->GetBinLowEdge(h0->GetNbinsX()+2);
			double min=h0->GetBinLowEdge(1);
			// LeftMargin
			double rm= p2->GetRightMargin();
			double lm= p2->GetLeftMargin();
			l->DrawLineNDC( (1.-rm-lm)*(x1-min)/(max-min)+lm,.38, 
					(1.-lm-rm)*(x2-min)/(max-min)+lm,0.07);
			}
		p0->cd();
		h2_shifted->Draw("HIST SAME");
		h2->Draw("HIST SAME"); // redraw
		c->SaveAs("Matched.png");
		c->SaveAs("Matched.pdf");
		c->SaveAs("Matched.root");
	}
	return 0;
#else
	printf("ROOT is Required: Recompile w/ ROOT\n");
	return 1;
#endif
}