ROOTPWA
sampleWeightedEvts.C
Go to the documentation of this file.
1 #include "TTree.h"
2 #include "TLorentzVector.h"
3 #include "TVector3.h"
4 #include "TLorentzRotation.h"
5 #include "TH1D.h"
6 #include "TClonesArray.h"
7 #include "TROOT.h"
8 #include "TMath.h"
9 #include "TRandom3.h"
10 #include "TCanvas.h"
11 #include <iostream>
12 #include <fstream>
13 #include <vector>
14 #include "NParticleEvent.h"
15 
16 
17 using namespace std;
18 
19 
20 void sampleWeightedEvents(TTree* mctr, string outputfile,unsigned int n,bool doweight=true){
21 
22 
23  ofstream outfile(outputfile.c_str());
24 
25 
26  TTree* tr=mctr;
27  double weight=1;
28  double maxweight=0;
29  TClonesArray* p=new TClonesArray("TLorentzVector");
30  TLorentzVector* beam=NULL;
31  int qbeam;
32  std::vector<int>* q=NULL;
33  tr->SetBranchAddress("weight",&weight);
34 
35  // get max weight
36  unsigned int nevt=tr->GetEntries();
37  for(unsigned int i=0;i<nevt;++i){
38  tr->GetEntry(i);
39  if(weight>maxweight)maxweight=weight;
40  }// end loop over events
41  cout<<"Maxweight="<<maxweight<<endl;
42 
43  tr->SetBranchAddress("p",&p);
44  tr->SetBranchAddress("beam",&beam);
45  tr->SetBranchAddress("qbeam",&qbeam);
46  tr->SetBranchAddress("q",&q);
47  TVector3 vertex;
48  NParticleEvent event(p,q,beam,&qbeam,&vertex);
49 
50  unsigned int nselected=0;
51  unsigned int attempts=0;
52  while(nselected<n){
53  for(unsigned int i=0;i<nevt;++i){
54  tr->GetEntry(i);
55  ++attempts;
56  if(doweight && gRandom->Uniform()>weight/maxweight)continue;
57 
58  ++nselected;
59  event.refresh();
60  event.writeGAMP(outfile);
61  if(nselected==n)break;
62 
63  }// end loop over events
64  }
65  cout << "Attempts: " << attempts << endl;
66  cout << "Efficiency=" << (double)nselected/(double)attempts << endl;
67 
68  outfile.close();
69 
70 }