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