Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions CRVResponse/inc/MakeCrvPhotons.hh
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,10 @@ class MakeCrvPhotons
public:
static const int _nSiPMs=4;

MakeCrvPhotons(CLHEP::RandFlat &randFlat, CLHEP::RandGaussQ &randGaussQ, CLHEP::RandPoissonQ &randPoissonQ) :
_randFlat(randFlat), _randGaussQ(randGaussQ), _randPoissonQ(randPoissonQ)
MakeCrvPhotons(CLHEP::RandFlat &randFlat, CLHEP::RandGaussQ &randGaussQ, CLHEP::RandPoissonQ &randPoissonQ, CLHEP::RandBinomial &randBinomial) :
_randFlat(randFlat), _randGaussQ(randGaussQ), _randPoissonQ(randPoissonQ), _randBinomial(randBinomial)
{
_scintillationYield=39400;
_scintillationYield=0;
for(int i=0; i<_nSiPMs; ++i) _photonYieldDeviation[i]=1.0;
}

Expand Down Expand Up @@ -135,7 +135,9 @@ class MakeCrvPhotons
CLHEP::RandFlat &_randFlat;
CLHEP::RandGaussQ &_randGaussQ;
CLHEP::RandPoissonQ &_randPoissonQ;
CLHEP::RandBinomial &_randBinomial;

void ProcessPhotons(const LookupBin *theBin, int nPhotons, double photonStartTime, int SiPM, int reflector);
bool IsInsideScintillator(const CLHEP::Hep3Vector &p);
bool IsInsideFiber(const CLHEP::Hep3Vector &p, const CLHEP::Hep3Vector &dir, double &r, double &phi);
double GetRandomTime(const LookupBin *theBin);
Expand Down
23 changes: 11 additions & 12 deletions CRVResponse/inc/MakeCrvSiPMCharges.hh
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ Based on Paul Rubinov's C# code
#define MakeCrvSiPMCharges_hh

#include <memory>
#include <set>
#include <map>
#include <algorithm>
#include <vector>
#include <utility>
#include "CLHEP/Random/Randomize.h"
Expand All @@ -21,9 +20,11 @@ namespace mu2eCrv

struct Pixel
{
bool _inactive;
bool _discharged;
double _t; //time of last discharge (if _discharged is true), or 0 (if _discharged is false)
Pixel() : _discharged(false), _t(0) {}
long _counter; //see explanation below. old counter values count as fully recharged
Pixel() : _inactive(false), _discharged(false), _t(0), _counter(0) {}
};

struct SiPMresponse
Expand All @@ -45,10 +46,6 @@ namespace mu2eCrv
bool _darkNoise; //this charge is dark noise and was not created by an "outside photon"
ScheduledCharge(const std::pair<int,int> &pixelId, double time, size_t photonIndex, bool darkNoise) :
_pixelId(pixelId), _time(time), _photonIndex(photonIndex), _darkNoise(darkNoise) {}
bool operator<(const ScheduledCharge &r) const
{
return _time < r._time;
};
private:
ScheduledCharge();
};
Expand Down Expand Up @@ -76,15 +73,16 @@ namespace mu2eCrv

private:
ProbabilitiesStruct _probabilities;
std::vector<std::pair<int,int> > _inactivePixels;

std::map<std::pair<int,int>,Pixel> _pixels;
std::multiset<ScheduledCharge> _scheduledCharges;
long _counter{0}; //the value of this counter gets increased for every call to Simulate() and pixel discharges get this number attached.
//when encountering a pixel with an old counter value, it indicates that it is from a previous Simulate()
//and can be considered fully charged. this removes the need to reset all pixels after every event.
std::vector<Pixel> _pixels; //the pixel index corresponds to x*_nPixelsY+y
std::vector<ScheduledCharge> _scheduledCharges;
size_t _currentChargeIndex{0};

std::vector<std::pair<int,int> > FindCrossTalkPixelIds(const std::pair<int,int> &pixelId);
std::pair<int,int> FindThermalNoisePixelId();
std::pair<int,int> FindFiberPhotonsPixelId();
bool IsInactivePixelId(const std::pair<int,int> &pixelId);

