CMS 3D CMS Logo

/data/doxygen/doxygen-1.7.3/gen/CMSSW_4_2_8/src/CalibCalorimetry/EcalTPGTools/plugins/EcalTPGParamBuilder.cc

Go to the documentation of this file.
00001 #include "EcalTPGParamBuilder.h"
00002 
00003 #include "CalibCalorimetry/EcalTPGTools/plugins/EcalTPGDBApp.h"
00004 
00005 
00006 #include "Geometry/CaloGeometry/interface/CaloGeometry.h"
00007 #include "Geometry/CaloGeometry/interface/CaloSubdetectorGeometry.h"
00008 #include "Geometry/CaloGeometry/interface/CaloCellGeometry.h"
00009 #include "Geometry/Records/interface/CaloGeometryRecord.h"
00010 #include "Geometry/EcalMapping/interface/EcalElectronicsMapping.h"
00011 #include "Geometry/EcalMapping/interface/EcalMappingRcd.h"
00012 
00013 #include "DataFormats/EcalDetId/interface/EcalSubdetector.h"
00014 #include "DataFormats/EcalDetId/interface/EBDetId.h"
00015 #include "DataFormats/EcalDetId/interface/EEDetId.h"
00016 
00017 #include "CondFormats/DataRecord/interface/EcalIntercalibConstantsRcd.h"
00018 #include "CondFormats/EcalObjects/interface/EcalADCToGeVConstant.h"
00019 #include "CondFormats/DataRecord/interface/EcalADCToGeVConstantRcd.h"
00020 #include "CondFormats/EcalObjects/interface/EcalMGPAGainRatio.h"
00021 #include "CondFormats/DataRecord/interface/EcalGainRatiosRcd.h"
00022 #include "CondFormats/DataRecord/interface/EcalPedestalsRcd.h"
00023 
00024 #include "SimCalorimetry/EcalSimAlgos/interface/EcalSimParameterMap.h"
00025 #if (CMSSW_VERSION>=340)
00026 #include "SimCalorimetry/EcalSimAlgos/interface/EBShape.h"
00027 #include "SimCalorimetry/EcalSimAlgos/interface/EEShape.h"
00028 #endif
00029 
00030 #include <iostream>
00031 #include <string>
00032 #include <sstream>
00033 #include <vector>
00034 #include <time.h>
00035 
00036 #include <TF1.h>
00037 #include <TH2F.h>
00038 #include <TFile.h>
00039 #include <TNtuple.h>
00040 #include <iomanip>
00041 #include <fstream>
00042 
00043 
00044 
00045 double oneOverEtResolEt(double *x, double *par) { 
00046   double Et = x[0] ;
00047   if (Et<1e-6) return 1./par[1] ; // to avoid division by 0.
00048   double resolEt_overEt = sqrt( (par[0]/sqrt(Et))*(par[0]/sqrt(Et)) + (par[1]/Et)*(par[1]/Et) + par[2]*par[2] ) ;
00049   return 1./(Et*resolEt_overEt) ;
00050 }
00051 
00052 EcalTPGParamBuilder::EcalTPGParamBuilder(edm::ParameterSet const& pSet)
00053   : xtal_LSB_EB_(0), xtal_LSB_EE_(0), nSample_(5), complement2_(7)
00054 {
00055   ped_conf_id_=0;
00056   lin_conf_id_=0;
00057   lut_conf_id_=0;
00058   wei_conf_id_=0;
00059   fgr_conf_id_=0;
00060   sli_conf_id_=0;
00061   bxt_conf_id_=0;
00062   btt_conf_id_=0;
00063   tag_="";
00064   version_=0;
00065 
00066   m_write_ped=1;
00067   m_write_lin=1;
00068   m_write_lut=1;
00069   m_write_wei=1;
00070   m_write_fgr=1;
00071   m_write_sli=1;
00072   m_write_bxt=1;
00073   m_write_btt=1;
00074 
00075   writeToDB_  = pSet.getParameter<bool>("writeToDB") ;
00076   DBEE_ = pSet.getParameter<bool>("allowDBEE") ;
00077   std::string DBsid    = pSet.getParameter<std::string>("DBsid") ;
00078   std::string DBuser   = pSet.getParameter<std::string>("DBuser") ;
00079   std::string DBpass   = pSet.getParameter<std::string>("DBpass") ;
00080   //unsigned int32_t DBport = pSet.getParameter<unsigned int>("DBport") ;
00081   
00082   tag_   = pSet.getParameter<std::string>("TPGtag") ;
00083   version_ = pSet.getParameter<unsigned int>("TPGversion") ;
00084 
00085   m_write_ped = pSet.getParameter<unsigned int>("TPGWritePed") ;
00086   m_write_lin = pSet.getParameter<unsigned int>("TPGWriteLin") ;
00087   m_write_lut = pSet.getParameter<unsigned int>("TPGWriteLut") ;
00088   m_write_wei = pSet.getParameter<unsigned int>("TPGWriteWei") ;
00089   m_write_fgr = pSet.getParameter<unsigned int>("TPGWriteFgr") ;
00090   m_write_sli = pSet.getParameter<unsigned int>("TPGWriteSli") ;
00091   m_write_bxt = pSet.getParameter<unsigned int>("TPGWriteBxt") ;
00092   m_write_btt = pSet.getParameter<unsigned int>("TPGWriteBtt") ;
00093 
00094   btt_conf_id_=m_write_btt;
00095   bxt_conf_id_=m_write_bxt;
00096  
00097   if (writeToDB_) {
00098     try {
00099       std::cout << "data will be saved with tag and version="<< tag_<< ".version"<<version_<< std::endl;
00100       db_ = new EcalTPGDBApp(DBsid, DBuser, DBpass) ;
00101     } catch (std::exception &e) {
00102       std::cout << "ERROR:  " << e.what() << std::endl;
00103     } catch (...) {
00104       std::cout << "Unknown error caught" << std::endl;
00105     }
00106   }
00107 
00108   writeToFiles_ =  pSet.getParameter<bool>("writeToFiles") ;
00109   if (writeToFiles_) {
00110     std::string outFile = pSet.getParameter<std::string>("outFile") ;
00111     out_file_ = new std::ofstream(outFile.c_str(), std::ios::out) ;  
00112   }
00113   geomFile_   = new std::ofstream("geomFile.txt", std::ios::out) ;  
00114 
00115 
00116   useTransverseEnergy_ = pSet.getParameter<bool>("useTransverseEnergy") ;
00117   
00118   Et_sat_EB_ = pSet.getParameter<double>("Et_sat_EB") ;
00119   Et_sat_EE_ = pSet.getParameter<double>("Et_sat_EE") ;
00120   sliding_ = pSet.getParameter<unsigned int>("sliding") ;
00121   weight_timeShift_ = pSet.getParameter<double>("weight_timeShift") ;
00122   sampleMax_ = pSet.getParameter<unsigned int>("weight_sampleMax") ;
00123   weight_unbias_recovery_ = pSet.getParameter<bool>("weight_unbias_recovery") ;
00124 
00125   forcedPedestalValue_ = pSet.getParameter<int>("forcedPedestalValue") ;
00126   forceEtaSlice_ = pSet.getParameter<bool>("forceEtaSlice") ;
00127     
00128   LUT_option_ = pSet.getParameter<std::string>("LUT_option") ;
00129   LUT_threshold_EB_ = pSet.getParameter<double>("LUT_threshold_EB") ;
00130   LUT_threshold_EE_ = pSet.getParameter<double>("LUT_threshold_EE") ;
00131   LUT_stochastic_EB_ = pSet.getParameter<double>("LUT_stochastic_EB") ;
00132   LUT_noise_EB_ =pSet.getParameter<double>("LUT_noise_EB") ;
00133   LUT_constant_EB_ =pSet.getParameter<double>("LUT_constant_EB") ;
00134   LUT_stochastic_EE_ = pSet.getParameter<double>("LUT_stochastic_EE") ;
00135   LUT_noise_EE_ =pSet.getParameter<double>("LUT_noise_EE") ;
00136   LUT_constant_EE_ =pSet.getParameter<double>("LUT_constant_EE") ;
00137 
00138   TTF_lowThreshold_EB_ = pSet.getParameter<double>("TTF_lowThreshold_EB") ;
00139   TTF_highThreshold_EB_ = pSet.getParameter<double>("TTF_highThreshold_EB") ;
00140   TTF_lowThreshold_EE_ = pSet.getParameter<double>("TTF_lowThreshold_EE") ;
00141   TTF_highThreshold_EE_ = pSet.getParameter<double>("TTF_highThreshold_EE") ;
00142 
00143   FG_lowThreshold_EB_ = pSet.getParameter<double>("FG_lowThreshold_EB") ;
00144   FG_highThreshold_EB_ = pSet.getParameter<double>("FG_highThreshold_EB") ;
00145   FG_lowRatio_EB_ = pSet.getParameter<double>("FG_lowRatio_EB") ;
00146   FG_highRatio_EB_ = pSet.getParameter<double>("FG_highRatio_EB") ;
00147   FG_lut_EB_ = pSet.getParameter<unsigned int>("FG_lut_EB") ;
00148   FG_Threshold_EE_ = pSet.getParameter<double>("FG_Threshold_EE") ;
00149   FG_lut_strip_EE_ = pSet.getParameter<unsigned int>("FG_lut_strip_EE") ;
00150   FG_lut_tower_EE_ = pSet.getParameter<unsigned int>("FG_lut_tower_EE") ;
00151   SFGVB_Threshold_ = pSet.getParameter<unsigned int>("SFGVB_Threshold") ;
00152   SFGVB_lut_ = pSet.getParameter<unsigned int>("SFGVB_lut") ;
00153   pedestal_offset_ = pSet.getParameter<unsigned int>("pedestal_offset") ;
00154 
00155   useInterCalibration_  = pSet.getParameter<bool>("useInterCalibration") ;
00156 }
00157 
00158 EcalTPGParamBuilder::~EcalTPGParamBuilder()
00159 { 
00160   if (writeToFiles_) {
00161     (*out_file_ )<<"EOF"<<std::endl ;
00162     out_file_->close() ;
00163     delete out_file_ ;
00164   }
00165 }
00166 
00167 
00168 bool EcalTPGParamBuilder::checkIfOK(EcalPedestals::Item item) 
00169 {
00170   bool result=true;
00171   if( item.mean_x1 <150. || item.mean_x1 >250) result=false;
00172   if( item.mean_x6 <150. || item.mean_x6 >250) result=false;
00173   if( item.mean_x12 <150. || item.mean_x12 >250) result=false;
00174   if( item.rms_x1 <0 || item.rms_x1 > 2) result=false;
00175   if( item.rms_x6 <0 || item.rms_x6 > 3) result=false;
00176   if( item.rms_x12 <0 || item.rms_x12 > 5) result=false;
00177   return result; 
00178 }
00179 
00180 int EcalTPGParamBuilder::getEtaSlice(int tccId, int towerInTCC)
00181 {
00182   int etaSlice = (towerInTCC-1)/4+1 ;
00183   // barrel
00184   if (tccId>36 || tccId<73) return etaSlice ;
00185   //endcap
00186   else {
00187     if (tccId >=1 && tccId <= 18) etaSlice += 21 ; // inner -
00188     if (tccId >=19 && tccId <= 36) etaSlice += 17 ; // outer -
00189     if (tccId >=91 && tccId <= 108) etaSlice += 21 ; // inner +
00190     if (tccId >=73 && tccId <= 90) etaSlice += 17 ; // outer +
00191   }
00192   return etaSlice ;
00193 }
00194 
00195 void EcalTPGParamBuilder::analyze(const edm::Event& evt, const edm::EventSetup& evtSetup) 
00196 {
00197   using namespace edm;
00198   using namespace std;
00199 
00200   // geometry
00201   ESHandle<CaloGeometry> theGeometry;
00202   ESHandle<CaloSubdetectorGeometry> theEndcapGeometry_handle, theBarrelGeometry_handle;
00203   evtSetup.get<CaloGeometryRecord>().get( theGeometry );
00204   evtSetup.get<EcalEndcapGeometryRecord>().get("EcalEndcap",theEndcapGeometry_handle);
00205   evtSetup.get<EcalBarrelGeometryRecord>().get("EcalBarrel",theBarrelGeometry_handle);
00206   evtSetup.get<IdealGeometryRecord>().get(eTTmap_);
00207   theEndcapGeometry_ = &(*theEndcapGeometry_handle);
00208   theBarrelGeometry_ = &(*theBarrelGeometry_handle);
00209 
00210   // electronics mapping
00211   ESHandle< EcalElectronicsMapping > ecalmapping;
00212   evtSetup.get< EcalMappingRcd >().get(ecalmapping);
00213   theMapping_ = ecalmapping.product();
00214 
00215   
00216   // histo
00217   TFile saving ("EcalTPGParam.root","recreate") ;
00218   saving.cd () ;
00219   TH2F * ICEB = new TH2F("ICEB", "IC: Barrel", 360, 1, 361, 172, -86, 86) ;
00220   ICEB->GetYaxis()->SetTitle("eta index") ;
00221   ICEB->GetXaxis()->SetTitle("phi index") ;  
00222   TH2F * tpgFactorEB = new TH2F("tpgFactorEB", "tpgFactor: Barrel", 360, 1, 361, 172, -86, 86) ;
00223   tpgFactorEB->GetYaxis()->SetTitle("eta index") ;
00224   tpgFactorEB->GetXaxis()->SetTitle("phi index") ;  
00225 
00226   TH2F * ICEEPlus = new TH2F("ICEEPlus", "IC: Plus Endcap", 120, -9, 111, 120, -9, 111) ;
00227   ICEEPlus->GetYaxis()->SetTitle("y index") ;
00228   ICEEPlus->GetXaxis()->SetTitle("x index") ;
00229   TH2F * tpgFactorEEPlus = new TH2F("tpgFactorEEPlus", "tpgFactor: Plus Endcap", 120, -9, 111, 120, -9, 111) ;
00230   tpgFactorEEPlus->GetYaxis()->SetTitle("y index") ;
00231   tpgFactorEEPlus->GetXaxis()->SetTitle("x index") ;
00232   TH2F * ICEEMinus = new TH2F("ICEEMinus", "IC: Minus Endcap", 120, -9, 111, 120, -9, 111) ;
00233   ICEEMinus->GetYaxis()->SetTitle("y index") ;
00234   ICEEMinus->GetXaxis()->SetTitle("x index") ;
00235   TH2F * tpgFactorEEMinus = new TH2F("tpgFactorEEMinus", "tpgFactor: Minus Endcap", 120, -9, 111, 120, -9, 111) ;
00236   tpgFactorEEMinus->GetYaxis()->SetTitle("y index") ;
00237   tpgFactorEEMinus->GetXaxis()->SetTitle("x index") ;
00238 
00239   TH2F * IC = new TH2F("IC", "IC", 720, -acos(-1.), acos(-1.), 600, -3., 3.) ;
00240   IC->GetYaxis()->SetTitle("eta") ;
00241   IC->GetXaxis()->SetTitle("phi") ;  
00242   TH2F * tpgFactor = new TH2F("tpgFactor", "tpgFactor", 720, -acos(-1.), acos(-1.), 600, -3., 3.) ;
00243   tpgFactor->GetYaxis()->SetTitle("eta") ;
00244   tpgFactor->GetXaxis()->SetTitle("phi") ;  
00245 
00246   TH1F * hshapeEB = new TH1F("shapeEB", "shapeEB", 250, 0., 10.) ;
00247   TH1F * hshapeEE = new TH1F("shapeEE", "shapeEE", 250, 0., 10.) ;
00248 
00249   TTree * ntuple = new TTree("tpgmap","TPG geometry map") ;
00250   const char * branchFloat[24] = {"fed","tcc","tower","stripInTower","xtalInStrip",
00251                             "CCU","VFE","xtalInVFE","xtalInCCU","ieta","iphi",
00252                             "ix","iy","iz","hashedId","ic","ietaTT","iphiTT",
00253                             "TCCch","TCCslot","SLBch","SLBslot","ietaGCT","iphiGCT"} ;
00254   ntupleFloats_ = new Float_t[24] ;
00255   for (int i=0 ; i<24 ; i++) ntuple->Branch(branchFloat[i],&ntupleFloats_[i],branchFloat[i]) ;
00256   ntuple->Branch("det",ntupleDet_,"det/C") ;
00257   ntuple->Branch("crate",ntupleCrate_,"crate/C") ;
00258 
00259 
00260   TNtuple *ntupleSpike = new TNtuple("spikeParam","Spike parameters","gainId:theta:G:g:ped:pedLin") ;
00261 
00262 
00263 
00264 
00266   // Initialization section //
00268   list<uint32_t> towerListEB ;
00269   list<uint32_t> stripListEB ;
00270   list<uint32_t> towerListEE ;
00271   list<uint32_t> stripListEE ;
00272   list<uint32_t>::iterator itList ;
00273   
00274   std::map<int, uint32_t> stripMapEB ; // <EcalLogicId.hashed, strip elec id>
00275   std::map<uint32_t, uint32_t> stripMapEBsintheta ; // <strip elec id, sintheta>
00276 
00277 
00278   // Pedestals
00279   std::cout <<"Getting the pedestals from offline DB..."<<std::endl;
00280   ESHandle<EcalPedestals> pedHandle;
00281   evtSetup.get<EcalPedestalsRcd>().get( pedHandle );
00282   const EcalPedestalsMap & pedMap = pedHandle.product()->getMap() ;
00283   EcalPedestalsMapIterator pedIter ; 
00284   int nPed = 0 ;
00285   for (pedIter = pedMap.begin() ; pedIter != pedMap.end() && nPed<10 ; ++pedIter, nPed++) {
00286     EcalPedestals::Item aped = (*pedIter);
00287     std::cout<<aped.mean_x12<<", "<<aped.mean_x6<<", "<<aped.mean_x1<<std::endl ;
00288   }
00289   std::cout<<"...\n"<<std::endl ; 
00290 
00291 
00292   // Intercalib constants
00293   std::cout <<"Getting intercalib from offline DB..."<<std::endl;
00294   ESHandle<EcalIntercalibConstants> pIntercalib ;
00295   evtSetup.get<EcalIntercalibConstantsRcd>().get(pIntercalib) ;
00296   const EcalIntercalibConstants * intercalib = pIntercalib.product() ;
00297   const EcalIntercalibConstantMap & calibMap = intercalib->getMap() ;
00298   EcalIntercalibConstantMap::const_iterator calIter ;
00299   int nCal = 0 ;
00300   for (calIter = calibMap.begin() ; calIter != calibMap.end() && nCal<10 ; ++calIter, nCal++) {
00301     std::cout<<(*calIter)<<std::endl ;
00302   }  
00303   std::cout<<"...\n"<<std::endl ;
00304 
00305 
00306   // Gain Ratios
00307   std::cout <<"Getting the gain ratios from offline DB..."<<std::endl;
00308   ESHandle<EcalGainRatios> pRatio;
00309   evtSetup.get<EcalGainRatiosRcd>().get(pRatio);
00310   const EcalGainRatioMap & gainMap = pRatio.product()->getMap();
00311   EcalGainRatioMap::const_iterator gainIter ;
00312   int nGain = 0 ;
00313   for (gainIter = gainMap.begin() ; gainIter != gainMap.end() && nGain<10 ; ++gainIter, nGain++) {
00314     const EcalMGPAGainRatio & aGain = (*gainIter) ;
00315     std::cout<<aGain.gain12Over6()<<", "<<aGain.gain6Over1() * aGain.gain12Over6()<<std::endl ;
00316   }  
00317   std::cout<<"...\n"<<std::endl ;    
00318 
00319 
00320   // ADCtoGeV
00321   std::cout <<"Getting the ADC to GEV from offline DB..."<<std::endl;
00322   ESHandle<EcalADCToGeVConstant> pADCToGeV ;
00323   evtSetup.get<EcalADCToGeVConstantRcd>().get(pADCToGeV) ;
00324   const EcalADCToGeVConstant * ADCToGeV = pADCToGeV.product() ;
00325   xtal_LSB_EB_ = ADCToGeV->getEBValue() ;
00326   xtal_LSB_EE_ = ADCToGeV->getEEValue() ;
00327   std::cout<<"xtal_LSB_EB_ = "<<xtal_LSB_EB_<<std::endl ;
00328   std::cout<<"xtal_LSB_EE_ = "<<xtal_LSB_EE_<<std::endl ;
00329   std::cout<<std::endl ;  
00330 
00331   
00332   std::vector<EcalLogicID> my_EcalLogicId;
00333   std::vector<EcalLogicID> my_TTEcalLogicId;
00334   std::vector<EcalLogicID> my_StripEcalLogicId;
00335   EcalLogicID my_EcalLogicId_EB;
00336     // Endcap identifiers
00337   EcalLogicID my_EcalLogicId_EE;
00338   std::vector<EcalLogicID> my_TTEcalLogicId_EE;
00339   std::vector<EcalLogicID> my_RTEcalLogicId_EE;
00340   std::vector<EcalLogicID> my_StripEcalLogicId1_EE;
00341   std::vector<EcalLogicID> my_StripEcalLogicId2_EE;
00342   std::vector<EcalLogicID> my_CrystalEcalLogicId_EE;
00343 
00344   if (writeToDB_){
00345     std::cout<<"going to get the ecal logic id set"<< std::endl;
00346 
00347     my_EcalLogicId_EB = db_->getEcalLogicID( "EB",EcalLogicID::NULLID,EcalLogicID::NULLID,EcalLogicID::NULLID,"EB");
00348     my_EcalLogicId_EE = db_->getEcalLogicID( "EE",EcalLogicID::NULLID,EcalLogicID::NULLID,EcalLogicID::NULLID,"EE");
00349 
00350     my_EcalLogicId = db_->getEcalLogicIDSetOrdered( "EB_crystal_number",
00351                                                     1, 36,
00352                                                     1, 1700,
00353                                                     EcalLogicID::NULLID,EcalLogicID::NULLID,
00354                                                     "EB_crystal_number",12 );
00355     my_TTEcalLogicId = db_->getEcalLogicIDSetOrdered( "EB_trigger_tower",
00356                                                     1, 36,
00357                                                     1, 68,
00358                                                     EcalLogicID::NULLID,EcalLogicID::NULLID,
00359                                                     "EB_trigger_tower",12 );
00360     my_StripEcalLogicId = db_->getEcalLogicIDSetOrdered( "EB_VFE",   1, 36,   1, 68,   1,5 ,  "EB_VFE",123 ); //last digi means ordered 1st by SM,then TT, then strip 
00361     std::cout<<"got the 3 ecal barrel logic id set"<< std::endl;
00362 
00363     // EE crystals identifiers
00364     // EE crystals identifiers
00365     my_CrystalEcalLogicId_EE = db_->getEcalLogicIDSetOrdered("EE_crystal_number",
00366                                                     -1, 1,
00367                                                     0, 200,
00368                                                     0, 200,
00369                                                     "EE_crystal_number",123 );
00370 
00371                                                     
00372     // EE Strip identifiers
00373     // DCC=601-609 TT = ~40 EEstrip = 5
00374     my_StripEcalLogicId1_EE = db_->getEcalLogicIDSetOrdered( "ECAL_readout_strip",   
00375                                                         601, 609,   
00376                                                         1, 100,   
00377                                                         0,5 ,  
00378                                                         "ECAL_readout_strip",123 );
00379                                                     
00380     // EE Strip identifiers
00381     // DCC=646-654 TT = ~40 EEstrip = 5
00382     my_StripEcalLogicId2_EE = db_->getEcalLogicIDSetOrdered( "ECAL_readout_strip",   
00383                                                         646, 654,   
00384                                                         1, 100,   
00385                                                         0,5 ,  
00386                                                         "ECAL_readout_strip",123 );
00387     
00388     // TTC=72 TT = 1440
00389     my_TTEcalLogicId_EE = db_->getEcalLogicIDSetOrdered( "EE_trigger_tower",
00390                                                     1, 108,
00391                                                     1, 40,
00392                                                     EcalLogicID::NULLID,EcalLogicID::NULLID,
00393                                                     "EE_trigger_tower",12 );
00394 
00395     
00396     // TTC=72 TT = 1440
00397     my_RTEcalLogicId_EE = db_->getEcalLogicIDSetOrdered( "EE_readout_tower",
00398                                                     1, 1000,
00399                                                     1, 100,
00400                                                     EcalLogicID::NULLID,EcalLogicID::NULLID,
00401                                                     "EE_readout_tower",12 );
00402 
00403     std::cout<<"got the end cap logic id set"<< std::endl;
00404     std::cout<<"now just get the latest ids for this tag (latest version) "<< std::endl;
00405 
00406 
00407     FEConfigMainInfo fe_main_info;
00408     fe_main_info.setConfigTag(tag_);
00409     try {
00410       std::cout << "trying to read previous tag if it exists tag="<< tag_<< ".version"<<version_<< std::endl;
00411 
00412       db_-> fetchConfigSet(&fe_main_info);
00413       ped_conf_id_=fe_main_info.getPedId();
00414       lin_conf_id_=fe_main_info.getLinId();
00415       lut_conf_id_=fe_main_info.getLUTId();
00416       wei_conf_id_=fe_main_info.getWeiId();
00417       fgr_conf_id_=fe_main_info.getFgrId();
00418       sli_conf_id_=fe_main_info.getSliId();
00419       if(fe_main_info.getBxtId()>0) bxt_conf_id_=fe_main_info.getBxtId();
00420       if(fe_main_info.getBttId()>0 && btt_conf_id_==0 ) btt_conf_id_=fe_main_info.getBttId();
00421       // those that are not written specifically in this program are propagated
00422       // from the previous record with the same tag and the highest version
00423 
00424       std::cout<<"got it "<< std::endl;
00425 
00426     } catch (exception &e) {
00427       std::cout << " tag did not exist a new tag will be created " << std::endl;
00428     } catch (...) {
00429       std::cout << "Unknown error caught" << std::endl;
00430     }
00431 
00432   }
00433 
00435   // Compute linearization coeff section //
00437 
00438   std::map<EcalLogicID, FEConfigPedDat> pedset ;
00439   std::map<EcalLogicID, FEConfigLinDat> linset ;
00440   std::map<EcalLogicID, FEConfigLinParamDat> linparamset ;
00441   std::map<EcalLogicID, FEConfigLUTParamDat> lutparamset ;
00442   std::map<EcalLogicID, FEConfigFgrParamDat> fgrparamset ;
00443 
00444   std::map<int, linStruc> linEtaSlice ;
00445   std::map <std::vector<int>, linStruc > linMap ;
00446 
00447   // count number of strip per tower
00448   int NbOfStripPerTCC[108][68] ; 
00449   for (int i=0 ; i<108 ; i++)
00450     for (int j=0 ; j<68 ; j++) 
00451       NbOfStripPerTCC[i][j] = 0 ;
00452   const std::vector<DetId> & ebCells = theBarrelGeometry_->getValidDetIds(DetId::Ecal, EcalBarrel);
00453   const std::vector<DetId> & eeCells = theEndcapGeometry_->getValidDetIds(DetId::Ecal, EcalEndcap);
00454   for (std::vector<DetId>::const_iterator it = ebCells.begin(); it != ebCells.end(); ++it) {
00455     EBDetId id(*it) ;
00456     const EcalTrigTowerDetId towid= id.tower();
00457     const EcalTriggerElectronicsId elId = theMapping_->getTriggerElectronicsId(id) ;
00458     int tccNb = theMapping_->TCCid(towid) ;
00459     int towerInTCC = theMapping_->iTT(towid) ;
00460     int stripInTower = elId.pseudoStripId() ;  
00461     if (stripInTower>NbOfStripPerTCC[tccNb-1][towerInTCC-1]) NbOfStripPerTCC[tccNb-1][towerInTCC-1] = stripInTower ;
00462   }
00463   for (std::vector<DetId>::const_iterator it = eeCells.begin(); it != eeCells.end(); ++it) {
00464     EEDetId id(*it) ;
00465     const EcalTrigTowerDetId towid= (*eTTmap_).towerOf(id) ;
00466     const EcalTriggerElectronicsId elId = theMapping_->getTriggerElectronicsId(id) ;
00467     int tccNb = theMapping_->TCCid(towid) ;
00468     int towerInTCC = theMapping_->iTT(towid) ; 
00469     int stripInTower = elId.pseudoStripId() ;
00470     if (stripInTower>NbOfStripPerTCC[tccNb-1][towerInTCC-1]) NbOfStripPerTCC[tccNb-1][towerInTCC-1] = stripInTower ;
00471   }
00472 
00473 
00474 
00475   // loop on EB xtals
00476   if (writeToFiles_) (*out_file_)<<"COMMENT ====== barrel crystals ====== "<<std::endl ;
00477 
00478   // special case of eta slices
00479   for (std::vector<DetId>::const_iterator it = ebCells.begin(); it != ebCells.end(); ++it) {
00480     EBDetId id(*it) ;
00481     double theta = theBarrelGeometry_->getGeometry(id)->getPosition().theta() ;
00482     if (!useTransverseEnergy_) theta = acos(0.) ;
00483     const EcalTrigTowerDetId towid= id.tower();
00484     const EcalTriggerElectronicsId elId = theMapping_->getTriggerElectronicsId(id) ;
00485     int dccNb = theMapping_->DCCid(towid) ;
00486     int tccNb = theMapping_->TCCid(towid) ;
00487     int towerInTCC = theMapping_->iTT(towid) ; // from 1 to 68 (EB)
00488     int stripInTower = elId.pseudoStripId() ;  // from 1 to 5
00489     int xtalInStrip = elId.channelId() ;       // from 1 to 5
00490     const EcalElectronicsId Id = theMapping_->getElectronicsId(id) ;
00491     int CCUid = Id.towerId() ;
00492     int VFEid = Id.stripId() ;
00493     int xtalInVFE = Id.xtalId() ;
00494     int xtalWithinCCUid = 5*(VFEid-1) + xtalInVFE -1 ; // Evgueni expects [0,24]
00495          
00496     (*geomFile_)<<"dccNb = "<<dccNb<<" tccNb = "<<tccNb<<" towerInTCC = "<<towerInTCC
00497                 <<" stripInTower = "<<stripInTower<<" xtalInStrip = "<<xtalInStrip
00498                 <<" CCUid = "<<CCUid<<" VFEid = "<<VFEid<<" xtalInVFE = "<<xtalInVFE
00499                 <<" xtalWithinCCUid = "<<xtalWithinCCUid<<" ieta = "<<id.ieta()<<" iphi = "<<id.iphi()
00500                 <<" xtalhashedId = "<<id.hashedIndex()<<" xtalNb = "<<id.ic()
00501                 <<" ietaTT = "<<towid.ieta()<<" iphiTT = "<<towid.iphi()<<std::endl ;
00502 
00503     int TCCch = towerInTCC ;
00504     int SLBslot = int((towerInTCC-1)/8.) + 1 ;
00505     int SLBch = (towerInTCC-1)%8 + 1 ;
00506     float val[] = {float(dccNb+600),float(tccNb),float(towerInTCC),float(stripInTower),
00507                    float(xtalInStrip),float(CCUid),float(VFEid),float(xtalInVFE),
00508                    float(xtalWithinCCUid),float(id.ieta()),float(id.iphi()),
00509                    -999.,-999.,float(towid.ieta())/float(abs(towid.ieta())),
00510                    float(id.hashedIndex()),
00511                    float(id.ic()),float(towid.ieta()),float(towid.iphi()), 
00512                    float(TCCch), float(getCrate(tccNb).second), 
00513                    float(SLBch), float(SLBslot), 
00514                    float(getGCTRegionEta(towid.ieta())),float(getGCTRegionPhi(towid.iphi()))} ;
00515     for (int i=0 ; i<24 ; i++) ntupleFloats_[i] = val[i] ;
00516     
00517     sprintf(ntupleDet_,getDet(tccNb).c_str()) ;
00518     sprintf(ntupleCrate_,getCrate(tccNb).first.c_str()) ;
00519     ntuple->Fill() ;
00520     
00521     
00522     if (tccNb == 37 && stripInTower == 3 && xtalInStrip == 3 && (towerInTCC-1)%4==0) {
00523       int etaSlice = towid.ietaAbs() ;
00524       coeffStruc coeff ;
00525       getCoeff(coeff, calibMap, id.rawId()) ;
00526       getCoeff(coeff, gainMap, id.rawId()) ;
00527       getCoeff(coeff, pedMap, id.rawId()) ;
00528       linStruc lin ;
00529       for (int i=0 ; i<3 ; i++) {
00530         int mult, shift ;
00531         bool ok = computeLinearizerParam(theta, coeff.gainRatio_[i], coeff.calibCoeff_, "EB", mult , shift) ;
00532         if (!ok) std::cout << "unable to compute the parameters for SM="<< id.ism()<<" xt="<< id.ic()<<" " <<dec<<id.rawId()<<std::endl ;  
00533         else {
00534           lin.pedestal_[i] = coeff.pedestals_[i] ;
00535           lin.mult_[i] = mult ;
00536           lin.shift_[i] = shift ;
00537         }
00538       }
00539 
00540       bool ok(true) ;
00541       if (forcedPedestalValue_ == -2) ok = realignBaseline(lin, 0) ;
00542       if (!ok) std::cout<<"SM="<< id.ism()<<" xt="<< id.ic()<<" " <<dec<<id.rawId()<<std::endl ; 
00543       linEtaSlice[etaSlice] = lin ;     
00544     }
00545   }    
00546 
00547   // general case
00548   for (std::vector<DetId>::const_iterator it = ebCells.begin(); it != ebCells.end(); ++it) {
00549     EBDetId id(*it) ;
00550     double theta = theBarrelGeometry_->getGeometry(id)->getPosition().theta() ;
00551     if (!useTransverseEnergy_) theta = acos(0.) ;
00552     const EcalTrigTowerDetId towid= id.tower();
00553     towerListEB.push_back(towid.rawId()) ;
00554     const EcalTriggerElectronicsId elId = theMapping_->getTriggerElectronicsId(id) ;
00555     stripListEB.push_back(elId.rawId() & 0xfffffff8) ;
00556     int dccNb = theMapping_->DCCid(towid) ;
00557     //int tccNb = theMapping_->TCCid(towid) ;
00558     int towerInTCC = theMapping_->iTT(towid) ; // from 1 to 68 (EB)
00559     //int stripInTower = elId.pseudoStripId() ;  // from 1 to 5
00560     //int xtalInStrip = elId.channelId() ;       // from 1 to 5
00561     const EcalElectronicsId Id = theMapping_->getElectronicsId(id) ;
00562     int CCUid = Id.towerId() ;
00563     int VFEid = Id.stripId() ;
00564     int xtalInVFE = Id.xtalId() ;
00565     int xtalWithinCCUid = 5*(VFEid-1) + xtalInVFE -1 ; // Evgueni expects [0,24]
00566     int etaSlice = towid.ietaAbs() ;
00567 
00568     // hashed index of strip EcalLogicID:
00569     int hashedStripLogicID = 68*5*(id.ism()-1) + 5*(towerInTCC-1) +  (VFEid-1) ;
00570     stripMapEB[hashedStripLogicID] = elId.rawId() & 0xfffffff8 ;
00571     stripMapEBsintheta[elId.rawId() & 0xfffffff8] = SFGVB_Threshold_ + abs(int(sin(theta)*pedestal_offset_)) ;
00572 
00573     FEConfigPedDat pedDB ;
00574     FEConfigLinDat linDB ;
00575     if (writeToFiles_) (*out_file_)<<"CRYSTAL "<<dec<<id.rawId()<<std::endl ;
00576     //  if (writeToDB_) logicId = db_->getEcalLogicID ("EB_crystal_number", id.ism(), id.ic()) ;
00577 
00578     coeffStruc coeff ;
00579     getCoeff(coeff, calibMap, id.rawId()) ;
00580     getCoeff(coeff, gainMap, id.rawId()) ;
00581     getCoeff(coeff, pedMap, id.rawId()) ;
00582     ICEB->Fill(id.iphi(), id.ieta(), coeff.calibCoeff_) ;  
00583     IC->Fill(theBarrelGeometry_->getGeometry(id)->getPosition().phi(), theBarrelGeometry_->getGeometry(id)->getPosition().eta(), coeff.calibCoeff_) ;  
00584 
00585     std::vector<int> xtalCCU ;
00586     xtalCCU.push_back(dccNb+600) ; 
00587     xtalCCU.push_back(CCUid) ; 
00588     xtalCCU.push_back(xtalWithinCCUid) ;
00589     xtalCCU.push_back(id.rawId()) ;
00590     
00591     // compute and fill linearization parameters
00592     // case of eta slice
00593     if (forceEtaSlice_) {
00594       std::map<int, linStruc>::const_iterator itLin = linEtaSlice.find(etaSlice);
00595       if (itLin != linEtaSlice.end()) {
00596         linMap[xtalCCU] = itLin->second ;
00597         if (writeToFiles_) {
00598           for (int i=0 ; i<3 ; i++) 
00599             (*out_file_) << hex <<" 0x"<<itLin->second.pedestal_[i]<<" 0x"<<itLin->second.mult_[i]<<" 0x"<<itLin->second.shift_[i]<<std::endl;
00600         }
00601         if (writeToDB_) {
00602           for (int i=0 ; i<3 ; i++) {
00603             if (i==0)  {pedDB.setPedMeanG12(itLin->second.pedestal_[i]) ; linDB.setMultX12(itLin->second.mult_[i]) ; linDB.setShift12(itLin->second.shift_[i]) ; } 
00604             if (i==1)  {pedDB.setPedMeanG6(itLin->second.pedestal_[i]) ; linDB.setMultX6(itLin->second.mult_[i]) ; linDB.setShift6(itLin->second.shift_[i]) ; } 
00605             if (i==2)  {pedDB.setPedMeanG1(itLin->second.pedestal_[i]) ; linDB.setMultX1(itLin->second.mult_[i]) ; linDB.setShift1(itLin->second.shift_[i]) ; } 
00606           }
00607         }
00608         float factor = float(itLin->second.mult_[0])*pow(2.,-itLin->second.shift_[0])/xtal_LSB_EB_ ;
00609         tpgFactorEB->Fill(id.iphi(), id.ieta(), factor) ;
00610         tpgFactor->Fill(theBarrelGeometry_->getGeometry(id)->getPosition().phi(), 
00611                         theBarrelGeometry_->getGeometry(id)->getPosition().eta(), factor) ;
00612       }
00613       else std::cout<<"current EtaSlice = "<<etaSlice<<" not found in the EtaSlice map"<<std::endl ;
00614     }
00615     else {
00616       // general case
00617       linStruc lin ;
00618       int forceBase12 = 0 ;
00619       for (int i=0 ; i<3 ; i++) {
00620         int mult, shift ;
00621         bool ok = computeLinearizerParam(theta, coeff.gainRatio_[i], coeff.calibCoeff_, "EB", mult , shift) ;
00622         if (!ok) std::cout << "unable to compute the parameters for SM="<< id.ism()<<" xt="<< id.ic()<<" " <<dec<<id.rawId()<<std::endl ;  
00623         else {
00624           //PP begin
00625           //  mult = 0 ; shift = 0 ;
00626           //  if (CCUid==1 && xtalWithinCCUid==21) {
00627           //    if (i==0) {mult = 0x80 ; shift = 0x3 ;}
00628           //    if (i==1) {mult = 0x80 ; shift = 0x2 ;}
00629           //    if (i==2) {mult = 0xc0 ; shift = 0x0 ;}
00630           //  } 
00631           //PP end
00632           double base = coeff.pedestals_[i] ;
00633           if (forcedPedestalValue_ == -3 && i==0) {
00634             double G = mult*pow(2.,-(shift+2)) ;
00635             double g = G/sin(theta) ;
00636             // int pedestal = coeff.pedestals_[i] ;
00637             base = double(coeff.pedestals_[i]) - pedestal_offset_/g ;
00638             if (base<0.) base = 0 ;
00639             forceBase12 = int(base) ;
00640           }
00641           lin.pedestal_[i] = coeff.pedestals_[i] ;
00642           lin.mult_[i] = mult ;
00643           lin.shift_[i] = shift ;
00644         }
00645       }
00646 
00647       bool ok(true) ;
00648       if (forcedPedestalValue_ == -2) ok = realignBaseline(lin, 0) ;
00649       if (forcedPedestalValue_ == -3) ok = realignBaseline(lin, forceBase12) ;
00650       if (!ok) std::cout<<"SM="<< id.ism()<<" xt="<< id.ic()<<" " <<dec<<id.rawId()<<std::endl ; 
00651       
00652       for (int i=0 ; i<3 ; i++) {      
00653         if (writeToFiles_) (*out_file_) << hex <<" 0x"<<lin.pedestal_[i]<<" 0x"<<lin.mult_[i]<<" 0x"<<lin.shift_[i]<<std::endl; 
00654         if (writeToDB_) {
00655           if (i==0)  {pedDB.setPedMeanG12(lin.pedestal_[i]) ; linDB.setMultX12(lin.mult_[i]) ; linDB.setShift12(lin.shift_[i]) ; } 
00656           if (i==1)  {pedDB.setPedMeanG6(lin.pedestal_[i]) ; linDB.setMultX6(lin.mult_[i]) ; linDB.setShift6(lin.shift_[i]) ; } 
00657           if (i==2)  {pedDB.setPedMeanG1(lin.pedestal_[i]) ; linDB.setMultX1(lin.mult_[i]) ; linDB.setShift1(lin.shift_[i]) ; }
00658         }
00659         if (i==0) {
00660           float factor = float(lin.mult_[i])*pow(2.,-lin.shift_[i])/xtal_LSB_EB_ ;
00661           tpgFactorEB->Fill(id.iphi(), id.ieta(), factor) ;
00662           tpgFactor->Fill(theBarrelGeometry_->getGeometry(id)->getPosition().phi(), 
00663                           theBarrelGeometry_->getGeometry(id)->getPosition().eta(), factor) ;                       
00664         }
00665         double G = lin.mult_[i]*pow(2.,-(lin.shift_[i]+2)) ;
00666         double g = G/sin(theta) ;
00667         float val[] = {float(i),float(theta),float(G),float(g),
00668                        float(coeff.pedestals_[i]),float(lin.pedestal_[i])} ;// first arg = gainId (0 means gain12)
00669         ntupleSpike->Fill(val) ;
00670       }
00671       linMap[xtalCCU] = lin ;
00672     }
00673     if (writeToDB_) {
00674     // 1700 crystals/SM in the ECAL barrel
00675       int ixtal=(id.ism()-1)*1700+(id.ic()-1);
00676       EcalLogicID logicId =my_EcalLogicId[ixtal];
00677       pedset[logicId] = pedDB ;
00678       linset[logicId] = linDB ; 
00679     }
00680   } //ebCells
00681 
00682   if (writeToDB_) {
00683     // EcalLogicID  of the whole barrel is: my_EcalLogicId_EB
00684     FEConfigLinParamDat linparam ;
00685     linparam.setETSat(Et_sat_EB_); 
00686     linparamset[my_EcalLogicId_EB] = linparam ;
00687 
00688     FEConfigFgrParamDat fgrparam ;
00689     fgrparam.setFGlowthresh(FG_lowThreshold_EB_); 
00690     fgrparam.setFGhighthresh(FG_highThreshold_EB_); 
00691     fgrparam.setFGlowratio(FG_lowRatio_EB_); 
00692     fgrparam.setFGhighratio(FG_highRatio_EB_);
00693     fgrparamset[my_EcalLogicId_EB] = fgrparam ;
00694 
00695 
00696     FEConfigLUTParamDat lutparam ;
00697     lutparam.setETSat(Et_sat_EB_); 
00698     lutparam.setTTThreshlow(TTF_lowThreshold_EB_); 
00699     lutparam.setTTThreshhigh(TTF_highThreshold_EB_); 
00700     lutparamset[my_EcalLogicId_EB] = lutparam ;
00701 
00702   }
00703 
00704 
00705   // loop on EE xtals
00706   if (writeToFiles_) (*out_file_)<<"COMMENT ====== endcap crystals ====== "<<std::endl ;
00707   
00708   // special case of eta slices
00709   for (std::vector<DetId>::const_iterator it = eeCells.begin(); it != eeCells.end(); ++it) {
00710     EEDetId id(*it) ;
00711     double theta = theEndcapGeometry_->getGeometry(id)->getPosition().theta() ;
00712     if (!useTransverseEnergy_) theta = acos(0.) ;
00713     const EcalTrigTowerDetId towid= (*eTTmap_).towerOf(id) ;
00714     const EcalTriggerElectronicsId elId = theMapping_->getTriggerElectronicsId(id) ;
00715     const EcalElectronicsId Id = theMapping_->getElectronicsId(id) ;
00716     int dccNb = Id.dccId() ;
00717     int tccNb = theMapping_->TCCid(towid) ;
00718     int towerInTCC = theMapping_->iTT(towid) ; 
00719     int stripInTower = elId.pseudoStripId() ;
00720     int xtalInStrip = elId.channelId() ;
00721     int CCUid = Id.towerId() ;
00722     int VFEid = Id.stripId() ;
00723     int xtalInVFE = Id.xtalId() ;
00724     int xtalWithinCCUid = 5*(VFEid-1) + xtalInVFE -1 ; // Evgueni expects [0,24]
00725 
00726     (*geomFile_)<<"dccNb = "<<dccNb<<" tccNb = "<<tccNb<<" towerInTCC = "<<towerInTCC
00727                 <<" stripInTower = "<<stripInTower<<" xtalInStrip = "<<xtalInStrip
00728                 <<" CCUid = "<<CCUid<<" VFEid = "<<VFEid<<" xtalInVFE = "<<xtalInVFE
00729                 <<" xtalWithinCCUid = "<<xtalWithinCCUid<<" ix = "<<id.ix()<<" iy = "<<id.iy()
00730                 <<" xtalhashedId = "<<id.hashedIndex()<<" xtalNb = "<<id.isc()
00731                 <<" ietaTT = "<<towid.ieta()<<" iphiTT = "<<towid.iphi()<<std::endl ;
00732 
00733     int TCCch = stripInTower ;
00734     int SLBslot, SLBch ;
00735     if (towerInTCC<5) {
00736       SLBslot = 1 ;
00737       SLBch = 4 + towerInTCC ;
00738     }
00739     else {
00740       SLBslot = int((towerInTCC-5)/8.) + 2 ;
00741       SLBch = (towerInTCC-5)%8 + 1 ;
00742     } 
00743     for (int j=0 ; j<towerInTCC-1 ; j++) TCCch += NbOfStripPerTCC[tccNb-1][j] ;
00744     float val[] = {float(dccNb+600),float(tccNb),float(towerInTCC),float(stripInTower),
00745                    float(xtalInStrip),float(CCUid),float(VFEid),float(xtalInVFE),
00746                    float(xtalWithinCCUid),-999.,-999.,
00747                    float(id.ix()),float(id.iy()),float(towid.ieta())/float(abs(towid.ieta())),
00748                    float(id.hashedIndex()),
00749                    float(id.ic()),float(towid.ieta()),float(towid.iphi()),float(TCCch), 
00750                    float(getCrate(tccNb).second),
00751                    float(SLBch), float(SLBslot), 
00752                    float(getGCTRegionEta(towid.ieta())),float(getGCTRegionPhi(towid.iphi()))} ;
00753     for (int i=0 ; i<24 ; i++) ntupleFloats_[i] = val[i] ;
00754     sprintf(ntupleDet_,getDet(tccNb).c_str()) ;
00755     sprintf(ntupleCrate_,getCrate(tccNb).first.c_str()) ;
00756     ntuple->Fill() ;
00757      
00758     if ((tccNb == 76 || tccNb == 94) && stripInTower == 1 && xtalInStrip == 3 && (towerInTCC-1)%4==0) {
00759       int etaSlice = towid.ietaAbs() ;
00760       coeffStruc coeff ;
00761       getCoeff(coeff, calibMap, id.rawId()) ;
00762       getCoeff(coeff, gainMap, id.rawId()) ;
00763       getCoeff(coeff, pedMap, id.rawId()) ;
00764       linStruc lin ;
00765       for (int i=0 ; i<3 ; i++) {
00766         int mult, shift ;
00767         bool ok = computeLinearizerParam(theta, coeff.gainRatio_[i], coeff.calibCoeff_, "EE", mult , shift) ;
00768         if (!ok) std::cout << "unable to compute the parameters for Quadrant="<< id.iquadrant()<<" xt="<< id.ic()<<" " <<dec<<id.rawId()<<std::endl ;  
00769         else {
00770           lin.pedestal_[i] = coeff.pedestals_[i] ;
00771           lin.mult_[i] = mult ;
00772           lin.shift_[i] = shift ;
00773         }
00774       }
00775 
00776       bool ok(true) ;
00777       if (forcedPedestalValue_ == -2 || forcedPedestalValue_ == -3) ok = realignBaseline(lin, 0) ;
00778       if (!ok) std::cout<<"Quadrant="<< id.iquadrant()<<" xt="<< id.ic()<<" " <<dec<<id.rawId()<<std::endl ; 
00779 
00780       linEtaSlice[etaSlice] = lin ;
00781     }
00782   }
00783 
00784   // general case
00785   for (std::vector<DetId>::const_iterator it = eeCells.begin(); it != eeCells.end(); ++it) {
00786     EEDetId id(*it);
00787     double theta = theEndcapGeometry_->getGeometry(id)->getPosition().theta() ;
00788     if (!useTransverseEnergy_) theta = acos(0.) ;
00789     const EcalTrigTowerDetId towid= (*eTTmap_).towerOf(id) ;
00790     const EcalTriggerElectronicsId elId = theMapping_->getTriggerElectronicsId(id) ;
00791     const EcalElectronicsId Id = theMapping_->getElectronicsId(id) ;
00792     towerListEE.push_back(towid.rawId()) ;
00793     // special case of towers in inner rings of EE
00794     if (towid.ietaAbs() == 27 || towid.ietaAbs() == 28) {
00795       EcalTrigTowerDetId additionalTower(towid.zside(), towid.subDet(), towid.ietaAbs(), towid.iphi()+1) ;
00796       towerListEE.push_back(additionalTower.rawId()) ;
00797     }
00798     stripListEE.push_back(elId.rawId() & 0xfffffff8) ;
00799     int dccNb = Id.dccId() ;
00800     //int tccNb = theMapping_->TCCid(towid) ;
00801     //int towerInTCC = theMapping_->iTT(towid) ;
00802     //int stripInTower = elId.pseudoStripId() ;
00803     //int xtalInStrip = elId.channelId() ;
00804     int CCUid = Id.towerId() ;
00805     int VFEid = Id.stripId() ;
00806     int xtalInVFE = Id.xtalId() ;
00807     int xtalWithinCCUid = 5*(VFEid-1) + xtalInVFE -1 ; // Evgueni expects [0,24]
00808     int etaSlice = towid.ietaAbs() ;
00809 
00810     EcalLogicID logicId ;
00811     FEConfigPedDat pedDB ;
00812     FEConfigLinDat linDB ;
00813     if (writeToFiles_) (*out_file_)<<"CRYSTAL "<<dec<<id.rawId()<<std::endl ;
00814     if (writeToDB_ && DBEE_) {
00815       int iz = id.positiveZ() ;
00816       if (iz ==0) iz = -1 ;
00817       
00818       for(int k=0; k<(int)my_CrystalEcalLogicId_EE.size(); k++) {
00819 
00820         int z= my_CrystalEcalLogicId_EE[k].getID1() ;
00821         int x= my_CrystalEcalLogicId_EE[k].getID2() ;
00822         int y= my_CrystalEcalLogicId_EE[k].getID3() ;
00823 
00824         if(id.ix()==x && id.iy()==y && iz==z) {
00825 
00826         logicId=my_CrystalEcalLogicId_EE[k];
00827 
00828         }
00829       }
00830        
00831     }
00832     
00833     coeffStruc coeff ;
00834     getCoeff(coeff, calibMap, id.rawId()) ;
00835     getCoeff(coeff, gainMap, id.rawId()) ;
00836     getCoeff(coeff, pedMap, id.rawId()) ;
00837     if (id.zside()>0) ICEEPlus->Fill(id.ix(), id.iy(), coeff.calibCoeff_) ;  
00838     else ICEEMinus->Fill(id.ix(), id.iy(), coeff.calibCoeff_) ;  
00839     IC->Fill(theEndcapGeometry_->getGeometry(id)->getPosition().phi(), theEndcapGeometry_->getGeometry(id)->getPosition().eta(), coeff.calibCoeff_) ;  
00840   
00841     std::vector<int> xtalCCU ;
00842     xtalCCU.push_back(dccNb+600) ; 
00843     xtalCCU.push_back(CCUid) ; 
00844     xtalCCU.push_back(xtalWithinCCUid) ;
00845     xtalCCU.push_back(id.rawId()) ;
00846 
00847     // compute and fill linearization parameters
00848     // case of eta slice
00849     if (forceEtaSlice_) {
00850       std::map<int, linStruc>::const_iterator itLin = linEtaSlice.find(etaSlice);
00851       if (itLin != linEtaSlice.end()) {
00852         linMap[xtalCCU] = itLin->second ;
00853         if (writeToFiles_) {
00854           for (int i=0 ; i<3 ; i++) 
00855             (*out_file_) << hex <<" 0x"<<itLin->second.pedestal_[i]<<" 0x"<<itLin->second.mult_[i]<<" 0x"<<itLin->second.shift_[i]<<std::endl;
00856         }
00857         if (writeToDB_ && DBEE_) {
00858           for (int i=0 ; i<3 ; i++) {
00859             if (i==0)  {pedDB.setPedMeanG12(itLin->second.pedestal_[i]) ; linDB.setMultX12(itLin->second.mult_[i]) ; linDB.setShift12(itLin->second.shift_[i]) ; } 
00860             if (i==1)  {pedDB.setPedMeanG6(itLin->second.pedestal_[i]) ; linDB.setMultX6(itLin->second.mult_[i]) ; linDB.setShift6(itLin->second.shift_[i]) ; } 
00861             if (i==2)  {pedDB.setPedMeanG1(itLin->second.pedestal_[i]) ; linDB.setMultX1(itLin->second.mult_[i]) ; linDB.setShift1(itLin->second.shift_[i]) ; } 
00862           }
00863         }
00864         float factor = float(itLin->second.mult_[0])*pow(2.,-itLin->second.shift_[0])/xtal_LSB_EE_ ;
00865         if (id.zside()>0) tpgFactorEEPlus->Fill(id.ix(), id.iy(), factor) ;
00866         else tpgFactorEEMinus->Fill(id.ix(), id.iy(), factor) ;
00867         tpgFactor->Fill(theEndcapGeometry_->getGeometry(id)->getPosition().phi(), 
00868                         theEndcapGeometry_->getGeometry(id)->getPosition().eta(), factor) ;
00869       }
00870       else std::cout<<"current EtaSlice = "<<etaSlice<<" not found in the EtaSlice map"<<std::endl ;      
00871     }
00872     else {
00873       // general case
00874       linStruc lin ;
00875       for (int i=0 ; i<3 ; i++) {
00876         int mult, shift ;
00877         bool ok = computeLinearizerParam(theta, coeff.gainRatio_[i], coeff.calibCoeff_, "EE", mult , shift) ;
00878         if (!ok) std::cout << "unable to compute the parameters for "<<dec<<id.rawId()<<std::endl ;  
00879         else {
00880           lin.pedestal_[i] = coeff.pedestals_[i] ;
00881           lin.mult_[i] = mult ;
00882           lin.shift_[i] = shift ;
00883         }
00884       }
00885 
00886       bool ok(true) ;
00887       if (forcedPedestalValue_ == -2 || forcedPedestalValue_ == -3) ok = realignBaseline(lin, 0) ;
00888       if (!ok) std::cout<<"Quadrant="<< id.iquadrant()<<" xt="<< id.ic()<<" " <<dec<<id.rawId()<<std::endl ; 
00889 
00890       for (int i=0 ; i<3 ; i++) {
00891         if (writeToFiles_) (*out_file_) << hex <<" 0x"<<lin.pedestal_[i]<<" 0x"<<lin.mult_[i]<<" 0x"<<lin.shift_[i]<<std::endl; 
00892         if (writeToDB_ && DBEE_) {
00893           if (i==0)  {pedDB.setPedMeanG12(lin.pedestal_[i]) ; linDB.setMultX12(lin.mult_[i]) ; linDB.setShift12(lin.shift_[i]) ; } 
00894           if (i==1)  {pedDB.setPedMeanG6(lin.pedestal_[i]) ; linDB.setMultX6(lin.mult_[i]) ; linDB.setShift6(lin.shift_[i]) ; } 
00895           if (i==2)  {pedDB.setPedMeanG1(lin.pedestal_[i]) ; linDB.setMultX1(lin.mult_[i]) ; linDB.setShift1(lin.shift_[i]) ; }
00896         }
00897         if (i==0) {
00898           float factor = float(lin.mult_[i])*pow(2.,-lin.shift_[i])/xtal_LSB_EE_ ;
00899           if (id.zside()>0) tpgFactorEEPlus->Fill(id.ix(), id.iy(), factor) ;
00900           else tpgFactorEEMinus->Fill(id.ix(), id.iy(), factor) ;           
00901           tpgFactor->Fill(theEndcapGeometry_->getGeometry(id)->getPosition().phi(), 
00902                           theEndcapGeometry_->getGeometry(id)->getPosition().eta(), factor) ;                               
00903         }
00904       }
00905       linMap[xtalCCU] = lin ;
00906     }
00907     if (writeToDB_ && DBEE_) {
00908       pedset[logicId] = pedDB ;
00909       linset[logicId] = linDB ;
00910     }
00911   } //eeCells
00912 
00913   if (writeToDB_ ) {
00914     // EcalLogicID  of the whole barrel is: my_EcalLogicId_EB
00915     FEConfigLinParamDat linparam ;
00916     linparam.setETSat(Et_sat_EE_);
00917     linparamset[my_EcalLogicId_EE] = linparam ;
00918 
00919     FEConfigLUTParamDat lutparam ;
00920     lutparam.setETSat(Et_sat_EE_);
00921     lutparam.setTTThreshlow(TTF_lowThreshold_EE_); 
00922     lutparam.setTTThreshhigh(TTF_highThreshold_EE_);
00923     lutparamset[my_EcalLogicId_EE] = lutparam ;
00924 
00925  
00926     FEConfigFgrParamDat fgrparam ;
00927     fgrparam.setFGlowthresh(FG_Threshold_EE_); 
00928     fgrparam.setFGhighthresh(FG_Threshold_EE_); 
00929     fgrparamset[my_EcalLogicId_EE] = fgrparam ;
00930 
00931   }
00932 
00933   if (writeToDB_) {
00934 
00935     ostringstream ltag;
00936     ltag.str("EB_"); ltag<<Et_sat_EB_<<"_EE_"<<Et_sat_EE_;
00937     std::string lin_tag=ltag.str();
00938     std::cout<< " LIN tag "<<lin_tag<<std::endl;
00939 
00940     if(m_write_ped==1) ped_conf_id_=db_->writeToConfDB_TPGPedestals(pedset, 1, "from_OfflineDB") ;
00941     if(m_write_lin==1) lin_conf_id_=db_->writeToConfDB_TPGLinearCoef(linset,linparamset, 1, lin_tag) ;
00942   }
00943 
00945   // Evgueni interface
00947   std::ofstream evgueni("TPG_hardcoded.hh", std::ios::out) ;  
00948   evgueni<<"void getLinParamTPG_hardcoded(int fed, int ccu, int xtal,"<<std::endl ;
00949   evgueni<<"                        int & mult12, int & shift12, int & base12,"<<std::endl ;
00950   evgueni<<"                        int & mult6, int & shift6, int & base6,"<<std::endl ;
00951   evgueni<<"                        int & mult1, int & shift1, int & base1)"<<std::endl ;
00952   evgueni<<"{"<<std::endl;
00953   evgueni<<"  mult12 = 0 ; shift12 = 0 ; base12 = 0 ; mult6 = 0 ; shift6 = 0 ; base6 = 0 ; mult1 = 0 ; shift1 = 0 ; base1 = 0 ;"<<std::endl ;
00954   std::map <std::vector<int>, linStruc>::const_iterator itLinMap ;
00955   for (itLinMap = linMap.begin() ; itLinMap != linMap.end() ; itLinMap++) {
00956     std::vector<int> xtalInCCU = itLinMap->first ;
00957     evgueni<<"  if (fed=="<<xtalInCCU[0]<<" && ccu=="<<xtalInCCU[1]<<" && xtal=="<<xtalInCCU[2]<<") {" ;
00958     evgueni<<"  mult12 = "<<itLinMap->second.mult_[0]<<" ; shift12 = "<<itLinMap->second.shift_[0]<<" ; base12 = "<<itLinMap->second.pedestal_[0]<<" ; " ;
00959     evgueni<<"  mult6 = "<<itLinMap->second.mult_[1]<<" ; shift6 = "<<itLinMap->second.shift_[1]<<" ; base6 = "<<itLinMap->second.pedestal_[1]<<" ; " ;
00960     evgueni<<"  mult1 = "<<itLinMap->second.mult_[2]<<" ; shift1 = "<<itLinMap->second.shift_[2]<<" ; base1 = "<<itLinMap->second.pedestal_[2]<<" ; " ;
00961     evgueni<<"  return ;}" <<std::endl ;
00962   }
00963   evgueni<<"}" <<std::endl ;
00964   evgueni.close() ;
00965 
00966 
00967 
00969   // Compute weights section //
00971 
00972   const int NWEIGROUPS = 2 ; 
00973   std::vector<unsigned int> weights[NWEIGROUPS] ;
00974 
00975 #if (CMSSW_VERSION>=340)
00976   EBShape shapeEB ;
00977   EEShape shapeEE ;
00978   weights[0] = computeWeights(shapeEB, hshapeEB) ;
00979   weights[1] = computeWeights(shapeEE, hshapeEE) ;
00980 #else
00981   // loading reference signal representation
00982   EcalSimParameterMap parameterMap;  
00983   EBDetId   barrel(1,1);
00984   double    phase = parameterMap.simParameters(barrel).timePhase();
00985   EcalShape shape(phase); 
00986   weights[0] = computeWeights(shape, hshapeEB) ;
00987   weights[1] = weights[0] ;
00988 #endif
00989 
00990   std::map<EcalLogicID, FEConfigWeightGroupDat> dataset;
00991 
00992   for (int igrp=0 ; igrp<NWEIGROUPS ; igrp++) {
00993 
00994     if (weights[igrp].size() == 5) {
00995 
00996       if (writeToFiles_) {
00997         (*out_file_) <<std::endl ;
00998         (*out_file_) <<"WEIGHT "<<igrp<<std::endl ;
00999         for (unsigned int sample=0 ; sample<5 ; sample++) (*out_file_) << "0x" <<hex<<weights[igrp][sample]<<" " ;
01000         (*out_file_)<<std::endl ; 
01001         (*out_file_) <<std::endl ;
01002       }
01003       if (writeToDB_) {
01004         std::cout<<"going to write the weights for groupe:"<<igrp<<std::endl;
01005         FEConfigWeightGroupDat gut;
01006         gut.setWeightGroupId(igrp);
01007         //PP WARNING: weights order is reverted when stored in the DB 
01008         gut.setWeight0(weights[igrp][4] );
01009         gut.setWeight1(weights[igrp][3]+ 0x80); //0x80 to identify the max of the pulse in the FENIX (doesn't exist in emulator)
01010         gut.setWeight2(weights[igrp][2] );
01011         gut.setWeight3(weights[igrp][1] );
01012         gut.setWeight4(weights[igrp][0] );
01013         EcalLogicID ecid = EcalLogicID( "DUMMY", igrp,igrp); //1 dummy ID per group
01014         // Fill the dataset
01015         dataset[ecid] = gut;
01016       }
01017     }
01018   }
01019 
01020   if (writeToDB_) {
01021 
01022     // now we store in the DB the correspondence btw channels and groups 
01023     std::map<EcalLogicID, FEConfigWeightDat> dataset2;
01024 
01025     // EB loop
01026     for (int ich=0; ich<(int)my_StripEcalLogicId.size() ; ich++){
01027       FEConfigWeightDat wut;
01028       int igroup = 0; // this group is for EB
01029       wut.setWeightGroupId(igroup);
01030       dataset2[my_StripEcalLogicId[ich]] = wut;
01031     }
01032         
01033     // EE loop
01034     for (int ich=0; ich<(int)my_StripEcalLogicId1_EE.size() ; ich++){
01035       FEConfigWeightDat wut;
01036       int igroup = 1; // this group is for EE
01037       wut.setWeightGroupId(igroup);
01038       // Fill the dataset
01039       dataset2[my_StripEcalLogicId1_EE[ich]] = wut;
01040     }
01041     // EE loop 2 (we had to split the ids of EE in 2 vectors to avoid crash!)
01042     for (int ich=0; ich<(int)my_StripEcalLogicId2_EE.size() ; ich++){
01043       FEConfigWeightDat wut;
01044       int igroup = 1; // this group is for EE
01045       wut.setWeightGroupId(igroup);
01046       // Fill the dataset
01047       dataset2[my_StripEcalLogicId2_EE[ich]] = wut;
01048     }
01049 
01050     // Insert the datasets
01051     ostringstream wtag;
01052     wtag.str(""); wtag<<"Shape_NGroups_"<<NWEIGROUPS;
01053     std::string weight_tag=wtag.str();
01054     std::cout<< " weight tag "<<weight_tag<<std::endl; 
01055     if (m_write_wei==1) wei_conf_id_=db_->writeToConfDB_TPGWeight(dataset, dataset2, NWEIGROUPS, weight_tag) ;
01056   }      
01057 
01058 
01060   // Compute FG section //
01062 
01063   // barrel
01064   unsigned int lowRatio, highRatio, lowThreshold, highThreshold, lutFG ;
01065   computeFineGrainEBParameters(lowRatio, highRatio, lowThreshold, highThreshold, lutFG) ;
01066   if (writeToFiles_) {
01067     (*out_file_) <<std::endl ;
01068     (*out_file_) <<"FG 0"<<std::endl ;
01069     (*out_file_)<<hex<<"0x"<<lowThreshold<<" 0x"<<highThreshold
01070                   <<" 0x"<<lowRatio<<" 0x"<<highRatio<<" 0x"<<lutFG
01071                   <<std::endl ;
01072   }
01073 
01074   // endcap
01075   unsigned int threshold, lut_tower ;
01076   unsigned int lut_strip;
01077   computeFineGrainEEParameters(threshold, lut_strip, lut_tower) ; 
01078 
01079   // and here we store the fgr part
01080 
01081   
01082   if (writeToDB_) {
01083     std::cout<<"going to write the fgr "<< std::endl;
01084       std::map<EcalLogicID, FEConfigFgrGroupDat> dataset;
01085       // we create 1 group
01086       int NFGRGROUPS =1; 
01087       for (int ich=0; ich<NFGRGROUPS; ich++){
01088         FEConfigFgrGroupDat gut;
01089         gut.setFgrGroupId(ich);
01090         gut.setThreshLow(lowRatio );
01091         gut.setThreshHigh(highRatio);
01092         gut.setRatioLow(lowThreshold);
01093         gut.setRatioHigh(highThreshold);
01094         gut.setLUTValue(lutFG);
01095         EcalLogicID ecid = EcalLogicID( "DUMMY", ich,ich);
01096         // Fill the dataset
01097         dataset[ecid] = gut; // we use any logic id but different, because it is in any case ignored... 
01098       }
01099       
01100       // now we store in the DB the correspondence btw channels and groups 
01101       std::map<EcalLogicID, FEConfigFgrDat> dataset2;
01102       // in this case I decide in a stupid way which channel belongs to which group 
01103       for (int ich=0; ich<(int)my_TTEcalLogicId.size() ; ich++){
01104         FEConfigFgrDat wut;
01105         int igroup=0;
01106         wut.setFgrGroupId(igroup);
01107         // Fill the dataset
01108         // the logic ids are ordered by SM (1,...36) and TT (1,...68)  
01109         // you have to calculate the right index here 
01110         dataset2[my_TTEcalLogicId[ich]] = wut;
01111       }
01112 
01113       // endcap loop
01114       for (int ich=0; ich<(int)my_RTEcalLogicId_EE.size() ; ich++){
01115         //      std::cout << " endcap FGR " << std::endl;
01116         FEConfigFgrDat wut;
01117         int igroup=0;
01118         wut.setFgrGroupId(igroup);
01119         // Fill the dataset
01120         // the logic ids are ordered by .... ?  
01121         // you have to calculate the right index here 
01122         dataset2[my_RTEcalLogicId_EE[ich]] = wut;
01123       }
01124 
01125       // endcap TT loop for the FEfgr EE Tower
01126       std::map<EcalLogicID, FEConfigFgrEETowerDat> dataset3;
01127       for (int ich=0; ich<(int)my_TTEcalLogicId_EE.size() ; ich++){
01128         FEConfigFgrEETowerDat fgreett;
01129         fgreett.setLutValue(lut_tower);
01130         dataset3[my_TTEcalLogicId_EE[ich]]=fgreett;
01131       }
01132 
01133       // endcap strip loop for the FEfgr EE strip
01134       // and barrel strip loop for the spike parameters (same structure than EE FGr)
01135       std::map<EcalLogicID, FEConfigFgrEEStripDat> dataset4;
01136       for (int ich=0; ich<(int)my_StripEcalLogicId1_EE.size() ; ich++){
01137         FEConfigFgrEEStripDat zut;
01138         zut.setThreshold(threshold);
01139         zut.setLutFgr(lut_strip);
01140         dataset4[my_StripEcalLogicId1_EE[ich]] = zut;
01141       }
01142       for (int ich=0; ich<(int)my_StripEcalLogicId2_EE.size() ; ich++){
01143         FEConfigFgrEEStripDat zut;
01144         zut.setThreshold(threshold);
01145         zut.setLutFgr(lut_strip);
01146         // Fill the dataset
01147         dataset4[my_StripEcalLogicId2_EE[ich]] = zut;
01148       }
01149       for (int ich=0; ich<(int)my_StripEcalLogicId.size() ; ich++){
01150         // EB
01151         FEConfigFgrEEStripDat zut;
01152         EcalLogicID thestrip = my_StripEcalLogicId[ich] ;
01153         uint32_t elStripId = stripMapEB[ich] ;
01154         map<uint32_t, uint32_t>::const_iterator it = stripMapEBsintheta.find(elStripId) ;
01155         if (it != stripMapEBsintheta.end()) zut.setThreshold(it->second);
01156         else {
01157           std::cout<<"ERROR: strip SFGVB threshold parameter not found for that strip:"<<thestrip.getID1()<<" "<<thestrip.getID3()<<" "<<thestrip.getID3()<<std::endl ; 
01158           std::cout<<" using value = "<<SFGVB_Threshold_+pedestal_offset_<<std::endl ;
01159           zut.setThreshold(SFGVB_Threshold_+pedestal_offset_) ;
01160         }
01161         zut.setLutFgr(SFGVB_lut_);
01162         // Fill the dataset
01163         dataset4[thestrip] = zut;
01164       }
01165 
01166       // Insert the dataset
01167       ostringstream wtag;
01168       wtag.str(""); wtag<<"FGR_"<<lutFG<<"_N_"<<NFGRGROUPS<<"_eb_"<<FG_lowThreshold_EB_<<"_EB_"<<FG_highThreshold_EB_;
01169       std::string weight_tag=wtag.str();
01170       std::cout<< " weight tag "<<weight_tag<<std::endl; 
01171       if(m_write_fgr==1) fgr_conf_id_=db_->writeToConfDB_TPGFgr(dataset, dataset2,  fgrparamset,dataset3, dataset4, NFGRGROUPS, weight_tag) ;
01172   }
01173 
01174   if (writeToDB_) {
01175     std::cout<<"going to write the sliding "<< std::endl;
01176       std::map<EcalLogicID, FEConfigSlidingDat> dataset;
01177       // in this case I decide in a stupid way which channel belongs to which group 
01178       for (int ich=0; ich<(int)my_StripEcalLogicId.size() ; ich++){
01179         FEConfigSlidingDat wut;
01180         wut.setSliding(sliding_);
01181         // Fill the dataset
01182         // the logic ids are ordered by SM (1,...36) , TT (1,...68) and strip (1..5) 
01183         // you have to calculate the right index here 
01184         dataset[my_StripEcalLogicId[ich]] = wut;
01185       }
01186 
01187       // endcap loop
01188       for (int ich=0; ich<(int)my_StripEcalLogicId1_EE.size() ; ich++){
01189         FEConfigSlidingDat wut;
01190         wut.setSliding(sliding_);
01191         // Fill the dataset
01192         // the logic ids are ordered by fed tower strip
01193         // you have to calculate the right index here 
01194         dataset[my_StripEcalLogicId1_EE[ich]] = wut;
01195       }
01196       for (int ich=0; ich<(int)my_StripEcalLogicId2_EE.size() ; ich++){
01197         FEConfigSlidingDat wut;
01198         wut.setSliding(sliding_);
01199         // Fill the dataset
01200         // the logic ids are ordered by ... ? 
01201         // you have to calculate the right index here 
01202         dataset[my_StripEcalLogicId2_EE[ich]] = wut;
01203       }
01204       
01205 
01206       // Insert the dataset
01207       ostringstream wtag;
01208       wtag.str(""); wtag<<"Sliding_"<<sliding_;
01209       std::string justatag=wtag.str();
01210       std::cout<< " sliding tag "<<justatag<<std::endl;
01211       int iov_id=0; // just a parameter ... 
01212       if(m_write_sli==1) sli_conf_id_=db_->writeToConfDB_TPGSliding(dataset,iov_id, justatag) ;
01213   }
01214 
01215   
01216 
01217 
01218 
01220   // Compute LUT section //
01222 
01223   int lut_EB[1024], lut_EE[1024] ;
01224 
01225   // barrel
01226   computeLUT(lut_EB, "EB") ; 
01227   if (writeToFiles_) {
01228     (*out_file_) <<std::endl ;
01229     (*out_file_) <<"LUT 0"<<std::endl ;
01230     for (int i=0 ; i<1024 ; i++) (*out_file_)<<"0x"<<hex<<lut_EB[i]<<std::endl ;
01231     (*out_file_)<<std::endl ;
01232   }
01233   
01234   // endcap
01235   computeLUT(lut_EE, "EE") ;
01236   // check first if lut_EB and lut_EE are the same
01237   bool newLUT(false) ;
01238   for (int i=0 ; i<1024 ; i++) if (lut_EE[i] != lut_EB[i]) newLUT = true ;
01239   if (newLUT && writeToFiles_) { 
01240     (*out_file_) <<std::endl ;
01241     (*out_file_) <<"LUT 1"<<std::endl ;
01242     for (int i=0 ; i<1024 ; i++) (*out_file_)<<"0x"<<hex<<lut_EE[i]<<std::endl ;
01243     (*out_file_)<<std::endl ;
01244   }
01245 
01246 
01247 
01248   if (writeToDB_) {
01249 
01250 
01251 
01252     std::map<EcalLogicID, FEConfigLUTGroupDat> dataset;
01253     // we create 1 LUT group
01254     int NLUTGROUPS =0; 
01255     int ich=0;
01256       FEConfigLUTGroupDat lut;
01257       lut.setLUTGroupId(ich);
01258       for (int i=0; i<1024; i++){
01259         lut.setLUTValue(i, lut_EB[i] );
01260       }
01261       EcalLogicID ecid = EcalLogicID( "DUMMY", ich,ich);
01262       // Fill the dataset
01263       dataset[ecid] = lut; // we use any logic id but different, because it is in any case ignored... 
01264       
01265       ich++;
01266       
01267       FEConfigLUTGroupDat lute;
01268       lute.setLUTGroupId(ich);
01269       for (int i=0; i<1024; i++){
01270         lute.setLUTValue(i, lut_EE[i] );
01271       }
01272       EcalLogicID ecide = EcalLogicID( "DUMMY", ich,ich);
01273       // Fill the dataset
01274       dataset[ecide] = lute; // we use any logic id but different, because it is in any case ignored...
01275 
01276       ich++;
01277 
01278       NLUTGROUPS=ich;
01279 
01280     // now we store in the DB the correspondence btw channels and LUT groups 
01281     std::map<EcalLogicID, FEConfigLUTDat> dataset2;
01282     // in this case I decide in a stupid way which channel belongs to which group 
01283     for (int ich=0; ich<(int)my_TTEcalLogicId.size() ; ich++){
01284       FEConfigLUTDat lut;
01285       int igroup=0;
01286       lut.setLUTGroupId(igroup);
01287       // calculate the right TT - in the vector they are ordered by SM and by TT 
01288       // Fill the dataset
01289       dataset2[my_TTEcalLogicId[ich]] = lut;
01290     }
01291 
01292     // endcap loop 
01293     for (int ich=0; ich<(int)my_TTEcalLogicId_EE.size() ; ich++){
01294       FEConfigLUTDat lut;
01295       int igroup=1;
01296       lut.setLUTGroupId(igroup);
01297       // calculate the right TT  
01298       // Fill the dataset
01299       dataset2[my_TTEcalLogicId_EE[ich]] = lut;
01300     }    
01301 
01302     // Insert the dataset
01303     ostringstream ltag;
01304     ltag.str(""); ltag<<LUT_option_<<"_NGroups_"<<NLUTGROUPS;
01305     std::string lut_tag=ltag.str();
01306     std::cout<< " LUT tag "<<lut_tag<<std::endl; 
01307     if(m_write_lut==1) lut_conf_id_=db_->writeToConfDB_TPGLUT(dataset, dataset2,lutparamset, NLUTGROUPS, lut_tag) ;
01308 
01309   }
01310 
01311   // last we insert the FE_CONFIG_MAIN table 
01312  if (writeToDB_) {
01313    
01314    int conf_id_=db_->writeToConfDB_TPGMain(ped_conf_id_,lin_conf_id_, lut_conf_id_, fgr_conf_id_, 
01315                                         sli_conf_id_, wei_conf_id_, bxt_conf_id_, btt_conf_id_, tag_, version_) ;
01316    
01317    std::cout << "\n Conf ID = " << conf_id_ << std::endl;
01318 
01319  }
01320 
01321 
01323   // loop on strips and associate them with  values //
01325 
01326   // Barrel
01327   stripListEB.sort() ;
01328   stripListEB.unique() ;
01329   std::cout<<"Number of EB strips="<<dec<<stripListEB.size()<<std::endl ;
01330   if (writeToFiles_) {
01331     (*out_file_) <<std::endl ;
01332     for (itList = stripListEB.begin(); itList != stripListEB.end(); itList++ ) {
01333       (*out_file_) <<"STRIP_EB "<<dec<<(*itList)<<std::endl ;
01334       (*out_file_) << hex << "0x" <<sliding_<<std::endl ;
01335       (*out_file_) <<"0" <<std::endl ;
01336       (*out_file_) <<"0x"<<stripMapEBsintheta[(*itList)] << " 0x" << SFGVB_lut_ <<std::endl ;
01337     }
01338   }
01339 
01340   // Endcap
01341   stripListEE.sort() ;
01342   stripListEE.unique() ;
01343   std::cout<<"Number of EE strips="<<dec<<stripListEE.size()<<std::endl ;
01344   if (writeToFiles_) {
01345     (*out_file_) <<std::endl ;
01346     for (itList = stripListEE.begin(); itList != stripListEE.end(); itList++ ) {
01347       (*out_file_) <<"STRIP_EE "<<dec<<(*itList)<<std::endl ;
01348       (*out_file_) << hex << "0x" <<sliding_<<std::endl ;
01349       (*out_file_) <<" 0" << std::endl ;
01350       (*out_file_)<<hex<<"0x"<<threshold<<" 0x"<<lut_strip<<std::endl ;  
01351     }
01352   }
01353 
01354 
01356   // loop on towers and associate them with default values //
01358 
01359   // Barrel
01360   towerListEB.sort() ;
01361   towerListEB.unique() ;
01362   std::cout<<"Number of EB towers="<<dec<<towerListEB.size()<<std::endl ;
01363   if (writeToFiles_) {
01364     (*out_file_) <<std::endl ;
01365     for (itList = towerListEB.begin(); itList != towerListEB.end(); itList++ ) {
01366       (*out_file_) <<"TOWER_EB "<<dec<<(*itList)<<std::endl ;
01367       (*out_file_) <<" 0\n 0\n" ;
01368     }
01369   }
01370 
01371   // Endcap
01372   towerListEE.sort() ;
01373   towerListEE.unique() ;
01374   std::cout<<"Number of EE towers="<<dec<<towerListEE.size()<<std::endl ;
01375   if (writeToFiles_) {
01376     (*out_file_) <<std::endl ;
01377     for (itList = towerListEE.begin(); itList != towerListEE.end(); itList++ ) {
01378       (*out_file_) <<"TOWER_EE "<<dec<<(*itList)<<std::endl ;
01379       if (newLUT) (*out_file_) <<" 1\n" ;
01380       else  (*out_file_) <<" 0\n" ;
01381       (*out_file_)<<hex<<"0x"<<lut_tower<<std::endl ;
01382     }
01383   }
01384 
01385 
01386 
01387 
01389   // store control histos //
01391   ICEB->Write() ;
01392   tpgFactorEB->Write() ;
01393   ICEEPlus->Write() ;
01394   tpgFactorEEPlus->Write() ;  
01395   ICEEMinus->Write() ;
01396   tpgFactorEEMinus->Write() ;
01397   IC->Write() ;
01398   tpgFactor->Write() ;
01399   hshapeEB->Write() ;
01400   hshapeEE->Write() ;
01401   ntuple->Write() ;
01402   ntupleSpike->Write() ;
01403   saving.Close () ;
01404 }
01405 
01406 void EcalTPGParamBuilder::beginJob()
01407 {
01408   using namespace edm;
01409   using namespace std;
01410 
01411   std::cout<<"we are in beginJob"<<std::endl;
01412 
01413   create_header() ; 
01414 
01415   DetId eb(DetId::Ecal,EcalBarrel) ;
01416   DetId ee(DetId::Ecal,EcalEndcap) ;
01417 
01418   if (writeToFiles_) {
01419     (*out_file_)<<"PHYSICS_EB "<<dec<<eb.rawId()<<std::endl ;
01420     (*out_file_)<<Et_sat_EB_<<" "<<TTF_lowThreshold_EB_<<" "<<TTF_highThreshold_EB_<<std::endl ;
01421     (*out_file_)<<FG_lowThreshold_EB_<<" "<<FG_highThreshold_EB_<<" "
01422                   <<FG_lowRatio_EB_<<" "<<FG_highRatio_EB_<<std::endl ;
01423     (*out_file_) <<std::endl ;
01424 
01425     (*out_file_)<<"PHYSICS_EE "<<dec<<ee.rawId()<<std::endl ;
01426     (*out_file_)<<Et_sat_EE_<<" "<<TTF_lowThreshold_EE_<<" "<<TTF_highThreshold_EE_<<std::endl ;
01427     (*out_file_)<<FG_Threshold_EE_<<" "<<-1<<" "
01428                   <<-1<<" "<<-1<<std::endl ;
01429     (*out_file_) <<std::endl ;
01430   }
01431 
01432 }
01433 
01434 
01435 
01436 bool EcalTPGParamBuilder::computeLinearizerParam(double theta, double gainRatio, double calibCoeff, std::string subdet, int & mult , int & shift) 
01437 {
01438   /*
01439     Linearization coefficient are determined in order to satisfy:
01440     tpg(ADC_sat) = 1024
01441     where: 
01442     tpg() is a model of the linearized tpg response on 10b 
01443     ADC_sat is the number of ADC count corresponding the Et_sat, the maximum scale of the transverse energy
01444     
01445     Since we have:
01446     Et_sat = xtal_LSB * ADC_sat * gainRatio * calibCoeff * sin(theta)
01447     and a simple model of tpg() being given by:
01448     tpg(X) = [ (X*mult) >> (shift+2) ] >> (sliding+shiftDet) 
01449     we must satisfy:
01450     [ (Et_sat/(xtal_LSB * gainRatio * calibCoeff * sin(theta)) * mult) >> (shift+2) ] >> (sliding+shiftDet) = 1024 
01451     that is:
01452     mult = 1024/Et_sat * xtal_LSB * gainRatio * calibCoeff * sin(theta) * 2^-(sliding+shiftDet+2) * 2^-shift
01453     mult = factor * 2^-shift
01454   */
01455 
01456   // case barrel:
01457   int shiftDet = 2 ; //fixed, due to FE FENIX TCP format
01458   double ratio = xtal_LSB_EB_/Et_sat_EB_ ;
01459   // case endcap:
01460   if (subdet=="EE") {
01461     shiftDet = 2 ; //applied in TCC-EE and not in FE FENIX TCP... This parameters is setable in the TCC-EE
01462     //shiftDet = 0 ; //was like this before with FE bug
01463     ratio = xtal_LSB_EE_/Et_sat_EE_ ;
01464   }
01465 
01466 
01467 
01468   double factor = 1024 * ratio * gainRatio * calibCoeff * sin(theta) * (1 << (sliding_ + shiftDet + 2)) ;
01469   // Let's try first with shift = 0 (trivial solution)
01470   mult = (int)(factor+0.5) ; 
01471   for (shift = 0 ; shift<15 ; shift++) {
01472     if (mult>=128  && mult<256) return true ;
01473     factor *= 2 ; 
01474     mult = (int)(factor+0.5) ;
01475   }
01476   std::cout << "too bad we did not manage to calculate the factor for calib="<<calibCoeff<<std::endl;
01477   return false ;
01478 }
01479 
01480 void EcalTPGParamBuilder::create_header() 
01481 {
01482   if (!writeToFiles_) return ;
01483   (*out_file_) <<"COMMENT put your comments here"<<std::endl ; 
01484 
01485   (*out_file_) <<"COMMENT ================================="<<std::endl ;
01486   (*out_file_) <<"COMMENT           physics EB structure"<<std::endl ;
01487   (*out_file_) <<"COMMENT"<<std::endl ;
01488   (*out_file_) <<"COMMENT  EtSaturation (GeV), ttf_threshold_Low (GeV), ttf_threshold_High (GeV)"<<std::endl ;
01489   (*out_file_) <<"COMMENT  FG_lowThreshold (GeV), FG_highThreshold (GeV), FG_lowRatio, FG_highRatio"<<std::endl ;
01490   (*out_file_) <<"COMMENT ================================="<<std::endl ;
01491   (*out_file_) <<"COMMENT"<<std::endl ;
01492 
01493   (*out_file_) <<"COMMENT ================================="<<std::endl ;
01494   (*out_file_) <<"COMMENT           physics EE structure"<<std::endl ;
01495   (*out_file_) <<"COMMENT"<<std::endl ;
01496   (*out_file_) <<"COMMENT  EtSaturation (GeV), ttf_threshold_Low (GeV), ttf_threshold_High (GeV)"<<std::endl ;
01497   (*out_file_) <<"COMMENT  FG_Threshold (GeV), dummy, dummy, dummy"<<std::endl ;
01498   (*out_file_) <<"COMMENT ================================="<<std::endl ;
01499   (*out_file_) <<"COMMENT"<<std::endl ;
01500 
01501   (*out_file_) <<"COMMENT ================================="<<std::endl ;
01502   (*out_file_) <<"COMMENT           crystal structure (same for EB and EE)"<<std::endl ;
01503   (*out_file_) <<"COMMENT"<<std::endl ;
01504   (*out_file_) <<"COMMENT  ped, mult, shift [gain12]"<<std::endl ;
01505   (*out_file_) <<"COMMENT  ped, mult, shift [gain6]"<<std::endl ;
01506   (*out_file_) <<"COMMENT  ped, mult, shift [gain1]"<<std::endl ;
01507   (*out_file_) <<"COMMENT ================================="<<std::endl ;
01508   (*out_file_) <<"COMMENT"<<std::endl ;
01509 
01510   (*out_file_) <<"COMMENT ================================="<<std::endl ;
01511   (*out_file_) <<"COMMENT           strip EB structure"<<std::endl ;
01512   (*out_file_) <<"COMMENT"<<std::endl ;
01513   (*out_file_) <<"COMMENT  sliding_window"<<std::endl ;
01514   (*out_file_) <<"COMMENT  weightGroupId"<<std::endl ;
01515   (*out_file_) <<"COMMENT  threshold_sfg lut_sfg"<<std::endl ;
01516   (*out_file_) <<"COMMENT ================================="<<std::endl ;
01517   (*out_file_) <<"COMMENT"<<std::endl ;
01518 
01519   (*out_file_) <<"COMMENT ================================="<<std::endl ;
01520   (*out_file_) <<"COMMENT           strip EE structure"<<std::endl ;
01521   (*out_file_) <<"COMMENT"<<std::endl ;
01522   (*out_file_) <<"COMMENT  sliding_window"<<std::endl ;
01523   (*out_file_) <<"COMMENT  weightGroupId"<<std::endl ;
01524   (*out_file_) <<"COMMENT  threshold_fg lut_fg"<<std::endl ;
01525   (*out_file_) <<"COMMENT ================================="<<std::endl ;
01526   (*out_file_) <<"COMMENT"<<std::endl ;
01527 
01528   (*out_file_) <<"COMMENT ================================="<<std::endl ;
01529   (*out_file_) <<"COMMENT           tower EB structure"<<std::endl ;
01530   (*out_file_) <<"COMMENT"<<std::endl ;
01531   (*out_file_) <<"COMMENT  LUTGroupId"<<std::endl ;
01532   (*out_file_) <<"COMMENT  FgGroupId"<<std::endl ;
01533   (*out_file_) <<"COMMENT ================================="<<std::endl ;
01534   (*out_file_) <<"COMMENT"<<std::endl ;
01535 
01536   (*out_file_) <<"COMMENT ================================="<<std::endl ;
01537   (*out_file_) <<"COMMENT           tower EE structure"<<std::endl ;
01538   (*out_file_) <<"COMMENT"<<std::endl ;
01539   (*out_file_) <<"COMMENT  LUTGroupId"<<std::endl ;
01540   (*out_file_) <<"COMMENT  tower_lut_fg"<<std::endl ;
01541   (*out_file_) <<"COMMENT ================================="<<std::endl ;
01542   (*out_file_) <<"COMMENT"<<std::endl ;
01543   
01544   (*out_file_) <<"COMMENT ================================="<<std::endl ;
01545   (*out_file_) <<"COMMENT           Weight structure"<<std::endl ;
01546   (*out_file_) <<"COMMENT"<<std::endl ;
01547   (*out_file_) <<"COMMENT  weightGroupId"<<std::endl ;
01548   (*out_file_) <<"COMMENT  w0, w1, w2, w3, w4"<<std::endl ;
01549   (*out_file_) <<"COMMENT ================================="<<std::endl ;
01550   (*out_file_) <<"COMMENT"<<std::endl ;
01551 
01552   (*out_file_) <<"COMMENT ================================="<<std::endl ;
01553   (*out_file_) <<"COMMENT           lut structure"<<std::endl ;
01554   (*out_file_) <<"COMMENT"<<std::endl ;
01555   (*out_file_) <<"COMMENT  LUTGroupId"<<std::endl ;
01556   (*out_file_) <<"COMMENT  LUT[1-1024]"<<std::endl ;
01557   (*out_file_) <<"COMMENT ================================="<<std::endl ;
01558   (*out_file_) <<"COMMENT"<<std::endl ;
01559 
01560   (*out_file_) <<"COMMENT ================================="<<std::endl ;
01561   (*out_file_) <<"COMMENT           fg EB structure"<<std::endl ;
01562   (*out_file_) <<"COMMENT"<<std::endl ;
01563   (*out_file_) <<"COMMENT  FgGroupId"<<std::endl ;
01564   (*out_file_) <<"COMMENT  el, eh, tl, th, lut_fg"<<std::endl ;
01565   (*out_file_) <<"COMMENT ================================="<<std::endl ;
01566   (*out_file_) <<"COMMENT"<<std::endl ;
01567 
01568   (*out_file_) <<std::endl ;
01569 }
01570 
01571 
01572 int EcalTPGParamBuilder::uncodeWeight(double weight, int complement2)
01573 {
01574   int iweight ;
01575   unsigned int max = (unsigned int)(pow(2.,complement2)-1) ;
01576   if (weight>0) iweight=int((1<<6)*weight+0.5) ; // +0.5 for rounding pb
01577   else iweight= max - int(-weight*(1<<6)+0.5) +1 ;
01578   iweight = iweight & max ;
01579   return iweight ;
01580 }
01581 
01582 double EcalTPGParamBuilder::uncodeWeight(int iweight, int complement2)
01583 {
01584   double weight = double(iweight)/pow(2., 6.) ;
01585   // test if negative weight:
01586   if ( (iweight & (1<<(complement2-1))) != 0) weight = (double(iweight)-pow(2., complement2))/pow(2., 6.) ;
01587   return weight ;
01588 }
01589 
01590 #if (CMSSW_VERSION>=340)
01591 std::vector<unsigned int> EcalTPGParamBuilder::computeWeights(EcalShapeBase & shape, TH1F * histo)
01592 #else
01593 std::vector<unsigned int> EcalTPGParamBuilder::computeWeights(EcalShape & shape, TH1F * histo)
01594 #endif
01595 {
01596   std::cout<<"Computing Weights..."<<std::endl ;
01597 #if (CMSSW_VERSION>=340)
01598   double timeMax = shape.timeOfMax() - shape.timeOfThr() ; // timeMax w.r.t begining of pulse
01599 #else
01600   double timeMax = shape.computeTimeOfMaximum() - shape.computeT0() ; // timeMax w.r.t begining of pulse
01601 #endif
01602   double max = shape(timeMax) ;
01603 
01604   double sumf = 0. ;
01605   double sumf2 = 0. ;
01606   for (unsigned int sample = 0 ; sample<nSample_ ; sample++) {
01607     double time = timeMax - ((double)sampleMax_-(double)sample)*25. ;
01608     time -= weight_timeShift_ ;
01609     sumf += shape(time)/max ;
01610     sumf2 += shape(time)/max * shape(time)/max ;
01611     for (int subtime = 0 ; subtime<25 ; subtime++) histo->Fill(float(sample*25. + subtime)/25., shape(time+subtime)) ;
01612   }
01613   double lambda = 1./(sumf2-sumf*sumf/nSample_) ;
01614   double gamma = -lambda*sumf/nSample_ ;
01615   double * weight = new double[nSample_] ;
01616   for (unsigned int sample = 0 ; sample<nSample_ ; sample++) {
01617     double time = timeMax - ((double)sampleMax_-(double)sample)*25. ;
01618     time -= weight_timeShift_ ;
01619     weight[sample] = lambda*shape(time)/max + gamma ;
01620   }
01621 
01622 
01623   int * iweight = new int[nSample_] ;
01624   for (unsigned int sample = 0 ; sample<nSample_ ; sample++)   iweight[sample] = uncodeWeight(weight[sample], complement2_) ;
01625 
01626   // Let's check:  
01627   int isumw  = 0 ;  
01628   for (unsigned int sample = 0 ; sample<nSample_ ; sample++) isumw  += iweight[sample] ;
01629   unsigned int imax = (unsigned int)(pow(2.,int(complement2_))-1) ;
01630   isumw = (isumw & imax ) ;
01631 
01632   double ampl = 0. ;
01633   double sumw = 0. ;
01634   for (unsigned int sample = 0 ; sample<nSample_ ; sample++) {
01635      double time = timeMax - ((double)sampleMax_-(double)sample)*25. ;
01636      time -= weight_timeShift_ ;
01637      ampl += weight[sample]*shape(time) ;
01638      sumw += weight[sample] ;
01639      std::cout<<"weight="<<weight[sample]<<" shape="<<shape(time)<<std::endl ;
01640   }
01641   std::cout<<"Weights: sum="<<isumw<<" in float ="<<uncodeWeight(isumw, complement2_)<<" sum of floats ="<<sumw<<std::endl ;
01642   std::cout<<"Weights: sum (weight*shape) = "<<ampl<<std::endl ;
01643 
01644 
01645 
01646   // Let's correct for bias if any
01647   if (weight_unbias_recovery_) {
01648     int count = 0 ;
01649     while (isumw != 0 && count<10) {
01650       double min = 99. ;
01651       unsigned int index = 0 ;
01652       if ( (isumw & (1<<(complement2_-1))) != 0) {
01653         // add 1:
01654         std::cout<<"Correcting for bias: adding 1"<<std::endl ;
01655         for (unsigned int sample = 0 ; sample<nSample_ ; sample++) {
01656           int new_iweight = iweight[sample]+1 ; 
01657           double new_weight = uncodeWeight(new_iweight, complement2_) ;
01658           if (fabs(new_weight-weight[sample])<min) {
01659             min = fabs(new_weight-weight[sample]) ;
01660             index = sample ;
01661           }
01662         }
01663         iweight[index] ++ ; 
01664       } else {
01665         // Sub 1:
01666         std::cout<<"Correcting for bias: subtracting 1"<<std::endl ;
01667         for (unsigned int sample = 0 ; sample<nSample_ ; sample++) {
01668           int new_iweight = iweight[sample]-1 ;    
01669           double new_weight = uncodeWeight(new_iweight, complement2_) ;
01670           if (fabs(new_weight-weight[sample])<min) {
01671             min = fabs(new_weight-weight[sample]) ;
01672             index = sample ;
01673           }
01674         }
01675         iweight[index] -- ; 
01676       } 
01677       isumw  = 0 ;  
01678       for (unsigned int sample = 0 ; sample<nSample_ ; sample++) isumw  += iweight[sample] ; 
01679       imax = (unsigned int)(pow(2.,int(complement2_))-1) ;
01680       isumw = (isumw & imax ) ;
01681       std::cout<<"Correcting weight number: "<<index<<" sum weights = "<<isumw<<std::endl ;
01682       count ++ ;
01683     }
01684   }
01685   
01686   // let's check again
01687   isumw  = 0 ;  
01688   for (unsigned int sample = 0 ; sample<nSample_ ; sample++) isumw  += iweight[sample] ;
01689   imax = (unsigned int)(pow(2.,int(complement2_))-1) ;
01690   isumw = (isumw & imax ) ;
01691   ampl = 0. ;
01692   for (unsigned int sample = 0 ; sample<nSample_ ; sample++) {
01693      double time = timeMax - ((double)sampleMax_-(double)sample)*25. ;
01694      time -= weight_timeShift_ ;
01695      double new_weight = uncodeWeight(iweight[sample], complement2_) ;
01696      sumw += uncodeWeight(iweight[sample], complement2_) ;
01697      ampl += new_weight*shape(time) ;
01698      std::cout<<"weight unbiased after integer conversion="<<new_weight<<" shape="<<shape(time)<<std::endl ;
01699   }
01700   std::cout<<"Weights: sum="<<isumw<<" in float ="<<uncodeWeight(isumw, complement2_)<<" sum of floats ="<<sumw<<std::endl ;
01701   std::cout<<"Weights: sum (weight*shape) = "<<ampl<<std::endl ;
01702 
01703 
01704 
01705   std::vector<unsigned int> theWeights ;
01706   for (unsigned int sample = 0 ; sample<nSample_ ; sample++) theWeights.push_back(iweight[sample]) ;
01707   std::cout<<std::endl ;
01708 
01709   delete weight ;
01710   delete iweight ;
01711   return theWeights ;
01712 }
01713 
01714 void EcalTPGParamBuilder::computeLUT(int * lut, std::string det) 
01715 {
01716   double Et_sat = Et_sat_EB_ ;
01717   double LUT_threshold = LUT_threshold_EB_ ;
01718   double LUT_stochastic = LUT_stochastic_EB_ ;
01719   double LUT_noise = LUT_noise_EB_ ;
01720   double LUT_constant = LUT_constant_EB_ ;
01721   double TTF_lowThreshold = TTF_lowThreshold_EB_ ;
01722   double TTF_highThreshold = TTF_highThreshold_EB_ ;
01723   if (det == "EE") {
01724     Et_sat = Et_sat_EE_ ;
01725     LUT_threshold = LUT_threshold_EE_ ;
01726     LUT_stochastic = LUT_stochastic_EE_ ;
01727     LUT_noise = LUT_noise_EE_ ;
01728     LUT_constant = LUT_constant_EE_ ;
01729     TTF_lowThreshold = TTF_lowThreshold_EE_ ;
01730     TTF_highThreshold = TTF_highThreshold_EE_ ;
01731   }
01732 
01733   // initialisation with identity
01734   for (int i=0 ; i<1024 ; i++) {
01735     lut[i] = i ;
01736     if (lut[i]>0xff) lut[i] = 0xff ;
01737   }
01738 
01739   // case linear LUT
01740   if (LUT_option_ == "Linear") {
01741     int mylut = 0 ;
01742     for (int i=0 ; i<1024 ; i++) {
01743       lut[i] = mylut ;
01744       if ((i+1)%4 == 0 ) mylut++ ;
01745     }
01746   }
01747 
01748   // case LUT following Ecal resolution
01749   if (LUT_option_ == "EcalResolution") {
01750     TF1 * func = new TF1("func",oneOverEtResolEt, 0., Et_sat,3) ;
01751     func->SetParameters(LUT_stochastic, LUT_noise, LUT_constant) ;
01752     double norm = func->Integral(0., Et_sat) ;
01753     for (int i=0 ; i<1024 ; i++) {   
01754       double Et = i*Et_sat/1024. ;
01755       lut[i] =  int(0xff*func->Integral(0., Et)/norm + 0.5) ;
01756     }
01757   }
01758 
01759   // Now, add TTF thresholds to LUT and apply LUT threshold if needed
01760   for (int j=0 ; j<1024 ; j++) {
01761     double Et_GeV = Et_sat/1024*(j+0.5) ;
01762     if (Et_GeV <= LUT_threshold) lut[j] = 0 ; // LUT threshold
01763     int ttf = 0x0 ;    
01764     if (Et_GeV >= TTF_highThreshold) ttf = 3 ;
01765     if (Et_GeV >= TTF_lowThreshold && Et_GeV < TTF_highThreshold) ttf = 1 ;
01766     ttf = ttf << 8 ;
01767     lut[j] += ttf ;
01768   }
01769 
01770 }
01771 
01772 void EcalTPGParamBuilder::getCoeff(coeffStruc & coeff, const EcalIntercalibConstantMap & calibMap, unsigned int rawId)
01773 {
01774   // get current intercalibration coeff
01775   coeff.calibCoeff_ = 1. ;
01776   if (!useInterCalibration_) return ;
01777   EcalIntercalibConstantMap::const_iterator icalit = calibMap.find(rawId);
01778   if( icalit != calibMap.end() ) coeff.calibCoeff_ = (*icalit) ;
01779   else std::cout<<"getCoeff: "<<rawId<<" not found in EcalIntercalibConstantMap"<<std::endl ;
01780 }
01781 
01782 void EcalTPGParamBuilder::getCoeff(coeffStruc & coeff, const EcalGainRatioMap & gainMap, unsigned int rawId)
01783 {
01784   // get current gain ratio
01785   coeff.gainRatio_[0]  = 1. ;
01786   coeff.gainRatio_[1]  = 2. ;
01787   coeff.gainRatio_[2]  = 12. ;
01788   EcalGainRatioMap::const_iterator gainIter = gainMap.find(rawId);
01789   if (gainIter != gainMap.end()) {
01790     const EcalMGPAGainRatio & aGain = (*gainIter) ;
01791     coeff.gainRatio_[1] = aGain.gain12Over6() ;
01792     coeff.gainRatio_[2] = aGain.gain6Over1() * aGain.gain12Over6() ;
01793   }
01794   else std::cout<<"getCoeff: "<<rawId<<" not found in EcalGainRatioMap"<<std::endl ;
01795 }
01796 
01797 void EcalTPGParamBuilder::getCoeff(coeffStruc & coeff, const EcalPedestalsMap & pedMap, unsigned int rawId)
01798 {
01799   coeff.pedestals_[0] = 0 ;
01800   coeff.pedestals_[1] = 0 ;
01801   coeff.pedestals_[2] = 0 ;
01802 
01803   if (forcedPedestalValue_ >= 0) {
01804     coeff.pedestals_[0] = forcedPedestalValue_ ;
01805     coeff.pedestals_[1] = forcedPedestalValue_ ;
01806     coeff.pedestals_[2] = forcedPedestalValue_ ;  
01807     return ;
01808   }
01809 
01810   // get current pedestal
01811   EcalPedestalsMapIterator pedIter = pedMap.find(rawId);
01812   if (pedIter != pedMap.end()) {
01813     EcalPedestals::Item aped = (*pedIter);
01814     coeff.pedestals_[0] = int(aped.mean_x12 + 0.5) ; 
01815     coeff.pedestals_[1] = int(aped.mean_x6 + 0.5) ;
01816     coeff.pedestals_[2] = int(aped.mean_x1 + 0.5) ;
01817   }
01818   else std::cout<<"getCoeff: "<<rawId<<" not found in EcalPedestalsMap"<<std::endl ;
01819 }
01820 
01821 void EcalTPGParamBuilder::getCoeff(coeffStruc & coeff, const std::map<EcalLogicID, MonPedestalsDat> & pedMap, const EcalLogicID & logicId)
01822 {
01823   // get current pedestal
01824   coeff.pedestals_[0] = 0 ;
01825   coeff.pedestals_[1] = 0 ;
01826   coeff.pedestals_[2] = 0 ;
01827 
01828   std::map<EcalLogicID, MonPedestalsDat>::const_iterator it =  pedMap.find(logicId);
01829   if (it != pedMap.end()) {
01830     MonPedestalsDat ped = it->second ;
01831     coeff.pedestals_[0] = int(ped.getPedMeanG12() + 0.5) ; 
01832     coeff.pedestals_[1] = int(ped.getPedMeanG6() + 0.5) ; 
01833     coeff.pedestals_[2] = int(ped.getPedMeanG1() + 0.5) ; 
01834   } 
01835   else std::cout<<"getCoeff: "<<logicId.getID1()<<", "<<logicId.getID2()<<", "<<logicId.getID3()
01836                 <<" not found in std::map<EcalLogicID, MonPedestalsDat>"<<std::endl ;
01837 }
01838 
01839 void EcalTPGParamBuilder::computeFineGrainEBParameters(unsigned int & lowRatio, unsigned int & highRatio,
01840                                                        unsigned int & lowThreshold, unsigned int & highThreshold, unsigned int & lut)
01841 {
01842   lowRatio = int(0x80*FG_lowRatio_EB_ + 0.5) ;
01843   if (lowRatio>0x7f) lowRatio = 0x7f ;
01844   highRatio = int(0x80*FG_highRatio_EB_ + 0.5) ;
01845   if (highRatio>0x7f) highRatio = 0x7f ;
01846   
01847   // lsb at the stage of the FG calculation is:
01848   double lsb_FG = Et_sat_EB_/1024./4 ;
01849   lowThreshold = int(FG_lowThreshold_EB_/lsb_FG+0.5) ;
01850   if (lowThreshold>0xff) lowThreshold = 0xff ;
01851   highThreshold = int(FG_highThreshold_EB_/lsb_FG+0.5) ;
01852   if (highThreshold>0xff) highThreshold = 0xff ;
01853 
01854   // FG lut: FGVB response is LUT(adress) where adress is: 
01855   // bit3: maxof2/ET >= lowRatio, bit2: maxof2/ET >= highRatio, bit1: ET >= lowThreshold, bit0: ET >= highThreshold
01856   // FGVB =1 if jet-like (veto active), =0 if E.M.-like
01857   // the condition for jet-like is: ET>Threshold and  maxof2/ET < Ratio (only TT with enough energy are vetoed)
01858 
01859   // With the following lut, what matters is only max(TLow, Thigh) and max(Elow, Ehigh)
01860   // So, jet-like if maxof2/ettot<max(TLow, Thigh) && ettot >= max(Elow, Ehigh)
01861   if (FG_lut_EB_ == 0) lut = 0x0888 ; 
01862   else lut = FG_lut_EB_ ; // let's use the users value (hope he/she knows what he/she does!)
01863 }
01864 
01865 void EcalTPGParamBuilder::computeFineGrainEEParameters(unsigned int & threshold, unsigned int & lut_strip, unsigned int & lut_tower) 
01866 {
01867   // lsb for EE:
01868   double lsb_FG = Et_sat_EE_/1024. ; // FIXME is it true????
01869   threshold = int(FG_Threshold_EE_/lsb_FG+0.5) ;
01870   lut_strip = FG_lut_strip_EE_  ;
01871   lut_tower = FG_lut_tower_EE_  ;
01872 }
01873 
01874 bool EcalTPGParamBuilder::realignBaseline(linStruc & lin, float forceBase12)
01875 {
01876   bool ok(true) ;
01877   float base[3] = {forceBase12, float(lin.pedestal_[1]), float(lin.pedestal_[2])} ;
01878   for (int i=1 ; i<3 ; i++)
01879     base[i] = float(lin.pedestal_[i]) - 
01880       float(lin.mult_[0])/float(lin.mult_[i])*pow(2., -(lin.shift_[0]-lin.shift_[i]))*(lin.pedestal_[0]-base[0]) ;
01881 
01882   for (int i=0 ; i<3 ; i++) {
01883     //std::cout<<lin.pedestal_[i]<<" "<<base[i]<<std::endl ;
01884     lin.pedestal_[i] = base[i] ;
01885     if (base[i]<0) {
01886       std::cout<<"WARNING: base= "<<base[i]<<" for gainId[0-2]="<<i<<" ==> forcing at 0"<<std::endl ;
01887       lin.pedestal_[i] = 0 ; 
01888       ok = false ;
01889     }
01890   }
01891   return ok ;
01892 
01893 }
01894 
01895 int EcalTPGParamBuilder::getGCTRegionPhi(int ttphi){
01896   int gctphi=0;
01897   gctphi = (ttphi+1)/4;
01898   if(ttphi<=2) gctphi=0;
01899   if(ttphi>=71) gctphi=0;
01900   return gctphi;
01901 }
01902 
01903 int EcalTPGParamBuilder::getGCTRegionEta(int tteta){
01904   int gcteta = 0;
01905   if(tteta>0) gcteta = (tteta-1)/4 + 11;
01906   else if(tteta<0) gcteta = (tteta+1)/4 + 10;
01907   return gcteta;
01908 }
01909 
01910 std::string EcalTPGParamBuilder::getDet(int tcc){
01911   std::stringstream sdet ;
01912 
01913   if (tcc>36 && tcc<55) sdet<<"EB-"<<tcc-36 ;
01914   else if (tcc>=55 && tcc<73) sdet<<"EB+"<<tcc-54 ;
01915   else if (tcc<=36) sdet<<"EE-" ;
01916   else sdet<<"EE+" ;
01917   
01918   if (tcc<=36 || tcc>=73) {
01919     if (tcc>=73) tcc-=72 ;
01920     if (tcc==1 || tcc==18 || tcc==19 || tcc==36)  sdet<<7 ;
01921     else if (tcc==2 || tcc==3 || tcc==20 || tcc==21)  sdet<<8 ;
01922     else if (tcc==4 || tcc==5 || tcc==22 || tcc==23)  sdet<<9 ;
01923     else if (tcc==6 || tcc==7 || tcc==24 || tcc==25)  sdet<<1 ;
01924     else if (tcc==8 || tcc==9 || tcc==26 || tcc==27)  sdet<<2 ;
01925     else if (tcc==10 || tcc==11 || tcc==28 || tcc==29)  sdet<<3 ;
01926     else if (tcc==12 || tcc==13 || tcc==30 || tcc==31)  sdet<<4 ;
01927     else if (tcc==14 || tcc==15 || tcc==32 || tcc==33)  sdet<<5 ;
01928     else if (tcc==16 || tcc==17 || tcc==34 || tcc==35)  sdet<<6 ;
01929   }
01930 
01931   return sdet.str() ;
01932 }
01933 
01934 std::pair < std::string, int >  EcalTPGParamBuilder::getCrate(int tcc){
01935   std::stringstream crate ;
01936   std::string pos ;
01937   int slot = 0 ;
01938 
01939   crate<<"S2D" ;  
01940   if (tcc>=40 && tcc<=42) {crate<<"02d" ; slot = 5 + (tcc-40)*6 ;}
01941   if (tcc>=43 && tcc<=45) {crate<<"03d" ; slot = 5 + (tcc-43)*6 ;}
01942   if (tcc>=37 && tcc<=39) {crate<<"04d" ; slot = 5 + (tcc-37)*6 ;}
01943   if (tcc>=52 && tcc<=54) {crate<<"06d" ; slot = 5 + (tcc-52)*6 ;}
01944   if (tcc>=46 && tcc<=48) {crate<<"07d" ; slot = 5 + (tcc-46)*6 ;}
01945   if (tcc>=49 && tcc<=51) {crate<<"08d" ; slot = 5 + (tcc-49)*6 ;}
01946   if (tcc>=58 && tcc<=60) {crate<<"02h" ; slot = 5 + (tcc-58)*6 ;}
01947   if (tcc>=61 && tcc<=63) {crate<<"03h" ; slot = 5 + (tcc-61)*6 ;}
01948   if (tcc>=55 && tcc<=57) {crate<<"04h" ; slot = 5 + (tcc-55)*6 ;}
01949   if (tcc>=70 && tcc<=72) {crate<<"06h" ; slot = 5 + (tcc-70)*6 ;}
01950   if (tcc>=64 && tcc<=66) {crate<<"07h" ; slot = 5 + (tcc-64)*6 ;}
01951   if (tcc>=67 && tcc<=69) {crate<<"08h" ; slot = 5 + (tcc-67)*6 ;}
01952 
01953   if (tcc>=76 && tcc<=81) {
01954     crate<<"02l" ; 
01955     if (tcc%2==0) slot = 2 + (tcc-76)*3 ;
01956     else slot = 4 + (tcc-77)*3 ;
01957   }
01958   if (tcc>=94 && tcc<=99) {
01959     crate<<"02l" ; 
01960     if (tcc%2==0) slot = 3 + (tcc-94)*3 ;
01961     else slot = 5 + (tcc-95)*3 ;
01962   }
01963 
01964   if (tcc>=22 && tcc<=27) {
01965     crate<<"03l" ; 
01966     if (tcc%2==0) slot = 2 + (tcc-22)*3 ;
01967     else slot = 4 + (tcc-23)*3 ;
01968   }
01969   if (tcc>=4 && tcc<=9) {
01970     crate<<"03l" ; 
01971     if (tcc%2==0) slot = 3 + (tcc-4)*3 ;
01972     else slot = 5 + (tcc-5)*3 ;
01973   }
01974 
01975   if (tcc>=82 && tcc<=87) {
01976     crate<<"07l" ; 
01977     if (tcc%2==0) slot = 2 + (tcc-82)*3 ;
01978     else slot = 4 + (tcc-83)*3 ;
01979   }
01980   if (tcc>=100 && tcc<=105) {
01981     crate<<"07l" ; 
01982     if (tcc%2==0) slot = 3 + (tcc-100)*3 ;
01983     else slot = 5 + (tcc-101)*3 ;
01984   }
01985 
01986   if (tcc>=28 && tcc<=33) {
01987     crate<<"08l" ; 
01988     if (tcc%2==0) slot = 2 + (tcc-28)*3 ;
01989     else slot = 4 + (tcc-29)*3 ;
01990   }
01991   if (tcc>=10 && tcc<=15) {
01992     crate<<"08l" ; 
01993     if (tcc%2==0) slot = 3 + (tcc-10)*3 ;
01994     else slot = 5 + (tcc-11)*3 ;
01995   }
01996 
01997   if (tcc==34) {crate<<"04l" ; slot = 2 ;}
01998   if (tcc==16) {crate<<"04l" ; slot = 3 ;}
01999   if (tcc==35) {crate<<"04l" ; slot = 4 ;}
02000   if (tcc==17) {crate<<"04l" ; slot = 5 ;}
02001   if (tcc==36) {crate<<"04l" ; slot = 8 ;}
02002   if (tcc==18) {crate<<"04l" ; slot = 9 ;}
02003   if (tcc==19) {crate<<"04l" ; slot = 10 ;}
02004   if (tcc==1)  {crate<<"04l" ; slot = 11 ;}
02005   if (tcc==20) {crate<<"04l" ; slot = 14 ;}
02006   if (tcc==2)  {crate<<"04l" ; slot = 15 ;}
02007   if (tcc==21) {crate<<"04l" ; slot = 16 ;}
02008   if (tcc==3)  {crate<<"04l" ; slot = 17 ;}
02009 
02010   if (tcc==88)  {crate<<"06l" ; slot = 2 ;}
02011   if (tcc==106) {crate<<"06l" ; slot = 3 ;}
02012   if (tcc==89)  {crate<<"06l" ; slot = 4 ;}
02013   if (tcc==107) {crate<<"06l" ; slot = 5 ;}
02014   if (tcc==90)  {crate<<"06l" ; slot = 8 ;}
02015   if (tcc==108) {crate<<"06l" ; slot = 9 ;}
02016   if (tcc==73)  {crate<<"06l" ; slot = 10 ;}
02017   if (tcc==91)  {crate<<"06l" ; slot = 11 ;}
02018   if (tcc==74)  {crate<<"06l" ; slot = 14 ;}
02019   if (tcc==92)  {crate<<"06l" ; slot = 15 ;}
02020   if (tcc==75)  {crate<<"06l" ; slot = 16 ;}
02021   if (tcc==93)  {crate<<"06l" ; slot = 17 ;}
02022 
02023   return std::pair< std::string, int > (crate.str(),slot) ;
02024 }