46 RandObj::RandObj() { fRand = Random::Instance(); fObj.SetOwner(kFALSE); }
47 RandObj::~RandObj() { fObj.Clear();}
49 void RandObj::Add(TObject *obj, Float_t weight)
54 which = fObj.IndexOf(obj);
58 {fObj.Add(obj); fWeight.push_back(-weight);}
60 {fObj.Add(obj); fWeight.push_back(weight); }
63 if ( (fWeight[which] + weight) > 0 ) fWeight[which] = fWeight[which] + weight;
65 fObj.Remove(obj); fObj.Compress(); fWeight.erase(fWeight.begin()+which);
71 void RandObj::ComputeCumu()
75 fCumu.clear();
if ( fObj.GetEntries() == 0 )
return;
78 fCumu.resize(fObj.GetEntries());
81 fCumu[0] = fWeight[0];
82 for( i = 1; i < fCumu.size(); i++ ){ fCumu[i] = fCumu[i-1] + fWeight[i]; }
84 Double_t sum = fCumu[fCumu.size()-1];
85 for( i = 0; i < fCumu.size() ; i++ ){
if ( sum != 0.0 ) fCumu[i] = fCumu[i] / sum; }
88 void RandObj::Clear(Option_t *options)
90 fObj.Clear(options); fWeight.clear(); fCumu.clear();
93 TObject * RandObj::Rand()
95 Int_t sup, inf, middle; inf = 0; sup = fCumu.size();
97 if ( sup == 1 )
return fObj[0];
99 Double_t r = fRand->Current()->Rndm();
101 while( (sup-inf) > 1) {
102 middle = (sup+inf)/2;
103 if (r == fCumu[middle-1])
return fObj[middle-1];
104 if (r < fCumu[middle-1])
113 TObject * RandObj::Rand(Int_t &slot)
115 Int_t sup, inf, middle; inf = 0; sup = fCumu.size();
117 if ( sup == 1 ) { slot = 0;
return fObj[0]; }
119 Double_t r = fRand->Current()->Rndm();
121 while( (sup-inf) > 1) {
122 middle = (sup+inf)/2;
123 if (r == fCumu[middle-1]) { slot = middle-1;
return fObj[middle-1]; }
124 if (r < fCumu[middle-1])
129 slot = inf;
return fObj[slot];
132 void RandObj::ls(Option_t* )
const
134 cout <<
" # of objects " << fObj.GetEntries()
135 <<
" dim cumulative " << fCumu.size()
136 <<
" dim cumulative " << fWeight.size() <<
endl;
139 void RandObj::FillRandom(TH1 *h, Int_t ntimes)
143 if ( fObj.GetEntries() > 0 && ntimes > 0 ) {
144 h =
new TH1D(
"RandObj",
"Random distribution from RandObj::FillRandom",fObj.GetEntries(),0,fObj.GetEntries());
145 for (Int_t i = 0; i < ntimes; i++ )
146 { RandObj::Rand(slot); h->Fill(slot); }
A class to select randomly an object in a TObjArray of objects.
header file for a RandObj
ADF::LogMessage & endl(ADF::LogMessage &log)