double GetAvalancheProbability(double v);
double GenerateAvalanche(Pixel &pixel, const std::pair<int,int> &pixelId, double time, size_t photonIndex, bool darkNoise);
Expand All @@ -94,6 +92,7 @@ namespace mu2eCrv
CLHEP::RandFlat &_randFlat;
CLHEP::RandPoissonQ &_randPoissonQ;
double _avalancheProbFullyChargedPixel;
double _crossTalkProbabilitySinglePixel;

TFile *_photonMapFile;
TH2F *_photonMap;
Expand Down
6 changes: 4 additions & 2 deletions CRVResponse/src/CrvPhotonGenerator_module.cc
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ namespace mu2e
CLHEP::RandFlat _randFlat;
CLHEP::RandGaussQ _randGaussQ;
CLHEP::RandPoissonQ _randPoissonQ;
CLHEP::RandBinomial _randBinomial;
};

CrvPhotonGenerator::CrvPhotonGenerator(const Parameters& conf) :
Expand All @@ -173,7 +174,8 @@ namespace mu2e
_engine{createEngine(art::ServiceHandle<SeedService>()->getSeed())},
_randFlat(_engine),
_randGaussQ(_engine),
_randPoissonQ(_engine)
_randPoissonQ(_engine),
_randBinomial(_engine)
{
//if(_moduleLabels.size()==0) throw std::logic_error("ERROR: a list of crvSteps module labels needs to be provided");
if(_moduleLabels.size()!=_processNames.size()) throw std::logic_error("ERROR: mismatch between specified selectors (crvStepModuleLabels/crvStepProcessNames)");
Expand Down Expand Up @@ -211,7 +213,7 @@ namespace mu2e
}
if(tableLoaded) continue;

