CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
SiPixelDigitizerAlgorithm.cc
Go to the documentation of this file.
1 //class SiPixelDigitizerAlgorithm SimTracker/SiPixelDigitizer/src/SiPixelDigitizerAlgoithm.cc
2 
3 // Original Author Danek Kotlinski
4 // Ported in CMSSW by Michele Pioppi-INFN perugia
5 // Added DB capabilities by F.Blekman, Cornell University
6 // Created: Mon Sep 26 11:08:32 CEST 2005
7 // Add tof, change AddNoise to tracked. 4/06
8 // Change drift direction. 6/06 d.k.
9 // Add the statuis (non-rate dependent) inefficiency.
10 // -1 - no ineffciency
11 // 0 - static inefficency only
12 // 1,2 - low-lumi rate dependent inefficency added
13 // 10 - high-lumi inefficiency added
14 // Adopt the correct drift sign convetion from Morris Swartz. d.k. 8/06
15 // Add more complex misscalinbration, change kev/e to 3.61, diff=3.7,d.k.9/06
16 // Add the readout channel electronic noise. d.k. 3/07
17 // Lower the pixel noise from 500 to 175elec.
18 // Change the input threshold from noise units to electrons.
19 // Lower the amount of static dead pixels from 0.01 to 0.001.
20 // Modify to the new random number services. d.k. 5/07
21 // Protect against sigma=0 (delta tracks on the surface). d.k.5/07
22 // Change the TOF cut to lower and upper limit. d.k. 7/07
23 //
24 // July 2008: Split Lorentz Angle configuration in BPix/FPix (V. Cuplov)
25 // tanLorentzAngleperTesla_FPix=0.0912 and tanLorentzAngleperTesla_BPix=0.106
26 // Sept. 2008: Disable Pixel modules which are declared dead in the configuration python file. (V. Cuplov)
27 // Oct. 2008: Accessing/Reading the Lorentz angle from the DataBase instead of the cfg file. (V. Cuplov)
28 // Accessing dead modules from the DB. Implementation done and tested on a test.db
29 // Do not use this option for now. The PixelQuality Objects are not in the official DB yet.
30 // Feb. 2009: Split Fpix and Bpix threshold and use official numbers (V. Cuplov)
31 // ThresholdInElectrons_FPix = 2870 and ThresholdInElectrons_BPix = 3700
32 // update the electron to VCAL conversion using: VCAL_electrons = VCAL * 65.5 - 414
33 // Feb. 2009: Threshold gaussian smearing (V. Cuplov)
34 // March, 2009: changed DB access to *SimRcd objects (to de-couple the DB objects from reco chain) (F. Blekman)
35 // May, 2009: Pixel charge VCAL smearing. (V. Cuplov)
36 // November, 2009: new parameterization of the pixel response. (V. Cuplov)
37 // December, 2009: Fix issue with different compilers.
38 // October, 2010: Improvement: Removing single dead ROC (V. Cuplov)
39 // November, 2010: Bug fix in removing TBMB/A half-modules (V. Cuplov)
40 // February, 2011: Time improvement in DriftDirection() (J. Bashir Butt)
41 // June, 2011: Bug Fix for pixels on ROC edges in module_killing_DB() (J. Bashir Butt)
42 #include <iostream>
43 
45 
51 
52 #include <gsl/gsl_sf_erf.h>
54 #include "CLHEP/Random/RandGaussQ.h"
55 #include "CLHEP/Random/RandFlat.h"
56 
57 //#include "PixelIndices.h"
61 
67 
68 // Accessing dead pixel modules from the DB:
70 
72 
85 
91 
92 // Geometry
97 
99 
100 using namespace edm;
101 using namespace sipixelobjects;
102 
103 #define TP_DEBUG // protect all LogDebug with ifdef. Takes too much CPU
104 
105 
107  if(use_ineff_from_db_){// load gain calibration service fromdb...
108  theSiPixelGainCalibrationService_->setESObjects( es );
109  }
110  if(use_deadmodule_DB_) {
111  es.get<SiPixelQualityRcd>().get(SiPixelBadModule_);
112  }
113  if(use_LorentzAngle_DB_) {
114  // Get Lorentz angle from DB record
115  es.get<SiPixelLorentzAngleSimRcd>().get(SiPixelLorentzAngle_);
116  }
117  //gets the map and geometry from the DB (to kill ROCs)
118  es.get<SiPixelFedCablingMapRcd>().get(map_);
119  es.get<TrackerDigiGeometryRecord>().get(geom_);
120 }
121 
122 //=========================================================================
123 
125 
126  _signal(),
127  makeDigiSimLinks_(conf.getUntrackedParameter<bool>("makeDigiSimLinks", true)),
128  use_ineff_from_db_(conf.getParameter<bool>("useDB")),
129  use_module_killing_(conf.getParameter<bool>("killModules")), // boolean to kill or not modules
130  use_deadmodule_DB_(conf.getParameter<bool>("DeadModules_DB")), // boolean to access dead modules from DB
131  use_LorentzAngle_DB_(conf.getParameter<bool>("LorentzAngle_DB")), // boolean to access Lorentz angle from DB
132 
133  DeadModules(use_deadmodule_DB_ ? Parameters() : conf.getParameter<Parameters>("DeadModules")), // get dead module from cfg file
134 
135  // Common pixel parameters
136  // These are parameters which are not likely to be changed
137  GeVperElectron(3.61E-09), // 1 electron(3.61eV, 1keV(277e, mod 9/06 d.k.
138  Sigma0(0.00037), // Charge diffusion constant 7->3.7
139  Dist300(0.0300), // normalized to 300micron Silicon
140  alpha2Order(conf.getParameter<bool>("Alpha2Order")), // switch on/off of E.B effect
141  ClusterWidth(3.), // Charge integration spread on the collection plane
142 
143  // get external parameters:
144  // To account for upgrade geometries do not assume the number
145  // of layers or disks.
146  NumberOfBarrelLayers(conf.exists("NumPixelBarrel")?conf.getParameter<int>("NumPixelBarrel"):3),
147  NumberOfEndcapDisks(conf.exists("NumPixelEndcap")?conf.getParameter<int>("NumPixelEndcap"):2),
148 
149  theInstLumiScaleFactor(conf.getParameter<double>("theInstLumiScaleFactor")), //For dynamic inefficiency PU scaling
150  bunchScaleAt25(conf.getParameter<double>("bunchScaleAt25")), //For dynamic inefficiency bunchspace scaling
151 
152  // ADC calibration 1adc count(135e.
153  // Corresponds to 2adc/kev, 270[e/kev]/135[e/adc](2[adc/kev]
154  // Be carefull, this parameter is also used in SiPixelDet.cc to
155  // calculate the noise in adc counts from noise in electrons.
156  // Both defaults should be the same.
157  theElectronPerADC(conf.getParameter<double>("ElectronPerAdc")),
158 
159  // ADC saturation value, 255(8bit adc.
160  //theAdcFullScale(conf.getUntrackedParameter<int>("AdcFullScale",255)),
161  theAdcFullScale(conf.getParameter<int>("AdcFullScale")),
162  theAdcFullScaleStack(conf.exists("AdcFullScaleStack")?conf.getParameter<int>("AdcFullScaleStack"):255),
163  theFirstStackLayer(conf.exists("FirstStackLayer")?conf.getParameter<int>("FirstStackLayer"):5),
164 
165  // Noise in electrons:
166  // Pixel cell noise, relevant for generating noisy pixels
167  theNoiseInElectrons(conf.getParameter<double>("NoiseInElectrons")),
168 
169  // Fill readout noise, including all readout chain, relevant for smearing
170  //theReadoutNoise(conf.getUntrackedParameter<double>("ReadoutNoiseInElec",500.)),
171  theReadoutNoise(conf.getParameter<double>("ReadoutNoiseInElec")),
172 
173  // Pixel threshold in units of noise:
174  // thePixelThreshold(conf.getParameter<double>("ThresholdInNoiseUnits")),
175  // Pixel threshold in electron units.
176  theThresholdInE_FPix(conf.getParameter<double>("ThresholdInElectrons_FPix")),
177  theThresholdInE_BPix(conf.getParameter<double>("ThresholdInElectrons_BPix")),
178  theThresholdInE_BPix_L1(conf.exists("ThresholdInElectrons_BPix_L1")?conf.getParameter<double>("ThresholdInElectrons_BPix_L1"):theThresholdInE_BPix),
179 
180  // Add threshold gaussian smearing:
181  theThresholdSmearing_FPix(conf.getParameter<double>("ThresholdSmearing_FPix")),
182  theThresholdSmearing_BPix(conf.getParameter<double>("ThresholdSmearing_BPix")),
183  theThresholdSmearing_BPix_L1(conf.exists("ThresholdSmearing_BPix_L1")?conf.getParameter<double>("ThresholdSmearing_BPix_L1"):theThresholdSmearing_BPix),
184 
185  // electrons to VCAL conversion needed in misscalibrate()
186  electronsPerVCAL(conf.getParameter<double>("ElectronsPerVcal")),
187  electronsPerVCAL_Offset(conf.getParameter<double>("ElectronsPerVcal_Offset")),
188 
189  //theTofCut 12.5, cut in particle TOD +/- 12.5ns
190  //theTofCut(conf.getUntrackedParameter<double>("TofCut",12.5)),
191  theTofLowerCut(conf.getParameter<double>("TofLowerCut")),
192  theTofUpperCut(conf.getParameter<double>("TofUpperCut")),
193 
194  // Get the Lorentz angle from the cfg file:
195  tanLorentzAnglePerTesla_FPix(use_LorentzAngle_DB_ ? 0.0 : conf.getParameter<double>("TanLorentzAnglePerTesla_FPix")),
196  tanLorentzAnglePerTesla_BPix(use_LorentzAngle_DB_ ? 0.0 : conf.getParameter<double>("TanLorentzAnglePerTesla_BPix")),
197 
198  // signal response new parameterization: split Fpix and BPix
199  FPix_p0(conf.getParameter<double>("FPix_SignalResponse_p0")),
200  FPix_p1(conf.getParameter<double>("FPix_SignalResponse_p1")),
201  FPix_p2(conf.getParameter<double>("FPix_SignalResponse_p2")),
202  FPix_p3(conf.getParameter<double>("FPix_SignalResponse_p3")),
203 
204  BPix_p0(conf.getParameter<double>("BPix_SignalResponse_p0")),
205  BPix_p1(conf.getParameter<double>("BPix_SignalResponse_p1")),
206  BPix_p2(conf.getParameter<double>("BPix_SignalResponse_p2")),
207  BPix_p3(conf.getParameter<double>("BPix_SignalResponse_p3")),
208 
209  // Add noise
210  addNoise(conf.getParameter<bool>("AddNoise")),
211 
212  // Smear the pixel charge with a gaussian which RMS is a function of the
213  // pixel charge (Danek's study)
214  addChargeVCALSmearing(conf.getParameter<bool>("ChargeVCALSmearing")),
215 
216  // Add noisy pixels
217  addNoisyPixels(conf.getParameter<bool>("AddNoisyPixels")),
218 
219  // Fluctuate charge in track subsegments
220  fluctuateCharge(conf.getUntrackedParameter<bool>("FluctuateCharge",true)),
221 
222  // Control the pixel inefficiency
223  AddPixelInefficiency(conf.getParameter<bool>("AddPixelInefficiencyFromPython")),
224 
225  // Add threshold gaussian smearing:
226  addThresholdSmearing(conf.getParameter<bool>("AddThresholdSmearing")),
227 
228  // Get the constants for the miss-calibration studies
229  doMissCalibrate(conf.getParameter<bool>("MissCalibrate")), // Enable miss-calibration
230  theGainSmearing(conf.getParameter<double>("GainSmearing")), // sigma of the gain smearing
231  theOffsetSmearing(conf.getParameter<double>("OffsetSmearing")), //sigma of the offset smearing
232 
233  // Add pixel radiation damage for upgrade studies
234  AddPixelAging(conf.getParameter<bool>("DoPixelAging")),
235 
236  // delta cutoff in MeV, has to be same as in OSCAR(0.030/cmsim=1.0 MeV
237  //tMax(0.030), // In MeV.
238  //tMax(conf.getUntrackedParameter<double>("DeltaProductionCut",0.030)),
239  tMax(conf.getParameter<double>("DeltaProductionCut")),
240 
241  fluctuate(fluctuateCharge ? new SiG4UniversalFluctuation() : 0),
242  theNoiser(addNoise ? new GaussianTailNoiseGenerator() : 0),
243  calmap(doMissCalibrate ? initCal() : std::map<int,CalParameters,std::less<int> >()),
244  theSiPixelGainCalibrationService_(use_ineff_from_db_ ? new SiPixelGainCalibrationOfflineSimService(conf) : 0),
245  pixelEfficiencies_(conf, AddPixelInefficiency,NumberOfBarrelLayers,NumberOfEndcapDisks),
246  pixelAging_(conf,AddPixelAging,NumberOfBarrelLayers,NumberOfEndcapDisks)
247 {
248  LogInfo ("PixelDigitizer ") <<"SiPixelDigitizerAlgorithm constructed"
249  <<"Configuration parameters:"
250  << "Threshold/Gain = "
251  << "threshold in electron FPix = "
253  << "threshold in electron BPix = "
255  << "threshold in electron BPix Layer1 = "
257  <<" " << theElectronPerADC << " " << theAdcFullScale
258  << " The delta cut-off is set to " << tMax
259  << " pix-inefficiency "<<AddPixelInefficiency;
260 
261 }
262 
263 std::map<int, SiPixelDigitizerAlgorithm::CalParameters, std::less<int> >
265 
266  using std::cerr;
267  using std::cout;
268  using std::endl;
269 
270  std::map<int, SiPixelDigitizerAlgorithm::CalParameters, std::less<int> > calmap;
271  // Prepare for the analog amplitude miss-calibration
272  LogDebug ("PixelDigitizer ")
273  << " miss-calibrate the pixel amplitude ";
274 
275  const bool ReadCalParameters = false;
276  if(ReadCalParameters) { // Read the calibration files from file
277  // read the calibration constants from a file (testing only)
278  std::ifstream in_file; // data file pointer
279  char filename[80] = "phCalibrationFit_C0.dat";
280 
281  in_file.open(filename, std::ios::in ); // in C++
282  if(in_file.bad()) {
283  cout << " File not found " << endl;
284  return calmap; // signal error
285  }
286  cout << " file opened : " << filename << endl;
287 
288  char line[500];
289  for (int i = 0; i < 3; i++) {
290  in_file.getline(line, 500,'\n');
291  cout<<line<<endl;
292  }
293 
294  cout << " test map" << endl;
295 
296  float par0,par1,par2,par3;
297  int colid,rowid;
299  // Read MC tracks
300  for(int i=0;i<(52*80);i++) { // loop over tracks
301  in_file >> par0 >> par1 >> par2 >> par3 >> name >> colid >> rowid;
302  if(in_file.bad()) { // check for errors
303  cerr << "Cannot read data file" << endl;
304  return calmap;
305  }
306  if( in_file.eof() != 0 ) {
307  cerr << in_file.eof() << " " << in_file.gcount() << " "
308  << in_file.fail() << " " << in_file.good() << " end of file "
309  << endl;
310  return calmap;
311  }
312 
313  //cout << " line " << i << " " <<par0<<" "<<par1<<" "<<par2<<" "<<par3<<" "
314  // <<colid<<" "<<rowid<<endl;
315 
316  CalParameters onePix;
317  onePix.p0=par0;
318  onePix.p1=par1;
319  onePix.p2=par2;
320  onePix.p3=par3;
321 
322  // Convert ROC pixel index to channel
323  int chan = PixelIndices::pixelToChannelROC(rowid,colid);
324  calmap.insert(std::pair<int,CalParameters>(chan,onePix));
325 
326  // Testing the index conversion, can be skipped
327  std::pair<int,int> p = PixelIndices::channelToPixelROC(chan);
328  if(rowid!=p.first) cout<<" wrong channel row "<<rowid<<" "<<p.first<<endl;
329  if(colid!=p.second) cout<<" wrong channel col "<<colid<<" "<<p.second<<endl;
330 
331  } // pixel loop in a ROC
332 
333  cout << " map size " << calmap.size() <<" max "<<calmap.max_size() << " "
334  <<calmap.empty()<< endl;
335 
336 // cout << " map size " << calmap.size() << endl;
337 // map<int,CalParameters,std::less<int> >::iterator ix,it;
338 // map<int,CalParameters,std::less<int> >::const_iterator ip;
339 // for (ix = calmap.begin(); ix != calmap.end(); ++ix) {
340 // int i = (*ix).first;
341 // std::pair<int,int> p = channelToPixelROC(i);
342 // it = calmap.find(i);
343 // CalParameters y = (*it).second;
344 // CalParameters z = (*ix).second;
345 // cout << i <<" "<<p.first<<" "<<p.second<<" "<<y.p0<<" "<<z.p0<<" "<<calmap[i].p0<<endl;
346 
347 // //int dummy=0;
348 // //cin>>dummy;
349 // }
350 
351  } // end if readparameters
352  return calmap;
353 } // end initCal()
354 
355 //=========================================================================
357  LogDebug ("PixelDigitizer")<<"SiPixelDigitizerAlgorithm deleted";
358 }
359 
360 SiPixelDigitizerAlgorithm::PixelEfficiencies::PixelEfficiencies(const edm::ParameterSet& conf, bool AddPixelInefficiency, int NumberOfBarrelLayers, int NumberOfEndcapDisks) {
361  // pixel inefficiency
362  // Don't use Hard coded values, read inefficiencies in from python or don't use any
363  int NumberOfTotLayers = NumberOfBarrelLayers + NumberOfEndcapDisks;
365  if (AddPixelInefficiency){
366  int i=0;
367  thePixelColEfficiency[i++] = conf.getParameter<double>("thePixelColEfficiency_BPix1");
368  thePixelColEfficiency[i++] = conf.getParameter<double>("thePixelColEfficiency_BPix2");
369  thePixelColEfficiency[i++] = conf.getParameter<double>("thePixelColEfficiency_BPix3");
370  if (NumberOfBarrelLayers>=4){thePixelColEfficiency[i++] = conf.getParameter<double>("thePixelColEfficiency_BPix4");}
371  //
372  i=0;
373  thePixelEfficiency[i++] = conf.getParameter<double>("thePixelEfficiency_BPix1");
374  thePixelEfficiency[i++] = conf.getParameter<double>("thePixelEfficiency_BPix2");
375  thePixelEfficiency[i++] = conf.getParameter<double>("thePixelEfficiency_BPix3");
376  if (NumberOfBarrelLayers>=4){thePixelEfficiency[i++] = conf.getParameter<double>("thePixelEfficiency_BPix4");}
377  //
378  i=0;
379  thePixelChipEfficiency[i++] = conf.getParameter<double>("thePixelChipEfficiency_BPix1");
380  thePixelChipEfficiency[i++] = conf.getParameter<double>("thePixelChipEfficiency_BPix2");
381  thePixelChipEfficiency[i++] = conf.getParameter<double>("thePixelChipEfficiency_BPix3");
382  if (NumberOfBarrelLayers>=4){thePixelChipEfficiency[i++] = conf.getParameter<double>("thePixelChipEfficiency_BPix4");}
383  //
384  i=0;
385  theLadderEfficiency_BPix[i++] = conf.getParameter<std::vector<double> >("theLadderEfficiency_BPix1");
386  theLadderEfficiency_BPix[i++] = conf.getParameter<std::vector<double> >("theLadderEfficiency_BPix2");
387  theLadderEfficiency_BPix[i++] = conf.getParameter<std::vector<double> >("theLadderEfficiency_BPix3");
388  if ( ((theLadderEfficiency_BPix[0].size()!=20) || (theLadderEfficiency_BPix[1].size()!=32) ||
389  (theLadderEfficiency_BPix[2].size()!=44)) && (NumberOfBarrelLayers==3) )
390  throw cms::Exception("Configuration") << "Wrong ladder number in efficiency config!";
391  //
392  i=0;
393  theModuleEfficiency_BPix[i++] = conf.getParameter<std::vector<double> >("theModuleEfficiency_BPix1");
394  theModuleEfficiency_BPix[i++] = conf.getParameter<std::vector<double> >("theModuleEfficiency_BPix2");
395  theModuleEfficiency_BPix[i++] = conf.getParameter<std::vector<double> >("theModuleEfficiency_BPix3");
396  if ( ((theModuleEfficiency_BPix[0].size()!=4) || (theModuleEfficiency_BPix[1].size()!=4) ||
397  (theModuleEfficiency_BPix[2].size()!=4)) && (NumberOfBarrelLayers==3) )
398  throw cms::Exception("Configuration") << "Wrong module number in efficiency config!";
399  //
400  i=0;
401  thePUEfficiency[i++] = conf.getParameter<std::vector<double> >("thePUEfficiency_BPix1");
402  thePUEfficiency[i++] = conf.getParameter<std::vector<double> >("thePUEfficiency_BPix2");
403  thePUEfficiency[i++] = conf.getParameter<std::vector<double> >("thePUEfficiency_BPix3");
404  if ( ((thePUEfficiency[0].size()==0) || (thePUEfficiency[1].size()==0) ||
405  (thePUEfficiency[2].size()==0)) && (NumberOfBarrelLayers==3) )
406  throw cms::Exception("Configuration") << "At least one PU efficiency (BPix) number is needed in efficiency config!";
407  // The next is needed for Phase2 Tracker studies
408  if (NumberOfBarrelLayers>=5){
409  if (NumberOfTotLayers>20){throw cms::Exception("Configuration") <<"SiPixelDigitizer was given more layers than it can handle";}
410  // For Phase2 tracker layers just set the outermost BPix inefficiency to 99.9%
411  for (int j=5 ; j<=NumberOfBarrelLayers ; j++){
412  thePixelColEfficiency[j-1]=0.999;
413  thePixelEfficiency[j-1]=0.999;
414  thePixelChipEfficiency[j-1]=0.999;
415  }
416  }
417  //
418  i=FPixIndex;
419  thePixelColEfficiency[i++] = conf.getParameter<double>("thePixelColEfficiency_FPix1");
420  thePixelColEfficiency[i++] = conf.getParameter<double>("thePixelColEfficiency_FPix2");
421  if (NumberOfEndcapDisks>=3){thePixelColEfficiency[i++] = conf.getParameter<double>("thePixelColEfficiency_FPix3");}
422  i=FPixIndex;
423  thePixelEfficiency[i++] = conf.getParameter<double>("thePixelEfficiency_FPix1");
424  thePixelEfficiency[i++] = conf.getParameter<double>("thePixelEfficiency_FPix2");
425  if (NumberOfEndcapDisks>=3){thePixelEfficiency[i++] = conf.getParameter<double>("thePixelEfficiency_FPix3");}
426  i=FPixIndex;
427  thePixelChipEfficiency[i++] = conf.getParameter<double>("thePixelChipEfficiency_FPix1");
428  thePixelChipEfficiency[i++] = conf.getParameter<double>("thePixelChipEfficiency_FPix2");
429  if (NumberOfEndcapDisks>=3){thePixelChipEfficiency[i++] = conf.getParameter<double>("thePixelChipEfficiency_FPix3");}
430  // The next is needed for Phase2 Tracker studies
431  if (NumberOfEndcapDisks>=4){
432  if (NumberOfTotLayers>20){throw cms::Exception("Configuration") <<"SiPixelDigitizer was given more layers than it can handle";}
433  // For Phase2 tracker layers just set the extra FPix disk inefficiency to 99.9%
434  for (int j=4+FPixIndex ; j<=NumberOfEndcapDisks+NumberOfBarrelLayers ; j++){
435  thePixelColEfficiency[j-1]=0.999;
436  thePixelEfficiency[j-1]=0.999;
437  thePixelChipEfficiency[j-1]=0.999;
438  }
439  }
440  //FPix Dynamic Inefficiency
441  i=FPixIndex;
442  theInnerEfficiency_FPix[i++] = conf.getParameter<double>("theInnerEfficiency_FPix1");
443  theInnerEfficiency_FPix[i++] = conf.getParameter<double>("theInnerEfficiency_FPix2");
444  i=FPixIndex;
445  theOuterEfficiency_FPix[i++] = conf.getParameter<double>("theOuterEfficiency_FPix1");
446  theOuterEfficiency_FPix[i++] = conf.getParameter<double>("theOuterEfficiency_FPix2");
447  i=FPixIndex;
448  thePUEfficiency[i++] = conf.getParameter<std::vector<double> >("thePUEfficiency_FPix_Inner");
449  thePUEfficiency[i++] = conf.getParameter<std::vector<double> >("thePUEfficiency_FPix_Outer");
450  if ( ((thePUEfficiency[3].size()==0) || (thePUEfficiency[4].size()==0)) && (NumberOfEndcapDisks==2) )
451  throw cms::Exception("Configuration") << "At least one (FPix) PU efficiency number is needed in efficiency config!";
452  }
453  // the first "NumberOfBarrelLayers" settings [0],[1], ... , [NumberOfBarrelLayers-1] are for the barrel pixels
454  // the next "NumberOfEndcapDisks" settings [NumberOfBarrelLayers],[NumberOfBarrelLayers+1], ... [NumberOfEndcapDisks+NumberOfBarrelLayers-1]
455 }
456 
458  // pixel aging
459  // Don't use Hard coded values, read aging in from python or don't use any
460  if(AddAging) {
461  int NumberOfTotLayers = NumberOfBarrelLayers + NumberOfEndcapDisks;
462  FPixIndex=NumberOfBarrelLayers;
463 
464  int i=0;
465  thePixelPseudoRadDamage[i++] = conf.getParameter<double>("thePixelPseudoRadDamage_BPix1");
466  thePixelPseudoRadDamage[i++] = conf.getParameter<double>("thePixelPseudoRadDamage_BPix2");
467  thePixelPseudoRadDamage[i++] = conf.getParameter<double>("thePixelPseudoRadDamage_BPix3");
468  thePixelPseudoRadDamage[i++] = conf.getParameter<double>("thePixelPseudoRadDamage_BPix4");
469 
470  // to be removed when Gaelle will have the phase2 digitizer
471  if (NumberOfBarrelLayers>=5){
472  if (NumberOfTotLayers>20){throw cms::Exception("Configuration") <<"SiPixelDigitizer was given more layers than it can handle";}
473  // For Phase2 tracker layers just set the outermost BPix aging 0.
474  for (int j=5 ; j<=NumberOfBarrelLayers ; j++){
475  thePixelPseudoRadDamage[j-1]=0.;
476  }
477  }
478  //
479  i=FPixIndex;
480  thePixelPseudoRadDamage[i++] = conf.getParameter<double>("thePixelPseudoRadDamage_FPix1");
481  thePixelPseudoRadDamage[i++] = conf.getParameter<double>("thePixelPseudoRadDamage_FPix2");
482  thePixelPseudoRadDamage[i++] = conf.getParameter<double>("thePixelPseudoRadDamage_FPix3");
483 
484  //To be removed when Phase2 digitizer will be available
485  if (NumberOfEndcapDisks>=4){
486  if (NumberOfTotLayers>20){throw cms::Exception("Configuration") <<"SiPixelDigitizer was given more layers than it can handle";}
487  // For Phase2 tracker layers just set the extra FPix disk aging to 0.
488  for (int j=4+FPixIndex ; j<=NumberOfEndcapDisks+NumberOfBarrelLayers ; j++){
489  thePixelPseudoRadDamage[j-1]=0.;
490  }
491  }
492  }
493  // the first "NumberOfBarrelLayers" settings [0],[1], ... , [NumberOfBarrelLayers-1] are for the barrel pixels
494  // the next "NumberOfEndcapDisks" settings [NumberOfBarrelLayers],[NumberOfBarrelLayers+1], ... [NumberOfEndcapDisks+NumberOfBarrelLayers-1]
495 }
496 
497 //=========================================================================
498 void SiPixelDigitizerAlgorithm::accumulateSimHits(std::vector<PSimHit>::const_iterator inputBegin,
499  std::vector<PSimHit>::const_iterator inputEnd,
500  const size_t inputBeginGlobalIndex,
501  const unsigned int tofBin,
502  const PixelGeomDetUnit* pixdet,
503  const GlobalVector& bfield,
504  const TrackerTopology *tTopo,
505  CLHEP::HepRandomEngine* engine) {
506  // produce SignalPoint's for all SimHit's in detector
507  // Loop over hits
508 
509  uint32_t detId = pixdet->geographicalId().rawId();
510  size_t simHitGlobalIndex=inputBeginGlobalIndex; // This needs to stored to create the digi-sim link later
511  for (std::vector<PSimHit>::const_iterator ssbegin = inputBegin; ssbegin != inputEnd; ++ssbegin, ++simHitGlobalIndex) {
512  // skip hits not in this detector.
513  if((*ssbegin).detUnitId() != detId) {
514  continue;
515  }
516 
517 #ifdef TP_DEBUG
518  LogDebug ("Pixel Digitizer")
519  << (*ssbegin).particleType() << " " << (*ssbegin).pabs() << " "
520  << (*ssbegin).energyLoss() << " " << (*ssbegin).tof() << " "
521  << (*ssbegin).trackId() << " " << (*ssbegin).processType() << " "
522  << (*ssbegin).detUnitId()
523  << (*ssbegin).entryPoint() << " " << (*ssbegin).exitPoint() ;
524 #endif
525 
526 
527  std::vector<EnergyDepositUnit> ionization_points;
528  std::vector<SignalPoint> collection_points;
529 
530  // fill collection_points for this SimHit, indpendent of topology
531  // Check the TOF cut
532  if ( ((*ssbegin).tof() - pixdet->surface().toGlobal((*ssbegin).localPosition()).mag()/30.)>= theTofLowerCut &&
533  ((*ssbegin).tof()- pixdet->surface().toGlobal((*ssbegin).localPosition()).mag()/30.) <= theTofUpperCut ) {
534  primary_ionization(*ssbegin, ionization_points, engine); // fills _ionization_points
535  drift(*ssbegin, pixdet, bfield, tTopo, ionization_points, collection_points); // transforms _ionization_points to collection_points
536  // compute induced signal on readout elements and add to _signal
537  induce_signal(*ssbegin, simHitGlobalIndex, tofBin, pixdet, collection_points); // 1st 3 args needed only for SimHit<-->Digi link
538  } // end if
539  } // end for
540 
541 }
542 
543 //============================================================================
545  //Instlumi scalefactor calculating for dynamic inefficiency
546 
547  if (puInfo) {
548  const std::vector<int> bunchCrossing = puInfo->getMix_bunchCrossing();
549  const std::vector<float> TrueInteractionList = puInfo->getMix_TrueInteractions();
550  const int bunchSpacing = puInfo->getMix_bunchSpacing();
551  double bunchScale=1.0;
552 
553  if (bunchSpacing==25) bunchScale=bunchScaleAt25;
554 
555  int pui = 0, p = 0;
556  std::vector<int>::const_iterator pu;
557  std::vector<int>::const_iterator pu0 = bunchCrossing.end();
558 
559  for (pu=bunchCrossing.begin(); pu!=bunchCrossing.end(); ++pu) {
560  if (*pu==0) {
561  pu0 = pu;
562  p = pui;
563  }
564  pui++;
565  }
566 
567  if (pu0!=bunchCrossing.end()) {
568  for (size_t i=0; i<5; i++) {
569  double instlumi = TrueInteractionList.at(p)*theInstLumiScaleFactor*bunchScale;
570  double instlumi_pow=1.;
571  _pu_scale[i] = 0;
572  for (size_t j=0; j<pixelEfficiencies_.thePUEfficiency[i].size(); j++){
573  _pu_scale[i]+=instlumi_pow*pixelEfficiencies_.thePUEfficiency[i][j];
574  instlumi_pow*=instlumi;
575  }
576  }
577  }
578  }
579  else {
580  for (int i=0; i<5;i++) {
581  _pu_scale[i] = 1.;
582  }
583  }
584 }
585 
586 //============================================================================
588  std::vector<PixelDigi>& digis,
589  std::vector<PixelDigiSimLink>& simlinks,
590  const TrackerTopology *tTopo,
591  CLHEP::HepRandomEngine* engine) {
592 
593  // Pixel Efficiency moved from the constructor to this method because
594  // the information of the det are not available in the constructor
595  // Efficiency parameters. 0 - no inefficiency, 1-low lumi, 10-high lumi
596 
597  uint32_t detID = pixdet->geographicalId().rawId();
598  const signal_map_type& theSignal = _signal[detID];
599 
600  const PixelTopology* topol=&pixdet->specificTopology();
601  int numColumns = topol->ncolumns(); // det module number of cols&rows
602  int numRows = topol->nrows();
603 
604  // Noise already defined in electrons
605  // thePixelThresholdInE = thePixelThreshold * theNoiseInElectrons ;
606  // Find the threshold in noise units, needed for the noiser.
607 
608  unsigned int Sub_detid=DetId(detID).subdetId();
609 
610  float thePixelThresholdInE = 0.;
611 
612  if(theNoiseInElectrons>0.){
613  if(Sub_detid == PixelSubdetector::PixelBarrel){ // Barrel modules
614  int lay = tTopo->pxbLayer(detID);
616  if(lay==1) {
617  thePixelThresholdInE = CLHEP::RandGaussQ::shoot(engine, theThresholdInE_BPix_L1, theThresholdSmearing_BPix_L1); // gaussian smearing
618  } else {
619  thePixelThresholdInE = CLHEP::RandGaussQ::shoot(engine, theThresholdInE_BPix , theThresholdSmearing_BPix); // gaussian smearing
620  }
621  } else {
622  if(lay==1) {
623  thePixelThresholdInE = theThresholdInE_BPix_L1;
624  } else {
625  thePixelThresholdInE = theThresholdInE_BPix; // no smearing
626  }
627  }
628  } else { // Forward disks modules
630  thePixelThresholdInE = CLHEP::RandGaussQ::shoot(engine, theThresholdInE_FPix, theThresholdSmearing_FPix); // gaussian smearing
631  } else {
632  thePixelThresholdInE = theThresholdInE_FPix; // no smearing
633  }
634  }
635  }
636 
637 
638 #ifdef TP_DEBUG
639  // full detector thickness
640  float moduleThickness = pixdet->specificSurface().bounds().thickness();
641  LogDebug ("PixelDigitizer")
642  << " PixelDigitizer "
643  << numColumns << " " << numRows << " " << moduleThickness;
644 #endif
645 
646  if(addNoise) add_noise(pixdet, thePixelThresholdInE/theNoiseInElectrons, engine); // generate noise
647 
648  // Do only if needed
649 
650  if((AddPixelInefficiency) && (theSignal.size()>0))
651  pixel_inefficiency(pixelEfficiencies_, pixdet, tTopo, engine); // Kill some pixels
652 
653  if(use_ineff_from_db_ && (theSignal.size()>0))
654  pixel_inefficiency_db(detID);
655 
656  if(use_module_killing_) {
657  if (use_deadmodule_DB_) { // remove dead modules using DB
658  module_killing_DB(detID);
659  } else { // remove dead modules using the list in cfg file
660  module_killing_conf(detID);
661  }
662  }
663 
664  make_digis(thePixelThresholdInE, detID, digis, simlinks, tTopo);
665 
666 #ifdef TP_DEBUG
667  LogDebug ("PixelDigitizer") << "[SiPixelDigitizerAlgorithm] converted " << digis.size() << " PixelDigis in DetUnit" << detID;
668 #endif
669 }
670 
671 //***********************************************************************/
672 // Generate primary ionization along the track segment.
673 // Divide the track into small sub-segments
674 void SiPixelDigitizerAlgorithm::primary_ionization(const PSimHit& hit, std::vector<EnergyDepositUnit>& ionization_points, CLHEP::HepRandomEngine* engine) const {
675 
676  // Straight line approximation for trajectory inside active media
677 
678  const float SegmentLength = 0.0010; //10microns in cm
679  float energy;
680 
681  // Get the 3D segment direction vector
682  LocalVector direction = hit.exitPoint() - hit.entryPoint();
683 
684  float eLoss = hit.energyLoss(); // Eloss in GeV
685  float length = direction.mag(); // Track length in Silicon
686 
687  int NumberOfSegments = int ( length / SegmentLength); // Number of segments
688  if(NumberOfSegments < 1) NumberOfSegments = 1;
689 
690 #ifdef TP_DEBUG
691  LogDebug ("Pixel Digitizer")
692  << " enter primary_ionzation " << NumberOfSegments
693  << " shift = "
694  << (hit.exitPoint().x()-hit.entryPoint().x()) << " "
695  << (hit.exitPoint().y()-hit.entryPoint().y()) << " "
696  << (hit.exitPoint().z()-hit.entryPoint().z()) << " "
697  << hit.particleType() <<" "<< hit.pabs() ;
698 #endif
699 
700  float* elossVector = new float[NumberOfSegments]; // Eloss vector
701 
702  if( fluctuateCharge ) {
703  //MP DA RIMUOVERE ASSOLUTAMENTE
704  int pid = hit.particleType();
705  //int pid=211; // assume it is a pion
706 
707  float momentum = hit.pabs();
708  // Generate fluctuated charge points
709  fluctuateEloss(pid, momentum, eLoss, length, NumberOfSegments,
710  elossVector, engine);
711  }
712 
713  ionization_points.resize( NumberOfSegments); // set size
714 
715  // loop over segments
716  for ( int i = 0; i != NumberOfSegments; i++) {
717  // Divide the segment into equal length subsegments
718  Local3DPoint point = hit.entryPoint() +
719  float((i+0.5)/NumberOfSegments) * direction;
720 
721  if( fluctuateCharge )
722  energy = elossVector[i]/GeVperElectron; // Convert charge to elec.
723  else
724  energy = hit.energyLoss()/GeVperElectron/float(NumberOfSegments);
725 
726  EnergyDepositUnit edu( energy, point); //define position,energy point
727  ionization_points[i] = edu; // save
728 
729 #ifdef TP_DEBUG
730  LogDebug ("Pixel Digitizer")
731  << i << " " << ionization_points[i].x() << " "
732  << ionization_points[i].y() << " "
733  << ionization_points[i].z() << " "
734  << ionization_points[i].energy();
735 #endif
736 
737  } // end for loop
738 
739  delete[] elossVector;
740 
741 }
742 //******************************************************************************
743 
744 // Fluctuate the charge comming from a small (10um) track segment.
745 // Use the G4 routine. For mip pions for the moment.
746 void SiPixelDigitizerAlgorithm::fluctuateEloss(int pid, float particleMomentum,
747  float eloss, float length,
748  int NumberOfSegs,float elossVector[],
749  CLHEP::HepRandomEngine* engine) const {
750 
751  // Get dedx for this track
752  //float dedx;
753  //if( length > 0.) dedx = eloss/length;
754  //else dedx = eloss;
755 
756  double particleMass = 139.6; // Mass in MeV, Assume pion
757  pid = std::abs(pid);
758  if(pid!=211) { // Mass in MeV
759  if(pid==11) particleMass = 0.511;
760  else if(pid==13) particleMass = 105.7;
761  else if(pid==321) particleMass = 493.7;
762  else if(pid==2212) particleMass = 938.3;
763  }
764  // What is the track segment length.
765  float segmentLength = length/NumberOfSegs;
766 
767  // Generate charge fluctuations.
768  float de=0.;
769  float sum=0.;
770  double segmentEloss = (1000.*eloss)/NumberOfSegs; //eloss in MeV
771  for (int i=0;i<NumberOfSegs;i++) {
772  // material,*, momentum,energy,*, *, mass
773  //myglandz_(14.,segmentLength,2.,2.,dedx,de,0.14);
774  // The G4 routine needs momentum in MeV, mass in Mev, delta-cut in MeV,
775  // track segment length in mm, segment eloss in MeV
776  // Returns fluctuated eloss in MeV
777  double deltaCutoff = tMax; // the cutoff is sometimes redefined inside, so fix it.
778  de = fluctuate->SampleFluctuations(double(particleMomentum*1000.),
779  particleMass, deltaCutoff,
780  double(segmentLength*10.),
781  segmentEloss, engine )/1000.; //convert to GeV
782  elossVector[i]=de;
783  sum +=de;
784  }
785 
786  if(sum>0.) { // If fluctuations give eloss>0.
787  // Rescale to the same total eloss
788  float ratio = eloss/sum;
789 
790  for (int ii=0;ii<NumberOfSegs;ii++) elossVector[ii]= ratio*elossVector[ii];
791  } else { // If fluctuations gives 0 eloss
792  float averageEloss = eloss/NumberOfSegs;
793  for (int ii=0;ii<NumberOfSegs;ii++) elossVector[ii]= averageEloss;
794  }
795  return;
796 }
797 
798 //*******************************************************************************
799 // Drift the charge segments to the sensor surface (collection plane)
800 // Include the effect of E-field and B-field
802  const PixelGeomDetUnit* pixdet,
803  const GlobalVector& bfield,
804  const TrackerTopology *tTopo,
805  const std::vector<EnergyDepositUnit>& ionization_points,
806  std::vector<SignalPoint>& collection_points) const {
807 
808 #ifdef TP_DEBUG
809  LogDebug ("Pixel Digitizer") << " enter drift " ;
810 #endif
811 
812  collection_points.resize(ionization_points.size()); // set size
813 
814  LocalVector driftDir=DriftDirection(pixdet, bfield, hit.detUnitId()); // get the charge drift direction
815  if(driftDir.z() ==0.) {
816  LogWarning("Magnetic field") << " pxlx: drift in z is zero ";
817  return;
818  }
819 
820  // tangent of Lorentz angle
821  //float TanLorenzAngleX = driftDir.x()/driftDir.z();
822  //float TanLorenzAngleY = 0.; // force to 0, driftDir.y()/driftDir.z();
823 
824  float TanLorenzAngleX, TanLorenzAngleY,dir_z, CosLorenzAngleX,
825  CosLorenzAngleY;
826  if( alpha2Order) {
827  TanLorenzAngleX = driftDir.x(); // tangen of Lorentz angle
828  TanLorenzAngleY = driftDir.y();
829  dir_z = driftDir.z(); // The z drift direction
830  CosLorenzAngleX = 1./sqrt(1.+TanLorenzAngleX*TanLorenzAngleX); //cosine
831  CosLorenzAngleY = 1./sqrt(1.+TanLorenzAngleY*TanLorenzAngleY); //cosine;
832 
833  } else{
834  TanLorenzAngleX = driftDir.x();
835  TanLorenzAngleY = 0.; // force to 0, driftDir.y()/driftDir.z();
836  dir_z = driftDir.z(); // The z drift direction
837  CosLorenzAngleX = 1./sqrt(1.+TanLorenzAngleX*TanLorenzAngleX); //cosine to estimate the path length
838  CosLorenzAngleY = 1.;
839  }
840 
841  float moduleThickness = pixdet->specificSurface().bounds().thickness();
842 #ifdef TP_DEBUG
843  LogDebug ("Pixel Digitizer")
844  << " Lorentz Tan " << TanLorenzAngleX << " " << TanLorenzAngleY <<" "
845  << CosLorenzAngleX << " " << CosLorenzAngleY << " "
846  << moduleThickness*TanLorenzAngleX << " " << driftDir;
847 #endif
848 
849  float Sigma_x = 1.; // Charge spread
850  float Sigma_y = 1.;
851  float DriftDistance; // Distance between charge generation and collection
852  float DriftLength; // Actual Drift Lentgh
853  float Sigma;
854 
855  for (unsigned int i = 0; i != ionization_points.size(); i++) {
856 
857  float SegX, SegY, SegZ; // position
858  SegX = ionization_points[i].x();
859  SegY = ionization_points[i].y();
860  SegZ = ionization_points[i].z();
861 
862  // Distance from the collection plane
863  //DriftDistance = (moduleThickness/2. + SegZ); // Drift to -z
864  // Include explixitely the E drift direction (for CMS dir_z=-1)
865  DriftDistance = moduleThickness/2. - (dir_z * SegZ); // Drift to -z
866 
867  //if( DriftDistance <= 0.)
868  //cout<<" <=0 "<<DriftDistance<<" "<<i<<" "<<SegZ<<" "<<dir_z<<" "
869  // <<SegX<<" "<<SegY<<" "<<(moduleThickness/2)<<" "
870  // <<ionization_points[i].energy()<<" "
871  // <<hit.particleType()<<" "<<hit.pabs()<<" "<<hit.energyLoss()<<" "
872  // <<hit.entryPoint()<<" "<<hit.exitPoint()
873  // <<std::endl;
874 
875  if( DriftDistance < 0.) {
876  DriftDistance = 0.;
877  } else if( DriftDistance > moduleThickness )
878  DriftDistance = moduleThickness;
879 
880  // Assume full depletion now, partial depletion will come later.
881  float XDriftDueToMagField = DriftDistance * TanLorenzAngleX;
882  float YDriftDueToMagField = DriftDistance * TanLorenzAngleY;
883 
884  // Shift cloud center
885  float CloudCenterX = SegX + XDriftDueToMagField;
886  float CloudCenterY = SegY + YDriftDueToMagField;
887 
888  // Calculate how long is the charge drift path
889  DriftLength = sqrt( DriftDistance*DriftDistance +
890  XDriftDueToMagField*XDriftDueToMagField +
891  YDriftDueToMagField*YDriftDueToMagField );
892 
893  // What is the charge diffusion after this path
894  Sigma = sqrt(DriftLength/Dist300) * Sigma0;
895 
896  // Project the diffusion sigma on the collection plane
897  Sigma_x = Sigma / CosLorenzAngleX ;
898  Sigma_y = Sigma / CosLorenzAngleY ;
899 
900  // Insert a charge loss due to Rad Damage here
901  float energyOnCollector = ionization_points[i].energy(); // The energy that reaches the collector
902 
903  // add pixel aging
904  if (AddPixelAging) {
905  float kValue = pixel_aging(pixelAging_,pixdet,tTopo);
906  energyOnCollector *= exp( -1*kValue*DriftDistance/moduleThickness );
907  }
908 
909 #ifdef TP_DEBUG
910  LogDebug ("Pixel Digitizer")
911  <<" Dift DistanceZ= "<<DriftDistance<<" module thickness= "<<moduleThickness
912  <<" Start Energy= "<<ionization_points[i].energy()<<" Energy after loss= "<<energyOnCollector;
913 #endif
914  SignalPoint sp( CloudCenterX, CloudCenterY,
915  Sigma_x, Sigma_y, hit.tof(), energyOnCollector );
916 
917  // Load the Charge distribution parameters
918  collection_points[i] = (sp);
919 
920  } // loop over ionization points, i.
921 
922 } // end drift
923 
924 //*************************************************************************
925 // Induce the signal on the collection plane of the active sensor area.
927  const size_t hitIndex,
928  const unsigned int tofBin,
929  const PixelGeomDetUnit* pixdet,
930  const std::vector<SignalPoint>& collection_points) {
931 
932  // X - Rows, Left-Right, 160, (1.6cm) for barrel
933  // Y - Columns, Down-Up, 416, (6.4cm)
934 
935  const PixelTopology* topol=&pixdet->specificTopology();
936  uint32_t detID= pixdet->geographicalId().rawId();
937  signal_map_type& theSignal = _signal[detID];
938 
939 #ifdef TP_DEBUG
940  LogDebug ("Pixel Digitizer")
941  << " enter induce_signal, "
942  << topol->pitch().first << " " << topol->pitch().second; //OK
943 #endif
944 
945  // local map to store pixels hit by 1 Hit.
946  typedef std::map< int, float, std::less<int> > hit_map_type;
947  hit_map_type hit_signal;
948 
949  // map to store pixel integrals in the x and in the y directions
950  std::map<int, float, std::less<int> > x,y;
951 
952  // Assign signals to readout channels and store sorted by channel number
953 
954  // Iterate over collection points on the collection plane
955  for ( std::vector<SignalPoint>::const_iterator i=collection_points.begin();
956  i != collection_points.end(); ++i) {
957 
958  float CloudCenterX = i->position().x(); // Charge position in x
959  float CloudCenterY = i->position().y(); // in y
960  float SigmaX = i->sigma_x(); // Charge spread in x
961  float SigmaY = i->sigma_y(); // in y
962  float Charge = i->amplitude(); // Charge amplitude
963 
964 
965  //if(SigmaX==0 || SigmaY==0) {
966  //cout<<SigmaX<<" "<<SigmaY
967  // << " cloud " << i->position().x() << " " << i->position().y() << " "
968  // << i->sigma_x() << " " << i->sigma_y() << " " << i->amplitude()<<std::endl;
969  //}
970 
971 #ifdef TP_DEBUG
972  LogDebug ("Pixel Digitizer")
973  << " cloud " << i->position().x() << " " << i->position().y() << " "
974  << i->sigma_x() << " " << i->sigma_y() << " " << i->amplitude();
975 #endif
976 
977  // Find the maximum cloud spread in 2D plane , assume 3*sigma
978  float CloudRight = CloudCenterX + ClusterWidth*SigmaX;
979  float CloudLeft = CloudCenterX - ClusterWidth*SigmaX;
980  float CloudUp = CloudCenterY + ClusterWidth*SigmaY;
981  float CloudDown = CloudCenterY - ClusterWidth*SigmaY;
982 
983  // Define 2D cloud limit points
984  LocalPoint PointRightUp = LocalPoint(CloudRight,CloudUp);
985  LocalPoint PointLeftDown = LocalPoint(CloudLeft,CloudDown);
986 
987  // This points can be located outside the sensor area.
988  // The conversion to measurement point does not check for that
989  // so the returned pixel index might be wrong (outside range).
990  // We rely on the limits check below to fix this.
991  // But remember whatever we do here THE CHARGE OUTSIDE THE ACTIVE
992  // PIXEL AREA IS LOST, it should not be collected.
993 
994  // Convert the 2D points to pixel indices
995  MeasurementPoint mp = topol->measurementPosition(PointRightUp ); //OK
996 
997  int IPixRightUpX = int( floor( mp.x()));
998  int IPixRightUpY = int( floor( mp.y()));
999 
1000 #ifdef TP_DEBUG
1001  LogDebug ("Pixel Digitizer") << " right-up " << PointRightUp << " "
1002  << mp.x() << " " << mp.y() << " "
1003  << IPixRightUpX << " " << IPixRightUpY ;
1004 #endif
1005 
1006  mp = topol->measurementPosition(PointLeftDown ); //OK
1007 
1008  int IPixLeftDownX = int( floor( mp.x()));
1009  int IPixLeftDownY = int( floor( mp.y()));
1010 
1011 #ifdef TP_DEBUG
1012  LogDebug ("Pixel Digitizer") << " left-down " << PointLeftDown << " "
1013  << mp.x() << " " << mp.y() << " "
1014  << IPixLeftDownX << " " << IPixLeftDownY ;
1015 #endif
1016 
1017  // Check detector limits to correct for pixels outside range.
1018  int numColumns = topol->ncolumns(); // det module number of cols&rows
1019  int numRows = topol->nrows();
1020 
1021  IPixRightUpX = numRows>IPixRightUpX ? IPixRightUpX : numRows-1 ;
1022  IPixRightUpY = numColumns>IPixRightUpY ? IPixRightUpY : numColumns-1 ;
1023  IPixLeftDownX = 0<IPixLeftDownX ? IPixLeftDownX : 0 ;
1024  IPixLeftDownY = 0<IPixLeftDownY ? IPixLeftDownY : 0 ;
1025 
1026  x.clear(); // clear temporary integration array
1027  y.clear();
1028 
1029  // First integrate charge strips in x
1030  int ix; // TT for compatibility
1031  for (ix=IPixLeftDownX; ix<=IPixRightUpX; ix++) { // loop over x index
1032  float xUB, xLB, UpperBound, LowerBound;
1033 
1034  // Why is set to 0 if ix=0, does it meen that we accept charge
1035  // outside the sensor? CHeck How it was done in ORCA?
1036  //if(ix == 0) LowerBound = 0.;
1037  if(ix == 0 || SigmaX==0. ) // skip for surface segemnts
1038  LowerBound = 0.;
1039  else {
1040  mp = MeasurementPoint( float(ix), 0.0);
1041  xLB = topol->localPosition(mp).x();
1042  LowerBound = 1-calcQ((xLB-CloudCenterX)/SigmaX);
1043  }
1044 
1045  if(ix == numRows-1 || SigmaX==0. )
1046  UpperBound = 1.;
1047  else {
1048  mp = MeasurementPoint( float(ix+1), 0.0);
1049  xUB = topol->localPosition(mp).x();
1050  UpperBound = 1. - calcQ((xUB-CloudCenterX)/SigmaX);
1051  }
1052 
1053  float TotalIntegrationRange = UpperBound - LowerBound; // get strip
1054  x[ix] = TotalIntegrationRange; // save strip integral
1055  //if(SigmaX==0 || SigmaY==0)
1056  //cout<<TotalIntegrationRange<<" "<<ix<<std::endl;
1057 
1058  }
1059 
1060  // Now integrate strips in y
1061  int iy; // TT for compatibility
1062  for (iy=IPixLeftDownY; iy<=IPixRightUpY; iy++) { //loope over y ind
1063  float yUB, yLB, UpperBound, LowerBound;
1064 
1065  if(iy == 0 || SigmaY==0.)
1066  LowerBound = 0.;
1067  else {
1068  mp = MeasurementPoint( 0.0, float(iy) );
1069  yLB = topol->localPosition(mp).y();
1070  LowerBound = 1. - calcQ((yLB-CloudCenterY)/SigmaY);
1071  }
1072 
1073  if(iy == numColumns-1 || SigmaY==0. )
1074  UpperBound = 1.;
1075  else {
1076  mp = MeasurementPoint( 0.0, float(iy+1) );
1077  yUB = topol->localPosition(mp).y();
1078  UpperBound = 1. - calcQ((yUB-CloudCenterY)/SigmaY);
1079  }
1080 
1081  float TotalIntegrationRange = UpperBound - LowerBound;
1082  y[iy] = TotalIntegrationRange; // save strip integral
1083  //if(SigmaX==0 || SigmaY==0)
1084  //cout<<TotalIntegrationRange<<" "<<iy<<std::endl;
1085  }
1086 
1087  // Get the 2D charge integrals by folding x and y strips
1088  int chan;
1089  for (ix=IPixLeftDownX; ix<=IPixRightUpX; ix++) { // loop over x index
1090  for (iy=IPixLeftDownY; iy<=IPixRightUpY; iy++) { //loope over y ind
1091 
1092  float ChargeFraction = Charge*x[ix]*y[iy];
1093 
1094  if( ChargeFraction > 0. ) {
1095  chan = PixelDigi::pixelToChannel( ix, iy); // Get index
1096  // Load the amplitude
1097  hit_signal[chan] += ChargeFraction;
1098  } // endif
1099 
1100 
1101  mp = MeasurementPoint( float(ix), float(iy) );
1102  LocalPoint lp = topol->localPosition(mp);
1103  chan = topol->channel(lp);
1104 
1105 #ifdef TP_DEBUG
1106  LogDebug ("Pixel Digitizer")
1107  << " pixel " << ix << " " << iy << " - "<<" "
1108  << chan << " " << ChargeFraction<<" "
1109  << mp.x() << " " << mp.y() <<" "
1110  << lp.x() << " " << lp.y() << " " // givex edge position
1111  << chan; // edge belongs to previous ?
1112 #endif
1113 
1114  } // endfor iy
1115  } //endfor ix
1116 
1117 
1118  // Test conversions (THIS IS FOR TESTING ONLY) comment-out.
1119  // mp = topol->measurementPosition( i->position() ); //OK
1120  // LocalPoint lp = topol->localPosition(mp); //OK
1121  // std::pair<float,float> p = topol->pixel( i->position() ); //OK
1122  // chan = PixelDigi::pixelToChannel( int(p.first), int(p.second));
1123  // std::pair<int,int> ip = PixelDigi::channelToPixel(chan);
1124  // MeasurementPoint mp1 = MeasurementPoint( float(ip.first),
1125  // float(ip.second) );
1126  // LogDebug ("Pixel Digitizer") << " Test "<< mp.x() << " " << mp.y()
1127  // << " "<< lp.x() << " " << lp.y() << " "<<" "
1128  // <<p.first <<" "<<p.second<<" "<<chan<< " "
1129  // <<" " << ip.first << " " << ip.second << " "
1130  // << mp1.x() << " " << mp1.y() << " " //OK
1131  // << topol->localPosition(mp1).x() << " " //OK
1132  // << topol->localPosition(mp1).y() << " "
1133  // << topol->channel( i->position() ); //OK
1134 
1135 
1136  } // loop over charge distributions
1137 
1138  // Fill the global map with all hit pixels from this event
1139 
1140  for ( hit_map_type::const_iterator im = hit_signal.begin();
1141  im != hit_signal.end(); ++im) {
1142  int chan = (*im).first;
1143  theSignal[chan] += (makeDigiSimLinks_ ? Amplitude( (*im).second, &hit, hitIndex, tofBin, (*im).second) : Amplitude( (*im).second, (*im).second) ) ;
1144 
1145 #ifdef TP_DEBUG
1146  std::pair<int,int> ip = PixelDigi::channelToPixel(chan);
1147  LogDebug ("Pixel Digitizer")
1148  << " pixel " << ip.first << " " << ip.second << " "
1149  << theSignal[chan];
1150 #endif
1151  }
1152 
1153 } // end induce_signal
1154 
1155 /***********************************************************************/
1156 
1157 // Build pixels, check threshold, add misscalibration, ...
1158 void SiPixelDigitizerAlgorithm::make_digis(float thePixelThresholdInE,
1159  uint32_t detID,
1160  std::vector<PixelDigi>& digis,
1161  std::vector<PixelDigiSimLink>& simlinks,
1162  const TrackerTopology *tTopo) const {
1163 
1164 #ifdef TP_DEBUG
1165  LogDebug ("Pixel Digitizer") << " make digis "<<" "
1166  << " pixel threshold FPix" << theThresholdInE_FPix << " "
1167  << " pixel threshold BPix" << theThresholdInE_BPix << " "
1168  << " pixel threshold BPix Layer1" << theThresholdInE_BPix_L1 << " "
1169  << " List pixels passing threshold ";
1170 #endif
1171 
1172  // Loop over hit pixels
1173 
1174  signalMaps::const_iterator it = _signal.find(detID);
1175  if (it == _signal.end()) {
1176  return;
1177  }
1178 
1179  const signal_map_type& theSignal = (*it).second;
1180 
1181  for (signal_map_const_iterator i = theSignal.begin(); i != theSignal.end(); ++i) {
1182 
1183  float signalInElectrons = (*i).second ; // signal in electrons
1184 
1185  // Do the miss calibration for calibration studies only.
1186  //if(doMissCalibrate) signalInElectrons = missCalibrate(signalInElectrons)
1187 
1188  // Do only for pixels above threshold
1189 
1190  if( signalInElectrons >= thePixelThresholdInE) { // check threshold
1191 
1192  int chan = (*i).first; // channel number
1193  std::pair<int,int> ip = PixelDigi::channelToPixel(chan);
1194  int adc=0; // ADC count as integer
1195 
1196  // Do the miss calibration for calibration studies only.
1197  if(doMissCalibrate) {
1198  int row = ip.first; // X in row
1199  int col = ip.second; // Y is in col
1200  adc = int(missCalibrate(detID, col, row, signalInElectrons)); //full misscalib.
1201  } else { // Just do a simple electron->adc conversion
1202  adc = int( signalInElectrons / theElectronPerADC ); // calibrate gain
1203  }
1204  adc = std::min(adc, theAdcFullScale); // Check maximum value
1205 // Calculate layerIndex
1207  unsigned int Sub_detid=DetId(detID).subdetId();
1208  if(Sub_detid == PixelSubdetector::PixelBarrel){ // Barrel modules
1209  int lay = tTopo->pxbLayer(detID);
1210  if (lay>=theFirstStackLayer) {
1211  // Set to 1 if over the threshold
1212  if (theAdcFullScaleStack==1) {adc=1;}
1213  // Make it a linear fit to the full scale of the normal adc count. Start new adc from 1 not zero.
1215  }
1216  }
1217  } // Only enter this if the Adc changes for the outer layers
1218 #ifdef TP_DEBUG
1219  LogDebug ("Pixel Digitizer")
1220  << (*i).first << " " << (*i).second << " " << signalInElectrons
1221  << " " << adc << ip.first << " " << ip.second ;
1222 #endif
1223 
1224  // Load digis
1225  digis.emplace_back(ip.first, ip.second, adc);
1226 
1227  if (makeDigiSimLinks_ && (*i).second.hitInfo()!=0) {
1228  //digilink
1229  if((*i).second.trackIds().size()>0){
1230  simlink_map simi;
1231  unsigned int il=0;
1232  for( std::vector<unsigned int>::const_iterator itid = (*i).second.trackIds().begin();
1233  itid != (*i).second.trackIds().end(); ++itid) {
1234  simi[*itid].push_back((*i).second.individualampl()[il]);
1235  il++;
1236  }
1237 
1238  //sum the contribution of the same trackid
1239  for( simlink_map::iterator simiiter=simi.begin();
1240  simiiter!=simi.end();
1241  simiiter++){
1242 
1243  float sum_samechannel=0;
1244  for (unsigned int iii=0;iii<(*simiiter).second.size();iii++){
1245  sum_samechannel+=(*simiiter).second[iii];
1246  }
1247  float fraction=sum_samechannel/(*i).second;
1248  if(fraction>1.) fraction=1.;
1249  simlinks.emplace_back((*i).first, (*simiiter).first, (*i).second.hitIndex(), (*i).second.tofBin(), (*i).second.eventId(), fraction);
1250  }
1251  }
1252  }
1253  }
1254  }
1255 }
1256 
1257 /***********************************************************************/
1258 
1259 // Add electronic noise to pixel charge
1261  float thePixelThreshold,
1262  CLHEP::HepRandomEngine* engine) {
1263 
1264 #ifdef TP_DEBUG
1265  LogDebug ("Pixel Digitizer") << " enter add_noise " << theNoiseInElectrons;
1266 #endif
1267 
1268  uint32_t detID= pixdet->geographicalId().rawId();
1269  signal_map_type& theSignal = _signal[detID];
1270 
1271 
1272  // First add noise to hit pixels
1273  float theSmearedChargeRMS = 0.0;
1274 
1275  for ( signal_map_iterator i = theSignal.begin(); i != theSignal.end(); i++) {
1276 
1278  {
1279  if((*i).second < 3000)
1280  {
1281  theSmearedChargeRMS = 543.6 - (*i).second * 0.093;
1282  } else if((*i).second < 6000){
1283  theSmearedChargeRMS = 307.6 - (*i).second * 0.01;
1284  } else{
1285  theSmearedChargeRMS = -432.4 +(*i).second * 0.123;
1286  }
1287 
1288  // Noise from Vcal smearing:
1289  float noise_ChargeVCALSmearing = theSmearedChargeRMS * CLHEP::RandGaussQ::shoot(engine, 0., 1.);
1290  // Noise from full readout:
1291  float noise = CLHEP::RandGaussQ::shoot(engine, 0., theReadoutNoise);
1292 
1293  if(((*i).second + Amplitude(noise+noise_ChargeVCALSmearing, -1.)) < 0. ) {
1294  (*i).second.set(0);}
1295  else{
1296  (*i).second +=Amplitude(noise+noise_ChargeVCALSmearing, -1.);
1297  }
1298 
1299  } // End if addChargeVCalSmearing
1300  else
1301  {
1302  // Noise: ONLY full READOUT Noise.
1303  // Use here the FULL readout noise, including TBM,ALT,AOH,OPT-REC.
1304  float noise = CLHEP::RandGaussQ::shoot(engine, 0., theReadoutNoise);
1305 
1306  if(((*i).second + Amplitude(noise, -1.)) < 0. ) {
1307  (*i).second.set(0);}
1308  else{
1309  (*i).second +=Amplitude(noise, -1.);
1310  }
1311  } // end if only Noise from full readout
1312 
1313  }
1314 
1315  if(!addNoisyPixels) // Option to skip noise in non-hit pixels
1316  return;
1317 
1318  const PixelTopology* topol=&pixdet->specificTopology();
1319  int numColumns = topol->ncolumns(); // det module number of cols&rows
1320  int numRows = topol->nrows();
1321 
1322  // Add noise on non-hit pixels
1323  // Use here the pixel noise
1324  int numberOfPixels = (numRows * numColumns);
1325  std::map<int,float, std::less<int> > otherPixels;
1326  std::map<int,float, std::less<int> >::iterator mapI;
1327 
1328  theNoiser->generate(numberOfPixels,
1329  thePixelThreshold, //thr. in un. of nois
1330  theNoiseInElectrons, // noise in elec.
1331  otherPixels,
1332  engine );
1333 
1334 #ifdef TP_DEBUG
1335  LogDebug ("Pixel Digitizer")
1336  << " Add noisy pixels " << numRows << " "
1337  << numColumns << " " << theNoiseInElectrons << " "
1338  << theThresholdInE_FPix << theThresholdInE_BPix <<" "<< numberOfPixels<<" "
1339  << otherPixels.size() ;
1340 #endif
1341 
1342  // Add noisy pixels
1343  for (mapI = otherPixels.begin(); mapI!= otherPixels.end(); mapI++) {
1344  int iy = ((*mapI).first) / numRows;
1345  int ix = ((*mapI).first) - (iy*numRows);
1346 
1347  // Keep for a while for testing.
1348  if( iy < 0 || iy > (numColumns-1) )
1349  LogWarning ("Pixel Geometry") << " error in iy " << iy ;
1350  if( ix < 0 || ix > (numRows-1) )
1351  LogWarning ("Pixel Geometry") << " error in ix " << ix ;
1352 
1353  int chan = PixelDigi::pixelToChannel(ix, iy);
1354 
1355 #ifdef TP_DEBUG
1356  LogDebug ("Pixel Digitizer")
1357  <<" Storing noise = " << (*mapI).first << " " << (*mapI).second
1358  << " " << ix << " " << iy << " " << chan ;
1359 #endif
1360 
1361  if(theSignal[chan] == 0){
1362  // float noise = float( (*mapI).second );
1363  int noise=int( (*mapI).second );
1364  theSignal[chan] = Amplitude (noise, -1.);
1365  }
1366  }
1367 }
1368 
1369 /***********************************************************************/
1370 
1371 // Simulate the readout inefficiencies.
1372 // Delete a selected number of single pixels, dcols and rocs.
1374  const PixelGeomDetUnit* pixdet,
1375  const TrackerTopology *tTopo,
1376  CLHEP::HepRandomEngine* engine) {
1377 
1378  uint32_t detID= pixdet->geographicalId().rawId();
1379  signal_map_type& theSignal = _signal[detID];
1380  const PixelTopology* topol=&pixdet->specificTopology();
1381  int numColumns = topol->ncolumns(); // det module number of cols&rows
1382  int numRows = topol->nrows();
1383 
1384  // Predefined efficiencies
1385  double pixelEfficiency = 1.0;
1386  double columnEfficiency = 1.0;
1387  double chipEfficiency = 1.0;
1388 
1389  // setup the chip indices conversion
1390  unsigned int Subid=DetId(detID).subdetId();
1391  if (Subid== PixelSubdetector::PixelBarrel){// barrel layers
1392  int layerIndex=tTopo->pxbLayer(detID);
1393  pixelEfficiency = eff.thePixelEfficiency[layerIndex-1];
1394  columnEfficiency = eff.thePixelColEfficiency[layerIndex-1];
1395  chipEfficiency = eff.thePixelChipEfficiency[layerIndex-1];
1396  //std::cout <<"Using BPix columnEfficiency = "<<columnEfficiency<< " for layer = "<<layerIndex <<"\n";
1397  // This should never happen, but only check if it is not an upgrade geometry
1398  if (NumberOfBarrelLayers==3){
1399  if(numColumns>416) LogWarning ("Pixel Geometry") <<" wrong columns in barrel "<<numColumns;
1400  if(numRows>160) LogWarning ("Pixel Geometry") <<" wrong rows in barrel "<<numRows;
1401 
1402  int ladder=tTopo->pxbLadder(detID);
1403  int module=tTopo->pxbModule(detID);
1404  if (module<=4) module=5-module;
1405  else module-=4;
1406 
1407  columnEfficiency *= eff.theLadderEfficiency_BPix[layerIndex-1][ladder-1]*eff.theModuleEfficiency_BPix[layerIndex-1][module-1]*_pu_scale[layerIndex-1];
1408  }
1409  } else { // forward disks
1410  unsigned int diskIndex=tTopo->pxfDisk(detID)+eff.FPixIndex; // Use diskIndex-1 later to stay consistent with BPix
1411  unsigned int panelIndex=tTopo->pxfPanel(detID);
1412  unsigned int moduleIndex=tTopo->pxfModule(detID);
1413  //if (eff.FPixIndex>diskIndex-1){throw cms::Exception("Configuration") <<"SiPixelDigitizer is using the wrong efficiency value. index = "
1414  // <<diskIndex-1<<" , MinIndex = "<<eff.FPixIndex<<" ... "<<tTopo->pxfDisk(detID);}
1415  pixelEfficiency = eff.thePixelEfficiency[diskIndex-1];
1416  columnEfficiency = eff.thePixelColEfficiency[diskIndex-1];
1417  chipEfficiency = eff.thePixelChipEfficiency[diskIndex-1];
1418  //std::cout <<"Using FPix columnEfficiency = "<<columnEfficiency<<" for Disk = "<< tTopo->pxfDisk(detID)<<"\n";
1419  // Sometimes the forward pixels have wrong size,
1420  // this crashes the index conversion, so exit, but only check if it is not an upgrade geometry
1421  if (NumberOfBarrelLayers==3){
1422  if(numColumns>260 || numRows>160) {
1423  if(numColumns>260) LogWarning ("Pixel Geometry") <<" wrong columns in endcaps "<<numColumns;
1424  if(numRows>160) LogWarning ("Pixel Geometry") <<" wrong rows in endcaps "<<numRows;
1425  return;
1426  }
1427  if ((panelIndex==1 && (moduleIndex==1 || moduleIndex==2)) || (panelIndex==2 && moduleIndex==1)) { //inner modules
1428  columnEfficiency*=eff.theInnerEfficiency_FPix[diskIndex-1]*_pu_scale[3];
1429  } else { //outer modules
1430  columnEfficiency*=eff.theOuterEfficiency_FPix[diskIndex-1]*_pu_scale[4];
1431  }
1432  } // current detector, forward
1433  } // if barrel/forward
1434 
1435 #ifdef TP_DEBUG
1436  LogDebug ("Pixel Digitizer") << " enter pixel_inefficiency " << pixelEfficiency << " "
1437  << columnEfficiency << " " << chipEfficiency;
1438 #endif
1439 
1440  // Initilize the index converter
1441  //PixelIndices indexConverter(numColumns,numRows);
1442  std::auto_ptr<PixelIndices> pIndexConverter(new PixelIndices(numColumns,numRows));
1443 
1444  int chipIndex = 0;
1445  int rowROC = 0;
1446  int colROC = 0;
1447  std::map<int, int, std::less<int> >chips, columns;
1448  std::map<int, int, std::less<int> >::iterator iter;
1449 
1450  // Find out the number of columns and rocs hits
1451  // Loop over hit pixels, amplitude in electrons, channel = coded row,col
1452  for (signal_map_const_iterator i = theSignal.begin(); i != theSignal.end(); ++i) {
1453 
1454  int chan = i->first;
1455  std::pair<int,int> ip = PixelDigi::channelToPixel(chan);
1456  int row = ip.first; // X in row
1457  int col = ip.second; // Y is in col
1458  //transform to ROC index coordinates
1459  pIndexConverter->transformToROC(col,row,chipIndex,colROC,rowROC);
1460  int dColInChip = pIndexConverter->DColumn(colROC); // get ROC dcol from ROC col
1461  //dcol in mod
1462  int dColInDet = pIndexConverter->DColumnInModule(dColInChip,chipIndex);
1463 
1464  chips[chipIndex]++;
1465  columns[dColInDet]++;
1466  }
1467 
1468  // Delete some ROC hits.
1469  for ( iter = chips.begin(); iter != chips.end() ; iter++ ) {
1470  //float rand = RandFlat::shoot();
1471  float rand = CLHEP::RandFlat::shoot(engine);
1472  if( rand > chipEfficiency ) chips[iter->first]=0;
1473  }
1474 
1475  // Delete some Dcol hits.
1476  for ( iter = columns.begin(); iter != columns.end() ; iter++ ) {
1477  //float rand = RandFlat::shoot();
1478  float rand = CLHEP::RandFlat::shoot(engine);
1479  if( rand > columnEfficiency ) columns[iter->first]=0;
1480  }
1481 
1482  // Now loop again over pixels to kill some of them.
1483  // Loop over hit pixels, amplitude in electrons, channel = coded row,col
1484  for(signal_map_iterator i = theSignal.begin();i != theSignal.end(); ++i) {
1485 
1486  // int chan = i->first;
1487  std::pair<int,int> ip = PixelDigi::channelToPixel(i->first);//get pixel pos
1488  int row = ip.first; // X in row
1489  int col = ip.second; // Y is in col
1490  //transform to ROC index coordinates
1491  pIndexConverter->transformToROC(col,row,chipIndex,colROC,rowROC);
1492  int dColInChip = pIndexConverter->DColumn(colROC); //get ROC dcol from ROC col
1493  //dcol in mod
1494  int dColInDet = pIndexConverter->DColumnInModule(dColInChip,chipIndex);
1495 
1496  //float rand = RandFlat::shoot();
1497  float rand = CLHEP::RandFlat::shoot(engine);
1498  if( chips[chipIndex]==0 || columns[dColInDet]==0
1499  || rand>pixelEfficiency ) {
1500  // make pixel amplitude =0, pixel will be lost at clusterization
1501  i->second.set(0.); // reset amplitude,
1502  } // end if
1503 
1504  } // end pixel loop
1505 } // end pixel_indefficiency
1506 
1507 //***************************************************************************************
1508 // Simulate pixel aging with an exponential function
1509 //**************************************************************************************
1510 
1512  const PixelGeomDetUnit *pixdet,
1513  const TrackerTopology *tTopo) const {
1514 
1515  uint32_t detID= pixdet->geographicalId().rawId();
1516 
1517 
1518  // Predefined damage parameter (no aging)
1519  float pseudoRadDamage = 0.0;
1520 
1521  // setup the chip indices conversion
1522  unsigned int Subid=DetId(detID).subdetId();
1523  if (Subid== PixelSubdetector::PixelBarrel){// barrel layers
1524  int layerIndex=tTopo->pxbLayer(detID);
1525 
1526  pseudoRadDamage = aging.thePixelPseudoRadDamage[layerIndex-1];
1527 
1528  // std::cout << "pixel_aging: " << std::endl;
1529  // std::cout << "Subid " << Subid << " layerIndex " << layerIndex << " ladder " << tTopo->pxbLadder(detID) << " module " << tTopo->pxbModule(detID) << std::endl;
1530 
1531  } else { // forward disks
1532  unsigned int diskIndex=tTopo->pxfDisk(detID)+aging.FPixIndex; // Use diskIndex-1 later to stay consistent with BPix
1533 
1534  pseudoRadDamage = aging.thePixelPseudoRadDamage[diskIndex-1];
1535 
1536  // std::cout << "pixel_aging: " << std::endl;
1537  // std::cout << "Subid " << Subid << " diskIndex " << diskIndex << std::endl;
1538 
1539  } // if barrel/forward
1540 
1541  // std::cout << " pseudoRadDamage " << pseudoRadDamage << std::endl;
1542  // std::cout << " end pixel_aging " << std::endl;
1543 
1544  return pseudoRadDamage;
1545 #ifdef TP_DEBUG
1546  LogDebug ("Pixel Digitizer") << " enter pixel_aging " << pseudoRadDamage;
1547 #endif
1548 
1549 }
1550 
1551 //***********************************************************************
1552 
1553 // Fluctuate the gain and offset for the amplitude calibration
1554 // Use gaussian smearing.
1555 //float SiPixelDigitizerAlgorithm::missCalibrate(const float amp) const {
1556  //float gain = RandGaussQ::shoot(1.,theGainSmearing);
1557  //float offset = RandGaussQ::shoot(0.,theOffsetSmearing);
1558  //float newAmp = amp * gain + offset;
1559  // More complex misscalibration
1560 float SiPixelDigitizerAlgorithm::missCalibrate(uint32_t detID, int col,int row,
1561  const float signalInElectrons) const {
1562  // Central values
1563  //const float p0=0.00352, p1=0.868, p2=112., p3=113.; // pix(0,0,0)
1564  // const float p0=0.00382, p1=0.886, p2=112.7, p3=113.0; // average roc=0
1565  //const float p0=0.00492, p1=1.998, p2=90.6, p3=134.1; // average roc=6
1566  // Smeared (rms)
1567  //const float s0=0.00020, s1=0.051, s2=5.4, s3=4.4; // average roc=0
1568  //const float s0=0.00015, s1=0.043, s2=3.2, s3=3.1; // col average roc=0
1569 
1570  // Make 2 sets of parameters for Fpix and BPIx:
1571 
1572  float p0=0.0;
1573  float p1=0.0;
1574  float p2=0.0;
1575  float p3=0.0;
1576 
1577  unsigned int Sub_detid=DetId(detID).subdetId();
1578 
1579  if(Sub_detid == PixelSubdetector::PixelBarrel){// barrel layers
1580  p0 = BPix_p0;
1581  p1 = BPix_p1;
1582  p2 = BPix_p2;
1583  p3 = BPix_p3;
1584  } else {// forward disks
1585  p0 = FPix_p0;
1586  p1 = FPix_p1;
1587  p2 = FPix_p2;
1588  p3 = FPix_p3;
1589  }
1590 
1591  // const float electronsPerVCAL = 65.5; // our present VCAL calibration (feb 2009)
1592  // const float electronsPerVCAL_Offset = -414.0; // our present VCAL calibration (feb 2009)
1593  float newAmp = 0.; //Modified signal
1594 
1595  // Convert electrons to VCAL units
1596  float signal = (signalInElectrons-electronsPerVCAL_Offset)/electronsPerVCAL;
1597 
1598  // Simulate the analog response with fixed parametrization
1599  newAmp = p3 + p2 * tanh(p0*signal - p1);
1600 
1601 
1602  // Use the pixel-by-pixel calibrations
1603  //transform to ROC index coordinates
1604  //int chipIndex=0, colROC=0, rowROC=0;
1605  //std::auto_ptr<PixelIndices> pIndexConverter(new PixelIndices(numColumns,numRows));
1606  //pIndexConverter->transformToROC(col,row,chipIndex,colROC,rowROC);
1607 
1608  // Use calibration from a file
1609  //int chanROC = PixelIndices::pixelToChannelROC(rowROC,colROC); // use ROC coordinates
1610  //float pp0=0, pp1=0,pp2=0,pp3=0;
1611  //map<int,CalParameters,std::less<int> >::const_iterator it=calmap.find(chanROC);
1612  //CalParameters y = (*it).second;
1613  //pp0 = y.p0;
1614  //pp1 = y.p1;
1615  //pp2 = y.p2;
1616  //pp3 = y.p3;
1617 
1618  //
1619  // Use random smearing
1620  // Randomize the pixel response
1621  //float pp0 = RandGaussQ::shoot(p0,s0);
1622  //float pp1 = RandGaussQ::shoot(p1,s1);
1623  //float pp2 = RandGaussQ::shoot(p2,s2);
1624  //float pp3 = RandGaussQ::shoot(p3,s3);
1625 
1626  //newAmp = pp3 + pp2 * tanh(pp0*signal - pp1); // Final signal
1627 
1628  //cout<<" misscalibrate "<<col<<" "<<row<<" "<<chipIndex<<" "<<colROC<<" "
1629  // <<rowROC<<" "<<signalInElectrons<<" "<<signal<<" "<<newAmp<<" "
1630  // <<(signalInElectrons/theElectronPerADC)<<std::endl;
1631 
1632  return newAmp;
1633 }
1634 //******************************************************************************
1635 
1636 // Set the drift direction accoring to the Bfield in local det-unit frame
1637 // Works for both barrel and forward pixels.
1638 // Replace the sign convention to fit M.Swartz's formulaes.
1639 // Configurations for barrel and foward pixels possess different tanLorentzAngleperTesla
1640 // parameter value
1641 
1643  const GlobalVector& bfield,
1644  const DetId& detId) const {
1645  Frame detFrame(pixdet->surface().position(),pixdet->surface().rotation());
1646  LocalVector Bfield=detFrame.toLocal(bfield);
1647 
1648  float alpha2_FPix;
1649  float alpha2_BPix;
1650  float alpha2;
1651 
1652  //float dir_x = -tanLorentzAnglePerTesla * Bfield.y();
1653  //float dir_y = +tanLorentzAnglePerTesla * Bfield.x();
1654  //float dir_z = -1.; // E field always in z direction, so electrons go to -z
1655  // The dir_z has to be +/- 1. !
1656  // LocalVector theDriftDirection = LocalVector(dir_x,dir_y,dir_z);
1657 
1658  float dir_x = 0.0;
1659  float dir_y = 0.0;
1660  float dir_z = 0.0;
1661  float scale = 0.0;
1662 
1663  uint32_t detID= pixdet->geographicalId().rawId();
1664 
1665  unsigned int Sub_detid=DetId(detID).subdetId();
1666 
1667  // Read Lorentz angle from cfg file:**************************************************************
1668 
1669  if(!use_LorentzAngle_DB_){
1670 
1671  if( alpha2Order) {
1674  }else {
1675  alpha2_FPix = 0.0;
1676  alpha2_BPix = 0.0;
1677  }
1678 
1679  if(Sub_detid == PixelSubdetector::PixelBarrel){// barrel layers
1680  dir_x = -( tanLorentzAnglePerTesla_BPix * Bfield.y() + alpha2_BPix* Bfield.z()* Bfield.x() );
1681  dir_y = +( tanLorentzAnglePerTesla_BPix * Bfield.x() - alpha2_BPix* Bfield.z()* Bfield.y() );
1682  dir_z = -(1 + alpha2_BPix* Bfield.z()*Bfield.z() );
1683  scale = -dir_z;
1684  } else {// forward disks
1685  dir_x = -( tanLorentzAnglePerTesla_FPix * Bfield.y() + alpha2_FPix* Bfield.z()* Bfield.x() );
1686  dir_y = +( tanLorentzAnglePerTesla_FPix * Bfield.x() - alpha2_FPix* Bfield.z()* Bfield.y() );
1687  dir_z = -(1 + alpha2_FPix* Bfield.z()*Bfield.z() );
1688  scale = -dir_z;
1689  }
1690  } // end: Read LA from cfg file.
1691 
1692  //Read Lorentz angle from DB:********************************************************************
1694  float lorentzAngle = SiPixelLorentzAngle_->getLorentzAngle(detId);
1695  alpha2 = lorentzAngle * lorentzAngle;
1696  //std::cout << "detID is: "<< it->first <<"The LA per tesla is: "<< it->second << std::std::endl;
1697  dir_x = -( lorentzAngle * Bfield.y() + alpha2 * Bfield.z()* Bfield.x() );
1698  dir_y = +( lorentzAngle * Bfield.x() - alpha2 * Bfield.z()* Bfield.y() );
1699  dir_z = -(1 + alpha2 * Bfield.z()*Bfield.z() );
1700  scale = -dir_z;
1701  }// end: Read LA from DataBase.
1702 
1703  LocalVector theDriftDirection = LocalVector(dir_x/scale, dir_y/scale, dir_z/scale );
1704 
1705 #ifdef TP_DEBUG
1706  LogDebug ("Pixel Digitizer") << " The drift direction in local coordinate is "
1707  << theDriftDirection ;
1708 #endif
1709 
1710  return theDriftDirection;
1711 }
1712 
1713 //****************************************************************************************************
1714 
1716 
1717  signal_map_type& theSignal = _signal[detID];
1718 
1719  // Loop over hit pixels, amplitude in electrons, channel = coded row,col
1720  for(signal_map_iterator i = theSignal.begin();i != theSignal.end(); ++i) {
1721 
1722  // int chan = i->first;
1723  std::pair<int,int> ip = PixelDigi::channelToPixel(i->first);//get pixel pos
1724  int row = ip.first; // X in row
1725  int col = ip.second; // Y is in col
1726  //transform to ROC index coordinates
1727  if(theSiPixelGainCalibrationService_->isDead(detID, col, row)){
1728  // std::cout << "now in isdead check, row " << detID << " " << col << "," << row << std::std::endl;
1729  // make pixel amplitude =0, pixel will be lost at clusterization
1730  i->second.set(0.); // reset amplitude,
1731  } // end if
1732  } // end pixel loop
1733 } // end pixel_indefficiency
1734 
1735 
1736 //****************************************************************************************************
1737 
1739 
1740  bool isbad=false;
1741 
1742  Parameters::const_iterator itDeadModules=DeadModules.begin();
1743 
1744  int detid = detID;
1745  for(; itDeadModules != DeadModules.end(); ++itDeadModules){
1746  int Dead_detID = itDeadModules->getParameter<int>("Dead_detID");
1747  if(detid == Dead_detID){
1748  isbad=true;
1749  break;
1750  }
1751  }
1752 
1753  if(!isbad)
1754  return;
1755 
1756  signal_map_type& theSignal = _signal[detID];
1757 
1758  std::string Module = itDeadModules->getParameter<std::string>("Module");
1759 
1760  if(Module=="whole"){
1761  for(signal_map_iterator i = theSignal.begin();i != theSignal.end(); ++i) {
1762  i->second.set(0.); // reset amplitude
1763  }
1764  }
1765 
1766  for(signal_map_iterator i = theSignal.begin();i != theSignal.end(); ++i) {
1767  std::pair<int,int> ip = PixelDigi::channelToPixel(i->first);//get pixel pos
1768 
1769  if(Module=="tbmA" && ip.first>=80 && ip.first<=159){
1770  i->second.set(0.);
1771  }
1772 
1773  if( Module=="tbmB" && ip.first<=79){
1774  i->second.set(0.);
1775  }
1776  }
1777 }
1778 //****************************************************************************************************
1780 // Not SLHC safe for now
1781 
1782  bool isbad=false;
1783 
1784  std::vector<SiPixelQuality::disabledModuleType>disabledModules = SiPixelBadModule_->getBadComponentList();
1785 
1787 
1788  for (size_t id=0;id<disabledModules.size();id++)
1789  {
1790  if(detID==disabledModules[id].DetID){
1791  isbad=true;
1792  badmodule = disabledModules[id];
1793  break;
1794  }
1795  }
1796 
1797  if(!isbad)
1798  return;
1799 
1800  signal_map_type& theSignal = _signal[detID];
1801 
1802  //std::cout<<"Hit in: "<< detID <<" errorType "<< badmodule.errorType<<" BadRocs="<<std::hex<<SiPixelBadModule_->getBadRocs(detID)<<dec<<" "<<std::endl;
1803  if(badmodule.errorType == 0){ // this is a whole dead module.
1804 
1805  for(signal_map_iterator i = theSignal.begin();i != theSignal.end(); ++i) {
1806  i->second.set(0.); // reset amplitude
1807  }
1808  }
1809  else { // all other module types: half-modules and single ROCs.
1810  // Get Bad ROC position:
1811  //follow the example of getBadRocPositions in CondFormats/SiPixelObjects/src/SiPixelQuality.cc
1812  std::vector<GlobalPixel> badrocpositions (0);
1813  for(unsigned int j = 0; j < 16; j++){
1814  if(SiPixelBadModule_->IsRocBad(detID, j) == true){
1815 
1816  std::vector<CablingPathToDetUnit> path = map_.product()->pathToDetUnit(detID);
1817  typedef std::vector<CablingPathToDetUnit>::const_iterator IT;
1818  for (IT it = path.begin(); it != path.end(); ++it) {
1819  const PixelROC* myroc = map_.product()->findItem(*it);
1820  if( myroc->idInDetUnit() == j) {
1821  LocalPixel::RocRowCol local = { 39, 25}; //corresponding to center of ROC row, col
1822  GlobalPixel global = myroc->toGlobal( LocalPixel(local) );
1823  badrocpositions.push_back(global);
1824  break;
1825  }
1826  }
1827  }
1828  }// end of getBadRocPositions
1829 
1830 
1831  for(signal_map_iterator i = theSignal.begin();i != theSignal.end(); ++i) {
1832  std::pair<int,int> ip = PixelDigi::channelToPixel(i->first);//get pixel pos
1833 
1834  for(std::vector<GlobalPixel>::const_iterator it = badrocpositions.begin(); it != badrocpositions.end(); ++it){
1835  if(it->row >= 80 && ip.first >= 80 ){
1836  if((fabs(ip.second - it->col) < 26) ) {i->second.set(0.);}
1837  else if(it->row==120 && ip.second-it->col==26){i->second.set(0.);}
1838  else if(it->row==119 && it->col-ip.second==26){i->second.set(0.);}
1839  }
1840  else if(it->row < 80 && ip.first < 80 ){
1841  if((fabs(ip.second - it->col) < 26) ){i->second.set(0.);}
1842  else if(it->row==40 && ip.second-it->col==26){i->second.set(0.);}
1843  else if(it->row==39 && it->col-ip.second==26){i->second.set(0.);}
1844  }
1845  }
1846  }
1847  }
1848 }
1849 
int adc(sample_type sample)
get the ADC sample (12 bits)
#define LogDebug(id)
void init(const edm::EventSetup &es)
GlobalPoint toGlobal(const Point2DBase< Scalar, LocalTag > lp) const
Definition: Surface.h:114
T getParameter(std::string const &) const
int i
Definition: DBlmapReader.cc:9
void pixel_inefficiency_db(uint32_t detID)
signal_map_type::const_iterator signal_map_const_iterator
Local3DVector LocalVector
Definition: LocalVector.h:12
float tof() const
deprecated name for timeOfFlight()
Definition: PSimHit.h:72
edm::ESHandle< SiPixelFedCablingMap > map_
T y() const
Definition: PV2DBase.h:46
std::map< int, CalParameters, std::less< int > > initCal() const
std::map< unsigned int, std::vector< float >, std::less< unsigned int > > simlink_map
const std::unique_ptr< SiPixelGainCalibrationOfflineSimService > theSiPixelGainCalibrationService_
virtual LocalPoint localPosition(const MeasurementPoint &) const =0
LocalVector DriftDirection(const PixelGeomDetUnit *pixdet, const GlobalVector &bfield, const DetId &detId) const
SiPixelDigitizerAlgorithm(const edm::ParameterSet &conf)
virtual int ncolumns() const =0
const std::vector< float > & getMix_TrueInteractions() const
const std::unique_ptr< SiG4UniversalFluctuation > fluctuate
PixelEfficiencies(const edm::ParameterSet &conf, bool AddPixelInefficiency, int NumberOfBarrelLayers, int NumberOfEndcapDisks)
T mag() const
The vector magnitude. Equivalent to sqrt(vec.mag2())
unsigned int pxfDisk(const DetId &id) const
const std::vector< int > & getMix_bunchCrossing() const
float missCalibrate(uint32_t detID, int col, int row, float amp) const
unsigned int pxbLadder(const DetId &id) const
T y() const
Definition: PV3DBase.h:63
virtual int nrows() const =0
const Bounds & bounds() const
Definition: Surface.h:128
unsigned int pxbModule(const DetId &id) const
#define Module(md)
Definition: vmac.h:201
int ii
Definition: cuy.py:588
const Plane & surface() const
The nominal surface of the GeomDet.
Definition: GeomDet.h:40
identify pixel inside single ROC
Definition: LocalPixel.h:7
static int pixelToChannel(int row, int col)
Definition: PixelDigi.h:68
global coordinates (row and column in DetUnit, as in PixelDigi)
Definition: GlobalPixel.h:6
uint32_t rawId() const
get the raw id
Definition: DetId.h:43
virtual float thickness() const =0
void induce_signal(const PSimHit &hit, const size_t hitIndex, const unsigned int tofBin, const PixelGeomDetUnit *pixdet, const std::vector< SignalPoint > &collection_points)
Measurement2DPoint MeasurementPoint
Measurement points are two-dimensional by default.
Local3DPoint exitPoint() const
Exit point in the local Det frame.
Definition: PSimHit.h:38
T mag() const
Definition: PV3DBase.h:67
tuple path
else: Piece not in the list, fine.
const std::map< int, CalParameters, std::less< int > > calmap
float pixel_aging(const PixelAging &aging, const PixelGeomDetUnit *pixdet, const TrackerTopology *tTopo) const
T sqrt(T t)
Definition: SSEVec.h:48
T z() const
Definition: PV3DBase.h:64
static int pixelToChannelROC(const int rowROC, const int colROC)
Definition: PixelIndices.h:250
static std::pair< int, int > channelToPixelROC(const int chan)
Definition: PixelIndices.h:253
unsigned int idInDetUnit() const
id of this ROC in DetUnit etermined by token path
Definition: PixelROC.h:39
void digitize(const PixelGeomDetUnit *pixdet, std::vector< PixelDigi > &digis, std::vector< PixelDigiSimLink > &simlinks, const TrackerTopology *tTopo, CLHEP::HepRandomEngine *)
Abs< T >::type abs(const T &t)
Definition: Abs.h:22
int j
Definition: DBlmapReader.cc:9
virtual int channel(const LocalPoint &p) const =0
DetId geographicalId() const
The label of this GeomDet.
Definition: GeomDet.h:77
virtual MeasurementPoint measurementPosition(const LocalPoint &) const =0
T min(T a, T b)
Definition: MathUtil.h:58
std::vector< LinkConnSpec >::const_iterator IT
float pabs() const
fast and more accurate access to momentumAtEntry().mag()
Definition: PSimHit.h:63
signal_map_type::iterator signal_map_iterator
int subdetId() const
get the contents of the subdetector field (not cast into any detector&#39;s numbering enum) ...
Definition: DetId.h:37
double p2[4]
Definition: TauolaWrapper.h:90
edm::ESHandle< SiPixelLorentzAngle > SiPixelLorentzAngle_
tuple conf
Definition: dbtoconf.py:185
unsigned int pxfModule(const DetId &id) const
tuple par0
Definition: fitWZ.py:51
virtual std::pair< float, float > pitch() const =0
void fluctuateEloss(int particleId, float momentum, float eloss, float length, int NumberOfSegments, float elossVector[], CLHEP::HepRandomEngine *) const
unsigned int pxbLayer(const DetId &id) const
const std::unique_ptr< GaussianTailNoiseGenerator > theNoiser
Definition: DetId.h:18
std::map< int, Amplitude, std::less< int > > signal_map_type
void make_digis(float thePixelThresholdInE, uint32_t detID, std::vector< PixelDigi > &digis, std::vector< PixelDigiSimLink > &simlinks, const TrackerTopology *tTopo) const
const PixelEfficiencies pixelEfficiencies_
edm::ESHandle< SiPixelQuality > SiPixelBadModule_
void primary_ionization(const PSimHit &hit, std::vector< EnergyDepositUnit > &ionization_points, CLHEP::HepRandomEngine *) const
void calculateInstlumiFactor(PileupMixingContent *puInfo)
const T & get() const
Definition: EventSetup.h:55
static std::pair< int, int > channelToPixel(int ch)
Definition: PixelDigi.h:62
tuple pid
Definition: sysUtil.py:22
virtual const PixelTopology & specificTopology() const
Returns a reference to the pixel proxy topology.
T const * product() const
Definition: ESHandle.h:86
void accumulateSimHits(const std::vector< PSimHit >::const_iterator inputBegin, const std::vector< PSimHit >::const_iterator inputEnd, const size_t inputBeginGlobalIndex, const unsigned int tofBin, const PixelGeomDetUnit *pixdet, const GlobalVector &bfield, const TrackerTopology *tTopo, CLHEP::HepRandomEngine *)
row and collumn in ROC representation
Definition: LocalPixel.h:15
std::vector< edm::ParameterSet > Parameters
float energyLoss() const
The energy deposit in the PSimHit, in ???.
Definition: PSimHit.h:75
int particleType() const
Definition: PSimHit.h:85
double p1[4]
Definition: TauolaWrapper.h:89
tuple filename
Definition: lut2db_cfg.py:20
Signal rand(Signal arg)
Definition: vlib.cc:442
Local3DPoint LocalPoint
Definition: LocalPoint.h:11
const int & getMix_bunchSpacing() const
const RotationType & rotation() const
tuple cout
Definition: gather_cfg.py:121
PixelAging(const edm::ParameterSet &conf, bool AddPixelAging, int NumberOfBarrelLayers, int NumberOfEndcapDisks)
Definition: DDAxes.h:10
void drift(const PSimHit &hit, const PixelGeomDetUnit *pixdet, const GlobalVector &bfield, const TrackerTopology *tTopo, const std::vector< EnergyDepositUnit > &ionization_points, std::vector< SignalPoint > &collection_points) const
int col
Definition: cuy.py:1008
T x() const
Definition: PV2DBase.h:45
T x() const
Definition: PV3DBase.h:62
const PositionType & position() const
Definition: vlib.h:208
Local3DPoint entryPoint() const
Entry point in the local Det frame.
Definition: PSimHit.h:35
tuple size
Write out results.
unsigned int pxfPanel(const DetId &id) const
*vegas h *****************************************************used in the default bin number in original ***version of VEGAS is ***a higher bin number might help to derive a more precise ***grade subtle point
Definition: invegas.h:5
unsigned int detUnitId() const
Definition: PSimHit.h:93
const Plane & specificSurface() const
Same as surface(), kept for backward compatibility.
Definition: GeomDet.h:43
GlobalPixel toGlobal(const LocalPixel &loc) const
Definition: PixelROC.h:58
void add_noise(const PixelGeomDetUnit *pixdet, float thePixelThreshold, CLHEP::HepRandomEngine *)
double p3[4]
Definition: TauolaWrapper.h:91
void pixel_inefficiency(const PixelEfficiencies &eff, const PixelGeomDetUnit *pixdet, const TrackerTopology *tTopo, CLHEP::HepRandomEngine *)