Exemple #1
0
void actionMakeOtusMothur()
{
  estrarray uarr;
  eseqclusterData cdata;
  ldieif(argvc<4,"syntax: "+efile(argv[0]).basename()+" -makeotus_mothur <alignment> <mergelog> <cutoff>");

  cout << "# loading seqs file: " << argv[1] << endl;
  load_seqs(argv[1],uarr);
  cdata.load(argv[2],uarr.size());

  float t=estr(argv[3]).f();
  earray<eintarray> otuarr;
  cdata.getOTU(t,otuarr,uarr.size());

  cout << "label\tnumOtus";
  for (long i=0; i<otuarr.size(); ++i)
    cout << "\tOTU" << i;
  cout << endl;

  cout << (1.0-t) << "\t" << otuarr.size();
  for (long i=0; i<otuarr.size(); ++i){
//    cout << ">OTU" << i << " otu_size="<< otuarr[i].size() << endl;
    cout << "\t" << uarr.keys(otuarr[i][0]);
    for (long j=1; j<otuarr[i].size(); ++j)
      cout << "," << uarr.keys(otuarr[i][j]);
  }
  cout << endl;

  exit(0);
}
Exemple #2
0
mesh::mesh(std::string vfile_name, std::string sfile_name, std::string efile_name)
{
    std::ifstream vfile(vfile_name.c_str()), sfile(sfile_name.c_str()), efile(efile_name.c_str());

    vfile >> nv;
    sfile >> ns;
    efile >> ne;

    v = new vertex[nv];
    s = new side[ns];
    e = new element[ne];

    read_vertices(vfile);
    read_sides(sfile);
    read_elems(efile);

    vfile.close();
    sfile.close();
    efile.close();

    compute_geom_props();
    init_boundary_vertices();
    init_boundary_sides();

    ncolors = edge_coloring::do_edge_coloring(*this, false);
    nbcolors = edge_coloring::do_edge_coloring(*this, true);

    init_color_sides();
    init_b_color_sides();
}
Exemple #3
0
void actionMakePart()
{
  ldieif(argvc<3,"syntax: "+efile(argv[0]).basename()+" -makepart <alignment> <cutoff>");

  cout << "# loading seqs file: " << argv[1] << endl;
  load_seqs_compressed(argv[1],arr,seqlen);

  t=estr(argv[2]).f();

  ebasicarray<INDTYPE> uniqind;
  earray<ebasicarray<INDTYPE> > dupslist;
  finduniq(uniqind,dupslist);
  cout << "# unique seqs: " << uniqind.size() << endl;

  ebasicarray<INDTYPE> otuid;
  otuid.reserve(uniqind.size());
  for (long i=0l; i<uniqind.size(); ++i)
    otuid.add(i);

  cout << "# computing partitions. threshold: " << t << endl;
  if (partsTotal>(arr.size()-1l)*arr.size()/20l) partsTotal=(arr.size()-1l)*arr.size()/20l; // make fewer tasks if to few calculations per task
//  partsTotal=1;
  for (long i=0; i<partsTotal; ++i)
    taskman.addTask(dfuncpart.value().calcfunc,evararray(mutex,uniqind,arr,otuid,(const int&)seqlen,(const long int&)i,(const long int&)partsTotal,(const float&)t,(const int&)winlen));

  taskman.createThread(nthreads);
  taskman.wait();

  cout << endl;

  ebasicarray<INDTYPE> newotuid;
  earray<ebasicarray<INDTYPE> > otus;
  newotuid.init(otuid.size(),-1l);
  long otucount=0;
  for (long i=0; i<otuid.size(); ++i){
    if (newotuid[otuid[i]]==-1l){
      newotuid[otuid[i]]=otucount;
      otus.add(ebasicarray<INDTYPE>());
      ++otucount;
    }
    otuid[i]=newotuid[otuid[i]];
    otus[otuid[i]].add(i);
  }
  cout << "# partitions: " << otus.size() << endl;

  for (long i=0; i<otus.size(); ++i){
    cout << otus[i].size() << ":";
    for (long j=0; j<otus[i].size(); ++j){
//      cout << " " << uniqind[otus[i][j]];
      for (long k=0; k<dupslist[otus[i][j]].size(); ++k)
        cout << " " << dupslist[otus[i][j]][k];
    }
    cout << endl;
  }

  exit(0);
}
Exemple #4
0
	// 2 file arguments -> add e+m from different files e.g. data
	// this is considered to be data not added to sum histo
	TH1D* get(const TString& eFile, const TString& mFile){
		TFile mfile(path+mFile);
		TFile efile(path+eFile);
		TH1D* mH = (TH1D*)mfile.Get(mName);
		TH1D* eH = (TH1D*)efile.Get(eName);
		gROOT->cd();
		TH1D*  H = mH->Clone();
		H->Add(eH);
		return H;
	}