_makeCrvPhotons.emplace_back(boost::shared_ptr<mu2eCrv::MakeCrvPhotons>(new mu2eCrv::MakeCrvPhotons(_randFlat, _randGaussQ, _randPoissonQ)));
_makeCrvPhotons.emplace_back(boost::shared_ptr<mu2eCrv::MakeCrvPhotons>(new mu2eCrv::MakeCrvPhotons(_randFlat, _randGaussQ, _randPoissonQ, _randBinomial)));
boost::shared_ptr<mu2eCrv::MakeCrvPhotons> &photonMaker=_makeCrvPhotons.back();
if(_localLookupTables)
{
Expand Down
34 changes: 21 additions & 13 deletions CRVResponse/src/CrvSiPMChargeGenerator_module.cc
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
#include "fhiclcpp/ParameterSet.h"
#include "CLHEP/Units/GlobalSystemOfUnits.h"
#include "CLHEP/Random/Randomize.h"
#include "messagefacility/MessageLogger/MessageLogger.h"

#include <string>
#include <bitset>
Expand Down Expand Up @@ -194,6 +195,17 @@ namespace mu2e

GeomHandle<CosmicRayShield> CRS;
const std::vector<std::shared_ptr<CRSScintillatorBar> > &counters = CRS->getAllCRSScintillatorBars();

//put all photon collections into a vector with indices corresponding to the channel number
//so that the photon collections can be found easily later in the code
std::vector<CrvPhotonsCollection::const_iterator> photonsOfChannel(counters.size()*CRVId::nChanPerBar, crvPhotonsCollection->end());
for(CrvPhotonsCollection::const_iterator p=crvPhotonsCollection->begin(); p!=crvPhotonsCollection->end(); ++p)
{
size_t channel = p->GetScintillatorBarIndex().asUint()*CRVId::nChanPerBar + p->GetSiPMNumber();
if(photonsOfChannel.at(channel)==crvPhotonsCollection->end()) photonsOfChannel[channel]=p; //there haven't been photons for this channel yet (as it should be)
else throw cet::exception("CrvSiPMChargeGenerator") << "Found more than one entry in the CrvPhotonsCollection for channel " << channel << ".";
}

std::vector<std::shared_ptr<CRSScintillatorBar> >::const_iterator iter;
for(iter=counters.begin(); iter!=counters.end(); iter++)
{
Expand All @@ -206,29 +218,25 @@ namespace mu2e
//0 ... negative side
//1 ... positive side

size_t channel = barIndex.asUint()*CRVId::nChanPerBar + SiPM;
if(_useSipmStatusDB)
{
size_t channel = barIndex.asUint()*CRVId::nChanPerBar + SiPM;
std::bitset<16> status(sipmStatus.status(channel));
if(status.test(CRVStatus::Flags::notConnected) || status.test(CRVStatus::Flags::noData)) continue; //SiPM not connected (bit 0) or no data (bit 2)
}

//time wrapping happened in the photon generator
std::vector<std::pair<double,size_t> > photonTimesNew; //pair of photon time and index in the original photon vector
CrvPhotonsCollection::const_iterator crvPhotons; //after this loop, it will point to the correct index in the photon collection, if barIndex and SiPM is found
//otherwise it will be crvPhotonsCollection->end()
for(crvPhotons=crvPhotonsCollection->begin(); crvPhotons!=crvPhotonsCollection->end(); crvPhotons++)
CrvPhotonsCollection::const_iterator crvPhotons=photonsOfChannel.at(channel); //will be crvPhotonsCollection->end(), if there were no photons at this channel
if(crvPhotons!=crvPhotonsCollection->end())
{
if(crvPhotons->GetScintillatorBarIndex()==barIndex && crvPhotons->GetSiPMNumber()==(int)SiPM)
const std::vector<CrvPhotons::SinglePhoton> &photonTimes = crvPhotons->GetPhotons();
photonTimesNew.reserve(photonTimes.size());
for(size_t iphoton=0; iphoton<photonTimes.size(); iphoton++)
{
const std::vector<CrvPhotons::SinglePhoton> &photonTimes = crvPhotons->GetPhotons();
for(size_t iphoton=0; iphoton<photonTimes.size(); iphoton++)
{
//No check whether photons are within startTime and endTime
double time = photonTimes[iphoton]._time;
photonTimesNew.emplace_back(time,iphoton);
}
break;
//No check whether photons are within startTime and endTime
double time = photonTimes[iphoton]._time;
photonTimesNew.emplace_back(time,iphoton);
}
}

Expand Down
150 changes: 95 additions & 55 deletions CRVResponse/src/MakeCrvPhotons.cc
Original file line number Diff line number Diff line change
Expand Up @@ -118,12 +118,12 @@ unsigned int LookupBinDefinitions::getNFiberCerenkovBins()

unsigned int LookupBinDefinitions::findBin(const std::vector<double> &v, const double &x, bool &notFound)
{
for(size_t i=1; i<v.size(); i++)
if(v.size()<2 || !(v.front()<=x && x<=v.back()))
{
if(v[i-1]<=x && v[i]>=x) return(i-1);
notFound=true;
return(-1);
}
notFound=true;
return(-1);
return(std::lower_bound(v.begin()+1,v.end(),x)-v.begin()-1);
}
int LookupBinDefinitions::findScintillatorScintillationBin(double x, double y, double z)
{
Expand Down Expand Up @@ -347,10 +347,14 @@ void MakeCrvPhotons::MakePhotons(const CLHEP::Hep3Vector &stepStartTmp, //they
int nPhotonsCerenkovInScintillatorPerStep = GetNumberOfPhotonsFromAverage(avgNPhotonsCerenkovInScintillator,nSteps);
int nPhotonsCerenkovInFiberPerStep = GetNumberOfPhotonsFromAverage(avgNPhotonsCerenkovInFiber,nSteps);

//first find all bin numbers, so that repeated bin numbers can be merged
std::vector<int> binNumbers0, binNumbers1, binNumbers2;
binNumbers0.reserve(nSteps);
binNumbers1.reserve(nSteps);
binNumbers2.reserve(nSteps);
for(int step=0; step<nSteps; step++)
{
double stepFraction = (step+0.5)/nSteps;
double t = timeStart + (timeEnd-timeStart)*stepFraction;
CLHEP::Hep3Vector p = stepStart[SiPM] + distanceVector*stepFraction; //local start position of photons

bool isInScintillator = IsInsideScintillator(p);
Expand All @@ -359,69 +363,105 @@ void MakeCrvPhotons::MakePhotons(const CLHEP::Hep3Vector &stepStartTmp, //they
//0...+pi due to symmetry
bool isInFiber = IsInsideFiber(p,distanceVector, r,phi);

const LookupBin *scintillationBin=NULL;
const LookupBin *cerenkovBin=NULL;
int nPhotonsScintillation=0;
int nPhotonsCerenkov=0;
int binNumber0=-1;
int binNumber1=-1;
int binNumber2=-1;
if(isInScintillator)
{
int binNumberS=_LBD.findScintillatorScintillationBin(fabs(p.x()),p.y(),p.z()); //use only positive x values due to symmetry in x
if(binNumberS>=0)
{
scintillationBin = &_bins[0][binNumberS]; //lookup table number for scintillation in scintillator is 0
nPhotonsScintillation = nPhotonsScintillationPerStep;
}
int binNumberC=_LBD.findScintillatorCerenkovBin(fabs(p.x()),p.y(),p.z(),beta); //use only positive x values due to symmetry in x
if(binNumberC>=0)
{
cerenkovBin = &_bins[1][binNumberC]; //lookup table number for cerenkov in scintillator is 1
nPhotonsCerenkov = nPhotonsCerenkovInScintillatorPerStep;
}
binNumber0=_LBD.findScintillatorScintillationBin(fabs(p.x()),p.y(),p.z()); //use only positive x values due to symmetry in x
binNumber1=_LBD.findScintillatorCerenkovBin(fabs(p.x()),p.y(),p.z(),beta); //use only positive x values due to symmetry in x
}
else if(isInFiber)
{
int binNumber=_LBD.findFiberCerenkovBin(beta,theta,phi,r,p.z());
if(binNumber>=0)
{
cerenkovBin = &_bins[2][binNumber]; //lookup table number for cerenkov in fiber is 2
nPhotonsCerenkov = nPhotonsCerenkovInFiberPerStep;
}
binNumber2=_LBD.findFiberCerenkovBin(beta,theta,phi,r,p.z());
}
binNumbers0.push_back(binNumber0);
binNumbers1.push_back(binNumber1);
binNumbers2.push_back(binNumber2);
}

for(int step=0; step<nSteps; step++)
{
int binNumber0=binNumbers0.at(step);
int binNumber1=binNumbers1.at(step);
int binNumber2=binNumbers2.at(step);

//loop over all photons created at this point
int nPhotons = nPhotonsScintillation + nPhotonsCerenkov;
for(int i=0; i<nPhotons; i++)
//find out how many subsequent steps use the same bin numbers
int repeatedBins=1; //merge steps if they use the same bin.
for(int i=step+1; i<nSteps; ++i)
{
//get the right bin
const LookupBin *theBin=cerenkovBin;
if(i<nPhotonsScintillation) theBin=scintillationBin;
if(theBin==NULL) continue; //this can't actually happen

//photon arrival probability at SiPM
double probability = theBin->arrivalProbability;
probability*=_photonYieldDeviation[SiPM]; //channel-specific deviation from nominal, e.g. due to scintillator variations or SiPM misalignments
if(_randFlat.fire()<=probability) //a photon arrives at the SiPM --> calculate arrival time
{
//start time of photons
double arrivalTime = t;

//add fiber decay times depending on the number of emissions
int nEmissions = GetRandomFiberEmissions(theBin);
for(int iEmission=0; iEmission<nEmissions; iEmission++) arrivalTime+=-_LC.WLSfiberDecayTime*log(_randFlat.fire());

//add additional time delay due to the photons bouncing around
arrivalTime+=GetRandomTime(theBin);

if(reflector!=-1 && reflector!=-2) _arrivalTimes[SiPM].push_back(arrivalTime);
else _arrivalTimes[SiPM+1].push_back(arrivalTime);

}// if a photon was created
}//loop over all photons at this point
if(binNumbers0.at(i)==binNumber0 && binNumbers1.at(i)==binNumber1 && binNumbers2.at(i)==binNumber2) ++repeatedBins;
else break;
}

double stepFraction = (step+0.5*(repeatedBins-1)+0.5)/nSteps; //center of the sequence of multiple steps
double photonStartTime = timeStart + (timeEnd-timeStart)*stepFraction;
step+=repeatedBins-1; //skip forward

//lookup table numbers
//- for scintillation in scintillator is 0
//- for cerenkov in scintillator is 1
//- for cerenkov in fiber is 2
if(binNumber0>=0) ProcessPhotons(&_bins[0][binNumber0], nPhotonsScintillationPerStep*repeatedBins, photonStartTime, SiPM, reflector);
if(binNumber1>=0) ProcessPhotons(&_bins[1][binNumber1], nPhotonsCerenkovInScintillatorPerStep*repeatedBins, photonStartTime, SiPM, reflector);
if(binNumber2>=0) ProcessPhotons(&_bins[2][binNumber2], nPhotonsCerenkovInFiberPerStep*repeatedBins, photonStartTime, SiPM, reflector);
}//loop over all steps along the track
}//loop over all SiPMs

}

void MakeCrvPhotons::ProcessPhotons(const LookupBin *theBin, int nPhotons, double photonStartTime, int SiPM, int reflector)
{
if(theBin==NULL || nPhotons<=0) return;

//photon arrival probability at SiPM
double probability = theBin->arrivalProbability;
probability*=_photonYieldDeviation[SiPM]; //channel-specific deviation from nominal, e.g. due to scintillator variations or SiPM misalignments

//number of photons arriving at the SiPM - calculated from a binomial distribution
int nPhotonsArrived=0;
//special CLHEP::RandBinomial cases: probability equal to 0 or 1 results in -1. (also when nPhotons equal to 0, but this case is checked above.)
if(probability>=1.0) nPhotonsArrived=nPhotons;
else if(probability>0.0)
{
//CLHEP::RandBinomial returns values that are too low (or even zero) for small value of n*p.
//So it should be used only for large n*p, where it returns the correct results and is faster than the inversion.
if(nPhotons*probability>15.0) nPhotonsArrived=static_cast<int>(_randBinomial.fire(nPhotons,probability));
else //inverse transform sampling. takes more time for large n*p
{
double logq = std::log1p(-probability);
double pk = std::exp(nPhotons*logq); //P(0)=q^n //the n*p>15.0 cut prevents this from ever being zero (which could happen for very negative arguments)
double cdf = pk; //if pk was 0, the while loop wouldn't be entered
double r = probability/(1.0-probability); //(to prevent it from getting stuck, because pk would remain at 0 in the loop).
double u = _randFlat.fire();
while(u>cdf && nPhotonsArrived<nPhotons && pk>0.0)
{
pk *= r*(nPhotons-nPhotonsArrived)/(nPhotonsArrived+1.0); //P(k+1)=P(k)*(n-k)/(k+1)*p/q
cdf += pk;
++nPhotonsArrived;
}
}
}

//calculate arrival time for each photon
for(long iPhoton=0; iPhoton<nPhotonsArrived; ++iPhoton)
{
//start time of photons
double arrivalTime = photonStartTime;

//add fiber decay times depending on the number of emissions
int nEmissions = GetRandomFiberEmissions(theBin);
for(int iEmission=0; iEmission<nEmissions; iEmission++) arrivalTime+=-_LC.WLSfiberDecayTime*log(_randFlat.fire());

//add additional time delay due to the photons bouncing around
arrivalTime+=GetRandomTime(theBin);

if(reflector!=-1 && reflector!=-2) _arrivalTimes[SiPM].push_back(arrivalTime);
else _arrivalTimes[SiPM+1].push_back(arrivalTime);

}//photons arriving at the SiPM
}

bool MakeCrvPhotons::IsInsideScintillator(const CLHEP::Hep3Vector &p)
{
if(fabs(p.x())>=_LC.halfThickness) return false;
Expand Down
Loading