Exemplo n.º 1
0
void histoTrbyTr(string decay, int saveFig= 0 , int onlyFirstCandidate= 0){
  gROOT->Reset();
  gROOT->SetStyle("Plain");
  gStyle->SetOptStat(1);
  gStyle->SetHistLineWidth(2);
  //  gStyle->SetOptStat(111110);
  //gStyle->SetOptFit(111);

  gROOT->ForceStyle();
 //  double pigreco = 3.141592;

   stringstream file;
  file.str("");
  file << "rfdir:///castor/cern.ch/cms/store/caf/user/taroni/TkAlData2011-20110721/variables"<<decay<<".root";


  cout << __LINE__ << " Opening file: " << file.str().c_str() << endl;
  
  TFile * f = new TFile();
  
  f = TFile::Open(file.str().c_str());
  if (!f){
    cout << "FILE NOT FOUND" << endl;
    return;
  }
   cout << __LINE__ << " file " << file.str().c_str() <<  " opened" << endl;
   stringstream outstring;
   outstring.str("");
   outstring << "triggerFile" << decay << ".root";

   TFile* outfile = new TFile(outstring.str().c_str(),"RECREATE");

   outfile -> cd();

//    double etaMu1;
//    double phiMu1;
//    double ptMu1;
//    double etaMu2;
//    double phiMu2;
//    double ptMu2;
   
  double nbins = 0;
  double  firstbin = 0;
  double  lastbin  = 0;

  double maxMass =0, minMass=0;

  string str3;
  size_t pos;
  pos = decay.find("MuMu");    // position of "live" in str
  str3 = decay.substr (0, pos);   // get from "live" to the end
  cout << str3 << endl;

//   if (decay == "ZMuMu" || decay == "ZMuMuMC" ) {
  if (str3 == "Z" ) {
    nbins = 140;
    firstbin = 50;
    lastbin  = 120;
    maxMass = 115;
    minMass = 65;
  }  else if (str3 == "Jpsi") {
    nbins = 80;
    firstbin = 2;
    lastbin  = 4;
    maxMass = 3.4;
    minMass = 2.7;
  }  else if (str3 == "Upsilon") {
    nbins = 80;
    firstbin = 8.5;
    lastbin  = 10.5;
    maxMass = 9.9;
    minMass = 8.9;
  }

  if (DEBUG)    cout<< __LINE__ << endl;

  TH1D * hTrigger = new TH1D("trigger","trigger",100,0.,100.); 
  
 //   TH1D *hMass= new TH1D("hMass","Invariant Mass",nbins,firstbin,lastbin);
//   TH1D *hPtMother= new TH1D("hPtMother","MotherTransverse Momentum",200,0.,200.);
//   TH1D *hEtaMother= new TH1D("hEtaMother","Mother Eta",100,-5.,5.);
//   TH1D *hPhiMother= new TH1D("hPhiMother","Mother Phi",100,-4.,4.);


  TH1D *hPt= new TH1D("hPt","Transverse Momentum",200,0.,200.);
  TH1D *hEta= new TH1D("hEta","Eta",100,-4.,4.);
  TH1D *hPhi= new TH1D("hPhi","Phi",100,-4.,4.);

//   TH1D *hDeltaPhi= new TH1D("hDeltaPhi","DeltaPhi",100,-10.,10.);
//   TH1D *hDeltaEta= new TH1D("hDeltaEta","DeltaEta",100,-10.,10.);
//   TH1D *hDeltaR  = new TH1D("R"  ,"R"  ,100,-1.,10.);

  TH1I *hMultCand = new TH1I("hMultCand","MultipleCandidate",50,-.5,49.5);

//   TH2D * hEta1vsDeltaPhi = new TH2D ("hEta1vsDeltaPhi", "EtaMu1vsDeltaPhi", 100, -2., 2. , 100, -4., 4.) ;
//   TH2D * hEta2vsDeltaPhi = new TH2D ("hEta2vsDeltaPhi", "EtaMu2vsDeltaPhi", 100, -2., 2. , 100, -4., 4.) ;

  if (DEBUG)  cout<< __LINE__ << endl;


  map <string,  vector <TH1D *> > hTrMap;
  f->cd();

    TTree *t2 = (TTree*)f->Get("myanalysis/AnalysisTree");
    if (DEBUG) cout<< __LINE__ << endl;

//     TBranch *EtaMother= t2->GetBranch("EtaMother");
//     TBranch *PhiMother= t2->GetBranch("PhiMother");
//     TBranch *PtMother= t2->GetBranch("PtMother");
   
    TBranch *chi2 = t2->GetBranch("Chi");
//     TBranch *Ntk  = t2->GetBranch("mol");
    TBranch *M= t2->GetBranch("invMass");
    TBranch *P= t2->GetBranch("P");
    TBranch *Pt= t2->GetBranch("Pt");
    TBranch *Px= t2->GetBranch("Px");
    TBranch *Py= t2->GetBranch("Py");
    TBranch *Pz= t2->GetBranch("Pz");
    TBranch *Eta= t2->GetBranch("Eta");
    TBranch *Phi= t2->GetBranch("Phi");

    TBranch *trigger= t2->GetBranch("triggerInfo");

      if (DEBUG)cout<< __LINE__ << endl;



    vector <double> *chi2pt=0;

    vector <double> *Ppt=0, *Ptpt=0, *Pxpt=0, *Pypt=0, *Pzpt=0, *Etapt=0, *Phipt=0;
//     vector<double> *mass=0, *PtMotherpt=0,*EtaMotherpt=0,*PhiMotherpt=0;

    vector <pair <string, bool> > *triggerInfo =0;

//     M->SetAddress(&mass);
//     PtMother->SetAddress(&PtMotherpt);
//     EtaMother->SetAddress(&EtaMotherpt);
//     PhiMother->SetAddress(&PhiMotherpt);

    P->SetAddress(&Ppt);
    Pt->SetAddress(&Ptpt);
    Px->SetAddress(&Pxpt);
    Py->SetAddress(&Pypt);
    Pz->SetAddress(&Pzpt);
    Eta->SetAddress(&Etapt);
    Phi->SetAddress(&Phipt);

    trigger->SetAddress(&triggerInfo);

    Int_t nentries = (Int_t)t2->GetEntries();
//     nentries = 100;
    cout << __LINE__ << " Entries " << nentries << endl;
    vector < string > triggerNames;

//     nentries = 100 ;
    outfile->cd();
   
   for ( int i=0;i<nentries;i++) {
      t2->GetEntry(i);
      hTrigger->Fill(triggerInfo->size());

      for (unsigned int itr = 0; itr < triggerInfo->size(); itr++){
	if (triggerInfo->at(itr).second== 1) {
	  string triggerName= (triggerInfo->at(itr)).first ;
	  bool checkName = false;
	  for( unsigned int iname =0; iname<triggerNames.size(); iname++){

	    if (triggerNames.at(iname).compare(triggerName)==0){
 	      checkName = true;
	    }
	  }
	  if (checkName == false ) {
	    triggerNames.push_back(triggerName);

	  }
	}
      }
  
   }
    cout << "triggersize" << " " << triggerNames.size()<< endl;

   for (unsigned int itr=0; itr<triggerNames.size(); itr++){
      
      vector < TH1D *> hTrVector; 
      stringstream histoEtaName, histoPhiName, histoPtName, histoEtaMotherName, histoPhiMotherName;
      histoEtaName.str("");
      histoPhiName.str("");
      histoPtName.str("");
      histoEtaName << triggerNames.at(itr) << "TrackEta";
      histoPhiName << triggerNames.at(itr) << "TrackPhi";
      histoPtName  << triggerNames.at(itr) << "TrackPt";
      if (DEBUG)cout<< __LINE__ << endl;
      if (DEBUG) cout<< __LINE__ << endl;
      hTrMap[triggerNames.at(itr)].push_back(new TH1D (histoEtaName.str().c_str(),histoEtaName.str().c_str(),500,-5,5));
      hTrMap[triggerNames.at(itr)].push_back( new TH1D (histoPhiName.str().c_str(),histoPhiName.str().c_str(),640,-3.2,3.2));
      hTrMap[triggerNames.at(itr)].push_back( new TH1D (histoPtName.str().c_str(),histoPtName.str().c_str(),200,0.,0.));
      
      hTrVector.clear();
   }

      if (DEBUG)cout<< __LINE__ << endl;
    f->cd();
    t2->ResetBranchAddresses();

//     M->SetAddress(&mass);

//     PtMother->SetAddress(&PtMotherpt);
//     EtaMother->SetAddress(&EtaMotherpt);
//     PhiMother->SetAddress(&PhiMotherpt);

    P->SetAddress(&Ppt);
    Pt->SetAddress(&Ptpt);
    Px->SetAddress(&Pxpt);
    Py->SetAddress(&Pypt);
    Pz->SetAddress(&Pzpt);
    Eta->SetAddress(&Etapt);
    Phi->SetAddress(&Phipt);

    trigger->SetAddress(&triggerInfo);
    outfile->cd();
    for ( int i=0;i<nentries;i++) {

      t2->GetEntry(i); 

      unsigned int muonSize = Ptpt->size();
      if (DEBUG)cout<< __LINE__ << endl;
      for (unsigned int ivec=0; ivec< muonSize;ivec++){
	hPt->Fill(Ptpt->at(ivec));
	if (DEBUG) cout<< __LINE__ << endl;
 
	hEta->Fill(Etapt->at(ivec));
	hPhi->Fill(Phipt->at(ivec));

 	for (unsigned int itr = 0; itr < triggerInfo->size(); itr++){
//	for (unsigned int itr = 0; itr < 100; itr++){   
	string name = triggerInfo->at(itr).first;
// 	  cout << __LINE__ << " trigger "  << triggerInfo->at(itr).first << " " << triggerInfo->at(itr).second << endl;
	  if (triggerInfo->at(itr).second== 1) {
// 	     if (DEBUG) cout<< __LINE__ << endl;
	    (hTrMap[name][0])->Fill(Etapt->at(ivec));
// 	     if (DEBUG) cout<< __LINE__ << endl;
	    hTrMap[name][1]->Fill(Phipt->at(ivec));
// 	     if (DEBUG) cout<< __LINE__ << endl;
	    hTrMap[name][2]->Fill(Ptpt->at(ivec));
	  }
	}
      
        // cout<< __LINE__ << endl;
    
    
//     for (unsigned int ivec=0; ivec< MassSize;ivec++){
// 	for (unsigned int itr = 0; itr < triggerInfo->size(); itr++){
// 	  string name = triggerInfo->at(itr).first;
// 	  hTrMap[name][2]->Fill(EtaMotherpt->at(ivec));
// 	  hTrMap[name][3]->Fill(PhiMotherpt->at(ivec));
// 	}
	//     }
      }

	if (DEBUG) cout<< __LINE__ << endl;
      //   }//if

    }//entries
    if (DEBUG) cout<< __LINE__ << endl;
      
   outfile->cd();

 /////////////////////////////////////////////////////////////////////////////
   TCanvas *canv1= new TCanvas("canv1","firstAnalysis",1000,700);
//    TCanvas *canv3= new TCanvas("canv3","DeltaPhiDeltaEtaR",1000,700);
//    TCanvas *canv4= new TCanvas("canv4","EtaMuVsDeltaPhi",600,800);
   TCanvas *canv7= new TCanvas("canv7","trigger",600,400);
//    TCanvas *canv2= new TCanvas("canv2","MotherAnalysis",1000,700);

   if (DEBUG) cout<< __LINE__ << endl;
   map <string , TCanvas *> canvasMap;
   for (map < string , vector <TH1D*> >::const_iterator it=hTrMap.begin(); it!=hTrMap.end(); it++){
   if (DEBUG) cout<< __LINE__ << endl;
     if (it->second.size()<1) continue ;
   if (DEBUG) cout<< __LINE__ << endl;
     if (it->second.at(1)->GetEntries() < 2*nentries/10) continue;
   if (DEBUG) cout<< __LINE__ << endl;
     string name = it->first;
     if (DEBUG) cout << __LINE__ << ", entries  "<<   it->second.at(1)->GetEntries() << endl;
   if (DEBUG) cout<< __LINE__ << endl;
     stringstream canvasName; 
     canvasName << "c_"<< decay<< "_" << name;
     canvasMap[name] = new TCanvas (canvasName.str().c_str(),canvasName.str().c_str(),1000,700);
   if (DEBUG) cout<< __LINE__ << endl;
     canvasMap[name]->Divide(2,2);
     canvasMap[name]->cd(1); 
     it->second[0]->Draw(); 
     canvasMap[name]->cd(2); 
     it->second[1]->Draw(); 
   if (DEBUG) cout<< __LINE__ << endl;
     canvasMap[name]->cd(3); 
     canvasMap[name]->GetPad(3)->SetLogy();
     it->second[2]->Draw(); 
     it->second[2]->GetXaxis()->SetTitle("GeV/c"); 
//      canvasMap[name]->cd(4); 
//      it->second[3]->Draw(); 
   if (DEBUG) cout<< __LINE__ << endl;
     stringstream canvasFileName;
     canvasFileName << "plots/"<< canvasName.str().c_str()<< ".png" ; 
   if (DEBUG) cout<< __LINE__ << endl;
     if (saveFig ==1){
       if (it->second.at(1)->GetEntries() < 2*nentries/10) continue;
       if (DEBUG) cout<< __LINE__ << endl;
       canvasMap[name]->SaveAs(canvasFileName.str().c_str());
     }
   }
   if (DEBUG) cout<< __LINE__ << endl;
   for (map < string , vector <TH1D*> >::const_iterator it=hTrMap.begin(); it!=hTrMap.end(); it++){
     if (it->second.size()<1) continue ;
     if (it->second.at(1)->GetEntries() < 2*nentries/10) continue;
     string name = it->first;
     canvasMap[name]->Write();
   }
   if (DEBUG) cout<< __LINE__ << endl;

   vector <TCanvas*> cVector;
   cVector.push_back(canv1);
//    cVector.push_back(canv2);
//    cVector.push_back(canv3);
//    cVector.push_back(canv4);
   cVector.push_back(canv7);

   canv1->Draw();
   canv1->Divide(2,2);
      
   canv1->cd(1);
   if (DEBUG) cout<< __LINE__ << endl;
	
   hPt->SetFillStyle(3033);
   hPt->SetFillColor(99);
   hPt->GetXaxis()->SetTitle("P_{T} (GeV/c)");
   int maxBin = 0;
   for (int ibin = 1 ; ibin <= hPt->GetNbinsX() ; ibin++){
     if (hPt->GetBinContent(ibin) != 0) {
       maxBin = ibin;
     }
   }
   double maxX = (int )(hPt->GetBinCenter(maxBin)/10)*10  + 11  ;
   hPt->GetXaxis()->SetRangeUser(0,maxX);
   canv1->GetPad(1)->SetLogy();
   hPt->Draw();
   if (DEBUG) cout<< __LINE__ << endl;
	
   canv1->cd(2);
//    hMass->SetFillStyle(3020);
//    hMass->SetFillColor(3);
//    hMass->GetXaxis()->SetTitle("Mass (GeV/c^{2})");
//    hMass->Draw();
   
   canv1->cd(3);
   hPhi->SetFillStyle(3009);
   hPhi->SetFillColor(2);
   hPhi->GetXaxis()->SetTitle("#phi (rad)");
   hPhi->Draw();
   
   canv1->cd(4);
   hEta->SetFillStyle(3020);
   hEta->SetFillColor(4);
   hEta->GetXaxis()->SetTitle("#eta");
   hEta->Draw();
   canv1->Update();
   if (DEBUG) cout<< __LINE__ << endl;

     
//    canv2->Draw();
//    canv2->Divide(2,2);
//    canv2->cd(1);
//    hMass->Draw();
//    canv2->cd(2);
//    hPhiMother->Draw();
//    hPhiMother->GetXaxis()->SetTitle("#phi (rad)");
//    canv2->cd(3);
//    hEtaMother->Draw();
//    hEtaMother->GetXaxis()->SetTitle("#eta");
//    canv2->cd(4);
//    hPtMother->Draw();
//    hPtMother->GetXaxis()->SetTitle("p_{T} (GeV/c)");
//    canv2->Update();
 
//    canv3->Divide(2,2);
   
//    canv3->cd(1);
//    hDeltaPhi->SetFillStyle(3009);
//    hDeltaPhi->SetFillColor(1);
//    hDeltaPhi->GetXaxis()->SetTitle("#phi");
//    hDeltaPhi->Draw();
   
//    canv3->cd(2);
//    hDeltaEta->SetFillStyle(3020);
//    hDeltaEta->SetFillColor(3);
//    hDeltaEta->GetXaxis()->SetTitle("#eta");
//    hDeltaEta->Draw();
   
//    canv3->cd(3);
//    hDeltaR->SetFillStyle(3009);
//    hDeltaR->SetFillColor(2);
//    hDeltaR->GetXaxis()->SetTitle("R");
//    hDeltaR->Draw();

//    canv3->Update();
   
   canv7->Draw();
   canv7->cd();
   hTrigger->Draw();
   canv7->Update();
   
//    canv4->Draw();
//    canv4->Divide(1,2);
//    canv4->cd(1);
//    hEta1vsDeltaPhi->Draw();
//    canv4->cd(2);
//    hEta2vsDeltaPhi->Draw();
//    canv4->Update();
   if (DEBUG) cout<< __LINE__ << endl;



   if (saveFig == 1 ) {
     for (unsigned icanv = 0 ; icanv < cVector.size(); icanv++){
       stringstream imageName;
     // imageName.str("");
     // imageName <<decay<< cVector[icanv]->GetTitle()<<".jpg";
     // cVector[icanv]->SaveAs(imageName.str().c_str());
     // imageName.str("");
     // imageName <<decay<< cVector[icanv]->GetTitle()<<".gif";
     // cVector[icanv]->SaveAs(imageName.str().c_str());
       imageName.str("");
       imageName << "plots/"<<decay<< cVector[icanv]->GetTitle()<<".png";
       cVector[icanv]->SaveAs(imageName.str().c_str());
       imageName.str("");
       imageName <<"plots/"<<decay<< cVector[icanv]->GetTitle()<<".eps";
       cVector[icanv]->SaveAs(imageName.str().c_str());
     }
   }


   for (unsigned icanv = 0 ; icanv < cVector.size(); icanv++){
     cVector[icanv]->Write();
   }

//    hTriggCount -> Write();
   if (DEBUG) cout<< __LINE__ << endl;

//    hEta1vsDeltaPhi->Write();
//    hEta2vsDeltaPhi->Write();
//    if (DEBUG) cout<< __LINE__ << endl;
	
//    hMass->Write();
//    hPtMother->Write();
//    hEtaMother->Write();
//    hPhiMother->Write();
   hPt->Write();
   hEta->Write();
   hPhi->Write();

//    hDeltaPhi->Write();
//    hDeltaEta->Write();
//    hDeltaR  ->Write();

   hMultCand->Write();
   hTrigger ->Write();
   // cout<< __LINE__ << endl;

   for (map < string , vector <TH1D*> >::const_iterator it=hTrMap.begin(); it!=hTrMap.end(); it++){
     if (it->second.size()<1) continue ;
     if ((it->second).at(1)->GetEntries() < 2*nentries/10) continue;
     (it->second).at(0)->Write();
     (it->second).at(1)->Write();
     (it->second).at(2)->Write();
//      (it->second).at(3)->Write();
     
   }
   if (DEBUG) cout<< __LINE__ << endl;

   // cout<< __LINE__ << endl;


   for (unsigned icanv = 0 ; icanv < cVector.size(); icanv++){
     cVector[icanv]->~TCanvas();
   }


   if (DEBUG) cout<< __LINE__ << endl;

//    hMass->~TH1D();
   hPt->~TH1D();
   hEta->~TH1D();
   hPhi->~TH1D();

//    hDeltaPhi->~TH1D();
//    hDeltaEta->~TH1D();
//    hDeltaR  ->~TH1D();

   hTrigger ->~TH1D();

   hMultCand->~TH1I();
//    for (map<string, vector <TH1D*> >::iterator it=hTrMap.begin(); it!=hTrMap.end(); it++){
//      (it->second).at(0)->~TH1D();
//      (it->second).at(1)->~TH1D();
//      (it->second).at(2)->~TH1D();
//      (it->second).at(3)->~TH1D();
//    }

   outfile->Close();

   f->Close();
   cout << __LINE__ << " file " << file.str().c_str() <<  " closed" << endl;


}
Exemplo n.º 2
0
void NewCosmicstest(){
	//gROOT->Reset();	
	
	TStopwatch *clock0 = new TStopwatch();
	TFile *fout = new TFile("Cosmictest.root","RECREATE");
	bool high = 1;
	
	//Float_t z0 = 1400;
	Float_t z0 = 0;
	Float_t yTop = 600;
	Float_t xTop = 300;
	Float_t zTop = 3650;
	
	Float_t xdist = 3000;
	Float_t zdist = 9000;
	
	TH2D *StartXZ = new TH2D("xz","xz;x[cm];z[cm]",30,-(xdist/2),xdist/2,90,z0 - 4500,z0 + 4500);
	TH1D *StartTheta = new TH1D("#theta","#theta; #theta_Zenith",100,0,2);
	TH1D *StartPhi = new TH1D("#phi","#phi; #phi",50,0,7);
	TH1D *StartPHigh = new TH1D("PHigh","P; P[GeV]",100,-1,3);
	TH1D *StartP = new TH1D("P","P;P[GeV]",100,-1,3);
	TH1D *StartPLow = new TH1D("PLow","P;P[GeV]",100,-1,3);
	//TH1D *StartP = new TH1D("P","P;P[GeV]",100,0.1,1000);
	BinLogX(StartP);
	BinLogX(StartPHigh);
	BinLogX(StartPLow);
	
	TH2D *StartPTheta = new TH2D("P,Theta","P-Theta;P[GeV];#theta",150,-1,3,50,0,2);
	BinLogX(StartPTheta);
	
	TH2D *MCXZ = new TH2D("MCxz","xz;x[cm];z[cm]",30,-(xdist/2),xdist/2,90,z0 - 4500,z0 + 4500);
	TH1D *MCTheta = new TH1D("MC#theta","#theta; #theta",100,0,2);
	TH1D *MCPhi = new TH1D("MC#phi","#phi, #phi",50,0,7);
	
	TH1I *MCnTry = new TH1I("nTry","nTry",100,4.6,5);
	
	Double_t totalweightsum=0;
	Double_t px,py,pz,x,y,z,w, weighttest, weight;
	Int_t nTry,nInside,nEvent,nTest;	
	Co3Rng *fRandomEngine = new Co3Rng();
	
	int EVENTS = 400000;
	Int_t kmax = 40000;
	float weight1,weight1Low,weight1High;
	weight1Low = 123*xdist*zdist/EVENTS/10000; // expected #muons per spill/ #simulated events per spill 174*30*90/500000
	cout<<weight1Low<<endl;
	
	double I = fRandomEngine->fSpectrumH->Integral(100,1000);
	weight1High = 2*TMath::Pi()/3*I*xdist*zdist/EVENTS/10000;
		//weight2 = 900/I; // 1/(mean momentum weight), P_max-P_min/(3*0.3044/2pi)
	
	cout<< weight1High<<endl;
	Float_t weight3 = 4.833931503; // MC average of nTry/nEvents 4.833949997 +- 0.000010494			
	weight1 = 1;								
	weight = weight1 / weight3;
	
	nInside = 0; nEvent = 0; nTest = 0; weighttest = 0;
	y = 1900; //20m over beam axis

	w = weight/kmax;
	clock0->Start();
	for(Int_t k = 0;k<kmax;k++){
		cout<<k<<endl;
		nTry =0;
		for(Int_t i=0;i<EVENTS;i++){
		   Bool_t hit = 0;   
		   do{
				// shower characteristics
			   double phi = fRandomEngine->Uniform(0,2*TMath::Pi());
			   double theta = fRandomEngine->fTheta->GetRandom();
			  				  			    		 
	   	   //momentum components
				px = TMath::Sin(phi)*TMath::Sin(theta); 
				pz = TMath::Cos(phi)*TMath::Sin(theta);
				py = -TMath::Cos(theta);
				
				// start position, area 1120m^2
				x = fRandomEngine->Uniform(-xdist/2,xdist/2);
				z = fRandomEngine->Uniform(z0 - zdist/2, z0 + zdist/2);
				
				// claim for flight close to the actual detector
				if((abs(x-(y+yTop)*px/py) < xTop && abs(z-z0-(y+yTop)*pz/py) < zTop) || (abs(x-(y-yTop)*px/py) < xTop && abs(z-z0-(y-yTop)*pz/py) <  zTop)|| abs(y-(x+xTop)*py/px)<yTop && abs(z-z0-(x+xTop)*pz/px)<zTop || abs(y-(x-xTop)*py/px)<yTop && abs(z-z0-(x-xTop)*pz/px)<zTop){
					
					// muon momentum
					double P;
					//if (!high) {P = fRandomEngine->NEWstest(theta);}
					//else {P = fRandomEngine->fSpectrumH->GetRandom();}
					// high
					P = fRandomEngine->fSpectrumH->GetRandom();
					w = weight1High/weight3/kmax;
					StartP->Fill(P,w);
					StartPHigh->Fill(P,w);
					StartPTheta->Fill(P,theta,w);
					// low
					P = fRandomEngine->NEWstest(theta);
					w = weight1Low/weight3/kmax;
					StartP->Fill(P,w);
					StartPLow->Fill(P,w);
					StartPTheta->Fill(P,theta,w);
					
					
					px = px*P;
					py = py*P;
					pz = pz*P;
					
					//muon or anti-muon
					hit = 1; nInside++; 
					// StartP->Fill(P,w);
					
					w = weight1Low/weight3/kmax + weight1High/weight3/kmax;
					
					StartTheta->Fill(theta,w); // kein Weight!
					StartPhi->Fill(phi,w);	// kein Weight!	
					StartXZ->Fill(x,z,w); // kein Weight!	
					StartPTheta->Fill(P,theta,w);	
			   }
			   nTry++;
				weighttest += w;
				MCTheta->Fill(theta,w); // kein Weight!
				MCPhi->Fill(phi,w);
				MCXZ->Fill(x,z,w);
				nTest++;
			}while(!hit);
			nEvent++;
		}
		MCnTry->Fill(1.0*nTry/EVENTS);
	}
	clock0->Stop();
	
	delete fRandomEngine;
	cout<<nEvent<<" events have been generated."<<endl;
	cout<<"There is a total of "<<nInside<<"/"<<nTest<<" muons that passed close enough to the detector."<<endl;
	cout<<"Including the given weight this corresponds to ";
	cout<<kmax*weighttest/xdist/zdist*10000/123.3044<<" spills (1 spill = "<<xdist*zdist*123.3044/10000;
	cout<<" real cosmic muons = "<<EVENTS<<" simulated events)."<<endl;
   
   cout<<weighttest<<endl;
   clock0->Print();
   
   Double_t meanflux = 0;
   Int_t binsum = 0;
   for (Int_t ix = 2; ix<29;ix++){
	   for (Int_t iz = 2; iz<89;iz++){
		 	binsum++;
		   meanflux += MCXZ->GetBinContent(ix,iz);
		}
	}
	cout<< "meanflux: "<<meanflux/binsum<<"  "<< meanflux<<endl<<endl;
   printf("MCnTry: %.9f +- %.9f",MCnTry->GetMean(),MCnTry->GetMeanError());
   cout<<endl<<endl;
     
    TCanvas *c1 = new TCanvas("c1","c1",400,400);
	 c1->Divide(1,1);
	 c1->cd(1);
	 MCnTry->DrawCopy();
	
	 TCanvas *c4 = new TCanvas("c4","c4",400,400);
	 c4->Divide(1,1);
	 c4->cd(1);
	 StartPTheta->DrawCopy("SURF2");
	 gPad->SetLogx();
	
	 //TCanvas *c2 = new TCanvas("c2","c2",400,400);
	 //c2->Divide(1,1);
	 //c2->cd(1);
	 //gPad->SetLogy();
	 //wei->DrawCopy();
	
    TCanvas *c3 = new TCanvas("c3","c3",1600,800);
	 c3->Divide(4,2);
	 c3->cd(1);
	 StartXZ->DrawCopy("COLZ");
	 c3->cd(2);
	 //MCP->SetLineColor(kGreen);
	// MCP->DrawCopy();
	 //StartP->DrawCopy();
	 //TF1 *fs = new TF1("fs",NEWs,1,100,2);
	 //fs->FixParameter(0, 0);
	 //fs->FixParameter(1, 500);
	 //StartP->Add(fs,-1);
	 StartP->DrawCopy();
	 //StartP->Fit(fs,"I");
	 
	 
	// 
	 //fs->DrawCopy("SAME");
	 
	 //gPad->SetLogy();
	 gPad->SetLogx();
	 c3->cd(3);
	 MCTheta->SetLineColor(kGreen);
	 MCTheta->DrawCopy();
	 StartTheta->DrawCopy("SAME");
	 //TF1 *f1 = new TF1("f1","[0]*cos(x)*cos(x)",1.57,3.14);
	 //StartTheta->Fit(f1,"","",1.57,3.14);	
	 gPad->SetLogy(0);
	 gPad->SetLogx(0);
	 c3->cd(4);
	 MCPhi->SetLineColor(kGreen);
	 MCPhi->DrawCopy();
	 StartPhi->DrawCopy("SAME");
	//TF1 *f1 = new TF1("f1","[0]*cos(x)*cos(x)",1.57,3.14);
	//StartTheta->Fit(f1,"","",1.57,3.14);	
	 gPad->SetLogy(0);
	 gPad->SetLogx(0);
	 c3->cd(5);
	 MCXZ->DrawCopy("COLZ");
	 c3->cd(6);
	 //MCP->Divide(StartP);
	// MCP->DrawCopy();
	 gPad->SetLogy(0);
	 gPad->SetLogx(0);
	 c3->cd(7);
	 //MCTheta->Divide(StartTheta);
	 MCTheta->DrawCopy();
	 gPad->SetLogy();
	 gPad->SetLogx(0);
	 c3->cd(8);
	 //MCPhi->Divide(StartPhi);
	 MCPhi->DrawCopy();
	 gPad->SetLogy(0);
	 gPad->SetLogx(0);
	 c3->Update();
	 c3->SaveAs("Start.png");
	 
	 
	 
	 
	 StartXZ->Write();
	 StartTheta->Write();
	 StartPhi->Write();
	 StartP->Write();
	 StartPLow->Write();
	 StartPHigh->Write();
	
    StartPTheta->Write();
		
	 MCXZ->Write();
	 MCTheta->Write();
	 MCPhi->Write();
	
	 MCnTry->Write();
	 fout ->Close();
	 
	 
  
}
void processWaveforms(TTree* treeToSort, vector<Plots>& targetPlots, TFile* outFile, string mode)
{
    TH1D* fittedTimeHisto = new TH1D("raw fitted times", "raw fitted times", TOF_BINS,TOF_LOWER_BOUND,TOF_RANGE);

    TH2D* deltaTVsPulseHeight = new TH2D("delta T vs. pulse height","delta T vs. pulse height", 200, -10, 10, 1580, 0, 15800);

    TH2D* deltaTVsPulseIntegral0 = new TH2D("delta T vs. pulse integral, target 0","delta T vs. pulse integral, target 0",100, -10, 10, pow(2,15), 0, pow(2,15));
    TH2D* deltaTVsPulseIntegral1 = new TH2D("delta T vs. pulse integral, target 1","delta T vs. pulse integral, target 1",100, -10, 10, pow(2,15), 0, pow(2,15));
    TH2D* deltaTVsPulseIntegral2 = new TH2D("delta T vs. pulse integral, target 2","delta T vs. pulse integral, target 2",100, -10, 10, pow(2,15), 0, pow(2,15));
    TH2D* deltaTVsPulseIntegral3 = new TH2D("delta T vs. pulse integral, target 3","delta T vs. pulse integral, target 3",100, -10, 10, pow(2,15), 0, pow(2,15));
    TH2D* deltaTVsPulseIntegral4 = new TH2D("delta T vs. pulse integral, target 4","delta T vs. pulse integral, target 4",100, -10, 10, pow(2,15), 0, pow(2,15));
    TH2D* deltaTVsPulseIntegral5 = new TH2D("delta T vs. pulse integral, target 5","delta T vs. pulse integral, target 5",100, -10, 10, pow(2,15), 0, pow(2,15));

    TH1D* triggerAmplitudeHisto = new TH1D("triggerAmplitudeHisto","triggerAmplitudeHisto",pow(2,14),0,pow(2,14));
    TH1D* relativeTriggerTimeHisto = new TH1D("relativeTriggerTimeHisto","relative trigger time, from start of fitted wavelet",200,-5,5);
    TH2D* relativeTriggerTimeVsAmplitude = new TH2D("relativeTriggerTimeVSAmplitude","relative trigger time vs amplitude", 200, -5, 5, pow(2,14), 0, pow(2,14));

    TH1D* gammaToGammaTimeH = new TH1D("gammaToGammaTimeH","time between consecutive gammas", 1000, -5, 5);

    if(mode=="DPP")
    {
        setBranchesHistos(treeToSort);

        int totalEntries = treeToSort->GetEntries();
        cout << "Total waveforms = " << totalEntries << endl;

        vector<double> triggerList;

        waveformWrap = new TMultiGraph("DPP waveforms", "DPP waveforms");
        vector<TGraph*> waveletGraphs;
        vector<TGraph*> triggerGraphs;

        int gammaGate[2] = {80,90};

        double prevGammaTime = 0;

        for(int j=1; j<totalEntries; j++)
        {
            if(j%1000==0)
            {
                cout << "Processing triggers on waveform " << j << "\r";
                fflush(stdout);
            }

            /*if(j>500)
            {
                break;
            }*/

            triggerList.clear();
            triggerValues.clear();

            // pull individual waveform event
            treeToSort->GetEntry(j);

            // calculate the baseline for this waveform
            BASELINE = calculateBaseline(*procEvent.waveform);

            // Loop through all points in the waveform and fit peaks
            for(int k=DPP_PEAKFIT_START; (size_t)k<procEvent.waveform->size(); k++)
            {
                // Check to see if this point creates a new trigger
                if(isTrigger(k, *procEvent.waveform))
                {
                    // trigger found - plot/fit/extract time

                    double timeDiff = procEvent.completeTime-procEvent.macroTime;
                    double microTime = fmod(timeDiff,MICRO_LENGTH);

                    if(microTime > gammaGate[0] && microTime < gammaGate[1])
                    {
                        processTrigger(j, k, triggerList, *procEvent.waveform);

                        double fullTime = procEvent.completeTime-procEvent.macroTime+data.trigger1Time+DPP_PEAKFIT_OFFSET;
                        gammaToGammaTimeH->Fill(fmod(fullTime,MICRO_LENGTH)-prevGammaTime);
                        prevGammaTime=fmod(fullTime,MICRO_LENGTH);

                        fillTriggerHistos(fullTime, targetPlots);
                        fittedTimeHisto->Fill(data.trigger1Time);
                    }

                    //processTrigger(j, k, triggerList, *procEvent.waveform);

                    break;
                }
            }

            //produceTriggerOverlay(j, triggerList, *procEvent.waveform);

            TH2D* deltaTVsPulseIntegralHisto;

            switch(procEvent.targetPos-1)
            {
                case 0:
                    deltaTVsPulseIntegralHisto = deltaTVsPulseIntegral0;
                    break;

                case 1:
                    deltaTVsPulseIntegralHisto = deltaTVsPulseIntegral1;
                    break;

                case 2:
                    deltaTVsPulseIntegralHisto = deltaTVsPulseIntegral2;
                    break;

                case 3:
                    deltaTVsPulseIntegralHisto = deltaTVsPulseIntegral3;
                    break;

                case 4:
                    deltaTVsPulseIntegralHisto = deltaTVsPulseIntegral4;
                    break;

                case 5:
                    deltaTVsPulseIntegralHisto = deltaTVsPulseIntegral5;
                    break;
            }

            triggerAmplitudeHisto->Fill(data.peak1Amplitude);
            relativeTriggerTimeHisto->Fill(data.trigger1Time+DPP_PEAKFIT_OFFSET);
            relativeTriggerTimeVsAmplitude->Fill(data.trigger1Time+DPP_PEAKFIT_OFFSET,data.peak1Amplitude);

            deltaTVsPulseIntegralHisto->Fill(data.trigger1Time+DPP_PEAKFIT_OFFSET, procEvent.lgQ);
            deltaTVsPulseHeight->Fill(data.trigger1Time+DPP_PEAKFIT_OFFSET, data.peak1Amplitude);

            // Create a new graph for each wavelet
            //waveletGraphs.push_back(new TGraph());

            // Fill each micropulse graph with waveform samples
            /*for (int l=0; l<procEvent.waveform->size(); l++)
              {
              waveletGraphs.back()->SetPoint(l,l*SAMPLE_PERIOD,procEvent.waveform->at(l));
              }*/

            // Create a new graph for each wavelet
            //triggerGraphs.push_back(new TGraph());

            // Fill each micropulse graph with waveform samples
            //triggerGraphs.back()->SetPoint(0,triggerList[0],triggerValues[0]);

            fill(procEvent.waveform->begin(),procEvent.waveform->end(),BASELINE);
        }

        TGraph* exponentialFit = new TGraph();
        exponentialFit->SetPoint(0,-0.78,140);
        exponentialFit->SetPoint(1,0.16,206);
        exponentialFit->SetPoint(2,1.79,305);
        exponentialFit->SetPoint(3,2.82,417);
        exponentialFit->SetPoint(4,3.59,566);
        exponentialFit->SetPoint(5,4.4,929);
        exponentialFit->SetPoint(6,5.2,1482);
        exponentialFit->SetPoint(7,5.7,2149);
        exponentialFit->SetPoint(8,6.9,5319);
        exponentialFit->SetPoint(9,7.3,7808);
        exponentialFit->SetPoint(10,7.7,11395);
        exponentialFit->SetPoint(11,8.0,16200);
        exponentialFit->Write();

        // Add each wavelet graph to the MultiGraph
        for (int m=0; m<waveletGraphs.size(); m++)
        {
            //cout << "adding graph " << m << " to multigraph" << endl;
            waveletGraphs[m]->Draw();
            waveformWrap->Add(waveletGraphs[m],"l");
        }

        // Add each trigger graph to the MultiGraph
        for (int m=0; m<triggerGraphs.size(); m++)
        {
            //cout << "adding graph " << m << " to multigraph" << endl;
            triggerGraphs[m]->SetMarkerSize(2);
            triggerGraphs[m]->SetMarkerColor(2);
            triggerGraphs[m]->Draw();
            waveformWrap->Add(triggerGraphs[m],"*");
        }

        waveformWrap->Write();

        for(Plots p : targetPlots)
        {
            p.getTOFHisto()->Write();
            p.getEnergyHisto()->Write();
        }

        fittedTimeHisto->Write();

        deltaTVsPulseIntegral0->Write();
        deltaTVsPulseIntegral1->Write();
        deltaTVsPulseIntegral2->Write();
        deltaTVsPulseIntegral3->Write();
        deltaTVsPulseIntegral4->Write();
        deltaTVsPulseIntegral5->Write();

        deltaTVsPulseHeight->Write();

        relativeTriggerTimeHisto->Write();
        triggerAmplitudeHisto->Write();
        relativeTriggerTimeVsAmplitude->Write();

        gammaToGammaTimeH->Write();
    }

    else if(mode=="waveform")
    {
        setBranchesHistosW(treeToSort);

        triggerWalk = new TH2I("triggerWalk","trigger time vs. waveform chunk #",200,0,200,1000,0,1000);

        TH1I* monitorHisto = new TH1I("targetPosH", "targetPos", 7, 0, 7);
        monitorHisto->GetXaxis()->SetTitle("target position of each waveform");

        long triggersWithGamma = 0;
        vector<int> fullWaveform(MACRO_LENGTH/2, BASELINE);
        vector<double> triggerList;

        int prevTargetPos = 0;
        double firstTimetagInSeries = 0;

        int totalEntries = treeToSort->GetEntries();
        cout << "Total waveforms = " << totalEntries << endl;

        /*TCanvas *mycan = (TCanvas*)gROOT->FindObject("mycan");

          if(!mycan)
          {
          mycan = new TCanvas("mycan","mycan");
          }*/

        // EVENT LOOP for sorting through channel-specific waveforms
        for(int j=1; j<totalEntries; j++)
        {
            cout << "Processing triggers on waveform " << j << "\r";
            fflush(stdout);

            if(j>30)
            {
                break;
            }

            triggerList.clear();
            triggerValues.clear();

            prevTargetPos = procEvent.targetPos;

            // pull individual waveform event
            treeToSort->GetEntry(j);

            if(procEvent.evtNo==1)
            {
                // new macropulse; process the previous macropulse's waveform

                // calculate the baseline for this waveform
                BASELINE = calculateBaseline(fullWaveform);

                // Loop through all points in the waveform and fit peaks
                for(int k=PEAKFIT_WINDOW; (size_t)k<fullWaveform.size(); k++)
                {
                    // Check to see if this point creates a new trigger
                    if(isTrigger(k, fullWaveform))
                    {
                        // trigger found - plot/fit/extract time
                        processTrigger(j, k, triggerList, fullWaveform);

                        // shift waveform index past the end of this fitting window
                        // so that we don't refit the same data
                        k += PEAKFIT_WINDOW;
                    }
                    /*if(triggerList.size()>10)
                      {
                      for(int m=0; m<triggerList.size(); m++)
                      {
                      cout << "triggerList[" << m << "] = " << triggerList[m] << endl;
                      }
                      break;
                      }*/
                }

                // Use the gamma peaks to find the time offset for this waveform, and
                // adjust the microTime with this offset

                double gammaOffset = calculateGammaOffset(triggerList);

                /*for(int m=0; (size_t)m<triggerList.size(); m++)
                  {
                  fillTriggerHistos(triggerList[m]-gammaOffset, targetPlots);
                  }*/

                if(gammaOffset!=0)
                {
                    for(int m=0; (size_t)m<triggerList.size(); m++)
                    {
                        //fillTriggerHistos(triggerList[m]-gammaOffset+WAVEFORM_OFFSET, targetPlots);
                    }

                    triggersWithGamma++;
                }

                /*if(j<30)
                  {
                  produceTriggerOverlay(j, triggerList, fullWaveform);
                  }*/

                /*temp.str("");
                  temp << "waveformWrap" << j;

                  waveformWrap = new TMultiGraph(temp.str().c_str(), temp.str().c_str());

                  vector<TGraph*> microGraphs;

                // Create a new graph for each micropulse period to be plotted
                for (int m = 0; m<floor(2*procEvent.waveform->size()/MICRO_LENGTH); m++)
                {
                microGraphs.push_back(new TGraph());
                }

                // Fill each micropulse graph with waveform samples
                for (int l = 0; l<procEvent.waveform->size(); l++)
                {
                microGraphs[(int)floor(l/(double)MICRO_LENGTH)]->SetPoint(microGraphs[(int)floor(l/(double)MICRO_LENGTH)]->GetN(),fmod(2*l+WAVEFORM_OFFSET,MICRO_LENGTH),procEvent.waveform->at(l));
                //cout << "Adding value " << procEvent.waveform->at(l) << " to position " << fmod(l,MICRO_LENGTH) << " in microGraph " << floor(l/(double)MICRO_LENGTH) << endl;
                }

                // Add each graph to the MultiGraph
                for (int m = 0; m<microGraphs.size(); m++)
                {
                //cout << "adding graph " << m << " to multigraph" << endl;
                microGraphs[m]->Draw();
                waveformWrap->Add(microGraphs[m],"l");
                }

                waveformWrap->Write();
                */

                //gPad->Modified();
                //mycan->Update();

                // Fill trigger histogram
                /*for (int l = 0; l<triggerList.size(); l++)
                  {
                  cout << "trigger " << l << " = " << triggerList[l] << ", " << triggerValues[l] << endl;
                  }*/

                //triggerH->Write();
                //cout << "Finished processing waveform " << j << endl << endl;

                /*if(j==10)
                  {
                  break;
                  }*/

                monitorHisto->Fill(prevTargetPos);

                fill(fullWaveform.begin(),fullWaveform.end(),BASELINE);

                firstTimetagInSeries = procEvent.completeTime;
            }

            if (procEvent.targetPos == 0)
            {
                continue;
            }

            double timeOffset = procEvent.completeTime-firstTimetagInSeries;

            if(timeOffset<MACRO_LENGTH-2*procEvent.waveform->size())
            {
                for(int k=0; k<procEvent.waveform->size(); k++)
                {
                    fullWaveform[timeOffset/SAMPLE_PERIOD+k] = procEvent.waveform->at(k);
                }
            }
        }

        cout << "Triggers with gamma in wavelet: " << triggersWithGamma << endl;

        monitorHisto->Write();

        for(Plots p : targetPlots)
        {
            p.getTOFHisto()->Write();
            p.getEnergyHisto()->Write();
        }

        cout << "Number of good fits: " << numberGoodFits << endl;
        cout << "onePeak = " << numberOnePeakFits << endl; 
        cout << "onePeakExpBack = " << numberOnePeakExpBackFits << endl; 
        cout << "twoPeaks = " << numberTwoPeakFits << endl << endl; 
        cout << "Number of bad fits: " << numberBadFits << endl;
    }

    else
    {
        cerr << "Error: digitizer mode was " << mode << "; only possible options are 'DPP' or 'waveform'. Exiting..." << endl;
        exit(1);
    }
}