void run_dakota(const MPI_Comm& my_comm, const std::string& input, 
		const int& color)
{
  std::cout << "*** Starting DAKOTA run " << color << std::endl;
  
  // construct DAKOTA instances on the communicator
  Dakota::ParallelLibrary parallel_lib(my_comm);
  Dakota::ProblemDescDB problem_db(parallel_lib);

  // override output, error, and write restart files, but not read restart
  std::string ofile("dakota.o." + boost::lexical_cast<std::string>(color));
  std::string efile("dakota.e." + boost::lexical_cast<std::string>(color));
  std::string wfile("dakota.rst." + boost::lexical_cast<std::string>(color));
  const char* const rfile = NULL;
  parallel_lib.specify_outputs_restart(ofile.c_str(), efile.c_str(),
  				       rfile, wfile.c_str());

  nidr_set_input_string(input.c_str());

  // use manage_inputs since no late updates to data
  const char* const input_filename = NULL;
  problem_db.manage_inputs(input_filename);

  // Create strategy from the problem_db
  Dakota::Strategy selected_strategy(problem_db);

  // Perform interface plug-ins.
  // retrieve the currently active analysisComm from the Model.  In the most
  // general case, need an array of Comms to cover all Model configurations.
  Dakota::ModelList& models = problem_db.model_list();
  Dakota::ModelLIter ml_iter = models.begin();
  Dakota::ModelLIter ml_end = models.end();
  for ( ; ml_iter != ml_end; ++ml_iter) {
    Dakota::Interface& model_iface = ml_iter->interface();
    const Dakota::ParallelLevel& ea_level
      = ml_iter->parallel_configuration_iterator()->ea_parallel_level();
    const MPI_Comm& analysis_comm = ea_level.server_intra_communicator();
    model_iface.assign_rep(new SIM::ParallelDirectApplicInterface(problem_db, 
								  analysis_comm), 
			   false);
  }

  // Execute the strategy
  problem_db.lock(); // prevent run-time DB queries
  selected_strategy.run_strategy();

  std::cout << "*** Finished DAKOTA run " << color << std::endl;
}
ImportFromGG::ImportFromGG(const Account &acc, QString file, QObject *p): Importer(acc, p)
{
  //sprawdź czy plik istnieje
  QFile efile(file);
  if (!efile.exists())
  {
    QMessageBox::critical(0, tr("Error"), tr("File does no exist."));
    cancelImport();
    return;
  }

  if (account.isNull() || !History::instance()->currentStorage())
  {
    QMessageBox::critical(0, tr("Error"), tr("Could not find any Gadu-Gadu account."));
    cancelImport();
    return;
  }

  //wstępnie przeanalizuj plik z historią
  arch=new MemFile(file);                         //plik z archiwum - do odczytu danych
  arch->open(QIODevice::ReadOnly);
  /* odczytaj nagłówek pliku */
  arch->read(reinterpret_cast<char*>(&gg_header),sizeof(gg_header));

  owner_uin=gg_header.uin ^ 0xFFFFFD66;

  /* sprawdź czy uin sie zgadza */
  unsigned int acc_uin=account.id().toInt();
  if (acc_uin!=owner_uin)
  {
    if (QMessageBox::Yes==QMessageBox::warning(0, tr("Warning"),
        tr("It seems that it is not your Gadu-Gadu archive.\n"
           "The uin saved in archives.dat file, and your current uin are different.\n"
           "Cancel import?"),
        QMessageBox::Yes|QMessageBox::No,QMessageBox::Yes)
       )
      cancelImport();
  }
}
Exemple #7
0
void help()
{
  printf("HPC-CLUST v%s\n",HPC_CLUST_PACKAGE_VERSION);
  printf("by Joao F. Matias Rodrigues and Christian von Mering\n");
  printf("Institute of Molecular Life Sciences, University of Zurich, Switzerland\n");
  printf("Matias Rodrigues JF, Mering C von. HPC-CLUST: Distributed hierarchical clustering for very large sets of nucleotide sequences. Bioinformatics. 2013.\n");
  printf("\n");
  printf("Usage:\n");
  printf("    %s [...] <-sl true|-cl true|-al true> alignedseqs.fa\n",efile(argv[0]).basename()._str);
  printf("\n");
  printf("Clusters a set of multiple aligned sequences in fasta or stockholm format to a given threshold.\n");
  printf("Example: hpc-clust -nthreads 4 -t 0.8 -dfunc gap -sl true alignedseqs.fa\n"); 
  printf("\n"); 
  printf("Optional arguments:\n");
  printf("%10s    %s\n","-t","distance threshold until which to do the clustering [default: 0.9]");
  printf("%10s    %s\n","-dfunc","distance function to use: gap, nogap, tamura [default: gap]");
  printf("%10s    %s\n","-nthreads","number of threads to use [default: 4]");
  printf("%10s    %s\n","-ofile","output filename [defaults to input filename] + \".sl\",\".cl\", or \".al\" extension");
  printf("\n");
  printf("One or more is required:\n");
  printf("%10s    %s\n","-sl true","perform single-linkage clustering");
  printf("%10s    %s\n","-cl true","perform complete-linkage clustering");
  printf("%10s    %s\n","-al true","perform average-linkage clustering");
  printf("\n");

  printf("After clustering:\n");
  printf("%10s    %s\n","-makeotus <alignment> <mergelog> <threshold>","generate an OTU file at a given threshold");
  printf("%10s    %s\n","-makeotus_mothur <alignment> <mergelog> <threshold>","generate a MOTHUR compatible OTU file at a given threshold");
  printf("%10s    %s\n","-makereps <alignment> <otu>","generate a fasta file of OTU representatives. Sequences chosen have the minimum average distance to other sequences in the OTU.");
  printf("\n");

  printf("Report bugs to: [email protected]\n");
  printf("http://meringlab.org/software/hpc-clust/\n");

  exit(0);
}
Exemple #8
0
void nmssm_wh_4b::Loop()
{
//   In a ROOT session, you can do:
//      Root > .L nmssm_wh_4b.C
//      Root > nmssm_wh_4b t
//      Root > t.GetEntry(12); // Fill t data members with entry number 12
//      Root > t.Show();       // Show values of entry 12
//      Root > t.Show(16);     // Read and show values of entry 16
//      Root > t.Loop();       // Loop on all entries
//

//     This is the loop skeleton where:
//    jentry is the global entry number in the chain
//    ientry is the entry number in the current Tree
//  Note that the argument to GetEntry must be:
//    jentry for TChain::GetEntry
//    ientry for TTree::GetEntry and TBranch::GetEntry
//
//       To read only selected branches, Insert statements like:
// METHOD1:
//    fChain->SetBranchStatus("*",0);  // disable all branches
//    fChain->SetBranchStatus("branchname",1);  // activate branchname
// METHOD2: replace line
//    fChain->GetEntry(jentry);       //read all branches
//by  b_branchname->GetEntry(ientry); //read only this branch
   if (fChain == 0) return;

   Long64_t nentries = fChain->GetEntriesFast();

   Long64_t nbytes = 0, nb = 0;

   TH1F * hptl  = new TH1F( "hptl", "ptl", 20, 0., 100.);
   TH1F * hetal = new TH1F( "hetal", "etal", 50, -5.0, 5.0);

   TH1F * hptb   = new TH1F( "hptb", "ptb", 20, 0., 100.);
   TH1F * hetab  = new TH1F( "hetab", "etab", 50, -5.0, 5.0);

   TH1F * hdrlbmin  = new TH1F( "hdrlbmin", "drlbmin", 25, 0., 5.0);

   TH1F * hdrb1b2   = new TH1F( "hdrb1b2", "drb1b2", 25, 0., 5.0);
   TH1F * hdrb1b3   = new TH1F( "hdrb1b3", "drb1b3", 25, 0., 5.0);
   TH1F * hdrb1b4   = new TH1F( "hdrb1b4", "drb1b4", 25, 0., 5.0);
   TH1F * hdrb2b3   = new TH1F( "hdrb2b3", "drb2b3", 25, 0., 5.0);
   TH1F * hdrb2b4   = new TH1F( "hdrb2b4", "drb2b4", 25, 0., 5.0);
   TH1F * hdrb3b4   = new TH1F( "hdrb3b4", "drb3b4", 25, 0., 5.0);

   //   TH2F * hdsbj   = new TH2F( "hhdsbj", "hdsbj", 7, 0., 7., 7, 0., 7.);

   TH1F * hdsbj   = new TH1F( "hdsbj", "hdsbj", 8, 0., 8.);

   int ntot     = 0;
   int lpteta   = 0;
   int bpteta   = 0;
   int drlb     = 0;

   double nbtot = 0.;
   double nbhe  = 0.;

   double di_b_jet = 0.;
   double single_b_jet = 0.;

   vector<int> twobjet1stindex;
   vector<int> twobjet2ndindex;
   vector<int> singlebindex;
   vector<double> drpair;

   for (Long64_t jentry=0; jentry<nentries;jentry++) {
      Long64_t ientry = LoadTree(jentry);
      if (ientry < 0) break;
      nb = fChain->GetEntry(jentry);   nbytes += nb;
      
      ntot += 1;

      // select pt/eta lepton
      if(ptl < 20. || fabs(etal) > 2.4) {continue;}
      lpteta += 1;

      hptl->Fill(ptl);
      hetal->Fill(etal);

      Double_t drb1b2 = deltaR((*etab)[0],(*phib)[0],(*etab)[1],(*phib)[1]);
      Double_t drb1b3 = deltaR((*etab)[0],(*phib)[0],(*etab)[2],(*phib)[2]);
      Double_t drb1b4 = deltaR((*etab)[0],(*phib)[0],(*etab)[3],(*phib)[3]);
      Double_t drb2b3 = deltaR((*etab)[1],(*phib)[1],(*etab)[2],(*phib)[2]);
      Double_t drb2b4 = deltaR((*etab)[1],(*phib)[1],(*etab)[3],(*phib)[3]);
      Double_t drb3b4 = deltaR((*etab)[2],(*phib)[2],(*etab)[3],(*phib)[3]);

      hdrb1b2->Fill(drb1b2);
      hdrb1b3->Fill(drb1b3);
      hdrb1b4->Fill(drb1b4);
      hdrb2b3->Fill(drb2b3);
      hdrb2b4->Fill(drb2b4);
      hdrb3b4->Fill(drb3b4);
      
      twobjet1stindex.clear();
      twobjet2ndindex.clear();
      singlebindex.clear();

      Int_t ndbj = 0;
      Int_t nbj = ptb->size();
      for (unsigned int i = 0; i < nbj-1; i++) {
	for (unsigned int j = i+1; j < nbj; j++) {
	  Double_t dr = deltaR((*etab)[i],(*phib)[i],(*etab)[j],(*phib)[j]);
	  if(dr < 0.5) 
	    {
	      twobjet1stindex.push_back(i);
	      twobjet2ndindex.push_back(j);
	      drpair.push_back(dr);	      
	      //	      cout <<"  dr = " << dr 
	      //		   <<" i = " << i 
	      //		   <<" j = " << j << endl;
	    }
	}
      }

      Int_t ndbj = twobjet1stindex.size();

      for (unsigned int i = 0; i < nbj; i++) {
	Int_t sj = 1;
	for (unsigned int i2 = 0; i2 < ndbj; i2++) {
	  if(i == twobjet1stindex[i2] || i == twobjet2ndindex[i2]) {sj = 0;}
	}
	if(sj == 1) {singlebindex.push_back(i);}
      }

      Int_t nsbj = singlebindex.size();
      
      if(nsbj == 4 ) {

	cout <<" " << endl;
	cout <<" ==> Next event nsbj = " << nsbj <<" ndbj = " << ndbj << endl;

	for (unsigned int i = 0; i < nsbj; i++) {
	  cout <<"          singlebindex j = " << singlebindex[i] << endl;
	}

	for (unsigned int i = 0; i < ndbj; i++) {
	  cout <<" pair ij =" << twobjet1stindex[i]
	       <<" " << twobjet2ndindex[i] 
	       <<" dr = " << drpair[i] << endl;
	}
      }

      hdsbj->Fill(1.*nsbj);

      // select pt/eta b  
      int b_in_acc = 1;
      for (unsigned int j = 0; j < nbj; j++) {
	if( (*ptb)[j] < 0. || fabs((*etab)[j]) > 4.0) {b_in_acc = 0;}
      }
      if(b_in_acc == 0) {continue;}
      bpteta += 1;

      for (unsigned int j = 0; j < nbj; j++) {
	hptb->Fill((*ptb)[j]);
	if((*ptb)[j] > 30.) hetab->Fill((*etab)[j]);
      }

      // DR l-b > 0.5
      Double_t drlb_min = 1000.;
      for (unsigned int j = 0; j < nbj; j++) {
	Double_t dr = deltaR((*etab)[j],(*phib)[j],etal,phil);
	if(dr < drlb_min) {
	  drlb_min = dr;
	}
      }

      if(drlb_min < 0.5) {continue;}
      drlb += 1;
      hdrlbmin->Fill(drlb_min);

      // if (Cut(ientry) < 0) continue;
   }

   cout <<"  ========= Selections =========== " << endl;
   cout <<" nton = " << ntot << endl;
   cout <<" lpteta = " << lpteta << endl;
   cout <<" bpteta = " << bpteta << endl;
   cout <<" drlb = " << drlb << endl;
     

   //TFile efile("nmssm_wh_4b_mh60_histos.root","recreate");
   TFile efile("nmssm_wh_4b_mh60_histos.root","recreate");

   hptl->Write();
   hetal->Write();

   hptb->Write();
   hetab->Write();

   hdrlbmin->Write();

   hdrb1b2->Write();
   hdrb1b3->Write();
   hdrb1b4->Write();
   hdrb2b3->Write();
   hdrb2b4->Write();
   hdrb3b4->Write();

   hdsbj->Write();

   efile.Close();
}
Exemple #9
0
//_____________________________________________________________________
void h1analysisProxy_Terminate()
{
   printf("Terminate (final) h1analysis\n");

   // function called at the end of the event loop

   hdmd = dynamic_cast<TH1F*>(fOutput->FindObject("hdmd"));
   h2 = dynamic_cast<TH2F*>(fOutput->FindObject("h2"));

   if (hdmd == 0 || h2 == 0) {
      Error("Terminate", "hdmd = %p , h2 = %p", hdmd, h2);
      return;
   }

   //create the canvas for the h1analysis fit
   gStyle->SetOptFit();
   TCanvas *c1 = new TCanvas("c1","h1analysis analysis",10,10,800,600);
   c1->SetBottomMargin(0.15);
   hdmd->GetXaxis()->SetTitle("m_{K#pi#pi} - m_{K#pi}[GeV/c^{2}]");
   hdmd->GetXaxis()->SetTitleOffset(1.4);

   //fit histogram hdmd with function f5 using the loglikelihood option
   TF1 *f5 = new TF1("f5",fdm5,0.139,0.17,5);
   f5->SetParameters(1000000, .25, 2000, .1454, .001);
   hdmd->Fit("f5","lr");

   //create the canvas for tau d0
   gStyle->SetOptFit(0);
   gStyle->SetOptStat(1100);
   TCanvas *c2 = new TCanvas("c2","tauD0",100,100,800,600);
   c2->SetGrid();
   c2->SetBottomMargin(0.15);

   // Project slices of 2-d histogram h2 along X , then fit each slice
   // with function f2 and make a histogram for each fit parameter
   // Note that the generated histograms are added to the list of objects
   // in the current directory.
   TF1 *f2 = new TF1("f2",fdm2,0.139,0.17,2);
   f2->SetParameters(10000, 10);
   h2->FitSlicesX(f2,0,-1,1,"qln");
   TH1D *h2_1 = (TH1D*)gDirectory->Get("h2_1");
   h2_1->GetXaxis()->SetTitle("#tau[ps]");
   h2_1->SetMarkerStyle(21);
   h2_1->Draw();
   c2->Update();
   TLine *line = new TLine(0,0,0,c2->GetUymax());
   line->Draw();

   // Have the number of entries on the first histogram (to cross check when running
   // with entry lists)
   TPaveStats *psdmd = (TPaveStats *)hdmd->GetListOfFunctions()->FindObject("stats");
   psdmd->SetOptStat(1110);
   c1->Modified();
   
   //save the entry list to a Root file if one was produced
   if (fillList) {
      elist = dynamic_cast<TEntryList*>(fOutput->FindObject("elist"));
      if (elist) {
         TFile efile("elist.root","recreate");
         elist->Write();
      } else {
         Error("Terminate", "entry list requested but not found in output");
      }
   }
}
void MinBias1::Loop()
{
//   In a ROOT session, you can do:
//      Root > .L MinBias1.C
//      Root > MinBias1 t
//      Root > t.GetEntry(12); // Fill t data members with entry number 12
//      Root > t.Show();       // Show values of entry 12
//      Root > t.Show(16);     // Read and show values of entry 16
//      Root > t.Loop();       // Loop on all entries
//

//     This is the loop skeleton where:
//    jentry is the global entry number in the chain
//    ientry is the entry number in the current Tree
//  Note that the argument to GetEntry must be:
//    jentry for TChain::GetEntry
//    ientry for TTree::GetEntry and TBranch::GetEntry
//
//       To read only selected branches, Insert statements like:
// METHOD1:
//    fChain->SetBranchStatus("*",0);  // disable all branches
//    fChain->SetBranchStatus("branchname",1);  // activate branchname
// METHOD2: replace line
//    fChain->GetEntry(jentry);       //read all branches
//by  b_branchname->GetEntry(ientry); //read only this branch
   if (fChain == 0) return;

   Long64_t nentries = fChain->GetEntriesFast();

   Int_t nbytes = 0, nb = 0;
   
   FILE *Out1 = fopen("coef.txt", "w+");  
   FILE *Out2 = fopen("var.txt", "w+");

// distribution of <Energy deposition per readout> over 40000 events 
// without cut (all rechits) and with cut on rechit energy (0.5 GeV)
// for all readouts (phi, eta, depth) 1 (-ieta), 2 (+ieta)
     
   TH1F  *hCalo1[80][50][5][5];
   TH1F  *hCalo2[80][50][5][5];


// distribution of variances of energy deposition per 
// readout without cut (all rechits) and with cut on rechit energy (0.5 GeV)
// for all readouts (phi, eta, depth) 1 (-ieta), 2 (+ieta)
   
   TH1F  *hCalo1mom2[80][50][5][5];
   TH1F  *hCalo2mom2[80][50][5][5];
   
// 1D distribution of <energy deposition per readout>
// for single eta without cut (all rechits) and with cut on rechit energy (0.5 GeV)
// for all readouts (eta, depth) 1 (-ieta), 2 (+ieta)
   
   TH1F  *hCalo1eta[50][5][5];
   TH1F  *hCalo2eta[50][5][5];
    
// 1D distribution of variances of energy deposition per 
// readout for single eta without cut (all rechits) and with cut on rechit energy (0.5 GeV)
// for all readouts (eta, depth) 1 (-ieta), 2 (+ieta)
   
   TH1F  *hCalo1mom2eta[50][5][5];
   TH1F  *hCalo2mom2eta[50][5][5];

// 2D distribution of <energy deposition per readout>
// for single eta without cut (all rechits) and with cut on rechit energy (0.5 GeV)
// for all readouts (eta, depth) 1 (-ieta), 2 (+ieta)

   
   TH2F  *hCalo1etatwo[50][5][5];
   TH2F  *hCalo2etatwo[50][5][5];

// 2D distribution of variances of energy deposition per 
// readout for single eta without cut (all rechits) and with cut on rechit energy (0.5 GeV)
// for all readouts (eta, depth) 1 (-ieta), 2 (+ieta)
   
   TH2F  *hCalo1mom2etatwo[50][5][5];
   TH2F  *hCalo2mom2etatwo[50][5][5];
   
// 2D distribution of coefficients per 
// readout for single eta without cut (all rechits) and with cut on rechit energy (0.5 GeV)
// for all readouts (eta, depth) 1 (-ieta), 2 (+ieta)
   
   
   TH2F  *hCalo1etatwocoef[50][5][5];
   TH2F  *hCalo2etatwocoef[50][5][5];
   
   TH1F  *hCalo1etaonecoef[50][5][5];
   TH1F  *hCalo2etaonecoef[50][5][5];
   
   TH1F  *hCalo1etacoefdist[50][5][5]; 
   TH1F  *hCalo2etacoefdist[50][5][5];

   TH1F  *hCalo1etacoefdist_nonoise[50][5][5];
   TH1F  *hCalo2etacoefdist_nonoise[50][5][5];

   
   Float_t plmeang[80][80][5][5],plnoise[80][80][5][5],plerrg[80][80][5][5],plerr[80][5][5];
   Float_t plmeang_nn[80][80][5][5]; 
   Float_t plmean[80][5][5]; 
   Float_t plmean_nn[80][5][5];
   Float_t minmeang[80][80][5][5],minnoise[80][80][5][5],minerrg[80][80][5][5],minerr[80][5][5];
   Float_t minmeang_nn[80][80][5][5];
   Float_t minmean[80][5][5];
   Float_t minmean_nn[80][5][5];
   
   Int_t plneveta[80][5][5]; 
   Int_t plnevetaphi[80][80][5][5];
   Int_t minneveta[80][5][5]; 
   Int_t minnevetaphi[80][80][5][5];
   Int_t mysubdetpl0[80][5][5];
   Int_t mysubdetmin0[80][5][5];
   Int_t hb_excluded_min[80][80][5];
  
   cout<<" Read noise comment for neutrino samples/uncomment for data samples"<<endl;
      string line;
      
/*
   std::ifstream in20( "disp_11.txt" );
   while( std::getline( in20, line)){
   istringstream linestream(line);
   Float_t var;
   int subd,eta,phi,dep; 
   linestream>>subd>>eta>>phi>>dep>>var;
   if(phi == 1) cout<<subd<<" "<<var<<endl;
   if( eta > 0 )
   {
     plnoise[eta][phi][dep][subd] = var;
//     cout<<plnoise[eta][phi][dep]<<endl;
   } else
   {
     minnoise[abs(eta)][phi][dep][subd] = var;
//     cout<<minnoise[abs(eta)][phi][dep]<<endl;
   }
  }

*/ 
  for(Int_t ietak = 0; ietak < 80; ietak++ )
  {
   for(Int_t idep = 0; idep < 5; idep++ )
   {
    for(Int_t isub = 0; isub < 5; isub++ )
   {
    
    plneveta[ietak][idep][isub] = 0;
    minneveta[ietak][idep][isub] = 0;
    plmean[ietak][idep][isub] = 0;
    plmean_nn[ietak][idep][isub] = 0;
    minmean[ietak][idep][isub] = 0;
    minmean_nn[ietak][idep][isub] = 0;
    mysubdetmin0[ietak][idep][isub] = 0;
    mysubdetpl0[ietak][idep][isub] = 0;

    for(Int_t iphik = 0; iphik < 80; iphik++ )
    {
       plnevetaphi[ietak][iphik][idep][isub] = 0;
       minnevetaphi[ietak][iphik][idep][isub] = 0;
       plmeang[ietak][iphik][idep][isub] = 0;
       minmeang[ietak][iphik][idep][isub] = 0;
       plmeang_nn[ietak][iphik][idep][isub] = 0;
       minmeang_nn[ietak][iphik][idep][isub] = 0;
      if(isub==0)
      {
         hb_excluded_min[ietak][iphik][idep] = 0.;
      }
     }
    } 
   }
  }
  
   std::ifstream in21( "HB_exclusion.txt" );
   
   while( std::getline( in21, line)){
   istringstream linestream(line);
 
   int eta,phi,dep; 
   linestream>>dep>>eta>>phi;
    cout<<" Eta="<<eta<<endl;
   if( eta > 0 )
   {
     cout<<" eta > 0 "<<endl;
   } else
   {
     hb_excluded_min[abs(eta)][phi][dep] = 1;
   }
  }
  
  cout<< " Start to order histograms "<<endl;
  
//    
   char shCalo1[50];
   char shCalo2[50];
   
   char shCalo1mom2[50];
   char shCalo2mom2[50];
  
   char shCalo1eta[50];
   char shCalo2eta[50];

   
   char shCalo1mom2eta[50];
   char shCalo2mom2eta[50];
   
   char shCalo1etatwo[50];
   char shCalo2etatwo[50];

   char shCalo1mom2etatwo[50];
   char shCalo2mom2etatwo[50];   
   char shCalo1etatwocoef[50];
   char shCalo2etatwocoef[50];
   
   char shCalo1etaonecoef[50];
   char shCalo2etaonecoef[50];

   char shCalo1etacoefdist[50];
   char shCalo2etacoefdist[50];
   
   char shCalo1etacoefdist_nonoise[50];
   char shCalo2etacoefdist_nonoise[50];

   char sDet(2);
  
  
   int k;
   for(int i=1;i<73;i++){
    for(int j=1;j<43;j++){
     for(int l=1;l<5;l++){
       for(int m=1;m<5;m++){
        k = i*10000+j*100+l*10+m;
        sprintf(shCalo1,"hCalo1_%d",k);
        sprintf(shCalo2,"hCalo2_%d",k);
	
        sprintf(shCalo1mom2,"hCalo1mom2_%d",k);
        sprintf(shCalo2mom2,"hCalo2mom2_%d",k);

    if( j < 30 )
    {
// first order moment	
    hCalo1[i][j][l][m] = new TH1F(shCalo1, "hCalo1", 320, -0.1, 0.1); 
    hCalo2[i][j][l][m] = new TH1F(shCalo2, "hCalo2", 320, -0.1, 0.1);

// second order moment    
    hCalo1mom2[i][j][l][m] = new TH1F(shCalo1mom2, "hCalo1mom2", 320, 0., 0.5); 
    hCalo2mom2[i][j][l][m] = new TH1F(shCalo2mom2, "hCalo2mom2", 320, 0., 0.5); 
    
    }
      else
      {

// HF
// first order moment
//   cout<<" "<<i<<" "<<j<<" "<<k<<endl;

   if(j < 38)
   {	
    hCalo1[i][j][l][m] = new TH1F(shCalo1, "hCalo1", 320, -0.1, 0.1); 
    hCalo2[i][j][l][m] = new TH1F(shCalo2, "hCalo2", 320, -0.1, 0.1);
//
// second order moment    
    hCalo1mom2[i][j][l][m] = new TH1F(shCalo1mom2, "hCalo1mom2", 320, 0., 10.); 
    hCalo2mom2[i][j][l][m] = new TH1F(shCalo2mom2, "hCalo2mom2", 320, 0., 10.); 
   }
     else
     {
    hCalo1[i][j][l][m] = new TH1F(shCalo1,"hCalo1" , 320, -0.1, 0.1); 
    hCalo2[i][j][l][m] = new TH1F(shCalo2, "hCalo2", 320, -0.1, 0.1);

// second order moment    
    hCalo1mom2[i][j][l][m] = new TH1F(shCalo1mom2, "hCalo1mom2", 320, 0., 120.); 
    hCalo2mom2[i][j][l][m] = new TH1F(shCalo2mom2, "hCalo2mom2", 320, 0., 120.); 
       
     }  
    } // HE/HF boundary
      } // m
     } // l
    } // j
   } // i
 
   cout<<" First histos "<<endl;
   
     for(int j=1;j<43;j++)
     {
       for(int l=1;l<5;l++)
       {
         for(int m=1;m<5;m++)
         {
       
         Int_t jj = 100*j+10*l+m;
	 
        sprintf(shCalo1eta,"hCalo1eta_%d",jj);
        sprintf(shCalo2eta,"hCalo2eta_%d",jj);

	
        sprintf(shCalo1mom2eta,"hCalo1mom2eta_%d",jj);
        sprintf(shCalo2mom2eta,"hCalo2mom2eta_%d",jj);
 	
	sprintf(shCalo1etatwo,"hCalo1etatwo_%d",jj);
	sprintf(shCalo2etatwo,"hCalo2etatwo_%d",jj);
	
	sprintf(shCalo1mom2etatwo, "hCalo1mom2etatwo_%d",jj);
	sprintf(shCalo2mom2etatwo, "hCalo2mom2etatwo_%d",jj);
	
	sprintf(shCalo1etatwocoef,"hCalo1etatwocoef_%d",jj);
	sprintf(shCalo2etatwocoef,"hCalo2etatwocoef_%d",jj);
	sprintf(shCalo1etaonecoef,"hCalo1etaonecoef_%d",jj);
	sprintf(shCalo2etaonecoef,"hCalo2etaonecoef_%d",jj);
	
	sprintf(shCalo1etacoefdist,"hCalo1etacoefdist_%d",jj);
	sprintf(shCalo2etacoefdist,"hCalo2etacoefdist_%d",jj);
        sprintf(shCalo1etacoefdist_nonoise,"hCalo1etacoefdist_nn_%d",jj);
        sprintf(shCalo2etacoefdist_nonoise,"hCalo2etacoefdist_nn_%d",jj);
	
        hCalo1etatwocoef[j][l][m] = new TH2F(shCalo1etatwocoef, "hCalo1etatwocoef", 72, 0.5, 72.5, 320, 0., 2.); 
        hCalo2etatwocoef[j][l][m] = new TH2F(shCalo2etatwocoef, "hCalo2etatwocoef", 72, 0.5, 72.5, 320, 0., 2.);
        hCalo1etaonecoef[j][l][m] = new TH1F(shCalo1etaonecoef, "hCalo1etaonecoef", 72, 0.5, 72.5); 
        hCalo2etaonecoef[j][l][m] = new TH1F(shCalo2etaonecoef, "hCalo2etaonecoef", 72, 0.5, 72.5);
        hCalo1etacoefdist[j][l][m] = new TH1F(shCalo1etacoefdist, "hCalo1etacoefdist", 100, 0., 2.); 
        hCalo2etacoefdist[j][l][m] = new TH1F(shCalo2etacoefdist, "hCalo2etacoefdist", 100, 0., 2.);
        hCalo1etacoefdist_nonoise[j][l][m] = new TH1F(shCalo1etacoefdist_nonoise, "hCalo1etacoefdist_nonoise", 100, 0., 2.);
        hCalo2etacoefdist_nonoise[j][l][m] = new TH1F(shCalo2etacoefdist_nonoise, "hCalo2etacoefdist_nonoise", 100, 0., 2.);

       if( j < 30 )
       {	
	
        hCalo1eta[j][l][m] = new TH1F(shCalo1eta, "hCalo1eta", 320, -0.1, 0.1); 
        hCalo2eta[j][l][m] = new TH1F(shCalo2eta,"hCalo2eta" , 320, -0.1, 0.1);
	
        hCalo1mom2eta[j][l][m] = new TH1F(shCalo1mom2eta,"hCalo1mom2eta" , 320, 0., 0.2); 
        hCalo2mom2eta[j][l][m] = new TH1F(shCalo2mom2eta,"hCalo2mom2eta" , 320, 0., 0.2);        
        hCalo1etatwo[j][l][m] = new TH2F(shCalo1etatwo, "hCalo1etatwo", 72, 0.5, 72.5, 320, -1.5, 1.5); 
        hCalo2etatwo[j][l][m] = new TH2F(shCalo2etatwo, "hCalo2etatwo", 72, 0.5, 72.5, 320, -1.5, 1.5);
        if (j < 24)
        {
        hCalo1mom2etatwo[j][l][m] = new TH2F(shCalo1mom2etatwo, "hCalo1mom2etatwo", 72, 0.5, 72.5, 320, 0., 0.2); 
        hCalo2mom2etatwo[j][l][m] = new TH2F(shCalo2mom2etatwo, "hCalo2mom2etatwo", 72, 0.5, 72.5, 320, 0., 0.2);
	}
          else
          {
        hCalo1mom2etatwo[j][l][m] = new TH2F(shCalo1mom2etatwo, "hCalo1mom2etatwo", 72, 0.5, 72.5, 320, 0., 1.5);
        hCalo2mom2etatwo[j][l][m] = new TH2F(shCalo2mom2etatwo, "hCalo2mom2etatwo", 72, 0.5, 72.5, 320, 0., 1.5);
          }
       }
         else
	 {
	 if( j < 38 )
	 {
        hCalo1eta[j][l][m] = new TH1F(shCalo1eta, "hCalo1eta", 320, -0.1, 0.1); 
        hCalo2eta[j][l][m] = new TH1F(shCalo2eta,"hCalo2eta" , 320, -0.1, 0.1);
	
        hCalo1etatwo[j][l][m] = new TH2F(shCalo1etatwo, "hCalo1etatwo", 72, 0.5, 72.5, 320, -1.5, 1.5); 
        hCalo2etatwo[j][l][m] = new TH2F(shCalo2etatwo, "hCalo2etatwo", 72, 0.5, 72.5, 320, -1.5, 1.5);
	
        hCalo1mom2eta[j][l][m] = new TH1F(shCalo1mom2eta,"hCalo1mom2eta" , 320, 0., 0.2); 
        hCalo2mom2eta[j][l][m] = new TH1F(shCalo2mom2eta,"hCalo2mom2eta" , 320, 0., 0.2);        
	
        hCalo1mom2etatwo[j][l][m] = new TH2F(shCalo1mom2etatwo, "hCalo1mom2etatwo", 72, 0.5, 72.5, 320, 0., 10.); 
        hCalo2mom2etatwo[j][l][m] = new TH2F(shCalo2mom2etatwo, "hCalo2mom2etatwo", 72, 0.5, 72.5, 320, 0., 10.);
	 
	 }
	   else
	   {
	   
        hCalo1eta[j][l][m] = new TH1F(shCalo1eta, "hCalo1eta", 320, -0.1, 0.1); 
        hCalo2eta[j][l][m] = new TH1F(shCalo2eta,"hCalo2eta" , 320, -0.1, 0.1);
	
        hCalo1mom2eta[j][l][m] = new TH1F(shCalo1mom2eta,"hCalo1mom2eta" , 320, 0., 0.2); 
        hCalo2mom2eta[j][l][m] = new TH1F(shCalo2mom2eta,"hCalo2mom2eta" , 320, 0., 0.2);        
	
        hCalo1etatwo[j][l][m] = new TH2F(shCalo1etatwo, "hCalo1etatwo", 72, 0.5, 72.5, 320, -1.5, 1.5); 
        hCalo2etatwo[j][l][m] = new TH2F(shCalo2etatwo, "hCalo2etatwo", 72, 0.5, 72.5, 320, -1.5, 1.5);
	
        hCalo1mom2etatwo[j][l][m] = new TH2F(shCalo1mom2etatwo, "hCalo1mom2etatwo", 72, 0.5, 72.5, 320, 5., 20.); 
        hCalo2mom2etatwo[j][l][m] = new TH2F(shCalo2mom2etatwo, "hCalo2mom2etatwo", 72, 0.5, 72.5, 320, 5., 20.);
	
	   }
	 }
	 }// m
       } // l	 
     } // j == 50  

   cout<<" Second histos "<<endl;
   
   for (Long64_t jentry=0; jentry<nentries;jentry++) {
      Long64_t ientry = LoadTree(jentry);
      if (ientry < 0) break;
      nb = fChain->GetEntry(jentry);   nbytes += nb;
      // if (Cut(ientry) < 0) continue;
      
      if(mom0 == 0) continue;
      
       Float_t mean = mom1/mom0;
       Float_t disp = mom2/mom0 - (mom1/mom0)*(mom1/mom0);
       
       if(ieta<0) {

        hCalo1[iphi][abs(ieta)][depth][mysubd]->Fill(mom1/mom0);
        hCalo1eta[abs(ieta)][depth][mysubd]->Fill(mom1/mom0);
	hCalo1mom2[iphi][abs(ieta)][depth][mysubd]->Fill(disp);
        hCalo1mom2eta[abs(ieta)][depth][mysubd]->Fill(disp);
        hCalo1etatwo[abs(ieta)][depth][mysubd]->Fill((float)iphi, mom1/mom0);
        hCalo1mom2etatwo[abs(ieta)][depth][mysubd]->Fill((float)iphi, disp);

// Calculation of mean values ===============================
         mysubdetmin0[abs(ieta)][depth][mysubd] = mysubd;
	 minmeang[abs(ieta)][iphi][depth][mysubd]=minmeang[abs(ieta)][iphi][depth][mysubd] + (float)mean;
	 
	 if(mysubd == 1){
 	   if(hb_excluded_min[abs(ieta)][iphi][depth]>0) minmean[abs(ieta)][depth][mysubd]=minmean[abs(ieta)][depth][mysubd] + (float)mean;
	 } else {
	    minmean[abs(ieta)][depth][mysubd]=minmean[abs(ieta)][depth][mysubd] + (float)mean;
	 }
	 
         minneveta[abs(ieta)][depth][mysubd]++;
	 minnevetaphi[abs(ieta)][iphi][depth][mysubd]++;
	 
         minerrg[abs(ieta)][iphi][depth][mysubd] = minerrg[abs(ieta)][iphi][depth][mysubd] + mean*mean;
         minerr[abs(ieta)][depth][mysubd] = minerr[abs(ieta)][depth][mysubd] + mean*mean;
	 
// ==========================================================
	
      }	
      if(ieta>=0) {

         hCalo2[iphi][ieta][depth][mysubd]->Fill(mom1/mom0);
         hCalo2eta[abs(ieta)][depth][mysubd]->Fill(mom1/mom0);
	 hCalo2mom2[iphi][ieta][depth][mysubd]->Fill(disp);
         hCalo2mom2eta[abs(ieta)][depth][mysubd]->Fill(disp);
	 hCalo2etatwo[abs(ieta)][depth][mysubd]->Fill((float)iphi, mom1/mom0);
	 hCalo2mom2etatwo[abs(ieta)][depth][mysubd]->Fill((float)iphi, disp);

// Calculation of dispersion ===============================
          mysubdetpl0[abs(ieta)][depth][mysubd] = mysubd;
	  plmeang[ieta][iphi][depth][mysubd]=plmeang[ieta][iphi][depth][mysubd] + (float)mean;
	  plmean[ieta][depth][mysubd]=plmean[ieta][depth][mysubd] + (float)mean;
	  
	  plneveta[abs(ieta)][depth][mysubd]++;
	  plnevetaphi[abs(ieta)][iphi][depth][mysubd]++;
	  
	  plerrg[abs(ieta)][iphi][depth][mysubd] = plerrg[abs(ieta)][iphi][depth][mysubd] + mean*mean;
	  plerr[abs(ieta)][depth][mysubd] = plerr[abs(ieta)][depth][mysubd] + mean*mean;
	  
// ==========================================================

	 
      }
     
            
   } // jentry

   cout<<" Finish cycle "<<endl;


  Double_t perr,perrg;
  Double_t plmean_mean; 
  Double_t plmeang_mean; 
  Double_t minmean_mean; 
  Double_t minmeang_mean; 
  
  
  for (int idep = 1; idep <5; idep++ )
  {
  for(int ietak = 1; ietak != 42; ietak++ )
  {
  for(int isub = 1; isub < 5; isub++ )
  {
    
    if( plneveta[ietak][idep][isub] <= 0 ) continue;
    
    plmean_mean = plmean[ietak][idep][isub]/plneveta[ietak][idep][isub];
    perr = plerr[ietak][idep][isub]/plneveta[ietak][idep][isub] - plmean_mean*plmean_mean;
    
    
    for(Int_t iphik = 1; iphik != 73; iphik++ )
    {

          if(plnevetaphi[ietak][iphik][idep][isub] == 0) {
            Float_t ss = 1.;
	    fprintf(Out2,"%d %d %d %d %.8f\n",mysubdetpl0[ietak][idep][isub],ietak,iphik,idep,ss);
            fprintf(Out1,"%d %d %d %d %.5f %.5f\n",isub,idep, ietak,iphik,ss,ss); 
            continue;
           }
	
	   
       plmeang_mean = plmeang[ietak][iphik][idep][isub]/plnevetaphi[ietak][iphik][idep][isub];
       Float_t newdist = plmeang_mean/plmean_mean;
       hCalo2etacoefdist_nonoise[ietak][idep][isub]->Fill(newdist);
           
// Mean value and dispersion

       Double_t plmeang_mean_corr = plmean_mean/plmeang_mean;
       
       perrg = plerrg[ietak][iphik][idep][isub]/plnevetaphi[ietak][iphik][idep][isub] - plmeang_mean*plmeang_mean;
      
       Double_t yy = sqrt(plmean_mean*perrg/(4.*plmeang_mean*plmeang_mean*plmeang_mean));	
	 
       fprintf(Out2,"%d %d %d %d %.8f\n",mysubdetpl0[ietak][idep][isub],ietak,iphik,idep,plmeang_mean);
	
       Float_t zz = (Float_t)yy;  		       
//         if( isub == 1 ) fprintf(Out1,"%s %d %d %d %.5f %.5f\n","HB",ietak,iphik,idep,plmeang_mean_corr,zz);
//         if( isub == 2 ) fprintf(Out1,"%s %d %d %d %.5f %.5f\n","HE",ietak,iphik,idep,plmeang_mean_corr,zz);
//         if( isub == 3 ) fprintf(Out1,"%s %d %d %d %.5f %.5f\n","HO",ietak,iphik,idep,plmeang_mean_corr,zz);
//         if( isub == 4 ) fprintf(Out1,"%s %d %d %d %.5f %.5f\n","HF",ietak,iphik,idep,plmeang_mean_corr,zz);

       fprintf(Out1,"%d %d %d %d %.5f %.5f\n",isub,idep, ietak,iphik,plmeang_mean_corr,zz); 

         hCalo2etatwocoef[ietak][idep][isub]->Fill((float)iphik,plmeang_mean_corr);
         hCalo2etaonecoef[ietak][idep][isub]->Fill((float)iphik,plmeang_mean_corr);
	 hCalo2etacoefdist[ietak][idep][isub]->Fill(plmeang_mean_corr);
    }
  }  
  }
  }
   
  for (int idep = 1; idep <5; idep++ )
  {
  for(int ietak = 1; ietak != 42; ietak++ )
  {
  for(int isub = 1; isub < 5; isub++ )
  {
   
   int iieta = -1*ietak;
    
    if( minneveta[ietak][idep][isub] <= 0 ) continue;
    
    minmean_mean = minmean[ietak][idep][isub]/minneveta[ietak][idep][isub];
    
    perr = minerr[ietak][idep][isub]/minneveta[ietak][idep][isub] - minmean_mean*minmean_mean;
    
    if( idep == 1 && ietak == 1) cout<<" My "<< ietak<<" "<<idep<<" "<<minneveta[ietak][idep][isub]<<" "<<minerr[ietak][idep][isub]<<" "<<minmean_mean<<" "<<perr<<endl;
    
    for(Int_t iphik = 1; iphik != 73; iphik++ )
    {
    
          if(minnevetaphi[ietak][iphik][idep][isub] == 0) {
            Float_t ss = 1.;
            fprintf(Out1,"%d %d %d %d %.5f %.5f\n",isub,idep,iieta,iphik,ss,ss); 
            fprintf(Out2,"%d %d %d %d %.8f\n",mysubdetmin0[ietak][idep][isub],iieta,iphik,idep,ss);
            continue;
           }
	
	   
       minmeang_mean = minmeang[ietak][iphik][idep][isub]/minnevetaphi[ietak][iphik][idep][isub];
       Float_t newdist = minmeang_mean/minmean_mean;
       hCalo1etacoefdist_nonoise[ietak][idep][isub]->Fill(newdist);
           
// Mean value and dispersion

       Double_t minmeang_mean_corr = minmean_mean/minmeang_mean;
       
       perrg = minerrg[ietak][iphik][idep][isub]/minnevetaphi[ietak][iphik][idep][isub] - minmeang_mean*minmeang_mean;
      
       Double_t yy = sqrt(minmean_mean*perrg/(4.*minmeang_mean*minmeang_mean*minmeang_mean));	
			
	 

       fprintf(Out2,"%d %d %d %d %.8f\n",mysubdetmin0[ietak][idep][isub],iieta,iphik,idep,minmeang_mean);

	Float_t zz = (Float_t)yy;  
		       
       fprintf(Out1,"%d %d %d %d %.5f %.5f\n",isub,idep,iieta,iphik,minmeang_mean_corr,zz); 

         hCalo1etatwocoef[ietak][idep][isub]->Fill((float)iphik,minmeang_mean_corr);
         hCalo1etaonecoef[ietak][idep][isub]->Fill((float)iphik,minmeang_mean_corr);
	 hCalo1etacoefdist[ietak][idep][isub]->Fill(minmeang_mean_corr);
    }
  }  
  }
  }
 
  fclose(Out1);
  fclose(Out2);
  
     TFile efile("mom_initial_12mln.root","recreate");
  
     for(int j=1;j<43;j++)
     {
          for(int k=1;k<5;k++)
     {
          for(int m=1;m<5;m++)
     {

// Mean values     
        if(fabs(hCalo1eta[j][k][m]->GetEntries())>0.1) hCalo1eta[j][k][m]->Write();
	if(fabs(hCalo2eta[j][k][m]->GetEntries())>0.1) hCalo2eta[j][k][m]->Write();
		
	if(fabs(hCalo1etatwo[j][k][m]->GetEntries())>0.1) hCalo1etatwo[j][k][m]->Write();
	if(fabs(hCalo2etatwo[j][k][m]->GetEntries())>0.1) hCalo2etatwo[j][k][m]->Write();
	if(fabs(hCalo1mom2etatwo[j][k][m]->GetEntries())>0.1) hCalo1mom2etatwo[j][k][m]->Write();
        if(fabs(hCalo2mom2etatwo[j][k][m]->GetEntries())>0.1) hCalo2mom2etatwo[j][k][m]->Write();

// Variance
        if(fabs(hCalo1mom2eta[j][k][m]->GetEntries())>0.1) hCalo1mom2eta[j][k][m]->Write();
	if(fabs(hCalo2mom2eta[j][k][m]->GetEntries())>0.1) hCalo2mom2eta[j][k][m]->Write();

// Coefficients	
	if(fabs(hCalo1etatwocoef[j][k][m]->GetEntries())>0.1) hCalo1etatwocoef[j][k][m]->Write();
	if(fabs(hCalo2etatwocoef[j][k][m]->GetEntries())>0.1) hCalo2etatwocoef[j][k][m]->Write();
	if(fabs(hCalo1etaonecoef[j][k][m]->GetEntries())>0.1) hCalo1etaonecoef[j][k][m]->Write();
	if(fabs(hCalo2etaonecoef[j][k][m]->GetEntries())>0.1) hCalo2etaonecoef[j][k][m]->Write();
	if(fabs(hCalo1etacoefdist[j][k][m]->GetEntries())>0.1) hCalo1etacoefdist[j][k][m]->Write();
	if(fabs(hCalo2etacoefdist[j][k][m]->GetEntries())>0.1) hCalo2etacoefdist[j][k][m]->Write();
        if(fabs(hCalo1etacoefdist_nonoise[j][k][m]->GetEntries())>0.1) hCalo1etacoefdist_nonoise[j][k][m]->Write();
        if(fabs(hCalo2etacoefdist_nonoise[j][k][m]->GetEntries())>0.1) hCalo2etacoefdist_nonoise[j][k][m]->Write();
	
        for(int i=1;i<72;i++)
	{
	   if(fabs(hCalo1[i][j][k][m]->GetEntries())>0.1) hCalo1[i][j][k][m]->Write();
	   if(fabs(hCalo2[i][j][k][m]->GetEntries())>0.1) hCalo2[i][j][k][m]->Write();
	   if(fabs(hCalo1mom2[i][j][k][m]->GetEntries())>0.1) hCalo1mom2[i][j][k][m]->Write();
	   if(fabs(hCalo2mom2[i][j][k][m]->GetEntries())>0.1)  hCalo2mom2[i][j][k][m]->Write();
	   
	}
     }
     }
     }  
       
}
void SinglePionEfficiencyNewVSpT::Loop()
{
//   In a ROOT session, you can do:
//      Root > .L SinglePionEfficiencyNewVSpT.C
//      Root > SinglePionEfficiencyNewVSpT t
//      Root > t.GetEntry(12); // Fill t data members with entry number 12
//      Root > t.Show();       // Show values of entry 12
//      Root > t.Show(16);     // Read and show values of entry 16
//      Root > t.Loop();       // Loop on all entries
//

//     This is the loop skeleton where:
//    jentry is the global entry number in the chain
//    ientry is the entry number in the current Tree
//  Note that the argument to GetEntry must be:
//    jentry for TChain::GetEntry
//    ientry for TTree::GetEntry and TBranch::GetEntry
//
//       To read only selected branches, Insert statements like:
// METHOD1:
//    fChain->SetBranchStatus("*",0);  // disable all branches
//    fChain->SetBranchStatus("branchname",1);  // activate branchname
// METHOD2: replace line
//    fChain->GetEntry(jentry);       //read all branches
//by  b_branchname->GetEntry(ientry); //read only this branch
    if (fChain == 0) return;

    Long64_t nentries = fChain->GetEntriesFast();

    Long64_t nbytes = 0, nb = 0;


    // number of pt bins and intervals
    const Int_t nptbins = 17;
    const Int_t nptcuts = nptbins+1;
    //   const Double_t pt[nptcuts]={0.0, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.5, 3.0, 4.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 40., 50.0};
    const Double_t pt[nptcuts]= {1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.5, 3.0, 4.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 40., 50.0, 60.0};
    //                              0    1    2    3    4    5    6    7    8    9
    // energy ecal+hcal in different matrices
    TProfile* hprEH11x5  = new  TProfile("hprEH11x5","prEH11x5",nptbins, pt, -10., 10.);
    TProfile* hprEH11x3  = new  TProfile("hprEH11x3","prEH11x3",nptbins, pt, -10., 10.);
    TProfile* hprEH7x5   = new  TProfile("hprEH7x5","prEH7x5",nptbins, pt, -10., 10.);
    TProfile* hprEH7x3   = new  TProfile("hprEH7x3","prEH7x3",nptbins, pt, -10., 10.);
    // energy in hcal matrix
    TProfile* hprH5  = new  TProfile("hprH5","prH5",nptbins, pt, -10., 10.);
    TProfile* hprH3  = new  TProfile("hprH3","prH3",nptbins, pt, -10., 10.);

    //
    TH1F * hH5_1_2GeV    = new TH1F( "hH5_1_2GeV", "H5_1_2GeV", 40, -2., 2.);
    TH1F * hH3_1_2GeV    = new TH1F( "hH3_1_2GeV", "H3_1_2GeV", 40, -2., 2.);
    TH1F * hH5_3_4GeV    = new TH1F( "hH5_3_4GeV", "H5_3_4GeV", 40, -2., 2.);
    TH1F * hH3_3_4GeV    = new TH1F( "hH3_3_4GeV", "H3_3_4GeV", 40, -2., 2.);
    TH1F * hH5_5_10GeV   = new TH1F( "hH5_5_10GeV", "H5_5_10GeV", 40, -2., 2.);
    TH1F * hH3_5_10GeV   = new TH1F( "hH3_5_10GeV", "H3_5_10GeV", 40, -2., 2.);

    //
    TH1F * hE11_1_2GeV   = new TH1F( "hE11_1_2GeV", "E11_1_2GeV", 100, -2., 2.);
    TH1F * hE11_3_4GeV   = new TH1F( "hE11_3_4GeV", "E11_3_4GeV", 100, -2., 2.);
    TH1F * hE11_5_10GeV  = new TH1F( "hE11_5_10GeV", "E11_5_10GeV", 100, -2., 2.);

    //
    TH1F * hE11H5_1_2GeV   = new TH1F( "hE11H5_1_2GeV", "E11H5_1_2GeV", 40, -2., 2.);
    TH1F * hE11H5_3_4GeV   = new TH1F( "hE11H5_3_4GeV", "E11H5_3_4GeV", 40, -2., 2.);
    TH1F * hE11H5_5_10GeV  = new TH1F( "hE11H5_5_10GeV", "E11H5_5_10GeV", 40, -2., 2.);

    //   TH1F * hEH11x5 = new TH1F( "hEH11x5", "EH11x5", 200, -2., 2.);
    //   TH2F * hresp2 = new TH2F( "hresp2", "resp2", 200, -2., 2.,200, -2., 2.);

    // prepare for graph
    Float_t ptgr[nptbins], eptgr[nptbins];
    for(Int_t i = 0; i < nptbins; i++) {
        ptgr[i]  = 0.5*(pt[i]+pt[i+1]);
        eptgr[i] = 0.5*(pt[i+1]-pt[i]);
        cout <<" i = " << i <<" pT = " << ptgr[i] <<" err pT = " << eptgr[i] << endl;
    }

    // number of eta bins and intervals
    const Int_t netabins = 12;
    const Int_t netacuts = netabins+1;
    Float_t eta[netacuts]= {0.01, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4};
    cout <<"  Eta bins " << endl;
    // prepare eta points for graph
    Float_t etagr[netabins], eetagr[netabins];
    for(Int_t i = 0; i < netabins; i++) {
        etagr[i]  = 0.5*(eta[i]+eta[i+1]);
        eetagr[i] = 0.5*(eta[i+1]-eta[i]);
        cout <<" i = " << i <<" Eta = " << etagr[i] <<" err Eta = " << eetagr[i] << endl;
    }

    // ===> for pi- and pi+
    // N total and N reco tracks
    // efficiency and error as a function of pT
    Int_t ntrk[nptbins]     = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    Int_t ntrkreco[nptbins] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    Int_t ntrkrecor[nptbins] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    Float_t trkeff[nptbins], etrkeff[nptbins];
    Double_t responceVSpt[nptbins]  = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    Double_t responceVSptF[nptbins];
    Double_t eresponceVSpt[nptbins] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

    // N total and N reco tracks
    // efficiency and error as a function of eta
    Int_t ntrketa[netabins]     = {0,0,0,0,0,0,0,0,0,0,0,0};
    Int_t ntrketareco[netabins] = {0,0,0,0,0,0,0,0,0,0,0,0};
    Int_t ntrketarecor[netabins] = {0,0,0,0,0,0,0,0,0,0,0,0};
    Float_t trketaeff[netabins], etrketaeff[netabins];
    Double_t responceVSeta[nptbins]  = {0,0,0,0,0,0,0,0,0,0,0,0};
    Double_t responceVSetaF[nptbins];
    Double_t eresponceVSeta[nptbins] = {0,0,0,0,0,0,0,0,0,0,0,0};

    //
    Int_t Ntot = 0;
    for (Long64_t jentry=0; jentry<nentries; jentry++) {
        Long64_t ientry = LoadTree(jentry);
        if (ientry < 0) break;
        nb = fChain->GetEntry(jentry);
        nbytes += nb;
        Ntot = Ntot + 1;
        // if (Cut(ientry) < 0) continue;
        // evaluate as a function of pT
        for(Int_t i = 0; i < nptbins; i++) {
            // ==> pi+
            if(ptSim1 >= pt[i] && ptSim1 < pt[i+1]) {
                ntrk[i] = ntrk[i]+1;
                // number of reco tracks
                if(drTrk1 < 0.01 && purityTrk1 == 1) {
                    ntrkreco[i] = ntrkreco[i]+1;
                    Double_t theta = 2.*atan(exp(-etaSim1));
                    Double_t eSim1 = ptSim1/sin(theta);
                    if(e1ECAL11x11 > -1000. && e1HCAL5x5 > -1000. && fabs(etaSim1) < 1.0) {
                        //	    if(e1ECAL11x11 > -1000. && e1HCAL5x5 > -1000. && fabs(etaSim1) < 1000) {
                        ntrkrecor[i] = ntrkrecor[i]+1;

                        Double_t e_ecal11 = e1ECAL11x11/eSim1;
                        Double_t e_ecal7  = e1ECAL7x7/eSim1;
                        Double_t e_hcal5  = e1HCAL5x5/eSim1;
                        Double_t e_hcal3  = e1HCAL3x3/eSim1;

                        Double_t e_ecalhcal11x5 = e_ecal11 + e_hcal5;
                        Double_t e_ecalhcal11x3 = e_ecal11 + e_hcal3;
                        Double_t e_ecalhcal7x5  = e_ecal7 + e_hcal5;
                        Double_t e_ecalhcal7x3  = e_ecal7 + e_hcal3;

                        responceVSpt[i] = responceVSpt[i] + e_ecalhcal11x5;

                        hprEH11x5->Fill(ptSim1,e_ecalhcal11x5,1.);
                        hprEH11x3->Fill(ptSim1,e_ecalhcal11x3,1.);
                        hprEH7x5->Fill(ptSim1,e_ecalhcal7x5,1.);
                        hprEH7x3->Fill(ptSim1,e_ecalhcal7x3,1.);

                        hprH5->Fill(ptSim1,e_hcal5,1.);
                        hprH3->Fill(ptSim1,e_hcal3,1.);

                        //	      if(i == nptbins-1) {
                        if(i < 5) {
                            hH5_1_2GeV->Fill(e_hcal5,1.);
                            hH3_1_2GeV->Fill(e_hcal3,1.);
                            hE11_1_2GeV->Fill(e_ecal11,1.);
                            hE11H5_1_2GeV->Fill(e_ecalhcal11x5,1.);
                        }
                        if(i == 7) {
                            hH5_3_4GeV->Fill(e_hcal5,1.);
                            hH3_3_4GeV->Fill(e_hcal3,1.);
                            hE11_3_4GeV->Fill(e_ecal11,1.);
                            hE11H5_3_4GeV->Fill(e_ecalhcal11x5,1.);
                        }
                        if(i == 9) {
                            hH5_5_10GeV->Fill(e_hcal5,1.);
                            hH3_5_10GeV->Fill(e_hcal3,1.);
                            hE11_5_10GeV->Fill(e_ecal11,1.);
                            hE11H5_5_10GeV->Fill(e_ecalhcal11x5,1.);
                        }
                    }
                }
            }
            // ==> pi-
            if(ptSim2 >= pt[i] && ptSim2 < pt[i+1]) {
                ntrk[i] = ntrk[i]+1;
                // number of reco tracks
                if(drTrk2 < 0.01 && purityTrk2 == 1) {
                    ntrkreco[i] = ntrkreco[i]+1;
                    Double_t theta = 2.*atan(exp(-etaSim2));
                    Double_t eSim2 = ptSim2/sin(theta);
                    if(e2ECAL11x11 > -1000. && e2HCAL5x5 > -1000. && fabs(etaSim2) < 1.0) {
                        //	    if(e2ECAL11x11 > -1000. && e2HCAL5x5 > -1000. && fabs(etaSim2) < 1000.) {
                        ntrkrecor[i] = ntrkrecor[i]+1;

                        Double_t e_ecal11 = e2ECAL11x11/eSim2;
                        Double_t e_ecal7  = e2ECAL7x7/eSim2;
                        Double_t e_hcal5  = e2HCAL5x5/eSim2;
                        Double_t e_hcal3  = e2HCAL3x3/eSim2;

                        Double_t e_ecalhcal11x5 = e_ecal11 + e_hcal5;
                        Double_t e_ecalhcal11x3 = e_ecal11 + e_hcal3;
                        Double_t e_ecalhcal7x5  = e_ecal7 + e_hcal5;
                        Double_t e_ecalhcal7x3  = e_ecal7 + e_hcal3;

                        responceVSpt[i] = responceVSpt[i] + e_ecalhcal11x5;

                        hprEH11x5->Fill(ptSim2,e_ecalhcal11x5,1.);
                        hprEH11x3->Fill(ptSim2,e_ecalhcal11x3,1.);
                        hprEH7x5->Fill(ptSim2,e_ecalhcal7x5,1.);
                        hprEH7x3->Fill(ptSim2,e_ecalhcal7x3,1.);

                        hprH5->Fill(ptSim2,e_hcal5,1.);
                        hprH3->Fill(ptSim2,e_hcal3,1.);

                        //	      if(i == nptbins-1) {
                        if(i < 5) {
                            hH5_1_2GeV->Fill(e_hcal5,1.);
                            hH3_1_2GeV->Fill(e_hcal3,1.);
                            hE11_1_2GeV->Fill(e_ecal11,1.);
                            hE11H5_1_2GeV->Fill(e_ecalhcal11x5,1.);
                        }
                        if(i == 7) {
                            hH5_3_4GeV->Fill(e_hcal5,1.);
                            hH3_3_4GeV->Fill(e_hcal3,1.);
                            hE11_3_4GeV->Fill(e_ecal11,1.);
                            hE11H5_3_4GeV->Fill(e_ecalhcal11x5,1.);
                        }
                        if(i == 9) {
                            hH5_5_10GeV->Fill(e_hcal5,1.);
                            hH3_5_10GeV->Fill(e_hcal3,1.);
                            hE11_5_10GeV->Fill(e_ecal11,1.);
                            hE11H5_5_10GeV->Fill(e_ecalhcal11x5,1.);
                        }
                    }
                }
            }
        }
        // Nick
        // evaluate efficiency as a function on eta
        for(Int_t i = 0; i < netabins; i++) {
            // ==> pi+
            if(fabs(etaSim1) >= eta[i] && fabs(etaSim1) < eta[i+1]) {
                // number of sim tracks in pt interval
                ntrketa[i] = ntrketa[i]+1;
                // number of reco tracks
                if(drTrk1 < 0.04 && purityTrk1 >= 0.7) {
                    Double_t theta = 2.*atan(exp(-etaSim1));
                    Double_t eSim1 = ptSim1/sin(theta);
                    ntrketareco[i] = ntrketareco[i]+1;
                    if(e1ECAL11x11 > -1000. && e1HCAL5x5 > -1000.) {
                        ntrketarecor[i] = ntrketarecor[i]+1;
                        responceVSeta[i] = responceVSeta[i] + (e1ECAL7x7 + e1HCAL3x3)/eSim1;
                    }
                }
            }
            // ==> pi-
            if(fabs(etaSim2) >= eta[i] && fabs(etaSim2) < eta[i+1]) {
                // number of sim tracks in pt interval
                ntrketa[i] = ntrketa[i]+1;
                // number of reco tracks
                if(drTrk2 < 0.04 && purityTrk2 >= 0.7) {
                    ntrketareco[i] = ntrketareco[i]+1;
                    Double_t theta = 2.*atan(exp(-etaSim2));
                    Double_t eSim2 = ptSim2/sin(theta);
                    if(e2ECAL11x11 > -1000. && e2HCAL5x5 > -1000.) {
                        ntrketarecor[i] = ntrketarecor[i]+1;
                        responceVSeta[i] = responceVSeta[i] + (e2ECAL7x7 + e2HCAL3x3)/eSim2;
                    }
                }
            }
        }
    }

    // calculate efficiency and full graph
    for(Int_t i = 0; i < nptbins; i++) {
        if(ntrk[i] > 0) {
            trkeff[i] = 1.*ntrkreco[i]/ntrk[i];
            etrkeff[i] = sqrt( trkeff[i]*(1.-trkeff[i])/ntrk[i] );
            //       responceVSptF[i] = responceVSpt[i]/ntrkrecor[i];
            cout <<" i = " << i
                 <<" pt interval = " << pt[i] <<" - " << pt[i+1]
                 <<" ntrkreco[i] = " << ntrkreco[i]
                 <<" ntrkrecor[i] = " << ntrkrecor[i]
                 <<" ntrk[i] = " << ntrk[i]
                 <<" eff = " << trkeff[i] << endl;
            //       	    <<" responce = " << responceVSptF[i] << endl;
        }
    }
    // calculate efficiency vs Eta and full graph
    cout <<" Efficiency vs Eta " << endl;
    for(Int_t i = 0; i < netabins; i++) {
        if(ntrketa[i] > 0) {
            trketaeff[i] = 1.*ntrketareco[i]/ntrketa[i];
            etrketaeff[i] = sqrt( trketaeff[i]*(1.-trketaeff[i])/ntrketa[i] );
            responceVSetaF[i] = responceVSeta[i]/ntrketarecor[i];
            cout <<" i = " << i
                 <<" eta interval = " << eta[i] <<" - " << eta[i+1]
                 <<" ntrketareco[i] = " << ntrketareco[i]
                 <<" ntrketa[i] = " << ntrketa[i]
                 <<" eff = " << trketaeff[i]
                 <<" responce = " << responceVSetaF[i] << endl;
        }
    }

    // create graph
    //  vs pT
    setTDRStyle(1,0);
    TCanvas* c1 = new TCanvas("X","Y",1);
    TGraph *grpt  = new TGraphErrors(nptbins,ptgr,trkeff,eptgr,etrkeff);
    TAxis* xaxis = grpt->GetXaxis();
    grpt->GetXaxis()->SetTitle("p_{T}, GeV");
    grpt->GetYaxis()->SetTitle("track finding efficiency");
    xaxis->SetLimits(0.8,50.);
    grpt->SetMarkerStyle(21);
    grpt->SetMaximum(0.9);
    grpt->SetMinimum(0.6);
    grpt->Draw("AP");
    TLatex *t = new TLatex();
    t->SetTextSize(0.042);
    //   TLegend *leg = new TLegend(0.5,0.2,0.7,0.35,NULL,"brNDC");
    //   leg->SetFillColor(10);
    //   leg->AddEntry(grpt,"#pi ^{+} and #pi ^{-}","P");
    //   leg->Draw();
    t->DrawLatex(1.,0.85,"CMSSW169, single #pi ^{+} and #pi ^{-}. |#eta ^{#pi}|< 2.5");
    c1->SaveAs("trkeff_vs_pt.gif");
    c1->SaveAs("trkeff_vs_pt.eps");

    setTDRStyle(0,0);
    //  vs Eta
    TCanvas* c2 = new TCanvas("X","Y",1);
    TGraph *greta = new TGraphErrors(netabins,etagr,trketaeff,eetagr,etrketaeff);
    TAxis* xaxis = greta->GetXaxis();
    greta->GetXaxis()->SetTitle("#eta");
    greta->GetYaxis()->SetTitle("track finding efficiency");
    xaxis->SetLimits(0.0,2.4);
    greta->SetMarkerStyle(21);
    greta->SetMaximum(1.0);
    greta->SetMinimum(0.50);
    greta->Draw("AP");
    TLatex *t = new TLatex();
    t->SetTextSize(0.042);
    //   TLegend *leg = new TLegend(0.5,0.2,0.7,0.35,NULL,"brNDC");
    //   leg->SetFillColor(10);
    //   leg->AddEntry(greta,"#pi ^{+} and #pi ^{-}","P");
    //   leg->Draw();
    t->DrawLatex(0.3,0.87,"CMSSW217, single #pi ^{+} and #pi ^{-}");
    t->DrawLatex(0.8,0.85,"1 < p^{#pi^{#pm}} < 50 GeV");
    c2->SaveAs("trkeff_vs_eta.gif");
    c2->SaveAs("trkeff_vs_eta.eps");

    cout <<" Ntot = " << Ntot << endl;

    /*
    setTDRStyle(1,0);
    //
    TCanvas* c3 = new TCanvas("X","Y",1);
    TAxis* xaxis = hEH->GetXaxis();
    hEH->GetXaxis()->SetTitle("p_{T} of #pi ^{+} and #pi ^{-}, GeV");
    hEH->GetYaxis()->SetTitle("(ECAL11x11+HCAL5x5)/E^{true}");
    //   xaxis->SetLimits(1.2,50.);
    hEH->SetMarkerStyle(21);
    hEH->SetMaximum(0.9);
    hEH->SetMinimum(0.2);
    hEH->Draw();
    c3->SaveAs("EmatrixtWithZSP11x11.5x5.gif");

    setTDRStyle(1,0);
    //
    TCanvas* c4 = new TCanvas("X","Y",1);
    TAxis* xaxis = hEmatrix->GetXaxis();
    hHmatrix->GetXaxis()->SetTitle("p_{T} of #pi ^{+} and #pi ^{-}, GeV");
    hHmatrix->GetYaxis()->SetTitle("HCAL3x3/E^{true}");
    //   xaxis->SetLimits(1.2,50.);
    hHmatrix->SetMarkerStyle(21);
    hHmatrix->SetMaximum(0.9);
    hHmatrix->SetMinimum(-0.2);
    hHmatrix->Draw();
    c4->SaveAs("HmatrixWithNoZSP3x3.gif");

    setTDRStyle(0,0);
    TCanvas* c5 = new TCanvas("X","Y",1);
    hresp2->Draw("hist");

    setTDRStyle(0,0);
    TCanvas* c6 = new TCanvas("X","Y",1);
    hhcal->Draw("hist");
    */

    TFile efile("sr_barrel.root","recreate");

    hprEH11x5->Write();
    hprEH11x3->Write();
    hprEH7x5->Write();
    hprEH7x3->Write();
    hprH5->Write();
    hprH3->Write();
    hH5_1_2GeV->Write();
    hH3_1_2GeV->Write();
    hH5_3_4GeV->Write();
    hH3_3_4GeV->Write();
    hH5_5_10GeV->Write();
    hH3_5_10GeV->Write();
    hE11_1_2GeV->Write();
    hE11_3_4GeV->Write();
    hE11_5_10GeV->Write();
    hE11H5_1_2GeV->Write();
    hE11H5_3_4GeV->Write();
    hE11H5_5_10GeV->Write();

    efile.Close();
}
Exemple #12
0
void JetHij::Loop()
{
//   In a ROOT session, you can do:
//      Root > .L JetHij.C
//      Root > JetHij t
//      Root > t.GetEntry(12); // Fill t data members with entry number 12
//      Root > t.Show();       // Show values of entry 12
//      Root > t.Show(16);     // Read and show values of entry 16
//      Root > t.Loop();       // Loop on all entries
//

//     This is the loop skeleton where:
//    jentry is the global entry number in the chain
//    ientry is the entry number in the current Tree
//  Note that the argument to GetEntry must be:
//    jentry for TChain::GetEntry
//    ientry for TTree::GetEntry and TBranch::GetEntry
//
//       To read only selected branches, Insert statements like:
// METHOD1:
//    fChain->SetBranchStatus("*",0);  // disable all branches
//    fChain->SetBranchStatus("branchname",1);  // activate branchname
// METHOD2: replace line
//    fChain->GetEntry(jentry);       //read all branches
//by  b_branchname->GetEntry(ientry); //read only this branch
   if (fChain == 0) return;

   Long64_t nentries = fChain->GetEntriesFast();

   Long64_t nbytes = 0, nb = 0;
//
   Double_t M_PI = 3.14159265358979323846;
   Double_t M_PI2 = 3.14159265358979323846*2.;
//===> Histograms
// CENTRALITY_BIN
   TH1F *h_centrality   = new TH1F("h_centrality","",100,0., 100.);

// Mean ETGEN
   TH1F *h_Etgen_75_85 = new TH1F("h_Etgen_75_85","",70, 60., 90.);
   TH1F *h_Etgen_85_95 = new TH1F("h_Etgen_85_95","",70, 70., 100.);
   TH1F *h_Etgen_95_105 = new TH1F("h_Etgen_95_105","",70, 80., 110.);
   TH1F *h_Etgen_105_115 = new TH1F("h_Etgen_105_115","",70, 90., 120.);

// Etrec/ETgen - reconstructed from calotowers
   TH1F *h_EtrecEtgen_75_85 = new TH1F("h_EtrecEtgen_75_85","",70, 0., 2.);
   TH1F *h_EtrecEtgen_85_95 = new TH1F("h_EtrecEtgen_85_95","",70, 0., 2.);
   TH1F *h_EtrecEtgen_95_105 = new TH1F("h_EtrecEtgen_95_105","",70, 0., 2.);
   TH1F *h_EtrecEtgen_105_115 = new TH1F("h_EtrecEtgen_105_115","",70, 0., 2.);

// Etcorzsjpt/ETgen - jpt + ZS
   TH1F *h_EtcorzsjptEtgen_75_85 = new TH1F("h_EtcorzsjptEtgen_75_85","",70, 0., 2.);
   TH1F *h_EtcorzsjptEtgen_85_95 = new TH1F("h_EtcorzsjptEtgen_85_95","",70, 0., 2.);
   TH1F *h_EtcorzsjptEtgen_95_105 = new TH1F("h_EtcorzsjptEtgen_95_105","",70, 0., 2.);
   TH1F *h_EtcorzsjptEtgen_105_115 = new TH1F("h_EtcorzsjptEtgen_105_115","",70, 0., 2.);

//===>

   Int_t ifile = 0;  

   for (Long64_t jentry=0; jentry<nentries;jentry++) {
      Long64_t ientry = LoadTree(jentry);

//       cout <<" Event= "<<ientry<<endl;
      if(ientry == 0) {
        cout<<" New file "<<ifile<<endl;
        ifile++;
      }

      if (ientry < 0) break;
      nb = fChain->GetEntry(jentry);   nbytes += nb;
      // if (Cut(ientry) < 0) continue;

//===>
         Float_t centrality = centrality_bin;

      if( NumGenJets == 0 ) continue;
      if( NumRecoJetsCaloTower == 0  )  continue;
      if( NumRecoJetsJPTCorrected2 == 0  )  continue;

      Int_t njets = NumRecoJetsCaloTower;
      for( Int_t myjet=0;myjet<njets;myjet++)
      {
      //
//  Matching with Genjets
//
     Int_t firstgen = -1;

     for(Int_t i=0; i<NumGenJets; i++)
     {

         Float_t deta2 = JetGenEta[i]-JetRecoEtaCaloTower[myjet];
         Float_t dphi2 = fabs(JetGenPhi[i]-JetRecoPhiCaloTower[myjet]);
         if( dphi2 > M_PI ) dphi2 = M_PI2 - dphi2;
         Float_t dr0 = sqrt(dphi2*dphi2+deta2*deta2);
         if( dr0 < 0.3 ) firstgen = i;

     } // Cycle on GenJets

    if( firstgen < 0 ) continue;

//
// Matching with JPT+ZS corrected jets
//
     Int_t firstcor = -1;

     cout<<"NumRecoJetsJPTCorrected2="<<NumRecoJetsJPTCorrected2<<endl;

     for(Int_t i=0; i<NumRecoJetsJPTCorrected2; i++)
     {
         Float_t deta2 = JetRecoEtaJPTCorrected2[i]-JetRecoEtaCaloTower[myjet];
         Float_t dphi2 = fabs(JetRecoPhiJPTCorrected2[i]-JetRecoPhiCaloTower[myjet]);
         if( dphi2 > M_PI ) dphi2 = M_PI2 - dphi2;
         Float_t dr0 = sqrt(dphi2*dphi2+deta2*deta2);
         if( dr0 < 0.3 ) firstcor = i;

     } // Cycle on CorrJets
     if( firstcor < 0 ) continue;
// Filling histograms
     //cout<<"firstgen="<< firstgen<<" firstcor= "<<firstcor<<endl;
     Float_t etgen,etagen,etcalo,etcorzsjpt;
     etcalo = JetRecoEtCaloTower[myjet];
     etgen = JetGenEt[firstgen];
     etagen = JetGenEta[firstgen];
     etcorzsjpt = JetRecoEtJPTCorrected2[firstcor];

     Float_t ratio = etcalo/etgen;
     Float_t ratio_corzsjpt = etcorzsjpt/etgen;

     if(fabs(etagen)>1.4) continue;

         if(75.<etgen&& etgen<85.) {
           h_EtrecEtgen_75_85->Fill(ratio);
//           h_EtcorzsEtgen_75_85->Fill(ratio_corzs);
           h_EtcorzsjptEtgen_75_85->Fill(ratio_corzsjpt);
         }
         if(85.<etgen&& etgen<95.) {
           h_EtrecEtgen_85_95->Fill(ratio);
//           h_EtcorzsEtgen_85_95->Fill(ratio_corzs);
           h_EtcorzsjptEtgen_85_95->Fill(ratio_corzsjpt);
         }
         if(95.<etgen&& etgen<105.) {
           h_EtrecEtgen_95_105->Fill(ratio);
//           h_EtcorzsEtgen_95_105->Fill(ratio_corzs);
           h_EtcorzsjptEtgen_95_105->Fill(ratio_corzsjpt);
         }
         if(105.<etgen&& etgen<115.) {
           h_EtrecEtgen_105_115->Fill(ratio);
//           h_EtcorzsEtgen_105_115->Fill(ratio_corzs);
           h_EtcorzsjptEtgen_105_115->Fill(ratio_corzsjpt);
         }

    } // calojets
//  } // Nevents

//===>
         h_centrality       -> Fill(centrality);

   } // Nevents

     TFile efile("histo.root","recreate");

     h_centrality       ->  Write();

// Gen and rec mean
    h_Etgen_75_85->Write();
    h_Etgen_85_95->Write();
    h_Etgen_95_105->Write();
    h_Etgen_105_115->Write();

    h_EtrecEtgen_75_85->Write();
    h_EtrecEtgen_85_95->Write();
    h_EtrecEtgen_95_105->Write();
    h_EtrecEtgen_105_115->Write();

    h_EtcorzsjptEtgen_75_85->Write();
    h_EtcorzsjptEtgen_85_95->Write();
    h_EtcorzsjptEtgen_95_105->Write();
    h_EtcorzsjptEtgen_105_115->Write();

          efile.Close();

}
Exemple #13
0
int emain()
{ 
  bool cl=false;
  bool sl=false;
  bool al=false;
  bool cdist=false;
  epregister(cl);
  epregister(sl);
  epregister(al);
  epregister(cdist);
  epregisterFunc(help);

  dfuncpart.choice=0;
  dfuncpart.add("gap",edistfunc(part_calc_dists_u<estrarray,eseqdist,dist_compressed2>,dist_compressed2));
  dfuncpart.add("nogap",edistfunc(part_calc_dists_u<estrarray,eseqdist,dist_nogap_compressed2>,dist_nogap_compressed2));
  dfuncpart.add("gap2",edistfunc(part_calc_dists_u<estrarray,eseqdist,dist_compressed>,dist_compressed));
  dfuncpart.add("nogap2",edistfunc(part_calc_dists_u<estrarray,eseqdist,dist_nogap_compressed>,dist_nogap_compressed));
  dfuncpart.add("nogapsingle",edistfunc(part_calc_dists_u<estrarray,eseqdist,dist_nogapsingle_compressed>,dist_nogapsingle_compressed));
  dfuncpart.add("tamura",edistfunc(part_calc_dists_u<estrarray,eseqdist,dist_tamura_compressed>,dist_tamura_compressed));
  epregister(dfuncpart);

  dfunc.choice=0;
  dfunc.add("gap",edistfunc(t_calc_dists_u<estrarray,eseqdist,eblockarray<eseqdist>,dist_compressed2>,dist_compressed2));
  dfunc.add("nogap",edistfunc(t_calc_dists_u<estrarray,eseqdist,eblockarray<eseqdist>,dist_nogap_compressed2>,dist_nogap_compressed2));
  dfunc.add("gap2",edistfunc(t_calc_dists_u<estrarray,eseqdist,eblockarray<eseqdist>,dist_compressed>,dist_compressed));
  dfunc.add("nogap2",edistfunc(t_calc_dists_u<estrarray,eseqdist,eblockarray<eseqdist>,dist_nogap_compressed>,dist_nogap_compressed));
  dfunc.add("nogapsingle",edistfunc(t_calc_dists_u<estrarray,eseqdist,eblockarray<eseqdist>,dist_nogapsingle_compressed>,dist_nogapsingle_compressed));
  dfunc.add("tamura",edistfunc(t_calc_dists_u<estrarray,eseqdist,eblockarray<eseqdist>,dist_tamura_compressed>,dist_tamura_compressed));

  epregisterClass(eoption<edistfunc>);
  epregisterClassMethod4(eoption<edistfunc>,operator=,int,(const estr& val),"=");

  epregister(dfunc);

  epregister(winlen);

  estr ofile;
  estr dfile;
  estr dupfile;

  epregister(dupfile);
  epregister(ignoreUnique);
  epregister(t);
  epregister(nthreads);
  epregister(ofile);
  epregister(dfile);
  epregister(ignoreMemThres);

  getParser()->actions.add("makereps",actionMakeReps);
  getParser()->actions.add("makeotus",actionMakeOtus);
  getParser()->actions.add("makeotus_mothur",actionMakeOtusMothur);
  getParser()->actions.add("makepart",actionMakePart);
  eparseArgs(argvc,argv);

//  cout << "# initializing identity lookup table" << endl;
//  initLookupTable();

  if(argvc<2) {
    cout << "syntax: "+efile(argv[0]).basename()+" <-sl true|-cl true|-al true> <seqali>" << endl;
    cout << "\""+efile(argv[0]).basename()+ " --help\" for more help" << endl;
    exit(-1);
  }
  if(!cl && !sl && !al) {
    cout << "syntax: "+efile(argv[0]).basename()+" <-sl true|-cl true|-al true> <seqali>" << endl;
    cout << "please choose at least one clustering method <-sl true|-cl true|-al true>" << endl;
    cout << "\""+efile(argv[0]).basename()+ " --help\" for more help" << endl;
    exit(-1);
  }

  cout << "# " << date() << endl;
  cout << "# " << args2str(argvc,argv) << endl;
  cout << "# system RAM: " << getSystem()->getTotalRam()/1024 << "Mb" << endl;
  cout << "# free system RAM: " << (getSystem()->getFreeRam()+getSystem()->getBufferRam())/1024 << "Mb" << endl;
  cout << "# process memory limit: " << ((getSystem()->getMemLimit()&0x3fffffffffffff)==0x3fffffffffffff?estr("unlimited"):estr(getSystem()->getMemLimit()/1024/1024)+"Mb") << endl;

  warnMemThres=MIN(MIN(getSystem()->getTotalRam(),getSystem()->getMemLimit()/1024),getSystem()->getFreeRam()+getSystem()->getBufferRam())*0.6/1024;
  exitMemThres=MIN(MIN(getSystem()->getTotalRam(),getSystem()->getMemLimit()/1024),getSystem()->getFreeRam()+getSystem()->getBufferRam())*0.65/1024;

  cout << "# warning memory threshold: " << warnMemThres << "Mb" << endl;
  cout << "# exit memory threshold: " << exitMemThres << "Mb" << endl;

  cout << "# distance function: " << dfunc.key() << endl;

  if (ofile.len()==0)
    ofile=argv[1];

  epregisterClass(eseqdist);
  epregisterClassSerializeMethod(eseqdist);
  epregisterClassProperty(eseqdist,dist);
  epregisterClassProperty(eseqdist,x);
  epregisterClassProperty(eseqdist,y);

  epregisterClass(ebasicarray<eseqdist>);
  epregisterClassInheritance(ebasicarray<eseqdist>,ebasearray);
  epregisterClassMethod(ebasicarray<eseqdist>,subset);
  epregisterClassSerializeMethod(ebasicarray<eseqdist>);

  long i,j;
  cout << "# loading seqs file: " << argv[1] << endl;
  load_seqs_compressed(argv[1],arr,seqlen);
#ifndef HPC_CLUST_USE_LONGIND
  ldieif(arr.size() > (2l<<31),"To cluster more than 2 million sequences please recompile hpc-clust with the --enable-longind flag.");
#endif

  ebasicarray<INDTYPE> uniqind;
  earray<ebasicarray<INDTYPE> > dupslist;
  finduniq(uniqind,dupslist);
  cout << "# unique seqs: " << uniqind.size() << endl;


  if (dupfile.len()){
    efile dupf(dupfile,"w");
    for (i=0; i<dupslist.size(); ++i){
      dupf.write(estr(dupslist[i][0])+" "+estr(dupslist[i].size()));
      for (j=1; j<dupslist[i].size(); ++j)
        dupf.write(estr(" ")+dupslist[i][j]);
      dupf.write("\n");
    }
    dupf.close();
  }

  long maxdists=uniqind.size()*(uniqind.size()-1)/2;
  long maxmem=maxdists*sizeof(eseqdist)/1024/1024;
  cout << "# maximum number of distance pairs: " << maxdists << " (" << maxmem << "Mb)" << endl;

  if (maxmem > warnMemThres){
    cout << "# WARNING: Number of sequences provided may require more memory than is currently available on this system." << endl;
    cout << "#           Please monitor the memory usage of this program and check the log at the end. This program will" << endl;
    cout << "#           automatically exit if it reaches the exitMemThres value shown above. You can force the program" << endl;
    cout << "#           to ignore this threshold using the argument: -ignoreMemThres true" << endl;
    cout << "#           Memory requirements can be reduced by increasing the clustering threshold, or reducing the number" << endl;
    cout << "#           of sequences to be clustered. For more information and tips on optimizing hpc-clust memory" << endl;
    cout << "#           usage please refer to the documentation." << endl;
  }

  
  float dtime,stime;
  etimer t1;
  t1.reset();

  efile df(dfile);
  cout << "# computing distances" << endl;
//  if ((arr.size()-1l)*arr.size()/2l/partsTotal > 10000l) partsTotal=(arr.size()-1l)*arr.size()/2l/10000l;  // make more tasks if too many calculations per task
  if (partsTotal>(arr.size()-1l)*arr.size()/20l) partsTotal=(arr.size()-1l)*arr.size()/20l; // make fewer tasks if to few calculations per task

//  cout << "partsTotal: " << partsTotal << endl;
  cerr << endl; // needed for keeping track of the progress

  for (i=0; i<partsTotal; ++i)
    taskman.addTask(dfunc.value().calcfunc,evararray(mutex,uniqind,arr,dists,(const int&)seqlen,(const long int&)i,(const long int&)partsTotal,(const float&)t,(const int&)winlen));

  taskman.createThread(nthreads);
  taskman.wait();
  cerr << endl;

  dtime=t1.lap()*0.001;
  cout << "# time calculating distances: " << dtime << endl;
  cout << "# distances within threshold: " << dists.size() << endl;

  cout << "# number of tasks: " << taskman.tasks.size() << endl;
  fradix256sort<eblockarray<eseqdist>,radixKey>(dists);
  cout << "# number of tasks: " << taskman.tasks.size() << endl;
  stime=t1.lap()*0.001;

  if (dfile.len()){
    cout << "# saving distances to file: "<<dfile << endl;
    for (i=0; i<dists.size(); ++i)
      df.write(estr(arr.keys(dists[i].x))+"\t"+arr.keys(dists[i].y)+"\t"+(1.0-dists[i].dist)+"\n");
/*
    for (i=0; i<dupslist.size(); ++i){
      for (j=1; j<dupslist[i].size(); ++j)
        df.write(estr(dupslist[i][0])+" "+dupslist[i][j]+" 1.0\n");
    }
*/
    df.close();
  }
//  }else{
//    cout << "# loading distances from file: "<<dfile << endl;
/*
    estr str;
    df.read(str);
    ldieif(mindists.unserial(str,0)==-1,"problem loading distance file: "+dfile);
    df.close();
*/
//  } 

  totaldists=dists.size();
  cout << "# time sorting distances: " << stime << endl;

  cout << "# initializing cluster"<<endl;
  if (cl)
    clcluster.init(arr.size(),ofile+".cl",argv[1],dupslist);
  if (sl)
    slcluster.init(arr.size(),ofile+".sl",argv[1],dupslist);
  if (al)
    alcluster.init(arr.size(),ofile+".al",argv[1],dupslist,t,dfunc.value().calcfunc_single,arr,seqlen);

  cout << "# starting clustering"<<endl;
  t1.reset();
  for (i=dists.size()-1; i>=0; --i){
    if (cl)
      clcluster.add(dists[i]);
    if (al)
      alcluster.add(dists[i]);
    if (sl)
      slcluster.add(dists[i]);
  }
  if (al)
    alcluster.finalize();

  float clustime=t1.lap()*0.001;
  cout << "# time calculating distances: " << dtime << endl;
  cout << "# time sorting distances: " << stime << endl;
  cout << "# time clustering: " << clustime << endl;
  cout << "# total time: " << dtime+clustime+stime << endl;
  cout << "# distances within threshold: " << totaldists << endl;

  if (cdist){
    efile fsl,fcl,fal;
    if (sl) fsl.open(ofile+".sl.dist","w");
    if (cl) fcl.open(ofile+".cl.dist","w");
    if (al) fal.open(ofile+".cl.dist","w");

    for (i=dists.size()-1; i>=0; --i){
      if (sl) fsl.write(estr(dists[i].x)+" "+dists[i].y+" "+dists[i].dist+" "+slcluster.clusterData.getMergeDistance(dists[i].x,dists[i].y)+"\n");
      if (cl) fcl.write(estr(dists[i].x)+" "+dists[i].y+" "+dists[i].dist+" "+clcluster.clusterData.getMergeDistance(dists[i].x,dists[i].y)+"\n");
      if (al) fal.write(estr(dists[i].x)+" "+dists[i].y+" "+dists[i].dist+" "+alcluster.clusterData.getMergeDistance(dists[i].x,dists[i].y)+"\n");
    }
  }
  return(0);
}
Exemple #14
0
void actionMakeReps()
{
  ldieif(argvc<3,"syntax: "+efile(argv[0]).basename()+" -makereps <alignment> <otu>");
  estrhashof<INDTYPE> seqind;

  estrarray uarr;

  cout << "# loading seqs file: " << argv[1] << endl;
  load_seqs_compressed(argv[1],arr,seqind,seqlen);
  load_seqs(argv[1],uarr);

  earray<ebasicarray<INDTYPE> > otus;

  efile f;
  estr line;
  estrarray parts;
  f.open(argv[2],"r");
  while (!f.eof()){
    f.readln(line);
    if (line.len()==0 || line[0]=='#') continue;
    if (line[0]=='>'){
      otus.add(ebasicarray<INDTYPE>());
      continue;
    }
    ldieif(otus.size()==0,"first entry not start of OTU or missing '>'");
    parts=line.explode("\t");
    ldieif(parts.size()==0,"array empty: "+line);
    ldieif(!seqind.exists(parts[0]),"sequence not found: "+parts[0]);
    otus[otus.size()-1].add(seqind[parts[0]]);
  }

  cerr << endl;

  ebasicarray<INDTYPE> tuniqind;
  earray<ebasicarray<INDTYPE> > dupslist;
  finduniq(tuniqind,dupslist);

  eintarray uniqmask;
  uniqmask.init(arr.size(),0);
  for (long i=0; i<tuniqind.size(); ++i)
    uniqmask[tuniqind[i]]=dupslist[i].size();


//  ebasicarray<INDTYPE> uniqind;
  taskman.createThread(nthreads);

  ebasicarray<INDTYPE> uniqind;
  const float t=0.0;
  efloatarray avgdist;
  for (long j=0; j<otus.size(); ++j){
//    cout << "# computing distances for otu "<< j << " size: " << otus[j].size() <<  endl;
    if (otus[j].size()==1){
      cout << ">OTU" << j << " " << arr.keys(otus[j][0]) << " avg_id=1.0 otu_size=1" << endl;
      cout << uarr.values(otus[j][0]) << endl;
      continue;
    }
    uniqind.clear();
    for (long l=0; l<otus[j].size(); ++l){
      if (uniqmask[otus[j][l]]!=0)
        uniqind.add(otus[j][l]);
    }
//    uniqind=otus[j];
    ldieif(uniqind.size()==0,"empty OTU");

    if (uniqind.size()==1){
      cout << ">OTU" << j << " " << arr.keys(uniqind[0]) << " avg_id=1.0 otu_size=" << otus[j].size() << endl;
      cout << uarr.values(uniqind[0]) << endl;
      continue;
    }
    avgdist.clear();
    avgdist.init(arr.size(),0.0);
    dists.clear();
  
    partsTotal=10000;
    if (partsTotal>(uniqind.size()-1l)*uniqind.size()/20l) partsTotal=(uniqind.size()-1l)*uniqind.size()/20l; // make fewer tasks if to few calculations per task
    if (partsTotal<=0) partsTotal=1;
    
    taskman.clear();
    for (long i=0; i<partsTotal; ++i)
      taskman.addTask(dfunc.value().calcfunc,evararray(mutex,uniqind,arr,dists,(const int&)seqlen,(const long int&)i,(const long int&)partsTotal,(const float&)t,(const int&)winlen));
    taskman.wait();
    for (long i=0; i<dists.size(); ++i){
      eseqdist& d(dists[i]);
      avgdist[d.x]+=d.dist*uniqmask[d.y];
      avgdist[d.y]+=d.dist*uniqmask[d.x];
//      cout << "# "<< arr.keys(d.x) << " " << arr.keys(d.y) << " " << d.dist << " " << uniqmask[d.x] << " " << uniqmask[d.y] << endl;
    }
    long k=uniqind[0];
    for (long i=0; i<uniqind.size(); ++i){
      long ti=uniqind[i];
      avgdist[ti]+=uniqmask[ti]-1;
      if (avgdist[k]<avgdist[ti]) {
//        cout << "# " << arr.keys(ti) << " " << ti << " " << uniqmask[ti] << " " << avgdist[ti] << " " << counts[ti] << endl;
        k=ti;
      }
    }
//    cout << "OTU" << j << " " << otus[j].size() << " " << arr.keys(k) << " " << avgdist[k]/(otus[j].size()-1) << " " << dists.size() << endl;
    cout << ">OTU" << j << " " << arr.keys(k) << " avg_id=" << avgdist[k]/(otus[j].size()-1) << " otu_size=" << otus[j].size() << endl;
    cout << uarr.values(k) << endl;
  }
  cerr << endl;

  exit(0);
}
Exemple #15
0
int main(){

sky sky1;

double Mu = M;   //Mass in MeV
complex <double> M_I(0,1);

// Create momentum space grid
std::vector<double> kmesh;
std::vector<double> kweights;
double const kmax = 5.0;
int const kpts = 300;
kmesh.resize( kpts );
kweights.resize( kpts );
GausLeg( 0., kmax, kmesh, kweights );

////////Input Parameters of the potential (fit parameters) /////
std::string parameters_filename="Input.inp";

NuclearParameters Nu = read_nucleus_parameters( "Input/nca40.inp" );

double Ef=Nu.Ef;
int lmax=6;
double z0=20.0;
double zp0;
double A0=40.0;
double tz=-0.5;

int type=1;
int mvolume = 4;
int AsyVolume = 1;

double A = 40.0;

double  mu = (A)/((A-1.));

if (tz>0) { zp0=1;}
else {zp0=0;}

double ph_gap = Nu.ph_gap;
cout<<"ph_gap = "<<Nu.ph_gap<<endl;
double  rStart = .05;
double  rmax = 20.;
int  ham_pts = 300; 

double  rdelt = rmax / ham_pts;

vector<double> dr;
dr.assign(ham_pts,rdelt);

// Construct Parameters Object
Parameters p = get_parameters( parameters_filename, Nu.A, Nu.Z, zp0 );

// Construct Potential Object
pot pottt = get_bobs_pot2( type, mvolume, AsyVolume, tz, Nu, p );
pot * pott = &pottt;

boundRspace initiate(rmax , ham_pts , Ef, ph_gap , lmax , Nu.Z , zp0 , Nu.A , pott);

 double Elower = -11.61818;
 double Eupper = -9.4;
 double jj = .5;
 int ll = 0;
 int Ifine = 1;
 initiate.searchNonLoc( Elower, Eupper, jj,  ll,  Ifine);
 initiate.exteriorWaveFunct(ll);
 initiate.normalizeWF();


double tol=.01;
double estart=Ef;

///// Making rmesh///

std::vector<double> rmesh_p= initiate.make_rmesh_point();
std::vector<double> rmesh= initiate.make_rmesh();

double  rdelt_p = rdelt / 1.025641026;

double Emax = 2*Ef;
double Emin=-200.0 + Emax;

//Generating the propagator

double J;

//Starting loop over L and J to construct the density matrix
//want to start at L=3 to see what QPE I find
lmax=6;
for(int L=0;L<lmax+1;L++){
	for(int s=0;s<2;s++){	
		J=L-0.5+s;
		if(J<0){
			J=0.5;
			s=1;
		}	

		string presky = "waves/neutron/data/ecut120/";

		string jlab = sky1.jlab(J);

		string llab = sky1.llab(L);
	
		cout<<endl;
		cout<<"L = "<<L<<" J = "<<J<<endl;
		cout<<endl;

		int N = 0;

		double QPE = initiate.find_level(rmesh, Ef, N, L, J, tol);

		//cout<<"    QPE = "<<QPE<<endl;

		//dom_nonlocal_r dom(Ef, N, L, J, rmesh, dr);
		matrix_t ham;
		ham.clear();
		//change this back to QPE when needed
		ham = initiate.re_hamiltonian(rmesh, QPE, L, J);

		matrix_t nonlocal;
		nonlocal.clear();
		nonlocal = initiate.nonlocal_ham(rmesh,QPE,L,J);

		/* string hamname = "waves/ham" + llab + jlab + ".txt";
		ofstream fham(hamname.c_str());
		
		double hmax=0.0;

		for(int i=0;i<kmesh.size();i++){
			for(int j=0;j<kmesh.size();j++){
				fham << ham(i,j) << " ";
				if(ham(i,j) > hmax){
					hmax = ham(i,j);
				}
			}
			fham<<endl;
		}
		fham.close();

		*/

		vector <eigen_t> hameig = initiate.real_eigvecs(ham);

		string ename = "waves/hameig" + llab + jlab + ".txt";
		ofstream efile(ename.c_str());

		cvector_t local(rmesh.size());

		double enorm = 0;

		double fac = -1.0 / ( pott->kconstant * mu );

		for(int i=0;i<rmesh.size();i++){
			enorm += pow(hameig[0].second[i], 2) * rdelt;
			local[i] = pott->localPart(rmesh[i]); /* - 2 * fac / pow( rdelt, 2 ) - fac * L * ( L + 1 ) / pow( rmesh[i], 2 ); */
			ham(i,i) -= real(local[i]);
		}

		/*

		ofstream hamfile("waves/ham.txt");

		for(int i=0;i<rmesh.size();i++){
			hamfile << ham(i,i) << endl;
		}

		hamfile.close();

		*/

		//cout << "enorm = " << enorm << endl;

		//cout << "initial ham eig = " << hameig[0].first << endl;

/*

		double kh;
		double kh2;	
		double kh3;
		
		for(int i=0;i<kmesh.size();i++){
			if(i%30 == 0){
				cout<<"i = "<<i<<endl;
			}
			for(int j=0;j<kmesh.size();j++){
				kh=0;
				kh2=0;
				kh3=0;
				for(int ii=0;ii<rmesh.size();ii++){
					//kh += bess_mtx(i,ii) * bess_mtx(j,ii) * (2.0/M_PI) * real(local[ii]) * pow(rmesh[ii], 2) * rdelt;
					kh += bess_mtx(i,ii) * bess_mtx(j,ii) * (2.0/M_PI) * real(local[ii]) * rmesh[ii] * rdelt;
					//kh3 += bess_mtx(i,ii) * bess_mtx(j,ii) * (2.0/M_PI) * real(local[ii]) * pow(rmesh[ii], 2) * rdelt;
					kh3 += bess_mtx(i,ii) * bess_mtx(j,ii) * (2.0/M_PI) * real(local[ii]) * rmesh[ii] * rdelt;
					for(int jj=0;jj<rmesh.size();jj++){
						//Assuming hamiltonian as not factors of rmesh in it
						kh += bess_mtx(i,ii) * bess_mtx(j,jj) * (2.0/M_PI) * nonlocal(ii,jj)*rmesh[ii]*rmesh[jj]*pow(rdelt,2);
						//kh += bess_mtx(i,ii) * bess_mtx(j,jj) * (2.0/M_PI) * nonlocal(ii,jj)*pow(rmesh[ii]*rmesh[jj]*rdelt,2);
						kh2 += bess_mtx(i,ii) * bess_mtx(j,jj) * (2.0/M_PI) * ham(ii,jj) * rmesh[ii] * rmesh[jj] * pow(rdelt,2);
						//kh2 += bess_mtx(i,ii) * bess_mtx(j,jj) * (2.0/M_PI) * ham(ii,jj) * pow(rmesh[ii] * rmesh[jj] *rdelt,2);
						kh3 += bess_mtx(i,ii) * bess_mtx(j,jj) * (2.0/M_PI) * ham(ii,jj) * rmesh[ii] * rmesh[jj] * pow(rdelt,2);
						//kh3 += bess_mtx(i,ii) * bess_mtx(j,jj) * (2.0/M_PI) * ham(ii,jj) * pow(rmesh[ii] * rmesh[jj] *rdelt,2);
						if(ii==jj){
							//kh3 -= bess_mtx(i,ii) * bess_mtx(j,jj) * (2.0/M_PI) * real(local[ii]) * pow(rmesh[ii],2) * rdelt;
							kh3 -= bess_mtx(i,ii) * bess_mtx(j,jj) * (2.0/M_PI) * real(local[ii]) * rmesh[jj] * rdelt;
						}
					}
				}
				k_ham(i,j) = kh;
				k_ham2(i,j) = kh2;
				k_ham3(i,j) = kh3;
			}
			//adding kinetic part here
			k_ham(i,i) += pow(kmesh[i],2) / (2*mu);
		}

		vector <eigen_t> khameig = initiate.real_eigvecs(k_ham);
		vector <eigen_t> khameig2 = initiate.real_eigvecs(k_ham2);
		vector <eigen_t> khameig3 = initiate.real_eigvecs(k_ham3);

		cout << "k-space ham eig[0] = " << khameig[0].first << endl;
		cout << "k-space ham eig[N] = " << khameig[rmesh.size()-1].first << endl;
		cout << "k-space ham2 eig[0] = " << khameig2[0].first << endl;
		cout << "k-space ham2 eig[N] = " << khameig2[rmesh.size()-1].first << endl;
		cout << "k-space ham3 eig[0] = " << khameig3[0].first << endl;
		cout << "k-space ham3 eig[N] = " << khameig3[rmesh.size()-1].first << endl;

		*/

		int Nmax=14;
		if(L>1){
			Nmax=13;
		}
		if(L>3){
			Nmax=12;
		}

		matrix_t skyham(Nmax, Nmax);
		skyham.clear();	

		for(int N=0;N<Nmax;N++){
			Nlab = sky1.Nlab(N);

//opening skyrme file which gives u(r)
			vector<double> sky0 = sky1.read(N,L,J,presky,rmesh.size());	

			vector <double> expo;
			expo.assign(rmesh.size(),0);

			vector <double> wave = hameig[N].second;
			
			for(int M=0;M<Nmax;M++){
				string Mlab;
				ostringstream convert;
				convert << M;
				Mlab = convert.str();

//opening skyrme file which gives u(r)
				vector<double> skyrme = sky1.read(M,L,J,presky,rmesh.size());

				double proj=0;

				for(int i=0;i<rmesh.size();i++){
					proj += wave[i]/sqrt(enorm) * skyrme[i] * rdelt;
				}

				for(int i=0;i<rmesh.size();i++){
					expo[i] += proj * skyrme[i];
				}

				//gonna do in terms of rdelt_p
				//ham definitely has r*r'*dr in it
				for(int i=0;i<rmesh.size();i++){
					for(int j=0;j<rmesh.size();j++){
						//skyham(N,M) += ham(i,j) * sky0[i] * skyrme[j] * pow(rmesh_p[i]/rmesh[i] * rmesh_p[j]/rmesh[j] * rdelt_p,2) / rdelt;
						skyham(N,M) += ham(i,j) * sky0[i] * skyrme[j] * rdelt;
					}
					//delta functions in local part get rid of one integral
					//assuming even the diagonal also has r*r'*dr included
					//skyham(N,M) += real(local[i]) * sky0[i] * skyrme[i] / pow(rmesh[i],4) / rdelt * pow(rmesh_p[i],2) * rdelt_p;
					skyham(N,M) += real(local[i]) * sky0[i] * skyrme[i] / pow(rmesh[i],2);
				}

			} //end loop over m

			string exponame = "waves/expo" + llab + jlab + Nlab + ".txt";
			ofstream expofile(exponame.c_str());

			double expnorm=0;
			for(int i=0;i<rmesh.size();i++){
				expnorm += pow(expo[i],2) * rdelt;
			}

		//cout << "expnorm = "<<expnorm<<endl;

			double factor;
	
			if(expo[10]<0){
				factor=-1.0;
			}else{	
				factor=1.0;
			}

			for(int i=0;i<rmesh.size();i++){
				expofile << rmesh[i] << " " << expo[i]/rmesh[i]/sqrt(expnorm)*factor << endl;
			}

		//acting on the expanded wavefuncion with h(r,r')
		/*double act=0;		
		for(int i=0;i<rmesh.size();i++){
			act += ham(0,i) * expo[i];
		}

		cout<<"act = "<<act/expo[0]<<endl;

		*/

		} //end loop over n
	
		vector <eigen_t> eig = initiate.real_eigvecs(skyham);

		for(int M=0;M<Nmax;M++){
			cout<<"M = "<<M<<endl;
			string Mlab;
			ostringstream convert;
			convert << M;
			Mlab = convert.str();

			cout<<"hameig = "<<hameig[M].first<<endl;

			string fname = "waves/eigvec" + llab + jlab + Mlab + ".txt";
			ofstream feig(fname.c_str());

			eigen_t dom_wf = initiate.find_boundstate(rmesh, Ef, M, L, J, tol);
			cout<<"bound energy = "<<dom_wf.first<<endl;

			string domname = "waves/dom" + llab + jlab + Mlab + ".txt";
			ofstream domfile(domname.c_str());

			double hnorm=0;
			for(int i=0;i<rmesh.size();i++){
				hnorm += pow(hameig[M].second[i],2) * rdelt;
			}

			for(int i=0;i<rmesh.size();i++){
				//domfile << rmesh[i] << " " << dom_wf.second[i]<< endl;
				domfile << rmesh[i] << " " << hameig[M].second[i]/rmesh[i]/sqrt(hnorm) << endl;
			}

			//the eigenvector is already normalized
			for(int i=0;i<Nmax;i++){
				feig << eig[M].second[i] << endl;
			}

			cout << "eigval = " << eig[M].first << endl;

			vector<double> qpf;
			qpf.assign(rmesh.size(),0);
		
			for(int j=0;j<Nmax;j++){
				vector<double> skyrme = sky1.read(N,L,J,presky,rmesh.size());
				for(int i=0;i<rmesh.size();i++){
					qpf[i] += eig[M].second[j] * skyrme[i];
				}
			}

			string qpname = "waves/qp" + llab + jlab + Mlab + ".txt";
			ofstream qpfile(qpname.c_str());
			string oname = "waves/overlap" + llab +jlab + Mlab + ".txt";
			ofstream ofile(oname.c_str());

			double norm=0;
			double overlap=0;

			for(int i=0;i<rmesh.size();i++){
				norm += pow(qpf[i],2) * rdelt;
			}

			double fac;
		
			if(qpf[10] < 0){
				fac = -1.0;
			}else{
				fac = 1.0;
			}


			for(int i=0;i<rmesh.size();i++){
				qpfile << rmesh[i] <<" "<< qpf[i] / sqrt(norm) / rmesh[i] * fac << endl;
				overlap += qpf[i] / sqrt(norm) * dom_wf.second[i] * rmesh[i] * rdelt;
			}

			cout << "overlap = " << overlap << endl;

		}

			
	} //end loop over J
} //end loop over L



}
Exemple #16
0
void VBFHinvis::Loop()
{
//   In a ROOT session, you can do:
//      Root > .L VBFHinvis.C
//      Root > VBFHinvis t
//      Root > t.GetEntry(12); // Fill t data members with entry number 12
//      Root > t.Show();       // Show values of entry 12
//      Root > t.Show(16);     // Read and show values of entry 16
//      Root > t.Loop();       // Loop on all entries
//

//    jentry is the global entry number in the chain
//    ientry is the entry number in the current Tree
//  Note that the argument to GetEntry must be:
//    jentry for TChain::GetEntry
//    ientry for TTree::GetEntry and TBranch::GetEntry
//
//       To read only selected branches, Insert statements like:
// METHOD1:
//    fChain->SetBranchStatus("*",0);  // disable all branches
//    fChain->SetBranchStatus("branchname",1);  // activate branchname
// METHOD2: replace line
//    fChain->GetEntry(jentry);       //read all branches
//by  b_branchname->GetEntry(ientry); //read only this branch
   if (fChain == 0) return;

   // selections

   TH1F * hPtJ1   = new TH1F( "hPtJ1", "PtJ1", 30, 0., 150.);
   TH1F * hPtJ2   = new TH1F( "hPtJ2", "PtJ2", 30, 0., 150.);
   TH1F * hEtaJ1  = new TH1F( "hEtaJ1", "EtaJ1", 50, -5.0, 5.0);
   TH1F * hEtaJ2  = new TH1F( "hEtaJ2", "EtaJ2", 50, -5.0, 5.0);
   TH1F * hmJJ    = new TH1F( "hmJJ", "mJJ", 40, 0., 2000.);

   TH2F * hDetaJJmJJ = new TH2F( "hDetaJJmJJ", "DetaJJmJJ", 50, 0., 10.,40,0.,2000.);

   TH1F * hDphiJJ        = new TH1F( "hDphiJJ", "DphiJJ", 17, 0., 3.4);
   TH1F * hDphiJJmJJ300  = new TH1F( "hDphiJJmJJ300", "DphiJJmJJ300", 17, 0., 3.4);
   TH1F * hDphiJJmJJ500  = new TH1F( "hDphiJJmJJ500", "DphiJJmJJ500", 17, 0., 3.4);
   TH1F * hDphiJJDetaJJ2 = new TH1F( "hDphiJJDetaJJ2", "DphiJJDetaJJ2", 17, 0., 3.4);
   TH1F * hDphiJJDetaJJ3 = new TH1F( "hDphiJJDetaJJ3", "DphiJJDetaJJ3", 17, 0., 3.4);

   Long64_t nentries = fChain->GetEntriesFast();
   Long64_t nbytes = 0, nb = 0;

   for (Long64_t jentry=0; jentry<nentries;jentry++) {
      Long64_t ientry = LoadTree(jentry);
      //      break;
      if (ientry < 0) break;
      nb = fChain->GetEntry(jentry);   nbytes += nb;

      // if (Cut(ientry) < 0) continue;

      //      cout <<" run number = " << run << endl;

      // jet
      Int_t njets = EtJPT->size();
      if(njets < 2) {continue;}
      
      Double_t pTj1 = (*EtJPT)[0];
      Double_t pTj2 = (*EtJPT)[1];

      if(pTj1 <= 50. || pTj2 <= 50.) {continue;}

      Double_t DphiJJ = deltaPhi((*PhiJPT)[0],(*PhiJPT)[1]);
      Double_t DetaJJ = deltaEta((*EtaJPT)[0],(*EtaJPT)[1]);

      // Mj1j2 calculations
      Double_t PJ1x = pTj1 * cos((*PhiJPT)[0]); 
      Double_t PJ1y = pTj1 * sin((*PhiJPT)[0]);
      Double_t Eta = (*EtaJPT)[0];
      Double_t theta = 2. * atan(exp(-Eta));
      Double_t PJ1z = pTj1 / tan(theta);
      Double_t EJ1  = pTj1 / sin(theta);

      Double_t PJ2x = pTj2 * cos((*PhiJPT)[1]); 
      Double_t PJ2y = pTj2 * sin((*PhiJPT)[1]);
      Eta = (*EtaJPT)[1];
      theta = 2. * atan(exp(-Eta));
      Double_t PJ2z = pTj2 / tan(theta);
      Double_t EJ2  = pTj2 / sin(theta);
      Double_t mJJ  = sqrt( (EJ1+EJ2)*(EJ1+EJ2) 
                           - (PJ1x+PJ2x)*(PJ1x+PJ2x) 
                           - (PJ1y+PJ2y)*(PJ1y+PJ2y) 
			   - (PJ1z+PJ2z)*(PJ1z+PJ2z) ); 
      if(L1ETM40 == 1) {
	hPtJ1->Fill(pTj1);
	hPtJ2->Fill(pTj2);
	hEtaJ1->Fill((*EtaJPT)[0]); 
	hEtaJ2->Fill((*EtaJPT)[1]); 
	hmJJ->Fill(mJJ);
        hDphiJJ->Fill(DphiJJ);
        hDetaJJmJJ->Fill(DetaJJ,mJJ);
	
	if(mJJ > 300.)   {hDphiJJmJJ300->Fill(DphiJJ);}
	if(mJJ > 500.)   {hDphiJJmJJ500->Fill(DphiJJ);}

	if(DetaJJ > 2.0) {hDphiJJDetaJJ2->Fill(DphiJJ);}
	if(DetaJJ > 3.0) {hDphiJJDetaJJ3->Fill(DphiJJ);}

      }
   }

   TFile efile("VBFHinvisAnalysis.root","recreate");

   hmJJ->Write();
   hPtJ1->Write();
   hPtJ2->Write();
   hEtaJ1->Write();
   hEtaJ2->Write();
   hDphiJJ->Write();
   hDetaJJmJJ->Write();

   hDphiJJmJJ300->Write();
   hDphiJJmJJ500->Write();
   hDphiJJDetaJJ2->Write();
   hDphiJJDetaJJ3->Write();

   efile.Close();
}
void JPTRootAnalysisDataMCTau::Loop()
{
//   In a ROOT session, you can do:
//      Root > .L JPTRootAnalysisDataMCTau.C
//      Root > JPTRootAnalysisDataMCTau t
//      Root > t.GetEntry(12); // Fill t data members with entry number 12
//      Root > t.Show();       // Show values of entry 12
//      Root > t.Show(16);     // Read and show values of entry 16
//      Root > t.Loop();       // Loop on all entries
//

//     This is the loop skeleton where:
//    jentry is the global entry number in the chain
//    ientry is the entry number in the current Tree
//  Note that the argument to GetEntry must be:
//    jentry for TChain::GetEntry
//    ientry for TTree::GetEntry and TBranch::GetEntry
//
//       To read only selected branches, Insert statements like:
// METHOD1:
//    fChain->SetBranchStatus("*",0);  // disable all branches
//    fChain->SetBranchStatus("branchname",1);  // activate branchname
// METHOD2: replace line
//    fChain->GetEntry(jentry);       //read all branches
//by  b_branchname->GetEntry(ientry); //read only this branch
   if (fChain == 0) return;

   Long64_t nentries = fChain->GetEntriesFast();

   // histos

   TH1F * hEtRaw     = new TH1F( "hEtRaw", "EtRaw", 100, 0., 100.);
   TH1F * hEtaRaw    = new TH1F( "hEtaRaw", "EtaRaw", 20, -2.0, 2.0);

   TH1F * hDRjettrk  = new TH1F( "hDRjettrk", "DRjettrk", 30, 0., 0.6);
   TH1F * hd0ltr     = new TH1F( "hd0ltr", "d0ltr", 25, 0., 0.05);
   TH1F * hptltr     = new TH1F( "hptltr", "ptltr", 100, 0., 20);
   TH1F * hntrsign   = new TH1F( "hntrsign", "ntrsign", 20, 0., 20);
   TH1F * hntrisol   = new TH1F( "hntrisol", "ntrisol", 20, 0., 20);
   TH1F * hptminsign = new TH1F( "hptminsign", "ptminsign", 100, 0., 20);
   TH1F * hptminisol = new TH1F( "hptminisol", "ptminisol", 100, 0., 20);
   TH1F * hdzmaxltr  = new TH1F( "hdzmaxltr", "dzmaxltr", 50, 0., 0.5);
   TH1F * hpisol     = new TH1F( "hpisol", "pisol", 20, 0., 10.);

   const Int_t netbins = 6;
   const Int_t netcuts = netbins+1;
   Double_t et[netcuts]={10., 15., 20., 25., 30., 40., 60.};
   TH1F * hetraw            = new TH1F( "hetraw","etraw",netbins, et);
   TH1F * hetrawLeadtrk     = new TH1F( "hetrawLeadtrk", "etrawLeadtrk",netbins, et); 
   TH1F * hetrawTrkisol     = new TH1F( "hetrawTrkisol", "etrawTrkisol",netbins, et); 
   TH1F * hetrawElrejec     = new TH1F( "hetrawElrejec", "etrawElrejec",netbins, et); 


   TH1F * hetaraw           = new TH1F( "hetaraw", "etaraw", 5, 0., 2.0);
   TH1F * hetarawLeadtrk    = new TH1F( "hetarawLeadtrk", "etarawLeadtrk", 5, 0., 2.0);
   TH1F * hetarawTrkisol    = new TH1F( "hetarawTrkisol", "etarawTrkisol", 5, 0., 2.0);
   TH1F * hetarawElrejec    = new TH1F( "hetarawElrejec", "etarawElrejec", 5, 0., 2.0);

   Long64_t nbytes = 0, nb = 0;
   for (Long64_t jentry=0; jentry<nentries;jentry++) {
      Long64_t ientry = LoadTree(jentry);
      if (ientry < 0) break;
      nb = fChain->GetEntry(jentry);   nbytes += nb;
      // if (Cut(ientry) < 0) continue;

      if(jtau >= 2) {
	Float_t dphi = deltaPhi( (*PhiRaw)[0] , (*PhiRaw)[1] );
	if(dphi > 2.14) {
	  if( fabs((*EtaRaw)[0]) < 2.0 && fabs((*EtaRaw)[1]) < 2.0 ) {
	    if( (*tcEt)[0] > 10. && (*tcEt)[1] > 10. ) {
	      // et , eta raw
	      for (unsigned int i = 0; i < 2; i++) {
		hEtRaw->Fill((*tcEt)[i]);
		hEtaRaw->Fill((*tcEta)[i]);
	      }
	      // DR jet track 
	      for (unsigned int i = 0; i < 2; i++) {
		hDRjettrk->Fill((*drltrjet)[i]);
	      }
	      
	      // ip of tracks
	      for (unsigned int i = 0; i < 2; i++) {
		hd0ltr->Fill((*d0ltr)[i]);
	      }
	      
	      // pt of ltr
	      for (unsigned int i = 0; i < 2; i++) {
		hptltr->Fill((*ptltr)[i]);
	      }
	      
	      // ntr in signal cone
	      for (unsigned int i = 0; i < 2; i++) {
		hntrsign->Fill((*ntrsign)[i]);
	      }
	      
	      // ntr in isol cone
	      for (unsigned int i = 0; i < 2; i++) {
		hntrisol->Fill( (*ntrisol)[i] - (*ntrsign)[i] );
	      }
	      
	      // pt min in signal cone
	      for (unsigned int i = 0; i < 2; i++) {
		hptminsign->Fill( (*ptminsign)[i]);
	      }
	      
	      // pt min in isol cone
	      for (unsigned int i = 0; i < 2; i++) {
		hptminisol->Fill( (*ptminisol)[i]);
	      }
	      
	      // dz max ltr-tr
	      for (unsigned int i = 0; i < 2; i++) {
		hdzmaxltr->Fill( (*dzmaxltr)[i]);
	      }
	    
	      // e.m. isolation
	      for (unsigned int i = 0; i < 2; i++) {
		hpisol->Fill( (*emisolat)[i]);
	      }
	    
	      //
	      for (unsigned int i = 0; i < 2; i++) {
		hetraw->Fill( (*tcEt)[i] );
		hetaraw->Fill( fabs((*tcEta)[i]) );     
		if( (*dByLeadingTrackPtCut)[i] == 1) {
		  hetrawLeadtrk->Fill( (*tcEt)[i] );
		  hetarawLeadtrk->Fill( fabs((*tcEta)[i]) );     
		}	
		if( (*dByIsolation)[i] == 1 ) {
		  hetrawTrkisol->Fill( (*tcEt)[i] );
		  hetarawTrkisol->Fill( fabs((*tcEta)[i]) );     
		}
		if( ((*dAgainstElectron)[i] == 1)  &&  ((*dByIsolation)[i] == 1) ) {
		  hetrawElrejec->Fill( (*tcEt)[i] );
		  hetarawElrejec->Fill( fabs((*tcEta)[i]) );     
		}
	      }
	    }
	  }
	}
      }
   }

   setTDRStyle(0);
   gStyle->SetOptFit();

   TFile efile("mctau7TeV.root","recreate");
   //   TFile efile("datatau7TeV.root","recreate");
   hEtRaw->Write();
   hEtaRaw->Write();
   hDRjettrk->Write();
   hd0ltr->Write();
   hptltr->Write();
   hntrsign->Write();
   hntrisol->Write();
   hptminsign->Write();
   hptminisol->Write();
   hdzmaxltr->Write();
   hpisol->Write();
   hetraw->Write();
   hetaraw->Write();     

   hetrawLeadtrk->Write();
   hetrawTrkisol->Write();
   hetrawElrejec->Write();

   hetarawLeadtrk->Write();
   hetarawTrkisol->Write();
   hetarawElrejec->Write();

   efile.Close();

   TCanvas* c1 = new TCanvas("X","Y",1);
   hDRjettrk->GetXaxis()->SetTitle("DR jet tracks");
   hDRjettrk->GetYaxis()->SetTitle("Nev");
   hDRjettrk->Draw("hist");

   TCanvas* c2 = new TCanvas("X","Y",1);
   hd0ltr->GetXaxis()->SetTitle("track ip");
   hd0ltr->GetYaxis()->SetTitle("Nev");
   hd0ltr->Draw("hist");

   TCanvas* c3 = new TCanvas("X","Y",1);
   hptltr->GetXaxis()->SetTitle("pt ltr");
   hptltr->GetYaxis()->SetTitle("Nev");
   hptltr->Draw("hist");

   TCanvas* c4 = new TCanvas("X","Y",1);
   hntrsign->GetXaxis()->SetTitle("Ntrk in signal cone");
   hntrsign->GetYaxis()->SetTitle("Nev");
   hntrsign->Draw("hist");

   TCanvas* c5 = new TCanvas("X","Y",1);
   hntrisol->GetXaxis()->SetTitle("Ntrk in isolation annulus");
   hntrisol->GetYaxis()->SetTitle("Nev");
   hntrisol->Draw("hist");

   TCanvas* c6 = new TCanvas("X","Y",1);
   hptminsign->GetXaxis()->SetTitle("pt min in sign cone");
   hptminsign->GetYaxis()->SetTitle("Nev");
   hptminsign->Draw("hist");

   TCanvas* c7 = new TCanvas("X","Y",1);
   hptminisol->GetXaxis()->SetTitle("pt min in isol cone");
   hptminisol->GetYaxis()->SetTitle("Nev");
   hptminisol->Draw("hist");

   TCanvas* c8 = new TCanvas("X","Y",1);
   hdzmaxltr->GetXaxis()->SetTitle("dz max ltr");
   hdzmaxltr->GetYaxis()->SetTitle("Nev");
   hdzmaxltr->Draw("hist");

   TCanvas* c9 = new TCanvas("X","Y",1);
   hpisol->GetXaxis()->SetTitle("e.m. isolation");
   hpisol->GetYaxis()->SetTitle("Nev");
   hpisol->Draw("hist");

   TCanvas* c10 = new TCanvas("X","Y",1);
   hetraw->GetXaxis()->SetTitle("Et raw");
   hetraw->GetYaxis()->SetTitle("Nev");
   hetraw->Draw("hist");
   //   hetraw->SetMaximum(200.0);
   hetraw->SetMinimum(0.5);
   //   hetrawLeadtrk->Draw("same");
   hetrawTrkisol->Draw("same");

   TCanvas* c11 = new TCanvas("X","Y",1);
   hEtRaw->GetXaxis()->SetTitle("Et raw");
   hEtRaw->GetYaxis()->SetTitle("Nev");
   hEtRaw->Draw("hist");
}
void SinglePionEfficiency::Loop()
{
//   In a ROOT session, you can do:
//      Root > .L SinglePionEfficiency.C
//      Root > SinglePionEfficiency t
//      Root > t.GetEntry(12); // Fill t data members with entry number 12
//      Root > t.Show();       // Show values of entry 12
//      Root > t.Show(16);     // Read and show values of entry 16
//      Root > t.Loop();       // Loop on all entries
//

//     This is the loop skeleton where:
//    jentry is the global entry number in the chain
//    ientry is the entry number in the current Tree
//  Note that the argument to GetEntry must be:
//    jentry for TChain::GetEntry
//    ientry for TTree::GetEntry and TBranch::GetEntry
//
//       To read only selected branches, Insert statements like:
// METHOD1:
//    fChain->SetBranchStatus("*",0);  // disable all branches
//    fChain->SetBranchStatus("branchname",1);  // activate branchname
// METHOD2: replace line
//    fChain->GetEntry(jentry);       //read all branches
//by  b_branchname->GetEntry(ientry); //read only this branch
   if (fChain == 0) return;

   Long64_t nentries = fChain->GetEntriesFast();
 
   Long64_t nbytes = 0, nb = 0;

   // number of pt bins and intervals
   const Int_t nptbins = 12;
   const Int_t nptcuts = nptbins+1;
   //                       0    1   2    3    4     5     6     7     8     9    10   11    
   Double_t pt[nptcuts]={0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 40., 50.0};
   // number of eta bins and intervals
   const Int_t netabins = 12;
   const Int_t netacuts = netabins+1;
   //                         0    1    2    3    4    5    6    7    8    9    10   11
   Double_t eta[netacuts]={0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4};
   cout <<"  Eta bins " << endl;

   // prepare eta points for graph
   Float_t etagr[netabins], eetagr[netabins];
   for(Int_t i = 0; i < netabins; i++) {
     etagr[i]  = 0.5*(eta[i]+eta[i+1]);
     eetagr[i] = 0.5*(eta[i+1]-eta[i]);
     cout <<" i = " << i <<" Eta = " << etagr[i] <<" err Eta = " << eetagr[i] << endl;
   } 
   // prepare for graph
   Float_t ptgr[nptbins], eptgr[nptbins];
   for(Int_t i = 0; i < nptbins; i++) {
     ptgr[i]  = 0.5*(pt[i]+pt[i+1]);
     eptgr[i] = 0.5*(pt[i+1]-pt[i]);
     cout <<" i = " << i <<" pT = " << ptgr[i] <<" err pT = " << eptgr[i] << endl;
   } 


   TH2D* hResp = new TH2D("hResp","Resp",nptbins, pt, netabins, eta);
   // histos for energy losses
   TH1F* hEnTrkNotInter[netabins];
   const char* namesEnTrkNotInter[netabins] = {"hEnTrkNotInter1",
					       "hEnTrkNotInter2",
					       "hEnTrkNotInter3",
					       "hEnTrkNotInter4",
					       "hEnTrkNotInter5",
					       "hEnTrkNotInter6",
					       "hEnTrkNotInter7",
					       "hEnTrkNotInter8",
					       "hEnTrkNotInter9",
					       "hEnTrkNotInter10",
					       "hEnTrkNotInter11",
					       "hEnTrkNotInter12"};

   const char* titleEnTrkNotInter[netabins] = {"EnTrkNotInter1",
					       "EnTrkNotInter2",
					       "EnTrkNotInter3",
					       "EnTrkNotInter4",
					       "EnTrkNotInter5",
					       "EnTrkNotInter6",
					       "EnTrkNotInter7",
					       "EnTrkNotInter8",
					       "EnTrkNotInter9",
					       "EnTrkNotInter10",
					       "EnTrkNotInter11",
					       "EnTrkNotInter12"};

   TH1F* hEnTrkInter[netabins];
   const char* namesEnTrkInter[netabins] = {"hEnTrkInter1",
					    "hEnTrkInter2",
					    "hEnTrkInter3",
					    "hEnTrkInter4",
					    "hEnTrkInter5",
					    "hEnTrkInter6",
					    "hEnTrkInter7",
					    "hEnTrkInter8",
					    "hEnTrkInter9",
					    "hEnTrkInter10",
					    "hEnTrkInter11",
					    "hEnTrkInter12"};

   const char* titleEnTrkInter[netabins] = {"EnTrkInter1",
					    "EnTrkInter2",
					    "EnTrkInter3",
					    "EnTrkInter4",
					    "EnTrkInter5",
					    "EnTrkInter6",
					    "EnTrkInter7",
					    "EnTrkInter8",
					    "EnTrkInter9",
					    "EnTrkInter10",
					    "EnTrkInter11",
					    "EnTrkInter12"};

   for(Int_t ih=0; ih < netabins; ih++) { 
     hEnTrkNotInter[ih] = new TH1F(namesEnTrkNotInter[ih], titleEnTrkNotInter[ih], 40, -1., 3.);
     hEnTrkInter[ih] = new TH1F(namesEnTrkInter[ih], titleEnTrkInter[ih], 40, -1., 3.);
   }
   //
 
   // ===> for pi- and pi+
   // N total and N reco tracks
   // find how to write output in file
   //~/scratch0/CMSSW_TEST/cmssw134gammajet/src/JetMETCorrections/GammaJet/src/GammaJetAnalysis.cc

   // total number of analized MC tracks
   Int_t ntrk[netabins][nptbins] =   {  
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
   };
   // number of found tracks
   Int_t ntrkreco[netabins][nptbins] = {
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
   };
   // number of lost tracks
   Int_t ntrklost[netabins][nptbins] = {
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
   };
   // number of tracks with impact point on calo
   Int_t ntrkrecor[netabins][nptbins] = {
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
   };

   // trk efficiency and error
   Float_t trkeff[netabins][nptbins], etrkeff[netabins][nptbins];
   // response in 11x11 crystals + 5x5 HCAL around IP in ECAL
   Double_t response[netabins][nptbins] = {
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
   };

   // response for found tracks in cone 0.5 around MC track direction at vertex
   Double_t responseFoundTrk[netabins][nptbins] = {
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
   };

   // response for lost tracks in cone 0.5 around MC track direction at vertex
   Double_t responseLostTrk[netabins][nptbins] = {
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
     {0,0,0,0,0,0,0,0,0,0,0,0},
   };

   // average response in 11x11 crystals + 5x5 HCAL around IP in ECAL
   Double_t responseF[netabins][nptbins];
   // average response for found tracks in cone 0.5 around MC track direction at vertex
   Double_t responseFoundTrkF[netabins][nptbins];
   // average response for lost tracks in cone 0.5 around MC track direction at vertex
   Double_t responseLostTrkF[netabins][nptbins];
   // ratio of responses of lost and found tracks
   Double_t leak[netabins][nptbins];

   Double_t drTrkcut = 0.01;
   Double_t purityTrkcut = 0.75;
   // 
   for (Long64_t jentry=0; jentry<nentries;jentry++) {
      Long64_t ientry = LoadTree(jentry);
      if (ientry < 0) break;
      nb = fChain->GetEntry(jentry);   nbytes += nb;
      // if (Cut(ientry) < 0) continue;
      // counting events for efficiency calculation
      for(Int_t ieta = 0; ieta < netabins; ieta++) {
	for(Int_t ipt = 0; ipt < nptbins; ipt++) {
	  // ==> pi+
	  if(fabs(etaSim1) >= eta[ieta] && fabs(etaSim1) < eta[ieta+1]) {
	    // checking leakage
	    if(ptSim1 > 10. && ptSim1 < 10000.)
	      {
		if(drTrk2 < 0.01 && purityTrk2 == 1) 
		  {
		    hEnTrkNotInter[ieta]->Fill(etCalo1/ptSim1);
		  } else {
		    hEnTrkInter[ieta]->Fill(etCalo1/ptSim1);
		  }
	      }
	    // end of checking leakage
	    if(ptSim1 >= pt[ipt] && ptSim1 < pt[ipt+1]) {
	      ntrk[ieta][ipt] = ntrk[ieta][ipt]+1;
	      // number of reco tracks
	      if(drTrk1 < drTrkcut && purityTrk1 >= purityTrkcut) { 
		ntrkreco[ieta][ipt] = ntrkreco[ieta][ipt]+1;
		// response for found tracks
		responseFoundTrk[ieta][ipt] = responseFoundTrk[ieta][ipt] + etCalo1/ptSim1;  
		//
		Double_t theta = 2.*atan(exp(-etaSim1));
		Double_t eSim1 = ptSim1/sin(theta);
		if(e1ECAL11x11 > -1000. && e1HCAL5x5 > -1000. && fabs(etaSim1) < 1000.) { 
		  ntrkrecor[ieta][ipt] = ntrkrecor[ieta][ipt]+1;
		  Double_t e_ecal11 = e1ECAL11x11/eSim1;
		  Double_t e_hcal5  = e1HCAL5x5/eSim1;
		  Double_t e_ecalhcal11x5 = e_ecal11 + e_hcal5;
		  response[ieta][ipt] = response[ieta][ipt] + e_ecalhcal11x5;
		}
	      } else {
		// response for lost tracks
		ntrklost[ieta][ipt] = ntrklost[ieta][ipt]+1;
		responseLostTrk[ieta][ipt] = responseLostTrk[ieta][ipt] + etCalo1/ptSim1;  
		//
	      }
	    }
	  }
	  // ==> pi-
	  if(fabs(etaSim2) >= eta[ieta] && fabs(etaSim2) < eta[ieta+1]) {
	    // checking leakage
	    if(ptSim2 > 10. && ptSim2 < 1000.)
	      {
		if(drTrk2 < 0.01 && purityTrk2 == 1) 
		  {
		    hEnTrkNotInter[ieta]->Fill(etCalo2/ptSim2);
		  } else {
		    hEnTrkInter[ieta]->Fill(etCalo2/ptSim2);
		  }
	      }
	    // end of checking leakage
	    if(ptSim2 >= pt[ipt] && ptSim2 < pt[ipt+1]) {
	      ntrk[ieta][ipt] = ntrk[ieta][ipt]+1;
	      // number of reco tracks
	      if(drTrk2 < drTrkcut && purityTrk2 >= purityTrkcut) { 
		ntrkreco[ieta][ipt] = ntrkreco[ieta][ipt]+1;
		// response for found tracks
		responseFoundTrk[ieta][ipt] = responseFoundTrk[ieta][ipt] + etCalo2/ptSim2;  
		//
		Double_t theta = 2.*atan(exp(-etaSim2));
		Double_t eSim2 = ptSim2/sin(theta);
		if(e2ECAL11x11 > -1000. && e2HCAL5x5 > -1000. && fabs(etaSim2) < 1000.) { 
		  ntrkrecor[ieta][ipt] = ntrkrecor[ieta][ipt]+1;
		  Double_t e_ecal11 = e2ECAL11x11/eSim2;
		  Double_t e_hcal5  = e2HCAL5x5/eSim2;
		  Double_t e_ecalhcal11x5 = e_ecal11 + e_hcal5;
		  response[ieta][ipt] = response[ieta][ipt] + e_ecalhcal11x5;
		}
	      } else {
		// response for lost tracks
		ntrklost[ieta][ipt] = ntrklost[ieta][ipt]+1;
		responseLostTrk[ieta][ipt] = responseLostTrk[ieta][ipt] + etCalo2/ptSim2;  
		//
	      }
	    }
	  }
	}
      }
   }

   // calculate efficiencfy, full graph and write output stream
   ofstream myoutput_eff("CMSSW_167_TrackNonEff.txt");
   ofstream myoutput_eff1("CMSSW_167_TrackNonEff_one.txt");
   ofstream myoutput_leak("CMSSW_167_TrackLeakage.txt");
   ofstream myoutput_leak1("CMSSW_167_TrackLeakage_one.txt");
   ofstream myoutput_resp("CMSSW_167_response.txt");

   // calculate map of leackage
   for(Int_t ieta = 0; ieta < netabins; ieta++) {
     for(Int_t ipt = 0; ipt < nptbins; ipt++) {
       
	 // found tracks
       if(ntrkreco[ieta][ipt] != 0) {
	 
	 responseFoundTrkF[ieta][ipt] = responseFoundTrk[ieta][ipt]/ntrkreco[ieta][ipt]; 
	 
       } else {
	 
	 responseFoundTrkF[ieta][ipt] = responseFoundTrkF[ieta][ipt-1];
       }
       // lost tracks
       if(ntrklost[ieta][ipt] != 0) {
	 
	 responseLostTrkF[ieta][ipt] = responseLostTrk[ieta][ipt]/ntrklost[ieta][ipt]; 
	 
       } else {
	 
	 responseLostTrkF[ieta][ipt] = responseLostTrkF[ieta][ipt-1];

       }
     }
   } 

   for(Int_t ieta = 0; ieta <= netabins; ieta++) {
     for(Int_t ipt = 0; ipt <= nptbins; ipt++) {

       if(ieta < netabins && ipt < nptbins) {

	 leak[ieta][ipt] = responseLostTrkF[ieta][ipt]/responseFoundTrkF[ieta][ipt];
	 
	 cout <<" ieta = " << ieta
	      <<" eta = " << eta[ieta]
	      <<" ipt = " << ipt
	      <<" pt = " << pt[ipt]
	      <<" ntrkreco = " << ntrkreco[ieta][ipt] 
	      <<" ntrklost = " << ntrklost[ieta][ipt] 
	      <<" responseFoundTrk = " << responseFoundTrkF[ieta][ipt] 
	      <<" responseLostTrk = " << responseLostTrkF[ieta][ipt]
	      <<" leak = " << leak[ieta][ipt] <<  endl;

	 myoutput_leak << ieta << " " 
		       << ipt  << " " 
		       << eta[ieta] << " " 
		       << pt[ipt] << " "
		       << leak[ieta][ipt] << endl;
	 myoutput_leak1 << ieta << " " 
			<< ipt  << " " 
			<< eta[ieta] << " " 
			<< pt[ipt] << " "
			<< " 1. " << endl;
       }
       if(ipt == nptbins && ieta < netabins) {
	 
	 myoutput_leak << ieta << " " 
		       << ipt  << " " 
		       << eta[ieta] << " " 
		       << pt[ipt] << " "
		       << leak[ieta][ipt-1] << endl;
	 myoutput_leak1 << ieta << " " 
			<< ipt  << " " 
			<< eta[ieta] << " " 
			<< pt[ipt] << " "
			<< " 1. " << endl;
       }
       if(ipt < nptbins && ieta == netabins) {

	 myoutput_leak << ieta << " " 
		       << ipt  << " " 
		       << eta[ieta] << " " 
		       << pt[ipt] << " "
		       << leak[ieta-1][ipt] << endl;
	 myoutput_leak1 << ieta << " " 
			<< ipt  << " " 
			<< eta[ieta] << " " 
			<< pt[ipt] << " "
			<< " 1. " << endl;

       }
       if(ipt == nptbins && ieta == netabins) {

	 myoutput_leak << ieta << " " 
		       << ipt  << " " 
		       << eta[ieta] << " " 
		       << pt[ipt] << " "
		       << leak[ieta-1][ipt-1] << endl;
	 myoutput_leak1 << ieta << " " 
			<< ipt  << " " 
			<< eta[ieta] << " " 
			<< pt[ipt] << " "
			<< " 1. " << endl;

       }
     }
   }

   // calculate map of response and tracker efficiency

   cout <<" " << endl;
   cout <<" " << endl;
   cout <<" " << endl;

   for(Int_t ieta = 0; ieta <= netabins; ieta++) {
     for(Int_t ipt = 0; ipt <= nptbins; ipt++) {

       if(ieta < netabins && ipt < nptbins) {

	 if(ntrk[ieta][ipt] != 0 && ntrkrecor[ieta][ipt] != 0) {
	   trkeff[ieta][ipt] = 1.*ntrkreco[ieta][ipt]/ntrk[ieta][ipt];
	   etrkeff[ieta][ipt] = sqrt( trkeff[ieta][ipt]*(1.-trkeff[ieta][ipt])/ntrk[ieta][ipt] );
	   responseF[ieta][ipt] = response[ieta][ipt]/ntrkrecor[ieta][ipt];
	   
	   cout <<" ieta = " << ieta
		<<" eta = " << eta[ieta]
		<<" ipt = " << ipt
		<<" pt = " << pt[ipt]
		<<" ntrkreco = " << ntrkreco[ieta][ipt] 
		<<" ntrkrecor = " << ntrkrecor[ieta][ipt] 
		<<" ntrk = " << ntrk[ieta][ipt]
		<<" eff = " << trkeff[ieta][ipt] 
		<<" +/- " << etrkeff[ieta][ipt] 
		<<" response = " << responseF[ieta][ipt] << endl;
	   hResp->Fill(pt[ipt],eta[ieta],responseF[ieta][ipt]);
	   
	   myoutput_eff << ieta << " " 
			<< ipt  << " " 
			<< eta[ieta] << " " 
			<< pt[ipt] << " "
			<< trkeff[ieta][ipt] << endl;
	   
	   myoutput_resp << ieta << " " 
			 << ipt  << " " 
			 << eta[ieta] << " " 
			 << pt[ipt] << " "
			 << responseF[ieta][ipt] << endl;
	   
	   myoutput_eff1 << ieta << " " 
			 << ipt  << " " 
			 << eta[ieta] << " " 
			 << pt[ipt] << " "
			 << " 1." << endl;
	 } else {

	   trkeff[ieta][ipt] = trkeff[ieta][ipt-1];
	   responseF[ieta][ipt] = responseF[ieta][ipt-1];
	   hResp->Fill(pt[ipt],eta[ieta],responseF[ieta][ipt]);
	   myoutput_eff << ieta << " " 
			<< ipt  << " " 
			<< eta[ieta] << " " 
			<< pt[ipt] << " "
			<< trkeff[ieta][ipt] << endl;
	   
	   myoutput_resp << ieta << " " 
			 << ipt  << " " 
			 << eta[ieta] << " " 
			 << pt[ipt] << " "
			 << responseF[ieta][ipt] << endl;
	   
	   myoutput_eff1 << ieta << " " 
			 << ipt  << " " 
			 << eta[ieta] << " " 
			 << pt[ipt] << " "
			 << " 1." << endl;
	 }
       }

       if(ipt == nptbins && ieta < netabins) {
	 myoutput_eff << ieta << " " 
		      << ipt  << " " 
		      << eta[ieta] << " " 
		      << pt[ipt] << " "
		      << trkeff[ieta][ipt-1] << endl;
	 
	 myoutput_resp << ieta << " " 
		       << ipt  << " " 
		       << eta[ieta] << " " 
		       << pt[ipt] << " "
		       << responseF[ieta][ipt-1] << endl;
	 
	 myoutput_eff1 << ieta << " " 
		       << ipt  << " " 
		       << eta[ieta] << " " 
		       << pt[ipt] << " "
		       << " 1." << endl;
       }
       if(ipt < nptbins && ieta == netabins) {
	 myoutput_eff << ieta << " " 
		      << ipt  << " " 
		      << eta[ieta] << " " 
		      << pt[ipt] << " "
		      << trkeff[ieta-1][ipt] << endl;
	 
	 myoutput_resp << ieta << " " 
		       << ipt  << " " 
		       << eta[ieta] << " " 
		       << pt[ipt] << " "
		       << responseF[ieta-1][ipt] << endl;
	 
	 myoutput_eff1 << ieta << " " 
		       << ipt  << " " 
		       << eta[ieta] << " " 
		       << pt[ipt] << " "
		       << " 1." << endl;
       }
       if(ipt == nptbins && ieta == netabins) {
	 myoutput_eff << ieta << " " 
		      << ipt  << " " 
		      << eta[ieta] << " " 
		      << pt[ipt] << " "
		      << trkeff[ieta-1][ipt-1] << endl;
	 
	 myoutput_resp << ieta << " " 
		       << ipt  << " " 
		       << eta[ieta] << " " 
		       << pt[ipt] << " "
		       << responseF[ieta-1][ipt-1] << endl;
	 
	 myoutput_eff1 << ieta << " " 
		       << ipt  << " " 
		       << eta[ieta] << " " 
		       << pt[ipt] << " "
		       << " 1." << endl;
       }
     }
   }
   
   //
   // plot leakage graph
   Float_t leakage[netabins], eleakage[netabins];
   Float_t MeanNotInter[netabins], MeanErrorNotInter[netabins];
   Float_t MeanInter[netabins], MeanErrorInter[netabins];

   for(Int_t ih=0; ih < netabins; ih++) { 
     //     hEnTrkNotInter[ih]->Write();
     //     hEnTrkInter[ih]->Write();

     MeanNotInter[ih]      = hEnTrkNotInter[ih]->GetMean();
     MeanErrorNotInter[ih] = hEnTrkNotInter[ih]->GetMeanError();
     MeanInter[ih]         = hEnTrkInter[ih]->GetMean();
     MeanErrorInter[ih]    = hEnTrkInter[ih]->GetMeanError();
     leakage[ih] = MeanInter[ih]/MeanNotInter[ih];
     eleakage[ih] = leakage[ih] *
       sqrt( (MeanErrorNotInter[ih]/MeanNotInter[ih])*(MeanErrorNotInter[ih]/MeanNotInter[ih]) +
             (MeanErrorInter[ih]/MeanInter[ih])*(MeanErrorInter[ih]/MeanInter[ih]));

     cout <<" ieta = " << ih <<" MeanNotInter = " << MeanNotInter[ih] <<" +/- " << MeanErrorNotInter[ih]
	  <<" MeanInter = " << MeanInter[ih] <<" +/- " << MeanErrorInter[ih]  
	  <<" leakage = " << leakage[ih] <<" +/- " << eleakage[ih] << endl; 
   }

   TGraph *gleak = new TGraphErrors(netabins,etagr,leakage, eetagr,eleakage);
   TGraph *eMeanNotInter = new TGraphErrors(netabins,etagr,MeanNotInter, eetagr,MeanErrorNotInter);
   TGraph *eMeanInter = new TGraphErrors(netabins,etagr,MeanInter, eetagr,MeanErrorInter);
   //  vs Eta
   setTDRStyle(0,0);
   TCanvas* c3 = new TCanvas("X","Y",1);
   c3->Divide(1,2);
   c3->cd(1);
   TAxis* xaxis = eMeanNotInter->GetXaxis();
   eMeanNotInter->GetXaxis()->SetTitle("#eta");
   eMeanNotInter->GetYaxis()->SetTitle("calo E_{T}^{raw reco} in cone 0.5/p_{T}^{MC}");
   xaxis->SetLimits(0.0,2.4);
   eMeanNotInter->SetMarkerStyle(21);
   //   eMeanNotInter->SetMaximum(0.95);
   //   eMeanNotInter->SetMinimum(0.55);
   eMeanNotInter->SetMaximum(1.);
   eMeanNotInter->SetMinimum(0.);
   eMeanNotInter->Draw("AP");
   eMeanInter->SetMarkerStyle(24);
   eMeanInter->Draw("P");
   TLatex *t = new TLatex();
   t->SetTextSize(0.08);
   t->DrawLatex(0.2,0.9,"CMSSW_1_6_9");
   TLegend *leg = new TLegend(0.2,0.2,0.8,0.4,NULL,"brNDC");
   leg->SetFillColor(10);
   leg->AddEntry(eMeanNotInter,"recontructed tracks 2 < p_{T}^{#pi^{#pm}} < 10 GeV","P");
   leg->AddEntry(eMeanInter,"not reconstructed tracks 2 < p_{T}^{#pi^{#pm}} < 10 GeV","P");
   leg->Draw();

   c3->cd(2);
   TAxis* xaxis = gleak->GetXaxis();
   gleak->GetXaxis()->SetTitle("#eta");
   gleak->GetYaxis()->SetTitle("ratio = <E_{T for lost tracks}^{raw reco} / E_{T for found tracks}^{raw reco}>");
   xaxis->SetLimits(0.0,2.4);
   gleak->SetMarkerStyle(21);
   gleak->SetMaximum(1.0);
   //  leak->SetMinimum(0.7);
   gleak->SetMinimum(0.5);
   gleak->Draw("AP");
   TLatex *t = new TLatex();
   t->SetTextSize(0.08);
   //   t->DrawLatex(0.1,0.75,"<E_{T for lost tracks}^{raw reco} / E_{T for found tracks}^{raw reco}> for p_{T}^{#pi^{#pm}} >2 GeV");
   c3->SaveAs("eMean_vs_eta_pt2-10.gif");
   c3->SaveAs("eMean_vs_eta_pt2-10.eps");

   //  original distribtions
   setTDRStyle(0,0);
   gStyle->SetOptFit(0);
   TCanvas* c4 = new TCanvas("X","Y",1);
   hEnTrkNotInter[0]->GetYaxis()->SetTitle("");
   hEnTrkNotInter[0]->GetXaxis()->SetTitle("calo E_{T}^{raw reco} in cone 0.5/p_{T}^{MC}");
   Double_t scale = 1./hEnTrkNotInter[0]->Integral();
   hEnTrkNotInter[0]->Scale(scale);
   hEnTrkNotInter[0]->SetLineWidth(4);
   hEnTrkNotInter[0]->SetMaximum(0.14);
   //   hEnTrkNotInter[0]->SetMinimum(0.55);
   // Fitting
   Int_t binMax = hEnTrkNotInter[0]->GetMaximumBin();
   TAxis* xaxis = hEnTrkNotInter[0]->GetXaxis();
   Double_t binCenter = xaxis->GetBinCenter(binMax);
   Double_t rms = hEnTrkNotInter[0]->GetRMS();
   Double_t rFitMin = binCenter - 1.5 * rms; 
   Double_t rFitMax = binCenter + 1.5 * rms;
   hEnTrkNotInter[0]->Fit("gaus","","",rFitMin,rFitMax);
   TF1 *fit = hEnTrkNotInter[0]->GetFunction("gaus"); 
   fit->SetLineWidth(4);
   fit->SetLineStyle(2);
   fit->Draw("same");
   scale = 1./hEnTrkInter[0]->Integral();
   hEnTrkInter[0]->Scale(scale);
   hEnTrkInter[0]->SetLineWidth(2);
  // Fitting
   Int_t binMax = hEnTrkInter[0]->GetMaximumBin();
   TAxis* xaxis = hEnTrkInter[0]->GetXaxis();
   Double_t binCenter = xaxis->GetBinCenter(binMax);
   Double_t rms = hEnTrkNotInter[0]->GetRMS();
   Double_t rFitMin = binCenter - 1.5 * rms; 
   Double_t rFitMax = binCenter + 1.5 * rms;
   hEnTrkInter[0]->Fit("gaus","","same",rFitMin,rFitMax);
   TF1 *fit = hEnTrkInter[0]->GetFunction("gaus"); 
   fit->SetLineWidth(2);
   fit->SetLineStyle(2);
   fit->Draw("same");
   TLatex *t = new TLatex();
   t->SetTextSize(0.08);
   t->DrawLatex(0.2,0.9,"CMSSW_1_6_9");
   TLegend *leg = new TLegend(0.15,0.7,0.9,0.9,NULL,"brNDC");
   leg->SetFillColor(10);
   leg->AddEntry(hEnTrkNotInter[0],"recontructed tracks 2< p_{T}^{#pi^{#pm}} < 10 GeV, 0<#eta<0.2","L");
   leg->AddEntry(hEnTrkInter[0],"not reconstructed tracks 2< p_{T}^{#pi^{#pm}} < 10 GeV, 0<#eta<0.2","L");
   leg->Draw();

   c4->SaveAs("eMean_at_eta0.gif");
   c4->SaveAs("eMean_at_eta0.eps");

   //  original distribtions
   setTDRStyle(0,0);
   gStyle->SetOptFit(0);
   TCanvas* c5 = new TCanvas("X","Y",1);
   hEnTrkNotInter[9]->GetYaxis()->SetTitle("");
   hEnTrkNotInter[9]->GetXaxis()->SetTitle("calo E_{T}^{raw reco} in cone 0.5/p_{T}^{MC}");
   Double_t scale = 1./hEnTrkNotInter[9]->Integral();
   hEnTrkNotInter[9]->Scale(scale);
   hEnTrkNotInter[9]->SetLineWidth(4);
   hEnTrkNotInter[9]->SetMaximum(0.17);
   //   hEnTrkNotInter[9]->SetMinimum(0.55);
   // Fitting
   Int_t binMax = hEnTrkNotInter[9]->GetMaximumBin();
   TAxis* xaxis = hEnTrkNotInter[9]->GetXaxis();
   Double_t binCenter = xaxis->GetBinCenter(binMax);
   Double_t rms = hEnTrkNotInter[9]->GetRMS();
   Double_t rFitMin = binCenter - 1.5 * rms; 
   Double_t rFitMax = binCenter + 1.5 * rms;
   hEnTrkNotInter[9]->Fit("gaus","","",rFitMin,rFitMax);
   TF1 *fit = hEnTrkNotInter[9]->GetFunction("gaus"); 
   fit->SetLineWidth(4);
   fit->SetLineStyle(2);
   fit->Draw("same");
   scale = 1./hEnTrkInter[9]->Integral();
   hEnTrkInter[9]->Scale(scale);
   hEnTrkInter[9]->SetLineWidth(2);
  // Fitting
   Int_t binMax = hEnTrkInter[9]->GetMaximumBin();
   TAxis* xaxis = hEnTrkInter[9]->GetXaxis();
   Double_t binCenter = xaxis->GetBinCenter(binMax);
   Double_t rms = hEnTrkNotInter[9]->GetRMS();
   Double_t rFitMin = binCenter - 1.2 * rms; 
   Double_t rFitMax = binCenter + 1.5 * rms;
   hEnTrkInter[9]->Fit("gaus","","same",rFitMin,rFitMax);
   TF1 *fit = hEnTrkInter[9]->GetFunction("gaus"); 
   fit->SetLineWidth(2);
   fit->SetLineStyle(2);
   fit->Draw("same");
   TLatex *t = new TLatex();
   t->SetTextSize(0.08);
   t->DrawLatex(0.2,0.9,"CMSSW_1_6_9");
   TLegend *leg = new TLegend(0.15,0.7,0.9,0.9,NULL,"brNDC");
   leg->SetFillColor(10);
   leg->AddEntry(hEnTrkNotInter[9],"recontructed tracks p_{T}^{#pi^{#pm}} > 2 GeV, 1.8<#eta<2.0","L");
   leg->AddEntry(hEnTrkInter[9],"not reconstructed tracks p_{T}^{#pi^{#pm}} > 2 GeV, 1.8<#eta<2.0","L");
   leg->Draw();

   c5->SaveAs("eMean_at_eta1.9.gif");
   c5->SaveAs("eMean_at_eta1.9.eps");

   TFile efile("response.root","recreate");
   hResp->Write();
   efile.Close();
}