CMS 3D CMS Logo

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 
00026 #include <iostream>
00027 #include <string>
00028 #include <sstream>
00029 #include <vector>
00030 #include <time.h>
00031 
00032 #include <TF1.h>
00033 #include <iomanip>
00034 #include <fstream>
00035 
00036 
00037 double oneOverEtResolEt(double *x, double *par) { 
00038   double Et = x[0] ;
00039   if (Et<1e-6) return 1./par[1] ; // to avoid division by 0.
00040   double resolEt_overEt = sqrt( (par[0]/sqrt(Et))*(par[0]/sqrt(Et)) + (par[1]/Et)*(par[1]/Et) + par[2]*par[2] ) ;
00041   return 1./(Et*resolEt_overEt) ;
00042 }
00043 
00044 EcalTPGParamBuilder::EcalTPGParamBuilder(edm::ParameterSet const& pSet)
00045   : xtal_LSB_EB_(0), xtal_LSB_EE_(0), nSample_(5), complement2_(7)
00046 {
00047   std::cout<<"here we are in EcalTPGParamBuilder::EcalTPGParamBuilder"<<endl;
00048 
00049   readFromDB_ = pSet.getParameter<bool>("readFromDB") ;
00050   writeToDB_  = pSet.getParameter<bool>("writeToDB") ;
00051   DBEE_ = pSet.getParameter<bool>("allowDBEE") ;
00052   string DBsid    = pSet.getParameter<std::string>("DBsid") ;
00053   string DBuser   = pSet.getParameter<std::string>("DBuser") ;
00054   string DBpass   = pSet.getParameter<std::string>("DBpass") ;
00055   uint32_t DBport = pSet.getParameter<unsigned int>("DBport") ;
00056   DBrunNb_        = pSet.getParameter<unsigned int>("DBrunNb") ;
00057 
00058   std::cout << "DB RUN NB="<< DBrunNb_<< endl;
00059  
00060   if (readFromDB_ || writeToDB_) {
00061     try {
00062       cout << "Warning: using the DB is not yet implemented " <<endl ;
00063       db_ = new EcalTPGDBApp(DBsid, DBuser, DBpass) ;
00064     } catch (exception &e) {
00065       cout << "ERROR:  " << e.what() << endl;
00066     } catch (...) {
00067       cout << "Unknown error caught" << endl;
00068     }
00069   }
00070 
00071   writeToFiles_ =  pSet.getParameter<bool>("writeToFiles") ;
00072   if (writeToFiles_) {
00073     std::string outFile = pSet.getParameter<std::string>("outFile") ;
00074     out_file_ = new std::ofstream(outFile.c_str(), std::ios::out) ;  
00075     geomFile_   = new std::ofstream("geomFile.txt", std::ios::out) ;  
00076   }
00077 
00078 
00079 
00080   useTransverseEnergy_ = pSet.getParameter<bool>("useTransverseEnergy") ;
00081   
00082   Et_sat_EB_ = pSet.getParameter<double>("Et_sat_EB") ;
00083   Et_sat_EE_ = pSet.getParameter<double>("Et_sat_EE") ;
00084   sliding_ = pSet.getParameter<unsigned int>("sliding") ;
00085   sampleMax_ = pSet.getParameter<unsigned int>("weight_sampleMax") ;
00086 
00087   std::cout<<"here we are in EcalTPGParamBuilder::EcalTPGParamBuilder 1/2"<<endl;
00088 
00089   LUT_option_ = pSet.getParameter<std::string>("LUT_option") ;
00090   LUT_threshold_EB_ = pSet.getParameter<double>("LUT_threshold_EB") ;
00091   LUT_threshold_EE_ = pSet.getParameter<double>("LUT_threshold_EE") ;
00092   LUT_stochastic_EB_ = pSet.getParameter<double>("LUT_stochastic_EB") ;
00093   LUT_noise_EB_ =pSet.getParameter<double>("LUT_noise_EB") ;
00094   LUT_constant_EB_ =pSet.getParameter<double>("LUT_constant_EB") ;
00095   LUT_stochastic_EE_ = pSet.getParameter<double>("LUT_stochastic_EE") ;
00096   LUT_noise_EE_ =pSet.getParameter<double>("LUT_noise_EE") ;
00097   LUT_constant_EE_ =pSet.getParameter<double>("LUT_constant_EE") ;
00098 
00099 
00100   std::cout<<"here we are in EcalTPGParamBuilder::EcalTPGParamBuilder after LUT"<<endl;
00101 
00102   TTF_lowThreshold_EB_ = pSet.getParameter<double>("TTF_lowThreshold_EB") ;
00103   TTF_highThreshold_EB_ = pSet.getParameter<double>("TTF_highThreshold_EB") ;
00104   TTF_lowThreshold_EE_ = pSet.getParameter<double>("TTF_lowThreshold_EE") ;
00105   TTF_highThreshold_EE_ = pSet.getParameter<double>("TTF_highThreshold_EE") ;
00106   std::cout<<"here we are in EcalTPGParamBuilder::EcalTPGParamBuilder after TTF"<<endl;
00107 
00108   FG_lowThreshold_EB_ = pSet.getParameter<double>("FG_lowThreshold_EB") ;
00109   FG_highThreshold_EB_ = pSet.getParameter<double>("FG_highThreshold_EB") ;
00110   FG_lowRatio_EB_ = pSet.getParameter<double>("FG_lowRatio_EB") ;
00111   FG_highRatio_EB_ = pSet.getParameter<double>("FG_highRatio_EB") ;
00112   FG_lut_EB_ = pSet.getParameter<unsigned int>("FG_lut_EB") ;
00113   FG_Threshold_EE_ = pSet.getParameter<double>("FG_Threshold_EE") ;
00114   FG_lut_strip_EE_ = pSet.getParameter<unsigned int>("FG_lut_strip_EE") ;
00115   FG_lut_tower_EE_ = pSet.getParameter<unsigned int>("FG_lut_tower_EE") ;
00116 
00117   std::cout<<"here we are in EcalTPGParamBuilder::EcalTPGParamBuilder done"<<endl;
00118 
00119 
00120 }
00121 
00122 EcalTPGParamBuilder::~EcalTPGParamBuilder()
00123 { 
00124   if (writeToFiles_) {
00125     (*out_file_ )<<"EOF"<<std::endl ;
00126     out_file_->close() ;
00127     delete out_file_ ;
00128   }
00129 }
00130 
00131 
00132 bool EcalTPGParamBuilder::checkIfOK(     EcalPedestals::Item item) {
00133 
00134   bool result=true;
00135   if( item.mean_x1 <150. || item.mean_x1 >250) result=false;
00136   if( item.mean_x6 <150. || item.mean_x6 >250) result=false;
00137   if( item.mean_x12 <150. || item.mean_x12 >250) result=false;
00138   if( item.rms_x1 <0 || item.rms_x1 > 2) result=false;
00139   if( item.rms_x6 <0 || item.rms_x1 > 3) result=false;
00140   if( item.rms_x12 <0 || item.rms_x1 > 5) result=false;
00141   return result; 
00142 
00143 }
00144 
00145 void EcalTPGParamBuilder::analyze(const edm::Event& evt, const edm::EventSetup& evtSetup) 
00146 {
00147   using namespace edm;
00148   using namespace std;
00149 
00150   std::cout<< "we are in analyze"<< endl; 
00151 
00152 
00153   // geometry
00154   // geometry
00155   ESHandle<CaloGeometry> theGeometry;
00156   ESHandle<CaloSubdetectorGeometry> theEndcapGeometry_handle, theBarrelGeometry_handle;
00157   evtSetup.get<CaloGeometryRecord>().get( theGeometry );
00158   evtSetup.get<EcalEndcapGeometryRecord>().get("EcalEndcap",theEndcapGeometry_handle);
00159   evtSetup.get<EcalBarrelGeometryRecord>().get("EcalBarrel",theBarrelGeometry_handle);
00160   evtSetup.get<IdealGeometryRecord>().get(eTTmap_);
00161   theEndcapGeometry_ = &(*theEndcapGeometry_handle);
00162   theBarrelGeometry_ = &(*theBarrelGeometry_handle);
00163 
00164   // electronics mapping
00165   ESHandle< EcalElectronicsMapping > ecalmapping;
00166   evtSetup.get< EcalMappingRcd >().get(ecalmapping);
00167   theMapping_ = ecalmapping.product();
00168 
00169 
00171   // Initialization section //
00173   list<uint32_t> towerListEB ;
00174   list<uint32_t> stripListEB ;
00175   list<uint32_t> towerListEE ;
00176   list<uint32_t> stripListEE ;
00177   list<uint32_t>::iterator itList ;
00178 
00179 
00180   std::cout <<"we get the pedestals from offline DB"<<endl;
00181 
00182   // Pedestals
00183   ESHandle<EcalPedestals> pedHandle;
00184   evtSetup.get<EcalPedestalsRcd>().get( pedHandle );
00185   const EcalPedestalsMap & pedMap = pedHandle.product()->getMap() ;
00186 
00187    
00188 
00189   // we copy the last valid record to a temporary object peds
00190   EcalPedestals* peds = new EcalPedestals();
00191   for(int iEta=-EBDetId::MAX_IETA; iEta<=EBDetId::MAX_IETA ;++iEta) {
00192     if(iEta==0) continue;
00193     for(int iPhi=EBDetId::MIN_IPHI; iPhi<=EBDetId::MAX_IPHI; ++iPhi) {
00194       // make an EBDetId since we need EBDetId::rawId() to be used as the key for the pedestals
00195       if (EBDetId::validDetId(iEta,iPhi))
00196         {
00197           EBDetId ebdetid(iEta,iPhi);
00198 
00199           EcalPedestals::Item aped= *(pedMap.find(ebdetid));
00200 
00201           // here I copy the last valid value in the peds object
00202           EcalPedestals::Item item;
00203           item.mean_x1  = aped.mean_x1;
00204           item.rms_x1   = aped.rms_x1;
00205           item.mean_x6  = aped.mean_x6;
00206           item.rms_x6   = aped.rms_x6;
00207           item.mean_x12 = aped.mean_x12;
00208           item.rms_x12  = aped.rms_x12;
00209 
00210           peds->insert(std::make_pair(ebdetid.rawId(),item));
00211         }
00212     }
00213   }
00214 
00215 
00216   std::cout <<"we get the pedestals from online DB"<<endl;
00217   map<EcalLogicID, MonPedestalsDat> pedMapDB ;
00218   int iovId = 0 ;
00219   std::cout << "DB RUN NB="<< DBrunNb_<< endl;
00220 
00221   if (readFromDB_) {
00222     iovId = db_->readFromCondDB_Pedestals(pedMapDB, DBrunNb_) ;
00223 
00224     typedef map<EcalLogicID, MonPedestalsDat>::const_iterator CImon;
00225     EcalLogicID ecid_xt;
00226     MonPedestalsDat  rd_ped;
00227           
00228     for (CImon p = pedMapDB.begin(); p != pedMapDB.end(); p++) {
00229       ecid_xt = p->first;
00230       rd_ped  = p->second;
00231       int sm_num=ecid_xt.getID1();
00232       int xt_num=ecid_xt.getID2(); 
00233       
00234       EcalPedestals::Item item;
00235       item.mean_x1  =rd_ped.getPedMeanG1() ;
00236       item.rms_x1   =rd_ped.getPedRMSG1();
00237       item.mean_x6  =rd_ped.getPedMeanG6();
00238       item.rms_x6   =rd_ped.getPedRMSG6() ;
00239       item.mean_x12 =rd_ped.getPedMeanG12();
00240       item.rms_x12  =rd_ped.getPedRMSG12();
00241       
00242       EBDetId ebdetid(sm_num,xt_num,EBDetId::SMCRYSTALMODE);
00243       // here we change in the peds object only the values that are available in the online DB 
00244       // otherwise we keep the old value
00245       if(checkIfOK(item)) peds->insert(std::make_pair(ebdetid.rawId(),item));
00246     }
00247   }
00248   // now peds is complete 
00249 
00250 
00251   const EcalPedestalsMap & pedMapNew = peds->getMap() ;
00252 
00253 
00254   std::cout <<"we get the intercalib from offline DB"<<endl;
00255   // Intercalib constants
00256   ESHandle<EcalIntercalibConstants> pIntercalib ;
00257   evtSetup.get<EcalIntercalibConstantsRcd>().get(pIntercalib) ;
00258   const EcalIntercalibConstants * intercalib = pIntercalib.product() ;
00259   const EcalIntercalibConstantMap & calibMap = intercalib->getMap() ;
00260 
00261 
00262   std::cout <<"we get the gain ratios from offline DB"<<endl;
00263   // Gain Ratios
00264   ESHandle<EcalGainRatios> pRatio;
00265   evtSetup.get<EcalGainRatiosRcd>().get(pRatio);
00266   const EcalGainRatioMap & gainMap = pRatio.product()->getMap();
00267   
00268 
00269   std::cout <<"we get the ADC to GEV from offline DB"<<endl;
00270   // ADCtoGeV
00271   ESHandle<EcalADCToGeVConstant> pADCToGeV ;
00272   evtSetup.get<EcalADCToGeVConstantRcd>().get(pADCToGeV) ;
00273   const EcalADCToGeVConstant * ADCToGeV = pADCToGeV.product() ;
00274   xtal_LSB_EB_ = ADCToGeV->getEBValue() ;
00275   xtal_LSB_EE_ = ADCToGeV->getEEValue() ;
00276   std::cout<<"xtal_LSB_EB_ = "<<xtal_LSB_EB_<<std::endl ;
00277   std::cout<<"xtal_LSB_EE_ = "<<xtal_LSB_EE_<<std::endl ;
00278 
00279   
00280   vector<EcalLogicID> my_EcalLogicId;
00281   vector<EcalLogicID> my_TTEcalLogicId;
00282   vector<EcalLogicID> my_StripEcalLogicId;
00283   EcalLogicID my_EcalLogicId_EB;
00284   EcalLogicID my_EcalLogicId_EE;
00285   if (writeToDB_ || readFromDB_){
00286     std::cout<<"going to get the ecal logic id set"<< endl;
00287 
00288     my_EcalLogicId_EB = db_->getEcalLogicID( "EB",EcalLogicID::NULLID,EcalLogicID::NULLID,EcalLogicID::NULLID,"EB");
00289     my_EcalLogicId_EE = db_->getEcalLogicID( "EE",EcalLogicID::NULLID,EcalLogicID::NULLID,EcalLogicID::NULLID,"EE");
00290 
00291     my_EcalLogicId = db_->getEcalLogicIDSetOrdered( "EB_crystal_number",
00292                                                     1, 36,
00293                                                     1, 1700,
00294                                                     EcalLogicID::NULLID,EcalLogicID::NULLID,
00295                                                     "EB_crystal_number",12 );
00296     my_TTEcalLogicId = db_->getEcalLogicIDSetOrdered( "EB_trigger_tower",
00297                                                     1, 36,
00298                                                     1, 68,
00299                                                     EcalLogicID::NULLID,EcalLogicID::NULLID,
00300                                                     "EB_trigger_tower",12 );
00301     my_StripEcalLogicId = db_->getEcalLogicIDSetOrdered( "EB_VFE",   1, 36,   1, 68,   1,5 ,  "EB_VFE",12 );
00302     std::cout<<"got the 3 ecal barrel logic id set"<< endl;
00303 
00304   }
00305 
00307   // Compute linearization coeff section //
00309 
00310   map<EcalLogicID, FEConfigPedDat> pedset ;
00311   map<EcalLogicID, FEConfigLinDat> linset ;
00312   map<EcalLogicID, FEConfigParamDat> linparamset ;
00313 
00314   // loop on EB xtals
00315   if (writeToFiles_) (*out_file_)<<"COMMENT ====== barrel crystals ====== "<<std::endl ;
00316   std::vector<DetId> ebCells = theBarrelGeometry_->getValidDetIds(DetId::Ecal, EcalBarrel);
00317   for (vector<DetId>::const_iterator it = ebCells.begin(); it != ebCells.end(); ++it) {
00318     EBDetId id(*it) ;
00319     double theta = theBarrelGeometry_->getGeometry(id)->getPosition().theta() ;
00320     if (!useTransverseEnergy_) theta = acos(0.) ;
00321     const EcalTrigTowerDetId towid= id.tower();
00322     towerListEB.push_back(towid.rawId()) ;
00323     const EcalTriggerElectronicsId elId = theMapping_->getTriggerElectronicsId(id) ;
00324     stripListEB.push_back(elId.rawId() & 0xfffffff8) ;
00325     int dccNb = theMapping_->DCCid(towid) ;
00326     int tccNb = theMapping_->TCCid(towid) ;
00327     int towerInTCC = theMapping_->iTT(towid) ;
00328     int stripInTower = elId.pseudoStripId() ;
00329     int xtalInStrip = elId.channelId() ;
00330 
00331     FEConfigPedDat ped ;
00332     FEConfigLinDat lin ;
00333     if (writeToFiles_) (*out_file_)<<"CRYSTAL "<<dec<<id.rawId()<<std::endl ;
00334     //  if (writeToDB_ || readFromDB_) logicId = db_->getEcalLogicID ("EB_crystal_number", id.ism(), id.ic()) ;
00335 
00336     coeffStruc coeff ;
00337     getCoeff(coeff, calibMap, id.rawId()) ;
00338     getCoeff(coeff, gainMap, id.rawId()) ;
00339     getCoeff(coeff, pedMapNew, id.rawId()) ;
00340     
00341 
00342     // compute and fill linearization parameters
00343     for (int i=0 ; i<3 ; i++) {
00344       int mult, shift ;
00345       bool ok = computeLinearizerParam(theta, coeff.gainRatio_[i], coeff.calibCoeff_, "EB", mult , shift) ;
00346       if (!ok) std::cout << "unable to compute the parameters for SM="<< id.ism()<<" xt="<< id.ic()<<" " <<dec<<id.rawId()<<std::endl ;  
00347       else {
00348         if (writeToFiles_) (*out_file_) << hex <<" 0x"<<coeff.pedestals_[i]<<" 0x"<<mult<<" 0x"<<shift<<std::endl; 
00349         if (writeToDB_) {
00350           if (i==0)  {ped.setPedMeanG12(coeff.pedestals_[i]) ; lin.setMultX12(mult) ; lin.setShift12(shift) ; } 
00351           if (i==1)  {ped.setPedMeanG6(coeff.pedestals_[i]) ; lin.setMultX6(mult) ; lin.setShift6(shift) ; } 
00352           if (i==2)  {ped.setPedMeanG1(coeff.pedestals_[i]) ; lin.setMultX1(mult) ; lin.setShift1(shift) ; }
00353         }
00354       }
00355     }
00356     if (writeToDB_) {
00357       int ixtal=(id.ism()-1)*1700+(id.ic()-1);
00358       EcalLogicID logicId =my_EcalLogicId[ixtal];
00359       pedset[logicId] = ped ;
00360       linset[logicId] = lin ;
00361 
00362     }
00363 
00364   } //ebCells
00365 
00366 
00367   if (writeToDB_) {
00368     // EcalLogicID  of the whole barrel is: my_EcalLogicId_EB
00369     FEConfigParamDat linparam ;
00370     linparam.setETSat(Et_sat_EB_); 
00371     linparam.setTTThreshlow(TTF_lowThreshold_EB_); 
00372     linparam.setTTThreshhigh(TTF_highThreshold_EB_); 
00373     linparam.setFGlowthresh(FG_lowThreshold_EB_); 
00374     linparam.setFGhighthresh(FG_highThreshold_EB_); 
00375     linparam.setFGlowratio(FG_lowRatio_EB_); 
00376     linparam.setFGhighratio(FG_highRatio_EB_);
00377     linparamset[my_EcalLogicId_EB] = linparam ;
00378   }
00379 
00380 
00381 
00382   if(DBEE_){
00383 
00384   // loop on EE xtals
00385   if (writeToFiles_) (*out_file_)<<"COMMENT ====== endcap crystals ====== "<<std::endl ;
00386 
00387 
00388   std::vector<DetId> eeCells = theEndcapGeometry_->getValidDetIds(DetId::Ecal, EcalEndcap);
00389   for (vector<DetId>::const_iterator it = eeCells.begin(); it != eeCells.end(); ++it) {
00390     EEDetId id(*it);
00391     double theta = theEndcapGeometry_->getGeometry(id)->getPosition().theta() ;
00392     if (!useTransverseEnergy_) theta = acos(0.) ;
00393     const EcalTrigTowerDetId towid= (*eTTmap_).towerOf(id) ;
00394     towerListEE.push_back(towid.rawId()) ;
00395     // special case of towers in inner rings of EE
00396     if (towid.ietaAbs() == 27 || towid.ietaAbs() == 28) {
00397       EcalTrigTowerDetId additionalTower(towid.zside(), towid.subDet(), towid.ietaAbs(), towid.iphi()+1) ;
00398       towerListEE.push_back(additionalTower.rawId()) ;
00399     }
00400     const EcalTriggerElectronicsId elId = theMapping_->getTriggerElectronicsId(id) ;
00401     stripListEE.push_back(elId.rawId() & 0xfffffff8) ;
00402     int dccNb = theMapping_->DCCid(towid) ;
00403     int tccNb = theMapping_->TCCid(towid) ;
00404     int towerInTCC = theMapping_->iTT(towid) ;
00405     int stripInTower = elId.pseudoStripId() ;
00406     int xtalInStrip = elId.channelId() ;
00407 
00408     EcalLogicID logicId ;
00409     FEConfigPedDat ped ;
00410     FEConfigLinDat lin ;
00411     if (writeToFiles_) (*out_file_)<<"CRYSTAL "<<dec<<id.rawId()<<std::endl ;
00412     if ((writeToDB_ || readFromDB_) && DBEE_) {
00413       int iz = id.positiveZ() ;
00414       if (iz ==0) iz = -1 ;
00415       logicId = db_->getEcalLogicID ("EE_crystal_number", iz, id.ix(), id.iy()) ;
00416     }
00417 
00418     coeffStruc coeff ;
00419     if (readFromDB_ && DBEE_) {
00420       getCoeff(coeff, calibMap, id.rawId()) ;
00421       getCoeff(coeff, gainMap, id.rawId()) ;
00422       getCoeff(coeff, pedMapDB, logicId) ;      
00423     } else {
00424       getCoeff(coeff, calibMap, id.rawId()) ;
00425       getCoeff(coeff, gainMap, id.rawId()) ;
00426       getCoeff(coeff, pedMap, id.rawId()) ;
00427     }
00428 
00429 
00430   
00431     // compute and fill linearization parameters
00432     for (int i=0 ; i<3 ; i++) {
00433       int mult, shift ;
00434       bool ok = computeLinearizerParam(theta, coeff.gainRatio_[i], coeff.calibCoeff_, "EE", mult , shift) ;
00435       if (!ok) std::cout << "unable to compute the parameters for "<<dec<<id.rawId()<<std::endl ;  
00436       else {
00437         if (writeToFiles_) (*out_file_) << hex <<" 0x"<<coeff.pedestals_[i]<<" 0x"<<mult<<" 0x"<<shift<<std::endl; 
00438         if (writeToDB_ && DBEE_) {
00439           if (i==0)  {ped.setPedMeanG12(coeff.pedestals_[i]) ; lin.setMultX12(mult) ; lin.setShift12(shift) ; } 
00440           if (i==1)  {ped.setPedMeanG6(coeff.pedestals_[i]) ; lin.setMultX6(mult) ; lin.setShift6(shift) ; } 
00441           if (i==2)  {ped.setPedMeanG1(coeff.pedestals_[i]) ; lin.setMultX1(mult) ; lin.setShift1(shift) ; } 
00442         }       
00443       }
00444     }
00445     if (writeToDB_ && DBEE_) {
00446       pedset[logicId] = ped ;
00447       linset[logicId] = lin ;
00448     }
00449   } //eeCells
00450   if (writeToDB_ ) {
00451     // EcalLogicID  of the whole barrel is: my_EcalLogicId_EB
00452     FEConfigParamDat linparam ;
00453     linparam.setETSat(Et_sat_EE_); 
00454     linparam.setTTThreshlow(TTF_lowThreshold_EE_); 
00455     linparam.setTTThreshhigh(TTF_highThreshold_EE_); 
00456     linparam.setFGlowthresh(FG_Threshold_EE_); 
00457     linparam.setFGhighthresh(FG_Threshold_EE_); 
00458     linparamset[my_EcalLogicId_EE] = linparam ;
00459   }
00460 
00461   }
00462   std::cout<< "we are in analyze 2"<< endl; 
00463 
00464   if (writeToDB_) {
00465     db_->writeToConfDB_TPGPedestals(pedset, iovId, "from_CondDB") ;
00466     db_->writeToConfDB_TPGLinearCoef(linset,linparamset, iovId, "from_CondDB") ;
00467   }
00468 
00470   // Compute weights section //
00472 
00473   // loading reference signal representation
00474   EcalSimParameterMap parameterMap;  
00475   EBDetId   barrel(1,1);
00476   double    phase = parameterMap.simParameters(barrel).timePhase();
00477   EcalShape shape(phase); 
00478   std::vector<unsigned int> weights = computeWeights(shape) ;
00479 
00480   if (weights.size() == 5) {
00481     if (writeToFiles_) {
00482       (*out_file_) <<std::endl ;
00483       (*out_file_) <<"WEIGHT 0"<<endl ;
00484       for (uint sample=0 ; sample<5 ; sample++) (*out_file_) << "0x" <<hex<<weights[sample]<<" " ;
00485       (*out_file_)<<std::endl ; 
00486     }
00487     if (writeToDB_) {
00488       std::cout<<"going to write the weights "<< endl;
00489       map<EcalLogicID, FEConfigWeightGroupDat> dataset;
00490       // we create 1 group
00491       int NWEIGROUPS =1; 
00492       for (int ich=0; ich<NWEIGROUPS; ich++){
00493         FEConfigWeightGroupDat gut;
00494         gut.setWeightGroupId(ich);
00495         gut.setWeight0(weights[0] );
00496         gut.setWeight1(weights[1] );
00497         gut.setWeight2(weights[2] );
00498         gut.setWeight3(weights[3] );
00499         gut.setWeight4(weights[4] );
00500         EcalLogicID ecid = EcalLogicID( "DUMMY", ich,ich);
00501         // Fill the dataset
00502         dataset[ecid] = gut; // we use any logic id but different, because it is in any case ignored... 
00503       }
00504       
00505       // now we store in the DB the correspondence btw channels and groups 
00506       map<EcalLogicID, FEConfigWeightDat> dataset2;
00507       // in this case I decide in a stupid way which channel belongs to which group 
00508       for (int ich=0; ich<my_StripEcalLogicId.size() ; ich++){
00509         FEConfigWeightDat wut;
00510         int igroup=0;
00511         wut.setWeightGroupId(igroup);
00512         // in case of real groups one has to look for the right logic id 
00513         // the logic ids are ordered in the vector by SM (EB+ 1,..,18, EB-, 19,..36), TT (1,...68), strip (1,...5)
00514         // Fill the dataset
00515         dataset2[my_StripEcalLogicId[ich]] = wut;
00516       }
00517 
00518       // endcap loop missing ... FIXME 
00519       //
00520       //
00521       //
00522 
00523       // Insert the dataset
00524       ostringstream wtag;
00525       wtag.str(""); wtag<<"SimShape_Phase"<<phase<<"_NGroups_"<<NWEIGROUPS;
00526       std::string weight_tag=wtag.str();
00527       std::cout<< " weight tag "<<weight_tag<<endl; 
00528       db_->writeToConfDB_TPGWeight(dataset, dataset2, NWEIGROUPS, weight_tag) ;
00529       
00530     }
00531   }
00532 
00534   // Compute FG section //
00536 
00537   // barrel
00538   uint lowRatio, highRatio, lowThreshold, highThreshold, lutFG ;
00539   computeFineGrainEBParameters(lowRatio, highRatio, lowThreshold, highThreshold, lutFG) ;
00540   if (writeToFiles_) {
00541     (*out_file_) <<std::endl ;
00542     (*out_file_) <<"FG 0"<<std::endl ;
00543     (*out_file_)<<hex<<"0x"<<lowThreshold<<" 0x"<<highThreshold
00544                   <<" 0x"<<lowRatio<<" 0x"<<highRatio<<" 0x"<<lutFG
00545                   <<std::endl ;
00546   }
00547 
00548   // endcap
00549   uint threshold, lut_strip, lut_tower ;
00550   computeFineGrainEEParameters(threshold, lut_strip, lut_tower) ; 
00551 
00552   // and here we store the fgr part
00553 
00554   
00555   if (writeToDB_) {
00556     std::cout<<"going to write the fgr "<< endl;
00557       map<EcalLogicID, FEConfigFgrGroupDat> dataset;
00558       // we create 1 group
00559       int NFGRGROUPS =1; 
00560       for (int ich=0; ich<NFGRGROUPS; ich++){
00561         FEConfigFgrGroupDat gut;
00562         gut.setFgrGroupId(ich);
00563         gut.setThreshLow(lowRatio );
00564         gut.setThreshHigh(highRatio);
00565         gut.setRatioLow(lowThreshold);
00566         gut.setRatioHigh(highThreshold);
00567         gut.setLUTConfId(lutFG);
00568         EcalLogicID ecid = EcalLogicID( "DUMMY", ich,ich);
00569         // Fill the dataset
00570         dataset[ecid] = gut; // we use any logic id but different, because it is in any case ignored... 
00571       }
00572       
00573       // now we store in the DB the correspondence btw channels and groups 
00574       map<EcalLogicID, FEConfigFgrDat> dataset2;
00575       // in this case I decide in a stupid way which channel belongs to which group 
00576       for (int ich=0; ich<my_TTEcalLogicId.size() ; ich++){
00577         FEConfigFgrDat wut;
00578         int igroup=0;
00579         wut.setFgrGroupId(igroup);
00580         // Fill the dataset
00581         // the logic ids are ordered by SM (1,...36) and TT (1,...68)  
00582         // you have to calculate the right index here 
00583         dataset2[my_TTEcalLogicId[ich]] = wut;
00584       }
00585 
00586       // endcap loop missing ... FIXME 
00587       //
00588       //
00589       //
00590 
00591       // Insert the dataset
00592       ostringstream wtag;
00593       wtag.str(""); wtag<<"FGR_"<<lutFG<<"_NGroups_"<<NFGRGROUPS;
00594       std::string weight_tag=wtag.str();
00595       std::cout<< " weight tag "<<weight_tag<<endl; 
00596       db_->writeToConfDB_TPGFgr(dataset, dataset2, NFGRGROUPS, weight_tag) ;
00597   }
00598 
00599   if (writeToDB_) {
00600     std::cout<<"going to write the sliding "<< endl;
00601       map<EcalLogicID, FEConfigSlidingDat> dataset;
00602       // in this case I decide in a stupid way which channel belongs to which group 
00603       for (int ich=0; ich<my_StripEcalLogicId.size() ; ich++){
00604         FEConfigSlidingDat wut;
00605         wut.setSliding(sliding_);
00606         // Fill the dataset
00607         // the logic ids are ordered by SM (1,...36) , TT (1,...68) and strip (1..5) 
00608         // you have to calculate the right index here 
00609         dataset[my_StripEcalLogicId[ich]] = wut;
00610       }
00611 
00612       // endcap loop missing ... FIXME 
00613       //
00614       //
00615       //
00616 
00617       // Insert the dataset
00618       ostringstream wtag;
00619       wtag.str(""); wtag<<"Sliding_"<<sliding_;
00620       std::string justatag=wtag.str();
00621       std::cout<< " sliding tag "<<justatag<<endl;
00622       int iov_id=0; // just a parameter ... 
00623       db_->writeToConfDB_TPGSliding(dataset,iov_id, justatag) ;
00624   }
00625 
00626   
00627 
00628 
00629 
00631   // Compute LUT section //
00633 
00634   int lut_EB[1024], lut_EE[1024] ;
00635 
00636   // barrel
00637   computeLUT(lut_EB, "EB") ; 
00638   if (writeToFiles_) {
00639     (*out_file_) <<std::endl ;
00640     (*out_file_) <<"LUT 0"<<std::endl ;
00641     for (int i=0 ; i<1024 ; i++) (*out_file_)<<"0x"<<hex<<lut_EB[i]<<" " ;
00642     (*out_file_)<<endl ;
00643   }
00644   
00645   // endcap
00646   computeLUT(lut_EE, "EE") ;
00647   // check first if lut_EB and lut_EE are the same
00648   bool newLUT(false) ;
00649   for (int i=0 ; i<1024 ; i++) if (lut_EE[i] != lut_EB[i]) newLUT = true ;
00650   if (newLUT && writeToFiles_) { 
00651     (*out_file_) <<std::endl ;
00652     (*out_file_) <<"LUT 1"<<std::endl ;
00653     for (int i=0 ; i<1024 ; i++) (*out_file_)<<"0x"<<hex<<lut_EE[i]<<" " ;
00654     (*out_file_)<<endl ;
00655   }
00656 
00657 
00658 
00659   if (writeToDB_) {
00660     map<EcalLogicID, FEConfigLUTGroupDat> dataset;
00661     // we create 1 LUT group
00662     int NLUTGROUPS =1; 
00663     for (int ich=0; ich<NLUTGROUPS; ich++){
00664       FEConfigLUTGroupDat lut;
00665       lut.setLUTGroupId(ich);
00666       for (int i=0; i<1024; i++){
00667         lut.setLUTValue(i, lut_EB[i] );
00668       }
00669       EcalLogicID ecid = EcalLogicID( "DUMMY", ich,ich);
00670       // Fill the dataset
00671       dataset[ecid] = lut; // we use any logic id but different, because it is in any case ignored... 
00672     }
00673 
00674     // now we store in the DB the correspondence btw channels and LUT groups 
00675     map<EcalLogicID, FEConfigLUTDat> dataset2;
00676     // in this case I decide in a stupid way which channel belongs to which group 
00677     for (int ich=0; ich<my_TTEcalLogicId.size() ; ich++){
00678       FEConfigLUTDat lut;
00679       int igroup=0;
00680       lut.setLUTGroupId(igroup);
00681       // calculate the right TT - in the vector they are ordere by SM and by TT 
00682       // Fill the dataset
00683       dataset2[my_TTEcalLogicId[ich]] = lut;
00684     }
00685 
00686     // endcap loop missing ... FIXME 
00687     //
00688     //
00689     //
00690 
00691     // Insert the dataset
00692     ostringstream ltag;
00693     ltag.str(""); ltag<<LUT_option_<<"_NGroups_"<<NLUTGROUPS;
00694     std::string lut_tag=ltag.str();
00695     std::cout<< " LUT tag "<<lut_tag<<endl; 
00696     db_->writeToConfDB_TPGLUT(dataset, dataset2, NLUTGROUPS, lut_tag) ;
00697 
00698   }
00699 
00700 
00701 
00702 
00704   // loop on strips and associate them with default values //
00706 
00707   // Barrel
00708   stripListEB.sort() ;
00709   stripListEB.unique() ;
00710   cout<<"Number of EB strips="<<stripListEB.size()<<endl ;
00711   if (writeToFiles_) {
00712     (*out_file_) <<std::endl ;
00713     for (itList = stripListEB.begin(); itList != stripListEB.end(); itList++ ) {
00714       (*out_file_) <<"STRIP_EB "<<dec<<(*itList)<<endl ;
00715       (*out_file_) << hex << "0x" <<sliding_<<std::endl ;
00716       (*out_file_) <<" 0" << std::endl ;
00717     }
00718   }
00719 
00720   // Endcap
00721   stripListEE.sort() ;
00722   stripListEE.unique() ;
00723   cout<<"Number of EE strips="<<stripListEE.size()<<endl ;
00724   if (writeToFiles_) {
00725     (*out_file_) <<std::endl ;
00726     for (itList = stripListEE.begin(); itList != stripListEE.end(); itList++ ) {
00727       (*out_file_) <<"STRIP_EE "<<dec<<(*itList)<<endl ;
00728       (*out_file_) << hex << "0x" <<sliding_<<std::endl ;
00729       (*out_file_) <<" 0" << std::endl ;
00730       (*out_file_)<<hex<<"0x"<<threshold<<" 0x"<<lut_strip<<std::endl ;  
00731     }
00732   }
00733 
00734 
00736   // loop on towers and associate them with default values //
00738 
00739   // Barrel
00740   towerListEB.sort() ;
00741   towerListEB.unique() ;
00742   cout<<"Number of EB towers="<<towerListEB.size()<<endl ;
00743   if (writeToFiles_) {
00744     (*out_file_) <<std::endl ;
00745     (*geomFile_)<<"BARREL"<<endl ;
00746     for (itList = towerListEB.begin(); itList != towerListEB.end(); itList++ ) {
00747       (*out_file_) <<"TOWER_EB "<<dec<<(*itList)<<endl ;
00748       (*out_file_) <<" 0\n 0\n" ;
00749       EcalTrigTowerDetId towerId((*itList)) ;
00750       int dccNb = theMapping_->DCCid(towerId) ;
00751       int tccNb = theMapping_->TCCid(towerId) ;
00752       int towerInTCC = theMapping_->iTT(towerId) ;
00753       (*geomFile_)<<"towerId="<<(*itList)<<" ieta="<<towerId.ietaAbs()<<" iphi="<<towerId.iphi()
00754                   <<" dccNb="<<dccNb<<" tccNb="<<tccNb<<" towerInTCC="<<towerInTCC<<endl ;
00755     }
00756   }
00757 
00758   // Endcap
00759   towerListEE.sort() ;
00760   towerListEE.unique() ;
00761   cout<<"Number of EE towers="<<towerListEE.size()<<endl ;
00762   if (writeToFiles_) {
00763     (*out_file_) <<std::endl ;
00764     (*geomFile_)<<"ENDCAP"<<endl ;
00765     for (itList = towerListEE.begin(); itList != towerListEE.end(); itList++ ) {
00766       (*out_file_) <<"TOWER_EE "<<dec<<(*itList)<<endl ;
00767       if (newLUT) (*out_file_) <<" 1\n" ;
00768       else  (*out_file_) <<" 0\n" ;
00769       (*out_file_)<<hex<<"0x"<<lut_tower<<std::endl ;
00770       EcalTrigTowerDetId towerId((*itList)) ;
00771       int dccNb = theMapping_->DCCid(towerId) ;
00772       int tccNb = theMapping_->TCCid(towerId) ;
00773       int towerInTCC = theMapping_->iTT(towerId) ;
00774       (*geomFile_)<<"towerId="<<(*itList)<<" ieta="<<towerId.ietaAbs()<<" iphi="<<towerId.iphi()
00775                   <<" dccNb="<<dccNb<<" tccNb="<<tccNb<<" towerInTCC="<<towerInTCC<<endl ;      
00776     }
00777   }
00778 
00779 }
00780 
00781 void EcalTPGParamBuilder::beginJob(const edm::EventSetup& evtSetup)
00782 {
00783   using namespace edm;
00784   using namespace std;
00785 
00786   std::cout<<"we are in beginJob"<<endl;
00787 
00788   create_header() ; 
00789   std::cout<<"we are in beginJob after create header"<<endl;
00790 
00791   DetId eb(DetId::Ecal,EcalBarrel) ;
00792   DetId ee(DetId::Ecal,EcalEndcap) ;
00793 
00794   std::cout<<"we are in beginJob after detid"<<endl;
00795 
00796   if (writeToFiles_) {
00797     (*out_file_)<<"PHYSICS_EB "<<dec<<eb.rawId()<<std::endl ;
00798     (*out_file_)<<Et_sat_EB_<<" "<<TTF_lowThreshold_EB_<<" "<<TTF_highThreshold_EB_<<std::endl ;
00799     (*out_file_)<<FG_lowThreshold_EB_<<" "<<FG_highThreshold_EB_<<" "
00800                   <<FG_lowRatio_EB_<<" "<<FG_highRatio_EB_<<std::endl ;
00801     (*out_file_) <<std::endl ;
00802 
00803     (*out_file_)<<"PHYSICS_EE "<<dec<<ee.rawId()<<std::endl ;
00804     (*out_file_)<<Et_sat_EE_<<" "<<TTF_lowThreshold_EE_<<" "<<TTF_highThreshold_EE_<<std::endl ;
00805     (*out_file_)<<FG_Threshold_EE_<<" "<<-1<<" "
00806                   <<-1<<" "<<-1<<std::endl ;
00807     (*out_file_) <<std::endl ;
00808   }
00809   std::cout<<"we are in beginJob ending..."<<endl;
00810 
00811 
00812 }
00813 
00814 
00815 
00816 bool EcalTPGParamBuilder::computeLinearizerParam(double theta, double gainRatio, double calibCoeff, std::string subdet, int & mult , int & shift) 
00817 {
00818   /*
00819     Linearization coefficient are determined in order to satisfy:
00820     tpg(ADC_sat) = 1024
00821     where: 
00822     tpg() is a model of the linearized tpg response on 10b 
00823     ADC_sat is the number of ADC count corresponding the Et_sat, the maximum scale of the transverse energy
00824     
00825     Since we have:
00826     Et_sat = xtal_LSB * ADC_sat * gainRatio * calibCoeff * sin(theta)
00827     and a simple model of tpg() being given by:
00828     tpg(X) = [ (X*mult) >> (shift+2) ] >> (sliding+shiftDet) 
00829     we must satisfy:
00830     [ (Et_sat/(xtal_LSB * gainRatio * calibCoeff * sin(theta)) * mult) >> (shift+2) ] >> (sliding+shiftDet) = 1024 
00831     that is:
00832     mult = 1024/Et_sat * xtal_LSB * gainRatio * calibCoeff * sin(theta) * 2^-(sliding+shiftDet+2) * 2^-shift
00833     mult = factor * 2^-shift
00834   */
00835 
00836   // case barrel:
00837   int shiftDet = 2 ;
00838   double ratio = xtal_LSB_EB_/Et_sat_EB_ ;
00839   // case endcap:
00840   if (subdet=="EE") {
00841     shiftDet = 0 ;
00842     ratio = xtal_LSB_EE_/Et_sat_EE_ ;
00843   }
00844 
00845 
00846 
00847   double factor = 1024 * ratio * gainRatio * calibCoeff * sin(theta) * (1 << (sliding_ + shiftDet + 2)) ;
00848   // Let's try first with shift = 0 (trivial solution)
00849   mult = (int)(factor+0.5) ; 
00850   for (shift = 0 ; shift<15 ; shift++) {
00851     if (mult>=128  && mult<256) return true ;
00852     factor *= 2 ; 
00853     mult = (int)(factor+0.5) ;
00854   }
00855   std::cout << "too bad we did not manage to calculate the factor for calib="<<calibCoeff<<endl;
00856   return false ;
00857 }
00858 
00859 void EcalTPGParamBuilder::create_header() 
00860 {
00861   if (!writeToFiles_) return ;
00862   (*out_file_) <<"COMMENT put your comments here"<<std::endl ; 
00863 
00864   (*out_file_) <<"COMMENT ================================="<<std::endl ;
00865   (*out_file_) <<"COMMENT           physics EB structure"<<std::endl ;
00866   (*out_file_) <<"COMMENT"<<std::endl ;
00867   (*out_file_) <<"COMMENT  EtSaturation (GeV), ttf_threshold_Low (GeV), ttf_threshold_High (GeV)"<<std::endl ;
00868   (*out_file_) <<"COMMENT  FG_lowThreshold (GeV), FG_highThreshold (GeV), FG_lowRatio, FG_highRatio"<<std::endl ;
00869   (*out_file_) <<"COMMENT ================================="<<std::endl ;
00870   (*out_file_) <<"COMMENT"<<std::endl ;
00871 
00872   (*out_file_) <<"COMMENT ================================="<<std::endl ;
00873   (*out_file_) <<"COMMENT           physics EE structure"<<std::endl ;
00874   (*out_file_) <<"COMMENT"<<std::endl ;
00875   (*out_file_) <<"COMMENT  EtSaturation (GeV), ttf_threshold_Low (GeV), ttf_threshold_High (GeV)"<<std::endl ;
00876   (*out_file_) <<"COMMENT  FG_Threshold (GeV), dummy, dummy, dummy"<<std::endl ;
00877   (*out_file_) <<"COMMENT ================================="<<std::endl ;
00878   (*out_file_) <<"COMMENT"<<std::endl ;
00879 
00880   (*out_file_) <<"COMMENT ================================="<<std::endl ;
00881   (*out_file_) <<"COMMENT           crystal structure (same for EB and EE)"<<std::endl ;
00882   (*out_file_) <<"COMMENT"<<std::endl ;
00883   (*out_file_) <<"COMMENT  ped, mult, shift [gain12]"<<std::endl ;
00884   (*out_file_) <<"COMMENT  ped, mult, shift [gain6]"<<std::endl ;
00885   (*out_file_) <<"COMMENT  ped, mult, shift [gain1]"<<std::endl ;
00886   (*out_file_) <<"COMMENT ================================="<<std::endl ;
00887   (*out_file_) <<"COMMENT"<<std::endl ;
00888 
00889   (*out_file_) <<"COMMENT ================================="<<std::endl ;
00890   (*out_file_) <<"COMMENT           strip EB structure"<<std::endl ;
00891   (*out_file_) <<"COMMENT"<<std::endl ;
00892   (*out_file_) <<"COMMENT  sliding_window"<<std::endl ;
00893   (*out_file_) <<"COMMENT  weightGroupId"<<std::endl ;
00894   (*out_file_) <<"COMMENT ================================="<<std::endl ;
00895   (*out_file_) <<"COMMENT"<<std::endl ;
00896 
00897   (*out_file_) <<"COMMENT ================================="<<std::endl ;
00898   (*out_file_) <<"COMMENT           strip EE structure"<<std::endl ;
00899   (*out_file_) <<"COMMENT"<<std::endl ;
00900   (*out_file_) <<"COMMENT  sliding_window"<<std::endl ;
00901   (*out_file_) <<"COMMENT  weightGroupId"<<std::endl ;
00902   (*out_file_) <<"COMMENT  threshold_fg strip_lut_fg"<<std::endl ;
00903   (*out_file_) <<"COMMENT ================================="<<std::endl ;
00904   (*out_file_) <<"COMMENT"<<std::endl ;
00905 
00906   (*out_file_) <<"COMMENT ================================="<<std::endl ;
00907   (*out_file_) <<"COMMENT           tower EB structure"<<std::endl ;
00908   (*out_file_) <<"COMMENT"<<std::endl ;
00909   (*out_file_) <<"COMMENT  LUTGroupId"<<std::endl ;
00910   (*out_file_) <<"COMMENT  FgGroupId"<<std::endl ;
00911   (*out_file_) <<"COMMENT ================================="<<std::endl ;
00912   (*out_file_) <<"COMMENT"<<std::endl ;
00913 
00914   (*out_file_) <<"COMMENT ================================="<<std::endl ;
00915   (*out_file_) <<"COMMENT           tower EE structure"<<std::endl ;
00916   (*out_file_) <<"COMMENT"<<std::endl ;
00917   (*out_file_) <<"COMMENT  LUTGroupId"<<std::endl ;
00918   (*out_file_) <<"COMMENT  tower_lut_fg"<<std::endl ;
00919   (*out_file_) <<"COMMENT ================================="<<std::endl ;
00920   (*out_file_) <<"COMMENT"<<std::endl ;
00921   
00922   (*out_file_) <<"COMMENT ================================="<<std::endl ;
00923   (*out_file_) <<"COMMENT           Weight structure"<<std::endl ;
00924   (*out_file_) <<"COMMENT"<<std::endl ;
00925   (*out_file_) <<"COMMENT  weightGroupId"<<std::endl ;
00926   (*out_file_) <<"COMMENT  w0, w1, w2, w3, w4"<<std::endl ;
00927   (*out_file_) <<"COMMENT ================================="<<std::endl ;
00928   (*out_file_) <<"COMMENT"<<std::endl ;
00929 
00930   (*out_file_) <<"COMMENT ================================="<<std::endl ;
00931   (*out_file_) <<"COMMENT           lut structure"<<std::endl ;
00932   (*out_file_) <<"COMMENT"<<std::endl ;
00933   (*out_file_) <<"COMMENT  LUTGroupId"<<std::endl ;
00934   (*out_file_) <<"COMMENT  LUT[1-1024]"<<std::endl ;
00935   (*out_file_) <<"COMMENT ================================="<<std::endl ;
00936   (*out_file_) <<"COMMENT"<<std::endl ;
00937 
00938   (*out_file_) <<"COMMENT ================================="<<std::endl ;
00939   (*out_file_) <<"COMMENT           fg EB structure"<<std::endl ;
00940   (*out_file_) <<"COMMENT"<<std::endl ;
00941   (*out_file_) <<"COMMENT  FgGroupId"<<std::endl ;
00942   (*out_file_) <<"COMMENT  el, eh, tl, th, lut_fg"<<std::endl ;
00943   (*out_file_) <<"COMMENT ================================="<<std::endl ;
00944   (*out_file_) <<"COMMENT"<<std::endl ;
00945 
00946   (*out_file_) <<std::endl ;
00947 }
00948 
00949 
00950 int EcalTPGParamBuilder::uncodeWeight(double weight, int complement2)
00951 {
00952   int iweight ;
00953   uint max = (uint)(pow(2.,complement2)-1) ;
00954   if (weight>0) iweight=int((1<<6)*weight+0.5) ; // +0.5 for rounding pb
00955   else iweight= max - int(-weight*(1<<6)+0.5) +1 ;
00956   iweight = iweight & max ;
00957   return iweight ;
00958 }
00959 
00960 double EcalTPGParamBuilder::uncodeWeight(int iweight, int complement2)
00961 {
00962   double weight = double(iweight)/pow(2., 6.) ;
00963   // test if negative weight:
00964   if ( (iweight & (1<<(complement2-1))) != 0) weight = (double(iweight)-pow(2., complement2))/pow(2., 6.) ;
00965   return weight ;
00966 }
00967 
00968 std::vector<unsigned int> EcalTPGParamBuilder::computeWeights(EcalShape & shape)
00969 {
00970   double timeMax = shape.computeTimeOfMaximum() - shape.computeT0() ; // timeMax w.r.t begining of pulse
00971   double max = shape(timeMax) ;
00972 
00973   double sumf = 0. ;
00974   double sumf2 = 0. ;
00975   for (uint sample = 0 ; sample<nSample_ ; sample++) {
00976     double time = timeMax - ((double)sampleMax_-(double)sample)*25. ;
00977     sumf += shape(time)/max ;
00978     sumf2 += shape(time)/max * shape(time)/max ;
00979   }
00980   double lambda = 1./(sumf2-sumf*sumf/nSample_) ;
00981   double gamma = -lambda*sumf/nSample_ ;
00982   double * weight = new double[nSample_] ;
00983   for (uint sample = 0 ; sample<nSample_ ; sample++) {
00984     double time = timeMax - ((double)sampleMax_-(double)sample)*25. ;
00985     weight[sample] = lambda*shape(time)/max + gamma ;
00986   }
00987 
00988 //   double ampl = 0. ;
00989 //   for (uint sample = 0 ; sample<nSample_ ; sample++) {
00990 //     double time = timeMax - ((double)sampleMax_-(double)sample)*25. ;
00991 //     ampl += weight[sample]*shape(time) ;
00992 //   }
00993 //   std::cout<<max<<" "<<ampl<<std::endl ;
00994 
00995 
00996   int * iweight = new int[nSample_] ;
00997   for (uint sample = 0 ; sample<nSample_ ; sample++)   iweight[sample] = uncodeWeight(weight[sample], complement2_) ;
00998 
00999   // Let's check:  
01000   int isumw  = 0 ;  
01001   for (uint sample = 0 ; sample<nSample_ ; sample++) isumw  += iweight[sample] ;
01002   uint imax = (uint)(pow(2.,int(complement2_))-1) ;
01003   isumw = (isumw & imax ) ;
01004 
01005   // Let's correct for bias if any
01006   if (isumw != 0) {
01007     double min = 99. ;
01008     uint index = 0 ;
01009     if ( (isumw & (1<<(complement2_-1))) != 0) {
01010       // add 1:
01011       for (uint sample = 0 ; sample<nSample_ ; sample++) {
01012         int new_iweight = iweight[sample]+1 ; 
01013         double new_weight = uncodeWeight(new_iweight, complement2_) ;
01014         if (fabs(new_weight-weight[sample])<min) {
01015           min = fabs(new_weight-weight[sample]) ;
01016           index = sample ;
01017         }
01018       }
01019       iweight[index] ++ ; 
01020     } else {
01021       // Sub 1:
01022       for (uint sample = 0 ; sample<nSample_ ; sample++) {
01023         int new_iweight = iweight[sample]-1 ;    
01024         double new_weight = uncodeWeight(new_iweight, complement2_) ;
01025         if (fabs(new_weight-weight[sample])<min) {
01026           min = fabs(new_weight-weight[sample]) ;
01027           index = sample ;
01028         }
01029       }
01030       iweight[index] -- ; 
01031     } 
01032   }
01033 
01034   std::vector<unsigned int> theWeights ;
01035   for (uint sample = 0 ; sample<nSample_ ; sample++) theWeights.push_back(iweight[sample]) ;
01036 
01037   delete weight ;
01038   delete iweight ;
01039   return theWeights ;
01040 }
01041 
01042 void EcalTPGParamBuilder::computeLUT(int * lut, std::string det) 
01043 {
01044   double Et_sat = Et_sat_EB_ ;
01045   double LUT_threshold = LUT_threshold_EB_ ;
01046   double LUT_stochastic = LUT_stochastic_EB_ ;
01047   double LUT_noise = LUT_noise_EB_ ;
01048   double LUT_constant = LUT_constant_EB_ ;
01049   double TTF_lowThreshold = TTF_lowThreshold_EB_ ;
01050   double TTF_highThreshold = TTF_highThreshold_EB_ ;
01051   if (det == "EE") {
01052     Et_sat = Et_sat_EE_ ;
01053     LUT_threshold = LUT_threshold_EE_ ;
01054     LUT_stochastic = LUT_stochastic_EE_ ;
01055     LUT_noise = LUT_noise_EE_ ;
01056     LUT_constant = LUT_constant_EE_ ;
01057     TTF_lowThreshold = TTF_lowThreshold_EE_ ;
01058     TTF_highThreshold = TTF_highThreshold_EE_ ;
01059   }
01060 
01061   // initialisation with identity
01062   for (int i=0 ; i<1024 ; i++) {
01063     lut[i] = i ;
01064     if (lut[i]>0xff) lut[i] = 0xff ;
01065   }
01066 
01067   // case linear LUT
01068   if (LUT_option_ == "Linear") {
01069     int mylut = 0 ;
01070     for (int i=0 ; i<1024 ; i++) {
01071       lut[i] = mylut ;
01072       if ((i+1)%4 == 0 ) mylut++ ;
01073     }
01074   }
01075 
01076   // case LUT following Ecal resolution
01077   if (LUT_option_ == "EcalResolution") {
01078     TF1 * func = new TF1("func",oneOverEtResolEt, 0., Et_sat,3) ;
01079     func->SetParameters(LUT_stochastic, LUT_noise, LUT_constant) ;
01080     double norm = func->Integral(0., Et_sat) ;
01081     for (int i=0 ; i<1024 ; i++) {   
01082       double Et = i*Et_sat/1024. ;
01083       lut[i] =  int(0xff*func->Integral(0., Et)/norm + 0.5) ;
01084     }
01085   }
01086 
01087   // Now, add TTF thresholds to LUT and apply LUT threshold if needed
01088   for (int j=0 ; j<1024 ; j++) {
01089     double Et_GeV = Et_sat/1024*(j+0.5) ;
01090     int ttf = 0x0 ;    
01091     if (Et_GeV >= TTF_highThreshold) ttf = 3 ;
01092     if (Et_GeV >= TTF_lowThreshold && Et_GeV < TTF_highThreshold) ttf = 1 ;
01093     ttf = ttf << 8 ;
01094     lut[j] += ttf ;
01095     if (Et_GeV <= LUT_threshold) lut[j] = 0 ;
01096   }
01097 
01098 }
01099 
01100 void EcalTPGParamBuilder::getCoeff(coeffStruc & coeff, const EcalIntercalibConstantMap & calibMap, uint rawId)
01101 {
01102   // get current intercalibration coeff
01103   coeff.calibCoeff_ = 1. ;
01104   EcalIntercalibConstantMap::const_iterator icalit = calibMap.find(rawId);
01105   if( icalit != calibMap.end() ) coeff.calibCoeff_ = (*icalit) ;
01106   else std::cout<<"getCoeff: "<<rawId<<" not found in EcalIntercalibConstantMap"<<std::endl ;
01107 }
01108 
01109 void EcalTPGParamBuilder::getCoeff(coeffStruc & coeff, const EcalGainRatioMap & gainMap, uint rawId)
01110 {
01111   // get current gain ratio
01112   coeff.gainRatio_[0]  = 1. ;
01113   coeff.gainRatio_[1]  = 2. ;
01114   coeff.gainRatio_[2]  = 12. ;
01115   EcalGainRatioMap::const_iterator gainIter = gainMap.find(rawId);
01116   if (gainIter != gainMap.end()) {
01117     const EcalMGPAGainRatio & aGain = (*gainIter) ;
01118     coeff.gainRatio_[1] = aGain.gain12Over6() ;
01119     coeff.gainRatio_[2] = aGain.gain6Over1() * aGain.gain12Over6() ;
01120   }
01121   else std::cout<<"getCoeff: "<<rawId<<" not found in EcalGainRatioMap"<<std::endl ;
01122 }
01123 
01124 void EcalTPGParamBuilder::getCoeff(coeffStruc & coeff, const EcalPedestalsMap & pedMap, uint rawId)
01125 {
01126   // get current pedestal
01127   coeff.pedestals_[0] = 0 ;
01128   coeff.pedestals_[1] = 0 ;
01129   coeff.pedestals_[2] = 0 ;
01130   EcalPedestalsMapIterator pedIter = pedMap.find(rawId);
01131   if (pedIter != pedMap.end()) {
01132     EcalPedestals::Item aped = (*pedIter);
01133     coeff.pedestals_[0] = int(aped.mean_x12 + 0.5) ; 
01134     coeff.pedestals_[1] = int(aped.mean_x6 + 0.5) ;
01135     coeff.pedestals_[2] = int(aped.mean_x1 + 0.5) ;
01136   }
01137   else std::cout<<"getCoeff: "<<rawId<<" not found in EcalPedestalsMap"<<std::endl ;
01138 }
01139 
01140 void EcalTPGParamBuilder::getCoeff(coeffStruc & coeff, const map<EcalLogicID, MonPedestalsDat> & pedMap, const EcalLogicID & logicId)
01141 {
01142   // get current pedestal
01143   coeff.pedestals_[0] = 0 ;
01144   coeff.pedestals_[1] = 0 ;
01145   coeff.pedestals_[2] = 0 ;
01146 
01147   map<EcalLogicID, MonPedestalsDat>::const_iterator it =  pedMap.find(logicId);
01148   if (it != pedMap.end()) {
01149     MonPedestalsDat ped = it->second ;
01150     coeff.pedestals_[0] = int(ped.getPedMeanG12() + 0.5) ; 
01151     coeff.pedestals_[1] = int(ped.getPedMeanG6() + 0.5) ; 
01152     coeff.pedestals_[2] = int(ped.getPedMeanG1() + 0.5) ; 
01153   } 
01154   else std::cout<<"getCoeff: "<<logicId.getID1()<<", "<<logicId.getID2()<<", "<<logicId.getID3()
01155                 <<" not found in map<EcalLogicID, MonPedestalsDat>"<<std::endl ;
01156 }
01157 
01158 void EcalTPGParamBuilder::computeFineGrainEBParameters(uint & lowRatio, uint & highRatio,
01159                                                        uint & lowThreshold, uint & highThreshold, uint & lut)
01160 {
01161   lowRatio = int(0x80*FG_lowRatio_EB_ + 0.5) ;
01162   if (lowRatio>0x7f) lowRatio = 0x7f ;
01163   highRatio = int(0x80*FG_highRatio_EB_ + 0.5) ;
01164   if (highRatio>0x7f) highRatio = 0x7f ;
01165   
01166   // lsb at the stage of the FG calculation is:
01167   double lsb_FG = Et_sat_EB_/1024./4 ;
01168   lowThreshold = int(FG_lowThreshold_EB_/lsb_FG+0.5) ;
01169   if (lowThreshold>0xff) lowThreshold = 0xff ;
01170   highThreshold = int(FG_highThreshold_EB_/lsb_FG+0.5) ;
01171   if (highThreshold>0xff) highThreshold = 0xff ;
01172 
01173   // FG lut: FGVB response is LUT(adress) where adress is: 
01174   // bit3: maxof2/ET >= lowRatio, bit2: maxof2/ET >= highRatio, bit1: ET >= lowThreshold, bit0: ET >= highThreshold
01175   // FGVB =1 if jet-like (veto active), =0 if E.M.-like
01176   // the condition for jet-like is: ET>Threshold and  maxof2/ET < Ratio (only TT with enough energy are vetoed)
01177 
01178   // With the following lut, what matters is only max(TLow, Thigh) and max(Elow, Ehigh)
01179   // So, jet-like if maxof2/ettot<max(TLow, Thigh) && ettot >= max(Elow, Ehigh)
01180   if (FG_lut_EB_ == 0) lut = 0x0888 ; 
01181   else lut = FG_lut_EB_ ; // let's use the users value (hope he/she knows what he/she does!)
01182 }
01183 
01184 void EcalTPGParamBuilder::computeFineGrainEEParameters(uint & threshold, uint & lut_strip, uint & lut_tower) 
01185 {
01186   // lsb for EE:
01187   double lsb_FG = Et_sat_EE_/1024. ; // FIXME is it true????
01188   threshold = int(FG_Threshold_EE_/lsb_FG+0.5) ;
01189   lut_strip = FG_lut_strip_EE_  ;
01190   lut_tower = FG_lut_tower_EE_  ;
01191 }
01192 

Generated on Tue Jun 9 17:25:19 2009 for CMSSW by  doxygen 1.5.4