Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2024-09-07 04:34:54

0001 //
0002 // This class is a first attempt at writing a configuration
0003 // object that will perform a calibration loop.
0004 //
0005 //
0006 //
0007 
0008 #include "CalibFormats/SiPixelObjects/interface/PixelCalibConfiguration.h"
0009 #include "CalibFormats/SiPixelObjects/interface/PixelTimeFormatter.h"
0010 #include "CalibFormats/SiPixelObjects/interface/PixelDACNames.h"
0011 //#include "PixelUtilities/PixelTestStandUtilities/include/PixelTimer.h"
0012 #include <fstream>
0013 #include <iostream>
0014 #include <ios>
0015 #include <cassert>
0016 #include <cstdlib>
0017 #include <algorithm>
0018 
0019 using namespace pos;
0020 using namespace std;
0021 
0022 #define BPIX
0023 
0024 PixelCalibConfiguration::PixelCalibConfiguration(std::vector<std::vector<std::string> >& tableMat)
0025     : PixelCalibBase(), PixelConfigBase("", "", "") {
0026   std::string mthn = "[PixelCalibConfiguration::PixelCalibConfiguration()]\t    ";
0027   std::map<std::string, int> colM;
0028   std::vector<std::string> colNames;
0029   /**
0030 
0031   EXTENSION_TABLE_NAME: PIXEL_CALIB_CLOB (VIEW: CONF_KEY_PIXEL_CALIB_V)
0032   
0033   CONFIG_KEY                    NOT NULL VARCHAR2(80)
0034   KEY_TYPE                  NOT NULL VARCHAR2(80)
0035   KEY_ALIAS                 NOT NULL VARCHAR2(80)
0036   VERSION                        VARCHAR2(40)
0037   KIND_OF_COND                  NOT NULL VARCHAR2(40)
0038   CALIB_TYPE                         VARCHAR2(200)
0039   CALIB_OBJ_DATA_FILE               NOT NULL VARCHAR2(200)
0040   CALIB_OBJ_DATA_CLOB               NOT NULL CLOB
0041   */
0042 
0043   colNames.push_back("CONFIG_KEY");
0044   colNames.push_back("KEY_TYPE");
0045   colNames.push_back("KEY_ALIAS");
0046   colNames.push_back("VERSION");
0047   colNames.push_back("KIND_OF_COND");
0048   colNames.push_back("CALIB_TYPE");
0049   colNames.push_back("CALIB_OBJ_DATA_FILE");
0050   colNames.push_back("CALIB_OBJ_DATA_CLOB");
0051 
0052   for (unsigned int c = 0; c < tableMat[0].size(); c++) {
0053     for (unsigned int n = 0; n < colNames.size(); n++) {
0054       if (tableMat[0][c] == colNames[n]) {
0055         colM[colNames[n]] = c;
0056         break;
0057       }
0058     }
0059   }  //end for
0060   for (unsigned int n = 0; n < colNames.size(); n++) {
0061     if (colM.find(colNames[n]) == colM.end()) {
0062       std::cerr << mthn << "Couldn't find in the database the column with name " << colNames[n] << std::endl;
0063       assert(0);
0064     }
0065   }
0066 
0067   _bufferData = true;
0068 
0069   std::istringstream in;
0070   in.str(tableMat[1][colM["CALIB_OBJ_DATA_CLOB"]]);
0071 
0072   std::string tmp;
0073 
0074   in >> tmp;
0075 
0076   if (tmp == "Mode:") {
0077     in >> mode_;
0078     //    std::cout << __LINE__ << "]\t" << mthn << "mode=" << mode_ << std::endl;
0079     in >> tmp;
0080   } else {
0081     mode_ = "FEDChannelOffsetPixel";
0082     std::cout << __LINE__ << "]\t" << mthn << "mode not set, is this an old file? " << std::endl;
0083     assert(0);
0084   }
0085 
0086   singleROC_ = false;
0087 
0088   if (tmp == "SingleROC") {
0089     singleROC_ = true;
0090     in >> tmp;
0091   }
0092 
0093   // Read in parameters, if any.
0094   if (tmp == "Parameters:") {
0095     in >> tmp;
0096     while (tmp != "Rows:") {
0097       assert(!in.eof());
0098       std::string paramName = tmp;
0099       in >> tmp;  // tmp contains the parameter value
0100       parameters_[paramName] = tmp;
0101       in >> tmp;  // tmp contains the next parameter's name, or "Rows:"
0102     }
0103   }
0104 
0105   assert(tmp == "Rows:");
0106 
0107   in >> tmp;
0108 
0109   std::vector<unsigned int> rows;
0110   while (tmp != "Cols:") {
0111     if (tmp == "|") {
0112       rows_.push_back(rows);
0113       rows.clear();
0114     } else {
0115       if (tmp != "*") {
0116         rows.push_back(atoi(tmp.c_str()));
0117       }
0118     }
0119     in >> tmp;
0120   }
0121   rows_.push_back(rows);
0122   rows.clear();
0123 
0124   in >> tmp;
0125 
0126   std::vector<unsigned int> cols;
0127   while ((tmp != "VcalLow:") && (tmp != "VcalHigh:") && (tmp != "Vcal:") && (tmp != "VcalHigh") && (tmp != "VcalLow")) {
0128     if (tmp == "|") {
0129       cols_.push_back(cols);
0130       cols.clear();
0131     } else {
0132       if (tmp != "*") {
0133         cols.push_back(atoi(tmp.c_str()));
0134       }
0135     }
0136     in >> tmp;
0137   }
0138   cols_.push_back(cols);
0139   cols.clear();
0140 
0141   highVCalRange_ = true;
0142 
0143   if (tmp == "VcalLow") {
0144     highVCalRange_ = false;
0145     in >> tmp;
0146   }
0147 
0148   if (tmp == "VcalHigh") {
0149     highVCalRange_ = true;
0150     in >> tmp;
0151   }
0152 
0153   if (tmp == "VcalLow:") {
0154     highVCalRange_ = false;
0155   }
0156 
0157   if ((tmp == "VcalLow:") || (tmp == "VcalHigh:") || (tmp == "Vcal:")) {
0158     unsigned int first, last, step;
0159     in >> first >> last >> step;
0160     unsigned int index = 1;
0161     if (!dacs_.empty()) {
0162       index = dacs_.back().index() * dacs_.back().getNPoints();
0163     }
0164     in >> tmp;
0165     bool mix = false;
0166     if (tmp == "mix") {
0167       mix = true;
0168       in >> tmp;
0169     }
0170     PixelDACScanRange dacrange(pos::k_DACName_Vcal, first, last, step, index, mix);
0171     dacs_.push_back(dacrange);
0172   } else {
0173     //in >> tmp;
0174     while (tmp == "Scan:" || tmp == "ScanValues:") {
0175       if (tmp == "ScanValues:") {
0176         std::string dacname;
0177         in >> dacname;
0178         vector<unsigned int> values;
0179         int val;
0180         in >> val;
0181         while (val != -1) {
0182           values.push_back(val);
0183           in >> val;
0184         }
0185         unsigned int index = 1;
0186         if (!dacs_.empty()) {
0187           index = dacs_.back().index() * dacs_.back().getNPoints();
0188         }
0189         PixelDACScanRange dacrange(dacname, values, index, false);
0190         dacs_.push_back(dacrange);
0191         in >> tmp;
0192       } else {
0193         std::string dacname;
0194         in >> dacname;
0195         unsigned int first, last, step;
0196         in >> first >> last >> step;
0197         unsigned int index = 1;
0198         if (!dacs_.empty()) {
0199           index = dacs_.back().index() * dacs_.back().getNPoints();
0200         }
0201         in >> tmp;
0202         bool mix = false;
0203         if (tmp == "mix") {
0204           mix = true;
0205           in >> tmp;
0206         }
0207         PixelDACScanRange dacrange(dacname, first, last, step, index, mix);
0208         dacs_.push_back(dacrange);
0209       }
0210     }
0211 
0212     while ((tmp == "Set:") || (tmp == "SetRelative:")) {
0213       string name;
0214       in >> name;
0215       int val;
0216       in >> val;
0217       unsigned int index = 1;
0218       if (!dacs_.empty())
0219         index = dacs_.back().index() * dacs_.back().getNPoints();
0220       PixelDACScanRange dacrange(name, val, val, 1, index, false);
0221       if (tmp == "SetRelative:") {
0222         dacrange.setRelative();
0223       }
0224       dacs_.push_back(dacrange);
0225       in >> tmp;
0226     }
0227   }
0228 
0229   assert(tmp == "Repeat:");
0230 
0231   in >> ntrigger_;
0232 
0233   in >> tmp;
0234 
0235   usesROCList_ = false;
0236   bool buildROCListNow = false;
0237   if (tmp == "Rocs:") {
0238     buildROCListNow = true;
0239     usesROCList_ = true;
0240   } else {
0241     assert(tmp == "ToCalibrate:");
0242     buildROCListNow = false;
0243   }
0244 
0245   while (!in.eof()) {
0246     tmp = "";
0247     in >> tmp;
0248 
0249     // added by F.Blekman to be able to deal with POS245 style calib.dat files in CMSSW
0250     // these files use the syntax:
0251     // Rocs:
0252     // all
0253 
0254     if (tmp == "all" || tmp == "+" || tmp == "-") {
0255       buildROCListNow = false;
0256     }
0257     // end of addition by F.B.
0258 
0259     if (tmp.empty())
0260       continue;
0261     rocListInstructions_.push_back(tmp);
0262   }
0263 
0264   rocAndModuleListsBuilt_ = false;
0265   if (buildROCListNow) {
0266     std::set<PixelROCName> rocSet;
0267     for (std::vector<std::string>::iterator rocListInstructions_itr = rocListInstructions_.begin();
0268          rocListInstructions_itr != rocListInstructions_.end();
0269          ++rocListInstructions_itr) {
0270       PixelROCName rocname(*rocListInstructions_itr);
0271       rocSet.insert(rocname);
0272     }
0273     buildROCAndModuleListsFromROCSet(rocSet);
0274   }
0275 
0276   objectsDependingOnTheNameTranslationBuilt_ = false;
0277 
0278   // Added by Dario as a temporary patch for Debbie (this will disappear in the future)
0279   calibFileContent_ = in.str();
0280   // End of temporary patch
0281 
0282   return;
0283 }
0284 
0285 PixelCalibConfiguration::PixelCalibConfiguration(std::string filename) : PixelCalibBase(), PixelConfigBase("", "", "") {
0286   std::string mthn = "[PixelCalibConfiguration::PixelCalibConfiguration()]\t    ";
0287 
0288   _bufferData = true;
0289 
0290   std::ifstream in(filename.c_str());
0291 
0292   if (!in.good()) {
0293     std::cout << __LINE__ << "]\t" << mthn << "Could not open:" << filename << std::endl;
0294     assert(0);
0295   } else {
0296     std::cout << __LINE__ << "]\t" << mthn << "Opened:" << filename << std::endl;
0297   }
0298 
0299   std::string tmp;
0300 
0301   in >> tmp;
0302 
0303   if (tmp == "Mode:") {
0304     in >> mode_;
0305     std::cout << __LINE__ << "]\t" << mthn << "PixelCalibConfiguration mode=" << mode_ << std::endl;
0306     in >> tmp;
0307   } else {
0308     mode_ = "FEDChannelOffsetPixel";
0309     std::cout << __LINE__ << "]\t" << mthn << "PixelCalibConfiguration mode not set, is this an old file? " << __LINE__
0310               << "]\t" << std::endl;
0311     assert(0);
0312   }
0313 
0314   singleROC_ = false;
0315 
0316   if (tmp == "SingleROC") {
0317     singleROC_ = true;
0318     in >> tmp;
0319   }
0320 
0321   // Read in parameters, if any.
0322   if (tmp == "Parameters:") {
0323     in >> tmp;
0324     while (tmp != "Rows:") {
0325       assert(!in.eof());
0326       std::string paramName = tmp;
0327       in >> tmp;  // tmp contains the parameter value
0328       parameters_[paramName] = tmp;
0329       in >> tmp;  // tmp contains the next parameter's name, or "Rows:"
0330     }
0331   }
0332 
0333   assert(tmp == "Rows:");
0334 
0335   in >> tmp;
0336 
0337   std::vector<unsigned int> rows;
0338   while (tmp != "Cols:") {
0339     if (tmp == "|") {
0340       rows_.push_back(rows);
0341       rows.clear();
0342     } else {
0343       if (tmp != "*") {
0344         rows.push_back(atoi(tmp.c_str()));
0345       }
0346     }
0347     in >> tmp;
0348   }
0349   rows_.push_back(rows);
0350   rows.clear();
0351 
0352   in >> tmp;
0353 
0354   std::vector<unsigned int> cols;
0355   while ((tmp != "VcalLow:") && (tmp != "VcalHigh:") && (tmp != "Vcal:") && (tmp != "VcalHigh") && (tmp != "VcalLow")) {
0356     if (tmp == "|") {
0357       cols_.push_back(cols);
0358       cols.clear();
0359     } else {
0360       if (tmp != "*") {
0361         cols.push_back(atoi(tmp.c_str()));
0362       }
0363     }
0364     in >> tmp;
0365   }
0366   cols_.push_back(cols);
0367   cols.clear();
0368 
0369   highVCalRange_ = true;
0370 
0371   if (tmp == "VcalLow") {
0372     highVCalRange_ = false;
0373     in >> tmp;
0374   }
0375 
0376   if (tmp == "VcalHigh") {
0377     highVCalRange_ = true;
0378     in >> tmp;
0379   }
0380 
0381   if (tmp == "VcalLow:") {
0382     highVCalRange_ = false;
0383   }
0384 
0385   if ((tmp == "VcalLow:") || (tmp == "VcalHigh:") || (tmp == "Vcal:")) {
0386     unsigned int first, last, step;
0387     in >> first >> last >> step;
0388     unsigned int index = 1;
0389     if (!dacs_.empty()) {
0390       index = dacs_.back().index() * dacs_.back().getNPoints();
0391     }
0392     in >> tmp;
0393     bool mix = false;
0394     if (tmp == "mix") {
0395       mix = true;
0396       in >> tmp;
0397     }
0398     PixelDACScanRange dacrange(pos::k_DACName_Vcal, first, last, step, index, mix);
0399     dacs_.push_back(dacrange);
0400   } else {
0401     //in >> tmp;
0402     while (tmp == "Scan:" || tmp == "ScanValues:") {
0403       if (tmp == "ScanValues:") {
0404         std::string dacname;
0405         in >> dacname;
0406         vector<unsigned int> values;
0407         int val;
0408         in >> val;
0409         while (val != -1) {
0410           values.push_back(val);
0411           in >> val;
0412         }
0413         unsigned int index = 1;
0414         if (!dacs_.empty()) {
0415           index = dacs_.back().index() * dacs_.back().getNPoints();
0416         }
0417         PixelDACScanRange dacrange(dacname, values, index, false);
0418         dacs_.push_back(dacrange);
0419         in >> tmp;
0420       } else {
0421         std::string dacname;
0422         in >> dacname;
0423         unsigned int first, last, step;
0424         in >> first >> last >> step;
0425         unsigned int index = 1;
0426         if (!dacs_.empty()) {
0427           index = dacs_.back().index() * dacs_.back().getNPoints();
0428         }
0429         in >> tmp;
0430         bool mix = false;
0431         if (tmp == "mix") {
0432           mix = true;
0433           in >> tmp;
0434         }
0435         PixelDACScanRange dacrange(dacname, first, last, step, index, mix);
0436         dacs_.push_back(dacrange);
0437       }
0438     }
0439 
0440     while ((tmp == "Set:") || (tmp == "SetRelative:")) {
0441       string name;
0442       in >> name;
0443       int val;
0444       in >> val;
0445       unsigned int absval = std::abs(val);
0446       unsigned int index = 1;
0447       if (!dacs_.empty())
0448         index = dacs_.back().index() * dacs_.back().getNPoints();
0449       PixelDACScanRange dacrange(name, absval, absval, 1, index, false);
0450       if (tmp == "SetRelative:") {
0451         dacrange.setRelative();
0452         if (val < 0) {
0453           dacrange.setNegative();
0454         }
0455       }
0456       dacs_.push_back(dacrange);
0457       in >> tmp;
0458     }
0459   }
0460 
0461   assert(tmp == "Repeat:");
0462 
0463   in >> ntrigger_;
0464 
0465   in >> tmp;
0466 
0467   usesROCList_ = false;
0468   bool buildROCListNow = false;
0469   if (tmp == "Rocs:") {
0470     buildROCListNow = true;
0471     usesROCList_ = true;
0472   } else {
0473     assert(tmp == "ToCalibrate:");
0474     buildROCListNow = false;
0475   }
0476 
0477   while (!in.eof()) {
0478     tmp = "";
0479     in >> tmp;
0480 
0481     // added by F.Blekman to be able to deal with POS245 style calib.dat files in CMSSW
0482     // these files use the syntax:
0483     // Rocs:
0484     // all
0485 
0486     if (tmp == "all" || tmp == "+" || tmp == "-") {
0487       buildROCListNow = false;
0488     }
0489     // end of addition by F.B.
0490 
0491     if (tmp.empty())
0492       continue;
0493     rocListInstructions_.push_back(tmp);
0494   }
0495 
0496   in.close();
0497 
0498   rocAndModuleListsBuilt_ = false;
0499   if (buildROCListNow) {
0500     std::set<PixelROCName> rocSet;
0501     for (std::vector<std::string>::iterator rocListInstructions_itr = rocListInstructions_.begin();
0502          rocListInstructions_itr != rocListInstructions_.end();
0503          ++rocListInstructions_itr) {
0504       PixelROCName rocname(*rocListInstructions_itr);
0505       rocSet.insert(rocname);
0506     }
0507     buildROCAndModuleListsFromROCSet(rocSet);
0508   }
0509 
0510   objectsDependingOnTheNameTranslationBuilt_ = false;
0511 
0512   // Added by Dario as a temporary patch for Debbie (this will disappear in the future)
0513   std::ifstream inTmp(filename.c_str());
0514   calibFileContent_ = "";
0515   while (!inTmp.eof()) {
0516     std::string tmpString;
0517     getline(inTmp, tmpString);
0518     calibFileContent_ += tmpString + "\n";
0519     //cout << __LINE__ << "]\t" << "[PixelCalibConfiguration::~PixelCalibConfiguration()]\t\t" << calibFileContent_ << endl ;
0520   }
0521   inTmp.close();
0522   // End of temporary patch
0523 
0524   return;
0525 }
0526 
0527 PixelCalibConfiguration::~PixelCalibConfiguration() {}
0528 
0529 void PixelCalibConfiguration::buildROCAndModuleLists(const PixelNameTranslation* translation,
0530                                                      const PixelDetectorConfig* detconfig) {
0531   assert(translation != nullptr);
0532   assert(detconfig != nullptr);
0533 
0534   if (rocAndModuleListsBuilt_) {
0535     buildObjectsDependingOnTheNameTranslation(translation);
0536     return;
0537   }
0538 
0539   // Build the ROC set from the instructions.
0540   std::set<PixelROCName> rocSet;
0541   bool addNext = true;
0542   const map<PixelROCName, PixelROCStatus>& iroclist = detconfig->getROCsList();
0543   for (std::vector<std::string>::iterator rocListInstructions_itr = rocListInstructions_.begin();
0544        rocListInstructions_itr != rocListInstructions_.end();
0545        ++rocListInstructions_itr) {
0546     std::string instruction = *rocListInstructions_itr;
0547 
0548     if (instruction == "+") {
0549       addNext = true;
0550       continue;
0551     }
0552     if (instruction == "-") {
0553       addNext = false;
0554       continue;
0555     }
0556 
0557     if (instruction == "all") {
0558       if (addNext)  // add all ROCs in the configuration
0559       {
0560         const std::vector<PixelModuleName>& moduleList = detconfig->getModuleList();
0561         for (std::vector<PixelModuleName>::const_iterator moduleList_itr = moduleList.begin();
0562              moduleList_itr != moduleList.end();
0563              ++moduleList_itr) {
0564           std::vector<PixelROCName> ROCsOnThisModule = translation->getROCsFromModule(*moduleList_itr);
0565           for (std::vector<PixelROCName>::const_iterator ROCsOnThisModule_itr = ROCsOnThisModule.begin();
0566                ROCsOnThisModule_itr != ROCsOnThisModule.end();
0567                ++ROCsOnThisModule_itr) {
0568             map<PixelROCName, PixelROCStatus>::const_iterator it = iroclist.find(*ROCsOnThisModule_itr);
0569             assert(it != iroclist.end());
0570             PixelROCStatus istatus = it->second;
0571             if (!istatus.get(PixelROCStatus::noAnalogSignal))
0572               rocSet.insert(*ROCsOnThisModule_itr);
0573           }
0574         }
0575       } else  // remove all ROCs
0576       {
0577         rocSet.clear();
0578       }
0579       addNext = true;
0580       continue;
0581     }
0582 
0583     // Assume it's a ROC or module name.
0584     PixelModuleName modulename(instruction);
0585 
0586     // Skip if this module (or the module this ROC is on) isn't in the detector config.
0587     if (!(detconfig->containsModule(modulename))) {
0588       addNext = true;
0589       continue;
0590     }
0591 
0592     if (modulename.modulename() == instruction)  // it's a module
0593     {
0594       std::vector<PixelROCName> ROCsOnThisModule = translation->getROCsFromModule(modulename);
0595       for (std::vector<PixelROCName>::iterator ROCsOnThisModule_itr = ROCsOnThisModule.begin();
0596            ROCsOnThisModule_itr != ROCsOnThisModule.end();
0597            ++ROCsOnThisModule_itr) {
0598         if (addNext) {
0599           map<PixelROCName, PixelROCStatus>::const_iterator it = iroclist.find(*ROCsOnThisModule_itr);
0600           assert(it != iroclist.end());
0601           PixelROCStatus istatus = it->second;
0602           if (!istatus.get(PixelROCStatus::noAnalogSignal))
0603             rocSet.insert(*ROCsOnThisModule_itr);
0604         } else
0605           rocSet.erase(*ROCsOnThisModule_itr);
0606       }
0607       addNext = true;
0608       continue;
0609     } else  // it's a ROC
0610     {
0611       PixelROCName rocname(instruction);
0612       if (addNext) {
0613         // Only add this ROC if it's in the configuration.
0614         bool foundIt = false;
0615         std::list<const PixelROCName*> allROCs = translation->getROCs();
0616         for (std::list<const PixelROCName*>::iterator allROCs_itr = allROCs.begin(); allROCs_itr != allROCs.end();
0617              ++allROCs_itr) {
0618           if ((*(*allROCs_itr)) == rocname) {
0619             foundIt = true;
0620             break;
0621           }
0622         }
0623         if (foundIt) {
0624           map<PixelROCName, PixelROCStatus>::const_iterator it = iroclist.find(rocname);
0625           assert(it != iroclist.end());
0626           PixelROCStatus istatus = it->second;
0627           if (!istatus.get(PixelROCStatus::noAnalogSignal))
0628             rocSet.insert(rocname);
0629         }
0630       } else {
0631         rocSet.erase(rocname);
0632       }
0633       addNext = true;
0634       continue;
0635     }
0636 
0637     // should never get here
0638     assert(0);
0639   }
0640   // done building ROC set
0641 
0642   buildROCAndModuleListsFromROCSet(rocSet);
0643 
0644   buildObjectsDependingOnTheNameTranslation(translation);
0645 }
0646 
0647 void PixelCalibConfiguration::buildROCAndModuleListsFromROCSet(const std::set<PixelROCName>& rocSet) {
0648   assert(!rocAndModuleListsBuilt_);
0649 
0650   std::string mthn = "[PixelCalibConfiguration::buildROCAndModuleListsFromROCSet()]    ";
0651   // Build the ROC list from the ROC set.
0652   for (std::set<PixelROCName>::iterator rocSet_itr = rocSet.begin(); rocSet_itr != rocSet.end(); ++rocSet_itr) {
0653     rocs_.push_back(*rocSet_itr);
0654   }
0655 
0656   //t.stop();
0657   //cout << "buildROCAndModuleListsFromROCSet 1 time="<<t.tottime()<<endl;
0658   //t.start();
0659 
0660   // Build the module set from the ROC set.
0661   std::map<PixelModuleName, unsigned int> countROC;
0662   for (std::set<PixelROCName>::iterator rocSet_itr = rocSet.begin(); rocSet_itr != rocSet.end(); ++rocSet_itr) {
0663     //t1.start();
0664     PixelModuleName modulename(*rocSet_itr);
0665     //t1.stop();
0666     //t2.start();
0667     modules_.insert(modulename);
0668     countROC[modulename]++;
0669     //t2.stop();
0670   }
0671 
0672   //t.stop();
0673   //cout << "buildROCAndModuleListsFromROCSet 2 time="<<t.tottime()<<endl;
0674   //cout << "buildROCAndModuleListsFromROCSet t1="<<t1.tottime()<<endl;
0675   //cout << "buildROCAndModuleListsFromROCSet t2="<<t2.tottime()<<endl;
0676   //t.start();
0677 
0678   // Test printout.
0679   /*cout << "\nROC list:\n";
0680     for ( std::vector<PixelROCName>::iterator rocs_itr = rocs_.begin(); 
0681     rocs_itr != rocs_.end(); 
0682     rocs_itr++ ){
0683     cout << rocs_itr->rocname() << "\n";
0684     }    cout << "\nModule list:\n";
0685     for ( std::set<PixelModuleName>::iterator modules_itr = modules_.begin(); modules_itr != modules_.end(); modules_itr++ )
0686     {
0687     cout << modules_itr->modulename() << "\n";
0688     }
0689     cout << "\n";*/
0690 
0691   // Determine max ROCs on a module for singleROC mode.
0692   nROC_ = 1;
0693   if (singleROC_) {
0694     unsigned maxROCs = 0;
0695     for (std::map<PixelModuleName, unsigned int>::iterator imodule = countROC.begin(); imodule != countROC.end();
0696          ++imodule) {
0697       if (imodule->second > maxROCs)
0698         maxROCs = imodule->second;
0699     }
0700     nROC_ = maxROCs;
0701 
0702     std::cout << __LINE__ << "]\t" << mthn << "Max ROCs on a module=" << nROC_ << std::endl;
0703   }
0704 
0705   for (unsigned int irocs = 0; irocs < rocs_.size(); irocs++) {
0706     old_irows.push_back(-1);
0707     old_icols.push_back(-1);
0708   }
0709 
0710   rocAndModuleListsBuilt_ = true;
0711 }
0712 
0713 void PixelCalibConfiguration::buildObjectsDependingOnTheNameTranslation(const PixelNameTranslation* aNameTranslation) {
0714   assert(!objectsDependingOnTheNameTranslationBuilt_);
0715   assert(rocAndModuleListsBuilt_);
0716   assert(aNameTranslation != nullptr);
0717 
0718   // Build the channel list.
0719   assert(channels_.empty());
0720   for (std::vector<PixelROCName>::const_iterator rocs_itr = rocs_.begin(); rocs_itr != rocs_.end(); ++rocs_itr) {
0721     channels_.insert(aNameTranslation->getChannelForROC(*rocs_itr));
0722   }
0723 
0724   // Build the maps from ROC to ROC number.
0725 
0726   assert(ROCNumberOnChannelAmongThoseCalibrated_.empty() && numROCsCalibratedOnChannel_.empty());
0727 
0728   std::set<PixelROCName> tempROCs;
0729 
0730   for (std::vector<PixelROCName>::const_iterator it = rocs_.begin(); it != rocs_.end(); ++it) {
0731     tempROCs.insert(*it);
0732   }
0733 
0734   for (std::set<PixelChannel>::const_iterator channels_itr = channels_.begin(); channels_itr != channels_.end();
0735        ++channels_itr) {
0736     std::vector<PixelROCName> rocsOnChannel = aNameTranslation->getROCsFromChannel(*channels_itr);
0737 
0738     std::set<PixelROCName> foundROCs;
0739 
0740     for (std::vector<PixelROCName>::const_iterator rocsOnChannel_itr = rocsOnChannel.begin();
0741          rocsOnChannel_itr != rocsOnChannel.end();
0742          ++rocsOnChannel_itr) {
0743       if (tempROCs.find(*rocsOnChannel_itr) != tempROCs.end()) {
0744         ROCNumberOnChannelAmongThoseCalibrated_[*rocsOnChannel_itr] = foundROCs.size();
0745         foundROCs.insert(*rocsOnChannel_itr);
0746       }
0747     }
0748 
0749     for (std::set<PixelROCName>::const_iterator foundROCs_itr = foundROCs.begin(); foundROCs_itr != foundROCs.end();
0750          ++foundROCs_itr) {
0751       numROCsCalibratedOnChannel_[*foundROCs_itr] = foundROCs.size();
0752     }
0753   }
0754 
0755   objectsDependingOnTheNameTranslationBuilt_ = true;
0756 }
0757 
0758 unsigned int PixelCalibConfiguration::iScan(std::string dac) const {
0759   for (unsigned int i = 0; i < dacs_.size(); i++) {
0760     if (dac == dacs_[i].name())
0761       return i;
0762   }
0763 
0764   std::cout << __LINE__ << "]\t[PixelCalibConfiguration::iScan()]\t\t    could not find dac=" << dac << std::endl;
0765 
0766   assert(0);
0767 
0768   return 0;
0769 }
0770 
0771 unsigned int PixelCalibConfiguration::scanROC(unsigned int state) const {
0772   assert(state < nConfigurations());
0773 
0774   unsigned int i_ROC = state / (cols_.size() * rows_.size() * nScanPoints());
0775 
0776   return i_ROC;
0777 }
0778 
0779 unsigned int PixelCalibConfiguration::scanValue(unsigned int iscan,
0780                                                 unsigned int state,
0781                                                 unsigned int ROCNumber,
0782                                                 unsigned int ROCsOnChannel) const {
0783   unsigned int i_threshold = scanCounter(iscan, state);
0784 
0785   // Spread the DAC values on the different ROCs uniformly across the scan range.
0786   if (dacs_[iscan].mixValuesAcrossROCs())
0787     i_threshold = (i_threshold + (nScanPoints(iscan) * ROCNumber) / ROCsOnChannel) % nScanPoints(iscan);
0788 
0789   unsigned int threshold = dacs_[iscan].value(i_threshold);
0790 
0791   //assert(threshold==dacs_[iscan].first()+i_threshold*dacs_[iscan].step());
0792 
0793   return threshold;
0794 }
0795 
0796 bool PixelCalibConfiguration::scanningROCForState(PixelROCName roc, unsigned int state) const {
0797   if (!singleROC_)
0798     return true;
0799   return scanROC(state) == ROCNumberOnChannelAmongThoseCalibrated(roc);
0800 }
0801 
0802 unsigned int PixelCalibConfiguration::scanValue(unsigned int iscan, unsigned int state, PixelROCName roc) const {
0803   unsigned int ROCNumber = ROCNumberOnChannelAmongThoseCalibrated(roc);
0804   unsigned int ROCsOnChannel = numROCsCalibratedOnChannel(roc);
0805 
0806   return scanValue(iscan, state, ROCNumber, ROCsOnChannel);
0807 }
0808 
0809 unsigned int PixelCalibConfiguration::ROCNumberOnChannelAmongThoseCalibrated(PixelROCName roc) const {
0810   assert(objectsDependingOnTheNameTranslationBuilt_);
0811   std::map<PixelROCName, unsigned int>::const_iterator foundROC = ROCNumberOnChannelAmongThoseCalibrated_.find(roc);
0812   assert(foundROC != ROCNumberOnChannelAmongThoseCalibrated_.end());
0813   return foundROC->second;
0814 }
0815 
0816 unsigned int PixelCalibConfiguration::numROCsCalibratedOnChannel(PixelROCName roc) const {
0817   assert(objectsDependingOnTheNameTranslationBuilt_);
0818   std::map<PixelROCName, unsigned int>::const_iterator foundROC = numROCsCalibratedOnChannel_.find(roc);
0819   assert(foundROC != numROCsCalibratedOnChannel_.end());
0820   return foundROC->second;
0821 }
0822 
0823 unsigned int PixelCalibConfiguration::scanCounter(unsigned int iscan, unsigned int state) const {
0824   assert(state < nConfigurations());
0825 
0826   unsigned int i_scan = state % nScanPoints();
0827 
0828   for (unsigned int i = 0; i < iscan; i++) {
0829     i_scan /= nScanPoints(i);
0830   }
0831 
0832   unsigned int i_threshold = i_scan % nScanPoints(iscan);
0833 
0834   return i_threshold;
0835 }
0836 
0837 unsigned int PixelCalibConfiguration::rowCounter(unsigned int state) const {
0838   unsigned int i_row =
0839       (state - scanROC(state) * cols_.size() * rows_.size() * nScanPoints()) / (cols_.size() * nScanPoints());
0840   assert(i_row < rows_.size());
0841   return i_row;
0842 }
0843 
0844 unsigned int PixelCalibConfiguration::colCounter(unsigned int state) const {
0845   unsigned int i_col = (state - scanROC(state) * cols_.size() * rows_.size() * nScanPoints() -
0846                         rowCounter(state) * cols_.size() * nScanPoints()) /
0847                        (nScanPoints());
0848   assert(i_col < cols_.size());
0849   return i_col;
0850 }
0851 
0852 void PixelCalibConfiguration::nextFECState(std::map<unsigned int, PixelFECConfigInterface*>& pixelFECs,
0853                                            PixelDetectorConfig* detconfig,
0854                                            PixelNameTranslation* trans,
0855                                            std::map<pos::PixelModuleName, pos::PixelMaskBase*>* masks,
0856                                            std::map<pos::PixelModuleName, pos::PixelTrimBase*>* trims,
0857                                            std::map<pos::PixelModuleName, pos::PixelDACSettings*>* dacs,
0858 
0859                                            unsigned int state) const {
0860   std::string mthn = "[PixelCalibConfiguration::nextFECState()]\t\t    ";
0861   std::string modeName = parameterValue("ScanMode");
0862 
0863   int mode = -1;
0864 
0865   if (modeName == "maskAllPixel")
0866     mode = 0;
0867   if (modeName == "useAllPixel" || modeName.empty())
0868     mode = 1;
0869   if (modeName == "default")
0870     mode = 2;
0871 
0872   static bool first = true;
0873 
0874   if (first) {
0875     cout << __LINE__ << "]\t" << mthn << "mode=" << mode << endl;
0876     first = false;
0877   }
0878 
0879   if (mode == -1) {
0880     cout << __LINE__ << "]\t" << mthn << "ScanMode=" << modeName << " not understood." << endl;
0881     ::abort();
0882   }
0883 
0884   if (rocInfo_.empty()) {
0885     //here we will do some initialization...
0886     for (unsigned int i = 0; i < rocs_.size(); i++) {
0887       const PixelHdwAddress* hdwadd = trans->getHdwAddress(rocs_[i]);
0888       PixelROCInfo rocInfo;
0889       rocInfo.use_ = true;
0890       //FIXME This is very inefficient
0891       PixelModuleName module(rocs_[i].rocname());
0892 
0893       std::map<pos::PixelModuleName, pos::PixelMaskBase*>::const_iterator foundMask = masks->find(module);
0894       if (foundMask == masks->end()) {
0895         rocInfo.use_ = false;
0896         rocInfo_.push_back(rocInfo);
0897         continue;
0898       }
0899 
0900       rocInfo.hdwadd_ = hdwadd;
0901       rocInfo.trims_ = (*trims)[module]->getTrimBits(rocs_[i]);
0902       rocInfo.masks_ = (*masks)[module]->getMaskBits(rocs_[i]);
0903 
0904 #ifdef BPIX
0905       const PixelChannel channel = trans->getChannelForROC(rocs_[i]);
0906       string tbmChannel = channel.TBMChannelString();
0907       //cout<<" tbm channel "<<tbmChannel<<endl;
0908       rocInfo.tbmChannel_ = tbmChannel;
0909 #endif
0910 
0911       std::map<std::string, unsigned int> defaultDACValues;
0912       (*dacs)[PixelModuleName(rocs_[i].rocname())]->getDACSettings(rocs_[i])->getDACs(defaultDACValues);
0913 
0914       for (std::vector<PixelDACScanRange>::const_iterator dacs_itr = dacs_.begin(); dacs_itr != dacs_.end();
0915            ++dacs_itr) {
0916         std::map<std::string, unsigned int>::const_iterator foundThisDAC = defaultDACValues.find(dacs_itr->name());
0917         assert(foundThisDAC != defaultDACValues.end());
0918 
0919         pair<unsigned int, unsigned int> dacchannelAndValue(dacs_itr->dacchannel(), foundThisDAC->second);
0920 
0921         rocInfo.defaultDACs_.push_back(dacchannelAndValue);
0922       }
0923       rocInfo_.push_back(rocInfo);
0924     }
0925   }
0926 
0927   assert(rocs_.size() == rocInfo_.size());
0928 
0929   bool changedWBC = false;
0930 
0931   //std::map<unsigned int, PixelFECConfigInterface*>::iterator iPixelFEC=pixelFECs.begin();
0932   //for(;iPixelFEC!=pixelFECs.end();++iPixelFEC){
0933   //iPixelFEC->second->fecDebug(1);
0934   //}
0935 
0936   //unsigned long version=0;
0937   //pixelFEC->getversion(&version);
0938   //std::cout<<"mfec firmware version:"<<version<<std::endl;
0939 
0940   assert(rocAndModuleListsBuilt_);
0941 
0942   assert(state < nConfigurations());
0943 
0944   // Which set of rows we're on.
0945   unsigned int i_row = rowCounter(state);
0946 
0947   // Which set of columns we're on.
0948   unsigned int i_col = colCounter(state);
0949 
0950   // Whether we're beginning a new scan over the DACs after changing which ROC or which pixel pattern.
0951   unsigned int first_scan = true;
0952   for (unsigned int i = 0; i < dacs_.size(); i++) {
0953     if (scanCounter(i, state) != 0)
0954       first_scan = false;
0955   }
0956 
0957   // Disable all pixels at the beginning.
0958   if (state == 0 && (mode == 0 || mode == 1)) {
0959     for (unsigned int i = 0; i < rocs_.size(); i++) {
0960       if (!rocInfo_[i].use_)
0961         continue;
0962 
0963       PixelHdwAddress theROC = *rocInfo_[i].hdwadd_;
0964       PixelROCTrimBits* rocTrims = rocInfo_[i].trims_;
0965 
0966       //Turn off all pixels
0967       disablePixels(pixelFECs[theROC.fecnumber()], rocTrims, theROC);
0968     }
0969 
0970     // reset
0971     //cout<<"finish init"<<endl;
0972     //sleep(1);
0973     //pixelFEC->injectrstroc(7,1);
0974     // or do    pixelFEC->rocreset(theROC.mfec(),
0975     //             theROC.mfecchannel(),
0976     //             14,                    //FIXME hardcode for Channel A
0977     //             theROC.hubaddress());
0978   }
0979 
0980   // When a scan is complete for a given ROC or pixel pattern, reset the DACs to default values and disable the previously-enabled pixels.
0981   if (first_scan && state != 0 && mode != 2) {
0982     unsigned int previousState = state - 1;
0983 
0984     unsigned int i_row_previous = rowCounter(previousState);
0985 
0986     unsigned int i_col_previous = colCounter(previousState);
0987 
0988     for (unsigned int i = 0; i < rocs_.size(); i++) {
0989       if (!rocInfo_[i].use_)
0990         continue;
0991 
0992       PixelHdwAddress theROC = *rocInfo_[i].hdwadd_;
0993 
0994       if (!scanningROCForState(rocs_[i], previousState))
0995         continue;
0996 
0997       // Set the DACs back to their default values when we're done with a scan.
0998       for (unsigned int j = 0; j < dacs_.size(); j++) {
0999         //Try to not reprogram DACs as often..
1000         if (state != 0) {
1001           if (scanCounter(dacs_[j].name(), state) == scanCounter(dacs_[j].name(), state - 1)) {
1002             continue;
1003           }
1004         }
1005 
1006         pixelFECs[theROC.fecnumber()]->progdac(theROC.mfec(),
1007                                                theROC.mfecchannel(),
1008                                                theROC.hubaddress(),
1009                                                theROC.portaddress(),
1010                                                theROC.rocid(),
1011                                                rocInfo_[i].defaultDACs_[j].first,
1012                                                rocInfo_[i].defaultDACs_[j].second,
1013                                                _bufferData);
1014 
1015         if (dacs_[j].dacchannel() == k_DACAddress_WBC) {
1016           changedWBC = true;
1017           //cout << "Changed WBC 1"<<endl;
1018         }
1019       }
1020 
1021       PixelROCTrimBits* rocTrims = rocInfo_[i].trims_;
1022 
1023       disablePixels(pixelFECs[theROC.fecnumber()], i_row_previous, i_col_previous, rocTrims, theROC);
1024     }
1025   }
1026 
1027   // Set each ROC with the new settings for this state.
1028   for (unsigned int i = 0; i < rocs_.size(); i++) {
1029     if (!rocInfo_[i].use_)
1030       continue;
1031 
1032     PixelHdwAddress theROC = *rocInfo_[i].hdwadd_;
1033 
1034     // Skip this ROC if we're in SingleROC mode and we're not on this ROC number.
1035     if (!scanningROCForState(rocs_[i], state))
1036       continue;
1037 
1038     //  std::cout << "Will call progdac for vcal:"<< vcal << std::endl;
1039 
1040     // Program all the DAC values.
1041     for (unsigned int ii = 0; ii < dacs_.size(); ii++) {
1042       //Try to not reprogram DACs as often..
1043       if (state != 0) {
1044         if (scanCounter(dacs_[ii].name(), state) == scanCounter(dacs_[ii].name(), state - 1)) {
1045           continue;
1046         }
1047       }
1048 
1049       int dacvalue = scanValue(ii, state, rocs_[i]);
1050 
1051       //cout << "dacname ii:"<<dacs_[ii].name()<<" "<<ii<<endl;
1052 
1053       if (dacs_[ii].relative()) {
1054         //We have to find the default DAC setting so that we can
1055         //add the offset as we are in relative mode.
1056 
1057         if (dacs_[ii].negative())
1058           dacvalue = -dacvalue;
1059 
1060         dacvalue += rocInfo_[i].defaultDACs_[ii].second;
1061         //cout << "[PixelCalibConfiguration::nextFECState] ROC="<<rocs_[i]
1062         //     << " dac="<<dacs_[ii].name()<<" new value="<<dacvalue<<endl;
1063       }
1064 
1065       pixelFECs[theROC.fecnumber()]->progdac(theROC.mfec(),
1066                                              theROC.mfecchannel(),
1067                                              theROC.hubaddress(),
1068                                              theROC.portaddress(),
1069                                              theROC.rocid(),
1070                                              rocInfo_[i].defaultDACs_[ii].first,
1071                                              dacvalue,
1072                                              _bufferData);
1073 
1074       if (dacs_[ii].dacchannel() == k_DACAddress_WBC) {
1075         changedWBC = true;
1076         //cout << "Changed WBC 2"<<endl;
1077       }
1078     }
1079 
1080     // At the beginning of a scan, set the pixel pattern.
1081     if (first_scan) {
1082       // Set masks and trims.
1083       if (mode != 2) {
1084         PixelROCMaskBits* rocMasks = rocInfo_[i].masks_;
1085         PixelROCTrimBits* rocTrims = rocInfo_[i].trims_;
1086 
1087         if (mode == 1)
1088           rocMasks = nullptr;
1089 
1090         //std::cout << "Will enable pixels!" <<std::endl;
1091         enablePixels(pixelFECs[theROC.fecnumber()], i_row, i_col, rocMasks, rocTrims, theROC);
1092       }
1093 
1094       // Set high or low Vcal range.
1095 
1096       if (state == 0) {
1097         PixelModuleName module(rocs_[i].rocname());
1098 
1099         unsigned int roccontrolword = (*dacs)[module]->getDACSettings(rocs_[i])->getControlRegister();
1100 
1101         //range is controlled here by one bit, but rest must match config
1102         //bit 0 on/off= 20/40 MHz speed; bit 1 on/off=disabled/enable; bit 3=Vcal range
1103 
1104         if (highVCalRange_)
1105           roccontrolword |= 0x4;  //turn range bit on
1106         else
1107           roccontrolword &= 0xfb;  //turn range bit off
1108 
1109         pixelFECs[theROC.fecnumber()]->progdac(theROC.mfec(),
1110                                                theROC.mfecchannel(),
1111                                                theROC.hubaddress(),
1112                                                theROC.portaddress(),
1113                                                theROC.rocid(),
1114                                                0xfd,
1115                                                roccontrolword,
1116                                                _bufferData);
1117       }
1118 
1119       // Clear all pixels before setting the pixel pattern.
1120       pixelFECs[theROC.fecnumber()]->clrcal(
1121           theROC.mfec(), theROC.mfecchannel(), theROC.hubaddress(), theROC.portaddress(), theROC.rocid(), _bufferData);
1122 
1123       // Program the pixel pattern.
1124       unsigned int nrow = rows_[i_row].size();
1125       unsigned int ncol = cols_[i_col].size();
1126       unsigned int nmax = std::max(nrow, ncol);
1127       if (nrow == 0 || ncol == 0)
1128         nmax = 0;
1129       for (unsigned int n = 0; n < nmax; n++) {
1130         unsigned int irow = n;
1131         unsigned int icol = n;
1132         if (irow >= nrow)
1133           irow = nrow - 1;
1134         if (icol >= ncol)
1135           icol = ncol - 1;
1136         unsigned int row = rows_[i_row][irow];
1137         unsigned int col = cols_[i_col][icol];
1138 
1139         pixelFECs[theROC.fecnumber()]->calpix(theROC.mfec(),
1140                                               theROC.mfecchannel(),
1141                                               theROC.hubaddress(),
1142                                               theROC.portaddress(),
1143                                               theROC.rocid(),
1144                                               col,
1145                                               row,
1146                                               1,
1147                                               _bufferData);
1148       }
1149 
1150     }  // end of instructions for the beginning of a scan
1151   }  // end of loop over ROCs
1152 
1153   if (_bufferData) {
1154     std::map<unsigned int, PixelFECConfigInterface*>::iterator iPixelFEC = pixelFECs.begin();
1155     for (; iPixelFEC != pixelFECs.end(); ++iPixelFEC) {
1156       iPixelFEC->second->qbufsend();
1157     }
1158   }
1159 
1160   if (changedWBC) {
1161     for (unsigned int i = 0; i < rocs_.size(); i++) {
1162       if (!rocInfo_[i].use_)
1163         continue;
1164 
1165       PixelHdwAddress theROC = *rocInfo_[i].hdwadd_;
1166 
1167       int tbmRegister = 14;  // define for TBM-A
1168 #ifdef BPIX
1169       string tbmChannel = rocInfo_[i].tbmChannel_;  // get TBM channel
1170       if (tbmChannel == "B")
1171         tbmRegister = 15;  // for TBM=B
1172 #endif
1173 
1174       pixelFECs[theROC.fecnumber()]->rocreset(theROC.mfec(), theROC.mfecchannel(), tbmRegister, theROC.hubaddress());
1175     }  // for rocs
1176   }
1177 
1178   return;
1179 }
1180 
1181 // FIXME This code breaks if it is called more than once with different crate numbers!
1182 std::vector<std::pair<unsigned int, std::vector<unsigned int> > >& PixelCalibConfiguration::fedCardsAndChannels(
1183     unsigned int crate,
1184     PixelNameTranslation* translation,
1185     PixelFEDConfig* fedconfig,
1186     PixelDetectorConfig* detconfig) const {
1187   assert(rocAndModuleListsBuilt_);
1188 
1189   assert(!rocs_.empty());
1190 
1191   for (unsigned int i = 0; i < rocs_.size(); i++) {
1192     PixelModuleName module(rocs_[i].rocname());
1193     if (!detconfig->containsModule(module))
1194       continue;
1195     const PixelHdwAddress* hdw = translation->getHdwAddress(rocs_[i]);
1196     assert(hdw != nullptr);
1197     //std::cout << "ROC, fednumber:"<<rocs_[i]<<" "<<hdw->fednumber()
1198     //    << std::endl;
1199     //first check if fed associated with the roc is in the right crate
1200     if (fedconfig->crateFromFEDNumber(hdw->fednumber()) != crate)
1201       continue;
1202     //next look if we have already found fed number
1203     unsigned int index = fedCardsAndChannels_.size();
1204     for (unsigned int j = 0; j < fedCardsAndChannels_.size(); j++) {
1205       if (fedCardsAndChannels_[j].first == hdw->fednumber()) {
1206         index = j;
1207         break;
1208       }
1209     }
1210     //If we didn't find the fedcard we will create it
1211     if (index == fedCardsAndChannels_.size()) {
1212       std::vector<unsigned int> tmp;
1213       tmp.push_back(hdw->fedchannel());
1214       std::pair<unsigned int, std::vector<unsigned int> > tmp2(hdw->fednumber(), tmp);
1215       fedCardsAndChannels_.push_back(tmp2);
1216       continue;
1217     }
1218     //Now look and see if the channel has been added
1219     std::vector<unsigned int>& channels = fedCardsAndChannels_[index].second;
1220     bool found = false;
1221     for (unsigned int k = 0; k < channels.size(); k++) {
1222       if (channels[k] == hdw->fedchannel()) {
1223         found = true;
1224         break;
1225       }
1226     }
1227     if (found)
1228       continue;
1229     channels.push_back(hdw->fedchannel());
1230   }
1231 
1232   return fedCardsAndChannels_;
1233 }
1234 
1235 std::map<unsigned int, std::set<unsigned int> > PixelCalibConfiguration::getFEDsAndChannels(
1236     PixelNameTranslation* translation) {
1237   assert(rocAndModuleListsBuilt_);
1238 
1239   std::map<unsigned int, std::set<unsigned int> > fedsChannels;
1240   assert(!rocs_.empty());
1241   std::vector<PixelROCName>::iterator iroc = rocs_.begin();
1242 
1243   for (; iroc != rocs_.end(); ++iroc) {
1244     const PixelHdwAddress* roc_hdwaddress = translation->getHdwAddress(*iroc);
1245     unsigned int fednumber = roc_hdwaddress->fednumber();
1246     unsigned int fedchannel = roc_hdwaddress->fedchannel();
1247     fedsChannels[fednumber].insert(fedchannel);
1248   }
1249 
1250   return fedsChannels;
1251 }
1252 
1253 std::set<unsigned int> PixelCalibConfiguration::getFEDCrates(const PixelNameTranslation* translation,
1254                                                              const PixelFEDConfig* fedconfig) const {
1255   assert(rocAndModuleListsBuilt_);
1256 
1257   std::set<unsigned int> fedcrates;
1258   assert(!modules_.empty());
1259   std::set<PixelModuleName>::iterator imodule = modules_.begin();
1260 
1261   for (; imodule != modules_.end(); ++imodule) {
1262     std::set<PixelChannel> channelsOnThisModule = translation->getChannelsOnModule(*imodule);
1263     for (std::set<PixelChannel>::const_iterator channelsOnThisModule_itr = channelsOnThisModule.begin();
1264          channelsOnThisModule_itr != channelsOnThisModule.end();
1265          ++channelsOnThisModule_itr) {
1266       const PixelHdwAddress& channel_hdwaddress = translation->getHdwAddress(*channelsOnThisModule_itr);
1267       unsigned int fednumber = channel_hdwaddress.fednumber();
1268       fedcrates.insert(fedconfig->crateFromFEDNumber(fednumber));
1269     }
1270   }
1271 
1272   return fedcrates;
1273 }
1274 
1275 std::set<unsigned int> PixelCalibConfiguration::getFECCrates(const PixelNameTranslation* translation,
1276                                                              const PixelFECConfig* fecconfig) const {
1277   assert(rocAndModuleListsBuilt_);
1278 
1279   std::set<unsigned int> feccrates;
1280   assert(!modules_.empty());
1281   std::set<PixelModuleName>::iterator imodule = modules_.begin();
1282 
1283   for (; imodule != modules_.end(); ++imodule) {
1284     std::set<PixelChannel> channelsOnThisModule = translation->getChannelsOnModule(*imodule);
1285     for (std::set<PixelChannel>::const_iterator channelsOnThisModule_itr = channelsOnThisModule.begin();
1286          channelsOnThisModule_itr != channelsOnThisModule.end();
1287          ++channelsOnThisModule_itr) {
1288       const PixelHdwAddress& channel_hdwaddress = translation->getHdwAddress(*channelsOnThisModule_itr);
1289       unsigned int fecnumber = channel_hdwaddress.fecnumber();
1290       feccrates.insert(fecconfig->crateFromFECNumber(fecnumber));
1291     }
1292   }
1293 
1294   return feccrates;
1295 }
1296 
1297 std::set<unsigned int> PixelCalibConfiguration::getTKFECCrates(
1298     const PixelPortcardMap* portcardmap,
1299     const std::map<std::string, PixelPortCardConfig*>& mapNamePortCard,
1300     const PixelTKFECConfig* tkfecconfig) const {
1301   assert(rocAndModuleListsBuilt_);
1302 
1303   std::set<unsigned int> tkfeccrates;
1304   assert(!modules_.empty());
1305   std::set<PixelModuleName>::iterator imodule = modules_.begin();
1306 
1307   for (; imodule != modules_.end(); ++imodule) {
1308     // implement this by module --(PixelPortcardMap)-> port card(s) --(PixelPortCardConfig)-> FEC # --(PixelFECConfig theTKFECConfiguration_)-> crate
1309     const std::set<std::string> portCards = portcardmap->portcards(*imodule);
1310     for (std::set<std::string>::const_iterator portCards_itr = portCards.begin(); portCards_itr != portCards.end();
1311          ++portCards_itr) {
1312       const std::string& portcardname = *portCards_itr;
1313       std::map<std::string, PixelPortCardConfig*>::const_iterator portcardconfig_itr =
1314           mapNamePortCard.find(portcardname);
1315       assert(portcardconfig_itr != mapNamePortCard.end());
1316       PixelPortCardConfig* portcardconfig = portcardconfig_itr->second;
1317       std::string TKFECID = portcardconfig->getTKFECID();
1318       tkfeccrates.insert(tkfecconfig->crateFromTKFECID(TKFECID));
1319     }
1320   }
1321 
1322   return tkfeccrates;
1323 }
1324 
1325 std::ostream& pos::operator<<(std::ostream& s, const PixelCalibConfiguration& calib) {
1326   if (!calib.parameters_.empty()) {
1327     s << "Parameters:" << std::endl;
1328     for (std::map<std::string, std::string>::const_iterator paramItr = calib.parameters_.begin();
1329          paramItr != calib.parameters_.end();
1330          ++paramItr) {
1331       s << paramItr->first << " " << paramItr->second << std::endl;
1332     }
1333   }
1334 
1335   s << "Rows:" << std::endl;
1336   for (unsigned int i = 0; i < calib.rows_.size(); i++) {
1337     for (unsigned int j = 0; j < calib.rows_[i].size(); j++) {
1338       s << calib.rows_[i][j] << " " << std::endl;
1339     }
1340     s << "|" << std::endl;
1341   }
1342 
1343   s << "Cols:" << std::endl;
1344   for (unsigned int i = 0; i < calib.cols_.size(); i++) {
1345     for (unsigned int j = 0; j < calib.cols_[i].size(); j++) {
1346       s << calib.cols_[i][j] << " " << std::endl;
1347     }
1348     s << "|" << std::endl;
1349   }
1350 
1351   s << "Vcal:" << std::endl;
1352 
1353   //s << calib.vcal_<<std::endl;
1354 
1355   s << "Vcthr:" << std::endl;
1356 
1357   s << calib.dacs_[0].first() << " " << calib.dacs_[0].last() << " " << calib.dacs_[0].step() << std::endl;
1358 
1359   s << "CalDel:" << std::endl;
1360 
1361   s << calib.dacs_[1].first() << " " << calib.dacs_[0].last() << " " << calib.dacs_[1].step() << std::endl;
1362 
1363   s << "Repeat:" << std::endl;
1364 
1365   s << calib.ntrigger_ << std::endl;
1366 
1367   return s;
1368 }
1369 
1370 void PixelCalibConfiguration::enablePixels(PixelFECConfigInterface* pixelFEC,
1371                                            unsigned int irows,
1372                                            unsigned int icols,
1373                                            pos::PixelROCMaskBits* masks,
1374                                            pos::PixelROCTrimBits* trims,
1375                                            const PixelHdwAddress& theROC) const {
1376   for (unsigned int irow = 0; irow < rows_[irows].size(); irow++) {
1377     for (unsigned int icol = 0; icol < cols_[icols].size(); icol++) {
1378       /*        std::cout << "Will turn on pixel col="
1379             <<cols_[icols][icol]
1380             <<" row="<<rows_[irows][irow]<<std::endl;
1381       */
1382       unsigned int bits = trims->trim(cols_[icols][icol], rows_[irows][irow]);
1383 
1384       //if masks==0 always enable pixel
1385       if (masks == nullptr || masks->mask(cols_[icols][icol], rows_[irows][irow]))
1386         bits |= 0x80;
1387 
1388       pixelFEC->progpix(theROC.mfec(),
1389                         theROC.mfecchannel(),
1390                         theROC.hubaddress(),
1391                         theROC.portaddress(),
1392                         theROC.rocid(),
1393                         cols_[icols][icol],
1394                         rows_[irows][irow],
1395                         bits,
1396                         _bufferData);
1397     }
1398   }
1399 }
1400 
1401 void PixelCalibConfiguration::disablePixels(PixelFECConfigInterface* pixelFEC,
1402                                             unsigned int irows,
1403                                             unsigned int icols,
1404                                             pos::PixelROCTrimBits* trims,
1405                                             const PixelHdwAddress& theROC) const {
1406   for (unsigned int irow = 0; irow < rows_[irows].size(); irow++) {
1407     for (unsigned int icol = 0; icol < cols_[icols].size(); icol++) {
1408       /*        std::cout << "Will turn off pixel col="
1409               <<cols_[old_icols][icol]
1410               <<" row="<<rows_[old_irows][irow]<<std::endl;
1411           */
1412       unsigned int bits = trims->trim(cols_[icols][icol], rows_[irows][irow]);
1413       pixelFEC->progpix(theROC.mfec(),
1414                         theROC.mfecchannel(),
1415                         theROC.hubaddress(),
1416                         theROC.portaddress(),
1417                         theROC.rocid(),
1418                         cols_[icols][icol],
1419                         rows_[irows][irow],
1420                         bits,
1421                         _bufferData);
1422     }
1423   }
1424 }
1425 
1426 void PixelCalibConfiguration::disablePixels(PixelFECConfigInterface* pixelFEC,
1427                                             pos::PixelROCTrimBits* trims,
1428                                             const PixelHdwAddress& theROC) const {
1429   //cout<<" disable ROC "<<theROC.hubaddress()<<" "<<theROC.rocid()<<endl;
1430   //FIXME This should be done with more efficient commands!
1431   for (unsigned int row = 0; row < 80; row++) {
1432     for (unsigned int col = 0; col < 52; col++) {
1433       unsigned int bits = trims->trim(col, row);
1434       pixelFEC->progpix(theROC.mfec(),
1435                         theROC.mfecchannel(),
1436                         theROC.hubaddress(),
1437                         theROC.portaddress(),
1438                         theROC.rocid(),
1439                         col,
1440                         row,
1441                         bits,
1442                         _bufferData);
1443     }
1444   }
1445 }
1446 
1447 std::string PixelCalibConfiguration::parameterValue(std::string parameterName) const {
1448   std::map<std::string, std::string>::const_iterator itr = parameters_.find(parameterName);
1449   if (itr == parameters_.end())  // parameterName is not in the list
1450   {
1451     return "";
1452   } else {
1453     return itr->second;
1454   }
1455 }
1456 
1457 void PixelCalibConfiguration::writeASCII(std::string dir) const {
1458   //FIXME this is not tested for all the use cases...
1459 
1460   if (!dir.empty())
1461     dir += "/";
1462   std::string filename = dir + "calib.dat";
1463   std::ofstream out(filename.c_str());
1464 
1465   out << "Mode: " << mode_ << endl;
1466   if (singleROC_)
1467     out << "SingleROC" << endl;
1468   if (!parameters_.empty()) {
1469     out << "Parameters:" << endl;
1470     std::map<std::string, std::string>::const_iterator it = parameters_.begin();
1471     for (; it != parameters_.end(); ++it) {
1472       out << it->first << "        " << it->second << endl;
1473     }
1474   }
1475   out << "Rows:" << endl;
1476   for (unsigned int i = 0; i < rows_.size(); i++) {
1477     for (unsigned int j = 0; j < rows_[i].size(); j++) {
1478       out << rows_[i][j] << " ";
1479     }
1480     if (i != rows_.size() - 1)
1481       out << "|";
1482     out << endl;
1483   }
1484   out << "Cols:" << endl;
1485   for (unsigned int i = 0; i < cols_.size(); i++) {
1486     for (unsigned int j = 0; j < cols_[i].size(); j++) {
1487       out << cols_[i][j] << " ";
1488     }
1489     if (i != cols_.size() - 1)
1490       out << "|";
1491     out << endl;
1492   }
1493 
1494   if (highVCalRange_) {
1495     out << "VcalHigh" << endl;
1496   } else {
1497     out << "VcalLow" << endl;
1498   }
1499 
1500   for (unsigned int i = 0; i < dacs_.size(); i++) {
1501     if (dacs_[i].uniformSteps()) {
1502       if (dacs_[i].first() != dacs_[i].last()) {
1503         out << "Scan: " << dacs_[i].name() << " ";
1504         out << dacs_[i].first() << " ";
1505         out << dacs_[i].last() << " ";
1506         out << dacs_[i].step() << endl;
1507       } else {
1508         out << "Set: " << dacs_[i].name() << " ";
1509         out << dacs_[i].first() << endl;
1510       }
1511     } else {
1512       out << "ScanValues: " << dacs_[i].name() << " ";
1513       for (unsigned int ival = 0; ival < dacs_[i].getNPoints(); ival++) {
1514         out << dacs_[i].value(ival) << " ";
1515       }
1516       out << " -1" << endl;
1517     }
1518   }
1519 
1520   out << "Repeat:" << endl;
1521   out << ntrigger_ << endl;
1522 
1523   if (usesROCList_) {
1524     out << "Rocs:" << endl;
1525   } else {
1526     out << "ToCalibrate:" << endl;
1527   }
1528   for (unsigned int i = 0; i < rocListInstructions_.size(); i++) {
1529     out << rocListInstructions_[i] << endl;
1530     if (rocListInstructions_[i] == "+" || rocListInstructions_[i] == "-") {
1531       out << " ";
1532     } else {
1533       out << endl;
1534     }
1535   }
1536 
1537   out.close();
1538 }
1539 
1540 unsigned int PixelCalibConfiguration::maxNumHitsPerROC() const {
1541   unsigned int returnValue = 0;
1542   for (std::vector<std::vector<unsigned int> >::const_iterator rows_itr = rows_.begin(); rows_itr != rows_.end();
1543        ++rows_itr) {
1544     for (std::vector<std::vector<unsigned int> >::const_iterator cols_itr = cols_.begin(); cols_itr != cols_.end();
1545          ++cols_itr) {
1546       unsigned int theSize = rows_itr->size() * cols_itr->size();
1547       returnValue = max(returnValue, theSize);
1548     }
1549   }
1550   return returnValue;
1551 }
1552 
1553 std::set<std::pair<unsigned int, unsigned int> > PixelCalibConfiguration::pixelsWithHits(unsigned int state) const {
1554   std::set<std::pair<unsigned int, unsigned int> > pixels;
1555   //                  column #      row #
1556 
1557   for (std::vector<unsigned int>::const_iterator col_itr = cols_[colCounter(state)].begin();
1558        col_itr != cols_[colCounter(state)].end();
1559        ++col_itr) {
1560     for (std::vector<unsigned int>::const_iterator row_itr = rows_[rowCounter(state)].begin();
1561          row_itr != rows_[rowCounter(state)].end();
1562          ++row_itr) {
1563       pixels.insert(std::pair<unsigned int, unsigned int>(*col_itr, *row_itr));
1564     }
1565   }
1566 
1567   return pixels;
1568 }
1569 
1570 bool PixelCalibConfiguration::containsScan(std::string name) const {
1571   for (unsigned int i = 0; i < numberOfScanVariables(); i++) {
1572     if (scanName(i) == name) {
1573       return true;
1574     }
1575   }
1576   return false;
1577 }
1578 
1579 //=============================================================================================
1580 void PixelCalibConfiguration::writeXMLHeader(pos::PixelConfigKey key,
1581                                              int version,
1582                                              std::string path,
1583                                              std::ofstream* outstream,
1584                                              std::ofstream* out1stream,
1585                                              std::ofstream* out2stream) const {
1586   std::string mthn = "[PixelCalibConfiguration::writeXMLHeader()]\t\t    ";
1587   std::stringstream maskFullPath;
1588 
1589   writeASCII(path);
1590 
1591   maskFullPath << path << "/PixelCalib_Test_" << PixelTimeFormatter::getmSecTime() << ".xml";
1592   std::cout << __LINE__ << "]\t" << mthn << "Writing to: " << maskFullPath.str() << std::endl;
1593 
1594   outstream->open(maskFullPath.str().c_str());
1595 
1596   *outstream << "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>" << std::endl;
1597   *outstream << "<ROOT xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" << std::endl;
1598   *outstream << "" << std::endl;
1599   *outstream << " <!-- " << mthn << "-->" << std::endl;
1600   *outstream << "" << std::endl;
1601   *outstream << " <HEADER>" << std::endl;
1602   *outstream << "  <TYPE>" << std::endl;
1603   *outstream << "   <EXTENSION_TABLE_NAME>PIXEL_CALIB_CLOB</EXTENSION_TABLE_NAME>" << std::endl;
1604   *outstream << "   <NAME>Calibration Object Clob</NAME>" << std::endl;
1605   *outstream << "  </TYPE>" << std::endl;
1606   *outstream << "  <RUN>" << std::endl;
1607   *outstream << "   <RUN_TYPE>Gain Calibration</RUN_TYPE>" << std::endl;
1608   *outstream << "   <RUN_NUMBER>1</RUN_NUMBER>" << std::endl;
1609   *outstream << "   <RUN_BEGIN_TIMESTAMP>" << PixelTimeFormatter::getTime() << "</RUN_BEGIN_TIMESTAMP>" << std::endl;
1610   *outstream << "   <LOCATION>CERN P5</LOCATION>" << std::endl;
1611   *outstream << "  </RUN>" << std::endl;
1612   *outstream << " </HEADER>" << std::endl;
1613   *outstream << "" << std::endl;
1614   *outstream << " <DATA_SET>" << std::endl;
1615   *outstream << "" << std::endl;
1616   *outstream << "  <VERSION>" << version << "</VERSION>" << std::endl;
1617   *outstream << "  <COMMENT_DESCRIPTION>" << getComment() << "</COMMENT_DESCRIPTION>" << std::endl;
1618   *outstream << "  <CREATED_BY_USER>" << getAuthor() << "</CREATED_BY_USER>" << std::endl;
1619   *outstream << "" << std::endl;
1620   *outstream << "  <PART>" << std::endl;
1621   *outstream << "   <NAME_LABEL>CMS-PIXEL-ROOT</NAME_LABEL>" << std::endl;
1622   *outstream << "   <KIND_OF_PART>Detector ROOT</KIND_OF_PART>" << std::endl;
1623   *outstream << "  </PART>" << std::endl;
1624 }
1625 
1626 //=============================================================================================
1627 void PixelCalibConfiguration::writeXML(std::ofstream* outstream,
1628                                        std::ofstream* out1stream,
1629                                        std::ofstream* out2stream) const {
1630   std::string mthn = "[PixelCalibConfiguration::writeXML()]\t\t    ";
1631 
1632   *outstream << " " << std::endl;
1633   *outstream << "  <DATA>" << std::endl;
1634   *outstream << "   <CALIB_OBJ_DATA_FILE>./calib.dat</CALIB_OBJ_DATA_FILE>" << std::endl;
1635   *outstream << "   <CALIB_TYPE>calib</CALIB_TYPE>" << std::endl;
1636   *outstream << "  </DATA>" << std::endl;
1637   *outstream << " " << std::endl;
1638 }
1639 
1640 //=============================================================================================
1641 void PixelCalibConfiguration::writeXMLTrailer(std::ofstream* outstream,
1642                                               std::ofstream* out1stream,
1643                                               std::ofstream* out2stream) const {
1644   std::string mthn = "[PixelCalibConfiguration::writeXMLTrailer()]\t\t    ";
1645 
1646   *outstream << " </DATA_SET>" << std::endl;
1647   *outstream << "</ROOT>" << std::endl;
1648 
1649   outstream->close();
1650   std::cout << __LINE__ << "]\t" << mthn << "Data written " << std::endl;
1651 }