CMS 3D CMS Logo

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 // February, 2018: Implement cluster charge reweighting (P. Schuetze, with code from A. Hazi)
43 #include <iostream>
44 #include <iomanip>
45 
47 
53 
54 #include <gsl/gsl_sf_erf.h>
56 #include "CLHEP/Random/RandGaussQ.h"
57 #include "CLHEP/Random/RandFlat.h"
58 #include "CLHEP/Random/RandGeneral.h"
59 
60 //#include "PixelIndices.h"
64 
70 
71 // Accessing dead pixel modules from the DB:
73 
75 
83 
97 
104 
105 // Geometry
109 
111 
112 using namespace edm;
113 using namespace sipixelobjects;
114 
115 
117  if(use_ineff_from_db_){// load gain calibration service fromdb...
118  theSiPixelGainCalibrationService_->setESObjects( es );
119  }
120  if(use_deadmodule_DB_) {
121  es.get<SiPixelQualityRcd>().get(SiPixelBadModule_);
122  }
123  if(use_LorentzAngle_DB_) {
124  // Get Lorentz angle from DB record
125  es.get<SiPixelLorentzAngleSimRcd>().get(SiPixelLorentzAngle_);
126  }
127  //gets the map and geometry from the DB (to kill ROCs)
128  es.get<SiPixelFedCablingMapRcd>().get(map_);
129  es.get<TrackerDigiGeometryRecord>().get(geom_);
130 
131  if (KillBadFEDChannels){
132  es.get<SiPixelStatusScenarioProbabilityRcd>().get(scenarioProbabilityHandle);
133  es.get<SiPixelFEDChannelContainerESProducerRcd>().get(PixelFEDChannelCollectionMapHandle);
134  quality_map = PixelFEDChannelCollectionMapHandle.product();
135  }
136 
137  // Read template files for charge reweighting
138  if (UseReweighting){
140  es.get<SiPixel2DTemplateDBObjectRcd>().get("denominator",SiPixel2DTemp_den);
141  dbobject_den = SiPixel2DTemp_den.product();
142 
144  es.get<SiPixel2DTemplateDBObjectRcd>().get("numerator",SiPixel2DTemp_num);
145  dbobject_num = SiPixel2DTemp_num.product();
146 
147  int numOfTemplates = dbobject_den->numOfTempl()+dbobject_num->numOfTempl();
148  templateStores_.reserve(numOfTemplates);
149  SiPixelTemplate2D::pushfile(*dbobject_den, templateStores_);
150  SiPixelTemplate2D::pushfile(*dbobject_num, templateStores_);
151 
152  track.resize(6);
153  }
154 }
155 
156 //=========================================================================
157 
159 
160  _signal(),
161  makeDigiSimLinks_(conf.getUntrackedParameter<bool>("makeDigiSimLinks", true)),
162  use_ineff_from_db_(conf.getParameter<bool>("useDB")),
163  use_module_killing_(conf.getParameter<bool>("killModules")), // boolean to kill or not modules
164  use_deadmodule_DB_(conf.getParameter<bool>("DeadModules_DB")), // boolean to access dead modules from DB
165  use_LorentzAngle_DB_(conf.getParameter<bool>("LorentzAngle_DB")), // boolean to access Lorentz angle from DB
166 
167  DeadModules(use_deadmodule_DB_ ? Parameters() : conf.getParameter<Parameters>("DeadModules")), // get dead module from cfg file
168 
169  templ2D(templateStores_),
170  xdouble(TXSIZE),
171  ydouble(TYSIZE),
172  IDnum(conf.exists("TemplateIDnumerator")?conf.getParameter<int>("TemplateIDnumerator"):0),
173  IDden(conf.exists("TemplateIDdenominator")?conf.getParameter<int>("TemplateIDdenominator"):0),
174 
175  // Common pixel parameters
176  // These are parameters which are not likely to be changed
177  GeVperElectron(3.61E-09), // 1 electron(3.61eV, 1keV(277e, mod 9/06 d.k.
178  Sigma0(0.00037), // Charge diffusion constant 7->3.7
179  Dist300(0.0300), // normalized to 300micron Silicon
180  alpha2Order(conf.getParameter<bool>("Alpha2Order")), // switch on/off of E.B effect
181  ClusterWidth(3.), // Charge integration spread on the collection plane
182 
183  // get external parameters:
184  // To account for upgrade geometries do not assume the number
185  // of layers or disks.
186  NumberOfBarrelLayers(conf.exists("NumPixelBarrel")?conf.getParameter<int>("NumPixelBarrel"):3),
187  NumberOfEndcapDisks(conf.exists("NumPixelEndcap")?conf.getParameter<int>("NumPixelEndcap"):2),
188 
189  // ADC calibration 1adc count(135e.
190  // Corresponds to 2adc/kev, 270[e/kev]/135[e/adc](2[adc/kev]
191  // Be carefull, this parameter is also used in SiPixelDet.cc to
192  // calculate the noise in adc counts from noise in electrons.
193  // Both defaults should be the same.
194  theElectronPerADC(conf.getParameter<double>("ElectronPerAdc")),
195 
196  // ADC saturation value, 255(8bit adc.
197  //theAdcFullScale(conf.getUntrackedParameter<int>("AdcFullScale",255)),
198  theAdcFullScale(conf.getParameter<int>("AdcFullScale")),
199 
200  // Noise in electrons:
201  // Pixel cell noise, relevant for generating noisy pixels
202  theNoiseInElectrons(conf.getParameter<double>("NoiseInElectrons")),
203 
204  // Fill readout noise, including all readout chain, relevant for smearing
205  //theReadoutNoise(conf.getUntrackedParameter<double>("ReadoutNoiseInElec",500.)),
206  theReadoutNoise(conf.getParameter<double>("ReadoutNoiseInElec")),
207 
208  // Pixel threshold in units of noise:
209  // thePixelThreshold(conf.getParameter<double>("ThresholdInNoiseUnits")),
210  // Pixel threshold in electron units.
211  theThresholdInE_FPix(conf.getParameter<double>("ThresholdInElectrons_FPix")),
212  theThresholdInE_BPix(conf.getParameter<double>("ThresholdInElectrons_BPix")),
213  theThresholdInE_BPix_L1(conf.exists("ThresholdInElectrons_BPix_L1")?conf.getParameter<double>("ThresholdInElectrons_BPix_L1"):theThresholdInE_BPix),
214  theThresholdInE_BPix_L2(conf.exists("ThresholdInElectrons_BPix_L2")?conf.getParameter<double>("ThresholdInElectrons_BPix_L2"):theThresholdInE_BPix),
215 
216  // Add threshold gaussian smearing:
217  theThresholdSmearing_FPix(conf.getParameter<double>("ThresholdSmearing_FPix")),
218  theThresholdSmearing_BPix(conf.getParameter<double>("ThresholdSmearing_BPix")),
219  theThresholdSmearing_BPix_L1(conf.exists("ThresholdSmearing_BPix_L1")?conf.getParameter<double>("ThresholdSmearing_BPix_L1"):theThresholdSmearing_BPix),
220  theThresholdSmearing_BPix_L2(conf.exists("ThresholdSmearing_BPix_L2")?conf.getParameter<double>("ThresholdSmearing_BPix_L2"):theThresholdSmearing_BPix),
221 
222  // electrons to VCAL conversion needed in misscalibrate()
223  electronsPerVCAL(conf.getParameter<double>("ElectronsPerVcal")),
224  electronsPerVCAL_Offset(conf.getParameter<double>("ElectronsPerVcal_Offset")),
225  electronsPerVCAL_L1(conf.exists("ElectronsPerVcal_L1")?conf.getParameter<double>("ElectronsPerVcal_L1"):electronsPerVCAL),
226  electronsPerVCAL_L1_Offset(conf.exists("ElectronsPerVcal_L1_Offset")?conf.getParameter<double>("ElectronsPerVcal_L1_Offset"):electronsPerVCAL_Offset),
227 
228  //theTofCut 12.5, cut in particle TOD +/- 12.5ns
229  //theTofCut(conf.getUntrackedParameter<double>("TofCut",12.5)),
230  theTofLowerCut(conf.getParameter<double>("TofLowerCut")),
231  theTofUpperCut(conf.getParameter<double>("TofUpperCut")),
232 
233  // Get the Lorentz angle from the cfg file:
234  tanLorentzAnglePerTesla_FPix(use_LorentzAngle_DB_ ? 0.0 : conf.getParameter<double>("TanLorentzAnglePerTesla_FPix")),
235  tanLorentzAnglePerTesla_BPix(use_LorentzAngle_DB_ ? 0.0 : conf.getParameter<double>("TanLorentzAnglePerTesla_BPix")),
236 
237  // signal response new parameterization: split Fpix and BPix
238  FPix_p0(conf.getParameter<double>("FPix_SignalResponse_p0")),
239  FPix_p1(conf.getParameter<double>("FPix_SignalResponse_p1")),
240  FPix_p2(conf.getParameter<double>("FPix_SignalResponse_p2")),
241  FPix_p3(conf.getParameter<double>("FPix_SignalResponse_p3")),
242 
243  BPix_p0(conf.getParameter<double>("BPix_SignalResponse_p0")),
244  BPix_p1(conf.getParameter<double>("BPix_SignalResponse_p1")),
245  BPix_p2(conf.getParameter<double>("BPix_SignalResponse_p2")),
246  BPix_p3(conf.getParameter<double>("BPix_SignalResponse_p3")),
247 
248  // Add noise
249  addNoise(conf.getParameter<bool>("AddNoise")),
250 
251  // Smear the pixel charge with a gaussian which RMS is a function of the
252  // pixel charge (Danek's study)
253  addChargeVCALSmearing(conf.getParameter<bool>("ChargeVCALSmearing")),
254 
255  // Add noisy pixels
256  addNoisyPixels(conf.getParameter<bool>("AddNoisyPixels")),
257 
258  // Fluctuate charge in track subsegments
259  fluctuateCharge(conf.getUntrackedParameter<bool>("FluctuateCharge",true)),
260 
261  // Control the pixel inefficiency
262  AddPixelInefficiency(conf.getParameter<bool>("AddPixelInefficiency")),
263  KillBadFEDChannels(conf.getParameter<bool>("KillBadFEDChannels")),
264 
265  // Add threshold gaussian smearing:
266  addThresholdSmearing(conf.getParameter<bool>("AddThresholdSmearing")),
267 
268  // Get the constants for the miss-calibration studies
269  doMissCalibrate(conf.getParameter<bool>("MissCalibrate")), // Enable miss-calibration
270  theGainSmearing(conf.getParameter<double>("GainSmearing")), // sigma of the gain smearing
271  theOffsetSmearing(conf.getParameter<double>("OffsetSmearing")), //sigma of the offset smearing
272 
273  // Add pixel radiation damage for upgrade studies
274  AddPixelAging(conf.getParameter<bool>("DoPixelAging")),
275  UseReweighting(conf.getParameter<bool>("UseReweighting")),
276  PrintClusters(conf.getParameter<bool>("PrintClusters")),
277  PrintTemplates(conf.getParameter<bool>("PrintTemplates")),
278 
279  // delta cutoff in MeV, has to be same as in OSCAR(0.030/cmsim=1.0 MeV
280  //tMax(0.030), // In MeV.
281  //tMax(conf.getUntrackedParameter<double>("deltaProductionCut",0.030)),
282  tMax(conf.getParameter<double>("deltaProductionCut")),
283 
284  fluctuate(fluctuateCharge ? new SiG4UniversalFluctuation() : nullptr),
285  theNoiser(addNoise ? new GaussianTailNoiseGenerator() : nullptr),
286  calmap(doMissCalibrate ? initCal() : std::map<int,CalParameters,std::less<int> >()),
287  theSiPixelGainCalibrationService_(use_ineff_from_db_ ? new SiPixelGainCalibrationOfflineSimService(conf) : nullptr),
288  pixelEfficiencies_(conf, AddPixelInefficiency,NumberOfBarrelLayers,NumberOfEndcapDisks),
289  pixelAging_(conf,AddPixelAging,NumberOfBarrelLayers,NumberOfEndcapDisks)
290 {
291  LogInfo ("PixelDigitizer ") <<"SiPixelDigitizerAlgorithm constructed"
292  <<"Configuration parameters:"
293  << "Threshold/Gain = "
294  << "threshold in electron FPix = "
296  << "threshold in electron BPix = "
298  << "threshold in electron BPix Layer1 = "
300  << "threshold in electron BPix Layer2 = "
302  <<" " << theElectronPerADC << " " << theAdcFullScale
303  << " The delta cut-off is set to " << tMax
304  << " pix-inefficiency "<<AddPixelInefficiency;
305 
306 }
307 
308 std::map<int, SiPixelDigitizerAlgorithm::CalParameters, std::less<int> >
310 
311  using std::cerr;
312  using std::cout;
313  using std::endl;
314 
315  std::map<int, SiPixelDigitizerAlgorithm::CalParameters, std::less<int> > calmap;
316  // Prepare for the analog amplitude miss-calibration
317  LogDebug ("PixelDigitizer ")
318  << " miss-calibrate the pixel amplitude ";
319 
320  const bool ReadCalParameters = false;
321  if(ReadCalParameters) { // Read the calibration files from file
322  // read the calibration constants from a file (testing only)
323  std::ifstream in_file; // data file pointer
324  char filename[80] = "phCalibrationFit_C0.dat";
325 
326  in_file.open(filename, std::ios::in ); // in C++
327  if(in_file.bad()) {
328  cout << " File not found " << endl;
329  return calmap; // signal error
330  }
331  cout << " file opened : " << filename << endl;
332 
333  char line[500];
334  for (int i = 0; i < 3; i++) {
335  in_file.getline(line, 500,'\n');
336  cout<<line<<endl;
337  }
338 
339  cout << " test map" << endl;
340 
341  float par0,par1,par2,par3;
342  int colid,rowid;
344  // Read MC tracks
345  for(int i=0;i<(52*80);i++) { // loop over tracks
346  in_file >> par0 >> par1 >> par2 >> par3 >> name >> colid >> rowid;
347  if(in_file.bad()) { // check for errors
348  cerr << "Cannot read data file" << endl;
349  return calmap;
350  }
351  if( in_file.eof() != 0 ) {
352  cerr << in_file.eof() << " " << in_file.gcount() << " "
353  << in_file.fail() << " " << in_file.good() << " end of file "
354  << endl;
355  return calmap;
356  }
357 
358  //cout << " line " << i << " " <<par0<<" "<<par1<<" "<<par2<<" "<<par3<<" "
359  // <<colid<<" "<<rowid<<endl;
360 
361  CalParameters onePix;
362  onePix.p0=par0;
363  onePix.p1=par1;
364  onePix.p2=par2;
365  onePix.p3=par3;
366 
367  // Convert ROC pixel index to channel
368  int chan = PixelIndices::pixelToChannelROC(rowid,colid);
369  calmap.insert(std::pair<int,CalParameters>(chan,onePix));
370 
371  // Testing the index conversion, can be skipped
372  std::pair<int,int> p = PixelIndices::channelToPixelROC(chan);
373  if(rowid!=p.first) cout<<" wrong channel row "<<rowid<<" "<<p.first<<endl;
374  if(colid!=p.second) cout<<" wrong channel col "<<colid<<" "<<p.second<<endl;
375 
376  } // pixel loop in a ROC
377 
378  cout << " map size " << calmap.size() <<" max "<<calmap.max_size() << " "
379  <<calmap.empty()<< endl;
380 
381 // cout << " map size " << calmap.size() << endl;
382 // map<int,CalParameters,std::less<int> >::iterator ix,it;
383 // map<int,CalParameters,std::less<int> >::const_iterator ip;
384 // for (ix = calmap.begin(); ix != calmap.end(); ++ix) {
385 // int i = (*ix).first;
386 // std::pair<int,int> p = channelToPixelROC(i);
387 // it = calmap.find(i);
388 // CalParameters y = (*it).second;
389 // CalParameters z = (*ix).second;
390 // cout << i <<" "<<p.first<<" "<<p.second<<" "<<y.p0<<" "<<z.p0<<" "<<calmap[i].p0<<endl;
391 
392 // //int dummy=0;
393 // //cin>>dummy;
394 // }
395 
396  } // end if readparameters
397  return calmap;
398 } // end initCal()
399 
400 //=========================================================================
402  LogDebug ("PixelDigitizer")<<"SiPixelDigitizerAlgorithm deleted";
403 }
404 
405 // Read DynIneff Scale factors from Configuration
407  // pixel inefficiency
408  // Don't use Hard coded values, read inefficiencies in from DB/python config or don't use any
409  int NumberOfTotLayers = NumberOfBarrelLayers + NumberOfEndcapDisks;
410  FPixIndex=NumberOfBarrelLayers;
411  if (AddPixelInefficiency){
412  FromConfig =
413  conf.exists("thePixelColEfficiency_BPix1") && conf.exists("thePixelColEfficiency_BPix2") && conf.exists("thePixelColEfficiency_BPix3") &&
414  conf.exists("thePixelColEfficiency_FPix1") && conf.exists("thePixelColEfficiency_FPix2") &&
415  conf.exists("thePixelEfficiency_BPix1") && conf.exists("thePixelEfficiency_BPix2") && conf.exists("thePixelEfficiency_BPix3") &&
416  conf.exists("thePixelEfficiency_FPix1") && conf.exists("thePixelEfficiency_FPix2") &&
417  conf.exists("thePixelChipEfficiency_BPix1") && conf.exists("thePixelChipEfficiency_BPix2") && conf.exists("thePixelChipEfficiency_BPix3") &&
418  conf.exists("thePixelChipEfficiency_FPix1") && conf.exists("thePixelChipEfficiency_FPix2");
419  if (NumberOfBarrelLayers==3) FromConfig = FromConfig && conf.exists("theLadderEfficiency_BPix1") && conf.exists("theLadderEfficiency_BPix2") && conf.exists("theLadderEfficiency_BPix3") &&
420  conf.exists("theModuleEfficiency_BPix1") && conf.exists("theModuleEfficiency_BPix2") && conf.exists("theModuleEfficiency_BPix3") &&
421  conf.exists("thePUEfficiency_BPix1") && conf.exists("thePUEfficiency_BPix2") && conf.exists("thePUEfficiency_BPix3") &&
422  conf.exists("theInnerEfficiency_FPix1") && conf.exists("theInnerEfficiency_FPix2") &&
423  conf.exists("theOuterEfficiency_FPix1") && conf.exists("theOuterEfficiency_FPix2") &&
424  conf.exists("thePUEfficiency_FPix_Inner") && conf.exists("thePUEfficiency_FPix_Outer") &&
425  conf.exists("theInstLumiScaleFactor");
426  if (NumberOfBarrelLayers>=4) FromConfig = FromConfig && conf.exists("thePixelColEfficiency_BPix4") &&
427  conf.exists("thePixelEfficiency_BPix4") && conf.exists("thePixelChipEfficiency_BPix4");
428  if (NumberOfEndcapDisks>=3) FromConfig = FromConfig && conf.exists("thePixelColEfficiency_FPix4") &&
429  conf.exists("thePixelEfficiency_FPix3") && conf.exists("thePixelChipEfficiency_FPix3");
430  if (FromConfig) {
431  LogInfo ("PixelDigitizer ") <<"The PixelDigitizer inefficiency configuration is read from the config file.\n";
432  theInstLumiScaleFactor = conf.getParameter<double>("theInstLumiScaleFactor");
433  int i=0;
434  thePixelColEfficiency[i++] = conf.getParameter<double>("thePixelColEfficiency_BPix1");
435  thePixelColEfficiency[i++] = conf.getParameter<double>("thePixelColEfficiency_BPix2");
436  thePixelColEfficiency[i++] = conf.getParameter<double>("thePixelColEfficiency_BPix3");
437  if (NumberOfBarrelLayers>=4){thePixelColEfficiency[i++] = conf.getParameter<double>("thePixelColEfficiency_BPix4");}
438  //
439  i=0;
440  thePixelEfficiency[i++] = conf.getParameter<double>("thePixelEfficiency_BPix1");
441  thePixelEfficiency[i++] = conf.getParameter<double>("thePixelEfficiency_BPix2");
442  thePixelEfficiency[i++] = conf.getParameter<double>("thePixelEfficiency_BPix3");
443  if (NumberOfBarrelLayers>=4){thePixelEfficiency[i++] = conf.getParameter<double>("thePixelEfficiency_BPix4");}
444  //
445  i=0;
446  thePixelChipEfficiency[i++] = conf.getParameter<double>("thePixelChipEfficiency_BPix1");
447  thePixelChipEfficiency[i++] = conf.getParameter<double>("thePixelChipEfficiency_BPix2");
448  thePixelChipEfficiency[i++] = conf.getParameter<double>("thePixelChipEfficiency_BPix3");
449  if (NumberOfBarrelLayers>=4){thePixelChipEfficiency[i++] = conf.getParameter<double>("thePixelChipEfficiency_BPix4");}
450  //
451  if (NumberOfBarrelLayers==3){
452  i=0;
453  theLadderEfficiency_BPix[i++] = conf.getParameter<std::vector<double> >("theLadderEfficiency_BPix1");
454  theLadderEfficiency_BPix[i++] = conf.getParameter<std::vector<double> >("theLadderEfficiency_BPix2");
455  theLadderEfficiency_BPix[i++] = conf.getParameter<std::vector<double> >("theLadderEfficiency_BPix3");
456  if ( ((theLadderEfficiency_BPix[0].size()!=20) || (theLadderEfficiency_BPix[1].size()!=32) ||
457  (theLadderEfficiency_BPix[2].size()!=44)) && (NumberOfBarrelLayers==3) )
458  throw cms::Exception("Configuration") << "Wrong ladder number in efficiency config!";
459  //
460  i=0;
461  theModuleEfficiency_BPix[i++] = conf.getParameter<std::vector<double> >("theModuleEfficiency_BPix1");
462  theModuleEfficiency_BPix[i++] = conf.getParameter<std::vector<double> >("theModuleEfficiency_BPix2");
463  theModuleEfficiency_BPix[i++] = conf.getParameter<std::vector<double> >("theModuleEfficiency_BPix3");
464  if ( ((theModuleEfficiency_BPix[0].size()!=4) || (theModuleEfficiency_BPix[1].size()!=4) ||
465  (theModuleEfficiency_BPix[2].size()!=4)) && (NumberOfBarrelLayers==3) )
466  throw cms::Exception("Configuration") << "Wrong module number in efficiency config!";
467  //
468  thePUEfficiency.push_back(conf.getParameter<std::vector<double> >("thePUEfficiency_BPix1"));
469  thePUEfficiency.push_back(conf.getParameter<std::vector<double> >("thePUEfficiency_BPix2"));
470  thePUEfficiency.push_back(conf.getParameter<std::vector<double> >("thePUEfficiency_BPix3"));
471  if ( ((thePUEfficiency[0].empty()) || (thePUEfficiency[1].empty()) ||
472  (thePUEfficiency[2].empty())) && (NumberOfBarrelLayers==3) )
473  throw cms::Exception("Configuration") << "At least one PU efficiency (BPix) number is needed in efficiency config!";
474  }
475  // The next is needed for Phase2 Tracker studies
476  if (NumberOfBarrelLayers>=5){
477  if (NumberOfTotLayers>20){throw cms::Exception("Configuration") <<"SiPixelDigitizer was given more layers than it can handle";}
478  // For Phase2 tracker layers just set the outermost BPix inefficiency to 99.9% THESE VALUES ARE HARDCODED ALSO ELSEWHERE IN THIS FILE
479  for (int j=5 ; j<=NumberOfBarrelLayers ; j++){
480  thePixelColEfficiency[j-1]=0.999;
481  thePixelEfficiency[j-1]=0.999;
482  thePixelChipEfficiency[j-1]=0.999;
483  }
484  }
485  //
486  i=FPixIndex;
487  thePixelColEfficiency[i++] = conf.getParameter<double>("thePixelColEfficiency_FPix1");
488  thePixelColEfficiency[i++] = conf.getParameter<double>("thePixelColEfficiency_FPix2");
489  if (NumberOfEndcapDisks>=3){thePixelColEfficiency[i++] = conf.getParameter<double>("thePixelColEfficiency_FPix3");}
490  i=FPixIndex;
491  thePixelEfficiency[i++] = conf.getParameter<double>("thePixelEfficiency_FPix1");
492  thePixelEfficiency[i++] = conf.getParameter<double>("thePixelEfficiency_FPix2");
493  if (NumberOfEndcapDisks>=3){thePixelEfficiency[i++] = conf.getParameter<double>("thePixelEfficiency_FPix3");}
494  i=FPixIndex;
495  thePixelChipEfficiency[i++] = conf.getParameter<double>("thePixelChipEfficiency_FPix1");
496  thePixelChipEfficiency[i++] = conf.getParameter<double>("thePixelChipEfficiency_FPix2");
497  if (NumberOfEndcapDisks>=3){thePixelChipEfficiency[i++] = conf.getParameter<double>("thePixelChipEfficiency_FPix3");}
498  // The next is needed for Phase2 Tracker studies
499  if (NumberOfEndcapDisks>=4){
500  if (NumberOfTotLayers>20){throw cms::Exception("Configuration") <<"SiPixelDigitizer was given more layers than it can handle";}
501  // For Phase2 tracker layers just set the extra FPix disk inefficiency to 99.9% THESE VALUES ARE HARDCODED ALSO ELSEWHERE IN THIS FILE
502  for (int j=4+FPixIndex ; j<=NumberOfEndcapDisks+NumberOfBarrelLayers ; j++){
503  thePixelColEfficiency[j-1]=0.999;
504  thePixelEfficiency[j-1]=0.999;
505  thePixelChipEfficiency[j-1]=0.999;
506  }
507  }
508  //FPix Dynamic Inefficiency
509  if (NumberOfBarrelLayers==3){
510  i=FPixIndex;
511  theInnerEfficiency_FPix[i++] = conf.getParameter<double>("theInnerEfficiency_FPix1");
512  theInnerEfficiency_FPix[i++] = conf.getParameter<double>("theInnerEfficiency_FPix2");
513  i=FPixIndex;
514  theOuterEfficiency_FPix[i++] = conf.getParameter<double>("theOuterEfficiency_FPix1");
515  theOuterEfficiency_FPix[i++] = conf.getParameter<double>("theOuterEfficiency_FPix2");
516  thePUEfficiency.push_back(conf.getParameter<std::vector<double> >("thePUEfficiency_FPix_Inner"));
517  thePUEfficiency.push_back(conf.getParameter<std::vector<double> >("thePUEfficiency_FPix_Outer"));
518  if ( ((thePUEfficiency[3].empty()) || (thePUEfficiency[4].empty())) && (NumberOfEndcapDisks==2) )
519  throw cms::Exception("Configuration") << "At least one (FPix) PU efficiency number is needed in efficiency config!";
520  pu_scale.resize(thePUEfficiency.size());
521  }
522  }
523  else LogInfo ("PixelDigitizer ") <<"The PixelDigitizer inefficiency configuration is read from the database.\n";
524  }
525  // the first "NumberOfBarrelLayers" settings [0],[1], ... , [NumberOfBarrelLayers-1] are for the barrel pixels
526  // the next "NumberOfEndcapDisks" settings [NumberOfBarrelLayers],[NumberOfBarrelLayers+1], ... [NumberOfEndcapDisks+NumberOfBarrelLayers-1]
527 }
528 
529 // Read DynIneff Scale factors from DB
532  if (bunchspace == 50) es.get<SiPixelDynamicInefficiencyRcd>().get("50ns",SiPixelDynamicInefficiency_);
535  }
536 }
537 
539 
540  theInstLumiScaleFactor = SiPixelDynamicInefficiency->gettheInstLumiScaleFactor();
541  const std::map<uint32_t, double>& PixelGeomFactorsDBIn = SiPixelDynamicInefficiency->getPixelGeomFactors();
542  const std::map<uint32_t, double>& ColGeomFactorsDB = SiPixelDynamicInefficiency->getColGeomFactors();
543  const std::map<uint32_t, double>& ChipGeomFactorsDB = SiPixelDynamicInefficiency->getChipGeomFactors();
544  const std::map<uint32_t, std::vector<double> >& PUFactors = SiPixelDynamicInefficiency->getPUFactors();
545  std::vector<uint32_t > DetIdmasks = SiPixelDynamicInefficiency->getDetIdmasks();
546 
547  // Loop on all modules, initialize map for easy access
548  for( const auto& it_module : geom->detUnits()) {
549  if( dynamic_cast<PixelGeomDetUnit const*>(it_module)==nullptr) continue;
550  const DetId detid = it_module->geographicalId();
551  uint32_t rawid = detid.rawId();
552  PixelGeomFactors[rawid] = 1;
553  ColGeomFactors[rawid] = 1;
554  ChipGeomFactors[rawid] = 1;
555  PixelGeomFactorsROCStdPixels[rawid] = std::vector<double>(16,1);
556  PixelGeomFactorsROCBigPixels[rawid] = std::vector<double>(16,1);
557  }
558 
559  // ROC level inefficiency for phase 1 (disentangle scale factors for big and std size pixels)
560  std::map<uint32_t, double> PixelGeomFactorsDB;
561 
564  for (auto db_factor : PixelGeomFactorsDBIn){
565  int shift = DetId(db_factor.first).subdetId() ==
566  static_cast<int>(PixelSubdetector::PixelBarrel) ? BPixRocIdShift:FPixRocIdShift;
567  unsigned int rocMask = rocIdMaskBits << shift;
568  unsigned int rocId = (((db_factor.first) & rocMask) >> shift);
569  if (rocId != 0) {
570  rocId--;
571  unsigned int rawid = db_factor.first & (~rocMask);
572  const PixelGeomDetUnit * theGeomDet = dynamic_cast<const PixelGeomDetUnit*> (geom->idToDet(rawid));
573  PixelTopology const * topology = &(theGeomDet->specificTopology());
574  const int nPixelsInROC = topology->rowsperroc()*topology->colsperroc();
575  const int nBigPixelsInROC = 2*topology->rowsperroc()+topology->colsperroc()-2;
576  double factor = db_factor.second;
577  double badFraction = 1 - factor;
578  double bigPixelFraction = static_cast<double> (nBigPixelsInROC)/nPixelsInROC;
579  double stdPixelFraction = 1. - bigPixelFraction;
580 
581  double badFractionBig = std::min(bigPixelFraction, badFraction);
582  double badFractionStd = std::max(0., badFraction - badFractionBig);
583  double badFractionBigReNormalized = badFractionBig/bigPixelFraction;
584  double badFractionStdReNormalized = badFractionStd/stdPixelFraction;
585  PixelGeomFactorsROCStdPixels[rawid][rocId] *= (1. - badFractionStdReNormalized);
586  PixelGeomFactorsROCBigPixels[rawid][rocId] *= (1. - badFractionBigReNormalized);
587  }
588  else{
589  PixelGeomFactorsDB[db_factor.first] = db_factor.second;
590  }
591  }
592  } // is Phase 1 geometry
593  else{
594  PixelGeomFactorsDB = PixelGeomFactorsDBIn;
595  }
596 
597  // Loop on all modules, store module level geometrical scale factors
598  for( const auto& it_module : geom->detUnits()) {
599  if( dynamic_cast<PixelGeomDetUnit const*>(it_module)==nullptr) continue;
600  const DetId detid = it_module->geographicalId();
601  uint32_t rawid = detid.rawId();
602  for (auto db_factor : PixelGeomFactorsDB) if (matches(detid, DetId(db_factor.first), DetIdmasks)) PixelGeomFactors[rawid] *= db_factor.second;
603  for (auto db_factor : ColGeomFactorsDB) if (matches(detid, DetId(db_factor.first), DetIdmasks)) ColGeomFactors[rawid] *= db_factor.second;
604  for (auto db_factor : ChipGeomFactorsDB) if (matches(detid, DetId(db_factor.first), DetIdmasks)) ChipGeomFactors[rawid] *= db_factor.second;
605  }
606 
607  // piluep scale factors are calculated once per event
608  // therefore vector index is stored in a map for each module that matches to a db_id
609  size_t i=0;
610  for (auto factor : PUFactors) {
611  const DetId db_id = DetId(factor.first);
612  for( const auto& it_module : geom->detUnits()) {
613  if( dynamic_cast<PixelGeomDetUnit const*>(it_module)==nullptr) continue;
614  const DetId detid = it_module->geographicalId();
615  if (!matches(detid, db_id, DetIdmasks)) continue;
616  if (iPU.count(detid.rawId())) {
617  throw cms::Exception("Database")<<"Multiple db_ids match to same module in SiPixelDynamicInefficiency DB Object";
618  } else {
619  iPU[detid.rawId()] = i;
620  }
621  }
622  thePUEfficiency.push_back(factor.second);
623  ++i;
624  }
625  pu_scale.resize(thePUEfficiency.size());
626 }
627 
628 bool SiPixelDigitizerAlgorithm::PixelEfficiencies::matches(const DetId& detid, const DetId& db_id, const std::vector<uint32_t >& DetIdmasks) {
629  if (detid.subdetId() != db_id.subdetId()) return false;
630  for (size_t i=0; i<DetIdmasks.size(); ++i) {
631  DetId maskid = DetId(DetIdmasks.at(i));
632  if (maskid.subdetId() != db_id.subdetId()) continue;
633  if ((detid.rawId()&maskid.rawId()) != (db_id.rawId()&maskid.rawId()) &&
634  (db_id.rawId()&maskid.rawId()) != DetId(db_id.det(), db_id.subdetId()).rawId()) return false;
635  }
636  return true;
637 }
638 
640  // pixel aging
641  // Don't use Hard coded values, read aging in from python or don't use any
642  if(AddAging) {
643  int NumberOfTotLayers = NumberOfBarrelLayers + NumberOfEndcapDisks;
644  FPixIndex=NumberOfBarrelLayers;
645 
646  int i=0;
647  thePixelPseudoRadDamage[i++] = conf.getParameter<double>("thePixelPseudoRadDamage_BPix1");
648  thePixelPseudoRadDamage[i++] = conf.getParameter<double>("thePixelPseudoRadDamage_BPix2");
649  thePixelPseudoRadDamage[i++] = conf.getParameter<double>("thePixelPseudoRadDamage_BPix3");
650  thePixelPseudoRadDamage[i++] = conf.getParameter<double>("thePixelPseudoRadDamage_BPix4");
651 
652  // to be removed when Gaelle will have the phase2 digitizer
653  if (NumberOfBarrelLayers>=5){
654  if (NumberOfTotLayers>20){throw cms::Exception("Configuration") <<"SiPixelDigitizer was given more layers than it can handle";}
655  // For Phase2 tracker layers just set the outermost BPix aging 0.
656  for (int j=5 ; j<=NumberOfBarrelLayers ; j++){
657  thePixelPseudoRadDamage[j-1]=0.;
658  }
659  }
660  //
661  i=FPixIndex;
662  thePixelPseudoRadDamage[i++] = conf.getParameter<double>("thePixelPseudoRadDamage_FPix1");
663  thePixelPseudoRadDamage[i++] = conf.getParameter<double>("thePixelPseudoRadDamage_FPix2");
664  thePixelPseudoRadDamage[i++] = conf.getParameter<double>("thePixelPseudoRadDamage_FPix3");
665 
666  //To be removed when Phase2 digitizer will be available
667  if (NumberOfEndcapDisks>=4){
668  if (NumberOfTotLayers>20){throw cms::Exception("Configuration") <<"SiPixelDigitizer was given more layers than it can handle";}
669  // For Phase2 tracker layers just set the extra FPix disk aging to 0. BE CAREFUL THESE VALUES ARE HARDCODED ALSO ELSEWHERE IN THIS FILE
670  for (int j=4+FPixIndex ; j<=NumberOfEndcapDisks+NumberOfBarrelLayers ; j++){
671  thePixelPseudoRadDamage[j-1]=0.;
672  }
673  }
674  }
675  // the first "NumberOfBarrelLayers" settings [0],[1], ... , [NumberOfBarrelLayers-1] are for the barrel pixels
676  // the next "NumberOfEndcapDisks" settings [NumberOfBarrelLayers],[NumberOfBarrelLayers+1], ... [NumberOfEndcapDisks+NumberOfBarrelLayers-1]
677 }
678 
679 //=========================================================================
680 void SiPixelDigitizerAlgorithm::accumulateSimHits(std::vector<PSimHit>::const_iterator inputBegin,
681  std::vector<PSimHit>::const_iterator inputEnd,
682  const size_t inputBeginGlobalIndex,
683  const unsigned int tofBin,
684  const PixelGeomDetUnit* pixdet,
685  const GlobalVector& bfield,
686  const TrackerTopology *tTopo,
687  CLHEP::HepRandomEngine* engine) {
688  // produce SignalPoint's for all SimHit's in detector
689  // Loop over hits
690 
691  uint32_t detId = pixdet->geographicalId().rawId();
692  size_t simHitGlobalIndex=inputBeginGlobalIndex; // This needs to stored to create the digi-sim link later
693  for (std::vector<PSimHit>::const_iterator ssbegin = inputBegin; ssbegin != inputEnd; ++ssbegin, ++simHitGlobalIndex) {
694  // skip hits not in this detector.
695  if((*ssbegin).detUnitId() != detId) {
696  continue;
697  }
698 
699 #ifdef TP_DEBUG
700  LogDebug ("Pixel Digitizer")
701  << (*ssbegin).particleType() << " " << (*ssbegin).pabs() << " "
702  << (*ssbegin).energyLoss() << " " << (*ssbegin).tof() << " "
703  << (*ssbegin).trackId() << " " << (*ssbegin).processType() << " "
704  << (*ssbegin).detUnitId()
705  << (*ssbegin).entryPoint() << " " << (*ssbegin).exitPoint() ;
706 #endif
707 
708 
709  std::vector<EnergyDepositUnit> ionization_points;
710  std::vector<SignalPoint> collection_points;
711 
712  // fill collection_points for this SimHit, indpendent of topology
713  // Check the TOF cut
714  if ( ((*ssbegin).tof() - pixdet->surface().toGlobal((*ssbegin).localPosition()).mag()/30.)>= theTofLowerCut &&
715  ((*ssbegin).tof()- pixdet->surface().toGlobal((*ssbegin).localPosition()).mag()/30.) <= theTofUpperCut ) {
716  primary_ionization(*ssbegin, ionization_points, engine); // fills _ionization_points
717  drift(*ssbegin, pixdet, bfield, tTopo, ionization_points, collection_points); // transforms _ionization_points to collection_points
718  // compute induced signal on readout elements and add to _signal
719  induce_signal(inputBegin, inputEnd, *ssbegin, simHitGlobalIndex, tofBin, pixdet, collection_points); // 1st 3 args needed only for SimHit<-->Digi link
720  } // end if
721  } // end for
722 
723 }
724 
725 //============================================================================
727  //Instlumi scalefactor calculating for dynamic inefficiency
728 
729  if (puInfo) {
730  const std::vector<int>& bunchCrossing = puInfo->getMix_bunchCrossing();
731  const std::vector<float>& TrueInteractionList = puInfo->getMix_TrueInteractions();
732  //const int bunchSpacing = puInfo->getMix_bunchSpacing();
733 
734  int pui = 0, p = 0;
735  std::vector<int>::const_iterator pu;
736  std::vector<int>::const_iterator pu0 = bunchCrossing.end();
737 
738  for (pu=bunchCrossing.begin(); pu!=bunchCrossing.end(); ++pu) {
739  if (*pu==0) {
740  pu0 = pu;
741  p = pui;
742  }
743  pui++;
744  }
745  if (pu0!=bunchCrossing.end()) {
746  for (size_t i=0, n = pixelEfficiencies_.thePUEfficiency.size(); i<n; i++) {
747  double instlumi = TrueInteractionList.at(p)*pixelEfficiencies_.theInstLumiScaleFactor;
748  double instlumi_pow=1.;
750  for (size_t j=0; j<pixelEfficiencies_.thePUEfficiency[i].size(); j++){
752  instlumi_pow*=instlumi;
753  }
754  }
755  }
756  }
757  else {
758  for (int i=0, n = pixelEfficiencies_.thePUEfficiency.size(); i<n; i++) {
760  }
761  }
762 }
763 
764 //============================================================================
765 void SiPixelDigitizerAlgorithm::calculateInstlumiFactor(const std::vector<PileupSummaryInfo> &ps, int bunchSpacing) {
766  int p = -1;
767  for(unsigned int i=0; i<ps.size(); i++)
768  if (ps[i].getBunchCrossing() == 0)
769  p=i;
770 
771  if(p >= 0) {
772  for (size_t i=0, n = pixelEfficiencies_.thePUEfficiency.size(); i<n; i++) {
773  double instlumi = ps[p].getTrueNumInteractions()*pixelEfficiencies_.theInstLumiScaleFactor;
774  double instlumi_pow=1.;
776  for (size_t j=0; j<pixelEfficiencies_.thePUEfficiency[i].size(); j++){
778  instlumi_pow*=instlumi;
779  }
780  }
781  }
782  else {
783  for (int i=0, n = pixelEfficiencies_.thePUEfficiency.size(); i<n; i++) {
785  }
786  }
787 }
788 
789 // ========== StuckTBMs
790 
792 
793 std::unique_ptr<PixelFEDChannelCollection> SiPixelDigitizerAlgorithm::chooseScenario(PileupMixingContent* puInfo, CLHEP::HepRandomEngine *engine){
794 
795  //Determine scenario to use for the current event based on pileup information
796 
797  std::unique_ptr<PixelFEDChannelCollection> PixelFEDChannelCollection_ = nullptr;
799  if (puInfo) {
800  const std::vector<int>& bunchCrossing = puInfo->getMix_bunchCrossing();
801  const std::vector<float>& TrueInteractionList = puInfo->getMix_TrueInteractions();
802 
803  int pui = 0, p = 0;
804  std::vector<int>::const_iterator pu;
805  std::vector<int>::const_iterator pu0 = bunchCrossing.end();
806 
807  for (pu=bunchCrossing.begin(); pu!=bunchCrossing.end(); ++pu) {
808  if (*pu==0) {
809  pu0 = pu;
810  p = pui;
811  }
812  pui++;
813  }
814 
815  if (pu0!=bunchCrossing.end()) {
816 
817  unsigned int PUBin = TrueInteractionList.at(p); // case delta PU=1, fix me
818  const auto& theProbabilitiesPerScenario = scenarioProbabilityHandle->getProbabilities(PUBin);
819  std::vector<double> probabilities;
820  probabilities.reserve(theProbabilitiesPerScenario.size());
821  for (auto it = theProbabilitiesPerScenario.begin(); it != theProbabilitiesPerScenario.end(); it++){
822  probabilities.push_back(it->second);
823  }
824 
825  CLHEP::RandGeneral randGeneral(*engine, &(probabilities.front()), probabilities.size());
826  double x = randGeneral.shoot();
827  unsigned int index = x * probabilities.size() - 1;
828  const std::string& scenario = theProbabilitiesPerScenario.at(index).first;
829 
830  PixelFEDChannelCollection_ = std::make_unique<PixelFEDChannelCollection>(quality_map->at(scenario));
831  pixelEfficiencies_.PixelFEDChannelCollection_ = std::make_unique<PixelFEDChannelCollection>(quality_map->at(scenario));
832  }
833  }
834  return PixelFEDChannelCollection_;
835 }
836 
837 //============================================================================
838 void SiPixelDigitizerAlgorithm::setSimAccumulator(const std::map<uint32_t, std::map<int, int> >& signalMap) {
839  for(const auto& det: signalMap) {
840  auto& theSignal = _signal[det.first];
841  for(const auto& chan: det.second) {
842  theSignal[chan.first].set(chan.second * theElectronPerADC); // will get divided again by theElectronPerAdc in digitize...
843  }
844  }
845 }
846 
847 //============================================================================
849  std::vector<PixelDigi>& digis,
850  std::vector<PixelDigiSimLink>& simlinks,
851  const TrackerTopology *tTopo,
852  CLHEP::HepRandomEngine* engine) {
853 
854  // Pixel Efficiency moved from the constructor to this method because
855  // the information of the det are not available in the constructor
856  // Efficiency parameters. 0 - no inefficiency, 1-low lumi, 10-high lumi
857 
858  uint32_t detID = pixdet->geographicalId().rawId();
859  const signal_map_type& theSignal = _signal[detID];
860 
861  // Noise already defined in electrons
862  // thePixelThresholdInE = thePixelThreshold * theNoiseInElectrons ;
863  // Find the threshold in noise units, needed for the noiser.
864 
865 
866  float thePixelThresholdInE = 0.;
867 
868  if(theNoiseInElectrons>0.){
869  if(pixdet->type().isTrackerPixel() && pixdet->type().isBarrel()){ // Barrel modules
870  int lay = tTopo->layer(detID);
873  if (lay==1) {
874  thePixelThresholdInE = CLHEP::RandGaussQ::shoot(engine, theThresholdInE_BPix_L1, theThresholdSmearing_BPix_L1); // gaussian smearing
875  } else if (lay==2) {
876  thePixelThresholdInE = CLHEP::RandGaussQ::shoot(engine, theThresholdInE_BPix_L2, theThresholdSmearing_BPix_L2); // gaussian smearing
877  } else {
878  thePixelThresholdInE = CLHEP::RandGaussQ::shoot(engine, theThresholdInE_BPix , theThresholdSmearing_BPix); // gaussian smearing
879  }
880  }
881  } else {
883  if (lay==1) {
884  thePixelThresholdInE = theThresholdInE_BPix_L1;
885  } else if (lay==2) {
886  thePixelThresholdInE = theThresholdInE_BPix_L2;
887  } else {
888  thePixelThresholdInE = theThresholdInE_BPix; // no smearing
889  }
890  }
891  }
892  } else if(pixdet->type().isTrackerPixel()) { // Forward disks modules
894  thePixelThresholdInE = CLHEP::RandGaussQ::shoot(engine, theThresholdInE_FPix, theThresholdSmearing_FPix); // gaussian smearing
895  } else {
896  thePixelThresholdInE = theThresholdInE_FPix; // no smearing
897  }
898  }
899  else {throw cms::Exception("NotAPixelGeomDetUnit") << "Not a pixel geomdet unit" << detID;}
900  }
901 
902 
903 #ifdef TP_DEBUG
904  const PixelTopology* topol=&pixdet->specificTopology();
905  int numColumns = topol->ncolumns(); // det module number of cols&rows
906  int numRows = topol->nrows();
907  // full detector thickness
908  float moduleThickness = pixdet->specificSurface().bounds().thickness();
909  LogDebug ("PixelDigitizer")
910  << " PixelDigitizer "
911  << numColumns << " " << numRows << " " << moduleThickness;
912 #endif
913 
914  if(addNoise) add_noise(pixdet, thePixelThresholdInE/theNoiseInElectrons, engine); // generate noise
915 
916  // Do only if needed
917 
918  if((AddPixelInefficiency) && (!theSignal.empty()))
919  pixel_inefficiency(pixelEfficiencies_, pixdet, tTopo, engine); // Kill some pixels
920 
921  if(use_ineff_from_db_ && (!theSignal.empty()))
922  pixel_inefficiency_db(detID);
923 
924  if(use_module_killing_) {
925  if (use_deadmodule_DB_) { // remove dead modules using DB
926  module_killing_DB(detID);
927  } else { // remove dead modules using the list in cfg file
928  module_killing_conf(detID);
929  }
930  }
931 
932  make_digis(thePixelThresholdInE, detID, pixdet, digis, simlinks, tTopo);
933 
934 #ifdef TP_DEBUG
935  LogDebug ("PixelDigitizer") << "[SiPixelDigitizerAlgorithm] converted " << digis.size() << " PixelDigis in DetUnit" << detID;
936 #endif
937 }
938 
939 //***********************************************************************/
940 // Generate primary ionization along the track segment.
941 // Divide the track into small sub-segments
942 void SiPixelDigitizerAlgorithm::primary_ionization(const PSimHit& hit, std::vector<EnergyDepositUnit>& ionization_points, CLHEP::HepRandomEngine* engine) const {
943 
944  // Straight line approximation for trajectory inside active media
945 
946  const float SegmentLength = 0.0010; //10microns in cm
947  float energy;
948 
949  // Get the 3D segment direction vector
950  LocalVector direction = hit.exitPoint() - hit.entryPoint();
951 
952  float eLoss = hit.energyLoss(); // Eloss in GeV
953  float length = direction.mag(); // Track length in Silicon
954 
955  int NumberOfSegments = int ( length / SegmentLength); // Number of segments
956  if(NumberOfSegments < 1) NumberOfSegments = 1;
957 
958 #ifdef TP_DEBUG
959  LogDebug ("Pixel Digitizer")
960  << " enter primary_ionzation " << NumberOfSegments
961  << " shift = "
962  << (hit.exitPoint().x()-hit.entryPoint().x()) << " "
963  << (hit.exitPoint().y()-hit.entryPoint().y()) << " "
964  << (hit.exitPoint().z()-hit.entryPoint().z()) << " "
965  << hit.particleType() <<" "<< hit.pabs() ;
966 #endif
967 
968  float* elossVector = new float[NumberOfSegments]; // Eloss vector
969 
970  if( fluctuateCharge ) {
971  //MP DA RIMUOVERE ASSOLUTAMENTE
972  int pid = hit.particleType();
973  //int pid=211; // assume it is a pion
974 
975  float momentum = hit.pabs();
976  // Generate fluctuated charge points
977  fluctuateEloss(pid, momentum, eLoss, length, NumberOfSegments,
978  elossVector, engine);
979  }
980 
981  ionization_points.resize( NumberOfSegments); // set size
982 
983  // loop over segments
984  for ( int i = 0; i != NumberOfSegments; i++) {
985  // Divide the segment into equal length subsegments
986  Local3DPoint point = hit.entryPoint() +
987  float((i+0.5)/NumberOfSegments) * direction;
988 
989  if( fluctuateCharge )
990  energy = elossVector[i]/GeVperElectron; // Convert charge to elec.
991  else
992  energy = hit.energyLoss()/GeVperElectron/float(NumberOfSegments);
993 
994  EnergyDepositUnit edu( energy, point); //define position,energy point
995  ionization_points[i] = edu; // save
996 
997 #ifdef TP_DEBUG
998  LogDebug ("Pixel Digitizer")
999  << i << " " << ionization_points[i].x() << " "
1000  << ionization_points[i].y() << " "
1001  << ionization_points[i].z() << " "
1002  << ionization_points[i].energy();
1003 #endif
1004 
1005  } // end for loop
1006 
1007  delete[] elossVector;
1008 
1009 }
1010 //******************************************************************************
1011 
1012 // Fluctuate the charge comming from a small (10um) track segment.
1013 // Use the G4 routine. For mip pions for the moment.
1014 void SiPixelDigitizerAlgorithm::fluctuateEloss(int pid, float particleMomentum,
1015  float eloss, float length,
1016  int NumberOfSegs,float elossVector[],
1017  CLHEP::HepRandomEngine* engine) const {
1018 
1019  // Get dedx for this track
1020  //float dedx;
1021  //if( length > 0.) dedx = eloss/length;
1022  //else dedx = eloss;
1023 
1024  double particleMass = 139.6; // Mass in MeV, Assume pion
1025  pid = std::abs(pid);
1026  if(pid!=211) { // Mass in MeV
1027  if(pid==11) particleMass = 0.511;
1028  else if(pid==13) particleMass = 105.7;
1029  else if(pid==321) particleMass = 493.7;
1030  else if(pid==2212) particleMass = 938.3;
1031  }
1032  // What is the track segment length.
1033  float segmentLength = length/NumberOfSegs;
1034 
1035  // Generate charge fluctuations.
1036  float de=0.;
1037  float sum=0.;
1038  double segmentEloss = (1000.*eloss)/NumberOfSegs; //eloss in MeV
1039  for (int i=0;i<NumberOfSegs;i++) {
1040  // material,*, momentum,energy,*, *, mass
1041  //myglandz_(14.,segmentLength,2.,2.,dedx,de,0.14);
1042  // The G4 routine needs momentum in MeV, mass in Mev, delta-cut in MeV,
1043  // track segment length in mm, segment eloss in MeV
1044  // Returns fluctuated eloss in MeV
1045  double deltaCutoff = tMax; // the cutoff is sometimes redefined inside, so fix it.
1046  de = fluctuate->SampleFluctuations(double(particleMomentum*1000.),
1047  particleMass, deltaCutoff,
1048  double(segmentLength*10.),
1049  segmentEloss, engine )/1000.; //convert to GeV
1050  elossVector[i]=de;
1051  sum +=de;
1052  }
1053 
1054  if(sum>0.) { // If fluctuations give eloss>0.
1055  // Rescale to the same total eloss
1056  float ratio = eloss/sum;
1057 
1058  for (int ii=0;ii<NumberOfSegs;ii++) elossVector[ii]= ratio*elossVector[ii];
1059  } else { // If fluctuations gives 0 eloss
1060  float averageEloss = eloss/NumberOfSegs;
1061  for (int ii=0;ii<NumberOfSegs;ii++) elossVector[ii]= averageEloss;
1062  }
1063  return;
1064 }
1065 
1066 //*******************************************************************************
1067 // Drift the charge segments to the sensor surface (collection plane)
1068 // Include the effect of E-field and B-field
1070  const PixelGeomDetUnit* pixdet,
1071  const GlobalVector& bfield,
1072  const TrackerTopology *tTopo,
1073  const std::vector<EnergyDepositUnit>& ionization_points,
1074  std::vector<SignalPoint>& collection_points) const {
1075 
1076 #ifdef TP_DEBUG
1077  LogDebug ("Pixel Digitizer") << " enter drift " ;
1078 #endif
1079 
1080  collection_points.resize(ionization_points.size()); // set size
1081 
1082  LocalVector driftDir=DriftDirection(pixdet, bfield, hit.detUnitId()); // get the charge drift direction
1083  if(driftDir.z() ==0.) {
1084  LogWarning("Magnetic field") << " pxlx: drift in z is zero ";
1085  return;
1086  }
1087 
1088  // tangent of Lorentz angle
1089  //float TanLorenzAngleX = driftDir.x()/driftDir.z();
1090  //float TanLorenzAngleY = 0.; // force to 0, driftDir.y()/driftDir.z();
1091 
1092  float TanLorenzAngleX, TanLorenzAngleY,dir_z, CosLorenzAngleX,
1093  CosLorenzAngleY;
1094  if( alpha2Order) {
1095  TanLorenzAngleX = driftDir.x(); // tangen of Lorentz angle
1096  TanLorenzAngleY = driftDir.y();
1097  dir_z = driftDir.z(); // The z drift direction
1098  CosLorenzAngleX = 1./sqrt(1.+TanLorenzAngleX*TanLorenzAngleX); //cosine
1099  CosLorenzAngleY = 1./sqrt(1.+TanLorenzAngleY*TanLorenzAngleY); //cosine;
1100 
1101  } else{
1102  TanLorenzAngleX = driftDir.x();
1103  TanLorenzAngleY = 0.; // force to 0, driftDir.y()/driftDir.z();
1104  dir_z = driftDir.z(); // The z drift direction
1105  CosLorenzAngleX = 1./sqrt(1.+TanLorenzAngleX*TanLorenzAngleX); //cosine to estimate the path length
1106  CosLorenzAngleY = 1.;
1107  }
1108 
1109  float moduleThickness = pixdet->specificSurface().bounds().thickness();
1110 #ifdef TP_DEBUG
1111  LogDebug ("Pixel Digitizer")
1112  << " Lorentz Tan " << TanLorenzAngleX << " " << TanLorenzAngleY <<" "
1113  << CosLorenzAngleX << " " << CosLorenzAngleY << " "
1114  << moduleThickness*TanLorenzAngleX << " " << driftDir;
1115 #endif
1116 
1117  float Sigma_x = 1.; // Charge spread
1118  float Sigma_y = 1.;
1119  float DriftDistance; // Distance between charge generation and collection
1120  float DriftLength; // Actual Drift Lentgh
1121  float Sigma;
1122 
1123  for (unsigned int i = 0; i != ionization_points.size(); i++) {
1124 
1125  float SegX, SegY, SegZ; // position
1126  SegX = ionization_points[i].x();
1127  SegY = ionization_points[i].y();
1128  SegZ = ionization_points[i].z();
1129 
1130  // Distance from the collection plane
1131  //DriftDistance = (moduleThickness/2. + SegZ); // Drift to -z
1132  // Include explixitely the E drift direction (for CMS dir_z=-1)
1133  DriftDistance = moduleThickness/2. - (dir_z * SegZ); // Drift to -z
1134 
1135  //if( DriftDistance <= 0.)
1136  //cout<<" <=0 "<<DriftDistance<<" "<<i<<" "<<SegZ<<" "<<dir_z<<" "
1137  // <<SegX<<" "<<SegY<<" "<<(moduleThickness/2)<<" "
1138  // <<ionization_points[i].energy()<<" "
1139  // <<hit.particleType()<<" "<<hit.pabs()<<" "<<hit.energyLoss()<<" "
1140  // <<hit.entryPoint()<<" "<<hit.exitPoint()
1141  // <<std::endl;
1142 
1143  if( DriftDistance < 0.) {
1144  DriftDistance = 0.;
1145  } else if( DriftDistance > moduleThickness )
1146  DriftDistance = moduleThickness;
1147 
1148  // Assume full depletion now, partial depletion will come later.
1149  float XDriftDueToMagField = DriftDistance * TanLorenzAngleX;
1150  float YDriftDueToMagField = DriftDistance * TanLorenzAngleY;
1151 
1152  // Shift cloud center
1153  float CloudCenterX = SegX + XDriftDueToMagField;
1154  float CloudCenterY = SegY + YDriftDueToMagField;
1155 
1156  // Calculate how long is the charge drift path
1157  DriftLength = sqrt( DriftDistance*DriftDistance +
1158  XDriftDueToMagField*XDriftDueToMagField +
1159  YDriftDueToMagField*YDriftDueToMagField );
1160 
1161  // What is the charge diffusion after this path
1162  Sigma = sqrt(DriftLength/Dist300) * Sigma0;
1163 
1164  // Project the diffusion sigma on the collection plane
1165  Sigma_x = Sigma / CosLorenzAngleX ;
1166  Sigma_y = Sigma / CosLorenzAngleY ;
1167 
1168  // Insert a charge loss due to Rad Damage here
1169  float energyOnCollector = ionization_points[i].energy(); // The energy that reaches the collector
1170 
1171  // add pixel aging
1172  if (AddPixelAging) {
1173  float kValue = pixel_aging(pixelAging_,pixdet,tTopo);
1174  energyOnCollector *= exp( -1*kValue*DriftDistance/moduleThickness );
1175  }
1176 
1177 #ifdef TP_DEBUG
1178  LogDebug ("Pixel Digitizer")
1179  <<" Dift DistanceZ= "<<DriftDistance<<" module thickness= "<<moduleThickness
1180  <<" Start Energy= "<<ionization_points[i].energy()<<" Energy after loss= "<<energyOnCollector;
1181 #endif
1182  SignalPoint sp( CloudCenterX, CloudCenterY,
1183  Sigma_x, Sigma_y, hit.tof(), energyOnCollector );
1184 
1185  // Load the Charge distribution parameters
1186  collection_points[i] = (sp);
1187 
1188  } // loop over ionization points, i.
1189 
1190 } // end drift
1191 
1192 //*************************************************************************
1193 // Induce the signal on the collection plane of the active sensor area.
1194 void SiPixelDigitizerAlgorithm::induce_signal(std::vector<PSimHit>::const_iterator inputBegin,
1195  std::vector<PSimHit>::const_iterator inputEnd,
1196  const PSimHit& hit,
1197  const size_t hitIndex,
1198  const unsigned int tofBin,
1199  const PixelGeomDetUnit* pixdet,
1200  const std::vector<SignalPoint>& collection_points) {
1201 
1202  // X - Rows, Left-Right, 160, (1.6cm) for barrel
1203  // Y - Columns, Down-Up, 416, (6.4cm)
1204 
1205  const PixelTopology* topol=&pixdet->specificTopology();
1206  uint32_t detID= pixdet->geographicalId().rawId();
1207  signal_map_type& theSignal = _signal[detID];
1208 
1209 #ifdef TP_DEBUG
1210  LogDebug ("Pixel Digitizer")
1211  << " enter induce_signal, "
1212  << topol->pitch().first << " " << topol->pitch().second; //OK
1213 #endif
1214 
1215  // local map to store pixels hit by 1 Hit.
1216  typedef std::map< int, float, std::less<int> > hit_map_type;
1217  hit_map_type hit_signal;
1218 
1219  // map to store pixel integrals in the x and in the y directions
1220  std::map<int, float, std::less<int> > x,y;
1221 
1222  // Assign signals to readout channels and store sorted by channel number
1223 
1224  // Iterate over collection points on the collection plane
1225  for ( std::vector<SignalPoint>::const_iterator i=collection_points.begin();
1226  i != collection_points.end(); ++i) {
1227 
1228  float CloudCenterX = i->position().x(); // Charge position in x
1229  float CloudCenterY = i->position().y(); // in y
1230  float SigmaX = i->sigma_x(); // Charge spread in x
1231  float SigmaY = i->sigma_y(); // in y
1232  float Charge = i->amplitude(); // Charge amplitude
1233 
1234 
1235  //if(SigmaX==0 || SigmaY==0) {
1236  //cout<<SigmaX<<" "<<SigmaY
1237  // << " cloud " << i->position().x() << " " << i->position().y() << " "
1238  // << i->sigma_x() << " " << i->sigma_y() << " " << i->amplitude()<<std::endl;
1239  //}
1240 
1241 #ifdef TP_DEBUG
1242  LogDebug ("Pixel Digitizer")
1243  << " cloud " << i->position().x() << " " << i->position().y() << " "
1244  << i->sigma_x() << " " << i->sigma_y() << " " << i->amplitude();
1245 #endif
1246 
1247  // Find the maximum cloud spread in 2D plane , assume 3*sigma
1248  float CloudRight = CloudCenterX + ClusterWidth*SigmaX;
1249  float CloudLeft = CloudCenterX - ClusterWidth*SigmaX;
1250  float CloudUp = CloudCenterY + ClusterWidth*SigmaY;
1251  float CloudDown = CloudCenterY - ClusterWidth*SigmaY;
1252 
1253  // Define 2D cloud limit points
1254  LocalPoint PointRightUp = LocalPoint(CloudRight,CloudUp);
1255  LocalPoint PointLeftDown = LocalPoint(CloudLeft,CloudDown);
1256 
1257  // This points can be located outside the sensor area.
1258  // The conversion to measurement point does not check for that
1259  // so the returned pixel index might be wrong (outside range).
1260  // We rely on the limits check below to fix this.
1261  // But remember whatever we do here THE CHARGE OUTSIDE THE ACTIVE
1262  // PIXEL AREA IS LOST, it should not be collected.
1263 
1264  // Convert the 2D points to pixel indices
1265  MeasurementPoint mp = topol->measurementPosition(PointRightUp ); //OK
1266 
1267  int IPixRightUpX = int( floor( mp.x()));
1268  int IPixRightUpY = int( floor( mp.y()));
1269 
1270 #ifdef TP_DEBUG
1271  LogDebug ("Pixel Digitizer") << " right-up " << PointRightUp << " "
1272  << mp.x() << " " << mp.y() << " "
1273  << IPixRightUpX << " " << IPixRightUpY ;
1274 #endif
1275 
1276  mp = topol->measurementPosition(PointLeftDown ); //OK
1277 
1278  int IPixLeftDownX = int( floor( mp.x()));
1279  int IPixLeftDownY = int( floor( mp.y()));
1280 
1281 #ifdef TP_DEBUG
1282  LogDebug ("Pixel Digitizer") << " left-down " << PointLeftDown << " "
1283  << mp.x() << " " << mp.y() << " "
1284  << IPixLeftDownX << " " << IPixLeftDownY ;
1285 #endif
1286 
1287  // Check detector limits to correct for pixels outside range.
1288  int numColumns = topol->ncolumns(); // det module number of cols&rows
1289  int numRows = topol->nrows();
1290 
1291  IPixRightUpX = numRows>IPixRightUpX ? IPixRightUpX : numRows-1 ;
1292  IPixRightUpY = numColumns>IPixRightUpY ? IPixRightUpY : numColumns-1 ;
1293  IPixLeftDownX = 0<IPixLeftDownX ? IPixLeftDownX : 0 ;
1294  IPixLeftDownY = 0<IPixLeftDownY ? IPixLeftDownY : 0 ;
1295 
1296  x.clear(); // clear temporary integration array
1297  y.clear();
1298 
1299  // First integrate charge strips in x
1300  int ix; // TT for compatibility
1301  for (ix=IPixLeftDownX; ix<=IPixRightUpX; ix++) { // loop over x index
1302  float xUB, xLB, UpperBound, LowerBound;
1303 
1304  // Why is set to 0 if ix=0, does it meen that we accept charge
1305  // outside the sensor? CHeck How it was done in ORCA?
1306  //if(ix == 0) LowerBound = 0.;
1307  if(ix == 0 || SigmaX==0. ) // skip for surface segemnts
1308  LowerBound = 0.;
1309  else {
1310  mp = MeasurementPoint( float(ix), 0.0);
1311  xLB = topol->localPosition(mp).x();
1312  LowerBound = 1-calcQ((xLB-CloudCenterX)/SigmaX);
1313  }
1314 
1315  if(ix == numRows-1 || SigmaX==0. )
1316  UpperBound = 1.;
1317  else {
1318  mp = MeasurementPoint( float(ix+1), 0.0);
1319  xUB = topol->localPosition(mp).x();
1320  UpperBound = 1. - calcQ((xUB-CloudCenterX)/SigmaX);
1321  }
1322 
1323  float TotalIntegrationRange = UpperBound - LowerBound; // get strip
1324  x[ix] = TotalIntegrationRange; // save strip integral
1325  //if(SigmaX==0 || SigmaY==0)
1326  //cout<<TotalIntegrationRange<<" "<<ix<<std::endl;
1327 
1328  }
1329 
1330  // Now integrate strips in y
1331  int iy; // TT for compatibility
1332  for (iy=IPixLeftDownY; iy<=IPixRightUpY; iy++) { //loope over y ind
1333  float yUB, yLB, UpperBound, LowerBound;
1334 
1335  if(iy == 0 || SigmaY==0.)
1336  LowerBound = 0.;
1337  else {
1338  mp = MeasurementPoint( 0.0, float(iy) );
1339  yLB = topol->localPosition(mp).y();
1340  LowerBound = 1. - calcQ((yLB-CloudCenterY)/SigmaY);
1341  }
1342 
1343  if(iy == numColumns-1 || SigmaY==0. )
1344  UpperBound = 1.;
1345  else {
1346  mp = MeasurementPoint( 0.0, float(iy+1) );
1347  yUB = topol->localPosition(mp).y();
1348  UpperBound = 1. - calcQ((yUB-CloudCenterY)/SigmaY);
1349  }
1350 
1351  float TotalIntegrationRange = UpperBound - LowerBound;
1352  y[iy] = TotalIntegrationRange; // save strip integral
1353  //if(SigmaX==0 || SigmaY==0)
1354  //cout<<TotalIntegrationRange<<" "<<iy<<std::endl;
1355  }
1356 
1357  // Get the 2D charge integrals by folding x and y strips
1358  int chan;
1359  for (ix=IPixLeftDownX; ix<=IPixRightUpX; ix++) { // loop over x index
1360  for (iy=IPixLeftDownY; iy<=IPixRightUpY; iy++) { //loope over y ind
1361 
1362  float ChargeFraction = Charge*x[ix]*y[iy];
1363 
1364  if( ChargeFraction > 0. ) {
1365  chan = PixelDigi::pixelToChannel( ix, iy); // Get index
1366  // Load the amplitude
1367  hit_signal[chan] += ChargeFraction;
1368  } // endif
1369 
1370 #ifdef TP_DEBUG
1371  mp = MeasurementPoint( float(ix), float(iy) );
1372  LocalPoint lp = topol->localPosition(mp);
1373  chan = topol->channel(lp);
1374  LogDebug ("Pixel Digitizer")
1375  << " pixel " << ix << " " << iy << " - "<<" "
1376  << chan << " " << ChargeFraction<<" "
1377  << mp.x() << " " << mp.y() <<" "
1378  << lp.x() << " " << lp.y() << " " // givex edge position
1379  << chan; // edge belongs to previous ?
1380 #endif
1381 
1382  } // endfor iy
1383  } //endfor ix
1384 
1385 
1386  } // loop over charge distributions
1387 
1388  // Fill the global map with all hit pixels from this event
1389 
1390  bool reweighted = false;
1391  if (UseReweighting){
1392  if(hit.processType()==0){
1393  reweighted = hitSignalReweight (hit, hit_signal, hitIndex, tofBin, topol, detID, theSignal, hit.processType());
1394  }else{
1395  // If it's not the primary particle, use the first hit in the collection as SimHit, which should be the corresponding primary.
1396  reweighted = hitSignalReweight ((*inputBegin), hit_signal, hitIndex, tofBin, topol, detID, theSignal, hit.processType());
1397  }
1398  }
1399  if (!reweighted){
1400  for ( hit_map_type::const_iterator im = hit_signal.begin();
1401  im != hit_signal.end(); ++im) {
1402  int chan = (*im).first;
1403  theSignal[chan] += (makeDigiSimLinks_ ? Amplitude( (*im).second, &hit, hitIndex, tofBin, (*im).second) : Amplitude( (*im).second, (*im).second) ) ;
1404 
1405 #ifdef TP_DEBUG
1406  std::pair<int,int> ip = PixelDigi::channelToPixel(chan);
1407  LogDebug ("Pixel Digitizer")
1408  << " pixel " << ip.first << " " << ip.second << " "
1409  << theSignal[chan];
1410 #endif
1411  }
1412  }
1413 
1414 } // end induce_signal
1415 
1416 /***********************************************************************/
1417 
1418 // Build pixels, check threshold, add misscalibration, ...
1419 void SiPixelDigitizerAlgorithm::make_digis(float thePixelThresholdInE,
1420  uint32_t detID,
1421  const PixelGeomDetUnit* pixdet,
1422  std::vector<PixelDigi>& digis,
1423  std::vector<PixelDigiSimLink>& simlinks,
1424  const TrackerTopology *tTopo) const {
1425 
1426 #ifdef TP_DEBUG
1427  LogDebug ("Pixel Digitizer") << " make digis "<<" "
1428  << " pixel threshold FPix" << theThresholdInE_FPix << " "
1429  << " pixel threshold BPix" << theThresholdInE_BPix << " "
1430  << " pixel threshold BPix Layer1" << theThresholdInE_BPix_L1 << " "
1431  << " pixel threshold BPix Layer2" << theThresholdInE_BPix_L2 << " "
1432  << " List pixels passing threshold ";
1433 #endif
1434 
1435  // Loop over hit pixels
1436 
1437  signalMaps::const_iterator it = _signal.find(detID);
1438  if (it == _signal.end()) {
1439  return;
1440  }
1441 
1442  const signal_map_type& theSignal = (*it).second;
1443 
1444  // unsigned long is enough to store SimTrack id and EncodedEventId
1445  using TrackEventId = std::pair<decltype(SimTrack().trackId()), decltype(EncodedEventId().rawId())>;
1446  std::map<TrackEventId, float> simi; // re-used
1447 
1448  for (signal_map_const_iterator i = theSignal.begin(); i != theSignal.end(); ++i) {
1449 
1450  float signalInElectrons = (*i).second ; // signal in electrons
1451 
1452  // Do the miss calibration for calibration studies only.
1453  //if(doMissCalibrate) signalInElectrons = missCalibrate(signalInElectrons)
1454 
1455  // Do only for pixels above threshold
1456 
1457  if( signalInElectrons >= thePixelThresholdInE && signalInElectrons > 0.) { // check threshold, always reject killed (0-charge) digis
1458 
1459  int chan = (*i).first; // channel number
1460  std::pair<int,int> ip = PixelDigi::channelToPixel(chan);
1461  int adc=0; // ADC count as integer
1462 
1463  // Do the miss calibration for calibration studies only.
1464  if(doMissCalibrate) {
1465  int row = ip.first; // X in row
1466  int col = ip.second; // Y is in col
1467  adc = int(missCalibrate(detID, tTopo, pixdet, col, row, signalInElectrons)); //full misscalib.
1468  } else { // Just do a simple electron->adc conversion
1469  adc = int( signalInElectrons / theElectronPerADC ); // calibrate gain
1470  }
1471  adc = std::min(adc, theAdcFullScale); // Check maximum value
1472 #ifdef TP_DEBUG
1473  LogDebug ("Pixel Digitizer")
1474  << (*i).first << " " << (*i).second << " " << signalInElectrons
1475  << " " << adc << ip.first << " " << ip.second ;
1476 #endif
1477 
1478  // Load digis
1479  digis.emplace_back(ip.first, ip.second, adc);
1480 
1481  if (makeDigiSimLinks_ && !(*i).second.hitInfos().empty()) {
1482  //digilink
1483  unsigned int il=0;
1484  for(const auto& info: (*i).second.hitInfos()) {
1485  // note: according to C++ standard operator[] does
1486  // value-initializiation, which for float means initial value of 0
1487  simi[std::make_pair(info.trackId(), info.eventId().rawId())] += (*i).second.individualampl()[il];
1488  il++;
1489  }
1490 
1491  //sum the contribution of the same trackid
1492  for(const auto& info: (*i).second.hitInfos()) {
1493  // skip if track already processed
1494  auto found = simi.find(std::make_pair(info.trackId(), info.eventId().rawId()));
1495  if(found == simi.end())
1496  continue;
1497 
1498  float sum_samechannel = found->second;
1499  float fraction=sum_samechannel/(*i).second;
1500  if(fraction>1.f) fraction=1.f;
1501 
1502  // Approximation: pick hitIndex and tofBin only from the first SimHit
1503  simlinks.emplace_back((*i).first, info.trackId(), info.hitIndex(), info.tofBin(), info.eventId(), fraction);
1504  simi.erase(found);
1505  }
1506  simi.clear(); // although should be empty already
1507  }
1508  }
1509  }
1510 }
1511 
1512 /***********************************************************************/
1513 
1514 // Add electronic noise to pixel charge
1516  float thePixelThreshold,
1517  CLHEP::HepRandomEngine* engine) {
1518 
1519 #ifdef TP_DEBUG
1520  LogDebug ("Pixel Digitizer") << " enter add_noise " << theNoiseInElectrons;
1521 #endif
1522 
1523  uint32_t detID= pixdet->geographicalId().rawId();
1524  signal_map_type& theSignal = _signal[detID];
1525 
1526 
1527  // First add noise to hit pixels
1528  float theSmearedChargeRMS = 0.0;
1529 
1530  for ( signal_map_iterator i = theSignal.begin(); i != theSignal.end(); i++) {
1531 
1533  {
1534  if((*i).second < 3000)
1535  {
1536  theSmearedChargeRMS = 543.6 - (*i).second * 0.093;
1537  } else if((*i).second < 6000){
1538  theSmearedChargeRMS = 307.6 - (*i).second * 0.01;
1539  } else{
1540  theSmearedChargeRMS = -432.4 +(*i).second * 0.123;
1541  }
1542 
1543  // Noise from Vcal smearing:
1544  float noise_ChargeVCALSmearing = theSmearedChargeRMS * CLHEP::RandGaussQ::shoot(engine, 0., 1.);
1545  // Noise from full readout:
1546  float noise = CLHEP::RandGaussQ::shoot(engine, 0., theReadoutNoise);
1547 
1548  if(((*i).second + Amplitude(noise+noise_ChargeVCALSmearing, -1.)) < 0. ) {
1549  (*i).second.set(0);}
1550  else{
1551  (*i).second +=Amplitude(noise+noise_ChargeVCALSmearing, -1.);
1552  }
1553 
1554  } // End if addChargeVCalSmearing
1555  else
1556  {
1557  // Noise: ONLY full READOUT Noise.
1558  // Use here the FULL readout noise, including TBM,ALT,AOH,OPT-REC.
1559  float noise = CLHEP::RandGaussQ::shoot(engine, 0., theReadoutNoise);
1560 
1561  if(((*i).second + Amplitude(noise, -1.)) < 0. ) {
1562  (*i).second.set(0);}
1563  else{
1564  (*i).second +=Amplitude(noise, -1.);
1565  }
1566  } // end if only Noise from full readout
1567 
1568  }
1569 
1570  if(!addNoisyPixels) // Option to skip noise in non-hit pixels
1571  return;
1572 
1573  const PixelTopology* topol=&pixdet->specificTopology();
1574  int numColumns = topol->ncolumns(); // det module number of cols&rows
1575  int numRows = topol->nrows();
1576 
1577  // Add noise on non-hit pixels
1578  // Use here the pixel noise
1579  int numberOfPixels = (numRows * numColumns);
1580  std::map<int,float, std::less<int> > otherPixels;
1581  std::map<int,float, std::less<int> >::iterator mapI;
1582 
1583  theNoiser->generate(numberOfPixels,
1584  thePixelThreshold, //thr. in un. of nois
1585  theNoiseInElectrons, // noise in elec.
1586  otherPixels,
1587  engine );
1588 
1589 #ifdef TP_DEBUG
1590  LogDebug ("Pixel Digitizer")
1591  << " Add noisy pixels " << numRows << " "
1592  << numColumns << " " << theNoiseInElectrons << " "
1593  << theThresholdInE_FPix << theThresholdInE_BPix <<" "<< numberOfPixels<<" "
1594  << otherPixels.size() ;
1595 #endif
1596 
1597  // Add noisy pixels
1598  for (mapI = otherPixels.begin(); mapI!= otherPixels.end(); mapI++) {
1599  int iy = ((*mapI).first) / numRows;
1600  int ix = ((*mapI).first) - (iy*numRows);
1601 
1602  // Keep for a while for testing.
1603  if( iy < 0 || iy > (numColumns-1) )
1604  LogWarning ("Pixel Geometry") << " error in iy " << iy ;
1605  if( ix < 0 || ix > (numRows-1) )
1606  LogWarning ("Pixel Geometry") << " error in ix " << ix ;
1607 
1608  int chan = PixelDigi::pixelToChannel(ix, iy);
1609 
1610 #ifdef TP_DEBUG
1611  LogDebug ("Pixel Digitizer")
1612  <<" Storing noise = " << (*mapI).first << " " << (*mapI).second
1613  << " " << ix << " " << iy << " " << chan ;
1614 #endif
1615 
1616  if(theSignal[chan] == 0){
1617  // float noise = float( (*mapI).second );
1618  int noise=int( (*mapI).second );
1619  theSignal[chan] = Amplitude (noise, -1.);
1620  }
1621  }
1622 }
1623 
1624 /***********************************************************************/
1625 
1626 // Simulate the readout inefficiencies.
1627 // Delete a selected number of single pixels, dcols and rocs.
1629  const PixelGeomDetUnit* pixdet,
1630  const TrackerTopology *tTopo,
1631  CLHEP::HepRandomEngine* engine) {
1632 
1633  uint32_t detID= pixdet->geographicalId().rawId();
1634  signal_map_type& theSignal = _signal[detID];
1635  const PixelTopology* topol=&pixdet->specificTopology();
1636  int numColumns = topol->ncolumns(); // det module number of cols&rows
1637  int numRows = topol->nrows();
1638  bool isPhase1 = pixdet->subDetector()==GeomDetEnumerators::SubDetector::P1PXB
1640  // Predefined efficiencies
1641  double pixelEfficiency = 1.0;
1642  double columnEfficiency = 1.0;
1643  double chipEfficiency = 1.0;
1644  std::vector<double> pixelEfficiencyROCStdPixels(16,1);
1645  std::vector<double> pixelEfficiencyROCBigPixels(16,1);
1646 
1647  auto pIndexConverter = PixelIndices(numColumns,numRows);
1648 
1649  std::vector<int> badRocsFromFEDChannels(16,0);
1650  if (eff.PixelFEDChannelCollection_ != nullptr){
1652 
1653  if (it != eff.PixelFEDChannelCollection_->end()){
1654  const std::vector<CablingPathToDetUnit> &path = map_->pathToDetUnit(detID);
1655  for(const auto& ch: *it) {
1656  for (unsigned int i_roc = ch.roc_first; i_roc <= ch.roc_last; ++i_roc){
1657  for(const auto p : path){
1658  const PixelROC* myroc = map_.product()->findItem(p);
1659  if( myroc->idInDetUnit() == static_cast<unsigned int>(i_roc)) {
1660  LocalPixel::RocRowCol local = {39, 25};//corresponding to center of ROC row,col
1661  GlobalPixel global = myroc->toGlobal( LocalPixel(local) );
1662  int chipIndex(0), colROC(0), rowROC(0);
1663  pIndexConverter.transformToROC(global.col,global.row,chipIndex,colROC,rowROC);
1664  badRocsFromFEDChannels.at(chipIndex) = 1;
1665  }
1666  }
1667  }
1668  } // loop over channels
1669  } // detID in PixelFEDChannelCollection_
1670  } // has PixelFEDChannelCollection_
1671 
1672 
1673  if (eff.FromConfig) {
1674  // setup the chip indices conversion
1676  pixdet->subDetector()==GeomDetEnumerators::SubDetector::P1PXB){// barrel layers
1677  int layerIndex=tTopo->layer(detID);
1678  pixelEfficiency = eff.thePixelEfficiency[layerIndex-1];
1679  columnEfficiency = eff.thePixelColEfficiency[layerIndex-1];
1680  chipEfficiency = eff.thePixelChipEfficiency[layerIndex-1];
1681  //std::cout <<"Using BPix columnEfficiency = "<<columnEfficiency<< " for layer = "<<layerIndex <<"\n";
1682  // This should never happen, but only check if it is not an upgrade geometry
1683  if (NumberOfBarrelLayers==3){
1684  if(numColumns>416) LogWarning ("Pixel Geometry") <<" wrong columns in barrel "<<numColumns;
1685  if(numRows>160) LogWarning ("Pixel Geometry") <<" wrong rows in barrel "<<numRows;
1686 
1687  int ladder=tTopo->pxbLadder(detID);
1688  int module=tTopo->pxbModule(detID);
1689  if (module<=4) module=5-module;
1690  else module-=4;
1691 
1692  columnEfficiency *= eff.theLadderEfficiency_BPix[layerIndex-1][ladder-1]*eff.theModuleEfficiency_BPix[layerIndex-1][module-1]*eff.pu_scale[layerIndex-1];
1693  }
1696  pixdet->subDetector()==GeomDetEnumerators::SubDetector::P2PXEC){ // forward disks
1697 
1698  unsigned int diskIndex=tTopo->layer(detID)+eff.FPixIndex; // Use diskIndex-1 later to stay consistent with BPix
1699  unsigned int panelIndex=tTopo->pxfPanel(detID);
1700  unsigned int moduleIndex=tTopo->pxfModule(detID);
1701  //if (eff.FPixIndex>diskIndex-1){throw cms::Exception("Configuration") <<"SiPixelDigitizer is using the wrong efficiency value. index = "
1702  // <<diskIndex-1<<" , MinIndex = "<<eff.FPixIndex<<" ... "<<tTopo->pxfDisk(detID);}
1703  pixelEfficiency = eff.thePixelEfficiency[diskIndex-1];
1704  columnEfficiency = eff.thePixelColEfficiency[diskIndex-1];
1705  chipEfficiency = eff.thePixelChipEfficiency[diskIndex-1];
1706  //std::cout <<"Using FPix columnEfficiency = "<<columnEfficiency<<" for Disk = "<< tTopo->pxfDisk(detID)<<"\n";
1707  // Sometimes the forward pixels have wrong size,
1708  // this crashes the index conversion, so exit, but only check if it is not an upgrade geometry
1709  if (NumberOfBarrelLayers==3){ // whether it is the present or the phase 1 detector can be checked using GeomDetEnumerators::SubDetector
1710  if(numColumns>260 || numRows>160) {
1711  if(numColumns>260) LogWarning ("Pixel Geometry") <<" wrong columns in endcaps "<<numColumns;
1712  if(numRows>160) LogWarning ("Pixel Geometry") <<" wrong rows in endcaps "<<numRows;
1713  return;
1714  }
1715  if ((panelIndex==1 && (moduleIndex==1 || moduleIndex==2)) || (panelIndex==2 && moduleIndex==1)) { //inner modules
1716  columnEfficiency*=eff.theInnerEfficiency_FPix[diskIndex-1]*eff.pu_scale[3];
1717  } else { //outer modules
1718  columnEfficiency*=eff.theOuterEfficiency_FPix[diskIndex-1]*eff.pu_scale[4];
1719  }
1720  } // current detector, forward
1722  // If phase 2 outer tracker, hardcoded values as they have been so far
1723  pixelEfficiency = 0.999;
1724  columnEfficiency = 0.999;
1725  chipEfficiency = 0.999;
1726  } // if barrel/forward
1727  } else { // Load precomputed factors from Database
1728  pixelEfficiency = eff.PixelGeomFactors.at(detID);
1729  columnEfficiency = eff.ColGeomFactors.at(detID)*eff.pu_scale[eff.iPU.at(detID)];
1730  chipEfficiency = eff.ChipGeomFactors.at(detID);
1731  if (isPhase1){
1732  for (unsigned int i_roc=0; i_roc<eff.PixelGeomFactorsROCStdPixels.at(detID).size();++i_roc){
1733  pixelEfficiencyROCStdPixels[i_roc] = eff.PixelGeomFactorsROCStdPixels.at(detID).at(i_roc);
1734  pixelEfficiencyROCBigPixels[i_roc] = eff.PixelGeomFactorsROCBigPixels.at(detID).at(i_roc);
1735  }
1736  } // is Phase 1
1737  }
1738 
1739 #ifdef TP_DEBUG
1740  LogDebug ("Pixel Digitizer") << " enter pixel_inefficiency " << pixelEfficiency << " "
1741  << columnEfficiency << " " << chipEfficiency;
1742 #endif
1743 
1744  // Initilize the index converter
1745  //PixelIndices indexConverter(numColumns,numRows);
1746 
1747  int chipIndex = 0;
1748  int rowROC = 0;
1749  int colROC = 0;
1750  std::map<int, int, std::less<int> >chips, columns, pixelStd, pixelBig;
1751  std::map<int, int, std::less<int> >::iterator iter;
1752 
1753  // Find out the number of columns and rocs hits
1754  // Loop over hit pixels, amplitude in electrons, channel = coded row,col
1755  for (signal_map_const_iterator i = theSignal.begin(); i != theSignal.end(); ++i) {
1756 
1757  int chan = i->first;
1758  std::pair<int,int> ip = PixelDigi::channelToPixel(chan);
1759  int row = ip.first; // X in row
1760  int col = ip.second; // Y is in col
1761  //transform to ROC index coordinates
1762  pIndexConverter.transformToROC(col,row,chipIndex,colROC,rowROC);
1763  int dColInChip = pIndexConverter.DColumn(colROC); // get ROC dcol from ROC col
1764  //dcol in mod
1765  int dColInDet = pIndexConverter.DColumnInModule(dColInChip,chipIndex);
1766 
1767  chips[chipIndex]++;
1768  columns[dColInDet]++;
1769  if (isPhase1){
1770  if (topol->isItBigPixelInX(row) || topol->isItBigPixelInY(col))
1771  pixelBig[chipIndex]++;
1772  else
1773  pixelStd[chipIndex]++;
1774  }
1775  }
1776 
1777  // Delete some ROC hits.
1778  for ( iter = chips.begin(); iter != chips.end() ; iter++ ) {
1779  //float rand = RandFlat::shoot();
1780  float rand = CLHEP::RandFlat::shoot(engine);
1781  if( rand > chipEfficiency ) chips[iter->first]=0;
1782  }
1783 
1784  // Delete some Dcol hits.
1785  for ( iter = columns.begin(); iter != columns.end() ; iter++ ) {
1786  //float rand = RandFlat::shoot();
1787  float rand = CLHEP::RandFlat::shoot(engine);
1788  if( rand > columnEfficiency ) columns[iter->first]=0;
1789  }
1790 
1791  // Delete some pixel hits based on DCDC issue damage.
1792  if (isPhase1){
1793  for ( iter = pixelStd.begin(); iter != pixelStd.end() ; iter++ ) {
1794  float rand = CLHEP::RandFlat::shoot(engine);
1795  if( rand > pixelEfficiencyROCStdPixels[iter->first]) pixelStd[iter->first] = 0;
1796  }
1797 
1798  for ( iter = pixelBig.begin(); iter != pixelBig.end() ; iter++ ) {
1799  float rand = CLHEP::RandFlat::shoot(engine);
1800  if( rand > pixelEfficiencyROCBigPixels[iter->first]) pixelBig[iter->first] = 0;
1801  }
1802  }
1803 
1804  // Now loop again over pixels to kill some of them.
1805  // Loop over hit pixels, amplitude in electrons, channel = coded row,col
1806  for(signal_map_iterator i = theSignal.begin();i != theSignal.end(); ++i) {
1807 
1808  // int chan = i->first;
1809  std::pair<int,int> ip = PixelDigi::channelToPixel(i->first);//get pixel pos
1810  int row = ip.first; // X in row
1811  int col = ip.second; // Y is in col
1812  //transform to ROC index coordinates
1813  pIndexConverter.transformToROC(col,row,chipIndex,colROC,rowROC);
1814  int dColInChip = pIndexConverter.DColumn(colROC); //get ROC dcol from ROC col
1815  //dcol in mod
1816  int dColInDet = pIndexConverter.DColumnInModule(dColInChip,chipIndex);
1817 
1818  //float rand = RandFlat::shoot();
1819  float rand = CLHEP::RandFlat::shoot(engine);
1820  if( chips[chipIndex]==0 || columns[dColInDet]==0
1821  || rand>pixelEfficiency
1822  || (pixelStd.count(chipIndex) && pixelStd[chipIndex] == 0)
1823  || (pixelBig.count(chipIndex) && pixelBig[chipIndex] == 0)) {
1824  // make pixel amplitude =0, pixel will be lost at clusterization
1825  i->second.set(0.); // reset amplitude,
1826  } // end if
1827  if (isPhase1){
1828  if((pixelStd.count(chipIndex) && pixelStd[chipIndex] == 0)
1829  || (pixelBig.count(chipIndex) && pixelBig[chipIndex] == 0)
1830  || (badRocsFromFEDChannels.at(chipIndex) == 1))
1831  {
1832  //============================================================
1833  // make pixel amplitude =0, pixel will be lost at clusterization
1834  i->second.set(0.); // reset amplitude,
1835  } // end if
1836  } // is Phase 1
1837  if (KillBadFEDChannels && badRocsFromFEDChannels.at(chipIndex) == 1){
1838  i->second.set(0.);
1839  }
1840  } // end pixel loop
1841 } // end pixel_indefficiency
1842 
1843 //***************************************************************************************
1844 // Simulate pixel aging with an exponential function
1845 //**************************************************************************************
1846 
1848  const PixelGeomDetUnit *pixdet,
1849  const TrackerTopology *tTopo) const {
1850 
1851  uint32_t detID= pixdet->geographicalId().rawId();
1852 
1853 
1854  // Predefined damage parameter (no aging)
1855  float pseudoRadDamage = 0.0f;
1856 
1857  // setup the chip indices conversion
1859  pixdet->subDetector() == GeomDetEnumerators::SubDetector::P1PXB){// barrel layers
1860  int layerIndex=tTopo->layer(detID);
1861 
1862  pseudoRadDamage = aging.thePixelPseudoRadDamage[layerIndex-1];
1863 
1864  // std::cout << "pixel_aging: " << std::endl;
1865  // std::cout << "Subid " << Subid << " layerIndex " << layerIndex << " ladder " << tTopo->pxbLadder(detID) << " module " << tTopo->pxbModule(detID) << std::endl;
1866 
1869  pixdet->subDetector() == GeomDetEnumerators::SubDetector::P2PXEC) { // forward disks
1870  unsigned int diskIndex=tTopo->layer(detID)+aging.FPixIndex; // Use diskIndex-1 later to stay consistent with BPix
1871 
1872  pseudoRadDamage = aging.thePixelPseudoRadDamage[diskIndex-1];
1873 
1874  // std::cout << "pixel_aging: " << std::endl;
1875  // std::cout << "Subid " << Subid << " diskIndex " << diskIndex << std::endl;
1877  // if phase 2 OT hardcoded value as it has always been
1878  pseudoRadDamage = 0.f;
1879  } // if barrel/forward
1880 
1881  // std::cout << " pseudoRadDamage " << pseudoRadDamage << std::endl;
1882  // std::cout << " end pixel_aging " << std::endl;
1883 
1884  return pseudoRadDamage;
1885 #ifdef TP_DEBUG
1886  LogDebug ("Pixel Digitizer") << " enter pixel_aging " << pseudoRadDamage;
1887 #endif
1888 
1889 }
1890 
1891 //***********************************************************************
1892 
1893 // Fluctuate the gain and offset for the amplitude calibration
1894 // Use gaussian smearing.
1895 //float SiPixelDigitizerAlgorithm::missCalibrate(const float amp) const {
1896  //float gain = RandGaussQ::shoot(1.,theGainSmearing);
1897  //float offset = RandGaussQ::shoot(0.,theOffsetSmearing);
1898  //float newAmp = amp * gain + offset;
1899  // More complex misscalibration
1900 float SiPixelDigitizerAlgorithm::missCalibrate(uint32_t detID, const TrackerTopology *tTopo, const PixelGeomDetUnit* pixdet, int col,int row,
1901  const float signalInElectrons) const {
1902  // Central values
1903  //const float p0=0.00352, p1=0.868, p2=112., p3=113.; // pix(0,0,0)
1904  // const float p0=0.00382, p1=0.886, p2=112.7, p3=113.0; // average roc=0
1905  //const float p0=0.00492, p1=1.998, p2=90.6, p3=134.1; // average roc=6
1906  // Smeared (rms)
1907  //const float s0=0.00020, s1=0.051, s2=5.4, s3=4.4; // average roc=0
1908  //const float s0=0.00015, s1=0.043, s2=3.2, s3=3.1; // col average roc=0
1909 
1910  // Make 2 sets of parameters for Fpix and BPIx:
1911 
1912  float p0=0.0f;
1913  float p1=0.0f;
1914  float p2=0.0f;
1915  float p3=0.0f;
1916 
1917  if(pixdet->type().isTrackerPixel() && pixdet->type().isBarrel()){// barrel layers
1918  p0 = BPix_p0;
1919  p1 = BPix_p1;
1920  p2 = BPix_p2;
1921  p3 = BPix_p3;
1922  } else if(pixdet->type().isTrackerPixel()) {// forward disks
1923  p0 = FPix_p0;
1924  p1 = FPix_p1;
1925  p2 = FPix_p2;
1926  p3 = FPix_p3;
1927  } else {
1928  throw cms::Exception("NotAPixelGeomDetUnit") << "Not a pixel geomdet unit" << detID;
1929  }
1930 
1931  float newAmp = 0.f; //Modified signal
1932 
1933  // Convert electrons to VCAL units
1934  float signal = (signalInElectrons-electronsPerVCAL_Offset)/electronsPerVCAL;
1935 
1936  // New gains/offsets are needed for phase1 L1
1937  int layer = 0;
1938  if (DetId(detID).subdetId()==1) layer = tTopo->pxbLayer(detID);
1939  if (layer==1) signal = (signalInElectrons-electronsPerVCAL_L1_Offset)/electronsPerVCAL_L1;
1940 
1941  // Simulate the analog response with fixed parametrization
1942  newAmp = p3 + p2 * tanh(p0*signal - p1);
1943 
1944 
1945  // Use the pixel-by-pixel calibrations
1946  //transform to ROC index coordinates
1947  //int chipIndex=0, colROC=0, rowROC=0;
1948  //std::unique_ptr<PixelIndices> pIndexConverter(new PixelIndices(numColumns,numRows));
1949  //pIndexConverter->transformToROC(col,row,chipIndex,colROC,rowROC);
1950 
1951  // Use calibration from a file
1952  //int chanROC = PixelIndices::pixelToChannelROC(rowROC,colROC); // use ROC coordinates
1953  //float pp0=0, pp1=0,pp2=0,pp3=0;
1954  //map<int,CalParameters,std::less<int> >::const_iterator it=calmap.find(chanROC);
1955  //CalParameters y = (*it).second;
1956  //pp0 = y.p0;
1957  //pp1 = y.p1;
1958  //pp2 = y.p2;
1959  //pp3 = y.p3;
1960 
1961  //
1962  // Use random smearing
1963  // Randomize the pixel response
1964  //float pp0 = RandGaussQ::shoot(p0,s0);
1965  //float pp1 = RandGaussQ::shoot(p1,s1);
1966  //float pp2 = RandGaussQ::shoot(p2,s2);
1967  //float pp3 = RandGaussQ::shoot(p3,s3);
1968 
1969  //newAmp = pp3 + pp2 * tanh(pp0*signal - pp1); // Final signal
1970 
1971  //cout<<" misscalibrate "<<col<<" "<<row<<" "<<chipIndex<<" "<<colROC<<" "
1972  // <<rowROC<<" "<<signalInElectrons<<" "<<signal<<" "<<newAmp<<" "
1973  // <<(signalInElectrons/theElectronPerADC)<<std::endl;
1974 
1975  return newAmp;
1976 }
1977 //******************************************************************************
1978 
1979 // Set the drift direction accoring to the Bfield in local det-unit frame
1980 // Works for both barrel and forward pixels.
1981 // Replace the sign convention to fit M.Swartz's formulaes.
1982 // Configurations for barrel and foward pixels possess different tanLorentzAngleperTesla
1983 // parameter value
1984 
1986  const GlobalVector& bfield,
1987  const DetId& detId) const {
1988  Frame detFrame(pixdet->surface().position(),pixdet->surface().rotation());
1989  LocalVector Bfield=detFrame.toLocal(bfield);
1990 
1991  float alpha2_FPix;
1992  float alpha2_BPix;
1993  float alpha2;
1994 
1995  //float dir_x = -tanLorentzAnglePerTesla * Bfield.y();
1996  //float dir_y = +tanLorentzAnglePerTesla * Bfield.x();
1997  //float dir_z = -1.; // E field always in z direction, so electrons go to -z
1998  // The dir_z has to be +/- 1. !
1999  // LocalVector theDriftDirection = LocalVector(dir_x,dir_y,dir_z);
2000 
2001  float dir_x = 0.0f;
2002  float dir_y = 0.0f;
2003  float dir_z = 0.0f;
2004  float scale = 0.0f;
2005 
2006  uint32_t detID= pixdet->geographicalId().rawId();
2007 
2008 
2009  // Read Lorentz angle from cfg file:**************************************************************
2010 
2011  if(!use_LorentzAngle_DB_){
2012 
2013  if( alpha2Order) {
2016  }else {
2017  alpha2_FPix = 0.0f;
2018  alpha2_BPix = 0.0f;
2019  }
2020 
2021  if(pixdet->type().isTrackerPixel() && pixdet->type().isBarrel()){// barrel layers
2022  dir_x = -( tanLorentzAnglePerTesla_BPix * Bfield.y() + alpha2_BPix* Bfield.z()* Bfield.x() );
2023  dir_y = +( tanLorentzAnglePerTesla_BPix * Bfield.x() - alpha2_BPix* Bfield.z()* Bfield.y() );
2024  dir_z = -(1 + alpha2_BPix* Bfield.z()*Bfield.z() );
2025  scale = -dir_z;
2026  } else if (pixdet->type().isTrackerPixel()) {// forward disks
2027  dir_x = -( tanLorentzAnglePerTesla_FPix * Bfield.y() + alpha2_FPix* Bfield.z()* Bfield.x() );
2028  dir_y = +( tanLorentzAnglePerTesla_FPix * Bfield.x() - alpha2_FPix* Bfield.z()* Bfield.y() );
2029  dir_z = -(1 + alpha2_FPix* Bfield.z()*Bfield.z() );
2030  scale = -dir_z;
2031  } else {
2032  throw cms::Exception("NotAPixelGeomDetUnit") << "Not a pixel geomdet unit" << detID;
2033  }
2034  } // end: Read LA from cfg file.
2035 
2036  //Read Lorentz angle from DB:********************************************************************
2038  float lorentzAngle = SiPixelLorentzAngle_->getLorentzAngle(detId);
2039  alpha2 = lorentzAngle * lorentzAngle;
2040  //std::cout << "detID is: "<< it->first <<"The LA per tesla is: "<< it->second << std::std::endl;
2041  dir_x = -( lorentzAngle * Bfield.y() + alpha2 * Bfield.z()* Bfield.x() );
2042  dir_y = +( lorentzAngle * Bfield.x() - alpha2 * Bfield.z()* Bfield.y() );
2043  dir_z = -(1 + alpha2 * Bfield.z()*Bfield.z() );
2044  scale = -dir_z;
2045  }// end: Read LA from DataBase.
2046 
2047  LocalVector theDriftDirection = LocalVector(dir_x/scale, dir_y/scale, dir_z/scale );
2048 
2049 #ifdef TP_DEBUG
2050  LogDebug ("Pixel Digitizer") << " The drift direction in local coordinate is "
2051  << theDriftDirection ;
2052 #endif
2053 
2054  return theDriftDirection;
2055 }
2056 
2057 //****************************************************************************************************
2058 
2060 
2061  signal_map_type& theSignal = _signal[detID];
2062 
2063  // Loop over hit pixels, amplitude in electrons, channel = coded row,col
2064  for(signal_map_iterator i = theSignal.begin();i != theSignal.end(); ++i) {
2065 
2066  // int chan = i->first;
2067  std::pair<int,int> ip = PixelDigi::channelToPixel(i->first);//get pixel pos
2068  int row = ip.first; // X in row
2069  int col = ip.second; // Y is in col
2070  //transform to ROC index coordinates
2071  if(theSiPixelGainCalibrationService_->isDead(detID, col, row)){
2072  // std::cout << "now in isdead check, row " << detID << " " << col << "," << row << std::std::endl;
2073  // make pixel amplitude =0, pixel will be lost at clusterization
2074  i->second.set(0.); // reset amplitude,
2075  } // end if
2076  } // end pixel loop
2077 } // end pixel_indefficiency
2078 
2079 
2080 //****************************************************************************************************
2081 
2083 
2084  bool isbad=false;
2085 
2086  Parameters::const_iterator itDeadModules=DeadModules.begin();
2087 
2088  int detid = detID;
2089  for(; itDeadModules != DeadModules.end(); ++itDeadModules){
2090  int Dead_detID = itDeadModules->getParameter<int>("Dead_detID");
2091  if(detid == Dead_detID){
2092  isbad=true;
2093  break;
2094  }
2095  }
2096 
2097  if(!isbad)
2098  return;
2099 
2100  signal_map_type& theSignal = _signal[detID];
2101 
2102  std::string Module = itDeadModules->getParameter<std::string>("Module");
2103 
2104  if(Module=="whole"){
2105  for(signal_map_iterator i = theSignal.begin();i != theSignal.end(); ++i) {
2106  i->second.set(0.); // reset amplitude
2107  }
2108  }
2109 
2110  for(signal_map_iterator i = theSignal.begin();i != theSignal.end(); ++i) {
2111  std::pair<int,int> ip = PixelDigi::channelToPixel(i->first);//get pixel pos
2112 
2113  if(Module=="tbmA" && ip.first>=80 && ip.first<=159){
2114  i->second.set(0.);
2115  }
2116 
2117  if( Module=="tbmB" && ip.first<=79){
2118  i->second.set(0.);
2119  }
2120  }
2121 }
2122 //****************************************************************************************************
2124 // Not SLHC safe for now
2125 
2126  bool isbad=false;
2127 
2128  std::vector<SiPixelQuality::disabledModuleType>disabledModules = SiPixelBadModule_->getBadComponentList();
2129 
2131 
2132  for (size_t id=0;id<disabledModules.size();id++)
2133  {
2134  if(detID==disabledModules[id].DetID){
2135  isbad=true;
2136  badmodule = disabledModules[id];
2137  break;
2138  }
2139  }
2140 
2141  if(!isbad)
2142  return;
2143 
2144  signal_map_type& theSignal = _signal[detID];
2145 
2146  //std::cout<<"Hit in: "<< detID <<" errorType "<< badmodule.errorType<<" BadRocs="<<std::hex<<SiPixelBadModule_->getBadRocs(detID)<<dec<<" "<<std::endl;
2147  if(badmodule.errorType == 0){ // this is a whole dead module.
2148 
2149  for(signal_map_iterator i = theSignal.begin();i != theSignal.end(); ++i) {
2150  i->second.set(0.); // reset amplitude
2151  }
2152  }
2153  else { // all other module types: half-modules and single ROCs.
2154  // Get Bad ROC position:
2155  //follow the example of getBadRocPositions in CondFormats/SiPixelObjects/src/SiPixelQuality.cc
2156  std::vector<GlobalPixel> badrocpositions (0);
2157  for(unsigned int j = 0; j < 16; j++){
2158  if(SiPixelBadModule_->IsRocBad(detID, j) == true){
2159 
2160  std::vector<CablingPathToDetUnit> path = map_.product()->pathToDetUnit(detID);
2161  typedef std::vector<CablingPathToDetUnit>::const_iterator IT;
2162  for (IT it = path.begin(); it != path.end(); ++it) {
2163  const PixelROC* myroc = map_.product()->findItem(*it);
2164  if( myroc->idInDetUnit() == j) {
2165  LocalPixel::RocRowCol local = { 39, 25}; //corresponding to center of ROC row, col
2166  GlobalPixel global = myroc->toGlobal( LocalPixel(local) );
2167  badrocpositions.push_back(global);
2168  break;
2169  }
2170  }
2171  }
2172  }// end of getBadRocPositions
2173 
2174 
2175  for(signal_map_iterator i = theSignal.begin();i != theSignal.end(); ++i) {
2176  std::pair<int,int> ip = PixelDigi::channelToPixel(i->first);//get pixel pos
2177 
2178  for(std::vector<GlobalPixel>::const_iterator it = badrocpositions.begin(); it != badrocpositions.end(); ++it){
2179  if(it->row >= 80 && ip.first >= 80 ){
2180  if((std::abs(ip.second - it->col) < 26) ) {i->second.set(0.);}
2181  else if(it->row==120 && ip.second-it->col==26){i->second.set(0.);}
2182  else if(it->row==119 && it->col-ip.second==26){i->second.set(0.);}
2183  }
2184  else if(it->row < 80 && ip.first < 80 ){
2185  if((std::abs(ip.second - it->col) < 26) ){i->second.set(0.);}
2186  else if(it->row==40 && ip.second-it->col==26){i->second.set(0.);}
2187  else if(it->row==39 && it->col-ip.second==26){i->second.set(0.);}
2188  }
2189  }
2190  }
2191  }
2192 }
2193 
2194 
2195 
2197  std::map< int, float, std::less<int> >& hit_signal,
2198  const size_t hitIndex,
2199  const unsigned int tofBin,
2200  const PixelTopology* topol,
2201  uint32_t detID,
2202  signal_map_type& theSignal,
2203  unsigned short int processType){
2204 
2205  int irow_min = topol->nrows();
2206  int irow_max = 0;
2207  int icol_min = topol->ncolumns();
2208  int icol_max = 0;
2209 
2210  float chargeBefore = 0;
2211  float chargeAfter = 0;
2212  signal_map_type hitSignal;
2213  LocalVector direction = hit.exitPoint() - hit.entryPoint();
2214 
2215  for ( std::map< int, float, std::less<int> >::const_iterator im = hit_signal.begin(); im != hit_signal.end(); ++im) {
2216  int chan = (*im).first;
2217  std::pair<int,int> pixelWithCharge = PixelDigi::channelToPixel( chan);
2218  //std::cout << "PixelHit - x: " << pixelWithCharge.first << " y: " << pixelWithCharge.second << " With Charge: " << (*im).second << std::endl;
2219 
2220  hitSignal[chan] += (makeDigiSimLinks_ ? Amplitude( (*im).second, &hit, hitIndex, tofBin, (*im).second) : Amplitude( (*im).second, (*im).second) ) ;
2221  chargeBefore += (*im).second;
2222 
2223  if(pixelWithCharge.first < irow_min)
2224  irow_min = pixelWithCharge.first;
2225  if(pixelWithCharge.first > irow_max)
2226  irow_max = pixelWithCharge.first;
2227  if(pixelWithCharge.second < icol_min)
2228  icol_min = pixelWithCharge.second;
2229  if(pixelWithCharge.second > icol_max)
2230  icol_max = pixelWithCharge.second;
2231  }
2232 
2233  LocalPoint hitEntryPoint = hit.entryPoint();
2234 
2235  float trajectoryScaleToPosition = hitEntryPoint.z()/direction.z();
2236 
2237  if( (hitEntryPoint.z() > 0 && direction.z() < 0) || (hitEntryPoint.z() < 0 && direction.z() > 0) ){
2238  trajectoryScaleToPosition *= -1;
2239  }
2240 
2241  LocalPoint hitPosition = hitEntryPoint + trajectoryScaleToPosition * direction;
2242 
2243  MeasurementPoint hitPositionPixel = topol->measurementPosition(hit.localPosition() );
2244  std::pair<int,int> hitPixel = std::pair<int,int>( int( floor(hitPositionPixel.x() ) ), int ( floor(hitPositionPixel.y() ) ));
2245 
2246  MeasurementPoint originPixel = MeasurementPoint(hitPixel.first - THX + 0.5, hitPixel.second - THY + 0.5);
2247  LocalPoint origin = topol->localPosition(originPixel);
2248 
2249  MeasurementPoint hitEntryPointPixel = topol->measurementPosition(hit.entryPoint() );
2250  MeasurementPoint hitExitPointPixel = topol->measurementPosition(hit.exitPoint() );
2251  std::pair<int,int> entryPixel = std::pair<int,int>( int( floor(hitEntryPointPixel.x() ) ), int ( floor(hitEntryPointPixel.y() ) ));
2252  std::pair<int,int> exitPixel = std::pair<int,int>( int( floor(hitExitPointPixel.x() ) ), int ( floor(hitExitPointPixel.y() ) ));
2253 
2254  int hitcol_min, hitcol_max, hitrow_min, hitrow_max;
2255  if(entryPixel.first>exitPixel.first){
2256  hitrow_min = exitPixel.first;
2257  hitrow_max = entryPixel.first;
2258  }else{
2259  hitrow_min = entryPixel.first;
2260  hitrow_max = exitPixel.first;
2261  }
2262 
2263  if(entryPixel.second>exitPixel.second){
2264  hitcol_min = exitPixel.second;
2265  hitcol_max = entryPixel.second;
2266  }else{
2267  hitcol_min = entryPixel.second;
2268  hitcol_max = exitPixel.second;
2269  }
2270 
2271 
2272 #ifdef TP_DEBUG
2273  LocalPoint CMSSWhitPosition = hit.localPosition();
2274 
2275  LogDebug ("Pixel Digitizer")
2276  << "\n"
2277  << "Particle ID is: " << hit.particleType() << "\n"
2278  << "Process type: " << hit.processType() << "\n"
2279  << "HitPosition:" << "\n"
2280  << "Hit entry x/y/z: " << hit.entryPoint().x() << " " << hit.entryPoint().y() << " " << hit.entryPoint().z() << " "
2281  << "Hit exit x/y/z: " << hit.exitPoint().x() << " " << hit.exitPoint().y() << " " << hit.exitPoint().z() << " "
2282 
2283  << "Pixel Pos - X: " << hitPositionPixel.x() << " Y: " << hitPositionPixel.y() << "\n"
2284  << "Cart.Cor. - X: " << CMSSWhitPosition.x() << " Y: " << CMSSWhitPosition.y() << "\n"
2285  << "Z=0 Pos - X: " << hitPosition.x() << " Y: " << hitPosition.y() << "\n"
2286 
2287  << "Origin of the template:" << "\n"
2288  << "Pixel Pos - X: " << originPixel.x() << " Y: " << originPixel.y() << "\n"
2289  << "Cart.Cor. - X: " << origin.x() << " Y: " << origin.y() << "\n"
2290  << "\n"
2291  << "Entry/Exit:" << "\n"
2292  << "Entry - X: " << hit.entryPoint().x() << " Y: " << hit.entryPoint().y() << " Z: " << hit.entryPoint().z() << "\n"
2293  << "Exit - X: " << hit.exitPoint().x() << " Y: " << hit.exitPoint().y() << " Z: " << hit.exitPoint().z() << "\n"
2294 
2295  << "Entry - X Pixel: " << hitEntryPointPixel.x() << " Y Pixel: " << hitEntryPointPixel.y() << "\n"
2296  << "Exit - X Pixel: " << hitExitPointPixel.x() << " Y Pixel: " << hitExitPointPixel.y() << "\n"
2297 
2298  << "row min: " << irow_min << " col min: " << icol_min << "\n";
2299 #endif
2300 
2301  if(!(irow_min<=hitrow_max && irow_max>=hitrow_min && icol_min<=hitcol_max && icol_max>=hitcol_min)){
2302  // The clusters do not have an overlap, hence the hit is NOT reweighted
2303  return false;
2304  }
2305 
2306 
2307  float cmToMicrons = 10000.f;
2308 
2309  track[0] = (hitPosition.x() - origin.x() )*cmToMicrons;
2310  track[1] = (hitPosition.y() - origin.y() )*cmToMicrons;
2311  track[2] = 0.0f; //Middle of sensor is origin for Z-axis
2312  track[3] = direction.x();
2313  track[4] = direction.y();
2314  track[5] = direction.z();
2315 
2316  array_2d pixrewgt(boost::extents[TXSIZE][TYSIZE]);
2317 
2318  for(int row = 0; row < TXSIZE; ++row) {
2319  for(int col = 0; col < TYSIZE; ++col) {
2320  pixrewgt[row][col] = 0;
2321  }
2322  }
2323 
2324  for(int row = 0; row < TXSIZE; ++row) {
2325  xdouble[row] = topol->isItBigPixelInX(hitPixel.first + row - THX);
2326  }
2327 
2328  for(int col = 0; col < TYSIZE; ++col) {
2329  ydouble[col] = topol->isItBigPixelInY(hitPixel.second + col - THY);
2330  }
2331 
2332  for(int row = 0; row < TXSIZE; ++row) {
2333  for(int col = 0; col < TYSIZE; ++col) {
2334  //Fill charges into 21x13 Pixel Array with hitPixel in centre
2335  pixrewgt[row][col] = hitSignal[PixelDigi::pixelToChannel(hitPixel.first + row - THX, hitPixel.second + col - THY)];
2336  //std::cout << "Signal in " << hitPixel.first + row - THX << "/" << hitPixel.second + col - THY << " is " << hitSignal[PixelDigi::pixelToChannel(hitPixel.first + row - THX, hitPixel.second + col - THY)] << std::endl;
2337  }
2338  }
2339 
2340  if(PrintClusters){
2341  std::cout << "Cluster before reweighting: " << std::endl;
2342  printCluster(pixrewgt);
2343  }
2344 
2345  int ierr;
2346  // for unirradiated: 2nd argument is IDden
2347  // for irradiated: 2nd argument is IDnum
2348  if (UseReweighting == true){
2349  int ID1 = dbobject_num->getTemplateID(detID);
2350  int ID0 = dbobject_den->getTemplateID(detID);
2351 
2352  if(ID0==ID1){
2353  return false;
2354  }
2355  ierr = PixelTempRewgt2D(ID0, ID1, pixrewgt);
2356  }
2357  else{
2358  ierr = PixelTempRewgt2D(IDden, IDden, pixrewgt);
2359  }
2360  if (ierr!=0){
2361 #ifdef TP_DEBUG
2362  LogDebug ("PixelDigitizer ") << "Cluster Charge Reweighting did not work properly.";
2363 #endif
2364  return false;
2365  }
2366 
2367  if(PrintClusters){
2368  std::cout << "Cluster after reweighting: " << std::endl;
2369  printCluster(pixrewgt);
2370  }
2371 
2372  for(int row = 0; row < TXSIZE; ++row) {
2373  for(int col = 0; col < TYSIZE; ++col) {
2374  float charge = 0;
2375  charge = pixrewgt[row][col];
2376  if( (hitPixel.first + row - THX) >= 0 && (hitPixel.first + row - THX) < topol->nrows() && (hitPixel.second + col - THY) >= 0 && (hitPixel.second + col - THY) < topol->ncolumns() && charge > 0){
2377  chargeAfter += charge;
2378  theSignal[PixelDigi::pixelToChannel(hitPixel.first + row - THX, hitPixel.second + col - THY)] += (makeDigiSimLinks_ ? Amplitude(charge , &hit, hitIndex, tofBin, charge) : Amplitude( charge, charge) ) ;
2379  }
2380  }
2381  }
2382 
2383  if(chargeBefore!=0. && chargeAfter==0.){
2384  return false;
2385  }
2386 
2387  if(PrintClusters){
2388  std::cout << std::endl;
2389  std::cout << "Charges (before->after): " << chargeBefore << " -> " << chargeAfter << std::endl;
2390  std::cout << "Charge loss: " << (1 - chargeAfter/chargeBefore)*100 << " %" << std::endl << std::endl;
2391  }
2392 
2393  return true;
2394 
2395 }
2396 
2397 // *******************************************************************************************************
2405 // *******************************************************************************************************
2406 int SiPixelDigitizerAlgorithm::PixelTempRewgt2D(int id_in, int id_rewgt, array_2d& cluster)
2407 {
2408  // Local variables
2409  int i, j, k, l, kclose;
2410  int nclusx, nclusy, success;
2411  float xsize, ysize, q50i, q100i, q50r, q10r, q100r, xhit2D, yhit2D, qclust, dist2, dmin2;
2412  float xy_in[BXM2][BYM2], xy_rewgt[BXM2][BYM2], xy_clust[TXSIZE][TYSIZE];
2413  int denx_clust[TXSIZE][TYSIZE], deny_clust[TXSIZE][TYSIZE];
2414  int goodWeightsUsed, nearbyWeightsUsed, noWeightsUsed;
2415  float cotalpha, cotbeta;
2416  // success = 0 is returned if everthing is OK
2417  success = 0;
2418 
2419  // Copy the array to remember original charges
2420  array_2d clust(cluster);
2421 
2422  // Take the pixel dimensions from the 2D template
2423  templ2D.getid(id_in);
2424  xsize = templ2D.xsize();
2425  ysize = templ2D.ysize();
2426 
2427  // Calculate the track angles
2428 
2429  if (std::abs(track[5]) > 0.f){
2430  cotalpha = track[3]/track[5]; //if track[5] (direction in z) is 0 the hit is not processed by re-weighting
2431  cotbeta = track[4]/track[5];
2432  } else {
2433  LogDebug ("Pixel Digitizer") << "Reweighting angle is not good!" << std::endl;
2434  return 9; //returned value here indicates that no reweighting was done in this case
2435  }
2436 
2437  // The 2-D templates are defined on a shifted coordinate system wrt the 1D templates
2438  if(ydouble[0]) {
2439  yhit2D = track[1] - cotbeta*track[2] + ysize;
2440  } else {
2441  yhit2D = track[1] - cotbeta*track[2] + 0.5f*ysize;
2442  }
2443  if(xdouble[0]) {
2444  xhit2D = track[0] - cotalpha*track[2] + xsize;
2445  } else {
2446  xhit2D = track[0] - cotalpha*track[2] + 0.5f*xsize;
2447  }
2448 
2449  // Zero the input and output templates
2450  for(i=0; i<BYM2; ++i) {
2451  for(j=0; j<BXM2; ++j) {
2452  xy_in[j][i] = 0.f;
2453  xy_rewgt[j][i] = 0.f;
2454  }
2455  }
2456 
2457  // Next, interpolate the CMSSW template needed to analyze this cluster
2458 
2459  if(!templ2D.xytemp(id_in, cotalpha, cotbeta, xhit2D, yhit2D, ydouble, xdouble, xy_in)) {success = 1;}
2460  if(success != 0){
2461 #ifdef TP_DEBUG
2462  LogDebug("Pixel Digitizer") << "No matching template found" << std::endl;
2463 #endif
2464  return 2;
2465  }
2466 
2467  if(PrintTemplates){
2468  std::cout << "Template unirrad: " << std::endl;
2469  printCluster(xy_in);
2470  }
2471 
2472  q50i = templ2D.s50();
2473  //q50i = 0;
2474  q100i = 2.f*q50i;
2475 
2476  // Check that the cluster container is a 13x21 matrix
2477 
2478  if(cluster.num_dimensions() != 2) {
2479  LogWarning ("Pixel Digitizer") << "Cluster is not 2-dimensional. Return." << std::endl;
2480  return 3;
2481  }
2482  nclusx = (int)cluster.shape()[0];
2483  nclusy = (int)cluster.shape()[1];
2484  if(nclusx != TXSIZE || xdouble.size() != TXSIZE) {
2485  LogWarning ("Pixel Digitizer") << "Sizes in x do not match: nclusx=" << nclusx << " xdoubleSize=" << xdouble.size() << " TXSIZE=" << TXSIZE << ". Return." << std::endl;
2486  return 4;
2487  }
2488  if(nclusy != TYSIZE || ydouble.size() != TYSIZE) {
2489  LogWarning ("Pixel Digitizer") << "Sizes in y do not match. Return." << std::endl;
2490  return 5;
2491  }
2492 
2493  // Sum initial charge in the cluster
2494 
2495  qclust = 0.f;
2496  for(i=0; i<TYSIZE; ++i) {
2497  for(j=0; j<TXSIZE; ++j) {
2498  xy_clust[j][i] = 0.f;
2499  denx_clust[j][i] = 0;
2500  deny_clust[j][i] = 0;
2501  if(cluster[j][i] > q100i) {
2502  qclust += cluster[j][i];
2503  }
2504  }
2505  }
2506 
2507  // Next, interpolate the physical output template needed to reweight
2508 
2509  if(!templ2D.xytemp(id_rewgt, cotalpha, cotbeta, xhit2D, yhit2D, ydouble, xdouble, xy_rewgt)) {success = 1;}
2510 
2511  if(PrintTemplates){
2512  std::cout << "Template irrad: " << std::endl;
2513  printCluster(xy_rewgt);
2514  }
2515 
2516  q50r = templ2D.s50();
2517  q100r = 2.f*q50r;
2518  q10r = 0.2f*q50r;
2519 
2520  // Find all non-zero denominator pixels in the input template and generate "inside" weights
2521 
2522  int ntpix = 0;
2523  int ncpix = 0;
2524  std::vector<int> ytclust;
2525  std::vector<int> xtclust;
2526  std::vector<int> ycclust;
2527  std::vector<int> xcclust;
2528  qclust = 0.f;
2529  for(i=0; i<TYSIZE; ++i) {
2530  for(j=0; j<TXSIZE; ++j) {
2531  if(xy_in[j+1][i+1] > q100i) {
2532  ++ntpix;
2533  ytclust.push_back(i);
2534  xtclust.push_back(j);
2535  xy_clust[j][i] = xy_rewgt[j+1][i+1]/xy_in[j+1][i+1];
2536  denx_clust[j][i] = j;
2537  deny_clust[j][i] = i;
2538  }
2539  }
2540  }
2541 
2542  // Find all non-zero numerator pixels not matched to denominator in the output template and generate "inside" weights
2543 
2544  for(i=0; i<TYSIZE; ++i) {
2545  for(j=0; j<TXSIZE; ++j) {
2546  if(xy_rewgt[j+1][i+1] > q10r && xy_clust[j][i] == 0.f && ntpix>0) {
2547  // Search for nearest denominator pixel
2548  dmin2 = 10000.f; kclose = 0;
2549  for(k=0; k<ntpix; ++k) {
2550  dist2=(i-ytclust[k])*(i-ytclust[k])+0.44444f*(j-xtclust[k])*(j-xtclust[k]);
2551  if(dist2 < dmin2) {
2552  dmin2 = dist2;
2553  kclose = k;
2554  }
2555  }
2556  xy_clust[j][i] = xy_rewgt[j+1][i+1]/xy_in[xtclust[kclose]+1][ytclust[kclose]+1];
2557  denx_clust[j][i] = xtclust[kclose];
2558  deny_clust[j][i] = ytclust[kclose];
2559  }
2560  }
2561  }
2562 
2563  if(PrintTemplates){
2564  std::cout << "Weights:" << std::endl;
2565  printCluster(xy_clust);
2566  }
2567 
2568 
2569 
2570  // Do the reweighting
2571  goodWeightsUsed = 0;
2572  nearbyWeightsUsed = 0;
2573  noWeightsUsed = 0;
2574 
2575  for(i=0; i<TYSIZE; ++i) {
2576  for(j=0; j<TXSIZE; ++j) {
2577  if(xy_clust[j][i] > 0.f) {
2578  cluster[j][i] = xy_clust[j][i]*clust[denx_clust[j][i]][deny_clust[j][i]];
2579  if(cluster[j][i] > q100r) {
2580  qclust += cluster[j][i];
2581  }
2582  if(cluster[j][i] > 0) {
2583  goodWeightsUsed++;
2584  }
2585  } else {
2586  if(clust[j][i] > 0.f) {
2587  ++ncpix;
2588  ycclust.push_back(i);
2589  xcclust.push_back(j);
2590  }
2591  }
2592  }
2593  }
2594 
2595  // Now reweight pixels outside of template footprint using closest weights
2596 
2597  if(ncpix > 0) {
2598  for(l=0; l<ncpix; ++l) {
2599  i=ycclust[l]; j=xcclust[l];
2600  dmin2 = 10000.f; kclose = 0;
2601  for(k=0; k<ntpix; ++k) {
2602  dist2=(i-ytclust[k])*(i-ytclust[k])+0.44444f*(j-xtclust[k])*(j-xtclust[k]);
2603  if(dist2 < dmin2) {
2604  dmin2 = dist2;
2605  kclose = k;
2606  }
2607  }
2608  if(dmin2 < 5.f) {
2609  nearbyWeightsUsed++;
2610  cluster[j][i] *= xy_clust[xtclust[kclose]][ytclust[kclose]];
2611  if(cluster[j][i] > q100r) {
2612  qclust += cluster[j][i];
2613  }
2614  } else {
2615  noWeightsUsed++;
2616  cluster[j][i] = 0.f;
2617  }
2618  }
2619  }
2620 
2621  return success;
2622 } // PixelTempRewgt2D
2623 
2625 {
2626  for(int col = 0; col < TYSIZE; ++col) {
2627  for(int row = 0; row < TXSIZE; ++row) {
2628  std::cout << std::setw(10) << std::setprecision(0) << std::fixed;
2629  std::cout << cluster[row][col];
2630  }
2631  std::cout << std::endl;
2632  }
2633  std::cout.copyfmt(std::ios(nullptr));
2634 }
2635 
2637 {
2638  for(int col = 0; col < BYM2; ++col) {
2639  for(int row = 0; row < BXM2; ++row) {
2640  std::cout << std::setw(10) << std::setprecision(0) << std::fixed;
2641  std::cout << arr[row][col];
2642  }
2643  std::cout << std::endl;
2644  }
2645  std::cout.copyfmt(std::ios(nullptr));
2646 }
2647 
2649 {
2650  for(int col = 0; col < TYSIZE; ++col) {
2651  for(int row = 0; row < TXSIZE; ++row) {
2652  std::cout << std::setw(10) << std::fixed;
2653  std::cout << arr[row][col];
2654  }
2655  std::cout << std::endl;
2656  }
2657  std::cout.copyfmt(std::ios(nullptr));
2658 }
int adc(sample_type sample)
get the ADC sample (12 bits)
#define LogDebug(id)
void init(const edm::EventSetup &es)
size
Write out results.
const SiPixel2DTemplateDBObject * dbobject_den
GlobalPoint toGlobal(const Point2DBase< Scalar, LocalTag > lp) const
Definition: Surface.h:106
T getParameter(std::string const &) const
Map map_
virtual int nrows() const =0
const GeomDetType & type() const override
void pixel_inefficiency_db(uint32_t detID)
boost::transform_iterator< IterHelp, const_IdIter > const_iterator
signal_map_type::const_iterator signal_map_const_iterator
static const TGPicture * info(bool iBackgroundIsBlack)
Local3DVector LocalVector
Definition: LocalVector.h:12
float tof() const
deprecated name for timeOfFlight()
Definition: PSimHit.h:72
float xsize()
pixel x-size (microns)
edm::ESHandle< SiPixelFedCablingMap > map_
void init_DynIneffDB(const edm::EventSetup &, const unsigned int &)
virtual int rowsperroc() const =0
Point3DBase< Scalar, LocalTag > LocalPoint
Definition: Definitions.h:32
bool isBarrel() const
Definition: GeomDetType.cc:13
T y() const
Definition: PV2DBase.h:46
std::map< int, CalParameters, std::less< int > > initCal() const
const std::unique_ptr< SiPixelGainCalibrationOfflineSimService > theSiPixelGainCalibrationService_
bool xytemp(float xhit, float yhit, bool ydouble[21+2], bool xdouble[13+2], float template2d[13+2][21+2], bool dervatives, float dpdx2d[2][13+2][21+2], float &QTemplate)
LocalVector DriftDirection(const PixelGeomDetUnit *pixdet, const GlobalVector &bfield, const DetId &detId) const
void induce_signal(std::vector< PSimHit >::const_iterator inputBegin, std::vector< PSimHit >::const_iterator inputEnd, const PSimHit &hit, const size_t hitIndex, const unsigned int tofBin, const PixelGeomDetUnit *pixdet, const std::vector< SignalPoint > &collection_points)
SiPixelDigitizerAlgorithm(const edm::ParameterSet &conf)
CaloTopology const * topology(0)
const DetContainer & detUnits() const override
Returm a vector of all GeomDet.
const std::vector< float > & getMix_TrueInteractions() const
probabilityVec getProbabilities(const unsigned int puBin) const
#define TXSIZE
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())
edm::ESHandle< SiPixelQualityProbabilities > scenarioProbabilityHandle
const std::vector< int > & getMix_bunchCrossing() const
unsigned int pxbLadder(const DetId &id) const
constexpr uint32_t rawId() const
get the raw id
Definition: DetId.h:50
T y() const
Definition: PV3DBase.h:63
bool exists(std::string const &parameterName) const
checks if a parameter exists
virtual std::pair< float, float > pitch() const =0
std::unique_ptr< PixelFEDChannelCollection > PixelFEDChannelCollection_
const Bounds & bounds() const
Definition: Surface.h:120
std::vector< std::vector< double > > thePUEfficiency
unsigned int pxbModule(const DetId &id) const
const Int_t ysize
bool IsRocBad(const uint32_t &detid, const short &rocNb) const
#define nullptr
virtual bool isItBigPixelInX(int ixbin) const =0
edm::ESHandle< TrackerGeometry > geom_
const Plane & surface() const
The nominal surface of the GeomDet.
Definition: GeomDet.h:42
float s50()
1/2 of the pixel threshold signal in adc units
SigmaX
Definition: gun_cff.py:25
#define THX
identify pixel inside single ROC
Definition: LocalPixel.h:7
const SiPixel2DTemplateDBObject * dbobject_num
void make_digis(float thePixelThresholdInE, uint32_t detID, const PixelGeomDetUnit *pixdet, std::vector< PixelDigi > &digis, std::vector< PixelDigiSimLink > &simlinks, const TrackerTopology *tTopo) const
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
#define BXM2
bool isThere(GeomDetEnumerators::SubDetector subdet) const
const std::vector< uint32_t > getDetIdmasks() const
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
bunchspace
in terms of 25 ns
const PixelFEDChannelCollectionMap * quality_map
const std::map< int, CalParameters, std::less< int > > calmap
virtual int colsperroc() const =0
boost::multi_array< float, 2 > array_2d
Local3DPoint localPosition() const
Definition: PSimHit.h:44
float pixel_aging(const PixelAging &aging, const PixelGeomDetUnit *pixdet, const TrackerTopology *tTopo) const
std::map< uint32_t, std::vector< double > > PixelGeomFactorsROCBigPixels
T sqrt(T t)
Definition: SSEVec.h:18
void printCluster(array_2d &cluster)
T z() const
Definition: PV3DBase.h:64
static int pixelToChannelROC(const int rowROC, const int colROC)
Definition: PixelIndices.h:250
virtual MeasurementPoint measurementPosition(const LocalPoint &) const =0
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:40
constexpr int subdetId() const
get the contents of the subdetector field (not cast into any detector&#39;s numbering enum) ...
Definition: DetId.h:41
virtual bool isItBigPixelInY(int iybin) const =0
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
DetId geographicalId() const
The label of this GeomDet.
Definition: GeomDet.h:79
#define BYM2
double f[11][100]
virtual int channel(const LocalPoint &p) const =0
const std::vector< disabledModuleType > getBadComponentList() const
T min(T a, T b)
Definition: MathUtil.h:58
std::vector< LinkConnSpec >::const_iterator IT
#define THY
float pabs() const
fast and more accurate access to momentumAtEntry().mag()
Definition: PSimHit.h:63
bool isTrackerPixel() const
Definition: GeomDetType.cc:29
signal_map_type::iterator signal_map_iterator
double p2[4]
Definition: TauolaWrapper.h:90
std::unique_ptr< PixelFEDChannelCollection > chooseScenario(PileupMixingContent *puInfo, CLHEP::HepRandomEngine *)
edm::ESHandle< SiPixelLorentzAngle > SiPixelLorentzAngle_
unsigned int pxfModule(const DetId &id) const
ii
Definition: cuy.py:590
void setSimAccumulator(const std::map< uint32_t, std::map< int, int > > &signalMap)
int k[5][pyjets_maxn]
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
#define TYSIZE
edm::ESHandle< SiPixelQuality > SiPixelBadModule_
short getTemplateID(const uint32_t &detid) const
std::map< uint32_t, std::vector< double > > PixelGeomFactorsROCStdPixels
virtual float thickness() const =0
SigmaY
Definition: gun_cff.py:26
void primary_ionization(const PSimHit &hit, std::vector< EnergyDepositUnit > &ionization_points, CLHEP::HepRandomEngine *) const
void init_from_db(const edm::ESHandle< TrackerGeometry > &, const edm::ESHandle< SiPixelDynamicInefficiency > &)
void calculateInstlumiFactor(PileupMixingContent *puInfo)
static std::pair< int, int > channelToPixel(int ch)
Definition: PixelDigi.h:62
virtual const PixelTopology & specificTopology() const
Returns a reference to the pixel proxy topology.
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
static bool pushfile(int filenum, std::vector< SiPixelTemplateStore2D > &pixelTemp, std::string dir="")
const sipixelobjects::PixelROC * findItem(const sipixelobjects::CablingPathToDetUnit &path) const final
virtual LocalPoint localPosition(const MeasurementPoint &) const =0
edm::ESHandle< SiPixelDynamicInefficiency > SiPixelDynamicInefficiency_
chan
lumi = TPaveText(lowX+0.38, lowY+0.061, lowX+0.45, lowY+0.161, "NDC") lumi.SetBorderSize( 0 ) lumi...
unsigned short processType() const
Definition: PSimHit.h:118
float ysize()
pixel y-size (microns)
unsigned int layer(const DetId &id) const
std::vector< sipixelobjects::CablingPathToDetUnit > pathToDetUnit(uint32_t rawDetId) const final
float missCalibrate(uint32_t detID, const TrackerTopology *tTopo, const PixelGeomDetUnit *pixdet, int col, int row, float amp) const
bool matches(const DetId &, const DetId &, const std::vector< uint32_t > &)
std::vector< edm::ParameterSet > Parameters
float energyLoss() const
The energy deposit in the PSimHit, in ???.
Definition: PSimHit.h:75
HLT enums.
virtual int ncolumns() const =0
int particleType() const
Definition: PSimHit.h:85
double p1[4]
Definition: TauolaWrapper.h:89
T get() const
Definition: EventSetup.h:68
col
Definition: cuy.py:1010
const TrackerGeomDet * idToDet(DetId) const override
Signal rand(Signal arg)
Definition: vlib.cc:442
static unsigned int const shift
float getLorentzAngle(const uint32_t &) const
const std::map< unsigned int, std::vector< double > > & getPUFactors() const
const RotationType & rotation() const
PixelAging(const edm::ParameterSet &conf, bool AddPixelAging, int NumberOfBarrelLayers, int NumberOfEndcapDisks)
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
virtual SubDetector subDetector() const
Which subdetector.
Definition: GeomDet.cc:44
const Int_t xsize
T x() const
Definition: PV2DBase.h:45
T x() const
Definition: PV3DBase.h:62
const PositionType & position() const
int PixelTempRewgt2D(int id_gen, int id_rewgt, array_2d &cluster)
T const * product() const
Definition: ESHandle.h:84
Definition: vlib.h:208
Local3DPoint entryPoint() const
Entry point in the local Det frame.
Definition: PSimHit.h:35
unsigned int pxfPanel(const DetId &id) const
const std::map< unsigned int, double > & getColGeomFactors() const
bool hitSignalReweight(const PSimHit &hit, std::map< int, float, std::less< int > > &hit_signal, const size_t hitIndex, const unsigned int tofBin, const PixelTopology *topol, uint32_t detID, signal_map_type &theSignal, unsigned short int processType)
*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:45
const std::map< unsigned int, double > & getPixelGeomFactors() const
Definition: aging.py:1
GlobalPixel toGlobal(const LocalPixel &loc) const
Definition: PixelROC.h:59
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 *)
constexpr Detector det() const
get the detector field from this detid
Definition: DetId.h:39
const std::map< unsigned int, double > & getChipGeomFactors() const