Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2021-02-14 13:31:11

0001 /**
0002  * \class L1GtVhdlWriterCore
0003  *
0004  *
0005  * Description: a class to deal with VHDL template files
0006  *
0007  * Implementation:
0008  *    <TODO: enter implementation details>
0009  *
0010  * \author: Philipp Wagner
0011  *
0012  *
0013  */
0014 
0015 // this class header
0016 #include "L1TriggerConfig/L1GtConfigProducers/interface/L1GtVhdlWriterCore.h"
0017 
0018 // system include files
0019 #include <iostream>
0020 #include <fstream>
0021 #include <map>
0022 #include <string>
0023 #include <sstream>
0024 #include <vector>
0025 #include <sys/stat.h>
0026 #include <algorithm>
0027 
0028 // CMSSW headers
0029 #include "L1TriggerConfig/L1GtConfigProducers/interface/L1GtVhdlTemplateFile.h"
0030 
0031 #include "CondFormats/L1TObjects/interface/L1GtFwd.h"
0032 #include "CondFormats/L1TObjects/interface/L1GtTriggerMenuFwd.h"
0033 
0034 #include "CondFormats/L1TObjects/interface/L1GtCaloTemplate.h"
0035 #include "CondFormats/L1TObjects/interface/L1GtMuonTemplate.h"
0036 #include "CondFormats/L1TObjects/interface/L1GtEnergySumTemplate.h"
0037 #include "CondFormats/L1TObjects/interface/L1GtJetCountsTemplate.h"
0038 #include "CondFormats/L1TObjects/interface/L1GtStableParameters.h"
0039 
0040 #include "CondFormats/L1TObjects/interface/L1GtTriggerMenu.h"
0041 
0042 #include "L1TriggerConfig/L1GtConfigProducers/interface/L1GtVhdlTemplateFile.h"
0043 #include "L1TriggerConfig/L1GtConfigProducers/interface/L1GtVhdlWriterBitManager.h"
0044 #include "L1TriggerConfig/L1GtConfigProducers/interface/L1GtVhdlDefinitions.h"
0045 
0046 #include "CondFormats/L1TObjects/interface/L1GtStableParameters.h"
0047 
0048 // constructor(s)
0049 L1GtVhdlWriterCore::L1GtVhdlWriterCore(const std::string &templatesDirectory,
0050                                        const std::string &outputDirectory,
0051                                        const bool &debug) {
0052   // set templates directory
0053   vhdlDir_ = templatesDirectory;
0054 
0055   // set output directory
0056   outputDir_ = outputDirectory;
0057 
0058   // Get maps
0059   L1GtVhdlDefinitions maps;
0060 
0061   objType2Str_ = maps.getObj2StrMap();
0062   caloType2Int_ = maps.getCalo2IntMap();
0063   condType2Str_ = maps.getCond2StrMap();
0064 
0065   // fill calo object vector
0066   caloObjects_.push_back(IsoEG);
0067   caloObjects_.push_back(NoIsoEG);
0068   caloObjects_.push_back(CenJet);
0069   caloObjects_.push_back(ForJet);
0070   caloObjects_.push_back(TauJet);
0071 
0072   esumObjects_.push_back(HTT);
0073   esumObjects_.push_back(ETT);
0074   esumObjects_.push_back(ETM);
0075 
0076   // prepare number of condition vector with two empty string vectors for the two condition chips
0077   std::vector<std::string> temp;
0078   numberOfConditions_.push_back(temp);
0079   numberOfConditions_.push_back(temp);
0080 
0081   // set debug mode
0082   debugMode_ = debug;
0083 }
0084 
0085 // destructor
0086 L1GtVhdlWriterCore::~L1GtVhdlWriterCore() {
0087   // empty
0088 }
0089 
0090 bool L1GtVhdlWriterCore::returnConditionsOfOneClass(const L1GtConditionType &type,
0091                                                     const L1GtConditionCategory &category,
0092                                                     const L1GtObject &object,
0093                                                     const ConditionMap &map,
0094                                                     ConditionMap &outputMap) {
0095   bool status = false;
0096 
0097   ConditionMap::const_iterator condIter = map.begin();
0098   while (condIter != map.end()) {
0099     if (condIter->second->condCategory() == category && condIter->second->condType() == type &&
0100         (condIter->second->objectType())[0] == object) {
0101       outputMap[condIter->first] = condIter->second;
0102       status = true;
0103     }
0104     condIter++;
0105   }
0106 
0107   return status;
0108 }
0109 
0110 bool L1GtVhdlWriterCore::findObjectType(const L1GtObject &object, ConditionMap &map) {
0111   bool status = false;
0112 
0113   ConditionMap::iterator condIter = map.begin();
0114   while (condIter != map.end()) {
0115     for (unsigned int i = 0; i < (condIter->second->objectType()).size(); i++) {
0116       if (condIter->second->objectType()[i] == object) {
0117         status = true;
0118         break;
0119       }
0120     }
0121 
0122     if (status)
0123       break;
0124     condIter++;
0125   }
0126 
0127   return status;
0128 }
0129 
0130 void L1GtVhdlWriterCore::getMuonSetupContentFromTriggerMenu(const unsigned short int &condChip,
0131                                                             std::map<std::string, std::string> &muonParameters) {
0132   // vector containing all relevant types for muon conditions
0133   std::vector<L1GtConditionType> muonConditionTypes;
0134 
0135   muonConditionTypes.push_back(Type1s);
0136   muonConditionTypes.push_back(Type2s);
0137   muonConditionTypes.push_back(Type2wsc);
0138   muonConditionTypes.push_back(Type3s);
0139   muonConditionTypes.push_back(Type4s);
0140 
0141   for (unsigned int i = 0; i < muonConditionTypes.size(); i++) {
0142     //std::cout<<i<<std::endl;
0143 
0144     ConditionMap MuonConditions1s;
0145 
0146     countCondsAndAdd2NumberVec(
0147         muonConditionTypes.at(i), CondMuon, Mu, (*conditionMap_).at(condChip - 1), MuonConditions1s, condChip);
0148 
0149     /*
0150          // Get the absoloute amount of conditions
0151          std::string initstr="CONSTANT nr_"+objType2Str_[Mu]+"_"+condType2Str_[muonConditionTypes.at(i)]+" : integer := ";
0152 
0153          if (returnConditionsOfOneClass(muonConditionTypes.at(i),CondMuon,Mu,conditionMap_.at(condChip-1), MuonConditions1s))
0154          initstr+=(int2str(MuonConditions1s.size())+";");
0155          else
0156          initstr+=("0;");
0157 
0158          numberOfConditions_.at(condChip-1).push_back(initstr);
0159 
0160          */
0161 
0162     //std::cout<< std::hex << (*myObjectParameter).at(0).etThreshold << std::endl;
0163     unsigned int counter = 0;
0164 
0165     for (ConditionMap::const_iterator iterCond = MuonConditions1s.begin(); iterCond != MuonConditions1s.end();
0166          iterCond++) {
0167       // add this condition to name -> integer conversion map
0168       conditionToIntegerMap_[iterCond->first] = counter;
0169 
0170       L1GtMuonTemplate *m_gtMuonTemplate = static_cast<L1GtMuonTemplate *>(iterCond->second);
0171       const std::vector<L1GtMuonTemplate::ObjectParameter> *op = m_gtMuonTemplate->objectParameter();
0172 
0173       if (muonConditionTypes.at(i) == Type1s) {
0174         // build eta
0175         muonParameters["eta_1_s"] += (bm_.buildEtaMuon(op, 1, counter));
0176 
0177         // add the parameters to parameter map
0178         muonParameters["phi_h_1_s"] += bm_.buildPhiMuon(op, 1, counter, true);
0179         muonParameters["phi_l_1_s"] += bm_.buildPhiMuon(op, 1, counter, false);
0180 
0181         if (debugMode_) {
0182           muonParameters["phi_l_1_s"] += ("--" + iterCond->first + "\n");
0183           muonParameters["phi_h_1_s"] += ("--" + iterCond->first + "\n");
0184           muonParameters["eta_1_s"] += ("--" + iterCond->first + "\n");
0185         }
0186 
0187       } else
0188 
0189           if (muonConditionTypes.at(i) == Type2s) {
0190         // build eta
0191         muonParameters["eta_2_s"] += (bm_.buildEtaMuon(op, 2, counter));
0192 
0193         // add the parameters to parameter map
0194         muonParameters["phi_h_2_s"] += bm_.buildPhiMuon(op, 2, counter, true);
0195         muonParameters["phi_l_2_s"] += bm_.buildPhiMuon(op, 2, counter, false);
0196 
0197         if (debugMode_) {
0198           muonParameters["phi_l_2_s"] += ("--" + iterCond->first + "\n");
0199           muonParameters["phi_h_2_s"] += ("--" + iterCond->first + "\n");
0200           muonParameters["eta_2_s"] += ("--" + iterCond->first + "\n");
0201         }
0202 
0203       } else
0204           //m_gtMuonTemplate->print(std::cout);
0205 
0206           if (muonConditionTypes.at(i) == Type3s) {
0207         // build eta
0208         muonParameters["eta_3"] += (bm_.buildEtaMuon(op, 3, counter));
0209 
0210         // add the parameters to parameter map
0211         muonParameters["phi_h_3"] += bm_.buildPhiMuon(op, 3, counter, true);
0212         muonParameters["phi_l_3"] += bm_.buildPhiMuon(op, 3, counter, false);
0213 
0214         if (debugMode_) {
0215           muonParameters["phi_l_3"] += ("--" + iterCond->first + "\n");
0216           muonParameters["phi_h_3"] += ("--" + iterCond->first + "\n");
0217           muonParameters["eta_3"] += ("--" + iterCond->first + "\n");
0218         }
0219       }
0220 
0221       if (muonConditionTypes.at(i) == Type4s) {
0222         // build eta
0223         muonParameters["eta_4"] += (bm_.buildEtaMuon(op, 4, counter));
0224 
0225         // add the parameters to parameter map
0226         muonParameters["phi_h_4"] += bm_.buildPhiMuon(op, 4, counter, true);
0227         muonParameters["phi_l_4"] += bm_.buildPhiMuon(op, 4, counter, false);
0228 
0229         if (debugMode_) {
0230           muonParameters["phi_l_4"] += ("--" + iterCond->first + "\n");
0231           muonParameters["phi_h_4"] += ("--" + iterCond->first + "\n");
0232           muonParameters["eta_4"] += ("--" + iterCond->first + "\n");
0233         }
0234       }
0235 
0236       if (muonConditionTypes.at(i) == Type2wsc) {
0237         const L1GtMuonTemplate::CorrelationParameter *cp = m_gtMuonTemplate->correlationParameter();
0238 
0239         // build eta
0240         muonParameters["eta_2_wsc"] += (bm_.buildEtaMuon(op, 2, counter));
0241 
0242         // build phi
0243         muonParameters["phi_h_2_wsc"] += bm_.buildPhiMuon(op, 2, counter, true);
0244         muonParameters["phi_l_2_wsc"] += bm_.buildPhiMuon(op, 2, counter, false);
0245 
0246         // build delta_eta
0247         std::ostringstream dEta;
0248         muonParameters["delta_eta"] += bm_.buildDeltaEtaMuon(cp, counter);
0249 
0250         // build delta_phi
0251         muonParameters["delta_phi"] += bm_.buildDeltaPhiMuon(cp, counter);
0252 
0253         if (debugMode_) {
0254           muonParameters["eta_2_wsc"] += ("--" + iterCond->first + "\n");
0255           muonParameters["phi_h_2_wsc"] += ("--" + iterCond->first + "\n");
0256           muonParameters["phi_l_2_wsc"] += ("--" + iterCond->first + "\n");
0257           muonParameters["delta_eta"] += ("--" + iterCond->first + "\n");
0258           muonParameters["delta_phi"] += ("--" + iterCond->first + "\n");
0259         }
0260       }
0261       counter++;
0262     }
0263   }
0264 }
0265 
0266 bool L1GtVhdlWriterCore::getCaloSetupContentFromTriggerMenu(const unsigned short int &condChip,
0267                                                             std::map<std::string, std::string> &caloParameters,
0268                                                             const L1GtObject &caloObject) {
0269   // vector containing all relevant types for calo conditions
0270   std::vector<L1GtConditionType> caloConditionTypes;
0271 
0272   caloConditionTypes.push_back(Type1s);
0273   caloConditionTypes.push_back(Type2s);
0274   caloConditionTypes.push_back(Type2wsc);
0275   caloConditionTypes.push_back(Type4s);
0276 
0277   for (unsigned int i = 0; i < caloConditionTypes.size(); i++) {
0278     unsigned int counter = 0;
0279 
0280     ConditionMap caloConditions;
0281 
0282     // stores all conditions of type given in the first three parameters
0283     countCondsAndAdd2NumberVec(
0284         caloConditionTypes.at(i), CondCalo, caloObject, (*conditionMap_).at(condChip - 1), caloConditions, condChip);
0285 
0286     for (ConditionMap::const_iterator iterCond = caloConditions.begin(); iterCond != caloConditions.end(); iterCond++) {
0287       // add this condition to name -> integer conversion map
0288       conditionToIntegerMap_[iterCond->first] = counter;
0289 
0290       L1GtCaloTemplate *m_gtCaloTemplate = static_cast<L1GtCaloTemplate *>(iterCond->second);
0291       const std::vector<L1GtCaloTemplate::ObjectParameter> *op = m_gtCaloTemplate->objectParameter();
0292 
0293       if (caloConditionTypes.at(i) == Type1s) {
0294         //= static_cast<std::vector<L1GtCaloTemplate::ObjectPaenergySumParameter+=rameter*> >(op);
0295 
0296         // build eta
0297         caloParameters["eta_1_s"] += (bm_.buildEtaCalo(op, 1, counter));
0298 
0299         caloParameters["phi_1_s"] += bm_.buildPhiCalo(op, 1, counter);
0300 
0301         if (debugMode_) {
0302           caloParameters["eta_1_s"] += ("--" + iterCond->first + "\n");
0303           caloParameters["phi_1_s"] += ("--" + iterCond->first + "\n");
0304         }
0305 
0306       } else if (caloConditionTypes.at(i) == Type2s) {
0307         // build eta
0308         caloParameters["eta_2_s"] += (bm_.buildEtaCalo(op, 2, counter));
0309 
0310         // add the parameters to parameter map
0311         caloParameters["phi_2_s"] += bm_.buildPhiCalo(op, 2, counter);
0312 
0313         if (debugMode_) {
0314           caloParameters["eta_2_s"] += ("--" + iterCond->first + "\n");
0315           caloParameters["phi_2_s"] += ("--" + iterCond->first + "\n");
0316         }
0317 
0318       } else if (caloConditionTypes.at(i) == Type4s) {
0319         // build eta
0320         caloParameters["eta_4"] += (bm_.buildEtaCalo(op, 4, counter));
0321 
0322         // add the parameters to parameter map
0323         caloParameters["phi_4"] += bm_.buildPhiCalo(op, 4, counter);
0324 
0325         if (debugMode_) {
0326           caloParameters["eta_4"] += ("--" + iterCond->first + "\n");
0327           caloParameters["phi_4"] += ("--" + iterCond->first + "\n");
0328         }
0329 
0330       } else if (caloConditionTypes.at(i) == Type2wsc) {
0331         const L1GtCaloTemplate::CorrelationParameter *cp = m_gtCaloTemplate->correlationParameter();
0332 
0333         // build eta
0334         caloParameters["eta_2_wsc"] += (bm_.buildEtaCalo(op, 2, counter));
0335 
0336         // build phi
0337         caloParameters["phi_2_wsc"] += bm_.buildPhiCalo(op, 2, counter);
0338 
0339         // build delta_eta
0340         caloParameters["delta_eta"] += bm_.buildDeltaEtaCalo(cp, counter);
0341 
0342         // build delta_phi
0343         caloParameters["delta_phi"] += bm_.buildDeltaPhiCalo(cp, counter);
0344 
0345         if (debugMode_) {
0346           caloParameters["eta_2_wsc"] += ("--" + iterCond->first + "\n");
0347           caloParameters["phi_2_wsc"] += ("--" + iterCond->first + "\n");
0348           caloParameters["delta_eta"] += ("--" + iterCond->first + "\n");
0349           caloParameters["delta_phi"] += ("--" + iterCond->first + "\n");
0350         }
0351       }
0352 
0353       counter++;
0354     }
0355   }
0356 
0357   return true;
0358 }
0359 
0360 bool L1GtVhdlWriterCore::getEsumsSetupContentFromTriggerMenu(const unsigned short int &condChip,
0361                                                              const L1GtObject &object,
0362                                                              std::string &energySumParameter) {
0363   L1GtConditionType type;
0364 
0365   unsigned int counter = 0;
0366 
0367   if (object == HTT)
0368     type = TypeHTT;
0369   else if (object == ETM)
0370     type = TypeETM;
0371   else if (object == ETT)
0372     type = TypeETT;
0373 
0374   ConditionMap esumsConditions;
0375   // stores all conditions of type given in the first three parameters
0376   countCondsAndAdd2NumberVec(type, CondEnergySum, object, (*conditionMap_).at(condChip - 1), esumsConditions, condChip);
0377 
0378   for (ConditionMap::const_iterator iterCond = esumsConditions.begin(); iterCond != esumsConditions.end(); iterCond++) {
0379     L1GtEnergySumTemplate *energySumTempl = static_cast<L1GtEnergySumTemplate *>(iterCond->second);
0380     const std::vector<L1GtEnergySumTemplate::ObjectParameter> *op = energySumTempl->objectParameter();
0381 
0382     if (!bm_.buildPhiEnergySum(op, 1, counter).empty())
0383       energySumParameter += bm_.buildPhiEnergySum(op, 1, counter);
0384 
0385     if (debugMode_) {
0386       energySumParameter += ("--" + iterCond->first + "\n");
0387     }
0388 
0389     conditionToIntegerMap_[(iterCond->first)] = counter;
0390 
0391     counter++;
0392   }
0393 
0394   return true;
0395 }
0396 
0397 bool L1GtVhdlWriterCore::getSubstParamCommonFromTriggerMenu(const unsigned short int &condChip,
0398                                                             L1GtVhdlTemplateFile &particle,
0399                                                             const L1GtObject &object,
0400                                                             const L1GtConditionCategory &category,
0401                                                             std::string &parameterStr) {
0402   std::map<L1GtConditionType, std::string> condType2Strcopy = condType2Str_;
0403 
0404   // make a copy since types will deleted later after they are processed
0405   std::map<L1GtConditionType, std::string>::iterator typeIterator = condType2Strcopy.begin();
0406 
0407   while (typeIterator != condType2Strcopy.end()) {
0408     ConditionMap outputMap;
0409 
0410     if (returnConditionsOfOneClass(
0411             (*typeIterator).first, category, object, (*conditionMap_).at(condChip - 1), outputMap)) {
0412       // special treatment for jet counts in buildCodChipParameters
0413       if (object != JetCounts) {
0414         std::string tempStr2 = particle.returnParameterMap()[stringConstantCommon_];
0415         while (particle.findAndReplaceString(tempStr2, sp(substParamParticle_), objType2Str_[object]))
0416           ;
0417         while (particle.findAndReplaceString(tempStr2, sp(substParamType_), condType2Str_[(*typeIterator).first]))
0418           ;
0419         parameterStr += (tempStr2 + "\n\n");
0420 
0421         //parameterStr+=(tempStr2+"<= '0';\n");
0422 
0423         // remove this type since it was already processed
0424         condType2Strcopy.erase(typeIterator);
0425       }
0426     }
0427 
0428     typeIterator++;
0429   }
0430 
0431   return true;
0432 }
0433 
0434 bool L1GtVhdlWriterCore::getCondChipVhdContentFromTriggerMenu(const unsigned short int &condChip,
0435                                                               std::map<std::string, L1GtVhdlTemplateFile> &templates,
0436                                                               std::map<std::string, std::string> &commonParams) {
0437   // open the necessary internal templates
0438   L1GtVhdlTemplateFile muon, calo, esums, jet;
0439 
0440   muon.open(vhdlDir_ + "InternalTemplates/muon", true);
0441   muon.substitute("particle", "muon");
0442 
0443   calo.open(vhdlDir_ + "InternalTemplates/calo", true);
0444   esums.open(vhdlDir_ + "InternalTemplates/esums", true);
0445   jet.open(vhdlDir_ + "InternalTemplates/jet_cnts", true);
0446 
0447   /*
0448      charge1s.open(vhdlDir_+"InternalTemplates/charge_1s",false);
0449      charge2s.open(vhdlDir_+"InternalTemplates/charge_2s",false);
0450      charge2wsc.open(vhdlDir_+"InternalTemplates/charge_2_wsc",false);
0451      charge3s.open(vhdlDir_+"InternalTemplates/charge_3",false);
0452      charge4s.open(vhdlDir_+"InternalTemplates/charge_4",false);
0453      */
0454 
0455   // only for jet_cnts common parameter relevant since common parameter is build in this routine
0456   std::vector<unsigned int> processedTypes;
0457 
0458   //-------------------------------------build the common parameters-------------------------------------------
0459 
0460   // build $(muon_common)
0461   getSubstParamCommonFromTriggerMenu(condChip, muon, Mu, CondMuon, commonParams["muon_common"]);
0462 
0463   // build $(calo_common) - loop over all calo objects
0464   std::vector<L1GtObject>::iterator caloObjIter = caloObjects_.begin();
0465 
0466   while (caloObjIter != caloObjects_.end()) {
0467     getSubstParamCommonFromTriggerMenu(condChip, muon, (*caloObjIter), CondCalo, commonParams["calo_common"]);
0468     caloObjIter++;
0469   }
0470 
0471   // build $(esums_common) - loop over all esums objects
0472   std::vector<L1GtObject>::iterator esumObjIter = esumObjects_.begin();
0473 
0474   while (esumObjIter != esumObjects_.end()) {
0475     getSubstParamCommonFromTriggerMenu(condChip, esums, (*esumObjIter), CondEnergySum, commonParams["esums_common"]);
0476     esumObjIter++;
0477   }
0478 
0479   //--------------------------------------build the parameter maps----------------------------------------------
0480 
0481   // loop over condition map
0482   for (ConditionMap::const_iterator iterCond = (*conditionMap_).at(condChip - 1).begin();
0483        iterCond != (*conditionMap_).at(condChip - 1).end();
0484        iterCond++) {
0485     switch ((iterCond->second)->condCategory()) {
0486       case CondMuon: {
0487         int cond2int;
0488         if (!getIntVal(conditionToIntegerMap_, (iterCond->first), cond2int)) {
0489           msg("Panik! Condition " + (iterCond->first) + " does not have a integer equivalent!");
0490           break;
0491         }
0492 
0493         std::string intVal = index4CondChipVhd(cond2int);
0494 
0495         L1GtVhdlTemplateFile muoncopy = muon;
0496 
0497         muoncopy.substitute("type", condType2Str_[(iterCond->second)->condType()]);
0498 
0499         muoncopy.substitute("ser_no", intVal);
0500 
0501         muoncopy.substitute("name", iterCond->first);
0502 
0503         if ((iterCond->second)->condType() == Type1s) {
0504           muoncopy.substitute(substParamCharge_, muon.getInternalParameter(stringConstantCharge1s_));
0505         } else if ((iterCond->second)->condType() == Type2s) {
0506           muoncopy.substitute(substParamCharge_, muon.getInternalParameter(stringConstantCharge2s_));
0507         } else if ((iterCond->second)->condType() == Type2wsc) {
0508           muoncopy.substitute(substParamCharge_, muon.getInternalParameter(stringConstantCharge2wsc_));
0509         } else if ((iterCond->second)->condType() == Type3s) {
0510           muoncopy.substitute(substParamCharge_, muon.getInternalParameter(stringConstantCharge3s_));
0511         } else if ((iterCond->second)->condType() == Type4s) {
0512           muoncopy.substitute(substParamCharge_, muon.getInternalParameter(stringConstantCharge4s_));
0513         }
0514 
0515         std::string tempStr = muoncopy.returnParameterMap()["PREALGO"];
0516 
0517         muoncopy.findAndReplaceString(tempStr, "$(particle)", "muon");
0518         muoncopy.findAndReplaceString(tempStr, "$(ser_no)", intVal);
0519         muoncopy.findAndReplaceString(tempStr, "$(type)", condType2Str_[(iterCond->second)->condType()]);
0520 
0521         muoncopy.append(tempStr);
0522 
0523         muoncopy.removeEmptyLines();
0524 
0525         // add the processed internal template to parameter map
0526         templates["muon"].append(muoncopy);
0527 
0528       } break;
0529 
0530       case CondCalo: {
0531         int cond2int;
0532 
0533         if (!getIntVal(conditionToIntegerMap_, (iterCond->first), cond2int)) {
0534           msg("Panik! Condition " + (iterCond->first) + " does not have a integer equivalent!");
0535           break;
0536         }
0537 
0538         std::string intVal = index4CondChipVhd(cond2int);
0539 
0540         L1GtVhdlTemplateFile calocopy = calo;
0541 
0542         calocopy.substitute("type", condType2Str_[(iterCond->second)->condType()]);
0543         calocopy.substitute("particle", objType2Str_[((iterCond->second)->objectType()).at(0)]);
0544         calocopy.substitute("name", iterCond->first);
0545         calocopy.substitute("ser_no", intVal);
0546         calocopy.substitute("calo_nr", caloType2Int_[((iterCond->second)->objectType()).at(0)]);
0547 
0548         // builds something like tau_1_s(20));
0549         calocopy.append(objType2Str_[((iterCond->second)->objectType()).at(0)] + "_" +
0550                         condType2Str_[(iterCond->second)->condType()] + "(" + intVal + "));");
0551 
0552         templates["calo"].append(calocopy);
0553 
0554       } break;
0555 
0556       case CondEnergySum: {
0557         int cond2int;
0558 
0559         if (!getIntVal(conditionToIntegerMap_, (iterCond->first), cond2int)) {
0560           msg("Panik! Condition " + (iterCond->first) + " does not have a integer equivalent!");
0561           break;
0562         }
0563 
0564         std::string intVal = index4CondChipVhd(cond2int);
0565 
0566         L1GtVhdlTemplateFile esumscopy = esums;
0567 
0568         esumscopy.substitute("type", condType2Str_[(iterCond->second)->condType()]);
0569         esumscopy.substitute("particle", objType2Str_[((iterCond->second)->objectType()).at(0)]);
0570         esumscopy.substitute("name", iterCond->first);
0571         esumscopy.substitute("ser_no", intVal);
0572 
0573         if (((iterCond->second)->objectType()).at(0) == ETM)
0574           esumscopy.substitute("if_etm_then_1_else_0", "1");
0575         else
0576           esumscopy.substitute("if_etm_then_1_else_0", "0");
0577 
0578         // builds something like htt_cond(4));
0579         esumscopy.append(objType2Str_[((iterCond->second)->objectType()).at(0)] + "_" +
0580                          condType2Str_[(iterCond->second)->condType()] + "(" + intVal + "));");
0581 
0582         templates["esums"].append(esumscopy);
0583       }
0584 
0585       break;
0586 
0587       case CondJetCounts: {
0588         // build the common parameter for the jet counts
0589 
0590         L1GtJetCountsTemplate *jetsTemplate = static_cast<L1GtJetCountsTemplate *>(iterCond->second);
0591 
0592         int nObjects = iterCond->second->nrObjects();
0593 
0594         const std::vector<L1GtJetCountsTemplate::ObjectParameter> *op = jetsTemplate->objectParameter();
0595 
0596         for (int i = 0; i < nObjects; i++) {
0597           std::vector<unsigned int>::iterator p =
0598               find(processedTypes.begin(), processedTypes.end(), (*op)[i].countIndex);
0599 
0600           // check, weather this count index was already processed
0601           // and process it if not
0602           if (p == processedTypes.end()) {
0603             std::ostringstream indStr;
0604             indStr << (*op)[i].countIndex;
0605 
0606             std::string tempStr2 = jet.returnParameterMap()[stringConstantCommon_];
0607             while (jet.findAndReplaceString(tempStr2, sp(substParamParticle_), objType2Str_[JetCounts]))
0608               ;
0609             while (jet.findAndReplaceString(tempStr2, sp(substParamType_), indStr.str()))
0610               ;
0611             commonParams[substParamJetCntsCommon_] += tempStr2 + "\n";  // +"<= '0';\n");
0612             processedTypes.push_back((*op)[i].countIndex);
0613           }
0614         }
0615 
0616         int cond2int;
0617 
0618         if (!getIntVal(conditionToIntegerMap_, (iterCond->first), cond2int)) {
0619           msg("Panik! Condition " + (iterCond->first) + " does not have a integer equivalent!");
0620           break;
0621         }
0622 
0623         std::string intVal = index4CondChipVhd(cond2int);
0624 
0625         L1GtVhdlTemplateFile jetcopy = jet;
0626 
0627         jetcopy.substitute("particle", condType2Str_[(iterCond->second)->condType()]);
0628         jetcopy.substitute("type", int2str((*op)[0].countIndex));
0629         jetcopy.substitute("name", iterCond->first);
0630 
0631         jetcopy.substitute("ser_no", intVal);
0632 
0633         // builds the final string
0634         std::string tempStr = jetcopy.returnParameterMap()["PREALGO"];
0635 
0636         jetcopy.findAndReplaceString(tempStr, "$(particle)", "jet_cnt");
0637         jetcopy.findAndReplaceString(tempStr, "$(ser_no)", intVal);
0638         jetcopy.findAndReplaceString(tempStr, "$(type)", int2str((*op)[0].countIndex));
0639 
0640         jetcopy.append(tempStr);
0641         jetcopy.removeEmptyLines();
0642 
0643         templates["jet_cnts"].append(jetcopy);
0644       }
0645 
0646       break;
0647 
0648       case CondCorrelation: {
0649         //empty
0650       } break;
0651 
0652       case CondNull: {
0653         //empty
0654       } break;
0655 
0656       default: {
0657         //empty
0658       } break;
0659     }
0660   }
0661 
0662   // delete superfluous newlines at the end of common parameters
0663   std::map<std::string, std::string>::iterator pIt = commonParams.begin();
0664 
0665   while (pIt != commonParams.end()) {
0666     if ((pIt->second)[((pIt->second).length() - 1)] == '\n')
0667       (pIt->second) = (pIt->second).substr(0, (pIt->second).length() - 1);
0668     pIt++;
0669   }
0670 
0671   return true;
0672 }
0673 
0674 bool L1GtVhdlWriterCore::processAlgorithmMap(std::vector<std::map<int, std::string> > &algoStrings) {
0675   std::map<int, std::string> algorithmsChip1;
0676   std::map<int, std::string> algorithmsChip2;
0677 
0678   AlgorithmMap::const_iterator algoIter = (*algorithmMap_).begin();
0679 
0680   // loop over algorithm map
0681   while (algoIter != (*algorithmMap_).end()) {
0682     // msg(algoIter->first);
0683 
0684     L1GtVhdlTemplateFile dummy;
0685 
0686     // get the logical expression
0687     std::string logicalExpr = (algoIter->second).algoLogicalExpression();
0688     std::vector<std::string> conditions;
0689 
0690     dummy.getConditionsFromAlgo(logicalExpr, conditions);
0691 
0692     std::string logicalExprCopy = logicalExpr;
0693 
0694     // loop over all condition names appearing in algorithm and replace them by type and integer value
0695     for (unsigned int i = 0; i < conditions.size(); i++) {
0696       std::ostringstream newExpr;
0697 
0698       // look for the condition on correct chip
0699       ConditionMap const &chip = conditionMap_->at(algoIter->second.algoChipNumber());
0700       L1GtCondition const *cond = (chip.find(conditions.at(i)) == chip.end()) ? nullptr : chip.at(conditions.at(i));
0701 
0702       // check weather condition exists
0703       if (cond != nullptr) {
0704         newExpr << objType2Str_[(cond->objectType()).at(0)];
0705         newExpr << "_" << condType2Str_[cond->condType()] << "(";
0706         newExpr << conditionToIntegerMap_[conditions.at(i)] << ")";
0707         dummy.findAndReplaceString(logicalExpr, conditions.at(i), newExpr.str());
0708       } else
0709         msg("Panik! Didn't find Condition " + conditions.at(i));
0710     }
0711 
0712     // has to be checked!
0713     std::vector<int> orderConditionChip;
0714     orderConditionChip.push_back(2);
0715     orderConditionChip.push_back(1);
0716 
0717     int pin = (algoIter->second).algoOutputPin(2, 96, orderConditionChip);
0718 
0719     //msg(int2str(pin));
0720 
0721     if (pin < 0)
0722       pin *= -1;
0723 
0724     if ((algoIter->second).algoChipNumber() == 0) {
0725       algorithmsChip1[pin] = logicalExpr;
0726       if (debugMode_)
0727         algorithmsChip1[pin] += ("-- " + logicalExprCopy);
0728     } else if ((algoIter->second).algoChipNumber() == 1) {
0729       algorithmsChip2[pin] = logicalExpr;
0730       if (debugMode_)
0731         algorithmsChip2[pin] += ("-- " + logicalExprCopy);
0732     }
0733 
0734     algoIter++;
0735   }
0736 
0737   algoStrings.push_back(algorithmsChip1);
0738   algoStrings.push_back(algorithmsChip2);
0739 
0740   return true;
0741 }
0742 
0743 std::string L1GtVhdlWriterCore::chip2OutputSubDir(const int &chip) {
0744   if (chip == 1)
0745     return outputDir_ + "/" + outputSubDir1_ + "/";
0746   if (chip == 2)
0747     return outputDir_ + "/" + outputSubDir2_ + "/";
0748 
0749   return "";
0750 }
0751 
0752 bool L1GtVhdlWriterCore::makeFirmware(const std::vector<ConditionMap> &conditionMap, const AlgorithmMap &algorithmMap) {
0753   conditionMap_ = &conditionMap;
0754 
0755   algorithmMap_ = &algorithmMap;
0756 
0757   std::string subDir1 = outputDir_ + outputSubDir1_;
0758   std::string subDir2 = outputDir_ + outputSubDir2_;
0759 
0760   (void)mkdir(subDir1.c_str(), 666);
0761   (void)mkdir(subDir2.c_str(), 666);
0762 
0763   chmod(subDir1.c_str(), 0777);
0764   chmod(subDir2.c_str(), 0777);
0765 
0766   /*
0767     subDirs_.push_back(subDir1);
0768     subDirs_.push_back(subDir2);
0769     */
0770 
0771   writeQsfSetupFiles(version_);
0772 
0773   //--------------------------------------build setups-------------------------------------------------------
0774 
0775   // loop over the two condition chips
0776   for (unsigned short int i = 1; i <= 2; i++) {
0777     // ----------------------- muon setup -------------------------------------------------------
0778 
0779     std::map<std::string, std::string> muonParameters;
0780     getMuonSetupContentFromTriggerMenu(i, muonParameters);
0781     writeMuonSetupVhdl(muonParameters, "muon", i);
0782 
0783     // ----------------------- calo setup -------------------------------------------------------
0784 
0785     // map containing all calo object types correlated with the strings
0786     // under which they appear in the firmware
0787     std::vector<L1GtObject>::iterator caloObjIter = caloObjects_.begin();
0788 
0789     // loop over all calo objectsbuildMuonSetupVhdl
0790     while (caloObjIter != caloObjects_.end()) {
0791       std::map<std::string, std::string> caloParameters;
0792       getCaloSetupContentFromTriggerMenu(i, caloParameters, (*caloObjIter));
0793       writeMuonSetupVhdl(caloParameters, objType2Str_[(*caloObjIter)], i);
0794 
0795       caloObjIter++;
0796     }
0797 
0798     // ----------------------- etm setup ---------------------------------------------------------
0799 
0800     // map containing all calo object types correlated with the strings
0801     // under which they appear in the firmware
0802     std::vector<L1GtObject>::iterator esumObjIter = esumObjects_.begin();
0803 
0804     while (esumObjIter != esumObjects_.end()) {
0805       std::string etmParameter;
0806 
0807       getEsumsSetupContentFromTriggerMenu(i, (*esumObjIter), etmParameter);
0808       writeEtmSetup(etmParameter, i);
0809 
0810       esumObjIter++;
0811     }
0812 
0813     // add jet counts to condition 2 integer map
0814     addJetCountsToCond2IntMap(i, (*conditionMap_), conditionToIntegerMap_);
0815 
0816     // --------------------cond chip setup---------------------------------------------------------
0817     // Important: all other setups have to be build BEFORE this one because it needs a
0818     // complete condition2integer map !!!
0819 
0820     std::map<std::string, L1GtVhdlTemplateFile> templates;
0821     std::map<std::string, std::string> common;
0822     getCondChipVhdContentFromTriggerMenu(i, templates, common);
0823     writeConditionChipSetup(templates, common, i);
0824 
0825     // despite yet not existing they have to appear in cond_chip_pkg vhds
0826     initializeDeltaConditions();
0827 
0828     // --------------------cond chip pkg------------------------------------------------------------
0829 
0830     writeCondChipPkg(i);
0831 
0832     // -----------------------def val pkg -------------------------------------------------
0833 
0834     writeDefValPkg((*conditionMap_), i);
0835 
0836     // debug
0837     if (debugMode_) {
0838       //printConditionsOfCategory(CondEnergySum, (*conditionMap_).at(i-1));
0839     }
0840   }
0841 
0842   if (debugMode_)
0843     writeCond2intMap2File();
0844 
0845   //-------------------------------process algorithms----------------------------------------------------------
0846 
0847   std::vector<std::map<int, std::string> > algoStrings;
0848 
0849   processAlgorithmMap(algoStrings);
0850 
0851   writeAlgoSetup(algoStrings);
0852 
0853   return true;
0854 }
0855 
0856 std::string L1GtVhdlWriterCore::gtTemplatesPath() { return vhdlDir_; }
0857 
0858 std::string L1GtVhdlWriterCore::int2str(const int &integerValue) {
0859   std::ostringstream oss;
0860   oss << integerValue;
0861   return oss.str();
0862 }
0863 
0864 void L1GtVhdlWriterCore::buildCommonHeader(std::map<std::string, std::string> &headerParameters,
0865                                            const std::vector<std::string> &connectedChannels) {
0866   commonHeader_.open(vhdlDir_ + "InternalTemplates/header");
0867 
0868   std::map<std::string, std::string>::iterator iter = headerParameters.begin();
0869 
0870   // loop over the header parameter map and replace all subsitution
0871   // parameters with their values
0872   while (iter != headerParameters.end()) {
0873     commonHeader_.substitute((*iter).first, (*iter).second);
0874     iter++;
0875   }
0876 
0877   commonHeader_.insert("$(connected_channels_1)", connectedChannels);
0878   commonHeader_.insert("$(connected_channels_2)", connectedChannels);
0879 
0880   //---------------------build the Quartus configuration files----------------------------------------
0881 
0882   //writeQsfSetupFiles(headerParameters["version"]);
0883 
0884   version_ = headerParameters["version"];
0885 
0886   msg("Build Common header and Quartus setup files sucessuflly!");
0887 }
0888 
0889 L1GtVhdlTemplateFile L1GtVhdlWriterCore::openVhdlFileWithCommonHeader(const std::string &filename,
0890                                                                       const std::string &outputFilename) {
0891   L1GtVhdlTemplateFile commonHeaderCp;
0892   commonHeaderCp = commonHeader_;
0893 
0894   commonHeaderCp.substitute("vhdl_file_name", outputFilename);
0895 
0896   L1GtVhdlTemplateFile myTemplate(vhdlDir_ + "Templates/" + filename);
0897   myTemplate.insert("$(header)", commonHeaderCp);
0898 
0899   return myTemplate;
0900 }
0901 
0902 void L1GtVhdlWriterCore::writeMuonSetupVhdl(std::map<std::string, std::string> &muonParameters,
0903                                             const std::string &particle,
0904                                             unsigned short int &condChip) {
0905   std::string filename;
0906 
0907   L1GtVhdlTemplateFile muonTemplate, internalTemplate, internalTemplateCopy;
0908 
0909   // choose the correct template file name
0910   if (particle == "muon") {
0911     filename = vhdlTemplateMuonSetup_;
0912     internalTemplate.open(vhdlDir_ + "InternalTemplates/muonsetup", true);
0913   } else {
0914     filename = vhdlTemplateCaloSetup_;
0915     internalTemplate.open(vhdlDir_ + "InternalTemplates/calosetup", true);
0916   }
0917 
0918   std::string outputFile;
0919   outputFile = filename;
0920 
0921   // modify filename
0922   if (particle != "muon")
0923     muonTemplate.findAndReplaceString(outputFile, "calo", particle);
0924 
0925   // add condition chip index to output filename
0926   //muonTemplate.findAndReplaceString(outputFile, ".", int2str(condChip)+".");
0927 
0928   // open the template file and insert header
0929   muonTemplate = openVhdlFileWithCommonHeader(filename, outputFile);
0930 
0931   std::map<std::string, std::string> parameterMap = internalTemplate.returnParameterMap();
0932 
0933   std::vector<std::string> substitutionParameters;
0934 
0935   // fills the map with all substitution parameters of the template file
0936   substitutionParameters = muonTemplate.getSubstitutionParametersFromTemplate();
0937 
0938   // insert a emty line at the end of each block
0939   internalTemplate.append("");
0940 
0941   std::map<std::string, std::string>::iterator iter;
0942 
0943   // loop over all substitution parameters that have been extracted from the template file
0944   for (unsigned int i = 0; i < substitutionParameters.size(); i++) {
0945     // make a working copy of the template file
0946     internalTemplateCopy = internalTemplate;
0947 
0948     // choose which of the three constant template strings to take - only for calo!
0949     if (particle != "muon") {
0950       if (substitutionParameters.at(i).substr(0, 3) == "eta")
0951         internalTemplateCopy.substitute("constant", parameterMap["eta"]);
0952       else if (substitutionParameters.at(i).substr(0, 3) == "phi")
0953         internalTemplateCopy.substitute("constant", parameterMap["phi"]);
0954       else if (substitutionParameters.at(i).substr(0, 3) == "del" /*ta*/) {
0955         internalTemplateCopy.substitute("constant", parameterMap["delta"]);
0956         while (internalTemplateCopy.substitute("delta", substitutionParameters[i]))
0957           internalTemplateCopy.substitute("delta", substitutionParameters[i]);
0958       }
0959     }
0960 
0961     if (particle == "muon") {
0962       // final preparation of the internal template before it is inserted in the actual template file
0963       internalTemplateCopy.substitute("type", substitutionParameters[i]);
0964     } else
0965 
0966     {
0967       internalTemplateCopy.substitute("type", substitutionParameters[i].substr(4));
0968     }
0969 
0970     // subsitute the second occurance of type without "_l" and "_h"
0971 
0972     std::string paramCopy = substitutionParameters[i];
0973 
0974     internalTemplateCopy.findAndReplaceString(paramCopy, "_l", "");
0975     internalTemplateCopy.findAndReplaceString(paramCopy, "_h", "");
0976 
0977     internalTemplateCopy.substitute("type2", paramCopy);
0978 
0979     internalTemplateCopy.substitute("others", parameterMap[substitutionParameters[i]]);
0980 
0981     // replace all the occurances of "particle"
0982     while (muonTemplate.substitute("particle", particle))
0983       muonTemplate.substitute("particle", particle);
0984 
0985     // remove the the parameter $(content) if its empty
0986     iter = muonParameters.find(substitutionParameters[i]);
0987 
0988     // check weather this parameter exists
0989     if (iter != muonParameters.end()) {
0990       if ((*iter).second[(*iter).second.length() - 1] == '\n')
0991         (*iter).second[(*iter).second.length() - 1] = ' ';
0992       internalTemplateCopy.substitute("content", (*iter).second);
0993     } else
0994       internalTemplateCopy.removeLineWithContent("$(content)");
0995 
0996     // insert the processed internal template in the muon template file
0997     muonTemplate.insert("$(" + substitutionParameters[i] + ")", internalTemplateCopy);
0998   }
0999 
1000   // save the muon template file
1001   muonTemplate.save(chip2OutputSubDir(condChip) + outputFile);
1002   chmod((chip2OutputSubDir(condChip) + outputFile).c_str(), 0666);
1003 }
1004 
1005 void L1GtVhdlWriterCore::writeConditionChipSetup(const std::map<std::string, L1GtVhdlTemplateFile> &templates,
1006                                                  const std::map<std::string, std::string> &common,
1007                                                  const unsigned short int &chip) {
1008   // get filename
1009   std::string filename = vhdlTemplateCondChip_;
1010 
1011   // build output filename
1012   std::string outputFileName = filename;
1013   L1GtVhdlTemplateFile::findAndReplaceString(outputFileName, ".", int2str(chip) + ".");
1014 
1015   L1GtVhdlTemplateFile myTemplate = openVhdlFileWithCommonHeader(filename, outputFileName);
1016 
1017   // map containing the subsitution parameters with their content (as L1GtVhdlTemplateFile file object)
1018   std::map<std::string, L1GtVhdlTemplateFile>::const_iterator iter = templates.begin();
1019 
1020   while (iter != templates.end()) {
1021     myTemplate.insert("$(" + (iter->first) + ")", iter->second);
1022 
1023     iter++;
1024   }
1025 
1026   // subsitutes common parameters
1027   std::map<std::string, std::string>::const_iterator iter2 = common.begin();
1028 
1029   while (iter2 != common.end()) {
1030     myTemplate.substitute((iter2->first), iter2->second);
1031 
1032     iter2++;
1033   }
1034 
1035   myTemplate.save(chip2OutputSubDir(chip) + filename);
1036   chmod((chip2OutputSubDir(chip) + filename).c_str(), 0666);
1037 }
1038 
1039 void L1GtVhdlWriterCore::writeAlgoSetup(std::vector<std::map<int, std::string> > &algoStrings) {
1040   // loop over the two condition chips
1041   for (unsigned int i = 1; i <= 2; i++) {
1042     std::string filename = vhdlTemplateAlgoAndOr_;
1043 
1044     // output file name
1045     std::string outputFileName = filename;
1046     L1GtVhdlTemplateFile::findAndReplaceString(outputFileName, ".", int2str(i) + ".");
1047 
1048     L1GtVhdlTemplateFile templateFile = openVhdlFileWithCommonHeader(filename, outputFileName);
1049 
1050     std::ostringstream buffer;
1051 
1052     unsigned int algoPinsPerChip = 96;
1053 
1054     for (unsigned int k = 1; k <= algoPinsPerChip; k++) {
1055       buffer << stringConstantAlgo_ << "(" << k << ")";
1056       if (!algoStrings.at(i - 1)[k].empty())
1057         buffer << " <= " << algoStrings.at(i - 1)[k] << ";" << std::endl;
1058       else
1059         buffer << " <= '0';" << std::endl;
1060     }
1061 
1062     templateFile.substitute(substParamAlgos_, buffer.str());
1063     templateFile.save(chip2OutputSubDir(i) + filename);
1064     chmod((chip2OutputSubDir(i) + filename).c_str(), 0666);
1065   }
1066 }
1067 
1068 void L1GtVhdlWriterCore::writeEtmSetup(std::string &etmString, const int &condChip) {
1069   // get filename
1070   std::string filename = vhdlTemplateEtmSetup_;
1071   std::string outputFile = filename;
1072 
1073   L1GtVhdlTemplateFile myTemplate;
1074 
1075   // modify output filename
1076   myTemplate.findAndReplaceString(outputFile, ".", int2str(condChip) + ".");
1077 
1078   myTemplate = openVhdlFileWithCommonHeader(filename, filename);
1079 
1080   // replace all occurances of $(particle)
1081   while (myTemplate.substitute("particle", "etm"))
1082     while (myTemplate.substitute("particle", "etm"))
1083       ;
1084 
1085   // delete last char if it is \n
1086   if (etmString[etmString.length() - 1] == '\n')
1087     etmString = etmString.substr(0, etmString.length() - 1);
1088 
1089   myTemplate.substitute("phi", etmString);
1090 
1091   myTemplate.save(chip2OutputSubDir(condChip) + filename);
1092   chmod((chip2OutputSubDir(condChip) + filename).c_str(), 0666);
1093 }
1094 
1095 void L1GtVhdlWriterCore::printCommonHeader() { commonHeader_.print(); }
1096 
1097 L1GtVhdlTemplateFile L1GtVhdlWriterCore::retrunCommonHeader() { return commonHeader_; }
1098 
1099 void L1GtVhdlWriterCore::writeQsfSetupFiles(const std::string &version) {
1100   std::vector<std::string> filenames;
1101   filenames.push_back(quartusSetupFileChip1_);
1102   filenames.push_back(quartusSetupFileChip2_);
1103 
1104   for (unsigned int i = 0; i < filenames.size(); i++) {
1105     L1GtVhdlTemplateFile myTemplate;
1106 
1107     myTemplate.open(vhdlDir_ + "Templates/" + filenames.at(i));
1108     myTemplate.substitute("version", version);
1109 
1110     std::string tempStr = filenames.at(i);
1111 
1112     if (i == 0)
1113       L1GtVhdlTemplateFile::findAndReplaceString(tempStr, "cond1", "cond");
1114     if (i == 1)
1115       L1GtVhdlTemplateFile::findAndReplaceString(tempStr, "cond2", "cond");
1116 
1117     myTemplate.save(chip2OutputSubDir(i + 1) + tempStr);
1118     chmod((chip2OutputSubDir(i + 1) + tempStr).c_str(), 0666);
1119   }
1120 }
1121 
1122 void L1GtVhdlWriterCore::msg(const std::string &message) { internMessageBuf_.push_back(message); }
1123 
1124 std::vector<std::string> L1GtVhdlWriterCore::getMsgBuf() { return internMessageBuf_; }
1125 
1126 bool L1GtVhdlWriterCore::getIntVal(const std::map<std::string, int> &map, const std::string &searchValue, int &intVal) {
1127   std::map<std::string, int>::const_iterator iter = map.find(searchValue);
1128   if (iter == map.end())
1129     return false;
1130   intVal = (*iter).second;
1131   return true;
1132 }
1133 
1134 std::string L1GtVhdlWriterCore::index4CondChipVhd(int intval) {
1135   intval++;
1136   return int2str(intval);
1137 }
1138 
1139 void L1GtVhdlWriterCore::addJetCountsToCond2IntMap(const int chip,
1140                                                    const std::vector<ConditionMap> &conditionMap,
1141                                                    std::map<std::string, int> &conditionToIntegerMap_) {
1142   ConditionMap jetConditions;
1143 
1144   returnConditionsOfOneClass(TypeJetCounts, CondJetCounts, JetCounts, conditionMap.at(chip - 1), jetConditions);
1145   /*
1146      int counter = 0;
1147 
1148      for (ConditionMap::const_iterator iterCond =  jetConditions.begin(); iterCond !=  jetConditions.end(); iterCond++)
1149      {
1150      conditionToIntegerMap_[iterCond->first]=counter;
1151      counter++;
1152      msg(iterCond->first);
1153      }
1154 
1155      */
1156 
1157   unsigned int maxJetsCountsIndex = 11;
1158 
1159   for (unsigned int i = 0; i <= maxJetsCountsIndex; i++) {
1160     int counter = 0;
1161 
1162     for (ConditionMap::const_iterator iterCond = jetConditions.begin(); iterCond != jetConditions.end(); iterCond++) {
1163       L1GtJetCountsTemplate *jetsTemplate = static_cast<L1GtJetCountsTemplate *>(iterCond->second);
1164       const std::vector<L1GtJetCountsTemplate::ObjectParameter> *op = jetsTemplate->objectParameter();
1165 
1166       conditionToIntegerMap_[iterCond->first] = counter;
1167       if ((*op)[0].countIndex == i)
1168         counter++;
1169 
1170       //msg(int2str((*op)[0].countIndex));
1171     }
1172 
1173     numberOfConditions_.at(chip - 1).push_back(
1174         retNumberOfConditionsString("jet_cnts_" + int2str(i) + "_cond", counter));
1175   }
1176 }
1177 
1178 void L1GtVhdlWriterCore::writeCond2intMap2File() {
1179   for (unsigned int i = 0; i <= 1; i++) {
1180     ConditionMap::const_iterator iterCond = conditionMap_->at(i).begin();
1181 
1182     std::string filename = chip2OutputSubDir(i + 1) + "cond_names_integer.txt";
1183 
1184     std::ofstream outputFile(filename.c_str());
1185 
1186     while (iterCond != conditionMap_->at(i).end()) {
1187       conditionToIntegerMap_[(*iterCond).first];
1188 
1189       outputFile << (iterCond->first) << ": " << conditionToIntegerMap_[(*iterCond).first] << std::endl;
1190       iterCond++;
1191     }
1192 
1193     outputFile.close();
1194 
1195     chmod(filename.c_str(), 0666);
1196   }
1197 
1198   /*
1199     
1200     
1201     const std::vector<ConditionMap> * conditionMap_;
1202     
1203     std::string filename=outputDir_+"cond_names_integer.txt";
1204     std::ofstream outputFile(filename.c_str());
1205 
1206     for (std::map<std::string,int>::const_iterator iterCond =
1207             conditionToIntegerMap_.begin(); iterCond
1208             != conditionToIntegerMap_.end(); iterCond++)
1209     {
1210         outputFile<<(iterCond->first)<<": "<<(iterCond->second)<<std::endl;
1211     }
1212     
1213     */
1214 }
1215 
1216 std::string L1GtVhdlWriterCore::buildDefValString(const int &conditionIndex, const std::vector<int> &values) {
1217   // has to produce something like 1 =>  ("00000000", "00000000")
1218 
1219   return "1 =>  (\"00000000\", \"00000000\")";
1220 }
1221 
1222 std::string L1GtVhdlWriterCore::getDefValsFromTriggerMenu(const L1GtConditionType &type,
1223                                                           const L1GtObject &object,
1224                                                           const VmeRegister &reg) {
1225   L1GtConditionCategory category;
1226 
1227   // get condition category from object
1228 
1229   category = getCategoryFromObject(object);
1230 
1231   ConditionMap conditions;
1232   returnConditionsOfOneClass(type, category, object, (*conditionMap_).at(0), conditions);
1233 
1234   std::string result;
1235 
1236   if (category == CondCalo) {
1237     for (ConditionMap::const_iterator iterCond = conditions.begin(); iterCond != conditions.end(); iterCond++) {
1238       L1GtCaloTemplate *caloTemplate = static_cast<L1GtCaloTemplate *>(iterCond->second);
1239       const std::vector<L1GtCaloTemplate::ObjectParameter> *op = caloTemplate->objectParameter();
1240 
1241       unsigned int nObjects = iterCond->second->nrObjects();
1242 
1243       for (unsigned int i = 0; i < nObjects; i++) {
1244         if (i == 0)
1245           result += "(";
1246         result += "\"";
1247         result += int2str((*op).at(i).etThreshold);
1248         result += "\"";
1249         if (i != nObjects - 1)
1250           result += ",";
1251         else
1252           result += ")\n";
1253       }
1254     }
1255   }
1256 
1257   return "-- 0 => (\"00000000\", \"00000000\" ... )";
1258   return result;
1259 }
1260 
1261 void L1GtVhdlWriterCore::writeDefValPkg(const std::vector<ConditionMap> &conditionMap, const int &chip) {
1262   // open internal template file
1263   L1GtVhdlTemplateFile internalTemplate;
1264   internalTemplate.open(vhdlDir_ + "InternalTemplates/defvalpkg", true);
1265 
1266   // to write the def_value_pkg file it has to be looped over all POSSIBLE types of conditions
1267   // POSSIBLE: calo_3 eg. does not exist and therefore makes no sense..
1268 
1269   // Process muon conditions first
1270 
1271   // temporary buffers for the default value blocks (see internal templates) of the different types.
1272   // in the end those buffers are simply appended to the actual template!
1273   L1GtVhdlTemplateFile muonDefValuesBuffer, caloDefValuesBuffer, jetCountsDefValuesBuffer, esumsDefValBuffer;
1274 
1275   // Get the default value type strings from internal template
1276   std::vector<std::string> muonDefValTypes;
1277   muonDefValTypes.push_back(internalTemplate.getInternalParameter(stringConstantPtl_));
1278   muonDefValTypes.push_back(internalTemplate.getInternalParameter(stringConstantPth_));
1279   muonDefValTypes.push_back(internalTemplate.getInternalParameter(stringConstantQuality_));
1280   muonDefValTypes.push_back(internalTemplate.getInternalParameter(substParamCharge_));
1281 
1282   int jetCountsMaxIndex = 11;
1283 
1284   // fill jet counts vector (from 1 to 11)
1285   std::vector<std::string> jetCountsDefValTypes;
1286   for (int i = 0; i <= jetCountsMaxIndex; i++) {
1287     jetCountsDefValTypes.push_back(int2str(i));
1288   }
1289 
1290   // only one default value for calo objects therefore only a empty string
1291   std::vector<std::string> caloDefValTypes;
1292   caloDefValTypes.push_back("");
1293 
1294   // get types of esums defvalues (as firmware strings) from the internal templates
1295   std::vector<std::string> esumsDefValTypes;
1296   esumsDefValTypes.push_back(internalTemplate.getInternalParameter(stringConstantEsumsLow_));
1297   esumsDefValTypes.push_back(internalTemplate.getInternalParameter(stringConstantEsumsHigh_));
1298 
1299   std::map<L1GtConditionType, std::string>::iterator typeIter;
1300 
1301   // prepare a map with all muon relevant types by removing
1302   // obsolete types from a copy of condType2Str_ map
1303   // should be improved
1304   std::map<L1GtConditionType, std::string> muonTypes = condType2Str_;
1305 
1306   typeIter = muonTypes.find(Type2cor);
1307   muonTypes.erase(typeIter);
1308   typeIter = muonTypes.find(TypeETM);
1309   muonTypes.erase(typeIter);
1310   typeIter = muonTypes.find(TypeETT);
1311   muonTypes.erase(typeIter);
1312   typeIter = muonTypes.find(TypeHTT);
1313   muonTypes.erase(typeIter);
1314   typeIter = muonTypes.find(TypeJetCounts);
1315   muonTypes.erase(typeIter);
1316 
1317   std::map<L1GtConditionType, std::string> caloTypes = muonTypes;
1318   typeIter = caloTypes.find(Type3s);
1319   caloTypes.erase(typeIter);
1320 
1321   // dummy type in order to be able to use the same code as for calo and muon
1322   // this map is also used for esums since there is no difference in treatment
1323   std::map<L1GtConditionType, std::string> jetCountsTypes;
1324   jetCountsTypes[TypeJetCounts] = "";
1325 
1326   // here the DefValuesBuffer are build (=objects of the class L1GtVhdlTemplateFile
1327   // that are containing all default values and finally can be inserted into the
1328   // def_val_pkg.vhd template
1329 
1330   buildDefValuesBuffer(muonDefValuesBuffer, muonTypes, muonDefValTypes, Mu);
1331 
1332   // loop over all possible calo objects here
1333   for (unsigned int i = 0; i < caloObjects_.size(); i++) {
1334     buildDefValuesBuffer(caloDefValuesBuffer, caloTypes, caloDefValTypes, caloObjects_.at(i));
1335   }
1336 
1337   // loop over all possible esums objects here
1338   for (unsigned int i = 0; i < esumObjects_.size(); i++) {
1339     buildDefValuesBuffer(esumsDefValBuffer, jetCountsTypes, esumsDefValTypes, esumObjects_.at(i));
1340   }
1341 
1342   // same procedure for jet counts
1343   buildDefValuesBuffer(esumsDefValBuffer, jetCountsTypes, jetCountsDefValTypes, JetCounts);
1344 
1345   //----------------------In this section the actual output file is written----------------
1346 
1347   // now open the actual template file:
1348 
1349   std::string filename = vhdlTemplateDefValPkg_;
1350 
1351   std::string outputFile = filename;
1352 
1353   // modify output filename
1354   L1GtVhdlTemplateFile::findAndReplaceString(outputFile, ".", int2str(chip) + ".");
1355   L1GtVhdlTemplateFile defValTemplate = openVhdlFileWithCommonHeader(filename, outputFile);
1356 
1357   // insert the temporary buffers to the template
1358 
1359   // muon default values
1360   defValTemplate.insert(sp(substParamMuonDefVals_), muonDefValuesBuffer);
1361 
1362   // calo default values
1363   defValTemplate.insert(sp(substParamCaloDefVals_), caloDefValuesBuffer);
1364 
1365   // esums default values
1366   defValTemplate.insert(sp(substParamEsumsDefVals_), esumsDefValBuffer);
1367 
1368   // jet counts default values
1369   defValTemplate.insert(sp(substParamJetsDefVals_), jetCountsDefValuesBuffer);
1370 
1371   // close and save the file
1372 
1373   L1GtVhdlTemplateFile::findAndReplaceString(outputFile, "1", "");
1374   L1GtVhdlTemplateFile::findAndReplaceString(outputFile, "2", "");
1375 
1376   defValTemplate.save(chip2OutputSubDir(chip) + outputFile);
1377   chmod((chip2OutputSubDir(chip) + outputFile).c_str(), 0666);
1378 }
1379 
1380 bool L1GtVhdlWriterCore::buildDefValuesBuffer(L1GtVhdlTemplateFile &buffer,
1381                                               const std::map<L1GtConditionType, std::string> &typeList,
1382                                               const std::vector<std::string> &defValuesList,
1383                                               const L1GtObject &object) {
1384   // type iterator
1385   std::map<L1GtConditionType, std::string>::const_iterator typeIter;
1386 
1387   for (typeIter = typeList.begin(); typeIter != typeList.end(); typeIter++) {
1388     for (unsigned int i = 0; i < defValuesList.size(); i++) {
1389       // open a new internale template
1390       L1GtVhdlTemplateFile internalTemplate;
1391       internalTemplate.open(vhdlDir_ + "InternalTemplates/defvalpkg", true);
1392 
1393       std::string idString = internalTemplate.getInternalParameter(stringConstantDefValId_);
1394 
1395       // The following three steps convert "$(particle)_$(type)_$(defvaltype)_def_val"
1396       // to e.g. "muon_1s_et_def_val"
1397 
1398       // replace the substiution parameter particle with muon - thereby parameterString is a
1399       // reference and therefore changed.
1400       L1GtVhdlTemplateFile::findAndReplaceString(idString, sp(substParamParticle_), objType2Str_[object]);
1401 
1402       // replace the substiution parameter particle with muon
1403       L1GtVhdlTemplateFile::findAndReplaceString(idString, sp(substParamType_), typeIter->second);
1404 
1405       // replace the substiution parameter defvaltype with muon
1406       L1GtVhdlTemplateFile::findAndReplaceString(idString, sp(substParamDefValType_), defValuesList.at(i));
1407 
1408       // usage of the subsitute routine:
1409       // first the substitution parameter, then the content
1410       internalTemplate.substitute(substParamDefValId_, idString);
1411 
1412       // !here the body of the internale template is build - almost done!
1413 
1414       // The body looks as follows $(def_val), $(max_nr), $(content) and
1415       // $(others) have to be subsituted
1416 
1417       /*
1418              * CONSTANT $(def_val) : $(calo_or_muon)_maxnr$(max_nr)vector8_arr := 
1419              * (
1420              * $(content)
1421              * $(others)
1422              * );
1423              */
1424 
1425       // substitute the particle
1426       internalTemplate.substitute(substParamParticle_, objType2Str_[object]);
1427 
1428       // go on with max number - get the correct expression for max number from the internal template
1429       internalTemplate.substitute(
1430           substParamMaxNr_,
1431           internalTemplate.getInternalParameter(substParamMaxNr_ + "_" + condType2Str_[typeIter->first]));
1432 
1433       // now we have to choose the correct OTHERS string for the
1434       // internal template. The identifier for the OTHERS string
1435       // is the condition type (as firmware string) therefore:
1436 
1437       // we get it as follows
1438       std::string othersString;
1439 
1440       // jet_cnts are a special case
1441       if (object == JetCounts || object == HTT || object == ETM || object == ETT)
1442         othersString = internalTemplate.getInternalParameter(objType2Str_[JetCounts]);
1443       else
1444         othersString = internalTemplate.getInternalParameter(typeIter->second);
1445 
1446       internalTemplate.substitute(substParamOthers_, othersString);
1447 
1448       // the actual content, taken from the trigger menu
1449 
1450       std::string content = getDefValsFromTriggerMenu(typeIter->first, object, RegEtThreshold);
1451 
1452       internalTemplate.substitute(substParamContent_, content);
1453 
1454       // Finally the parameter $(calo_or_muon) is left open
1455       std::string caloOrMuonStr = stringConstantCalo_;
1456 
1457       if (object == Mu)
1458         caloOrMuonStr = objType2Str_[Mu];
1459 
1460       internalTemplate.substitute(substParamCaloOrMuon_, caloOrMuonStr);
1461 
1462       // The internal template has been processed and now can be added to the buffer..
1463       buffer.append(internalTemplate);
1464     }
1465   }
1466 
1467   return true;
1468 }
1469 
1470 void L1GtVhdlWriterCore::countCondsAndAdd2NumberVec(const L1GtConditionType &type,
1471                                                     const L1GtConditionCategory &category,
1472                                                     const L1GtObject &object,
1473                                                     const ConditionMap &map,
1474                                                     ConditionMap &outputMap,
1475                                                     const int &condChip) {
1476   // Get the absoloute amount of conditions
1477 
1478   int number;
1479 
1480   if (returnConditionsOfOneClass(type, category, object, map, outputMap))
1481     number = outputMap.size();
1482   else
1483     number = 0;
1484 
1485   std::string initstr = retNumberOfConditionsString(objType2Str_[object] + "_" + condType2Str_[type], number);
1486 
1487   numberOfConditions_.at(condChip - 1).push_back(initstr);
1488 }
1489 
1490 void L1GtVhdlWriterCore::initializeDeltaConditions() {
1491   for (unsigned int k = 0; k <= 1; k++) {
1492     // combine muon with calo particles
1493     for (unsigned int i = 0; i < caloObjects_.size(); i++) {
1494       numberOfConditions_.at(k).push_back(
1495           retNumberOfConditionsString(objType2Str_[Mu] + "_" + objType2Str_[caloObjects_.at(i)], 0));
1496     }
1497 
1498     // combine etm with muon
1499     numberOfConditions_.at(k).push_back(retNumberOfConditionsString(objType2Str_[ETM] + "_" + objType2Str_[Mu], 0));
1500 
1501     // combine etm with calo particles
1502     for (unsigned int i = 0; i < caloObjects_.size(); i++) {
1503       numberOfConditions_.at(k).push_back(
1504           retNumberOfConditionsString(objType2Str_[ETM] + "_" + objType2Str_[caloObjects_.at(i)], 0));
1505     }
1506 
1507     std::vector<L1GtObject> caloObjectsCp = caloObjects_;
1508 
1509     while (!caloObjectsCp.empty()) {
1510       std::vector<L1GtObject>::iterator iter = caloObjectsCp.begin();
1511       L1GtObject firstPartner = (*iter);
1512       caloObjectsCp.erase(iter);
1513 
1514       iter = caloObjectsCp.begin();
1515       while (iter != caloObjectsCp.end()) {
1516         numberOfConditions_.at(k).push_back(
1517             retNumberOfConditionsString(objType2Str_[firstPartner] + "_" + objType2Str_[(*iter)], 0));
1518         iter++;
1519       }
1520     }
1521   }
1522 }
1523 
1524 L1GtConditionCategory L1GtVhdlWriterCore::getCategoryFromObject(const L1GtObject &object) {
1525   L1GtConditionCategory category;
1526 
1527   if (object == Mu)
1528     category = CondMuon;
1529   else if (object == ETM || object == HTT || object == ETT)
1530     category = CondEnergySum;
1531   else if (object == IsoEG || object == NoIsoEG || object == CenJet || object == ForJet || object == TauJet)
1532     category = CondCalo;
1533   else if (object == IsoEG || object == NoIsoEG || object == CenJet || object == ForJet || object == TauJet)
1534     category = CondCalo;
1535   else if (object == JetCounts)
1536     category = CondJetCounts;
1537   else
1538     category = CondNull;
1539 
1540   return category;
1541 }
1542 
1543 void L1GtVhdlWriterCore::printConditionsOfCategory(const L1GtConditionCategory &category, const ConditionMap &map) {
1544   int counter = 0;
1545   for (ConditionMap::const_iterator iterCond = map.begin(); iterCond != map.end(); iterCond++) {
1546     msg(iterCond->first);
1547     counter++;
1548   }
1549 
1550   msg("Total Occurances: " + int2str(counter));
1551 }
1552 
1553 void L1GtVhdlWriterCore::writeCondChipPkg(const int &chip) {
1554   // build filename
1555 
1556   std::string filename;
1557 
1558   if (chip == 1)
1559     filename = vhdlTemplateCondChipPkg1_;
1560   else if (chip == 2)
1561     filename = vhdlTemplateCondChipPkg2_;
1562 
1563   // write the output
1564   L1GtVhdlTemplateFile myTemplate = openVhdlFileWithCommonHeader(filename, filename);
1565 
1566   myTemplate.substitute("version", version_);
1567 
1568   myTemplate.insert("$(conditions_nr)", numberOfConditions_.at(chip - 1));
1569 
1570   L1GtVhdlTemplateFile::findAndReplaceString(filename, "1", "");
1571   L1GtVhdlTemplateFile::findAndReplaceString(filename, "2", "");
1572 
1573   myTemplate.save(chip2OutputSubDir(chip) + filename);
1574   chmod((chip2OutputSubDir(chip) + filename).c_str(), 0666);
1575 }
1576 
1577 std::string L1GtVhdlWriterCore::retNumberOfConditionsString(const std::string &typeStr, const int &number) {
1578   std::string initstr = stringConstantConstantNr_ + typeStr + " : integer := " + int2str(number) + ";";
1579 
1580   return initstr;
1581 }
1582 
1583 std::map<std::string, int> L1GtVhdlWriterCore::getCond2IntMap() { return conditionToIntegerMap_; }
1584 
1585 std::string L1GtVhdlWriterCore::sp(const std::string &name) { return "$(" + name + ")"; }