Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2024-04-06 11:58:00

0001 #include "EcalTPGParamBuilder.h"
0002 #include "EcalTPGDBApp.h"
0003 
0004 #include "Geometry/CaloGeometry/interface/CaloCellGeometry.h"
0005 
0006 #include "DataFormats/EcalDetId/interface/EcalSubdetector.h"
0007 #include "DataFormats/EcalDetId/interface/EBDetId.h"
0008 #include "DataFormats/EcalDetId/interface/EEDetId.h"
0009 
0010 #include "CondFormats/EcalObjects/interface/EcalMGPAGainRatio.h"
0011 
0012 //modif-alex-27-july-2015
0013 #include "CalibCalorimetry/EcalLaserCorrection/interface/EcalLaserDbService.h"
0014 #include "CalibCalorimetry/EcalLaserCorrection/interface/EcalLaserDbRecord.h"
0015 
0016 #include "SimCalorimetry/EcalSimAlgos/interface/EcalSimParameterMap.h"
0017 #include "FWCore/MessageLogger/interface/MessageLogger.h"
0018 
0019 #include <TF1.h>
0020 #include <TH2F.h>
0021 #include <TFile.h>
0022 #include <TNtuple.h>
0023 #include <ctime>
0024 #include <iomanip>
0025 #include <fstream>
0026 #include <iostream>
0027 #include <string>
0028 #include <sstream>
0029 
0030 using namespace std;
0031 
0032 double oneOverEtResolEt(double* x, double* par) {
0033   double Et = x[0];
0034   if (Et < 1e-6)
0035     return 1. / par[1];  // to avoid division by 0.
0036   double resolEt_overEt =
0037       sqrt((par[0] / sqrt(Et)) * (par[0] / sqrt(Et)) + (par[1] / Et) * (par[1] / Et) + par[2] * par[2]);
0038   return 1. / (Et * resolEt_overEt);
0039 }
0040 
0041 EcalTPGParamBuilder::EcalTPGParamBuilder(edm::ParameterSet const& pSet)
0042     : theEndcapGeometryToken_(esConsumes(edm::ESInputTag("", "EcalEndcap"))),
0043       theBarrelGeometryToken_(esConsumes(edm::ESInputTag("", "EcalBarrel"))),
0044       eTTmapToken_(esConsumes()),
0045       ecalmappingToken_(esConsumes()),
0046       ecalLaserAlphasToken_(esConsumes()),
0047       ecalLaserAPDPNRatiosToken_(esConsumes()),
0048       ecalPedestalsToken_(esConsumes()),
0049       ecalIntercalibConstantsToken_(esConsumes()),
0050       ecalGainRatiosToken_(esConsumes()),
0051       ecalADCToGeVConstantToken_(esConsumes()),
0052       xtal_LSB_EB_(0),
0053       xtal_LSB_EE_(0),
0054       nSample_(5),
0055       complement2_(7),
0056       shapeEB_(consumesCollector()),  // EBShape, EEShape are fetched now from DB (2018.05.22 K. Theofilatos)
0057       shapeEE_(consumesCollector()) {
0058   ped_conf_id_ = 0;
0059   lin_conf_id_ = 0;
0060   lut_conf_id_ = 0;
0061   wei_conf_id_ = 0;
0062   wei2_conf_id_ = 0;
0063   fgr_conf_id_ = 0;
0064   sli_conf_id_ = 0;
0065   spi_conf_id_ = 0;  //modif-alex 21/01/11
0066   del_conf_id_ = 0;  //modif-alex 21/01/11
0067   bxt_conf_id_ = 0;
0068   btt_conf_id_ = 0;
0069   bst_conf_id_ = 0;
0070   coke_conf_id_ = 0;
0071   tag_ = "";
0072   version_ = 0;
0073 
0074   m_write_ped = 1;
0075   m_write_lin = 1;
0076   m_write_lut = 1;
0077   m_write_wei = 1;
0078   m_write_wei2 = 1;
0079   m_write_fgr = 1;
0080   m_write_sli = 1;
0081   m_write_spi = 1;  //modif-alex 21/01/11
0082   m_write_del = 1;  //modif-alex 21/01/11
0083   m_write_bxt = 1;
0084   m_write_btt = 1;
0085   m_write_bst = 1;
0086 
0087   writeToDB_ = pSet.getParameter<bool>("writeToDB");
0088   DBEE_ = pSet.getParameter<bool>("allowDBEE");
0089   string DBsid = pSet.getParameter<std::string>("DBsid");
0090   string DBuser = pSet.getParameter<std::string>("DBuser");
0091   string DBpass = pSet.getParameter<std::string>("DBpass");
0092   //uint32_t DBport = pSet.getParameter<unsigned int>("DBport") ;
0093 
0094   tag_ = pSet.getParameter<std::string>("TPGtag");
0095   version_ = pSet.getParameter<unsigned int>("TPGversion");
0096 
0097   m_write_ped = pSet.getParameter<unsigned int>("TPGWritePed");
0098   m_write_lin = pSet.getParameter<unsigned int>("TPGWriteLin");
0099   m_write_lut = pSet.getParameter<unsigned int>("TPGWriteLut");
0100   m_write_wei = pSet.getParameter<unsigned int>("TPGWriteWei");
0101   m_write_wei2 = pSet.getParameter<unsigned int>("TPGWriteWei2");
0102   m_write_fgr = pSet.getParameter<unsigned int>("TPGWriteFgr");
0103   m_write_sli = pSet.getParameter<unsigned int>("TPGWriteSli");
0104   m_write_spi = pSet.getParameter<unsigned int>("TPGWriteSpi");  //modif-alex 21/01/11
0105   m_write_del = pSet.getParameter<unsigned int>("TPGWriteDel");  //modif-alex 21/01/11
0106   m_write_bxt = pSet.getParameter<unsigned int>("TPGWriteBxt");
0107   m_write_btt = pSet.getParameter<unsigned int>("TPGWriteBtt");
0108   m_write_bst = pSet.getParameter<unsigned int>("TPGWriteBst");
0109 
0110   btt_conf_id_ = m_write_btt;
0111   bxt_conf_id_ = m_write_bxt;
0112   bst_conf_id_ = m_write_bst;
0113 
0114   if (m_write_ped != 0 && m_write_ped != 1)
0115     ped_conf_id_ = m_write_ped;
0116 
0117   if (writeToDB_)
0118     edm::LogInfo("TopInfo") << "data will be saved with tag and version=" << tag_ << ".version" << version_ << "\n";
0119   db_ = new EcalTPGDBApp(DBsid, DBuser, DBpass);
0120 
0121   writeToFiles_ = pSet.getParameter<bool>("writeToFiles");
0122   if (writeToFiles_) {
0123     std::string outFile = pSet.getParameter<std::string>("outFile");
0124     out_file_ = new std::ofstream(outFile.c_str(), std::ios::out);
0125   }
0126   geomFile_ = new std::ofstream("geomFile.txt", std::ios::out);
0127 
0128   useTransverseEnergy_ = pSet.getParameter<bool>("useTransverseEnergy");
0129 
0130   Et_sat_EB_ = pSet.getParameter<double>("Et_sat_EB");
0131   Et_sat_EE_ = pSet.getParameter<double>("Et_sat_EE");
0132   sliding_ = pSet.getParameter<unsigned int>("sliding");
0133   weight_timeShift_ = pSet.getParameter<double>("weight_timeShift");
0134   sampleMax_ = pSet.getParameter<unsigned int>("weight_sampleMax");
0135   weight_unbias_recovery_ = pSet.getParameter<bool>("weight_unbias_recovery");
0136 
0137   weight_even_computeFromShape_ = pSet.getParameter<bool>("weight_even_computeFromShape");
0138   weight_even_idMapFile_ = pSet.getParameter<std::string>("weight_even_idMapFile");
0139   weight_even_weightGroupFile_ = pSet.getParameter<std::string>("weight_even_weightGroupFile");
0140   weight_odd_idMapFile_ = pSet.getParameter<std::string>("weight_odd_idMapFile");
0141   weight_odd_weightGroupFile_ = pSet.getParameter<std::string>("weight_odd_weightGroupFile");
0142 
0143   weight_useDoubleWeights_ = pSet.getParameter<bool>("weight_useDoubleWeights");
0144   TPmode_EnableEBOddFilter_ = pSet.getParameter<bool>("TPmode_EnableEBOddFilter");
0145   TPmode_EnableEEOddFilter_ = pSet.getParameter<bool>("TPmode_EnableEEOddFilter");
0146   TPmode_EnableEBOddPeakFinder_ = pSet.getParameter<bool>("TPmode_EnableEBOddPeakFinder");
0147   TPmode_EnableEEOddPeakFinder_ = pSet.getParameter<bool>("TPmode_EnableEEOddPeakFinder");
0148   TPmode_DisableEBEvenPeakFinder_ = pSet.getParameter<bool>("TPmode_DisableEBEvenPeakFinder");
0149   TPmode_DisableEEEvenPeakFinder_ = pSet.getParameter<bool>("TPmode_DisableEEEvenPeakFinder");
0150   TPmode_FenixEBStripOutput_ = pSet.getParameter<unsigned int>("TPmode_FenixEBStripOutput");
0151   TPmode_FenixEEStripOutput_ = pSet.getParameter<unsigned int>("TPmode_FenixEEStripOutput");
0152   TPmode_FenixEBStripInfobit2_ = pSet.getParameter<unsigned int>("TPmode_FenixEBStripInfobit2");
0153   TPmode_FenixEEStripInfobit2_ = pSet.getParameter<unsigned int>("TPmode_FenixEEStripInfobit2");
0154   TPmode_FenixEBTcpOutput_ = pSet.getParameter<unsigned int>("TPmode_FenixEBTcpOutput");
0155   TPmode_FenixEBTcpInfobit1_ = pSet.getParameter<unsigned int>("TPmode_FenixEBTcpInfobit1");
0156   TPmode_FenixEETcpOutput_ = pSet.getParameter<unsigned int>("TPmode_FenixEETcpOutput");
0157   TPmode_FenixEETcpInfobit1_ = pSet.getParameter<unsigned int>("TPmode_FenixEETcpInfobit1");
0158 
0159   forcedPedestalValue_ = pSet.getParameter<int>("forcedPedestalValue");
0160   forceEtaSlice_ = pSet.getParameter<bool>("forceEtaSlice");
0161 
0162   LUT_option_ = pSet.getParameter<std::string>("LUT_option");
0163   LUT_threshold_EB_ = pSet.getParameter<double>("LUT_threshold_EB");
0164   LUT_threshold_EE_ = pSet.getParameter<double>("LUT_threshold_EE");
0165   LUT_stochastic_EB_ = pSet.getParameter<double>("LUT_stochastic_EB");
0166   LUT_noise_EB_ = pSet.getParameter<double>("LUT_noise_EB");
0167   LUT_constant_EB_ = pSet.getParameter<double>("LUT_constant_EB");
0168   LUT_stochastic_EE_ = pSet.getParameter<double>("LUT_stochastic_EE");
0169   LUT_noise_EE_ = pSet.getParameter<double>("LUT_noise_EE");
0170   LUT_constant_EE_ = pSet.getParameter<double>("LUT_constant_EE");
0171 
0172   TTF_lowThreshold_EB_ = pSet.getParameter<double>("TTF_lowThreshold_EB");
0173   TTF_highThreshold_EB_ = pSet.getParameter<double>("TTF_highThreshold_EB");
0174   TTF_lowThreshold_EE_ = pSet.getParameter<double>("TTF_lowThreshold_EE");
0175   TTF_highThreshold_EE_ = pSet.getParameter<double>("TTF_highThreshold_EE");
0176 
0177   FG_lowThreshold_EB_ = pSet.getParameter<double>("FG_lowThreshold_EB");
0178   FG_highThreshold_EB_ = pSet.getParameter<double>("FG_highThreshold_EB");
0179   FG_lowRatio_EB_ = pSet.getParameter<double>("FG_lowRatio_EB");
0180   FG_highRatio_EB_ = pSet.getParameter<double>("FG_highRatio_EB");
0181   FG_lut_EB_ = pSet.getParameter<unsigned int>("FG_lut_EB");
0182   FG_Threshold_EE_ = pSet.getParameter<double>("FG_Threshold_EE");
0183   FG_lut_strip_EE_ = pSet.getParameter<unsigned int>("FG_lut_strip_EE");
0184   FG_lut_tower_EE_ = pSet.getParameter<unsigned int>("FG_lut_tower_EE");
0185   SFGVB_Threshold_ = pSet.getParameter<unsigned int>("SFGVB_Threshold");
0186   SFGVB_lut_ = pSet.getParameter<unsigned int>("SFGVB_lut");
0187   SFGVB_SpikeKillingThreshold_ = pSet.getParameter<int>("SFGVB_SpikeKillingThreshold");  //modif-alex 21/01/11
0188   pedestal_offset_ = pSet.getParameter<unsigned int>("pedestal_offset");
0189 
0190   useInterCalibration_ = pSet.getParameter<bool>("useInterCalibration");
0191   H2_ = pSet.getUntrackedParameter<bool>("H2", false);
0192 
0193   useTransparencyCorr_ = false;
0194   useTransparencyCorr_ = pSet.getParameter<bool>("useTransparencyCorr");            //modif-alex-25/04/2012
0195   Transparency_Corr_ = pSet.getParameter<std::string>("transparency_corrections");  //modif-alex-30/01/2012
0196 
0197   //modif-alex-23/02/2011
0198   //convert the spike killing first from GeV to ADC (10 bits)
0199   //depending on the saturation scale: Et_sat_EB_
0200   if (SFGVB_SpikeKillingThreshold_ == -1 || (SFGVB_SpikeKillingThreshold_ > Et_sat_EB_))
0201     SFGVB_SpikeKillingThreshold_ = 1023;  //nokilling
0202   else
0203     SFGVB_SpikeKillingThreshold_ = int(SFGVB_SpikeKillingThreshold_ * 1024 / Et_sat_EB_);
0204   edm::LogInfo("TopInfo") << "INFO:SPIKE KILLING THRESHOLD (ADC)=" << SFGVB_SpikeKillingThreshold_ << "\n";
0205 
0206   //modif-alex-02/02/11
0207   //TIMING information
0208   TimingDelays_EB_ = pSet.getParameter<std::string>("timing_delays_EB");
0209   TimingDelays_EE_ = pSet.getParameter<std::string>("timing_delays_EE");
0210   TimingPhases_EB_ = pSet.getParameter<std::string>("timing_phases_EB");
0211   TimingPhases_EE_ = pSet.getParameter<std::string>("timing_phases_EE");
0212 
0213   std::ostringstream ss;
0214   //  edm::LogInfo("TopInfo") << "INFO: READING timing files" << "\n";
0215   ss << "INFO: READING timing files\n";
0216   std::ifstream delay_eb(TimingDelays_EB_.c_str());
0217   if (!delay_eb)
0218     edm::LogError("TopInfo") << "ERROR: File " << TimingDelays_EB_.c_str() << " could not be opened"
0219                              << "\n";
0220   std::ifstream delay_ee(TimingDelays_EE_.c_str());
0221   if (!delay_ee)
0222     edm::LogError("TopInfo") << "ERROR: File " << TimingDelays_EE_.c_str() << " could not be opened"
0223                              << "\n";
0224   std::ifstream phase_eb(TimingPhases_EB_.c_str());
0225   if (!phase_eb)
0226     edm::LogError("TopInfo") << "ERROR: File " << TimingPhases_EB_.c_str() << " could not be opened"
0227                              << "\n";
0228   std::ifstream phase_ee(TimingPhases_EE_.c_str());
0229   if (!phase_ee)
0230     edm::LogError("TopInfo") << "ERROR: File " << TimingPhases_EE_.c_str() << " could not be opened"
0231                              << "\n";
0232 
0233   char buf[1024];
0234   //READING DELAYS EB
0235   delay_eb.getline(buf, sizeof(buf), '\n');
0236   while (delay_eb) {
0237     std::stringstream sin(buf);
0238 
0239     int tcc;
0240     sin >> tcc;
0241 
0242     vector<int> vec_delays_eb;
0243     for (int ieb = 0; ieb < 68; ++ieb) {
0244       int time_delay = -1;
0245       sin >> time_delay;
0246       vec_delays_eb.push_back(time_delay);
0247       if (time_delay == -1)
0248         edm::LogError("TopInfo") << "ERROR:Barrel timing delay -1, check file"
0249                                  << "\n";
0250     }
0251 
0252     if (vec_delays_eb.size() != 68)
0253       edm::LogError("TopInfo") << "ERROR:Barrel timing delay wrong, not enough towers, check file"
0254                                << "\n";
0255 
0256     if (delays_EB_.find(tcc) == delays_EB_.end())
0257       delays_EB_.insert(make_pair(tcc, vec_delays_eb));
0258 
0259     //    edm::LogInfo("TopInfo") << tcc << "\n";
0260     ss << tcc;
0261     for (unsigned int ieb = 0; ieb < vec_delays_eb.size(); ++ieb)
0262       //      edm::LogInfo("TopInfo") << vec_delays_eb[ieb] << "\n";
0263       ss << " " << vec_delays_eb[ieb];
0264     delay_eb.getline(buf, sizeof(buf), '\n');
0265     ss << "\n";
0266   }  //loop delay file EB
0267   delay_eb.close();
0268 
0269   //READING PHASES EB
0270   phase_eb.getline(buf, sizeof(buf), '\n');
0271   while (phase_eb) {
0272     std::stringstream sin(buf);
0273     int tcc;
0274     sin >> tcc;
0275 
0276     vector<int> vec_phases_eb;
0277     for (unsigned int ieb = 0; ieb < 68; ++ieb) {
0278       int time_phase = -1;
0279       sin >> time_phase;
0280       vec_phases_eb.push_back(time_phase);
0281       if (time_phase == -1)
0282         edm::LogError("TopInfo") << "ERROR:Barrel timing phase -1, check file"
0283                                  << "\n";
0284     }
0285 
0286     if (vec_phases_eb.size() != 68)
0287       edm::LogError("TopInfo") << "ERROR:Barrel timing phase wrong, not enough towers, check file"
0288                                << "\n";
0289 
0290     if (phases_EB_.find(tcc) == phases_EB_.end())
0291       phases_EB_.insert(make_pair(tcc, vec_phases_eb));
0292 
0293     //    edm::LogInfo("TopInfo") << tcc << "\n";
0294     ss << tcc;
0295     for (unsigned int ieb = 0; ieb < vec_phases_eb.size(); ++ieb)
0296       //      edm::LogInfo("TopInfo") << vec_phases_eb[ieb] << "\n";
0297       ss << " " << vec_phases_eb[ieb];
0298     phase_eb.getline(buf, sizeof(buf), '\n');
0299     ss << "\n";
0300   }  //loop phase file EB
0301   phase_eb.close();
0302 
0303   //READING DELAYS EE//------------------------------------------------
0304   delay_ee.getline(buf, sizeof(buf), '\n');
0305   while (delay_ee) {
0306     std::stringstream sin(buf);
0307     int tcc;
0308     sin >> tcc;
0309 
0310     vector<int> vec_delays_ee;
0311     for (unsigned int iee = 0; iee < 48; ++iee) {
0312       int time_delay = -1;
0313       sin >> time_delay;
0314       vec_delays_ee.push_back(time_delay);
0315       if (time_delay == -1)
0316         edm::LogError("TopInfo") << "ERROR:EE timing delay -1, check file"
0317                                  << "\n";
0318     }
0319 
0320     if (vec_delays_ee.size() != 48)
0321       edm::LogError("TopInfo") << "ERROR:EE timing delay wrong, not enough towers, check file"
0322                                << "\n";
0323 
0324     if (delays_EE_.find(tcc) == delays_EE_.end())
0325       delays_EE_.insert(make_pair(tcc, vec_delays_ee));
0326 
0327     //    edm::LogInfo("TopInfo") << tcc << "\n";
0328     ss << tcc;
0329     for (unsigned int iee = 0; iee < vec_delays_ee.size(); ++iee)
0330       //      edm::LogInfo("TopInfo") << vec_delays_ee[iee] << "\n";
0331       ss << " " << vec_delays_ee[iee];
0332     ss << "\n";
0333     delay_ee.getline(buf, sizeof(buf), '\n');
0334   }  //loop delay file EE
0335   delay_ee.close();
0336 
0337   //READING PHASES EE
0338   phase_ee.getline(buf, sizeof(buf), '\n');
0339   while (phase_ee) {
0340     std::stringstream sin(buf);
0341     int tcc;
0342     sin >> tcc;
0343 
0344     vector<int> vec_phases_ee;
0345     for (unsigned int iee = 0; iee < 48; ++iee) {
0346       int time_phase = -1;
0347       sin >> time_phase;
0348       vec_phases_ee.push_back(time_phase);
0349       if (time_phase == -1)
0350         edm::LogError("TopInfo") << "ERROR:EE timing phase -1, check file"
0351                                  << "\n";
0352     }
0353 
0354     if (vec_phases_ee.size() != 48)
0355       edm::LogError("TopInfo") << "ERROR:EE timing phase wrong, not enough towers, check file"
0356                                << "\n";
0357 
0358     if (phases_EE_.find(tcc) == phases_EE_.end())
0359       phases_EE_.insert(make_pair(tcc, vec_phases_ee));
0360     //    edm::LogInfo("TopInfo") << tcc << "\n";
0361     ss << tcc;
0362     for (unsigned int iee = 0; iee < vec_phases_ee.size(); ++iee)
0363       //      edm::LogInfo("TopInfo") << vec_phases_ee[iee] << "\n";
0364       ss << " " << vec_phases_ee[iee];
0365     ss << "\n";
0366     phase_ee.getline(buf, sizeof(buf), '\n');
0367   }  //loop phase file EE
0368   phase_ee.close();
0369 
0370   //  edm::LogInfo("TopInfo") << "INFO: DONE reading timing files for EB and EE" << "\n";
0371   ss << "INFO: DONE reading timing files for EB and EE\n";
0372   edm::LogInfo("TopInfo") << ss.str();
0373 }
0374 
0375 EcalTPGParamBuilder::~EcalTPGParamBuilder() {
0376   if (writeToFiles_) {
0377     (*out_file_) << "EOF" << std::endl;
0378     out_file_->close();
0379     delete out_file_;
0380   }
0381 }
0382 
0383 bool EcalTPGParamBuilder::checkIfOK(EcalPedestals::Item item) {
0384   bool result = true;
0385   if (item.mean_x1 < 150. || item.mean_x1 > 250)
0386     result = false;
0387   if (item.mean_x6 < 150. || item.mean_x6 > 250)
0388     result = false;
0389   if (item.mean_x12 < 150. || item.mean_x12 > 250)
0390     result = false;
0391   if (item.rms_x1 < 0 || item.rms_x1 > 2)
0392     result = false;
0393   if (item.rms_x6 < 0 || item.rms_x6 > 3)
0394     result = false;
0395   if (item.rms_x12 < 0 || item.rms_x12 > 5)
0396     result = false;
0397   return result;
0398 }
0399 
0400 int EcalTPGParamBuilder::getEtaSlice(int tccId, int towerInTCC) {
0401   int etaSlice = (towerInTCC - 1) / 4 + 1;
0402   // barrel
0403   if (tccId > 36 && tccId < 73)
0404     return etaSlice;
0405   //endcap
0406   else {
0407     if (tccId >= 1 && tccId <= 18)
0408       etaSlice += 21;  // inner -
0409     else if (tccId >= 19 && tccId <= 36)
0410       etaSlice += 17;  // outer -
0411     else if (tccId >= 91 && tccId <= 108)
0412       etaSlice += 21;  // inner +
0413     else if (tccId >= 73 && tccId <= 90)
0414       etaSlice += 17;  // outer +
0415   }
0416   return etaSlice;
0417 }
0418 
0419 void EcalTPGParamBuilder::analyze(const edm::Event& evt, const edm::EventSetup& evtSetup) {
0420   using namespace edm;
0421   using namespace std;
0422 
0423   // geometry
0424   eTTmap_ = &evtSetup.getData(eTTmapToken_);
0425   theEndcapGeometry_ = &evtSetup.getData(theEndcapGeometryToken_);
0426   theBarrelGeometry_ = &evtSetup.getData(theBarrelGeometryToken_);
0427 
0428   // electronics mapping
0429   theMapping_ = &evtSetup.getData(ecalmappingToken_);
0430 
0431   // get record for alpha
0432   std::ostringstream ss;
0433   ss << "EcalLaserDbAnalyzer::analyze\n";
0434   const EcalLaserAlphaMap& laserAlphaMap = evtSetup.getData(ecalLaserAlphasToken_).getMap();  // map of apdpns
0435   ss << "EcalLaserDbAnalyzer::analyze-> got EcalLaserDbRecord: \n";
0436 
0437   //modif-alex-27-july-2015-+ Jean june 2016 beg
0438   // use alpha to check
0439   EcalLaserAlphaMap::const_iterator italpha;
0440   int cnt = 0;
0441   // Barrel loop
0442   for (italpha = laserAlphaMap.barrelItems().begin(); italpha != laserAlphaMap.barrelItems().end(); ++italpha) {
0443     if (cnt % 1000 == 0) {
0444       EBDetId ebdetid = EBDetId::unhashIndex(cnt);
0445       ss << " Barrel ALPHA = " << (*italpha) << " cmsswId " << ebdetid.rawId() << "\n";
0446     }
0447     cnt++;
0448   }
0449   ss << "Number of barrel Alpha parameters : " << cnt << "\n";
0450   // Endcap loop
0451   cnt = 0;
0452   for (italpha = laserAlphaMap.endcapItems().begin(); italpha != laserAlphaMap.endcapItems().end(); ++italpha) {
0453     if (cnt % 1000 == 0) {
0454       EEDetId eedetid = EEDetId::unhashIndex(cnt);
0455       ss << "EndCap ALPHA = " << (*italpha) << " cmsswId " << eedetid.rawId() << "\n";
0456     }
0457     cnt++;
0458   }
0459   ss << "Number of Endcap Alpha parameters : " << cnt << "\n";
0460   edm::LogInfo("TopInfo") << ss.str();
0461   ss.str("");
0462   //modif-alex-27-july-2015 +-Jean june 2016-end
0463 
0464   //modif-alex-30/01/2012   displaced in analyze Jean 2018
0465   ss.str("");
0466   if (useTransparencyCorr_) {
0467     if (Transparency_Corr_ != "tag") {  // Jean 2018
0468       edm::LogInfo("TopInfo") << "INFO: READING transparency correction files"
0469                               << "\n";
0470       ss << "INFO: READING transparency correction files\n";
0471       std::ifstream transparency(Transparency_Corr_.c_str());
0472       if (!transparency)
0473         edm::LogError("TopInfo") << "ERROR: File " << Transparency_Corr_.c_str() << " could not be opened"
0474                                  << "\n";
0475 
0476       char buf[1024];
0477       transparency.getline(buf, sizeof(buf), '\n');
0478       int xtalcounter = 0;
0479       while (transparency) {
0480         std::stringstream sin(buf);
0481 
0482         int raw_xtal_id;
0483         sin >> raw_xtal_id;
0484 
0485         double xtal_trans_corr;
0486         sin >> xtal_trans_corr;
0487 
0488         //      edm::LogInfo("TopInfo") << raw_xtal_id << " " << xtal_trans_corr << "\n";
0489         ss << raw_xtal_id << " " << xtal_trans_corr << "\n";
0490 
0491         Transparency_Correction_.insert(make_pair(raw_xtal_id, xtal_trans_corr));
0492 
0493         xtalcounter++;
0494         transparency.getline(buf, sizeof(buf), '\n');
0495       }  //loop transparency
0496       transparency.close();
0497       ss << "INFO: DONE transparency correction files " << xtalcounter << "\n";
0498       edm::LogInfo("TopInfo") << ss.str();
0499       ss.str("");
0500     }       // file
0501     else {  // Jean 2018
0502       edm::LogInfo("TopInfo") << "INFO: READING transparency correction tag"
0503                               << "\n";
0504       //      std::cout << "new feature, read a tag" << std::endl;
0505       const EcalLaserAPDPNRatios* lratio = &evtSetup.getData(ecalLaserAPDPNRatiosToken_);
0506       //      std::cout << " laser map size " << lratio->getLaserMap().size() << std::endl;
0507 
0508       EcalLaserAPDPNRatios::EcalLaserAPDPNRatiosMap::const_iterator itratio;
0509       // Barrel loop
0510       for (int ib = 0; ib < 61200; ib++) {
0511         EBDetId ebdetid = EBDetId::unhashIndex(ib);
0512         itratio = lratio->getLaserMap().find(ebdetid.rawId());
0513         //  std::cout  << ib << " " << ebdetid.rawId() << " Barrel APDPNRatios = " << (*itratio).p1 << " " << (*itratio).p2 << " " << (*itratio).p3 << std::endl;
0514         Transparency_Correction_.insert(make_pair(ebdetid.rawId(), (*itratio).p2));
0515       }
0516       // Endcap loop
0517       for (int ie = 0; ie < 14648; ie++) {
0518         EEDetId eedetid = EEDetId::unhashIndex(ie);
0519         itratio = lratio->getLaserMap().find(eedetid.rawId());
0520         //  std::cout  << ie << " " << eedetid.rawId() << " Endcap APDPNRatios = " << (*itratio).p1 << " " << (*itratio).p2 << " " << (*itratio).p3 << std::endl;
0521         Transparency_Correction_.insert(make_pair(eedetid.rawId(), (*itratio).p2));
0522       }
0523       ss << "INFO: DONE transparency correction tag\n";
0524       edm::LogInfo("TopInfo") << ss.str();
0525       ss.str("");
0526     }  // Jean 2018
0527   }    //if transparency
0528 
0529   // histo
0530   TFile saving("EcalTPGParam.root", "recreate");
0531   saving.cd();
0532   TH2F* ICEB = new TH2F("ICEB", "IC: Barrel", 360, 1, 361, 172, -86, 86);
0533   ICEB->GetYaxis()->SetTitle("eta index");
0534   ICEB->GetXaxis()->SetTitle("phi index");
0535   TH2F* tpgFactorEB = new TH2F("tpgFactorEB", "tpgFactor: Barrel", 360, 1, 361, 172, -86, 86);
0536   tpgFactorEB->GetYaxis()->SetTitle("eta index");
0537   tpgFactorEB->GetXaxis()->SetTitle("phi index");
0538 
0539   TH2F* ICEEPlus = new TH2F("ICEEPlus", "IC: Plus Endcap", 120, -9, 111, 120, -9, 111);
0540   ICEEPlus->GetYaxis()->SetTitle("y index");
0541   ICEEPlus->GetXaxis()->SetTitle("x index");
0542   TH2F* tpgFactorEEPlus = new TH2F("tpgFactorEEPlus", "tpgFactor: Plus Endcap", 120, -9, 111, 120, -9, 111);
0543   tpgFactorEEPlus->GetYaxis()->SetTitle("y index");
0544   tpgFactorEEPlus->GetXaxis()->SetTitle("x index");
0545   TH2F* ICEEMinus = new TH2F("ICEEMinus", "IC: Minus Endcap", 120, -9, 111, 120, -9, 111);
0546   ICEEMinus->GetYaxis()->SetTitle("y index");
0547   ICEEMinus->GetXaxis()->SetTitle("x index");
0548   TH2F* tpgFactorEEMinus = new TH2F("tpgFactorEEMinus", "tpgFactor: Minus Endcap", 120, -9, 111, 120, -9, 111);
0549   tpgFactorEEMinus->GetYaxis()->SetTitle("y index");
0550   tpgFactorEEMinus->GetXaxis()->SetTitle("x index");
0551 
0552   TH2F* IC = new TH2F("IC", "IC", 720, -acos(-1.), acos(-1.), 600, -3., 3.);
0553   IC->GetYaxis()->SetTitle("eta");
0554   IC->GetXaxis()->SetTitle("phi");
0555   TH2F* tpgFactor = new TH2F("tpgFactor", "tpgFactor", 720, -acos(-1.), acos(-1.), 600, -3., 3.);
0556   tpgFactor->GetYaxis()->SetTitle("eta");
0557   tpgFactor->GetXaxis()->SetTitle("phi");
0558 
0559   TH1F* hshapeEB = new TH1F("shapeEB", "shapeEB", 250, 0., 10.);
0560   TH1F* hshapeEE = new TH1F("shapeEE", "shapeEE", 250, 0., 10.);
0561 
0562   TTree* ntuple = new TTree("tpgmap", "TPG geometry map");
0563   const std::string branchFloat[26] = {
0564       "fed",    "tcc",    "tower", "stripInTower", "xtalInStrip", "CCU",      "VFE",     "xtalInVFE", "xtalInCCU",
0565       "ieta",   "iphi",   "ix",    "iy",           "iz",          "hashedId", "ic",      "cmsswId",   "dbId",
0566       "ietaTT", "iphiTT", "TCCch", "TCCslot",      "SLBch",       "SLBslot",  "ietaGCT", "iphiGCT"};
0567   ntupleInts_ = new Int_t[26];
0568   for (int i = 0; i < 26; i++)
0569     ntuple->Branch(branchFloat[i].c_str(), &ntupleInts_[i], (branchFloat[i] + string("/I")).c_str());
0570   ntuple->Branch("det", ntupleDet_, "det/C");
0571   ntuple->Branch("crate", ntupleCrate_, "crate/C");
0572 
0573   TNtuple* ntupleSpike = new TNtuple("spikeParam", "Spike parameters", "gainId:theta:G:g:ped:pedLin");
0574 
0575   ////////////////////////////
0576   // Initialization section //
0577   ////////////////////////////
0578   list<uint32_t> towerListEB;
0579   list<uint32_t> stripListEB;
0580   list<uint32_t> towerListEE;
0581   list<uint32_t> stripListEE;
0582   list<uint32_t>::iterator itList;
0583 
0584   map<int, uint32_t> stripMapEB;               // <EcalLogicId.hashed, strip elec id>
0585   map<int, uint32_t> stripMapEE;               // <EcalLogicId.hashed, strip elec id>
0586   map<uint32_t, uint32_t> stripMapEBsintheta;  // <strip elec id, sintheta>
0587 
0588   // Pedestals
0589 
0590   EcalPedestalsMap pedMap;
0591 
0592   if (m_write_ped == 1) {
0593     ss << "Getting the pedestals from offline DB...\n";
0594 
0595     pedMap = evtSetup.getData(ecalPedestalsToken_).getMap();
0596 
0597     const auto& pedMapEB = pedMap.barrelItems();
0598     const auto& pedMapEE = pedMap.endcapItems();
0599     EcalPedestalsMapIterator pedIter;
0600     int nPed = 0;
0601     for (pedIter = pedMapEB.begin(); pedIter != pedMapEB.end() && nPed < 10; ++pedIter, ++nPed) {
0602       const auto aped = (*pedIter);
0603       ss << aped.mean_x12 << ", " << aped.mean_x6 << ", " << aped.mean_x1 << "\n";
0604     }
0605     for (pedIter = pedMapEE.begin(); pedIter != pedMapEE.end() && nPed < 10; ++pedIter, ++nPed) {
0606       const auto aped = (*pedIter);
0607       ss << aped.mean_x12 << ", " << aped.mean_x6 << ", " << aped.mean_x1 << "\n";
0608     }
0609   } else if (m_write_ped == 0) {
0610     ss << "Getting the pedestals from previous configuration\n";
0611 
0612     EcalPedestals peds;
0613 
0614     FEConfigMainInfo fe_main_info;
0615     fe_main_info.setConfigTag(tag_);
0616     ss << "trying to read previous tag if it exists tag=" << tag_ << ".version" << version_ << "\n";
0617     db_->fetchConfigSet(&fe_main_info);
0618     if (fe_main_info.getPedId() > 0)
0619       ped_conf_id_ = fe_main_info.getPedId();
0620 
0621     FEConfigPedInfo fe_ped_info;
0622     fe_ped_info.setId(ped_conf_id_);
0623     db_->fetchConfigSet(&fe_ped_info);
0624     std::map<EcalLogicID, FEConfigPedDat> dataset_TpgPed;
0625     db_->fetchDataSet(&dataset_TpgPed, &fe_ped_info);
0626 
0627     typedef std::map<EcalLogicID, FEConfigPedDat>::const_iterator CIfeped;
0628     EcalLogicID ecid_xt;
0629     FEConfigPedDat rd_ped;
0630     int icells = 0;
0631     for (CIfeped p = dataset_TpgPed.begin(); p != dataset_TpgPed.end(); p++) {
0632       ecid_xt = p->first;
0633       rd_ped = p->second;
0634 
0635       std::string ecid_name = ecid_xt.getName();
0636 
0637       // EB data
0638       if (ecid_name == "EB_crystal_number") {
0639         int sm_num = ecid_xt.getID1();
0640         int xt_num = ecid_xt.getID2();
0641 
0642         EBDetId ebdetid(sm_num, xt_num, EBDetId::SMCRYSTALMODE);
0643         EcalPedestals::Item item;
0644         item.mean_x1 = rd_ped.getPedMeanG1();
0645         item.mean_x6 = rd_ped.getPedMeanG6();
0646         item.mean_x12 = rd_ped.getPedMeanG12();
0647         item.rms_x1 = 0.5;
0648         item.rms_x6 = 1.;
0649         item.rms_x12 = 1.2;
0650 
0651         if (icells < 10)
0652           ss << " copy the EB data "
0653              << " ped = " << item.mean_x12 << "\n";
0654 
0655         peds.insert(std::make_pair(ebdetid.rawId(), item));
0656 
0657         ++icells;
0658       } else if (ecid_name == "EE_crystal_number") {
0659         // EE data
0660         int z = ecid_xt.getID1();
0661         int x = ecid_xt.getID2();
0662         int y = ecid_xt.getID3();
0663         EEDetId eedetid(x, y, z, EEDetId::XYMODE);
0664         EcalPedestals::Item item;
0665         item.mean_x1 = rd_ped.getPedMeanG1();
0666         item.mean_x6 = rd_ped.getPedMeanG6();
0667         item.mean_x12 = rd_ped.getPedMeanG12();
0668         item.rms_x1 = 0.5;
0669         item.rms_x6 = 1.;
0670         item.rms_x12 = 1.2;
0671 
0672         peds.insert(std::make_pair(eedetid.rawId(), item));
0673         ++icells;
0674       }
0675     }
0676 
0677     pedMap = peds.getMap();
0678 
0679     const auto& pedMapEB = pedMap.barrelItems();
0680     const auto& pedMapEE = pedMap.endcapItems();
0681     EcalPedestalsMapIterator pedIter;
0682     int nPed = 0;
0683     for (pedIter = pedMapEB.begin(); pedIter != pedMapEB.end() && nPed < 10; ++pedIter, ++nPed) {
0684       const auto aped = (*pedIter);
0685       ss << aped.mean_x12 << ", " << aped.mean_x6 << ", " << aped.mean_x1 << "\n";
0686     }
0687     for (pedIter = pedMapEE.begin(); pedIter != pedMapEE.end() && nPed < 10; ++pedIter, ++nPed) {
0688       const auto aped = (*pedIter);
0689       ss << aped.mean_x12 << ", " << aped.mean_x6 << ", " << aped.mean_x1 << "\n";
0690     }
0691 
0692   } else if (m_write_ped > 1) {
0693     ss << "Getting the pedestals from configuration number" << m_write_ped << "\n";
0694 
0695     EcalPedestals peds;
0696 
0697     FEConfigPedInfo fe_ped_info;
0698     fe_ped_info.setId(m_write_ped);
0699     db_->fetchConfigSet(&fe_ped_info);
0700     std::map<EcalLogicID, FEConfigPedDat> dataset_TpgPed;
0701     db_->fetchDataSet(&dataset_TpgPed, &fe_ped_info);
0702 
0703     typedef std::map<EcalLogicID, FEConfigPedDat>::const_iterator CIfeped;
0704     EcalLogicID ecid_xt;
0705     FEConfigPedDat rd_ped;
0706     int icells = 0;
0707     for (CIfeped p = dataset_TpgPed.begin(); p != dataset_TpgPed.end(); p++) {
0708       ecid_xt = p->first;
0709       rd_ped = p->second;
0710 
0711       std::string ecid_name = ecid_xt.getName();
0712 
0713       // EB data
0714       if (ecid_name == "EB_crystal_number") {
0715         if (icells < 10)
0716           edm::LogInfo("TopInfo") << " copy the EB data "
0717                                   << " icells = " << icells << "\n";
0718         int sm_num = ecid_xt.getID1();
0719         int xt_num = ecid_xt.getID2();
0720 
0721         EBDetId ebdetid(sm_num, xt_num, EBDetId::SMCRYSTALMODE);
0722         EcalPedestals::Item item;
0723         item.mean_x1 = (unsigned int)rd_ped.getPedMeanG1();
0724         item.mean_x6 = (unsigned int)rd_ped.getPedMeanG6();
0725         item.mean_x12 = (unsigned int)rd_ped.getPedMeanG12();
0726         item.rms_x1 = 0.5;
0727         item.rms_x6 = 1.;
0728         item.rms_x12 = 1.2;
0729 
0730         peds.insert(std::make_pair(ebdetid.rawId(), item));
0731         ++icells;
0732       } else if (ecid_name == "EE_crystal_number") {
0733         // EE data
0734         int z = ecid_xt.getID1();
0735         int x = ecid_xt.getID2();
0736         int y = ecid_xt.getID3();
0737         EEDetId eedetid(x, y, z, EEDetId::XYMODE);
0738         EcalPedestals::Item item;
0739         item.mean_x1 = (unsigned int)rd_ped.getPedMeanG1();
0740         item.mean_x6 = (unsigned int)rd_ped.getPedMeanG6();
0741         item.mean_x12 = (unsigned int)rd_ped.getPedMeanG12();
0742         item.rms_x1 = 0.5;
0743         item.rms_x6 = 1.;
0744         item.rms_x12 = 1.2;
0745 
0746         peds.insert(std::make_pair(eedetid.rawId(), item));
0747         ++icells;
0748       }
0749     }
0750 
0751     pedMap = peds.getMap();
0752 
0753     const auto& pedMapEB = pedMap.barrelItems();
0754     const auto& pedMapEE = pedMap.endcapItems();
0755     EcalPedestalsMapIterator pedIter;
0756     int nPed = 0;
0757     for (pedIter = pedMapEB.begin(); pedIter != pedMapEB.end() && nPed < 10; ++pedIter, ++nPed) {
0758       const auto aped = (*pedIter);
0759       ss << aped.mean_x12 << ", " << aped.mean_x6 << ", " << aped.mean_x1 << "\n";
0760     }
0761     for (pedIter = pedMapEE.begin(); pedIter != pedMapEE.end() && nPed < 10; ++pedIter, ++nPed) {
0762       const auto aped = (*pedIter);
0763       ss << aped.mean_x12 << ", " << aped.mean_x6 << ", " << aped.mean_x1 << "\n";
0764     }
0765   }
0766 
0767   edm::LogInfo("TopInfo") << ss.str();
0768   ss.str("");
0769 
0770   // Intercalib constants
0771   ss << "Getting intercalib from offline DB...\n";
0772   const EcalIntercalibConstants* intercalib = &evtSetup.getData(ecalIntercalibConstantsToken_);
0773   const EcalIntercalibConstantMap& calibMap = intercalib->getMap();
0774   const auto& calibMapEB = calibMap.barrelItems();
0775   const auto& calibMapEE = calibMap.endcapItems();
0776   EcalIntercalibConstantMap::const_iterator calIter;
0777   int nCal = 0;
0778   for (calIter = calibMapEB.begin(); calIter != calibMapEB.end() && nCal < 10; ++calIter, ++nCal) {
0779     ss << (*calIter) << "\n";
0780   }
0781   for (calIter = calibMapEE.begin(); calIter != calibMapEE.end() && nCal < 10; ++calIter, ++nCal) {
0782     ss << (*calIter) << "\n";
0783   }
0784   edm::LogInfo("TopInfo") << ss.str();
0785   ss.str("");
0786   float calibvec[1700];
0787   if (H2_) {
0788     edm::LogInfo("TopInfo") << "H2: overwriting IC coef with file"
0789                             << "\n";
0790     std::ifstream calibfile("calib_sm36.txt", std::ios::out);
0791     int idata, icry;
0792     float fdata, fcali;
0793     std::string strdata;
0794     if (calibfile.is_open()) {
0795       calibfile >> strdata >> strdata >> strdata >> strdata >> strdata;
0796       while (!calibfile.eof()) {
0797         calibfile >> idata >> icry >> fcali >> fdata >> fdata;
0798         calibvec[icry - 1] = fcali;
0799         if (calibfile.eof()) {
0800           break;  // avoid last line duplication
0801         }
0802       }
0803     }
0804   }
0805 
0806   // Gain Ratios
0807   ss << "Getting the gain ratios from offline DB...\n";
0808   const EcalGainRatioMap& gainMap = evtSetup.getData(ecalGainRatiosToken_).getMap();
0809   const auto& gainMapEB = gainMap.barrelItems();
0810   const auto& gainMapEE = gainMap.endcapItems();
0811   EcalGainRatioMap::const_iterator gainIter;
0812   int nGain = 0;
0813   for (gainIter = gainMapEB.begin(); gainIter != gainMapEB.end() && nGain < 10; ++gainIter, ++nGain) {
0814     const auto& aGain = (*gainIter);
0815     ss << aGain.gain12Over6() << ", " << aGain.gain6Over1() * aGain.gain12Over6() << "\n";
0816   }
0817   for (gainIter = gainMapEE.begin(); gainIter != gainMapEE.end() && nGain < 10; ++gainIter, ++nGain) {
0818     const auto& aGain = (*gainIter);
0819     ss << aGain.gain12Over6() << ", " << aGain.gain6Over1() * aGain.gain12Over6() << "\n";
0820   }
0821   edm::LogInfo("TopInfo") << ss.str();
0822   ss.str("");
0823 
0824   // ADCtoGeV
0825   ss << "Getting the ADC to GeV from offline DB...\n";
0826   const EcalADCToGeVConstant* ADCToGeV = &evtSetup.getData(ecalADCToGeVConstantToken_);
0827   xtal_LSB_EB_ = ADCToGeV->getEBValue();
0828   xtal_LSB_EE_ = ADCToGeV->getEEValue();
0829   ss << "xtal_LSB_EB_ = " << xtal_LSB_EB_ << "\n";
0830   ss << "xtal_LSB_EE_ = " << xtal_LSB_EE_ << "\n";
0831 
0832   vector<EcalLogicID> my_EcalLogicId;
0833   vector<EcalLogicID> my_TTEcalLogicId;
0834   vector<EcalLogicID> my_StripEcalLogicId;
0835   EcalLogicID my_EcalLogicId_EB;
0836   // Endcap identifiers
0837   EcalLogicID my_EcalLogicId_EE;
0838   vector<EcalLogicID> my_TTEcalLogicId_EE;
0839   vector<EcalLogicID> my_RTEcalLogicId_EE;
0840   vector<EcalLogicID> my_StripEcalLogicId1_EE;
0841   vector<EcalLogicID> my_StripEcalLogicId2_EE;
0842   vector<EcalLogicID> my_CrystalEcalLogicId_EE;
0843   vector<EcalLogicID> my_TTEcalLogicId_EB_by_TCC;
0844   vector<EcalLogicID> my_StripEcalLogicId_EE_strips_by_TCC;
0845 
0846   my_EcalLogicId_EB = db_->getEcalLogicID("EB", EcalLogicID::NULLID, EcalLogicID::NULLID, EcalLogicID::NULLID, "EB");
0847   my_EcalLogicId_EE = db_->getEcalLogicID("EE", EcalLogicID::NULLID, EcalLogicID::NULLID, EcalLogicID::NULLID, "EE");
0848   my_EcalLogicId = db_->getEcalLogicIDSetOrdered(
0849       "EB_crystal_number", 1, 36, 1, 1700, EcalLogicID::NULLID, EcalLogicID::NULLID, "EB_crystal_number", 12);
0850   my_TTEcalLogicId = db_->getEcalLogicIDSetOrdered(
0851       "EB_trigger_tower", 1, 36, 1, 68, EcalLogicID::NULLID, EcalLogicID::NULLID, "EB_trigger_tower", 12);
0852   my_StripEcalLogicId = db_->getEcalLogicIDSetOrdered(
0853       "EB_VFE", 1, 36, 1, 68, 1, 5, "EB_VFE", 123);  //last digi means ordered 1st by SM,then TT, then strip
0854   ss << "got the 3 ecal barrel logic id set\n";
0855 
0856   // EE crystals identifiers
0857   my_CrystalEcalLogicId_EE =
0858       db_->getEcalLogicIDSetOrdered("EE_crystal_number", -1, 1, 0, 200, 0, 200, "EE_crystal_number", 123);
0859 
0860   // EE Strip identifiers
0861   // DCC=601-609 TT = ~40 EEstrip = 5
0862   my_StripEcalLogicId1_EE =
0863       db_->getEcalLogicIDSetOrdered("ECAL_readout_strip", 601, 609, 1, 100, 0, 5, "ECAL_readout_strip", 123);
0864   // EE Strip identifiers
0865   // DCC=646-654 TT = ~40 EEstrip = 5
0866   my_StripEcalLogicId2_EE =
0867       db_->getEcalLogicIDSetOrdered("ECAL_readout_strip", 646, 654, 1, 100, 0, 5, "ECAL_readout_strip", 123);
0868   // ----> modif here 31/1/2011
0869   // EE Strip identifiers by TCC tower strip
0870   // TCC=1-108 TT = ~40 EEstrip = 1-5
0871   my_StripEcalLogicId_EE_strips_by_TCC =
0872       db_->getEcalLogicIDSetOrdered("EE_trigger_strip", 1, 108, 1, 100, 1, 5, "EE_trigger_strip", 123);
0873 
0874   // ----> modif here 31/1/2011
0875   // ECAL Barrel trigger towers by TCC/tower identifiers
0876   // TTC=38-72 TT = 1-68
0877   my_TTEcalLogicId_EB_by_TCC = db_->getEcalLogicIDSetOrdered(
0878       "ECAL_trigger_tower", 1, 108, 1, 68, EcalLogicID::NULLID, EcalLogicID::NULLID, "ECAL_trigger_tower", 12);
0879 
0880   // EE TT identifiers
0881   // TTC=72 TT = 1440
0882   my_TTEcalLogicId_EE = db_->getEcalLogicIDSetOrdered(
0883       "EE_trigger_tower", 1, 108, 1, 40, EcalLogicID::NULLID, EcalLogicID::NULLID, "EE_trigger_tower", 12);
0884 
0885   // EE TT identifiers
0886   // TTC=72 TT = 1440
0887   my_RTEcalLogicId_EE = db_->getEcalLogicIDSetOrdered(
0888       "EE_readout_tower", 1, 1000, 1, 100, EcalLogicID::NULLID, EcalLogicID::NULLID, "EE_readout_tower", 12);
0889   edm::LogInfo("TopInfo") << ss.str();
0890   ss.str("");
0891 
0892   if (writeToDB_) {
0893     ss << "Getting the latest ids for this tag (latest version) "
0894        << "\n";
0895 
0896     FEConfigMainInfo fe_main_info;
0897     fe_main_info.setConfigTag(tag_);
0898 
0899     ss << "trying to read previous tag if it exists tag=" << tag_ << ".version" << version_ << "\n";
0900 
0901     db_->fetchConfigSet(&fe_main_info);
0902     if (fe_main_info.getPedId() > 0 && ped_conf_id_ == 0)
0903       ped_conf_id_ = fe_main_info.getPedId();
0904     lin_conf_id_ = fe_main_info.getLinId();
0905     lut_conf_id_ = fe_main_info.getLUTId();
0906     wei_conf_id_ = fe_main_info.getWeiId();
0907     wei2_conf_id_ = fe_main_info.getWei2Id();
0908     fgr_conf_id_ = fe_main_info.getFgrId();
0909     sli_conf_id_ = fe_main_info.getSliId();
0910     spi_conf_id_ = fe_main_info.getSpiId();  //modif-alex 21/01/11
0911     del_conf_id_ = fe_main_info.getTimId();  //modif-alex 21/01/11
0912     coke_conf_id_ = fe_main_info.getCokeId();
0913     if (fe_main_info.getBxtId() > 0 && bxt_conf_id_ == 0)
0914       bxt_conf_id_ = fe_main_info.getBxtId();
0915     if (fe_main_info.getBttId() > 0 && btt_conf_id_ == 0)
0916       btt_conf_id_ = fe_main_info.getBttId();
0917     if (fe_main_info.getBstId() > 0 && bst_conf_id_ == 0)
0918       bst_conf_id_ = fe_main_info.getBstId();
0919     // those that are not written specifically in this program are propagated
0920     // from the previous record with the same tag and the highest version
0921   }
0922 
0923   /////////////////////////////////////////
0924   // Compute linearization coeff section //
0925   /////////////////////////////////////////
0926 
0927   map<EcalLogicID, FEConfigPedDat> pedset;
0928   map<EcalLogicID, FEConfigLinDat> linset;
0929   map<EcalLogicID, FEConfigLinParamDat> linparamset;
0930   map<EcalLogicID, FEConfigLUTParamDat> lutparamset;
0931   map<EcalLogicID, FEConfigFgrParamDat> fgrparamset;
0932 
0933   map<int, linStruc> linEtaSlice;
0934   map<vector<int>, linStruc> linMap;
0935 
0936   // count number of strip per tower
0937   int NbOfStripPerTCC[108][68];
0938   for (int i = 0; i < 108; i++)
0939     for (int j = 0; j < 68; j++)
0940       NbOfStripPerTCC[i][j] = 0;
0941   const std::vector<DetId>& ebCells = theBarrelGeometry_->getValidDetIds(DetId::Ecal, EcalBarrel);
0942   const std::vector<DetId>& eeCells = theEndcapGeometry_->getValidDetIds(DetId::Ecal, EcalEndcap);
0943   for (vector<DetId>::const_iterator it = ebCells.begin(); it != ebCells.end(); ++it) {
0944     EBDetId id(*it);
0945     const EcalTrigTowerDetId towid = id.tower();
0946     const EcalTriggerElectronicsId elId = theMapping_->getTriggerElectronicsId(id);
0947     int tccNb = theMapping_->TCCid(towid);
0948     int towerInTCC = theMapping_->iTT(towid);
0949     int stripInTower = elId.pseudoStripId();
0950     if (stripInTower > NbOfStripPerTCC[tccNb - 1][towerInTCC - 1])
0951       NbOfStripPerTCC[tccNb - 1][towerInTCC - 1] = stripInTower;
0952   }
0953   for (vector<DetId>::const_iterator it = eeCells.begin(); it != eeCells.end(); ++it) {
0954     EEDetId id(*it);
0955     const EcalTrigTowerDetId towid = (*eTTmap_).towerOf(id);
0956     const EcalTriggerElectronicsId elId = theMapping_->getTriggerElectronicsId(id);
0957     int tccNb = theMapping_->TCCid(towid);
0958     int towerInTCC = theMapping_->iTT(towid);
0959     int stripInTower = elId.pseudoStripId();
0960     if (stripInTower > NbOfStripPerTCC[tccNb - 1][towerInTCC - 1])
0961       NbOfStripPerTCC[tccNb - 1][towerInTCC - 1] = stripInTower;
0962   }
0963 
0964   // loop on EB xtals
0965   if (writeToFiles_)
0966     (*out_file_) << "COMMENT ====== barrel crystals ====== " << std::endl;
0967 
0968   // special case of eta slices
0969   for (vector<DetId>::const_iterator it = ebCells.begin(); it != ebCells.end(); ++it) {
0970     EBDetId id(*it);
0971     double theta = theBarrelGeometry_->getGeometry(id)->getPosition().theta();
0972     if (!useTransverseEnergy_)
0973       theta = acos(0.);
0974     const EcalTrigTowerDetId towid = id.tower();
0975     const EcalTriggerElectronicsId elId = theMapping_->getTriggerElectronicsId(id);
0976     int dccNb = theMapping_->DCCid(towid);
0977     int tccNb = theMapping_->TCCid(towid);
0978     int towerInTCC = theMapping_->iTT(towid);  // from 1 to 68 (EB)
0979     int stripInTower = elId.pseudoStripId();   // from 1 to 5
0980     int xtalInStrip = elId.channelId();        // from 1 to 5
0981     const EcalElectronicsId Id = theMapping_->getElectronicsId(id);
0982     int CCUid = Id.towerId();
0983     int VFEid = Id.stripId();
0984     int xtalInVFE = Id.xtalId();
0985     int xtalWithinCCUid = 5 * (VFEid - 1) + xtalInVFE - 1;  // Evgueni expects [0,24]
0986 
0987     (*geomFile_) << "dccNb = " << dccNb << " tccNb = " << tccNb << " towerInTCC = " << towerInTCC
0988                  << " stripInTower = " << stripInTower << " xtalInStrip = " << xtalInStrip << " CCUid = " << CCUid
0989                  << " VFEid = " << VFEid << " xtalInVFE = " << xtalInVFE << " xtalWithinCCUid = " << xtalWithinCCUid
0990                  << " ieta = " << id.ieta() << " iphi = " << id.iphi() << " xtalhashedId = " << id.hashedIndex()
0991                  << " xtalNb = " << id.ic() << " ietaTT = " << towid.ieta() << " iphiTT = " << towid.iphi()
0992                  << std::endl;
0993 
0994     int TCCch = towerInTCC;
0995     int SLBslot = int((towerInTCC - 1) / 8.) + 1;
0996     int SLBch = (towerInTCC - 1) % 8 + 1;
0997     int cmsswId = id.rawId();
0998     int ixtal = (id.ism() - 1) * 1700 + (id.ic() - 1);
0999     EcalLogicID logicId = my_EcalLogicId[ixtal];
1000     int dbId = logicId.getLogicID();
1001     int val[] = {dccNb + 600,
1002                  tccNb,
1003                  towerInTCC,
1004                  stripInTower,
1005                  xtalInStrip,
1006                  CCUid,
1007                  VFEid,
1008                  xtalInVFE,
1009                  xtalWithinCCUid,
1010                  id.ieta(),
1011                  id.iphi(),
1012                  -999,
1013                  -999,
1014                  towid.ieta() / abs(towid.ieta()),
1015                  id.hashedIndex(),
1016                  id.ic(),
1017                  cmsswId,
1018                  dbId,
1019                  towid.ieta(),
1020                  towid.iphi(),
1021                  TCCch,
1022                  getCrate(tccNb).second,
1023                  SLBch,
1024                  SLBslot,
1025                  getGCTRegionEta(towid.ieta()),
1026                  getGCTRegionPhi(towid.iphi())};
1027     for (int i = 0; i < 26; i++)
1028       ntupleInts_[i] = val[i];
1029 
1030     strcpy(ntupleDet_, getDet(tccNb).c_str());
1031     strcpy(ntupleCrate_, getCrate(tccNb).first.c_str());
1032     ntuple->Fill();
1033 
1034     if (tccNb == 37 && stripInTower == 3 && xtalInStrip == 3 && (towerInTCC - 1) % 4 == 0) {
1035       int etaSlice = towid.ietaAbs();
1036       coeffStruc coeff;
1037       //getCoeff(coeff, calibMap, id.rawId()) ;
1038       //modif-alex-27-july-2015
1039       string str;
1040       getCoeff(coeff, calibMap, laserAlphaMap, id.rawId(), str);
1041       ss << str;
1042       getCoeff(coeff, gainMap, id.rawId());
1043       getCoeff(coeff, pedMap, id.rawId());
1044       linStruc lin;
1045       for (int i = 0; i < 3; i++) {
1046         lin.pedestal_[i] = coeff.pedestals_[i];
1047         lin.mult_[i] = 0;
1048         lin.shift_[i] = 0;
1049         int mult = 0;
1050         int shift = 0;
1051         bool ok = computeLinearizerParam(theta, coeff.gainRatio_[i], coeff.calibCoeff_, "EB", mult, shift);
1052         if (!ok) {
1053           //If the mult is impossible to compute
1054           if (mult > 255) {
1055             edm::LogError("TopInfo") << "ByEtaSlice: unable to compute the parameters for SM=" << id.ism()
1056                                      << " xt=" << id.ic() << " " << dec << id.rawId() << " gainId=" << i
1057                                      << ", mult too large! forced to mult=255, shift=0\n";
1058             lin.mult_[i] = 255;
1059             lin.shift_[i] = 0;
1060           } else if (mult < 128) {
1061             edm::LogError("TopInfo") << "ByEtaSlice: unable to compute the parameters for SM=" << id.ism()
1062                                      << " xt=" << id.ic() << " " << dec << id.rawId() << " gainId=" << i
1063                                      << ", mult too small! forced to mult=128, shift=15\n";
1064             ;
1065             lin.mult_[i] = 128;
1066             lin.shift_[i] = 15;
1067           }
1068         } else {
1069           lin.mult_[i] = mult;
1070           lin.shift_[i] = shift;
1071         }
1072       }
1073 
1074       bool ok(true);
1075       if (forcedPedestalValue_ == -2)
1076         ok = realignBaseline(lin, 0, id.rawId());
1077       if (!ok)
1078         ss << "SM=" << id.ism() << " xt=" << id.ic() << " " << dec << id.rawId() << "\n";
1079       linEtaSlice[etaSlice] = lin;
1080     }
1081   }
1082 
1083   // general case
1084   for (vector<DetId>::const_iterator it = ebCells.begin(); it != ebCells.end(); ++it) {
1085     EBDetId id(*it);
1086     double theta = theBarrelGeometry_->getGeometry(id)->getPosition().theta();
1087     if (!useTransverseEnergy_)
1088       theta = acos(0.);
1089     const EcalTrigTowerDetId towid = id.tower();
1090     towerListEB.push_back(towid.rawId());
1091     const EcalTriggerElectronicsId elId = theMapping_->getTriggerElectronicsId(id);
1092     stripListEB.push_back(elId.rawId() & 0xfffffff8);
1093     int dccNb = theMapping_->DCCid(towid);
1094     //int tccNb = theMapping_->TCCid(towid) ;
1095     int towerInTCC = theMapping_->iTT(towid);  // from 1 to 68 (EB)
1096     //int stripInTower = elId.pseudoStripId() ;  // from 1 to 5
1097     //int xtalInStrip = elId.channelId() ;       // from 1 to 5
1098     const EcalElectronicsId Id = theMapping_->getElectronicsId(id);
1099     int CCUid = Id.towerId();
1100     int VFEid = Id.stripId();
1101     int xtalInVFE = Id.xtalId();
1102     int xtalWithinCCUid = 5 * (VFEid - 1) + xtalInVFE - 1;  // Evgueni expects [0,24]
1103     int etaSlice = towid.ietaAbs();
1104 
1105     // hashed index of strip EcalLogicID:
1106     int hashedStripLogicID = 68 * 5 * (id.ism() - 1) + 5 * (towerInTCC - 1) + (VFEid - 1);
1107     stripMapEB[hashedStripLogicID] = elId.rawId() & 0xfffffff8;
1108     stripMapEBsintheta[elId.rawId() & 0xfffffff8] = SFGVB_Threshold_ + abs(int(sin(theta) * pedestal_offset_));
1109 
1110     //modif-debug
1111     /*
1112     FEConfigFgrEEStripDat stripdebug;
1113     EcalLogicID thestrip_debug = my_StripEcalLogicId[hashedStripLogicID] ;
1114     if(towid.ieta() == 6 && towid.iphi() == 7){
1115       std::cout << "xtal info=" << id << " VFE=" << VFEid << std::endl;
1116       std::cout << "TOWER DEBUG ieta=" << towid.ieta() << " iphi=" << towid.iphi() << " SFGVB=" << SFGVB_Threshold_ + abs(int(sin(theta)*pedestal_offset_)) 
1117         << " dbId=" << (elId.rawId() & 0xfffffff8) << " " << hashedStripLogicID << " " << thestrip_debug.getLogicID() << std::endl;  //modif-debug
1118     }//EB+3 TT24
1119     */
1120     //std::cout<<std::dec<<SFGVB_Threshold_ + abs(int(sin(theta)*pedestal_offset_))<<" "<<SFGVB_Threshold_<<" "<<abs(int(sin(theta)*pedestal_offset_))<<std::endl ;
1121 
1122     FEConfigPedDat pedDB;
1123     FEConfigLinDat linDB;
1124     if (writeToFiles_)
1125       (*out_file_) << "CRYSTAL " << dec << id.rawId() << std::endl;
1126     //  if (writeToDB_) logicId = db_->getEcalLogicID ("EB_crystal_number", id.ism(), id.ic()) ;
1127 
1128     coeffStruc coeff;
1129     //getCoeff(coeff, calibMap, id.rawId()) ;
1130     //modif-alex-27-july-2015
1131     std::string str;
1132     getCoeff(coeff, calibMap, laserAlphaMap, id.rawId(), str);
1133     ss << str;
1134 
1135     if (H2_)
1136       coeff.calibCoeff_ = calibvec[id.ic() - 1];
1137     getCoeff(coeff, gainMap, id.rawId());
1138     getCoeff(coeff, pedMap, id.rawId());
1139     ICEB->Fill(id.iphi(), id.ieta(), coeff.calibCoeff_);
1140     IC->Fill(theBarrelGeometry_->getGeometry(id)->getPosition().phi(),
1141              theBarrelGeometry_->getGeometry(id)->getPosition().eta(),
1142              coeff.calibCoeff_);
1143 
1144     vector<int> xtalCCU;
1145     xtalCCU.push_back(dccNb + 600);
1146     xtalCCU.push_back(CCUid);
1147     xtalCCU.push_back(xtalWithinCCUid);
1148     xtalCCU.push_back(id.rawId());
1149 
1150     // compute and fill linearization parameters
1151     // case of eta slice
1152     if (forceEtaSlice_) {
1153       map<int, linStruc>::const_iterator itLin = linEtaSlice.find(etaSlice);
1154       if (itLin != linEtaSlice.end()) {
1155         linMap[xtalCCU] = itLin->second;
1156         if (writeToFiles_) {
1157           for (int i = 0; i < 3; i++)
1158             (*out_file_) << hex << " 0x" << itLin->second.pedestal_[i] << " 0x" << itLin->second.mult_[i] << " 0x"
1159                          << itLin->second.shift_[i] << std::endl;
1160         }
1161         if (writeToDB_) {
1162           for (int i = 0; i < 3; i++) {
1163             if (i == 0) {
1164               pedDB.setPedMeanG12(itLin->second.pedestal_[i]);
1165               linDB.setMultX12(itLin->second.mult_[i]);
1166               linDB.setShift12(itLin->second.shift_[i]);
1167             } else if (i == 1) {
1168               pedDB.setPedMeanG6(itLin->second.pedestal_[i]);
1169               linDB.setMultX6(itLin->second.mult_[i]);
1170               linDB.setShift6(itLin->second.shift_[i]);
1171             } else if (i == 2) {
1172               pedDB.setPedMeanG1(itLin->second.pedestal_[i]);
1173               linDB.setMultX1(itLin->second.mult_[i]);
1174               linDB.setShift1(itLin->second.shift_[i]);
1175             }
1176           }
1177         }
1178         float factor = float(itLin->second.mult_[0]) * pow(2., -itLin->second.shift_[0]) / xtal_LSB_EB_;
1179         tpgFactorEB->Fill(id.iphi(), id.ieta(), factor);
1180         tpgFactor->Fill(theBarrelGeometry_->getGeometry(id)->getPosition().phi(),
1181                         theBarrelGeometry_->getGeometry(id)->getPosition().eta(),
1182                         factor);
1183       } else
1184         ss << "current EtaSlice = " << etaSlice << " not found in the EtaSlice map"
1185            << "\n";
1186     } else {
1187       // general case
1188       linStruc lin;
1189       int forceBase12 = 0;
1190       double invSinTheta = 1. / sin(theta);
1191       for (int i = 0; i < 3; i++) {
1192         lin.pedestal_[i] = coeff.pedestals_[i];
1193         lin.mult_[i] = 0;
1194         lin.shift_[i] = 0;
1195         int mult = 0;
1196         int shift = 0;
1197         bool ok = computeLinearizerParam(theta, coeff.gainRatio_[i], coeff.calibCoeff_, "EB", mult, shift);
1198         if (!ok) {
1199           //If the mult is impossible to compute
1200           if (mult > 255) {
1201             edm::LogError("TopInfo") << "unable to compute the parameters for " << dec << id.rawId()
1202                                      << ", EB, gainId=" << i << ", mult too large! forced to mult=255, shift=0\n";
1203             lin.mult_[i] = 255;
1204             lin.shift_[i] = 0;
1205           } else if (mult < 128) {
1206             edm::LogError("TopInfo") << "unable to compute the parameters for " << dec << id.rawId()
1207                                      << ", EB, gainId=" << i << ", mult too small! forced to mult=128, shift=15\n";
1208             lin.mult_[i] = 128;
1209             lin.shift_[i] = 15;
1210           }
1211         } else {
1212           lin.mult_[i] = mult;
1213           lin.shift_[i] = shift;
1214         }
1215         // Force baseline for gain 12 also when mult not ok and the value is set to default
1216         if (forcedPedestalValue_ == -3 && i == 0) {
1217           double G = mult * pow(2.0, -(shift + 2));
1218           double g = G * invSinTheta;
1219           double base = double(coeff.pedestals_[i]) - pedestal_offset_ / g;
1220           if (base < 0.)
1221             base = 0;
1222           forceBase12 = int(base);
1223         }
1224       }
1225 
1226       bool ok(true);
1227       if (forcedPedestalValue_ == -2)
1228         ok = realignBaseline(lin, 0, id.rawId());
1229       else if (forcedPedestalValue_ == -3)
1230         ok = realignBaseline(lin, forceBase12, id.rawId());
1231       if (!ok)
1232         ss << "SM=" << id.ism() << " xt=" << id.ic() << " " << dec << id.rawId() << "\n";
1233 
1234       for (int i = 0; i < 3; i++) {
1235         if (writeToFiles_)
1236           (*out_file_) << hex << " 0x" << lin.pedestal_[i] << " 0x" << lin.mult_[i] << " 0x" << lin.shift_[i]
1237                        << std::endl;
1238         if (writeToDB_) {
1239           if (i == 0) {
1240             pedDB.setPedMeanG12(lin.pedestal_[i]);
1241             linDB.setMultX12(lin.mult_[i]);
1242             linDB.setShift12(lin.shift_[i]);
1243           } else if (i == 1) {
1244             pedDB.setPedMeanG6(lin.pedestal_[i]);
1245             linDB.setMultX6(lin.mult_[i]);
1246             linDB.setShift6(lin.shift_[i]);
1247           } else if (i == 2) {
1248             pedDB.setPedMeanG1(lin.pedestal_[i]);
1249             linDB.setMultX1(lin.mult_[i]);
1250             linDB.setShift1(lin.shift_[i]);
1251           }
1252         }
1253         if (i == 0) {
1254           float factor = float(lin.mult_[i]) * pow(2., -lin.shift_[i]) / xtal_LSB_EB_;
1255           tpgFactorEB->Fill(id.iphi(), id.ieta(), factor);
1256           tpgFactor->Fill(theBarrelGeometry_->getGeometry(id)->getPosition().phi(),
1257                           theBarrelGeometry_->getGeometry(id)->getPosition().eta(),
1258                           factor);
1259         }
1260         double G = lin.mult_[i] * pow(2.0, -(lin.shift_[i] + 2));
1261         double g = G * invSinTheta;
1262         float val[] = {float(i),
1263                        float(theta),
1264                        float(G),
1265                        float(g),
1266                        float(coeff.pedestals_[i]),
1267                        float(lin.pedestal_[i])};  // first arg = gainId (0 means gain12)
1268         ntupleSpike->Fill(val);
1269       }
1270       linMap[xtalCCU] = lin;
1271     }
1272     if (writeToDB_) {
1273       // 1700 crystals/SM in the ECAL barrel
1274       int ixtal = (id.ism() - 1) * 1700 + (id.ic() - 1);
1275       EcalLogicID logicId = my_EcalLogicId[ixtal];
1276       pedset[logicId] = pedDB;
1277       linset[logicId] = linDB;
1278     }
1279   }  //ebCells
1280 
1281   if (writeToDB_) {
1282     // EcalLogicID  of the whole barrel is: my_EcalLogicId_EB
1283     FEConfigLinParamDat linparam;
1284     linparam.setETSat(Et_sat_EB_);
1285     linparamset[my_EcalLogicId_EB] = linparam;
1286 
1287     FEConfigFgrParamDat fgrparam;
1288     fgrparam.setFGlowthresh(FG_lowThreshold_EB_);
1289     fgrparam.setFGhighthresh(FG_highThreshold_EB_);
1290     fgrparam.setFGlowratio(FG_lowRatio_EB_);
1291     fgrparam.setFGhighratio(FG_highRatio_EB_);
1292     fgrparamset[my_EcalLogicId_EB] = fgrparam;
1293 
1294     FEConfigLUTParamDat lutparam;
1295     lutparam.setETSat(Et_sat_EB_);
1296     lutparam.setTTThreshlow(TTF_lowThreshold_EB_);
1297     lutparam.setTTThreshhigh(TTF_highThreshold_EB_);
1298     lutparamset[my_EcalLogicId_EB] = lutparam;
1299   }
1300 
1301   // loop on EE xtals
1302   if (writeToFiles_)
1303     (*out_file_) << "COMMENT ====== endcap crystals ====== " << std::endl;
1304 
1305   // special case of eta slices
1306   for (vector<DetId>::const_iterator it = eeCells.begin(); it != eeCells.end(); ++it) {
1307     EEDetId id(*it);
1308     double theta = theEndcapGeometry_->getGeometry(id)->getPosition().theta();
1309     if (!useTransverseEnergy_)
1310       theta = acos(0.);
1311     const EcalTrigTowerDetId towid = (*eTTmap_).towerOf(id);
1312     const EcalTriggerElectronicsId elId = theMapping_->getTriggerElectronicsId(id);
1313     const EcalElectronicsId Id = theMapping_->getElectronicsId(id);
1314     int dccNb = Id.dccId();
1315     int tccNb = theMapping_->TCCid(towid);
1316     int towerInTCC = theMapping_->iTT(towid);
1317     int stripInTower = elId.pseudoStripId();
1318     int xtalInStrip = elId.channelId();
1319     int CCUid = Id.towerId();
1320     int VFEid = Id.stripId();
1321     int xtalInVFE = Id.xtalId();
1322     int xtalWithinCCUid = 5 * (VFEid - 1) + xtalInVFE - 1;  // Evgueni expects [0,24]
1323 
1324     // Creating the stripMap for EE
1325     bool foundStripLogic = false;
1326     for (EcalLogicID& stripLogicId : my_StripEcalLogicId1_EE) {
1327       if (stripLogicId.getID1() == 600 + dccNb && stripLogicId.getID2() == CCUid && stripLogicId.getID3() == VFEid) {
1328         stripMapEE[stripLogicId.getLogicID()] = elId.rawId() & 0xfffffff8;
1329         foundStripLogic = true;
1330         break;
1331       }
1332     }
1333     if (!foundStripLogic) {
1334       for (EcalLogicID& stripLogicId : my_StripEcalLogicId2_EE) {
1335         if (stripLogicId.getID1() == 600 + dccNb && stripLogicId.getID2() == CCUid && stripLogicId.getID3() == VFEid) {
1336           stripMapEE[stripLogicId.getLogicID()] = elId.rawId() & 0xfffffff8;
1337           foundStripLogic = true;
1338           break;
1339         }
1340       }
1341     }
1342     if (!foundStripLogic) {
1343       edm::LogWarning("TopInfo") << "Strip ID not found for DCC: " << 600 + dccNb << " CCU: " << CCUid
1344                                  << " VFEid: " << VFEid;
1345     }
1346 
1347     (*geomFile_) << "dccNb = " << dccNb << " tccNb = " << tccNb << " towerInTCC = " << towerInTCC
1348                  << " stripInTower = " << stripInTower << " xtalInStrip = " << xtalInStrip << " CCUid = " << CCUid
1349                  << " VFEid = " << VFEid << " xtalInVFE = " << xtalInVFE << " xtalWithinCCUid = " << xtalWithinCCUid
1350                  << " ix = " << id.ix() << " iy = " << id.iy() << " xtalhashedId = " << id.hashedIndex()
1351                  << " xtalNb = " << id.isc() << " ietaTT = " << towid.ieta() << " iphiTT = " << towid.iphi()
1352                  << std::endl;
1353 
1354     int TCCch = stripInTower;
1355     int SLBslot, SLBch;
1356     if (towerInTCC < 5) {
1357       SLBslot = 1;
1358       SLBch = 4 + towerInTCC;
1359     } else {
1360       SLBslot = int((towerInTCC - 5) / 8.) + 2;
1361       SLBch = (towerInTCC - 5) % 8 + 1;
1362     }
1363     for (int j = 0; j < towerInTCC - 1; j++)
1364       TCCch += NbOfStripPerTCC[tccNb - 1][j];
1365 
1366     int cmsswId = id.rawId();
1367     EcalLogicID logicId;
1368     int iz = id.positiveZ();
1369     if (iz == 0)
1370       iz = -1;
1371     for (int k = 0; k < (int)my_CrystalEcalLogicId_EE.size(); k++) {
1372       int z = my_CrystalEcalLogicId_EE[k].getID1();
1373       int x = my_CrystalEcalLogicId_EE[k].getID2();
1374       int y = my_CrystalEcalLogicId_EE[k].getID3();
1375       if (id.ix() == x && id.iy() == y && iz == z)
1376         logicId = my_CrystalEcalLogicId_EE[k];
1377     }
1378     int dbId = logicId.getLogicID();
1379 
1380     int val[] = {dccNb + 600,
1381                  tccNb,
1382                  towerInTCC,
1383                  stripInTower,
1384                  xtalInStrip,
1385                  CCUid,
1386                  VFEid,
1387                  xtalInVFE,
1388                  xtalWithinCCUid,
1389                  -999,
1390                  -999,
1391                  id.ix(),
1392                  id.iy(),
1393                  towid.ieta() / abs(towid.ieta()),
1394                  id.hashedIndex(),
1395                  id.ic(),
1396                  cmsswId,
1397                  dbId,
1398                  towid.ieta(),
1399                  towid.iphi(),
1400                  TCCch,
1401                  getCrate(tccNb).second,
1402                  SLBch,
1403                  SLBslot,
1404                  getGCTRegionEta(towid.ieta()),
1405                  getGCTRegionPhi(towid.iphi())};
1406     for (int i = 0; i < 26; i++)
1407       ntupleInts_[i] = val[i];
1408     strcpy(ntupleDet_, getDet(tccNb).c_str());
1409     strcpy(ntupleCrate_, getCrate(tccNb).first.c_str());
1410     ntuple->Fill();
1411 
1412     if ((tccNb == 76 || tccNb == 94) && stripInTower == 1 && xtalInStrip == 3 && (towerInTCC - 1) % 4 == 0) {
1413       int etaSlice = towid.ietaAbs();
1414       coeffStruc coeff;
1415       //getCoeff(coeff, calibMap, id.rawId()) ;
1416       //modif-alex-27-july-2015
1417       std::string str;
1418       getCoeff(coeff, calibMap, laserAlphaMap, id.rawId(), str);
1419       ss << str;
1420       getCoeff(coeff, gainMap, id.rawId());
1421       getCoeff(coeff, pedMap, id.rawId());
1422       linStruc lin;
1423       for (int i = 0; i < 3; i++) {
1424         lin.pedestal_[i] = coeff.pedestals_[i];
1425         lin.mult_[i] = 0;
1426         lin.shift_[i] = 0;
1427         int mult = 0;
1428         int shift = 0;
1429         bool ok = computeLinearizerParam(theta, coeff.gainRatio_[i], coeff.calibCoeff_, "EE", mult, shift);
1430         if (!ok) {
1431           //If the mult is impossible to compute
1432           if (mult > 255) {
1433             edm::LogError("TopInfo") << "ByEtaSlice: unable to compute the parameters for Quadrant=" << id.iquadrant()
1434                                      << " xt=" << id.ic() << " " << dec << id.rawId() << " gainId=" << i
1435                                      << ", mult too large! forced to mult=255, shift=0\n";
1436             lin.mult_[i] = 255;
1437             lin.shift_[i] = 0;
1438           } else if (mult < 128) {
1439             edm::LogError("TopInfo") << "ByEtaSlice: unable to compute the parameters for Quadrant=" << id.iquadrant()
1440                                      << " xt=" << id.ic() << " " << dec << id.rawId() << " gainId=" << i
1441                                      << ", mult too small! forced to mult=128, shift=15\n";
1442             ;
1443             lin.mult_[i] = 128;
1444             lin.shift_[i] = 15;
1445           }
1446         } else {
1447           lin.mult_[i] = mult;
1448           lin.shift_[i] = shift;
1449         }
1450       }
1451 
1452       bool ok(true);
1453       if (forcedPedestalValue_ == -2 || forcedPedestalValue_ == -3)
1454         ok = realignBaseline(lin, 0, id.rawId());
1455       if (!ok)
1456         ss << "Quadrant=" << id.iquadrant() << " xt=" << id.ic() << " " << dec << id.rawId() << "\n";
1457 
1458       linEtaSlice[etaSlice] = lin;
1459     }
1460   }
1461 
1462   // general case
1463   for (vector<DetId>::const_iterator it = eeCells.begin(); it != eeCells.end(); ++it) {
1464     EEDetId id(*it);
1465     double theta = theEndcapGeometry_->getGeometry(id)->getPosition().theta();
1466     if (!useTransverseEnergy_)
1467       theta = acos(0.);
1468     const EcalTrigTowerDetId towid = (*eTTmap_).towerOf(id);
1469     const EcalTriggerElectronicsId elId = theMapping_->getTriggerElectronicsId(id);
1470     const EcalElectronicsId Id = theMapping_->getElectronicsId(id);
1471     towerListEE.push_back(towid.rawId());
1472     // special case of towers in inner rings of EE
1473     if (towid.ietaAbs() == 27 || towid.ietaAbs() == 28) {
1474       EcalTrigTowerDetId additionalTower(towid.zside(), towid.subDet(), towid.ietaAbs(), towid.iphi() + 1);
1475       towerListEE.push_back(additionalTower.rawId());
1476     }
1477     stripListEE.push_back(elId.rawId() & 0xfffffff8);
1478 
1479     int dccNb = Id.dccId();
1480     //int tccNb = theMapping_->TCCid(towid) ;
1481     //int towerInTCC = theMapping_->iTT(towid) ;
1482     //int stripInTower = elId.pseudoStripId() ;
1483     //int xtalInStrip = elId.channelId() ;
1484     int CCUid = Id.towerId();
1485     int VFEid = Id.stripId();
1486     int xtalInVFE = Id.xtalId();
1487     int xtalWithinCCUid = 5 * (VFEid - 1) + xtalInVFE - 1;  // Evgueni expects [0,24]
1488     int etaSlice = towid.ietaAbs();
1489 
1490     EcalLogicID logicId;
1491     FEConfigPedDat pedDB;
1492     FEConfigLinDat linDB;
1493     if (writeToFiles_)
1494       (*out_file_) << "CRYSTAL " << dec << id.rawId() << std::endl;
1495     if (writeToDB_ && DBEE_) {
1496       int iz = id.positiveZ();
1497       if (iz == 0)
1498         iz = -1;
1499       for (int k = 0; k < (int)my_CrystalEcalLogicId_EE.size(); k++) {
1500         int z = my_CrystalEcalLogicId_EE[k].getID1();
1501         int x = my_CrystalEcalLogicId_EE[k].getID2();
1502         int y = my_CrystalEcalLogicId_EE[k].getID3();
1503         if (id.ix() == x && id.iy() == y && iz == z) {
1504           logicId = my_CrystalEcalLogicId_EE[k];
1505         }
1506       }
1507     }
1508 
1509     coeffStruc coeff;
1510     //getCoeff(coeff, calibMap, id.rawId()) ;
1511     //modif-alex-27-july-2015
1512     string str;
1513     getCoeff(coeff, calibMap, laserAlphaMap, id.rawId(), str);
1514     ss << str;
1515     getCoeff(coeff, gainMap, id.rawId());
1516     getCoeff(coeff, pedMap, id.rawId());
1517     if (id.zside() > 0)
1518       ICEEPlus->Fill(id.ix(), id.iy(), coeff.calibCoeff_);
1519     else
1520       ICEEMinus->Fill(id.ix(), id.iy(), coeff.calibCoeff_);
1521     IC->Fill(theEndcapGeometry_->getGeometry(id)->getPosition().phi(),
1522              theEndcapGeometry_->getGeometry(id)->getPosition().eta(),
1523              coeff.calibCoeff_);
1524 
1525     vector<int> xtalCCU;
1526     xtalCCU.push_back(dccNb + 600);
1527     xtalCCU.push_back(CCUid);
1528     xtalCCU.push_back(xtalWithinCCUid);
1529     xtalCCU.push_back(id.rawId());
1530 
1531     // compute and fill linearization parameters
1532     // case of eta slice
1533     if (forceEtaSlice_) {
1534       map<int, linStruc>::const_iterator itLin = linEtaSlice.find(etaSlice);
1535       if (itLin != linEtaSlice.end()) {
1536         linMap[xtalCCU] = itLin->second;
1537         if (writeToFiles_) {
1538           for (int i = 0; i < 3; i++)
1539             (*out_file_) << hex << " 0x" << itLin->second.pedestal_[i] << " 0x" << itLin->second.mult_[i] << " 0x"
1540                          << itLin->second.shift_[i] << std::endl;
1541         }
1542         if (writeToDB_ && DBEE_) {
1543           for (int i = 0; i < 3; i++) {
1544             if (i == 0) {
1545               pedDB.setPedMeanG12(itLin->second.pedestal_[i]);
1546               linDB.setMultX12(itLin->second.mult_[i]);
1547               linDB.setShift12(itLin->second.shift_[i]);
1548             } else if (i == 1) {
1549               pedDB.setPedMeanG6(itLin->second.pedestal_[i]);
1550               linDB.setMultX6(itLin->second.mult_[i]);
1551               linDB.setShift6(itLin->second.shift_[i]);
1552             } else if (i == 2) {
1553               pedDB.setPedMeanG1(itLin->second.pedestal_[i]);
1554               linDB.setMultX1(itLin->second.mult_[i]);
1555               linDB.setShift1(itLin->second.shift_[i]);
1556             }
1557           }
1558         }
1559         float factor = float(itLin->second.mult_[0]) * pow(2., -itLin->second.shift_[0]) / xtal_LSB_EE_;
1560         if (id.zside() > 0)
1561           tpgFactorEEPlus->Fill(id.ix(), id.iy(), factor);
1562         else
1563           tpgFactorEEMinus->Fill(id.ix(), id.iy(), factor);
1564         tpgFactor->Fill(theEndcapGeometry_->getGeometry(id)->getPosition().phi(),
1565                         theEndcapGeometry_->getGeometry(id)->getPosition().eta(),
1566                         factor);
1567       } else
1568         ss << "current EtaSlice = " << etaSlice << " not found in the EtaSlice map"
1569            << "\n";
1570     } else {
1571       // general case
1572       linStruc lin;
1573       for (int i = 0; i < 3; i++) {
1574         lin.pedestal_[i] = coeff.pedestals_[i];
1575         lin.mult_[i] = 0;
1576         lin.shift_[i] = 0;
1577         int mult = 0;
1578         int shift = 0;
1579         bool ok = computeLinearizerParam(theta, coeff.gainRatio_[i], coeff.calibCoeff_, "EE", mult, shift);
1580         if (!ok) {
1581           //If the mult is impossible to compute
1582           if (mult > 255) {
1583             edm::LogError("TopInfo") << "unable to compute the parameters for " << dec << id.rawId()
1584                                      << ", EE, gainId=" << i << ", mult too large! forced to mult=255, shift=0\n";
1585             lin.mult_[i] = 255;
1586             lin.shift_[i] = 0;
1587           } else if (mult < 128) {
1588             edm::LogError("TopInfo") << "unable to compute the parameters for " << dec << id.rawId()
1589                                      << ", EE, gainId=" << i << ", mult too small! forced to mult=128, shift=15\n";
1590             lin.mult_[i] = 128;
1591             lin.shift_[i] = 15;
1592           }
1593         } else {
1594           lin.mult_[i] = mult;
1595           lin.shift_[i] = shift;
1596         }
1597       }
1598 
1599       bool ok(true);
1600       if (forcedPedestalValue_ == -2 || forcedPedestalValue_ == -3)
1601         ok = realignBaseline(lin, 0, id.rawId());
1602       if (!ok)
1603         ss << "Quadrant=" << id.iquadrant() << " xt=" << id.ic() << " " << dec << id.rawId() << "\n";
1604 
1605       for (int i = 0; i < 3; i++) {
1606         if (writeToFiles_)
1607           (*out_file_) << hex << " 0x" << lin.pedestal_[i] << " 0x" << lin.mult_[i] << " 0x" << lin.shift_[i]
1608                        << std::endl;
1609         if (writeToDB_ && DBEE_) {
1610           if (i == 0) {
1611             pedDB.setPedMeanG12(lin.pedestal_[i]);
1612             linDB.setMultX12(lin.mult_[i]);
1613             linDB.setShift12(lin.shift_[i]);
1614           } else if (i == 1) {
1615             pedDB.setPedMeanG6(lin.pedestal_[i]);
1616             linDB.setMultX6(lin.mult_[i]);
1617             linDB.setShift6(lin.shift_[i]);
1618           } else if (i == 2) {
1619             pedDB.setPedMeanG1(lin.pedestal_[i]);
1620             linDB.setMultX1(lin.mult_[i]);
1621             linDB.setShift1(lin.shift_[i]);
1622           }
1623         }
1624         if (i == 0) {
1625           float factor = float(lin.mult_[i]) * pow(2., -lin.shift_[i]) / xtal_LSB_EE_;
1626           if (id.zside() > 0)
1627             tpgFactorEEPlus->Fill(id.ix(), id.iy(), factor);
1628           else
1629             tpgFactorEEMinus->Fill(id.ix(), id.iy(), factor);
1630           tpgFactor->Fill(theEndcapGeometry_->getGeometry(id)->getPosition().phi(),
1631                           theEndcapGeometry_->getGeometry(id)->getPosition().eta(),
1632                           factor);
1633         }
1634       }
1635       linMap[xtalCCU] = lin;
1636     }
1637     if (writeToDB_ && DBEE_) {
1638       pedset[logicId] = pedDB;
1639       linset[logicId] = linDB;
1640     }
1641   }  //eeCells
1642   edm::LogInfo("TopInfo") << ss.str();
1643   ss.str("");
1644 
1645   if (writeToDB_) {
1646     // EcalLogicID  of the whole barrel is: my_EcalLogicId_EB
1647     FEConfigLinParamDat linparam;
1648     linparam.setETSat(Et_sat_EE_);
1649     linparamset[my_EcalLogicId_EE] = linparam;
1650 
1651     FEConfigLUTParamDat lutparam;
1652     lutparam.setETSat(Et_sat_EE_);
1653     lutparam.setTTThreshlow(TTF_lowThreshold_EE_);
1654     lutparam.setTTThreshhigh(TTF_highThreshold_EE_);
1655     lutparamset[my_EcalLogicId_EE] = lutparam;
1656 
1657     FEConfigFgrParamDat fgrparam;
1658     fgrparam.setFGlowthresh(FG_Threshold_EE_);
1659     fgrparam.setFGhighthresh(FG_Threshold_EE_);
1660     fgrparamset[my_EcalLogicId_EE] = fgrparam;
1661   }
1662 
1663   if (writeToDB_) {
1664     ostringstream ltag;
1665     ltag.str("EB_");
1666     ltag << Et_sat_EB_ << "_EE_" << Et_sat_EE_;
1667     std::string lin_tag = ltag.str();
1668     ss << " LIN tag " << lin_tag << "\n";
1669 
1670     if (m_write_ped == 1) {
1671       ped_conf_id_ = db_->writeToConfDB_TPGPedestals(pedset, 1, "from_OfflineDB");
1672     } else {
1673       ss << "the ped id =" << ped_conf_id_ << " will be used for the pedestals "
1674          << "\n";
1675     }
1676 
1677     if (m_write_lin == 1)
1678       lin_conf_id_ = db_->writeToConfDB_TPGLinearCoef(linset, linparamset, 1, lin_tag);
1679   }
1680 
1681   /////////////////////
1682   // Evgueni interface
1683   ////////////////////
1684   std::ofstream evgueni("TPG_hardcoded.hh", std::ios::out);
1685   evgueni << "void getLinParamTPG_hardcoded(int fed, int ccu, int xtal," << std::endl;
1686   evgueni << "                        int & mult12, int & shift12, int & base12," << std::endl;
1687   evgueni << "                        int & mult6, int & shift6, int & base6," << std::endl;
1688   evgueni << "                        int & mult1, int & shift1, int & base1)" << std::endl;
1689   evgueni << "{" << std::endl;
1690   evgueni << "  mult12 = 0 ; shift12 = 0 ; base12 = 0 ; mult6 = 0 ; shift6 = 0 ; base6 = 0 ; mult1 = 0 ; shift1 = 0 ; "
1691              "base1 = 0 ;"
1692           << std::endl;
1693   map<vector<int>, linStruc>::const_iterator itLinMap;
1694   for (itLinMap = linMap.begin(); itLinMap != linMap.end(); itLinMap++) {
1695     vector<int> xtalInCCU = itLinMap->first;
1696     evgueni << "  if (fed==" << xtalInCCU[0] << " && ccu==" << xtalInCCU[1] << " && xtal==" << xtalInCCU[2] << ") {";
1697     evgueni << "  mult12 = " << itLinMap->second.mult_[0] << " ; shift12 = " << itLinMap->second.shift_[0]
1698             << " ; base12 = " << itLinMap->second.pedestal_[0] << " ; ";
1699     evgueni << "  mult6 = " << itLinMap->second.mult_[1] << " ; shift6 = " << itLinMap->second.shift_[1]
1700             << " ; base6 = " << itLinMap->second.pedestal_[1] << " ; ";
1701     evgueni << "  mult1 = " << itLinMap->second.mult_[2] << " ; shift1 = " << itLinMap->second.shift_[2]
1702             << " ; base1 = " << itLinMap->second.pedestal_[2] << " ; ";
1703     evgueni << "  return ;}" << std::endl;
1704   }
1705   evgueni << "}" << std::endl;
1706   evgueni.close();
1707 
1708   /////////////////////////////
1709   // Compute weights section //
1710   /////////////////////////////
1711 
1712   std::map<int, int> weights_map_even;
1713   std::map<int, int> weights_map_odd;
1714 
1715   if (weight_even_computeFromShape_) {
1716     // Computing the weights from shapes, 1 set for EB and 1 for EE only
1717     shapeEB_.setEventSetup(evtSetup);  // EBShape, EEShape are fetched now from DB (2018.05.22 K. Theofilatos)
1718     shapeEE_.setEventSetup(evtSetup);
1719     const int NWEIGROUPS = 2;
1720     std::vector<unsigned int> weights[NWEIGROUPS];
1721     weights[0] = computeWeights(shapeEB_, hshapeEB);
1722     weights[1] = computeWeights(shapeEE_, hshapeEE);
1723 
1724     map<EcalLogicID, FEConfigWeightGroupDat> dataset;
1725 
1726     for (int igrp = 0; igrp < NWEIGROUPS; igrp++) {
1727       if (weights[igrp].size() == EcalTPGParamBuilder::NWEIGHTS) {
1728         if (writeToFiles_) {
1729           (*out_file_) << std::endl;
1730           (*out_file_) << "WEIGHT " << dec << igrp << std::endl;
1731           for (unsigned int sample = 0; sample < EcalTPGParamBuilder::NWEIGHTS; sample++)
1732             (*out_file_) << "0x" << hex << weights[igrp][sample] << " ";
1733           (*out_file_) << std::endl;
1734           (*out_file_) << std::endl;
1735         }
1736         if (writeToDB_) {
1737           ss << "going to write the weights for group:" << igrp << "\n";
1738           FEConfigWeightGroupDat gut;
1739           gut.setWeightGroupId(igrp);
1740           //PP WARNING: weights order is reverted when stored in the DB
1741           gut.setWeight0(weights[igrp][4]);
1742           gut.setWeight1(weights[igrp][3] +
1743                          0x80);  //0x80 to identify the max of the pulse in the FENIX (doesn't exist in emulator)
1744           gut.setWeight2(weights[igrp][2]);
1745           gut.setWeight3(weights[igrp][1]);
1746           gut.setWeight4(weights[igrp][0]);
1747           EcalLogicID ecid = EcalLogicID("DUMMY", igrp, igrp);  //1 dummy ID per group
1748           // Fill the dataset
1749           dataset[ecid] = gut;
1750         }
1751       }
1752     }
1753     // now we store in the DB the correspondence btw channels and groups
1754     map<EcalLogicID, FEConfigWeightDat> dataset2;
1755     // EB loop
1756     for (int ich = 0; ich < (int)my_StripEcalLogicId.size(); ich++) {
1757       FEConfigWeightDat wut;
1758       int igroup = 0;  // this group is for EB
1759       weights_map_even[stripMapEB[ich]] = 0;
1760       wut.setWeightGroupId(igroup);
1761       dataset2[my_StripEcalLogicId[ich]] = wut;
1762     }
1763 
1764     // EE loop
1765     for (EcalLogicID& stripLogicId : my_StripEcalLogicId1_EE) {
1766       FEConfigWeightDat wut;
1767       int igroup = 1;  // this group is for EE
1768       weights_map_even[stripMapEE[stripLogicId.getLogicID()]] = 1;
1769       wut.setWeightGroupId(igroup);
1770       // Fill the dataset
1771       dataset2[stripLogicId] = wut;
1772     }
1773     // EE loop 2 (we had to split the ids of EE in 2 vectors to avoid crash!)
1774     for (EcalLogicID& stripLogicId : my_StripEcalLogicId2_EE) {
1775       FEConfigWeightDat wut;
1776       int igroup = 1;  // this group is for EE
1777       weights_map_even[stripMapEE[stripLogicId.getLogicID()]] = 1;
1778       wut.setWeightGroupId(igroup);
1779       // Fill the dataset
1780       dataset2[stripLogicId] = wut;
1781     }
1782 
1783     if (writeToDB_) {
1784       // Insert the datasets
1785       ostringstream wtag;
1786       wtag.str("");
1787       wtag << "Shape_NGroups_" << NWEIGROUPS;
1788       std::string weight_tag = wtag.str();
1789       ss << " weight tag " << weight_tag << "\n";
1790       if (m_write_wei == 1)
1791         wei_conf_id_ = db_->writeToConfDB_TPGWeight(dataset, dataset2, NWEIGROUPS, weight_tag);
1792     }
1793     /////////////////////////////////////////////////////////
1794   } else {
1795     // Read Even weights from file.
1796     std::vector<std::vector<unsigned int>> weights_even;
1797 
1798     std::ifstream file(weight_even_weightGroupFile_);
1799     std::string line;
1800     while (std::getline(file, line)) {
1801       std::istringstream iss(line);
1802       std::vector<unsigned int> wei_group_even;
1803       for (std::string s; iss >> s;)
1804         wei_group_even.push_back(stoi(s));
1805       weights_even.push_back(wei_group_even);
1806     }
1807     int nweigroups_even = weights_even.size();
1808 
1809     std::ifstream file2(weight_even_idMapFile_);
1810     std::string line2;
1811     while (std::getline(file2, line2)) {
1812       std::istringstream iss(line2);
1813       int ch_id, wei_gr;
1814       iss >> std::dec >> ch_id;
1815       iss >> std::dec >> wei_gr;
1816       int wei_group = wei_gr;
1817       if (wei_group > nweigroups_even - 1) {
1818         edm::LogError("TopInfo") << "Associating strip: " << ch_id << " to non-existing weight group: " << wei_gr
1819                                  << "\n";
1820       }
1821       weights_map_even[ch_id] = wei_group;
1822     }
1823 
1824     map<EcalLogicID, FEConfigWeightGroupDat> dataset_even;
1825 
1826     for (int igrp = 0; igrp < nweigroups_even; igrp++) {
1827       if (weights_even[igrp].size() == EcalTPGParamBuilder::NWEIGHTS) {
1828         if (writeToFiles_) {
1829           (*out_file_) << std::endl;
1830           (*out_file_) << "WEIGHT " << dec << igrp << std::endl;
1831           for (unsigned int sample = 0; sample < EcalTPGParamBuilder::NWEIGHTS; sample++)
1832             (*out_file_) << "0x" << hex << weights_even[igrp][sample] << " ";
1833           (*out_file_) << std::endl;
1834           (*out_file_) << std::endl;
1835         }
1836         if (writeToDB_) {
1837           ss << "going to write the weights for group:" << igrp << "\n";
1838           FEConfigWeightGroupDat gut;
1839           gut.setWeightGroupId(igrp);
1840           //PP WARNING: weights order is reverted when stored in the DB
1841           gut.setWeight0(weights_even[igrp][4]);
1842           gut.setWeight1(weights_even[igrp][3] +
1843                          0x80);  //0x80 to identify the max of the pulse in the FENIX (doesn't exist in emulator)
1844           gut.setWeight2(weights_even[igrp][2]);
1845           gut.setWeight3(weights_even[igrp][1]);
1846           gut.setWeight4(weights_even[igrp][0]);
1847           EcalLogicID ecid = EcalLogicID("DUMMY", igrp, igrp);  //1 dummy ID per group
1848           // Fill the dataset
1849           dataset_even[ecid] = gut;
1850         }
1851       }
1852     }
1853     if (writeToDB_) {
1854       // now we store in the DB the correspondence btw channels and groups
1855       map<EcalLogicID, FEConfigWeightDat> dataset_even_idmap;
1856       // EB loop
1857       for (int ich = 0; ich < (int)my_StripEcalLogicId.size(); ich++) {
1858         FEConfigWeightDat wut;
1859         int igroup = weights_map_even[stripMapEB[ich]];  // this group is for EB
1860         wut.setWeightGroupId(igroup);
1861         dataset_even_idmap[my_StripEcalLogicId[ich]] = wut;
1862       }
1863       // EE loop
1864       for (EcalLogicID& stripLogicId : my_StripEcalLogicId1_EE) {
1865         FEConfigWeightDat wut;
1866         int igroup = weights_map_even[stripMapEE[stripLogicId.getLogicID()]];
1867         wut.setWeightGroupId(igroup);
1868         // Fill the dataset
1869         dataset_even_idmap[stripLogicId] = wut;
1870       }
1871       // EE loop 2 (we had to split the ids of EE in 2 vectors to avoid crash!)
1872       for (EcalLogicID& stripLogicId : my_StripEcalLogicId2_EE) {
1873         FEConfigWeightDat wut;
1874         int igroup = weights_map_even[stripMapEE[stripLogicId.getLogicID()]];  // this group is for EE
1875         wut.setWeightGroupId(igroup);
1876         // Fill the dataset
1877         dataset_even_idmap[stripLogicId] = wut;
1878       }
1879       // Insert the datasets
1880       ostringstream wtag;
1881       wtag.str("");
1882       wtag << "Shape_even_NGroups_" << nweigroups_even;
1883       std::string weight_tag = wtag.str();
1884       ss << " weight tag " << weight_tag << "\n";
1885       if (m_write_wei == 1)
1886         wei_conf_id_ = db_->writeToConfDB_TPGWeight(dataset_even, dataset_even_idmap, nweigroups_even, weight_tag);
1887     }
1888   }
1889 
1890   //+=========================================================== Odd weights
1891   if (weight_useDoubleWeights_) {
1892     // Odd weights are always read from file
1893     std::vector<std::vector<unsigned int>> weights_odd;
1894     std::ifstream file3(weight_odd_weightGroupFile_);
1895     std::string line3;
1896     while (std::getline(file3, line3)) {
1897       std::istringstream iss(line3);
1898       std::vector<unsigned int> wei_group_odd;
1899       for (std::string s; iss >> s;)
1900         wei_group_odd.push_back(stoi(s));
1901       weights_odd.push_back(wei_group_odd);
1902     }
1903     int nweigroups_odd = weights_odd.size();
1904 
1905     std::ifstream file4(weight_odd_idMapFile_);
1906     std::string line4;
1907     while (std::getline(file4, line4)) {
1908       std::istringstream iss(line4);
1909       int ch_id, wei_gr;
1910       iss >> std::dec >> ch_id;
1911       iss >> std::dec >> wei_gr;
1912       int wei_group = wei_gr;
1913       if (wei_group > nweigroups_odd - 1) {
1914         edm::LogError("TopInfo") << "Associating strip: " << ch_id << " to non-existing weight group: " << wei_gr
1915                                  << "\n";
1916       }
1917       weights_map_odd[ch_id] = wei_group;
1918     }
1919 
1920     map<EcalLogicID, FEConfigOddWeightGroupDat> dataset_odd;
1921 
1922     for (int igrp = 0; igrp < nweigroups_odd; igrp++) {
1923       if (weights_odd[igrp].size() == EcalTPGParamBuilder::NWEIGHTS) {
1924         if (writeToFiles_) {
1925           (*out_file_) << std::endl;
1926           (*out_file_) << "WEIGHT_ODD " << dec << igrp << std::endl;
1927           for (unsigned int sample = 0; sample < EcalTPGParamBuilder::NWEIGHTS; sample++)
1928             (*out_file_) << "0x" << hex << weights_odd[igrp][sample] << " ";
1929           (*out_file_) << std::endl;
1930           (*out_file_) << std::endl;
1931         }
1932         if (writeToDB_) {
1933           ss << "going to write the weights for group:" << igrp << "\n";
1934           FEConfigOddWeightGroupDat gut;
1935           gut.setWeightGroupId(igrp);
1936           //PP WARNING: weights order is reverted when stored in the DB
1937           gut.setWeight0(weights_odd[igrp][4]);
1938           gut.setWeight1(weights_odd[igrp][3] +
1939                          0x80);  //0x80 to identify the max of the pulse in the FENIX (doesn't exist in emulator)
1940           gut.setWeight2(weights_odd[igrp][2]);
1941           gut.setWeight3(weights_odd[igrp][1]);
1942           gut.setWeight4(weights_odd[igrp][0]);
1943           EcalLogicID ecid = EcalLogicID("DUMMY", igrp, igrp);  //1 dummy ID per group
1944           // Fill the dataset
1945           dataset_odd[ecid] = gut;
1946         }
1947       }
1948     }
1949     // TP MODE configuration
1950     if (writeToFiles_) {
1951       (*out_file_) << std::endl;
1952       (*out_file_) << "TP_MODE " << std::endl;
1953       (*out_file_) << TPmode_EnableEBOddFilter_ << std::endl;
1954       (*out_file_) << TPmode_EnableEEOddFilter_ << std::endl;
1955       (*out_file_) << TPmode_EnableEBOddPeakFinder_ << std::endl;
1956       (*out_file_) << TPmode_EnableEEOddPeakFinder_ << std::endl;
1957       (*out_file_) << TPmode_DisableEBEvenPeakFinder_ << std::endl;
1958       (*out_file_) << TPmode_DisableEEEvenPeakFinder_ << std::endl;
1959       (*out_file_) << TPmode_FenixEBStripOutput_ << std::endl;
1960       (*out_file_) << TPmode_FenixEEStripOutput_ << std::endl;
1961       (*out_file_) << TPmode_FenixEBStripInfobit2_ << std::endl;
1962       (*out_file_) << TPmode_FenixEEStripInfobit2_ << std::endl;
1963       (*out_file_) << TPmode_FenixEBTcpOutput_ << std::endl;
1964       (*out_file_) << TPmode_FenixEBTcpInfobit1_ << std::endl;
1965       (*out_file_) << TPmode_FenixEETcpOutput_ << std::endl;
1966       (*out_file_) << TPmode_FenixEETcpInfobit1_ << std::endl;
1967       (*out_file_) << 0 << std::endl;  // FenixPar15-18 are placeholder parameters for future use
1968       (*out_file_) << 0 << std::endl;
1969       (*out_file_) << 0 << std::endl;
1970       (*out_file_) << 0 << std::endl;
1971       (*out_file_) << std::endl;
1972     }
1973 
1974     if (writeToDB_) {
1975       // now we store in the DB the correspondence btw channels and groups
1976       map<EcalLogicID, FEConfigOddWeightDat> dataset_odd_idmap;
1977 
1978       // EB loop
1979       for (int ich = 0; ich < (int)my_StripEcalLogicId.size(); ich++) {
1980         FEConfigOddWeightDat wut;
1981         int igroup = weights_map_odd[stripMapEB[ich]];  // this group is for EB
1982         wut.setWeightGroupId(igroup);
1983         dataset_odd_idmap[my_StripEcalLogicId[ich]] = wut;
1984       }
1985       // EE loop
1986       for (auto& stripLogicId : my_StripEcalLogicId1_EE) {
1987         FEConfigOddWeightDat wut;
1988         int igroup = weights_map_odd[stripMapEE[stripLogicId.getLogicID()]];
1989         wut.setWeightGroupId(igroup);
1990         // Fill the dataset
1991         dataset_odd_idmap[stripLogicId] = wut;
1992       }
1993       // EE loop 2 (we had to split the ids of EE in 2 vectors to avoid crash!)
1994       for (auto& stripLogicId : my_StripEcalLogicId2_EE) {
1995         FEConfigOddWeightDat wut;
1996         int igroup = weights_map_odd[stripMapEE[stripLogicId.getLogicID()]];  // this group is for EE
1997         wut.setWeightGroupId(igroup);
1998         // Fill the dataset
1999         dataset_odd_idmap[stripLogicId] = wut;
2000       }
2001       // TP mode on DB
2002       map<EcalLogicID, FEConfigOddWeightModeDat> dataset_tpmode;
2003       FEConfigOddWeightModeDat tp_mode;
2004       tp_mode.setEnableEBOddFilter(TPmode_EnableEBOddFilter_);
2005       tp_mode.setEnableEEOddFilter(TPmode_EnableEEOddFilter_);
2006       tp_mode.setEnableEBOddPeakFinder(TPmode_EnableEBOddPeakFinder_);
2007       tp_mode.setEnableEEOddPeakFinder(TPmode_EnableEEOddPeakFinder_);
2008       tp_mode.setDisableEBEvenPeakFinder(TPmode_DisableEBEvenPeakFinder_);
2009       tp_mode.setDisableEEEvenPeakFinder(TPmode_DisableEEEvenPeakFinder_);
2010       tp_mode.setFenixEBStripOutput(TPmode_FenixEBStripOutput_);
2011       tp_mode.setFenixEEStripOutput(TPmode_FenixEEStripOutput_);
2012       tp_mode.setFenixEBStripInfobit2(TPmode_FenixEBStripInfobit2_);
2013       tp_mode.setFenixEEStripInfobit2(TPmode_FenixEEStripInfobit2_);
2014       tp_mode.setFenixEBTcpOutput(TPmode_FenixEBTcpOutput_);
2015       tp_mode.setFenixEBTcpInfoBit1(TPmode_FenixEBTcpInfobit1_);
2016       tp_mode.setFenixEETcpOutput(TPmode_FenixEETcpOutput_);
2017       tp_mode.setFenixEETcpInfoBit1(TPmode_FenixEETcpInfobit1_);
2018       dataset_tpmode[my_StripEcalLogicId[0]] = tp_mode;  // The LogicID is not used in reality....
2019 
2020       // Insert the datasets
2021       ostringstream wtag;
2022       wtag.str("");
2023       wtag << "Shape_odd_NGroups_" << nweigroups_odd;
2024       std::string weight_tag = wtag.str();
2025       ss << " weight tag " << weight_tag << "\n";
2026       if (m_write_wei2 == 1)
2027         wei2_conf_id_ = db_->writeToConfDB_TPGWeight_doubleWeights(
2028             dataset_odd, dataset_odd_idmap, dataset_tpmode, nweigroups_odd, weight_tag);
2029     }
2030 
2031   } else {
2032     // If useDoubleWeight == False we need to use the default
2033     // wei2_conf_id=1 and save a blank TP mode and blank Odd weight group
2034     if (writeToFiles_) {
2035       // single set of ODD weights ==0 is written to the txt file
2036       (*out_file_) << "WEIGHT_ODD " << dec << 0 << std::endl;
2037       for (unsigned int sample = 0; sample < EcalTPGParamBuilder::NWEIGHTS; sample++)
2038         (*out_file_) << "0x0"
2039                      << " ";
2040       (*out_file_) << std::endl << std::endl;
2041 
2042       // Default TP mode with Run2 config == all parameters to 0
2043       (*out_file_) << "TP_MODE " << std::endl;
2044       for (int m = 0; m < 18; m++)
2045         (*out_file_) << 0 << std::endl;
2046       (*out_file_) << std::endl;
2047     }
2048     wei2_conf_id_ = 1;  // special value that is interpreted by online DAQ code as Run2 configuration
2049   }
2050 
2051   edm::LogInfo("TopInfo") << ss.str();
2052   ss.str("");
2053 
2054   /////////////////////////
2055   // Compute FG section //
2056   /////////////////////////
2057 
2058   // barrel
2059   unsigned int lowRatio, highRatio, lowThreshold, highThreshold, lutFG;
2060   computeFineGrainEBParameters(lowRatio, highRatio, lowThreshold, highThreshold, lutFG);
2061   if (writeToFiles_) {
2062     (*out_file_) << std::endl;
2063     (*out_file_) << "FG 0" << std::endl;
2064     (*out_file_) << hex << "0x" << lowThreshold << " 0x" << highThreshold << " 0x" << lowRatio << " 0x" << highRatio
2065                  << " 0x" << lutFG << std::endl;
2066   }
2067 
2068   // endcap
2069   unsigned int threshold, lut_tower;
2070   unsigned int lut_strip;
2071   computeFineGrainEEParameters(threshold, lut_strip, lut_tower);
2072 
2073   // and here we store the fgr part
2074 
2075   if (writeToDB_) {
2076     ss << "going to write the fgr "
2077        << "\n";
2078     map<EcalLogicID, FEConfigFgrGroupDat> dataset;
2079     // we create 1 group
2080     int NFGRGROUPS = 1;
2081     for (int ich = 0; ich < NFGRGROUPS; ich++) {
2082       FEConfigFgrGroupDat gut;
2083       gut.setFgrGroupId(ich);
2084       gut.setThreshLow(lowRatio);
2085       gut.setThreshHigh(highRatio);
2086       gut.setRatioLow(lowThreshold);
2087       gut.setRatioHigh(highThreshold);
2088       gut.setLUTValue(lutFG);
2089       EcalLogicID ecid = EcalLogicID("DUMMY", ich, ich);
2090       // Fill the dataset
2091       dataset[ecid] = gut;  // we use any logic id but different, because it is in any case ignored...
2092     }
2093 
2094     // now we store in the DB the correspondence btw channels and groups
2095     map<EcalLogicID, FEConfigFgrDat> dataset2;
2096     for (auto& id : my_TTEcalLogicId) {
2097       FEConfigFgrDat wut;
2098       int igroup = 0;
2099       wut.setFgrGroupId(igroup);
2100       // Fill the dataset
2101       // the logic ids are ordered by SM (1,...36) and TT (1,...68)
2102       dataset2[id] = wut;
2103     }
2104 
2105     // endcap loop
2106     for (auto& id : my_RTEcalLogicId_EE) {
2107       //    std::cout << " endcap FGR " << std::endl;
2108       FEConfigFgrDat wut;
2109       int igroup = 0;
2110       wut.setFgrGroupId(igroup);
2111       // Fill the dataset
2112       // the logic ids are ordered by .... ?
2113       // you have to calculate the right index here
2114       dataset2[id] = wut;
2115     }
2116 
2117     // endcap TT loop for the FEfgr EE Tower
2118     map<EcalLogicID, FEConfigFgrEETowerDat> dataset3;
2119     for (auto& id : my_TTEcalLogicId_EE) {
2120       FEConfigFgrEETowerDat fgreett;
2121       fgreett.setLutValue(lut_tower);
2122       dataset3[id] = fgreett;
2123     }
2124 
2125     // endcap strip loop for the FEfgr EE strip
2126     // and barrel strip loop for the spike parameters (same structure than EE FGr)
2127     map<EcalLogicID, FEConfigFgrEEStripDat> dataset4;
2128     for (auto& id : my_StripEcalLogicId1_EE) {
2129       FEConfigFgrEEStripDat zut;
2130       zut.setThreshold(threshold);
2131       zut.setLutFgr(lut_strip);
2132       dataset4[id] = zut;
2133     }
2134     for (auto& id : my_StripEcalLogicId2_EE) {
2135       FEConfigFgrEEStripDat zut;
2136       zut.setThreshold(threshold);
2137       zut.setLutFgr(lut_strip);
2138       // Fill the dataset
2139       dataset4[id] = zut;
2140     }
2141     for (int ich = 0; ich < (int)my_StripEcalLogicId.size(); ich++) {
2142       // EB
2143       FEConfigFgrEEStripDat zut;
2144       EcalLogicID thestrip = my_StripEcalLogicId[ich];
2145       uint32_t elStripId = stripMapEB[ich];
2146       map<uint32_t, uint32_t>::const_iterator it = stripMapEBsintheta.find(elStripId);
2147       if (it != stripMapEBsintheta.end())
2148         zut.setThreshold(it->second);
2149       else {
2150         edm::LogError("TopInfo") << "ERROR: strip SFGVB threshold parameter not found for that strip:"
2151                                  << thestrip.getID1() << " " << thestrip.getID3() << " " << thestrip.getID3() << "\n";
2152         edm::LogError("TopInfo") << " using value = " << SFGVB_Threshold_ + pedestal_offset_ << "\n";
2153         zut.setThreshold(SFGVB_Threshold_ + pedestal_offset_);
2154       }
2155       zut.setLutFgr(SFGVB_lut_);
2156       // Fill the dataset
2157       dataset4[thestrip] = zut;
2158     }
2159 
2160     // Insert the dataset
2161     ostringstream wtag;
2162     wtag.str("");
2163     wtag << "FGR_" << lutFG << "_N_" << NFGRGROUPS << "_eb_" << FG_lowThreshold_EB_ << "_EB_" << FG_highThreshold_EB_;
2164     std::string weight_tag = wtag.str();
2165     ss << " weight tag " << weight_tag << "\n";
2166     if (m_write_fgr == 1)
2167       fgr_conf_id_ =
2168           db_->writeToConfDB_TPGFgr(dataset, dataset2, fgrparamset, dataset3, dataset4, NFGRGROUPS, weight_tag);
2169 
2170     //modif-alex 21/01/11
2171     map<EcalLogicID, FEConfigSpikeDat> datasetspike;  //loob EB TT
2172     for (auto& id : my_TTEcalLogicId) {
2173       FEConfigSpikeDat spiketh;
2174       spiketh.setSpikeThreshold(SFGVB_SpikeKillingThreshold_);
2175       datasetspike[id] = spiketh;
2176     }  //loop EB TT towers
2177 
2178     //modif-alex 21/01/11
2179     ostringstream stag;
2180     stag.str("");
2181     stag << "SpikeTh" << SFGVB_SpikeKillingThreshold_;
2182     std::string spike_tag = stag.str();
2183     ss << " spike tag " << spike_tag << "\n";
2184     if (m_write_spi == 1)
2185       spi_conf_id_ = db_->writeToConfDB_Spike(datasetspike, spike_tag);  //modif-alex 21/01/11
2186 
2187     //modif-alex 31/01/11
2188     //DELAYS EB
2189     map<EcalLogicID, FEConfigTimingDat>
2190         datasetdelay;  // the loop goes from TCC 38 to 72 and throught the towers from 1 to 68
2191     for (int ich = 0; ich < (int)my_TTEcalLogicId_EB_by_TCC.size(); ich++) {
2192       FEConfigTimingDat delay;
2193 
2194       EcalLogicID logiciddelay = my_TTEcalLogicId_EB_by_TCC[ich];
2195       int id1_tcc = logiciddelay.getID1();  // the TCC
2196       int id2_tt = logiciddelay.getID2();   // the tower
2197       std::map<int, vector<int>>::const_iterator ittEB = delays_EB_.find(id1_tcc);
2198       std::vector<int> TimingDelaysEB = ittEB->second;
2199 
2200       if (ittEB != delays_EB_.end()) {
2201         if (TimingDelaysEB[id2_tt - 1] == -1) {
2202           edm::LogError("TopInfo") << "ERROR: Barrel timing delay not specified, check file, putting default value 1"
2203                                    << "\n";
2204           delay.setTimingPar1(1);
2205         } else
2206           delay.setTimingPar1(TimingDelaysEB[id2_tt - 1]);
2207       } else {
2208         edm::LogError("TopInfo") << "ERROR:Barrel Could not find delay parameter for that trigger tower "
2209                                  << "\n";
2210         edm::LogError("TopInfo") << "Using default value = 1"
2211                                  << "\n";
2212         delay.setTimingPar1(1);
2213       }
2214 
2215       std::map<int, vector<int>>::const_iterator ittpEB = phases_EB_.find(id1_tcc);
2216       std::vector<int> TimingPhasesEB = ittpEB->second;
2217 
2218       if (ittpEB != phases_EB_.end()) {
2219         if (TimingPhasesEB[id2_tt - 1] == -1) {
2220           edm::LogError("TopInfo") << "ERROR: Barrel timing phase not specified, check file, putting default value 0"
2221                                    << "\n";
2222           delay.setTimingPar2(0);
2223         } else
2224           delay.setTimingPar2(TimingPhasesEB[id2_tt - 1]);
2225       } else {
2226         edm::LogError("TopInfo") << "ERROR:Barrel Could not find phase parameter for that trigger tower "
2227                                  << "\n";
2228         edm::LogError("TopInfo") << "Using default value = 0"
2229                                  << "\n";
2230         delay.setTimingPar2(0);
2231       }
2232 
2233       ss << ich << " tcc=" << id1_tcc << " TT=" << id2_tt << " logicId=" << logiciddelay.getLogicID()
2234          << " delay=" << TimingDelaysEB[id2_tt - 1] << " phase=" << TimingPhasesEB[id2_tt - 1] << "\n";
2235 
2236       //delay.setTimingPar1(1);
2237       //delay.setTimingPar2(2);
2238       datasetdelay[logiciddelay] = delay;
2239     }  //loop EB TT towers
2240 
2241     //DELAYS EE
2242     int stripindex = 0;
2243     int tccin = 1;
2244     for (int ich = 0; ich < (int)my_StripEcalLogicId_EE_strips_by_TCC.size(); ich++) {
2245       FEConfigTimingDat delay;
2246 
2247       EcalLogicID logiciddelay = my_StripEcalLogicId_EE_strips_by_TCC[ich];
2248       int id1_tcc = logiciddelay.getID1();  // the TCC
2249       int id2_tt = logiciddelay.getID2();   // the tower
2250       int id3_st = logiciddelay.getID3();   // the strip
2251 
2252       //reset strip counter
2253       if (id1_tcc != tccin) {
2254         tccin = id1_tcc;
2255         stripindex = 0;
2256       }
2257 
2258       std::map<int, vector<int>>::const_iterator ittEE = delays_EE_.find(id1_tcc);
2259       std::vector<int> TimingDelaysEE = ittEE->second;
2260 
2261       if (ittEE != delays_EE_.end()) {
2262         if (TimingDelaysEE[stripindex] == -1) {
2263           edm::LogError("TopInfo") << "ERROR: Endcap timing delay not specified, check file, putting default value 1"
2264                                    << "\n";
2265           delay.setTimingPar1(1);
2266         } else
2267           delay.setTimingPar1(TimingDelaysEE[stripindex]);
2268       } else {
2269         edm::LogError("TopInfo") << "ERROR:Endcap Could not find delay parameter for that trigger tower "
2270                                  << "\n";
2271         edm::LogError("TopInfo") << "Using default value = 1"
2272                                  << "\n";
2273         delay.setTimingPar1(1);
2274       }
2275 
2276       std::map<int, vector<int>>::const_iterator ittpEE = phases_EE_.find(id1_tcc);
2277       std::vector<int> TimingPhasesEE = ittpEE->second;
2278 
2279       if (ittpEE != phases_EE_.end()) {
2280         if (TimingPhasesEE[stripindex] == -1) {
2281           edm::LogError("TopInfo") << "ERROR: Endcap timing phase not specified, check file, putting default value 0"
2282                                    << "\n";
2283           delay.setTimingPar2(0);
2284         } else
2285           delay.setTimingPar2(TimingPhasesEE[stripindex]);
2286       } else {
2287         edm::LogError("TopInfo") << "ERROR:Endcap Could not find phase parameter for that trigger tower "
2288                                  << "\n";
2289         edm::LogError("TopInfo") << "Using default value = 0"
2290                                  << "\n";
2291         delay.setTimingPar2(0);
2292       }
2293 
2294       ss << ich << " stripindex=" << stripindex << " tcc=" << id1_tcc << " TT=" << id2_tt << " id3_st=" << id3_st
2295          << " logicId=" << logiciddelay.getLogicID() << " delay=" << TimingDelaysEE[stripindex]
2296          << " phase=" << TimingPhasesEE[stripindex] << "\n";
2297 
2298       //delay.setTimingPar1(1);
2299       //delay.setTimingPar2(2);
2300       datasetdelay[logiciddelay] = delay;
2301       stripindex++;
2302     }  //loop EE strip towers
2303 
2304     ostringstream de_tag;
2305     de_tag.str("");
2306     de_tag << "DelaysFromFile";
2307     std::string delay_tag = de_tag.str();
2308     ss << " delay tag " << delay_tag << "\n";
2309     if (m_write_del == 1)
2310       del_conf_id_ = db_->writeToConfDB_Delay(datasetdelay, delay_tag);  //modif-alex 31/01/11
2311 
2312   }  //write to DB
2313 
2314   if (writeToDB_) {
2315     ss << "going to write the sliding "
2316        << "\n";
2317     map<EcalLogicID, FEConfigSlidingDat> dataset;
2318     for (auto& id : my_StripEcalLogicId) {
2319       FEConfigSlidingDat wut;
2320       wut.setSliding(sliding_);
2321       // Fill the dataset
2322       // the logic ids are ordered by SM (1,...36) , TT (1,...68) and strip (1..5)
2323       dataset[id] = wut;
2324     }
2325 
2326     // endcap loop
2327     for (auto& id : my_StripEcalLogicId1_EE) {
2328       FEConfigSlidingDat wut;
2329       wut.setSliding(sliding_);
2330       dataset[id] = wut;
2331     }
2332     for (auto& id : my_StripEcalLogicId2_EE) {
2333       FEConfigSlidingDat wut;
2334       wut.setSliding(sliding_);
2335       dataset[id] = wut;
2336     }
2337 
2338     // Insert the dataset
2339     ostringstream wtag;
2340     wtag.str("");
2341     wtag << "Sliding_" << sliding_;
2342     std::string justatag = wtag.str();
2343     ss << " sliding tag " << justatag << "\n";
2344     int iov_id = 0;  // just a parameter ...
2345     if (m_write_sli == 1)
2346       sli_conf_id_ = db_->writeToConfDB_TPGSliding(dataset, iov_id, justatag);
2347   }
2348 
2349   /////////////////////////
2350   // Compute LUT section //
2351   /////////////////////////
2352 
2353   int lut_EB[1024], lut_EE[1024];
2354 
2355   // barrel
2356   computeLUT(lut_EB, "EB");
2357   if (writeToFiles_) {
2358     (*out_file_) << std::endl;
2359     (*out_file_) << "LUT 0" << std::endl;
2360     for (int i = 0; i < 1024; i++)
2361       (*out_file_) << "0x" << hex << lut_EB[i] << std::endl;
2362     (*out_file_) << std::endl;
2363   }
2364 
2365   // endcap
2366   computeLUT(lut_EE, "EE");
2367   // check first if lut_EB and lut_EE are the same
2368   bool newLUT(false);
2369   for (int i = 0; i < 1024; i++)
2370     if (lut_EE[i] != lut_EB[i])
2371       newLUT = true;
2372   if (newLUT && writeToFiles_) {
2373     (*out_file_) << std::endl;
2374     (*out_file_) << "LUT 1" << std::endl;
2375     for (int i = 0; i < 1024; i++)
2376       (*out_file_) << "0x" << hex << lut_EE[i] << std::endl;
2377     (*out_file_) << std::endl;
2378   }
2379 
2380   if (writeToDB_) {
2381     map<EcalLogicID, FEConfigLUTGroupDat> dataset;
2382     // we create 1 LUT group
2383     int NLUTGROUPS = 0;
2384     int ich = 0;
2385     FEConfigLUTGroupDat lut;
2386     lut.setLUTGroupId(ich);
2387     for (int i = 0; i < 1024; i++) {
2388       lut.setLUTValue(i, lut_EB[i]);
2389     }
2390     EcalLogicID ecid = EcalLogicID("DUMMY", ich, ich);
2391     // Fill the dataset
2392     dataset[ecid] = lut;  // we use any logic id but different, because it is in any case ignored...
2393 
2394     ich++;
2395 
2396     FEConfigLUTGroupDat lute;
2397     lute.setLUTGroupId(ich);
2398     for (int i = 0; i < 1024; i++) {
2399       lute.setLUTValue(i, lut_EE[i]);
2400     }
2401     EcalLogicID ecide = EcalLogicID("DUMMY", ich, ich);
2402     // Fill the dataset
2403     dataset[ecide] = lute;  // we use any logic id but different, because it is in any case ignored...
2404 
2405     ich++;
2406 
2407     NLUTGROUPS = ich;
2408 
2409     // now we store in the DB the correspondence btw channels and LUT groups
2410     map<EcalLogicID, FEConfigLUTDat> dataset2;
2411     // in this case I decide in a stupid way which channel belongs to which group
2412     for (auto& id : my_TTEcalLogicId) {
2413       FEConfigLUTDat lut;
2414       int igroup = 0;
2415       lut.setLUTGroupId(igroup);
2416       // calculate the right TT - in the vector they are ordered by SM and by TT
2417       // Fill the dataset
2418       dataset2[id] = lut;
2419     }
2420 
2421     // endcap loop
2422     for (auto& id : my_TTEcalLogicId_EE) {
2423       FEConfigLUTDat lut;
2424       int igroup = 1;
2425       lut.setLUTGroupId(igroup);
2426       // calculate the right TT
2427       // Fill the dataset
2428       dataset2[id] = lut;
2429     }
2430 
2431     // Insert the dataset
2432     ostringstream ltag;
2433     ltag.str("");
2434     ltag << LUT_option_ << "_NGroups_" << NLUTGROUPS;
2435     std::string lut_tag = ltag.str();
2436     ss << " LUT tag " << lut_tag << "\n";
2437     if (m_write_lut == 1)
2438       lut_conf_id_ = db_->writeToConfDB_TPGLUT(dataset, dataset2, lutparamset, NLUTGROUPS, lut_tag);
2439   }
2440 
2441   // last we insert the FE_CONFIG_MAIN table
2442   if (writeToDB_) {
2443     //int conf_id_=db_->writeToConfDB_TPGMain(ped_conf_id_,lin_conf_id_, lut_conf_id_, fgr_conf_id_,
2444     //              sli_conf_id_, wei_conf_id_, bxt_conf_id_, btt_conf_id_, tag_, version_) ;
2445     int conf_id_ = db_->writeToConfDB_TPGMain(ped_conf_id_,
2446                                               lin_conf_id_,
2447                                               lut_conf_id_,
2448                                               fgr_conf_id_,
2449                                               sli_conf_id_,
2450                                               wei_conf_id_,
2451                                               wei2_conf_id_,
2452                                               spi_conf_id_,
2453                                               del_conf_id_,
2454                                               bxt_conf_id_,
2455                                               btt_conf_id_,
2456                                               bst_conf_id_,
2457                                               coke_conf_id_,
2458                                               tag_,
2459                                               version_);  //modif-alex 21/01/11
2460 
2461     ss << "\n Conf ID = " << conf_id_ << "\n";
2462   }
2463 
2464   ////////////////////////////////////////////////////
2465   // loop on strips and associate them with  values //
2466   ////////////////////////////////////////////////////
2467 
2468   // Barrel
2469   stripListEB.sort();
2470   stripListEB.unique();
2471   ss << "Number of EB strips=" << dec << stripListEB.size() << "\n";
2472   if (writeToFiles_) {
2473     (*out_file_) << std::endl;
2474     for (itList = stripListEB.begin(); itList != stripListEB.end(); itList++) {
2475       (*out_file_) << "STRIP_EB " << dec << (*itList) << std::endl;
2476       (*out_file_) << hex << "0x" << sliding_ << std::endl;
2477       (*out_file_) << hex << "0x" << weights_map_even[(*itList)] << " ";
2478       if (weight_useDoubleWeights_)
2479         (*out_file_) << hex << "0x" << weights_map_odd[(*itList)] << std::endl;
2480       else
2481         (*out_file_) << "0x0" << std::endl;
2482       (*out_file_) << "0x" << stripMapEBsintheta[(*itList)] << " 0x" << SFGVB_lut_ << std::endl;
2483     }
2484   }
2485 
2486   // Endcap
2487   stripListEE.sort();
2488   stripListEE.unique();
2489   ss << "Number of EE strips=" << dec << stripListEE.size() << "\n";
2490   if (writeToFiles_) {
2491     (*out_file_) << std::endl;
2492     for (itList = stripListEE.begin(); itList != stripListEE.end(); itList++) {
2493       (*out_file_) << "STRIP_EE " << dec << (*itList) << std::endl;
2494       (*out_file_) << hex << "0x" << sliding_ << std::endl;
2495       (*out_file_) << hex << "0x" << weights_map_even[(*itList)] << " ";
2496       if (weight_useDoubleWeights_)
2497         (*out_file_) << hex << "0x" << weights_map_odd[(*itList)] << std::endl;
2498       else
2499         (*out_file_) << "0x0" << std::endl;
2500       (*out_file_) << hex << "0x" << threshold << " 0x" << lut_strip << std::endl;
2501     }
2502   }
2503   edm::LogInfo("TopInfo") << ss.str();
2504   ss.str("");
2505 
2506   ///////////////////////////////////////////////////////////
2507   // loop on towers and associate them with default values //
2508   ///////////////////////////////////////////////////////////
2509 
2510   // Barrel
2511   towerListEB.sort();
2512   towerListEB.unique();
2513   ss << "Number of EB towers=" << dec << towerListEB.size() << "\n";
2514   if (writeToFiles_) {
2515     (*out_file_) << std::endl;
2516     for (itList = towerListEB.begin(); itList != towerListEB.end(); itList++) {
2517       (*out_file_) << "TOWER_EB " << dec << (*itList) << std::endl;
2518       (*out_file_) << " 0\n 0\n";
2519       (*out_file_) << " " << SFGVB_SpikeKillingThreshold_ << std::endl;  //modif-alex
2520     }
2521   }
2522 
2523   // Endcap
2524   towerListEE.sort();
2525   towerListEE.unique();
2526   ss << "Number of EE towers=" << dec << towerListEE.size() << "\n";
2527   if (writeToFiles_) {
2528     (*out_file_) << std::endl;
2529     for (itList = towerListEE.begin(); itList != towerListEE.end(); itList++) {
2530       (*out_file_) << "TOWER_EE " << dec << (*itList) << std::endl;
2531       if (newLUT)
2532         (*out_file_) << " 1\n";
2533       else
2534         (*out_file_) << " 0\n";
2535       (*out_file_) << hex << "0x" << lut_tower << std::endl;
2536     }
2537   }
2538   edm::LogInfo("TopInfo") << ss.str();
2539   ss.str("");
2540 
2541   //////////////////////////
2542   // store control histos //
2543   //////////////////////////
2544   ICEB->Write();
2545   tpgFactorEB->Write();
2546   ICEEPlus->Write();
2547   tpgFactorEEPlus->Write();
2548   ICEEMinus->Write();
2549   tpgFactorEEMinus->Write();
2550   IC->Write();
2551   tpgFactor->Write();
2552   hshapeEB->Write();
2553   hshapeEE->Write();
2554   ntuple->Write();
2555   ntupleSpike->Write();
2556   saving.Close();
2557 }
2558 
2559 void EcalTPGParamBuilder::beginJob() {
2560   using namespace edm;
2561   using namespace std;
2562 
2563   edm::LogInfo("TopInfo") << "we are in beginJob\n";
2564 
2565   create_header();
2566 
2567   DetId eb(DetId::Ecal, EcalBarrel);
2568   DetId ee(DetId::Ecal, EcalEndcap);
2569 
2570   if (writeToFiles_) {
2571     (*out_file_) << "PHYSICS_EB " << dec << eb.rawId() << std::endl;
2572     (*out_file_) << Et_sat_EB_ << " " << TTF_lowThreshold_EB_ << " " << TTF_highThreshold_EB_ << std::endl;
2573     (*out_file_) << FG_lowThreshold_EB_ << " " << FG_highThreshold_EB_ << " " << FG_lowRatio_EB_ << " "
2574                  << FG_highRatio_EB_ << std::endl;
2575     //(*out_file_) << SFGVB_SpikeKillingThreshold_ << std::endl; //modif-alex02/02/2011
2576     (*out_file_) << std::endl;
2577 
2578     (*out_file_) << "PHYSICS_EE " << dec << ee.rawId() << std::endl;
2579     (*out_file_) << Et_sat_EE_ << " " << TTF_lowThreshold_EE_ << " " << TTF_highThreshold_EE_ << std::endl;
2580     (*out_file_) << FG_Threshold_EE_ << " " << -1 << " " << -1 << " " << -1 << std::endl;
2581     (*out_file_) << std::endl;
2582   }
2583 }
2584 
2585 bool EcalTPGParamBuilder::computeLinearizerParam(
2586     double theta, double gainRatio, double calibCoeff, std::string subdet, int& mult, int& shift) {
2587   /*
2588     Linearization coefficient are determined in order to satisfy:
2589     tpg(ADC_sat) = 1024
2590     where: 
2591     tpg() is a model of the linearized tpg response on 10b 
2592     ADC_sat is the number of ADC count corresponding the Et_sat, the maximum scale of the transverse energy
2593     
2594     Since we have:
2595     Et_sat = xtal_LSB * ADC_sat * gainRatio * calibCoeff * sin(theta)
2596     and a simple model of tpg() being given by:
2597     tpg(X) = [ (X*mult) >> (shift+2) ] >> (sliding+shiftDet) 
2598     we must satisfy:
2599     [ (Et_sat/(xtal_LSB * gainRatio * calibCoeff * sin(theta)) * mult) >> (shift+2) ] >> (sliding+shiftDet) = 1024 
2600     that is:
2601     mult = 1024/Et_sat * xtal_LSB * gainRatio * calibCoeff * sin(theta) * 2^-(sliding+shiftDet+2) * 2^-shift
2602     mult = factor * 2^-shift
2603   */
2604 
2605   // case barrel:
2606   int shiftDet = 2;  //fixed, due to FE FENIX TCP format
2607   double ratio = xtal_LSB_EB_ / Et_sat_EB_;
2608   // case endcap:
2609   if (subdet == "EE") {
2610     shiftDet = 2;  //applied in TCC-EE and not in FE FENIX TCP... This parameters is setable in the TCC-EE
2611     //shiftDet = 0 ; //was like this before with FE bug
2612     ratio = xtal_LSB_EE_ / Et_sat_EE_;
2613   }
2614 
2615   //modif-alex-30/01/2012
2616   //std::cout << "calibCoeff="<<calibCoeff<<endl;
2617 
2618   double factor = 1024 * ratio * gainRatio * calibCoeff * sin(theta) * (1 << (sliding_ + shiftDet + 2));
2619   // Let's try first with shift = 0 (trivial solution)
2620   mult = (int)(factor + 0.5);
2621   for (shift = 0; shift < 15; shift++) {
2622     if (mult >= 128 && mult < 256)
2623       return true;
2624     factor *= 2;
2625     mult = (int)(factor + 0.5);
2626   }
2627   edm::LogError("TopInfo") << "too bad we did not manage to calculate the factor for calib=" << calibCoeff << "\n";
2628   return false;
2629 }
2630 
2631 void EcalTPGParamBuilder::create_header() {
2632   if (!writeToFiles_)
2633     return;
2634   (*out_file_) << "COMMENT put your comments here" << std::endl;
2635 
2636   (*out_file_) << "COMMENT =================================" << std::endl;
2637   (*out_file_) << "COMMENT           physics EB structure" << std::endl;
2638   (*out_file_) << "COMMENT" << std::endl;
2639   (*out_file_) << "COMMENT  EtSaturation (GeV), ttf_threshold_Low (GeV), ttf_threshold_High (GeV)" << std::endl;
2640   (*out_file_) << "COMMENT  FG_lowThreshold (GeV), FG_highThreshold (GeV), FG_lowRatio, FG_highRatio" << std::endl;
2641   //(*out_file_) <<"COMMENT  SFGVB_SpikeKillingThreshold (GeV)"<<std::endl ; //modif-alex-02/02/2011
2642   (*out_file_) << "COMMENT =================================" << std::endl;
2643   (*out_file_) << "COMMENT" << std::endl;
2644 
2645   (*out_file_) << "COMMENT =================================" << std::endl;
2646   (*out_file_) << "COMMENT           physics EE structure" << std::endl;
2647   (*out_file_) << "COMMENT" << std::endl;
2648   (*out_file_) << "COMMENT  EtSaturation (GeV), ttf_threshold_Low (GeV), ttf_threshold_High (GeV)" << std::endl;
2649   (*out_file_) << "COMMENT  FG_Threshold (GeV), dummy, dummy, dummy" << std::endl;
2650   (*out_file_) << "COMMENT =================================" << std::endl;
2651   (*out_file_) << "COMMENT" << std::endl;
2652 
2653   (*out_file_) << "COMMENT =================================" << std::endl;
2654   (*out_file_) << "COMMENT           crystal structure (same for EB and EE)" << std::endl;
2655   (*out_file_) << "COMMENT" << std::endl;
2656   (*out_file_) << "COMMENT  ped, mult, shift [gain12]" << std::endl;
2657   (*out_file_) << "COMMENT  ped, mult, shift [gain6]" << std::endl;
2658   (*out_file_) << "COMMENT  ped, mult, shift [gain1]" << std::endl;
2659   (*out_file_) << "COMMENT =================================" << std::endl;
2660   (*out_file_) << "COMMENT" << std::endl;
2661 
2662   (*out_file_) << "COMMENT =================================" << std::endl;
2663   (*out_file_) << "COMMENT           strip EB structure" << std::endl;
2664   (*out_file_) << "COMMENT" << std::endl;
2665   (*out_file_) << "COMMENT  sliding_window" << std::endl;
2666   (*out_file_) << "COMMENT  even_weightGroupId  odd_weightGroupId" << std::endl;
2667   (*out_file_) << "COMMENT  threshold_sfg lut_sfg" << std::endl;
2668   (*out_file_) << "COMMENT =================================" << std::endl;
2669   (*out_file_) << "COMMENT" << std::endl;
2670 
2671   (*out_file_) << "COMMENT =================================" << std::endl;
2672   (*out_file_) << "COMMENT           strip EE structure" << std::endl;
2673   (*out_file_) << "COMMENT" << std::endl;
2674   (*out_file_) << "COMMENT  sliding_window" << std::endl;
2675   (*out_file_) << "COMMENT  even_weightGroupId  odd_weightGroupId" << std::endl;
2676   (*out_file_) << "COMMENT  threshold_fg lut_fg" << std::endl;
2677   (*out_file_) << "COMMENT =================================" << std::endl;
2678   (*out_file_) << "COMMENT" << std::endl;
2679 
2680   (*out_file_) << "COMMENT =================================" << std::endl;
2681   (*out_file_) << "COMMENT           tower EB structure" << std::endl;
2682   (*out_file_) << "COMMENT" << std::endl;
2683   (*out_file_) << "COMMENT  LUTGroupId" << std::endl;
2684   (*out_file_) << "COMMENT  FgGroupId" << std::endl;
2685   (*out_file_) << "COMMENT  spike_killing_threshold" << std::endl;  //modif alex
2686   (*out_file_) << "COMMENT =================================" << std::endl;
2687   (*out_file_) << "COMMENT" << std::endl;
2688 
2689   (*out_file_) << "COMMENT =================================" << std::endl;
2690   (*out_file_) << "COMMENT           tower EE structure" << std::endl;
2691   (*out_file_) << "COMMENT" << std::endl;
2692   (*out_file_) << "COMMENT  LUTGroupId" << std::endl;
2693   (*out_file_) << "COMMENT  tower_lut_fg" << std::endl;
2694   (*out_file_) << "COMMENT =================================" << std::endl;
2695   (*out_file_) << "COMMENT" << std::endl;
2696 
2697   (*out_file_) << "COMMENT =================================" << std::endl;
2698   (*out_file_) << "COMMENT           Even Weight structure" << std::endl;
2699   (*out_file_) << "COMMENT" << std::endl;
2700   (*out_file_) << "COMMENT  Weight even" << std::endl;
2701   (*out_file_) << "COMMENT  weightGroupId" << std::endl;
2702   (*out_file_) << "COMMENT  w0, w1, w2, w3, w4" << std::endl;
2703   (*out_file_) << "COMMENT =================================" << std::endl;
2704   (*out_file_) << "COMMENT" << std::endl;
2705 
2706   (*out_file_) << "COMMENT =================================" << std::endl;
2707   (*out_file_) << "COMMENT           Odd Weight structure" << std::endl;
2708   (*out_file_) << "COMMENT" << std::endl;
2709   (*out_file_) << "COMMENT  Weight odd" << std::endl;
2710   (*out_file_) << "COMMENT  weightGroupId" << std::endl;
2711   (*out_file_) << "COMMENT  w0, w1, w2, w3, w4" << std::endl;
2712   (*out_file_) << "COMMENT =================================" << std::endl;
2713   (*out_file_) << "COMMENT" << std::endl;
2714 
2715   (*out_file_) << "COMMENT =================================" << std::endl;
2716   (*out_file_) << "COMMENT           TP mode" << std::endl;
2717   (*out_file_) << "COMMENT EnableEBOddFilter" << std::endl;
2718   (*out_file_) << "COMMENT EnableEEOddFilter" << std::endl;
2719   (*out_file_) << "COMMENT EnableEBOddPeakFinder" << std::endl;
2720   (*out_file_) << "COMMENT EnableEEOddPeakFinder" << std::endl;
2721   (*out_file_) << "COMMENT DisableEBEvenPeakFinder" << std::endl;
2722   (*out_file_) << "COMMENT DisableEEEvenPeakFinder" << std::endl;
2723   (*out_file_) << "COMMENT FenixEBStripOutput" << std::endl;
2724   (*out_file_) << "COMMENT FenixEEStripOutput" << std::endl;
2725   (*out_file_) << "COMMENT FenixEBStripInfobit2" << std::endl;
2726   (*out_file_) << "COMMENT FenixEEStripInfobit2" << std::endl;
2727   (*out_file_) << "COMMENT EBFenixTcpOutput" << std::endl;
2728   (*out_file_) << "COMMENT EBFenixTcpInfobit1" << std::endl;
2729   (*out_file_) << "COMMENT EEFenixTcpOutput" << std::endl;
2730   (*out_file_) << "COMMENT EEFenixTcpInfobit1" << std::endl;
2731   (*out_file_) << "COMMENT FenixPar15" << std::endl;
2732   (*out_file_) << "COMMENT FenixPar16" << std::endl;
2733   (*out_file_) << "COMMENT FenixPar17" << std::endl;
2734   (*out_file_) << "COMMENT FenixPar18" << std::endl;
2735   (*out_file_) << "COMMENT =================================" << std::endl;
2736   (*out_file_) << "COMMENT" << std::endl;
2737 
2738   (*out_file_) << "COMMENT =================================" << std::endl;
2739   (*out_file_) << "COMMENT           lut structure" << std::endl;
2740   (*out_file_) << "COMMENT" << std::endl;
2741   (*out_file_) << "COMMENT  LUTGroupId" << std::endl;
2742   (*out_file_) << "COMMENT  LUT[1-1024]" << std::endl;
2743   (*out_file_) << "COMMENT =================================" << std::endl;
2744   (*out_file_) << "COMMENT" << std::endl;
2745 
2746   (*out_file_) << "COMMENT =================================" << std::endl;
2747   (*out_file_) << "COMMENT           fg EB structure" << std::endl;
2748   (*out_file_) << "COMMENT" << std::endl;
2749   (*out_file_) << "COMMENT  FgGroupId" << std::endl;
2750   (*out_file_) << "COMMENT  el, eh, tl, th, lut_fg" << std::endl;
2751   (*out_file_) << "COMMENT =================================" << std::endl;
2752   (*out_file_) << "COMMENT" << std::endl;
2753 }
2754 
2755 int EcalTPGParamBuilder::uncodeWeight(double weight, int complement2) {
2756   int iweight;
2757   unsigned int max = (unsigned int)(pow(2., complement2) - 1);
2758   if (weight > 0)
2759     iweight = int((1 << 6) * weight + 0.5);  // +0.5 for rounding pb
2760   else
2761     iweight = max - int(-weight * (1 << 6) + 0.5) + 1;
2762   iweight = iweight & max;
2763   return iweight;
2764 }
2765 
2766 double EcalTPGParamBuilder::uncodeWeight(int iweight, int complement2) {
2767   double weight = double(iweight) / pow(2., 6.);
2768   // test if negative weight:
2769   if ((iweight & (1 << (complement2 - 1))) != 0)
2770     weight = (double(iweight) - pow(2., complement2)) / pow(2., 6.);
2771   return weight;
2772 }
2773 
2774 std::vector<unsigned int> EcalTPGParamBuilder::computeWeights(EcalShapeBase& shape, TH1F* histo) {
2775   std::ostringstream ss;
2776   ss << "Computing Weights...\n";
2777   double timeMax = shape.timeOfMax() - shape.timeOfThr();  // timeMax w.r.t begining of pulse
2778   double max = shape(timeMax);
2779 
2780   double sumf = 0.;
2781   double sumf2 = 0.;
2782   for (unsigned int sample = 0; sample < nSample_; sample++) {
2783     double time = timeMax - ((double)sampleMax_ - (double)sample) * 25.;
2784     time -= weight_timeShift_;
2785     sumf += shape(time) / max;
2786     sumf2 += shape(time) / max * shape(time) / max;
2787     for (int subtime = 0; subtime < 25; subtime++)
2788       histo->Fill(float(sample * 25. + subtime) / 25., shape(time + subtime));
2789   }
2790   double lambda = 1. / (sumf2 - sumf * sumf / nSample_);
2791   double gamma = -lambda * sumf / nSample_;
2792   double* weight = new double[nSample_];
2793   for (unsigned int sample = 0; sample < nSample_; sample++) {
2794     double time = timeMax - ((double)sampleMax_ - (double)sample) * 25.;
2795     time -= weight_timeShift_;
2796     weight[sample] = lambda * shape(time) / max + gamma;
2797   }
2798 
2799   int* iweight = new int[nSample_];
2800   for (unsigned int sample = 0; sample < nSample_; sample++)
2801     iweight[sample] = uncodeWeight(weight[sample], complement2_);
2802 
2803   // Let's check:
2804   int isumw = 0;
2805   for (unsigned int sample = 0; sample < nSample_; sample++)
2806     isumw += iweight[sample];
2807   unsigned int imax = (unsigned int)(pow(2., int(complement2_)) - 1);
2808   isumw = (isumw & imax);
2809 
2810   double ampl = 0.;
2811   double sumw = 0.;
2812   for (unsigned int sample = 0; sample < nSample_; sample++) {
2813     double time = timeMax - ((double)sampleMax_ - (double)sample) * 25.;
2814     time -= weight_timeShift_;
2815     ampl += weight[sample] * shape(time);
2816     sumw += weight[sample];
2817     ss << "weight=" << weight[sample] << " shape=" << shape(time) << "\n";
2818   }
2819   ss << "Weights: sum=" << isumw << " in float =" << uncodeWeight(isumw, complement2_) << " sum of floats =" << sumw
2820      << "\n";
2821   ss << "Weights: sum (weight*shape) = " << ampl << "\n";
2822 
2823   // Let's correct for bias if any
2824   if (weight_unbias_recovery_) {
2825     int count = 0;
2826     while (isumw != 0 && count < 10) {
2827       double min = 99.;
2828       unsigned int index = 0;
2829       if ((isumw & (1 << (complement2_ - 1))) != 0) {
2830         // add 1:
2831         ss << "Correcting for bias: adding 1\n";
2832         for (unsigned int sample = 0; sample < nSample_; sample++) {
2833           int new_iweight = iweight[sample] + 1;
2834           double new_weight = uncodeWeight(new_iweight, complement2_);
2835           if (fabs(new_weight - weight[sample]) < min) {
2836             min = fabs(new_weight - weight[sample]);
2837             index = sample;
2838           }
2839         }
2840         iweight[index]++;
2841       } else {
2842         // Sub 1:
2843         ss << "Correcting for bias: subtracting 1\n";
2844         for (unsigned int sample = 0; sample < nSample_; sample++) {
2845           int new_iweight = iweight[sample] - 1;
2846           double new_weight = uncodeWeight(new_iweight, complement2_);
2847           if (fabs(new_weight - weight[sample]) < min) {
2848             min = fabs(new_weight - weight[sample]);
2849             index = sample;
2850           }
2851         }
2852         iweight[index]--;
2853       }
2854       isumw = 0;
2855       for (unsigned int sample = 0; sample < nSample_; sample++)
2856         isumw += iweight[sample];
2857       imax = (unsigned int)(pow(2., int(complement2_)) - 1);
2858       isumw = (isumw & imax);
2859       ss << "Correcting weight number: " << index << " sum weights = " << isumw << "\n";
2860       count++;
2861     }
2862   }
2863 
2864   // let's check again
2865   isumw = 0;
2866   for (unsigned int sample = 0; sample < nSample_; sample++)
2867     isumw += iweight[sample];
2868   imax = (unsigned int)(pow(2., int(complement2_)) - 1);
2869   isumw = (isumw & imax);
2870   ampl = 0.;
2871   for (unsigned int sample = 0; sample < nSample_; sample++) {
2872     double time = timeMax - ((double)sampleMax_ - (double)sample) * 25.;
2873     time -= weight_timeShift_;
2874     double new_weight = uncodeWeight(iweight[sample], complement2_);
2875     sumw += uncodeWeight(iweight[sample], complement2_);
2876     ampl += new_weight * shape(time);
2877     ss << "weight unbiased after integer conversion=" << new_weight << " shape=" << shape(time) << "\n";
2878   }
2879   ss << "Weights: sum=" << isumw << " in float =" << uncodeWeight(isumw, complement2_) << " sum of floats =" << sumw
2880      << "\n";
2881   ss << "Weights: sum (weight*shape) = " << ampl << "\n";
2882   edm::LogInfo("TopInfo") << ss.str();
2883 
2884   std::vector<unsigned int> theWeights;
2885   for (unsigned int sample = 0; sample < nSample_; sample++)
2886     theWeights.push_back(iweight[sample]);
2887 
2888   delete[] weight;
2889   delete[] iweight;
2890   return theWeights;
2891 }
2892 
2893 void EcalTPGParamBuilder::computeLUT(int* lut, std::string det) {
2894   double Et_sat = Et_sat_EB_;
2895   double LUT_threshold = LUT_threshold_EB_;
2896   double LUT_stochastic = LUT_stochastic_EB_;
2897   double LUT_noise = LUT_noise_EB_;
2898   double LUT_constant = LUT_constant_EB_;
2899   double TTF_lowThreshold = TTF_lowThreshold_EB_;
2900   double TTF_highThreshold = TTF_highThreshold_EB_;
2901   if (det == "EE") {
2902     Et_sat = Et_sat_EE_;
2903     LUT_threshold = LUT_threshold_EE_;
2904     LUT_stochastic = LUT_stochastic_EE_;
2905     LUT_noise = LUT_noise_EE_;
2906     LUT_constant = LUT_constant_EE_;
2907     TTF_lowThreshold = TTF_lowThreshold_EE_;
2908     TTF_highThreshold = TTF_highThreshold_EE_;
2909   }
2910 
2911   // initialisation with identity
2912   for (int i = 0; i < 1024; i++) {
2913     lut[i] = i;
2914     if (lut[i] > 0xff)
2915       lut[i] = 0xff;
2916   }
2917 
2918   // case linear LUT
2919   if (LUT_option_ == "Linear") {
2920     int mylut = 0;
2921     for (int i = 0; i < 1024; i++) {
2922       lut[i] = mylut;
2923       if ((i + 1) % 4 == 0)
2924         mylut++;
2925       //if ((i+1)%8 == 0 ) mylut++ ;//modif-alex 16/12/2010 LSB==500MeV ONLY USED FOR BEAMV4 key
2926     }
2927   }
2928 
2929   // case LUT following Ecal resolution
2930   if (LUT_option_ == "EcalResolution") {
2931     TF1* func = new TF1("func", oneOverEtResolEt, 0., Et_sat, 3);
2932     func->SetParameters(LUT_stochastic, LUT_noise, LUT_constant);
2933     double norm = func->Integral(0., Et_sat);
2934     for (int i = 0; i < 1024; i++) {
2935       double Et = i * Et_sat / 1024.;
2936       lut[i] = int(0xff * func->Integral(0., Et) / norm + 0.5);
2937     }
2938   }
2939 
2940   // Now, add TTF thresholds to LUT and apply LUT threshold if needed
2941   for (int j = 0; j < 1024; j++) {
2942     double Et_GeV = Et_sat / 1024 * (j + 0.5);
2943     if (Et_GeV <= LUT_threshold)
2944       lut[j] = 0;  // LUT threshold
2945     int ttf = 0x0;
2946     if (Et_GeV >= TTF_highThreshold)
2947       ttf = 3;
2948     if (Et_GeV >= TTF_lowThreshold && Et_GeV < TTF_highThreshold)
2949       ttf = 1;
2950     ttf = ttf << 8;
2951     lut[j] += ttf;
2952   }
2953 }
2954 
2955 void EcalTPGParamBuilder::getCoeff(coeffStruc& coeff,
2956                                    const EcalIntercalibConstantMap& calibMap,
2957                                    const EcalLaserAlphaMap& laserAlphaMap,
2958                                    uint rawId,
2959                                    std::string& st) {
2960   // get current intercalibration coeff
2961   coeff.calibCoeff_ = 1.;
2962   if (!useInterCalibration_)
2963     return;
2964   EcalIntercalibConstantMap::const_iterator icalit = calibMap.find(rawId);
2965 
2966   //modif-alex-30/01/2012
2967   std::map<int, double>::const_iterator itCorr = Transparency_Correction_.find(rawId);
2968   double icorr = 1.0;
2969   double alpha_factor = 1.0;
2970 
2971   if (useTransparencyCorr_) {
2972     icorr = itCorr->second;
2973     if (itCorr != Transparency_Correction_.end()) {
2974       stringstream ss;
2975       ss << rawId;
2976       stringstream ss1;
2977       ss1 << icorr;
2978       stringstream ss2;
2979       ss2 << (*icalit);
2980       st = "Transparency correction found for xtal " + ss.str() + " corr=" + ss1.str() + " intercalib=" + ss2.str() +
2981            "\n";
2982     } else
2983       edm::LogError("TopInfo") << "ERROR = Transparency correction not found for xtal " << rawId << "\n";
2984 
2985     //modif-alex-27-july-2015
2986     DetId ECALdetid(rawId);
2987     //    ss << "DETID=" << ECALdetid.subdetId() << "\n";
2988     stringstream ss;
2989     ss << ECALdetid.subdetId();
2990     st += "DETID=" + ss.str() + "\n";
2991     if (ECALdetid.subdetId() == 1) {  //ECAL BARREL
2992       EBDetId barrel_detid(rawId);
2993       EcalLaserAlphaMap::const_iterator italpha = laserAlphaMap.find(barrel_detid);
2994       if (italpha != laserAlphaMap.end())
2995         alpha_factor = (*italpha);
2996       else
2997         edm::LogError("TopInfo") << "ERROR:LaserAlphe parameter note found!!"
2998                                  << "\n";
2999     }
3000     if (ECALdetid.subdetId() == 2) {  //ECAL ENDCAP
3001       EEDetId endcap_detid(rawId);
3002       EcalLaserAlphaMap::const_iterator italpha = laserAlphaMap.find(endcap_detid);
3003       if (italpha != laserAlphaMap.end())
3004         alpha_factor = (*italpha);
3005       else
3006         edm::LogError("TopInfo") << "ERROR:LaserAlphe parameter note found!!"
3007                                  << "\n";
3008     }
3009 
3010   }  //transparency corrections applied
3011 
3012   //if( icalit != calibMap.end() ) coeff.calibCoeff_ = (*icalit) ;
3013   //if( icalit != calibMap.end() ) coeff.calibCoeff_ = (*icalit)/icorr; //modif-alex-30/01/2010 tansparency corrections
3014   //  ss << "rawId " << (*icalit) << " " << icorr << " " << alpha_factor << "\n";
3015   stringstream ss;
3016   ss << (*icalit);
3017   stringstream ss1;
3018   ss1 << icorr;
3019   stringstream ss2;
3020   ss2 << alpha_factor;
3021   st += "rawId " + ss.str() + " " + ss1.str() + " " + ss2.str() + "\n";
3022   if (icalit != calibMap.end())
3023     coeff.calibCoeff_ =
3024         (*icalit) /
3025         std::pow(icorr, alpha_factor);  //modif-alex-27/07/2015 tansparency corrections with alpha parameters
3026 
3027   else
3028     edm::LogError("TopInfo") << "getCoeff: " << rawId << " not found in EcalIntercalibConstantMap"
3029                              << "\n";
3030 }
3031 
3032 void EcalTPGParamBuilder::getCoeff(coeffStruc& coeff, const EcalGainRatioMap& gainMap, unsigned int rawId) {
3033   // get current gain ratio
3034   coeff.gainRatio_[0] = 1.;
3035   coeff.gainRatio_[1] = 2.;
3036   coeff.gainRatio_[2] = 12.;
3037   EcalGainRatioMap::const_iterator gainIter = gainMap.find(rawId);
3038   if (gainIter != gainMap.end()) {
3039     const EcalMGPAGainRatio& aGain = (*gainIter);
3040     coeff.gainRatio_[1] = aGain.gain12Over6();
3041     coeff.gainRatio_[2] = aGain.gain6Over1() * aGain.gain12Over6();
3042   } else
3043     edm::LogError("TopInfo") << "getCoeff: " << rawId << " not found in EcalGainRatioMap"
3044                              << "\n";
3045 }
3046 
3047 void EcalTPGParamBuilder::getCoeff(coeffStruc& coeff, const EcalPedestalsMap& pedMap, unsigned int rawId) {
3048   coeff.pedestals_[0] = 0;
3049   coeff.pedestals_[1] = 0;
3050   coeff.pedestals_[2] = 0;
3051 
3052   if (forcedPedestalValue_ >= 0) {
3053     coeff.pedestals_[0] = forcedPedestalValue_;
3054     coeff.pedestals_[1] = forcedPedestalValue_;
3055     coeff.pedestals_[2] = forcedPedestalValue_;
3056     return;
3057   }
3058 
3059   // get current pedestal
3060   EcalPedestalsMapIterator pedIter = pedMap.find(rawId);
3061   if (pedIter != pedMap.end()) {
3062     EcalPedestals::Item aped = (*pedIter);
3063     coeff.pedestals_[0] = int(aped.mean_x12 + 0.5);
3064     coeff.pedestals_[1] = int(aped.mean_x6 + 0.5);
3065     coeff.pedestals_[2] = int(aped.mean_x1 + 0.5);
3066   } else
3067     edm::LogError("TopInfo") << "getCoeff: " << rawId << " not found in EcalPedestalsMap\n";
3068 }
3069 
3070 void EcalTPGParamBuilder::getCoeff(coeffStruc& coeff,
3071                                    const map<EcalLogicID, MonPedestalsDat>& pedMap,
3072                                    const EcalLogicID& logicId) {
3073   // get current pedestal
3074   coeff.pedestals_[0] = 0;
3075   coeff.pedestals_[1] = 0;
3076   coeff.pedestals_[2] = 0;
3077 
3078   map<EcalLogicID, MonPedestalsDat>::const_iterator it = pedMap.find(logicId);
3079   if (it != pedMap.end()) {
3080     MonPedestalsDat ped = it->second;
3081     coeff.pedestals_[0] = int(ped.getPedMeanG12() + 0.5);
3082     coeff.pedestals_[1] = int(ped.getPedMeanG6() + 0.5);
3083     coeff.pedestals_[2] = int(ped.getPedMeanG1() + 0.5);
3084   } else
3085     edm::LogError("TopInfo") << "getCoeff: " << logicId.getID1() << ", " << logicId.getID2() << ", " << logicId.getID3()
3086                              << " not found in map<EcalLogicID, MonPedestalsDat\n";
3087 }
3088 
3089 void EcalTPGParamBuilder::computeFineGrainEBParameters(unsigned int& lowRatio,
3090                                                        unsigned int& highRatio,
3091                                                        unsigned int& lowThreshold,
3092                                                        unsigned int& highThreshold,
3093                                                        unsigned int& lut) {
3094   lowRatio = int(0x80 * FG_lowRatio_EB_ + 0.5);
3095   if (lowRatio > 0x7f)
3096     lowRatio = 0x7f;
3097   highRatio = int(0x80 * FG_highRatio_EB_ + 0.5);
3098   if (highRatio > 0x7f)
3099     highRatio = 0x7f;
3100 
3101   // lsb at the stage of the FG calculation is:
3102   double lsb_FG = Et_sat_EB_ / 1024. / 4;
3103   lowThreshold = int(FG_lowThreshold_EB_ / lsb_FG + 0.5);
3104   if (lowThreshold > 0xff)
3105     lowThreshold = 0xff;
3106   highThreshold = int(FG_highThreshold_EB_ / lsb_FG + 0.5);
3107   if (highThreshold > 0xff)
3108     highThreshold = 0xff;
3109 
3110   // FG lut: FGVB response is LUT(adress) where adress is:
3111   // bit3: maxof2/ET >= lowRatio, bit2: maxof2/ET >= highRatio, bit1: ET >= lowThreshold, bit0: ET >= highThreshold
3112   // FGVB =1 if jet-like (veto active), =0 if E.M.-like
3113   // the condition for jet-like is: ET>Threshold and  maxof2/ET < Ratio (only TT with enough energy are vetoed)
3114 
3115   // With the following lut, what matters is only max(TLow, Thigh) and max(Elow, Ehigh)
3116   // So, jet-like if maxof2/ettot<max(TLow, Thigh) && ettot >= max(Elow, Ehigh)
3117   if (FG_lut_EB_ == 0)
3118     lut = 0x0888;
3119   else
3120     lut = FG_lut_EB_;  // let's use the users value (hope he/she knows what he/she does!)
3121 }
3122 
3123 void EcalTPGParamBuilder::computeFineGrainEEParameters(unsigned int& threshold,
3124                                                        unsigned int& lut_strip,
3125                                                        unsigned int& lut_tower) {
3126   // lsb for EE:
3127   double lsb_FG = Et_sat_EE_ / 1024.;  // FIXME is it true????
3128   threshold = int(FG_Threshold_EE_ / lsb_FG + 0.5);
3129   lut_strip = FG_lut_strip_EE_;
3130   lut_tower = FG_lut_tower_EE_;
3131 }
3132 
3133 bool EcalTPGParamBuilder::realignBaseline(linStruc& lin, float forceBase12, int cmsswid) {
3134   bool ok(true);
3135   float base[3] = {forceBase12, float(lin.pedestal_[1]), float(lin.pedestal_[2])};
3136   for (int i = 1; i < 3; i++) {
3137     if (lin.mult_[i] > 0) {
3138       base[i] = float(lin.pedestal_[i]) - float(lin.mult_[0]) / float(lin.mult_[i]) *
3139                                               pow(2., -(lin.shift_[0] - lin.shift_[i])) * (lin.pedestal_[0] - base[0]);
3140     } else
3141       base[i] = 0;
3142   }
3143   for (int i = 0; i < 3; i++) {
3144     if (base[i] < 0) {
3145       edm::LogError("TopInfo") << "PROBLEM in realignBaseline: xtal=" << cmsswid << " base= " << base[i] << ", "
3146                                << lin.pedestal_[i] << " for gainId[0-2]=" << i << " ==> smaller than 0 ==> set to 0"
3147                                << "  mult12:" << lin.mult_[0] << " mult:" << lin.mult_[i]
3148                                << " ped12:" << lin.pedestal_[0] << " ped:" << lin.pedestal_[i] << "  base12:" << base[0]
3149                                << " shift12:" << lin.shift_[0] << " shift: " << lin.shift_[i] << "\n";
3150       lin.pedestal_[i] = 0;
3151       ok = false;
3152     } else if (base[i] > 1024) {
3153       edm::LogError("TopInfo") << "PROBLEM in realignBaseline: xtal=" << cmsswid << " base= " << base[i] << ", "
3154                                << lin.pedestal_[i] << " for gainId[0-2]=" << i
3155                                << " ==> larger than 1024 ==> set to 1024"
3156                                << "  mult12:" << lin.mult_[0] << " mult:" << lin.mult_[i]
3157                                << " ped12:" << lin.pedestal_[0] << " ped:" << lin.pedestal_[i] << "  base12:" << base[0]
3158                                << " shift12:" << lin.shift_[0] << " shift: " << lin.shift_[i] << "\n";
3159       lin.pedestal_[i] = 1024;
3160       ok = false;
3161     } else {
3162       lin.pedestal_[i] = base[i];
3163     }
3164   }
3165   return ok;
3166 }
3167 
3168 int EcalTPGParamBuilder::getGCTRegionPhi(int ttphi) {
3169   int gctphi = 0;
3170   gctphi = (ttphi + 1) / 4;
3171   if (ttphi <= 2)
3172     gctphi = 0;
3173   if (ttphi >= 71)
3174     gctphi = 0;
3175   return gctphi;
3176 }
3177 
3178 int EcalTPGParamBuilder::getGCTRegionEta(int tteta) {
3179   int gcteta = 0;
3180   if (tteta > 0)
3181     gcteta = (tteta - 1) / 4 + 11;
3182   else if (tteta < 0)
3183     gcteta = (tteta + 1) / 4 + 10;
3184   return gcteta;
3185 }
3186 
3187 std::string EcalTPGParamBuilder::getDet(int tcc) {
3188   std::stringstream sdet;
3189 
3190   if (tcc > 36 && tcc < 55)
3191     sdet << "EB-" << tcc - 36;
3192   else if (tcc >= 55 && tcc < 73)
3193     sdet << "EB+" << tcc - 54;
3194   else if (tcc <= 36)
3195     sdet << "EE-";
3196   else
3197     sdet << "EE+";
3198 
3199   if (tcc <= 36 || tcc >= 73) {
3200     if (tcc >= 73)
3201       tcc -= 72;
3202     if (tcc == 1 || tcc == 18 || tcc == 19 || tcc == 36)
3203       sdet << 7;
3204     else if (tcc == 2 || tcc == 3 || tcc == 20 || tcc == 21)
3205       sdet << 8;
3206     else if (tcc == 4 || tcc == 5 || tcc == 22 || tcc == 23)
3207       sdet << 9;
3208     else if (tcc == 6 || tcc == 7 || tcc == 24 || tcc == 25)
3209       sdet << 1;
3210     else if (tcc == 8 || tcc == 9 || tcc == 26 || tcc == 27)
3211       sdet << 2;
3212     else if (tcc == 10 || tcc == 11 || tcc == 28 || tcc == 29)
3213       sdet << 3;
3214     else if (tcc == 12 || tcc == 13 || tcc == 30 || tcc == 31)
3215       sdet << 4;
3216     else if (tcc == 14 || tcc == 15 || tcc == 32 || tcc == 33)
3217       sdet << 5;
3218     else if (tcc == 16 || tcc == 17 || tcc == 34 || tcc == 35)
3219       sdet << 6;
3220   }
3221 
3222   return sdet.str();
3223 }
3224 
3225 std::pair<std::string, int> EcalTPGParamBuilder::getCrate(int tcc) {
3226   std::stringstream crate;
3227   std::string pos;
3228   int slot = 0;
3229 
3230   crate << "S2D";
3231   if (tcc >= 40 && tcc <= 42) {
3232     crate << "02d";
3233     slot = 5 + (tcc - 40) * 6;
3234   }
3235   if (tcc >= 43 && tcc <= 45) {
3236     crate << "03d";
3237     slot = 5 + (tcc - 43) * 6;
3238   }
3239   if (tcc >= 37 && tcc <= 39) {
3240     crate << "04d";
3241     slot = 5 + (tcc - 37) * 6;
3242   }
3243   if (tcc >= 52 && tcc <= 54) {
3244     crate << "06d";
3245     slot = 5 + (tcc - 52) * 6;
3246   }
3247   if (tcc >= 46 && tcc <= 48) {
3248     crate << "07d";
3249     slot = 5 + (tcc - 46) * 6;
3250   }
3251   if (tcc >= 49 && tcc <= 51) {
3252     crate << "08d";
3253     slot = 5 + (tcc - 49) * 6;
3254   }
3255   if (tcc >= 58 && tcc <= 60) {
3256     crate << "02h";
3257     slot = 5 + (tcc - 58) * 6;
3258   }
3259   if (tcc >= 61 && tcc <= 63) {
3260     crate << "03h";
3261     slot = 5 + (tcc - 61) * 6;
3262   }
3263   if (tcc >= 55 && tcc <= 57) {
3264     crate << "04h";
3265     slot = 5 + (tcc - 55) * 6;
3266   }
3267   if (tcc >= 70 && tcc <= 72) {
3268     crate << "06h";
3269     slot = 5 + (tcc - 70) * 6;
3270   }
3271   if (tcc >= 64 && tcc <= 66) {
3272     crate << "07h";
3273     slot = 5 + (tcc - 64) * 6;
3274   }
3275   if (tcc >= 67 && tcc <= 69) {
3276     crate << "08h";
3277     slot = 5 + (tcc - 67) * 6;
3278   }
3279 
3280   if (tcc >= 76 && tcc <= 81) {
3281     crate << "02l";
3282     if (tcc % 2 == 0)
3283       slot = 2 + (tcc - 76) * 3;
3284     else
3285       slot = 4 + (tcc - 77) * 3;
3286   }
3287   if (tcc >= 94 && tcc <= 99) {
3288     crate << "02l";
3289     if (tcc % 2 == 0)
3290       slot = 3 + (tcc - 94) * 3;
3291     else
3292       slot = 5 + (tcc - 95) * 3;
3293   }
3294 
3295   if (tcc >= 22 && tcc <= 27) {
3296     crate << "03l";
3297     if (tcc % 2 == 0)
3298       slot = 2 + (tcc - 22) * 3;
3299     else
3300       slot = 4 + (tcc - 23) * 3;
3301   }
3302   if (tcc >= 4 && tcc <= 9) {
3303     crate << "03l";
3304     if (tcc % 2 == 0)
3305       slot = 3 + (tcc - 4) * 3;
3306     else
3307       slot = 5 + (tcc - 5) * 3;
3308   }
3309 
3310   if (tcc >= 82 && tcc <= 87) {
3311     crate << "07l";
3312     if (tcc % 2 == 0)
3313       slot = 2 + (tcc - 82) * 3;
3314     else
3315       slot = 4 + (tcc - 83) * 3;
3316   }
3317   if (tcc >= 100 && tcc <= 105) {
3318     crate << "07l";
3319     if (tcc % 2 == 0)
3320       slot = 3 + (tcc - 100) * 3;
3321     else
3322       slot = 5 + (tcc - 101) * 3;
3323   }
3324 
3325   if (tcc >= 28 && tcc <= 33) {
3326     crate << "08l";
3327     if (tcc % 2 == 0)
3328       slot = 2 + (tcc - 28) * 3;
3329     else
3330       slot = 4 + (tcc - 29) * 3;
3331   }
3332   if (tcc >= 10 && tcc <= 15) {
3333     crate << "08l";
3334     if (tcc % 2 == 0)
3335       slot = 3 + (tcc - 10) * 3;
3336     else
3337       slot = 5 + (tcc - 11) * 3;
3338   }
3339 
3340   if (tcc == 34) {
3341     crate << "04l";
3342     slot = 2;
3343   }
3344   if (tcc == 16) {
3345     crate << "04l";
3346     slot = 3;
3347   }
3348   if (tcc == 35) {
3349     crate << "04l";
3350     slot = 4;
3351   }
3352   if (tcc == 17) {
3353     crate << "04l";
3354     slot = 5;
3355   }
3356   if (tcc == 36) {
3357     crate << "04l";
3358     slot = 8;
3359   }
3360   if (tcc == 18) {
3361     crate << "04l";
3362     slot = 9;
3363   }
3364   if (tcc == 19) {
3365     crate << "04l";
3366     slot = 10;
3367   }
3368   if (tcc == 1) {
3369     crate << "04l";
3370     slot = 11;
3371   }
3372   if (tcc == 20) {
3373     crate << "04l";
3374     slot = 14;
3375   }
3376   if (tcc == 2) {
3377     crate << "04l";
3378     slot = 15;
3379   }
3380   if (tcc == 21) {
3381     crate << "04l";
3382     slot = 16;
3383   }
3384   if (tcc == 3) {
3385     crate << "04l";
3386     slot = 17;
3387   }
3388 
3389   if (tcc == 88) {
3390     crate << "06l";
3391     slot = 2;
3392   }
3393   if (tcc == 106) {
3394     crate << "06l";
3395     slot = 3;
3396   }
3397   if (tcc == 89) {
3398     crate << "06l";
3399     slot = 4;
3400   }
3401   if (tcc == 107) {
3402     crate << "06l";
3403     slot = 5;
3404   }
3405   if (tcc == 90) {
3406     crate << "06l";
3407     slot = 8;
3408   }
3409   if (tcc == 108) {
3410     crate << "06l";
3411     slot = 9;
3412   }
3413   if (tcc == 73) {
3414     crate << "06l";
3415     slot = 10;
3416   }
3417   if (tcc == 91) {
3418     crate << "06l";
3419     slot = 11;
3420   }
3421   if (tcc == 74) {
3422     crate << "06l";
3423     slot = 14;
3424   }
3425   if (tcc == 92) {
3426     crate << "06l";
3427     slot = 15;
3428   }
3429   if (tcc == 75) {
3430     crate << "06l";
3431     slot = 16;
3432   }
3433   if (tcc == 93) {
3434     crate << "06l";
3435     slot = 17;
3436   }
3437 
3438   return std::pair<std::string, int>(crate.str(), slot);
3439 }