Back to home page

Project CMSSW displayed by LXR

 
 

    


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

0001 #include "DQM/SiStripCommissioningSources/interface/SiStripCommissioningSource.h"
0002 #include "CalibFormats/SiStripObjects/interface/SiStripFecCabling.h"
0003 #include "CondFormats/SiStripObjects/interface/SiStripFedCabling.h"
0004 #include "DQM/SiStripCommissioningSources/interface/ApvTimingTask.h"
0005 #include "DQM/SiStripCommissioningSources/interface/Averages.h"
0006 #include "DQM/SiStripCommissioningSources/interface/CalibrationScanTask.h"
0007 #include "DQM/SiStripCommissioningSources/interface/CalibrationTask.h"
0008 #include "DQM/SiStripCommissioningSources/interface/DaqScopeModeTask.h"
0009 #include "DQM/SiStripCommissioningSources/interface/FastFedCablingTask.h"
0010 #include "DQM/SiStripCommissioningSources/interface/FedCablingTask.h"
0011 #include "DQM/SiStripCommissioningSources/interface/FedTimingTask.h"
0012 #include "DQM/SiStripCommissioningSources/interface/FineDelayTask.h"
0013 #include "DQM/SiStripCommissioningSources/interface/LatencyTask.h"
0014 #include "DQM/SiStripCommissioningSources/interface/NoiseTask.h"
0015 #include "DQM/SiStripCommissioningSources/interface/OptoScanTask.h"
0016 #include "DQM/SiStripCommissioningSources/interface/PedestalsTask.h"
0017 #include "DQM/SiStripCommissioningSources/interface/PedsFullNoiseTask.h"
0018 #include "DQM/SiStripCommissioningSources/interface/PedsOnlyTask.h"
0019 #include "DQM/SiStripCommissioningSources/interface/VpspScanTask.h"
0020 #include "DQMServices/Core/interface/DQMStore.h"
0021 #include "DataFormats/Common/interface/Handle.h"
0022 #include "DataFormats/SiStripCommon/interface/SiStripEnumsAndStrings.h"
0023 #include "DataFormats/SiStripCommon/interface/SiStripEventSummary.h"
0024 #include "DataFormats/SiStripCommon/interface/SiStripFecKey.h"
0025 #include "DataFormats/SiStripCommon/interface/SiStripFedKey.h"
0026 #include "FWCore/Framework/interface/Event.h"
0027 #include "FWCore/Framework/interface/EventSetup.h"
0028 #include "FWCore/MessageLogger/interface/MessageLogger.h"
0029 #include "FWCore/ParameterSet/interface/ParameterSet.h"
0030 #include "FWCore/ServiceRegistry/interface/Service.h"
0031 #include "FWCore/Utilities/interface/Exception.h"
0032 #include <ctime>
0033 #include <iomanip>
0034 #include <memory>
0035 #include <sstream>
0036 
0037 #include <sys/types.h>
0038 #include <unistd.h>
0039 #include <iomanip>
0040 
0041 #include <arpa/inet.h>
0042 #include <cstdio>
0043 #include <netdb.h>
0044 #include <sys/socket.h>
0045 #include <sys/unistd.h>
0046 #include <cstdint>
0047 
0048 using namespace sistrip;
0049 
0050 // -----------------------------------------------------------------------------
0051 //
0052 SiStripCommissioningSource::SiStripCommissioningSource(const edm::ParameterSet& pset)
0053     : dqm_(nullptr),
0054       fedCablingToken_(esConsumes<edm::Transition::BeginRun>()),
0055       fecCabling_(nullptr),
0056       inputModuleLabel_(pset.getParameter<std::string>("InputModuleLabel")),
0057       inputModuleLabelAlt_(pset.existsAs<std::string>("InputModuleLabelAlt")
0058                                ? pset.getParameter<std::string>("InputModuleLabelAlt")
0059                                : ""),
0060       inputModuleLabelSummary_(pset.getParameter<std::string>("SummaryInputModuleLabel")),
0061       inputClusterLabel_(
0062           pset.existsAs<std::string>("InputClusterLabel") ? pset.getParameter<std::string>("InputClusterLabel") : ""),
0063       filename_(pset.getUntrackedParameter<std::string>("RootFileName", sistrip::dqmSourceFileName_)),
0064       run_(0),
0065       partitionName_(pset.existsAs<std::string>("PartitionName") ? pset.getParameter<std::string>("PartitionName")
0066                                                                  : ""),
0067       time_(0),
0068       isSpy_(pset.existsAs<bool>("isSpy") ? pset.getParameter<bool>("isSpy") : false),
0069       taskConfigurable_(pset.getUntrackedParameter<std::string>("CommissioningTask", "UNDEFINED")),
0070       task_(sistrip::UNDEFINED_RUN_TYPE),
0071       tasks_(),
0072       cablingTasks_(),
0073       tasksExist_(false),
0074       cablingTask_(false),
0075       updateFreq_(pset.getUntrackedParameter<int>("HistoUpdateFreq", 1)),
0076       base_(""),
0077       view_(pset.getUntrackedParameter<std::string>("View", "Default")),
0078       parameters_(pset) {
0079   inputModuleSummaryToken_ = consumes<SiStripEventSummary>(edm::InputTag(inputModuleLabelSummary_));
0080   digiVirginRawToken_ = mayConsume<edm::DetSetVector<SiStripRawDigi> >(edm::InputTag(inputModuleLabel_, "VirginRaw"));
0081   digiFineDelaySelectionToken_ =
0082       mayConsume<edm::DetSetVector<SiStripRawDigi> >(edm::InputTag(inputModuleLabel_, "FineDelaySelection"));
0083   digiReorderedToken_ = mayConsume<edm::DetSetVector<SiStripRawDigi> >(edm::InputTag(inputModuleLabel_, "Reordered"));
0084   /////////////////
0085   if (not isSpy_)
0086     digiScopeModeToken_ = mayConsume<edm::DetSetVector<SiStripRawDigi> >(edm::InputTag(inputModuleLabel_, "ScopeMode"));
0087   else {
0088     digiScopeModeToken_ =
0089         mayConsume<edm::DetSetVector<SiStripRawDigi> >(edm::InputTag(inputModuleLabelAlt_, "ScopeRawDigis"));
0090     clustersToken_ = mayConsume<edmNew::DetSetVector<SiStripCluster> >(edm::InputTag(inputClusterLabel_));
0091   }
0092   /////////////////
0093   LogTrace(mlDqmSource_) << "[SiStripCommissioningSource::" << __func__ << "]"
0094                          << " Constructing object...";
0095   tasks_.clear();
0096   tasks_.resize(1024, VecOfTasks(96, static_cast<CommissioningTask*>(nullptr)));
0097 
0098   if (task_ == sistrip::NOISE) {
0099     noiseToken_ = esConsumes();
0100   }
0101   if (task_ == sistrip::NOISE || task_ == sistrip::CALIBRATION_SCAN || task_ == sistrip::CALIBRATION_SCAN_DECO ||
0102       task_ == sistrip::CALIBRATION || task_ == sistrip::CALIBRATION_DECO) {
0103     pedestalToken_ = esConsumes();
0104   }
0105 }
0106 
0107 // -----------------------------------------------------------------------------
0108 //
0109 SiStripCommissioningSource::~SiStripCommissioningSource() {
0110   LogTrace(mlDqmSource_) << "[SiStripCommissioningSource::" << __func__ << "]"
0111                          << " Destructing object...";
0112 }
0113 
0114 // -----------------------------------------------------------------------------
0115 //
0116 SiStripCommissioningSource::DQMStore* const SiStripCommissioningSource::dqm(std::string method) const {
0117   if (!dqm_) {
0118     std::stringstream ss;
0119     if (!method.empty()) {
0120       ss << "[SiStripCommissioningSource::" << method << "]" << std::endl;
0121     } else {
0122       ss << "[SiStripCommissioningSource]" << std::endl;
0123     }
0124     ss << " NULL pointer to DQMStore";
0125     edm::LogWarning(mlDqmSource_) << ss.str();
0126     return nullptr;
0127   } else {
0128     return dqm_;
0129   }
0130 }
0131 
0132 // -----------------------------------------------------------------------------
0133 // Retrieve DQM interface, control cabling and "control view" utility
0134 // class, create histogram directory structure and generate "reverse"
0135 // control cabling.
0136 void SiStripCommissioningSource::beginRun(edm::Run const& run, const edm::EventSetup& setup) {
0137   LogTrace(mlDqmSource_) << "[SiStripCommissioningSource::" << __func__ << "]"
0138                          << " Configuring..." << std::endl;
0139 
0140   // ---------- DQM back-end interface ----------
0141 
0142   dqm_ = edm::Service<DQMStore>().operator->();
0143   edm::LogInfo(mlDqmSource_) << "[SiStripCommissioningSource::" << __func__ << "]"
0144                              << " DQMStore service: " << dqm_;
0145   dqm(__func__);
0146 
0147   // ---------- Base directory ----------
0148 
0149   std::stringstream dir("");
0150   base_ = dir.str();
0151 
0152   // ---------- FED and FEC cabling ----------
0153 
0154   const auto& fed_cabling = setup.getData(fedCablingToken_);
0155   fedCabling_ = const_cast<SiStripFedCabling*>(&fed_cabling);
0156   LogDebug(mlDqmSource_) << "[SiStripCommissioningSource::" << __func__ << "]"
0157                          << "Initialized FED cabling. Number of FEDs is " << fedCabling_->fedIds().size();
0158   fecCabling_ = new SiStripFecCabling(fed_cabling);
0159   if (fecCabling_->crates().empty()) {
0160     std::stringstream ss;
0161     ss << "[SiStripCommissioningSource::" << __func__ << "]"
0162        << " Empty std::vector returned by FEC cabling object!"
0163        << " Check if database connection failed...";
0164     edm::LogWarning(mlDqmSource_) << ss.str();
0165   }
0166 
0167   // ---------- Reset ----------
0168 
0169   tasksExist_ = false;
0170   task_ = sistrip::UNDEFINED_RUN_TYPE;
0171   cablingTask_ = false;
0172 
0173   remove();
0174 
0175   clearCablingTasks();
0176   clearTasks();
0177 }
0178 
0179 // -----------------------------------------------------------------------------
0180 //
0181 void SiStripCommissioningSource::endJob() {
0182   LogTrace(mlDqmSource_) << "[SiStripCommissioningSource::" << __func__ << "]"
0183                          << " Halting..." << std::endl;
0184 
0185   // ---------- Update histograms ----------
0186   // Cabling task
0187   for (TaskMap::iterator itask = cablingTasks_.begin(); itask != cablingTasks_.end(); itask++) {
0188     if (itask->second) {
0189       itask->second->updateHistograms();
0190     }
0191   }
0192 
0193   if (task_ == sistrip::APV_LATENCY) {
0194     for (uint16_t partition = 0; partition < 4; ++partition) {
0195       tasks_[0][partition]->updateHistograms();
0196     }
0197   } else if (task_ == sistrip::FINE_DELAY) {
0198     tasks_[0][0]->updateHistograms();
0199   } else {
0200     // All tasks except cabling
0201     uint16_t fed_id = 0;
0202     uint16_t fed_ch = 0;
0203     auto ifed = fedCabling_->fedIds().begin();
0204     for (; ifed != fedCabling_->fedIds().end(); ifed++) {
0205       auto conns = fedCabling_->fedConnections(*ifed);
0206       for (auto iconn = conns.begin(); iconn != conns.end(); iconn++) {
0207         if (!iconn->isConnected()) {
0208           continue;
0209         }
0210         fed_id = iconn->fedId();
0211         fed_ch = iconn->fedCh();
0212         if (tasks_[fed_id][fed_ch]) {
0213           tasks_[fed_id][fed_ch]->updateHistograms();
0214           delete tasks_[fed_id][fed_ch];
0215         }
0216       }
0217     }
0218   }
0219   // ---------- Save histos to root file ----------
0220 
0221   // Strip filename of ".root" extension
0222   std::string name;
0223   if (filename_.find(".root", 0) == std::string::npos) {
0224     name = filename_;
0225   } else {
0226     name = filename_.substr(0, filename_.find(".root", 0));
0227   }
0228 
0229   // Retrieve SCRATCH directory
0230   std::string scratch = "SCRATCH";  //@@ remove trailing slash!!!
0231   std::string dir = "";
0232   if (std::getenv(scratch.c_str()) != nullptr) {
0233     dir = std::getenv(scratch.c_str());
0234   }
0235 
0236   // Add directory path
0237   std::stringstream ss;
0238   if (!dir.empty()) {
0239     ss << dir << "/";
0240   } else {
0241     ss << "/tmp/";
0242   }
0243 
0244   // Add filename with run number, host ip, pid and .root extension
0245   ss << name << "_";
0246   if (task_ == sistrip::DAQ_SCOPE_MODE and not partitionName_.empty())  // only for spy-runs
0247     ss << partitionName_ << "_";
0248 
0249   directory(ss, run_);
0250   ss << ".root";
0251 
0252   // Save file with appropriate filename (if run number is known)
0253   if (!filename_.empty()) {
0254     if (run_ != 0) {
0255       dqm()->save(ss.str());
0256     } else {
0257       edm::LogWarning(mlDqmSource_) << "[SiStripCommissioningSource::" << __func__ << "]"
0258                                     << " NULL value for RunNumber! No root file saved!";
0259     }
0260   } else {
0261     edm::LogWarning(mlDqmSource_) << "[SiStripCommissioningSource::" << __func__ << "]"
0262                                   << " NULL value for filename! No root file saved!";
0263   }
0264 
0265   LogTrace(mlDqmSource_) << "[SiStripCommissioningSource::" << __func__ << "]"
0266                          << " Saved all histograms to file \"" << ss.str() << "\"";
0267 
0268   // ---------- Delete histograms ----------
0269   // Remove all MonitorElements in "SiStrip" dir and below
0270   // remove();
0271 
0272   // Delete histogram objects
0273   // clearCablingTasks();
0274   // clearTasks();
0275 
0276   // ---------- Delete cabling ----------
0277   if (fedCabling_) {
0278     fedCabling_ = nullptr;
0279   }
0280   if (fecCabling_) {
0281     delete fecCabling_;
0282     fecCabling_ = nullptr;
0283   }
0284 }
0285 
0286 // ----------------------------------------------------------------------------
0287 //
0288 void SiStripCommissioningSource::analyze(const edm::Event& event, const edm::EventSetup& setup) {
0289   // Retrieve commissioning information from "event summary"
0290   edm::Handle<SiStripEventSummary> summary;
0291   //  event.getByLabel( inputModuleLabelSummary_, summary );
0292   event.getByToken(inputModuleSummaryToken_, summary);
0293 
0294   // Check if EventSummary has info attached
0295   if ((summary->runType() == sistrip::UNDEFINED_RUN_TYPE || summary->runType() == sistrip::UNKNOWN_RUN_TYPE) &&
0296       summary->nullParams()) {
0297     edm::LogWarning(mlDqmSource_) << "[SiStripCommissioningSource::" << __func__ << "]"
0298                                   << " Unknown/undefined RunType and NULL parameter values!"
0299                                   << " It may be that the 'trigger FED' object was not found!";
0300   }
0301 
0302   // Check if need to rebuild FED/FEC cabling objects for connection run
0303   //cablingForConnectionRun( summary->runType() ); //@@ do not use!
0304 
0305   // Extract run number and forward to client
0306   if (event.id().run() != run_) {
0307     run_ = event.id().run();
0308     createRunNumber();
0309   }
0310 
0311   // Coarse event rate counter
0312   if (!(event.id().event() % updateFreq_)) {
0313     std::stringstream ss;
0314     ss << "[SiStripCommissioningSource::" << __func__ << "]"
0315        << " The last " << updateFreq_ << " events were processed at a rate of ";
0316     if (time(nullptr) == time_) {
0317       ss << ">" << updateFreq_ << " Hz";
0318     } else {
0319       ss << (updateFreq_ / (time(nullptr) - time_)) << " Hz";
0320     }
0321     edm::LogVerbatim(mlDqmSource_) << ss.str();
0322     time_ = time(nullptr);
0323   }
0324 
0325   // Create commissioning task objects
0326   if (!tasksExist_) {
0327     createTask(summary.product(), setup);
0328   } else {
0329     for (auto& v : tasks_) {
0330       for (auto& t : v) {
0331         t->eventSetup(&setup);
0332       }
0333     }
0334   }
0335 
0336   // Retrieve raw digis with mode appropriate to task
0337   edm::Handle<edm::DetSetVector<SiStripRawDigi> > raw;
0338   edm::Handle<edm::DetSetVector<SiStripRawDigi> > rawAlt;
0339   edm::Handle<edmNew::DetSetVector<SiStripCluster> > cluster;
0340 
0341   if (task_ == sistrip::DAQ_SCOPE_MODE) {  // scop-mode runs
0342     if (not isSpy_ and
0343         summary->fedReadoutMode() == FED_VIRGIN_RAW) {  // if the readout is virgin raw just take the VR digis
0344       event.getByToken(digiVirginRawToken_, raw);
0345     } else if (not isSpy_ and summary->fedReadoutMode() == FED_SCOPE_MODE) {
0346       event.getByToken(digiScopeModeToken_, raw);
0347     } else if (isSpy_) {  // spy case take both re-ordered and scope mode
0348       event.getByToken(digiScopeModeToken_, rawAlt);
0349       event.getByToken(digiReorderedToken_, raw);
0350       if (not inputClusterLabel_.empty())
0351         event.getByToken(clustersToken_, cluster);
0352     } else {
0353       std::stringstream ss;
0354       ss << "[SiStripCommissioningSource::" << __func__ << "]"
0355          << " Requested DAQ_SCOPE_MODE but unknown FED"
0356          << " readout mode retrieved from SiStripEventSummary: "
0357          << SiStripEnumsAndStrings::fedReadoutMode(summary->fedReadoutMode());
0358       edm::LogWarning(mlDqmSource_) << ss.str();
0359     }
0360   } else if (task_ == sistrip::FAST_CABLING || task_ == sistrip::FED_CABLING || task_ == sistrip::APV_TIMING ||
0361              task_ == sistrip::FED_TIMING || task_ == sistrip::OPTO_SCAN) {
0362     event.getByToken(digiScopeModeToken_, raw);
0363   } else if (task_ == sistrip::VPSP_SCAN || task_ == sistrip::CALIBRATION || task_ == sistrip::CALIBRATION_DECO ||
0364              task_ == sistrip::CALIBRATION_SCAN || task_ == sistrip::CALIBRATION_SCAN_DECO ||
0365              task_ == sistrip::PEDESTALS || task_ == sistrip::PEDS_ONLY || task_ == sistrip::NOISE ||
0366              task_ == sistrip::PEDS_FULL_NOISE) {
0367     event.getByToken(digiVirginRawToken_, raw);
0368   } else if (task_ == sistrip::APV_LATENCY || task_ == sistrip::FINE_DELAY) {
0369     event.getByToken(digiFineDelaySelectionToken_, raw);
0370   } else {
0371     std::stringstream ss;
0372     ss << "[SiStripCommissioningSource::" << __func__ << "]"
0373        << " Unknown CommissioningTask: " << SiStripEnumsAndStrings::runType(task_)
0374        << " Unable to establish FED readout mode and retrieve digi container!"
0375        << " Check if SiStripEventSummary object is found/present in Event";
0376     edm::LogWarning(mlDqmSource_) << ss.str();
0377     return;
0378   }
0379 
0380   // Check for NULL pointer to digi container
0381   if (not raw.isValid()) {
0382     std::stringstream ss;
0383     ss << "[SiStripCommissioningSource::" << __func__ << "]" << std::endl
0384        << " NULL pointer to DetSetVector!" << std::endl
0385        << " Unable to fill histograms!";
0386     edm::LogWarning(mlDqmSource_) << ss.str();
0387     return;
0388   }
0389 
0390   if (isSpy_ and not inputModuleLabelAlt_.empty() and not rawAlt.isValid()) {
0391     std::stringstream ss;
0392     ss << "[SiStripCommissioningSource::" << __func__ << "]" << std::endl
0393        << " NULL pointer to DetSetVector!" << std::endl
0394        << " Unable to fill histograms!";
0395     edm::LogWarning(mlDqmSource_) << ss.str();
0396     return;
0397   }
0398 
0399   if (isSpy_ and not inputClusterLabel_.empty() and not cluster.isValid()) {
0400     std::stringstream ss;
0401     ss << "[SiStripCommissioningSource::" << __func__ << "]" << std::endl
0402        << " NULL pointer to DetSetVector!" << std::endl
0403        << " Unable to fill histograms!";
0404     edm::LogWarning(mlDqmSource_) << ss.str();
0405     return;
0406   }
0407 
0408   if (!cablingTask_) {
0409     fillHistos(summary.product(), *raw, *rawAlt, *cluster);
0410   } else {
0411     fillCablingHistos(summary.product(), *raw);
0412   }
0413 }
0414 
0415 // ----------------------------------------------------------------------------
0416 //
0417 void SiStripCommissioningSource::fillCablingHistos(const SiStripEventSummary* const summary,
0418                                                    const edm::DetSetVector<SiStripRawDigi>& raw) {
0419   // Create FEC key using DCU id and LLD channel from SiStripEventSummary
0420   const SiStripModule& module = fecCabling_->module(summary->dcuId());
0421   uint16_t lld_channel = (summary->deviceId() & 0x3) + 1;
0422   SiStripFecKey key_object(module.key().fecCrate(),
0423                            module.key().fecSlot(),
0424                            module.key().fecRing(),
0425                            module.key().ccuAddr(),
0426                            module.key().ccuChan(),
0427                            lld_channel);
0428   uint32_t fec_key = key_object.key();
0429   std::stringstream sss;
0430   sss << "[SiStripCommissioningSource::" << __func__ << "]"
0431       << " Found DcuId 0x" << std::hex << std::setw(8) << std::setfill('0') << summary->dcuId() << std::dec
0432       << " with Crate/FEC/Ring/CCU/Module/LLD: " << module.key().fecCrate() << "/" << module.key().fecSlot() << "/"
0433       << module.key().fecRing() << "/" << module.key().ccuAddr() << "/" << module.key().ccuChan() << "/" << lld_channel;
0434   edm::LogWarning(mlDqmSource_) << sss.str();
0435 
0436   //LogTrace(mlTest_) << "TEST : " << key_object;
0437 
0438   // Check on whether DCU id is found
0439   if (key_object.isInvalid(sistrip::CCU_CHAN)) {
0440     std::stringstream ss;
0441     ss << "[SiStripCommissioningSource::" << __func__ << "]"
0442        << " DcuId 0x" << std::hex << std::setw(8) << std::setfill('0') << summary->dcuId() << std::dec
0443        << " in 'DAQ register' field not found in cabling map!"
0444        << " (NULL values returned for FEC path)";
0445     edm::LogWarning(mlDqmSource_) << ss.str();
0446     return;
0447   }
0448 
0449   // Iterate through FED ids
0450   for (auto ifed = fedCabling_->fedIds().begin(); ifed != fedCabling_->fedIds().end(); ifed++) {
0451     // Check if FedId is non-zero
0452     if (*ifed == sistrip::invalid_) {
0453       continue;
0454     }
0455 
0456     // Container to hold median signal level for FED cabling task
0457     std::map<uint16_t, float> medians;
0458     medians.clear();
0459     std::map<uint16_t, float> medians1;
0460     medians1.clear();
0461 
0462     // Iterate through FED channels
0463     for (uint16_t ichan = 0; ichan < 96; ichan++) {
0464       // Retrieve digis for given FED key
0465       uint32_t fed_key = ((*ifed & sistrip::invalid_) << 16) | (ichan & sistrip::invalid_);
0466 
0467       std::vector<edm::DetSet<SiStripRawDigi> >::const_iterator digis = raw.find(fed_key);
0468       if (digis != raw.end()) {
0469         if (digis->data.empty()) {
0470           continue;
0471         }
0472 
0473         Averages ave;
0474         for (uint16_t idigi = 0; idigi < digis->data.size(); idigi++) {
0475           ave.add(static_cast<uint32_t>(digis->data[idigi].adc()));
0476         }
0477         Averages::Params params;
0478         ave.calc(params);
0479         medians[ichan] = params.median_;  // Store median signal level
0480         medians1[ichan] = digis->data[0].adc();
0481       }
0482 
0483     }  // fed channel loop
0484 
0485     // Calculate mean and spread on all (median) signal levels
0486     Averages average;
0487     std::map<uint16_t, float>::const_iterator ii = medians.begin();
0488     for (; ii != medians.end(); ii++) {
0489       average.add(ii->second);
0490     }
0491     Averages::Params tmp;
0492     average.calc(tmp);
0493 
0494     std::stringstream ss;
0495     ss << "FED Averages:" << std::endl
0496        << "  nChans: " << medians.size() << std::endl
0497        << "  num/mean/median/rms/max/min: " << tmp.num_ << "/" << tmp.mean_ << "/" << tmp.median_ << "/" << tmp.rms_
0498        << "/" << tmp.max_ << "/" << tmp.min_ << std::endl;
0499     LogTrace(mlDqmSource_) << ss.str();
0500 
0501     // Calculate mean and spread on "filtered" data
0502     Averages truncated;
0503     std::map<uint16_t, float>::const_iterator jj = medians.begin();
0504     for (; jj != medians.end(); jj++) {
0505       if (jj->second < tmp.median_ + tmp.rms_) {
0506         truncated.add(jj->second);
0507       }
0508     }
0509     Averages::Params params;
0510     truncated.calc(params);
0511 
0512     std::stringstream ss1;
0513     ss1 << "Truncated Averages:" << std::endl
0514         << "  nChans: " << medians.size() << std::endl
0515         << "  num/mean/median/rms/max/min: " << params.num_ << "/" << params.mean_ << "/" << params.median_ << "/"
0516         << params.rms_ << "/" << params.max_ << "/" << params.min_ << std::endl;
0517     LogTrace(mlDqmSource_) << ss1.str();
0518 
0519     // Identify channels with signal
0520     std::stringstream ss2;
0521     std::stringstream ss3;
0522     std::map<uint16_t, float> channels;
0523     std::map<uint16_t, float>::const_iterator ichan = medians.begin();
0524     for (; ichan != medians.end(); ichan++) {
0525       if (ichan->second > 200.) {
0526         LogTrace(mlTest_) << "TEST FOUND SIGNAL HIGH: " << *ifed << " " << ichan->first << " " << ichan->second;
0527         channels[ichan->first] = ichan->second;
0528       }
0529       ss2  //<< ichan->first << "/"
0530           << ichan->second << " ";
0531       ss3  //<< ichan->first << "/"
0532           << medians1[ichan->first] << " ";
0533     }
0534 
0535     ss2 << std::endl;
0536     ss3 << std::endl;
0537     LogTrace(mlTest_) << "DUMP for FED  " << *ifed << ": " << ss2.str();
0538     LogTrace(mlTest_) << "FIRST ADC VAL " << *ifed << ": " << ss3.str();
0539 
0540     // Fill cabling histograms
0541     if (cablingTasks_.find(fec_key) != cablingTasks_.end()) {
0542       if (!channels.empty()) {
0543         cablingTasks_[fec_key]->fillHistograms(*summary, *ifed, channels);
0544         SiStripFecKey path(fec_key);
0545         std::stringstream ss;
0546         ss << "[SiStripCommissioningSource::" << __func__ << "]"
0547            << " Filled histogram for '" << cablingTasks_[fec_key]->myName() << "' object with FecKey: 0x" << std::hex
0548            << std::setfill('0') << std::setw(8) << fec_key << std::dec
0549            << " and Crate/FEC/ring/CCU/module/LLDchan: " << path.fecCrate() << "/" << path.fecSlot() << "/"
0550            << path.fecRing() << "/" << path.ccuAddr() << "/" << path.ccuChan() << "/" << path.channel();
0551         LogTrace(mlDqmSource_) << ss.str();
0552       }
0553     } else {
0554       SiStripFecKey path(fec_key);
0555       std::stringstream ss;
0556       ss << "[SiStripCommissioningSource::" << __func__ << "]"
0557          << " Unable to find CommissioningTask object with FecKey: 0x" << std::hex << std::setfill('0') << std::setw(8)
0558          << fec_key << std::dec << " and Crate/FEC/ring/CCU/module/LLDchan: " << path.fecCrate() << "/"
0559          << path.fecSlot() << "/" << path.fecRing() << "/" << path.ccuAddr() << "/" << path.ccuChan() << "/"
0560          << path.channel();
0561       edm::LogWarning(mlDqmSource_) << ss.str();
0562     }
0563 
0564   }  // fed id loop
0565 }
0566 
0567 // ----------------------------------------------------------------------------
0568 //
0569 void SiStripCommissioningSource::fillHistos(const SiStripEventSummary* const summary,
0570                                             const edm::DetSetVector<SiStripRawDigi>& raw,
0571                                             const edm::DetSetVector<SiStripRawDigi>& rawAlt,
0572                                             const edmNew::DetSetVector<SiStripCluster>& clusters) {
0573   // Iterate through FED ids and channels
0574   std::vector<uint16_t> stripOnClusters;
0575   auto ifed = fedCabling_->fedIds().begin();
0576   for (; ifed != fedCabling_->fedIds().end(); ifed++) {
0577     // Iterate through connected FED channels
0578     auto conns = fedCabling_->fedConnections(*ifed);
0579     for (auto iconn = conns.begin(); iconn != conns.end(); iconn++) {
0580       if (!(iconn->fedId()) || iconn->fedId() > sistrip::valid_) {
0581         continue;
0582       }
0583       if (!iconn->isConnected()) {
0584         continue;
0585       }
0586 
0587       // Create FED key and check if non-zero
0588       // note: the key is not computed using the same formula as in commissioning histograms.
0589       // beware that changes here must match changes in raw2digi and in SiStripFineDelayHit
0590       uint32_t fed_key = ((iconn->fedId() & sistrip::invalid_) << 16) | (iconn->fedCh() & sistrip::invalid_);
0591       // Retrieve digis for given FED key and check if found
0592       std::vector<edm::DetSet<SiStripRawDigi> >::const_iterator digis = raw.find(fed_key);
0593 
0594       // only for spy data-taking --> tick measurement
0595       std::vector<edm::DetSet<SiStripRawDigi> >::const_iterator digisAlt;
0596       if (not rawAlt.empty()) {
0597         digisAlt = rawAlt.find(fed_key);
0598         if (digisAlt == rawAlt.end())
0599           continue;
0600       }
0601 
0602       // find the strips belonging to the clusters connected to this APV pair
0603       stripOnClusters.clear();
0604       if (not clusters.empty()) {
0605         for (edmNew::DetSetVector<SiStripCluster>::const_iterator DSViter = clusters.begin(); DSViter != clusters.end();
0606              DSViter++) {
0607           if (DSViter->id() != iconn->detId())
0608             continue;  // select clusters on this module
0609           for (edmNew::DetSet<SiStripCluster>::const_iterator DSiter = DSViter->begin(); DSiter != DSViter->end();
0610                DSiter++) {  // loop on the clusters
0611             if (DSiter->firstStrip() >= iconn->apvPairNumber() * 256 and
0612                 DSiter->firstStrip() < (1 + iconn->apvPairNumber()) * 256) {  // found the right APV
0613               for (size_t istrip = 0; istrip < DSiter->amplitudes().size(); istrip++) {
0614                 stripOnClusters.push_back(DSiter->firstStrip() + istrip - iconn->apvPairNumber() * 256);
0615               }
0616             }
0617           }
0618         }
0619       }
0620 
0621       if (digis != raw.end()) {
0622         // tasks involving tracking have partition-level histos, so treat separately
0623         if (task_ == sistrip::APV_LATENCY) {
0624           if (tasks_[0][iconn->fecCrate() - 1]) {
0625             tasks_[0][iconn->fecCrate() - 1]->fillHistograms(*summary, *digis);
0626           } else {
0627             std::stringstream ss;
0628             ss << "[SiStripCommissioningSource::" << __func__ << "]"
0629                << " Unable to find CommissioningTask for FEC crate " << iconn->fecCrate()
0630                << ". Unable to fill histograms!";
0631             edm::LogWarning(mlDqmSource_) << ss.str();
0632           }
0633         } else if (task_ == sistrip::FINE_DELAY) {
0634           if (tasks_[0][0]) {
0635             tasks_[0][0]->fillHistograms(*summary, *digis);
0636           } else {
0637             std::stringstream ss;
0638             ss << "[SiStripCommissioningSource::" << __func__ << "]"
0639                << " Unable to find global CommissioningTask for FineDelay. Unable to fill histograms!";
0640             edm::LogWarning(mlDqmSource_) << ss.str();
0641           }
0642         } else {
0643           if (tasks_[iconn->fedId()][iconn->fedCh()]) {
0644             if (not rawAlt.empty() or digisAlt == rawAlt.end())
0645               tasks_[iconn->fedId()][iconn->fedCh()]->fillHistograms(*summary, *digis);
0646             else {  // for spy-data
0647               if (stripOnClusters.empty())
0648                 tasks_[iconn->fedId()][iconn->fedCh()]->fillHistograms(*summary, *digis, *digisAlt);
0649               else {
0650                 tasks_[iconn->fedId()][iconn->fedCh()]->fillHistograms(*summary, *digis, *digisAlt, stripOnClusters);
0651               }
0652             }
0653           } else {
0654             std::stringstream ss;
0655             ss << "[SiStripCommissioningSource::" << __func__ << "]"
0656                << " Unable to find CommissioningTask object with FED key " << std::hex << std::setfill('0')
0657                << std::setw(8) << fed_key << std::dec << " and FED id/ch " << iconn->fedId() << "/" << iconn->fedCh()
0658                << " Unable to fill histograms!";
0659             edm::LogWarning(mlDqmSource_) << ss.str();
0660           }
0661         }
0662       } else {
0663         // issue a warning only for standard runs, as latency and fine delay only deliver
0664         // pseudo zero-suppressed data
0665         if (task_ != sistrip::APV_LATENCY && task_ != sistrip::FINE_DELAY) {
0666           std::stringstream ss;
0667           ss << "[SiStripCommissioningSource::" << __func__ << "]"
0668              << " Unable to find any DetSet containing digis for FED key " << std::hex << std::setfill('0')
0669              << std::setw(8) << fed_key << std::dec << " and FED id/ch " << iconn->fedId() << "/" << iconn->fedCh();
0670           edm::LogWarning(mlDqmSource_) << ss.str();
0671         }
0672       }
0673     }  // fed channel loop
0674   }    // fed id loop
0675 }
0676 
0677 // -----------------------------------------------------------------------------
0678 //
0679 void SiStripCommissioningSource::createRunNumber() {
0680   // Set commissioning task to default ("undefined") value
0681   if (!run_) {
0682     edm::LogWarning(mlDqmSource_) << "[SiStripCommissioningSource::" << __func__ << "]"
0683                                   << " NULL run number!";
0684     return;
0685   }
0686 
0687   // Create MonitorElement that identifies run number
0688   dqm()->setCurrentFolder(base_ + sistrip::root_);
0689   std::stringstream run;
0690   run << run_;
0691   dqm()->bookString(std::string(sistrip::runNumber_) + sistrip::sep_ + run.str(), run.str());
0692 }
0693 
0694 // -----------------------------------------------------------------------------
0695 //
0696 void SiStripCommissioningSource::createTask(const SiStripEventSummary* const summary, const edm::EventSetup& setup) {
0697   // Set commissioning task to default ("undefined") value
0698   task_ = sistrip::UNDEFINED_RUN_TYPE;
0699 
0700   // Retrieve commissioning task from EventSummary
0701   if (summary) {
0702     task_ = summary->runType();
0703     std::stringstream ss;
0704     ss << "[SiStripCommissioningSource::" << __func__ << "]"
0705        << " Identified CommissioningTask from EventSummary to be \"" << SiStripEnumsAndStrings::runType(task_) << "\"";
0706     LogTrace(mlDqmSource_) << ss.str();
0707   } else {
0708     task_ = sistrip::UNKNOWN_RUN_TYPE;
0709     std::stringstream ss;
0710     ss << "[SiStripCommissioningSource::" << __func__ << "]"
0711        << " NULL pointer to SiStripEventSummary!"
0712        << " Check SiStripEventSummary is found/present in Event";
0713     edm::LogWarning(mlDqmSource_) << ss.str();
0714   }
0715 
0716   // Override task with ParameterSet configurable (if defined)
0717   sistrip::RunType configurable = SiStripEnumsAndStrings::runType(taskConfigurable_);
0718   if (configurable != sistrip::UNDEFINED_RUN_TYPE && configurable != sistrip::UNKNOWN_RUN_TYPE) {
0719     std::stringstream ss;
0720     ss << "[SiStripCommissioningSource::" << __func__ << "]"
0721        << " Overriding CommissioningTask from EventSummary (\"" << SiStripEnumsAndStrings::runType(task_)
0722        << "\") with value retrieved from .cfg file (\"" << SiStripEnumsAndStrings::runType(configurable) << "\")!";
0723     LogTrace(mlDqmSource_) << ss.str();
0724     task_ = configurable;
0725   }
0726 
0727   // Create ME (std::string) that identifies commissioning task
0728   dqm()->setCurrentFolder(base_ + sistrip::root_);
0729   std::string task_str = SiStripEnumsAndStrings::runType(task_);
0730   dqm()->bookString(std::string(sistrip::taskId_) + sistrip::sep_ + task_str, task_str);
0731 
0732   // Check commissioning task is known / defined
0733   if (task_ == sistrip::UNKNOWN_RUN_TYPE || task_ == sistrip::UNDEFINED_RUN_TYPE) {
0734     std::stringstream ss;
0735     ss << "[SiStripCommissioningSource::" << __func__ << "]"
0736        << " Unexpected CommissioningTask found (" << static_cast<uint16_t>(task_) << ") \""
0737        << SiStripEnumsAndStrings::runType(task_) << "\""
0738        << " Unexpected value found in SiStripEventSummary and/or cfg file"
0739        << " If SiStripEventSummary is not present in Event,"
0740        << " check 'CommissioningTask' configurable in cfg file";
0741     edm::LogWarning(mlDqmSource_) << ss.str();
0742     return;
0743   } else {
0744     std::stringstream ss;
0745     ss << "[SiStripCommissioningSource::" << __func__ << "]"
0746        << " Identified CommissioningTask to be \"" << SiStripEnumsAndStrings::runType(task_) << "\"";
0747     LogTrace(mlDqmSource_) << ss.str();
0748   }
0749 
0750   // Check if commissioning task is FED cabling
0751   if (task_ == sistrip::FED_CABLING) {
0752     cablingTask_ = true;
0753   } else {
0754     cablingTask_ = false;
0755   }
0756 
0757   std::stringstream ss;
0758   ss << "[SiStripCommissioningSource::" << __func__ << "]"
0759      << " CommissioningTask: " << SiStripEnumsAndStrings::runType(summary->runType());
0760   LogTrace(mlDqmSource_) << ss.str();
0761 
0762   edm::LogVerbatim(mlDqmSource_) << "[SiStripCommissioningSource::" << __func__ << "]"
0763                                  << " Creating CommissioningTask objects and booking histograms...";
0764   if (cablingTask_) {
0765     createCablingTasks();
0766   } else {
0767     createTasks(task_, setup);
0768   }
0769   edm::LogVerbatim(mlDqmSource_) << "[SiStripCommissioningSource::" << __func__ << "]"
0770                                  << " Finished booking histograms!";
0771   tasksExist_ = true;
0772 }
0773 
0774 // -----------------------------------------------------------------------------
0775 //
0776 void SiStripCommissioningSource::createCablingTasks() {
0777   // Iterate through FEC cabling and create commissioning task objects
0778   uint16_t booked = 0;
0779   for (std::vector<SiStripFecCrate>::const_iterator icrate = fecCabling_->crates().begin();
0780        icrate != fecCabling_->crates().end();
0781        icrate++) {
0782     for (std::vector<SiStripFec>::const_iterator ifec = icrate->fecs().begin(); ifec != icrate->fecs().end(); ifec++) {
0783       for (std::vector<SiStripRing>::const_iterator iring = ifec->rings().begin(); iring != ifec->rings().end();
0784            iring++) {
0785         for (std::vector<SiStripCcu>::const_iterator iccu = iring->ccus().begin(); iccu != iring->ccus().end();
0786              iccu++) {
0787           for (std::vector<SiStripModule>::const_iterator imodule = iccu->modules().begin();
0788                imodule != iccu->modules().end();
0789                imodule++) {
0790             // Build FEC key
0791             SiStripFecKey path(
0792                 icrate->fecCrate(), ifec->fecSlot(), iring->fecRing(), iccu->ccuAddr(), imodule->ccuChan());
0793 
0794             // Check if FEC key is invalid
0795             if (!path.isValid()) {
0796               continue;
0797             }
0798 
0799             // Set working directory prior to booking histograms
0800             std::string dir = base_ + path.path();
0801             dqm()->setCurrentFolder(dir);
0802 
0803             // Iterate through all APV pairs for this module
0804             for (uint16_t ipair = 0; ipair < imodule->nApvPairs(); ipair++) {
0805               // Retrieve active APV devices
0806               SiStripModule::PairOfU16 apvs = imodule->activeApvPair(imodule->lldChannel(ipair));
0807 
0808               // Create connection object to hold all relevant info
0809               FedChannelConnection conn(icrate->fecCrate(),
0810                                         ifec->fecSlot(),
0811                                         iring->fecRing(),
0812                                         iccu->ccuAddr(),
0813                                         imodule->ccuChan(),
0814                                         apvs.first,
0815                                         apvs.second,
0816                                         imodule->dcuId(),
0817                                         imodule->detId(),
0818                                         imodule->nApvPairs());
0819 
0820               // Define key encoding control path
0821               uint32_t key = SiStripFecKey(icrate->fecCrate(),
0822                                            ifec->fecSlot(),
0823                                            iring->fecRing(),
0824                                            iccu->ccuAddr(),
0825                                            imodule->ccuChan(),
0826                                            imodule->lldChannel(ipair))
0827                                  .key();
0828 
0829               // Check key is non zero
0830               if (!key) {
0831                 edm::LogWarning(mlDqmSource_) << "[SiStripCommissioningSource::" << __func__ << "]"
0832                                               << " Unexpected NULL value for FEC key!";
0833                 continue;
0834               }
0835 
0836               // Create cabling task objects if not already existing
0837               if (cablingTasks_.find(key) == cablingTasks_.end()) {
0838                 if (task_ == sistrip::FED_CABLING) {
0839                   cablingTasks_[key] = new FedCablingTask(dqm(), conn);
0840                 } else if (task_ == sistrip::UNDEFINED_RUN_TYPE) {
0841                   edm::LogWarning(mlDqmSource_) << "[SiStripCommissioningSource::" << __func__ << "]"
0842                                                 << " Undefined CommissioningTask"
0843                                                 << " Unable to create FedCablingTask object!";
0844                 } else if (task_ == sistrip::UNKNOWN_RUN_TYPE) {
0845                   edm::LogWarning(mlDqmSource_) << "[SiStripCommissioningSource::" << __func__ << "]"
0846                                                 << " Unknown CommissioningTask"
0847                                                 << " Unable to create FedCablingTask object!";
0848                 } else {
0849                   edm::LogWarning(mlDqmSource_)
0850                       << "[SiStripCommissioningSource::" << __func__ << "]"
0851                       << " Unexpected CommissioningTask: " << SiStripEnumsAndStrings::runType(task_)
0852                       << " Unable to create FedCablingTask object!";
0853                 }
0854 
0855                 // Check if key is found and, if so, book histos and set update freq
0856                 if (cablingTasks_.find(key) != cablingTasks_.end()) {
0857                   if (cablingTasks_[key]) {
0858                     cablingTasks_[key]->bookHistograms();
0859                     cablingTasks_[key]->updateFreq(1);  //@@ hardwired to update every event!!!
0860                     booked++;
0861                     std::stringstream ss;
0862                     ss << "[SiStripCommissioningSource::" << __func__ << "]"
0863                        << " Booking histograms for '" << cablingTasks_[key]->myName() << "' object with key 0x"
0864                        << std::hex << std::setfill('0') << std::setw(8) << key << std::dec << " in directory \"" << dir
0865                        << "\"";
0866                     LogTrace(mlDqmSource_) << ss.str();
0867                   } else {
0868                     std::stringstream ss;
0869                     ss << "[SiStripCommissioningSource::" << __func__ << "]"
0870                        << " NULL pointer to CommissioningTask for key 0x" << std::hex << std::setfill('0')
0871                        << std::setw(8) << key << std::dec << " in directory " << dir << " Unable to book histograms!";
0872                     edm::LogWarning(mlDqmSource_) << ss.str();
0873                   }
0874                 } else {
0875                   std::stringstream ss;
0876                   ss << "[SiStripCommissioningSource::" << __func__ << "]"
0877                      << " Unable to find CommissioningTask for key 0x" << std::hex << std::setfill('0') << std::setw(8)
0878                      << key << std::dec << " in directory " << dir << " Unable to book histograms!";
0879                   edm::LogWarning(mlDqmSource_) << ss.str();
0880                 }
0881 
0882               } else {
0883                 std::stringstream ss;
0884                 ss << "[SiStripCommissioningSource::" << __func__ << "]"
0885                    << " CommissioningTask object already exists for key 0x" << std::hex << std::setfill('0')
0886                    << std::setw(8) << key << std::dec << " in directory " << dir
0887                    << " Unable to create FedCablingTask object!";
0888                 edm::LogWarning(mlDqmSource_) << ss.str();
0889               }
0890 
0891             }  // loop through apv pairs
0892           }    // loop through modules
0893         }      // loop through ccus
0894       }        // loop through rings
0895     }          // loop through fecs
0896   }            // loop through crates
0897 
0898   edm::LogVerbatim(mlDqmSource_) << "[SiStripCommissioningSource::" << __func__ << "]"
0899                                  << " Created " << booked << " CommissioningTask objects and booked histograms";
0900 }
0901 
0902 // -----------------------------------------------------------------------------
0903 //
0904 void SiStripCommissioningSource::createTasks(sistrip::RunType run_type, const edm::EventSetup& setup) {
0905   uint16_t booked = 0;
0906 
0907   // latency has partition-level histos, so treat separately
0908   if (task_ == sistrip::APV_LATENCY) {
0909     for (uint16_t partition = 0; partition < 4; ++partition) {
0910       // make a task for every partition; tracker-wide histo is shared
0911       tasks_[0][partition] = new LatencyTask(
0912           dqm(),
0913           FedChannelConnection(
0914               partition + 1, sistrip::invalid_, sistrip::invalid_, sistrip::invalid_, sistrip::invalid_));
0915       tasks_[0][partition]->eventSetup(&setup);
0916       tasks_[0][partition]->bookHistograms();
0917       tasks_[0][partition]->updateFreq(updateFreq_);
0918       booked++;
0919     }
0920 
0921     // fine-delay has 1 histo for the whole tracker, so treat separately
0922   } else if (task_ == sistrip::FINE_DELAY) {
0923     tasks_[0][0] = new FineDelayTask(dqm(), FedChannelConnection());
0924     tasks_[0][0]->eventSetup(&setup);
0925     tasks_[0][0]->bookHistograms();
0926     tasks_[0][0]->updateFreq(updateFreq_);
0927     booked++;
0928 
0929   } else {  // now do any other task
0930 
0931     // Iterate through FED ids and channels
0932     for (auto ifed = fedCabling_->fedIds().begin(); ifed != fedCabling_->fedIds().end(); ++ifed) {
0933       // Iterate through connected FED channels
0934       auto conns = fedCabling_->fedConnections(*ifed);
0935       for (auto iconn = conns.begin(); iconn != conns.end(); ++iconn) {
0936         // Create FEC key
0937         SiStripFecKey fec_key(
0938             iconn->fecCrate(), iconn->fecSlot(), iconn->fecRing(), iconn->ccuAddr(), iconn->ccuChan());
0939         // Create FED key and check if non-zero
0940         SiStripFedKey fed_key(
0941             iconn->fedId(), SiStripFedKey::feUnit(iconn->fedCh()), SiStripFedKey::feChan(iconn->fedCh()));
0942         if (!iconn->isConnected()) {
0943           continue;
0944         }
0945 
0946         // define the view in which to work and paths for histograms
0947         //   currently FecView (control view) and FedView (readout view)
0948         //   DetView (detector view) implementation has started
0949         // Set working directory prior to booking histograms
0950         std::stringstream dir;
0951         dir << base_;
0952         if (view_ == "Default") {  // default
0953           if (run_type == sistrip::FAST_CABLING) {
0954             dir << fed_key.path();  // cabling in fed view
0955           } else {
0956             dir << fec_key.path();  // all other runs in control view
0957           }
0958         } else if (view_ == "FecView") {
0959           dir << fec_key.path();
0960         } else if (view_ == "FedView") {
0961           dir << fed_key.path();
0962         } else if (view_ == "DetView") {
0963           // currently just by detid from the connection, which is empty...
0964           dir << sistrip::root_ << sistrip::dir_ << sistrip::detectorView_ << sistrip::dir_ << iconn->detId();
0965         } else {
0966           edm::LogWarning(mlDqmSource_) << "[SiStripCommissioningSource::" << __func__ << "]"
0967                                         << " Invalid view " << view_ << std::endl
0968                                         << " Histograms will end up all in the top directory.";
0969         }  // end if view_ == ...
0970         dqm()->setCurrentFolder(dir.str());
0971 
0972         // Create commissioning task objects
0973         if (!tasks_[iconn->fedId()][iconn->fedCh()]) {
0974           if (task_ == sistrip::FAST_CABLING) {
0975             tasks_[iconn->fedId()][iconn->fedCh()] = new FastFedCablingTask(dqm(), *iconn);
0976           } else if (task_ == sistrip::APV_TIMING) {
0977             tasks_[iconn->fedId()][iconn->fedCh()] = new ApvTimingTask(dqm(), *iconn);
0978           } else if (task_ == sistrip::FED_TIMING) {
0979             tasks_[iconn->fedId()][iconn->fedCh()] = new FedTimingTask(dqm(), *iconn);
0980           } else if (task_ == sistrip::OPTO_SCAN) {
0981             tasks_[iconn->fedId()][iconn->fedCh()] = new OptoScanTask(dqm(), *iconn);
0982           } else if (task_ == sistrip::VPSP_SCAN) {
0983             tasks_[iconn->fedId()][iconn->fedCh()] = new VpspScanTask(dqm(), *iconn);
0984           } else if (task_ == sistrip::PEDESTALS) {
0985             tasks_[iconn->fedId()][iconn->fedCh()] = new PedestalsTask(dqm(), *iconn);
0986           } else if (task_ == sistrip::PEDS_ONLY) {
0987             tasks_[iconn->fedId()][iconn->fedCh()] = new PedsOnlyTask(dqm(), *iconn);
0988           } else if (task_ == sistrip::NOISE) {
0989             tasks_[iconn->fedId()][iconn->fedCh()] = new NoiseTask(dqm(), *iconn, pedestalToken_, noiseToken_);
0990           } else if (task_ == sistrip::PEDS_FULL_NOISE) {
0991             tasks_[iconn->fedId()][iconn->fedCh()] = new PedsFullNoiseTask(dqm(), *iconn, parameters_);
0992           } else if (task_ == sistrip::DAQ_SCOPE_MODE) {
0993             tasks_[iconn->fedId()][iconn->fedCh()] = new DaqScopeModeTask(dqm(), *iconn, parameters_);
0994           } else if (task_ == sistrip::CALIBRATION_SCAN || task_ == sistrip::CALIBRATION_SCAN_DECO) {
0995             tasks_[iconn->fedId()][iconn->fedCh()] =
0996                 new CalibrationScanTask(dqm(), *iconn, task_, filename_.c_str(), run_, setup.getData(pedestalToken_));
0997           } else if (task_ == sistrip::CALIBRATION || task_ == sistrip::CALIBRATION_DECO) {
0998             tasks_[iconn->fedId()][iconn->fedCh()] =
0999                 new CalibrationTask(dqm(), *iconn, task_, filename_.c_str(), run_, setup.getData(pedestalToken_));
1000           } else if (task_ == sistrip::UNDEFINED_RUN_TYPE) {
1001             edm::LogWarning(mlDqmSource_) << "[SiStripCommissioningSource::" << __func__ << "]"
1002                                           << " Undefined CommissioningTask"
1003                                           << " Unable to create CommissioningTask object!";
1004           } else {
1005             edm::LogWarning(mlDqmSource_) << "[SiStripCommissioningSource::" << __func__ << "]"
1006                                           << " Unknown CommissioningTask"
1007                                           << " Unable to create CommissioningTask object!";
1008           }
1009 
1010           // Check if fed_key is found and, if so, book histos and set update freq
1011           if (tasks_[iconn->fedId()][iconn->fedCh()]) {
1012             tasks_[iconn->fedId()][iconn->fedCh()]->eventSetup(&setup);
1013 
1014             if (task_ != sistrip::CALIBRATION_SCAN and task_ != sistrip::CALIBRATION_SCAN_DECO and
1015                 task_ != sistrip::CALIBRATION and task_ != sistrip::CALIBRATION_DECO)
1016               tasks_[iconn->fedId()][iconn->fedCh()]->bookHistograms();
1017             else {
1018               if (task_ == sistrip::CALIBRATION_SCAN or task_ == sistrip::CALIBRATION_SCAN_DECO)
1019                 static_cast<CalibrationScanTask*>(tasks_[iconn->fedId()][iconn->fedCh()])->setCurrentFolder(dir.str());
1020               else if (task_ == sistrip::CALIBRATION or task_ == sistrip::CALIBRATION_DECO)
1021                 static_cast<CalibrationTask*>(tasks_[iconn->fedId()][iconn->fedCh()])->setCurrentFolder(dir.str());
1022             }
1023             tasks_[iconn->fedId()][iconn->fedCh()]->updateFreq(updateFreq_);
1024             booked++;
1025           } else {
1026             std::stringstream ss;
1027             ss << "[SiStripCommissioningSource::" << __func__ << "]"
1028                << " NULL pointer to CommissioningTask for key 0x" << std::hex << std::setfill('0') << std::setw(8)
1029                << fed_key.key() << std::dec << " in directory " << dir.str() << " Unable to book histograms!";
1030             edm::LogWarning(mlDqmSource_) << ss.str();
1031           }
1032         } else {
1033           std::stringstream ss;
1034           ss << "[SiStripCommissioningSource::" << __func__ << "]"
1035              << " CommissioningTask object already exists for key 0x" << std::hex << std::setfill('0') << std::setw(8)
1036              << fed_key.key() << std::dec << " in directory " << dir.str()
1037              << " Unable to create CommissioningTask object!";
1038           edm::LogWarning(mlDqmSource_) << ss.str();
1039         }
1040       }  // loop over fed channels
1041     }    // loop over feds
1042   }      // end other tasks
1043   edm::LogVerbatim(mlDqmSource_) << "[SiStripCommissioningSource::" << __func__ << "]"
1044                                  << " Created " << booked << " CommissioningTask objects and booked histograms";
1045 }
1046 
1047 // ----------------------------------------------------------------------------
1048 //
1049 void SiStripCommissioningSource::clearCablingTasks() {
1050   if (cablingTasks_.empty()) {
1051     return;
1052   }
1053   for (TaskMap::iterator itask = cablingTasks_.begin(); itask != cablingTasks_.end(); itask++) {
1054     if (itask->second) {
1055       delete itask->second;
1056     }
1057   }
1058   cablingTasks_.clear();
1059 }
1060 
1061 // ----------------------------------------------------------------------------
1062 //
1063 void SiStripCommissioningSource::clearTasks() {
1064   if (tasks_.empty()) {
1065     return;
1066   }
1067   VecOfVecOfTasks::iterator ifed = tasks_.begin();
1068   for (; ifed != tasks_.end(); ifed++) {
1069     VecOfTasks::iterator ichan = ifed->begin();
1070     for (; ichan != ifed->end(); ichan++) {
1071       if (*ichan) {
1072         delete *ichan;
1073         *ichan = 0;
1074       }
1075     }
1076     ifed->resize(96, nullptr);
1077   }
1078   tasks_.resize(1024);
1079 }
1080 
1081 // ----------------------------------------------------------------------------
1082 //
1083 void SiStripCommissioningSource::remove() {
1084   // TODO: remove no longer supported in DQMStore.
1085 }
1086 
1087 // -----------------------------------------------------------------------------
1088 //
1089 void SiStripCommissioningSource::directory(std::stringstream& dir, uint32_t run_number) {
1090   // Get details about host
1091   char hn[256];
1092   gethostname(hn, sizeof(hn));
1093   struct hostent* he;
1094   he = gethostbyname(hn);
1095 
1096   // Extract host name and ip
1097   std::string host_name;
1098   std::string host_ip;
1099   if (he) {
1100     host_name = std::string(he->h_name);
1101     host_ip = std::string(inet_ntoa(*(struct in_addr*)(he->h_addr)));
1102   } else {
1103     host_name = "unknown.cern.ch";
1104     host_ip = "255.255.255.255";
1105   }
1106 
1107   // Reformat IP address
1108   std::string::size_type pos = 0;
1109   std::stringstream ip;
1110   //for ( uint16_t ii = 0; ii < 4; ++ii ) {
1111   while (pos != std::string::npos) {
1112     std::string::size_type tmp = host_ip.find('.', pos);
1113     if (tmp != std::string::npos) {
1114       ip << std::setw(3) << std::setfill('0') << host_ip.substr(pos, tmp - pos) << ".";
1115       pos = tmp + 1;  // skip the delimiter "."
1116     } else {
1117       ip << std::setw(3) << std::setfill('0') << host_ip.substr(pos);
1118       pos = std::string::npos;
1119     }
1120   }
1121 
1122   // Get pid
1123   pid_t pid = getpid();
1124 
1125   // Construct string
1126   if (run_number) {
1127     dir << std::setw(8) << std::setfill('0') << run_number << "_";
1128   }
1129   dir << ip.str() << "_" << std::setw(5) << std::setfill('0') << pid;
1130 }
1131 
1132 // -----------------------------------------------------------------------------
1133 //
1134 // void SiStripCommissioningSource::cablingForConnectionRun( const sistrip::RunType& type ) {
1135 
1136 //   if ( type == sistrip::FED_CABLING ||
1137 //        type == sistrip::QUITE_FAST_CABLING ||
1138 //        type == sistrip::FAST_CABLING ) {
1139 //     std::stringstream ss;
1140 //     ss << "[SiStripCommissioningSource::" << __func__ << "]"
1141 //        << " Run type is " << SiStripEnumsAndStrings::runType( type ) << "!"
1142 //        << " Checking if cabling should be rebuilt using FED and device descriptions!...";
1143 //     edm::LogVerbatim(mlDqmSource_) << ss.str();
1144 //   } else { return; }
1145 
1146 //   // Build and retrieve SiStripConfigDb object using service
1147 //   SiStripConfigDb* db = edm::Service<SiStripConfigDb>().operator->(); //@@ NOT GUARANTEED TO BE THREAD SAFE!
1148 //   LogTrace(mlCabling_)
1149 //     << "[SiStripCommissioningSource::" << __func__ << "]"
1150 //     << " Nota bene: using the SiStripConfigDb API"
1151 //     << " as a \"service\" does not presently guarantee"
1152 //     << " thread-safe behaviour!...";
1153 
1154 //   if ( !db ) {
1155 //     edm::LogError(mlCabling_)
1156 //       << "[SiStripCommissioningSource::" << __func__ << "]"
1157 //       << " NULL pointer to SiStripConfigDb returned by service!"
1158 //       << " Cannot check if cabling needs to be rebuilt!";
1159 //     return;
1160 //   }
1161 
1162 //   if ( db->getFedConnections().empty() ) {
1163 //     edm::LogVerbatim(mlCabling_)
1164 //       << "[SiStripCommissioningSource::" << __func__ << "]"
1165 //       << " Datbase does not contain FED connections!"
1166 //       << " Do not need to rebuild cabling object based on FED and device descriptions!";
1167 //    return;
1168 //   }
1169 
1170 //   if ( fecCabling_ ) { delete fecCabling_; fecCabling_ = 0; }
1171 //   if ( fedCabling_ ) { delete fedCabling_; fedCabling_ = 0; }
1172 
1173 //   // Build FEC cabling
1174 //   fecCabling_ = new SiStripFecCabling();
1175 //   SiStripConfigDb::DcuDetIdMap mapping;
1176 //   SiStripFedCablingBuilderFromDb::buildFecCablingFromDevices( db,
1177 //                                *fecCabling_,
1178 //                                mapping );
1179 //   // Build FED cabling
1180 //   fedCabling_ = new SiStripFedCabling();
1181 //   SiStripFedCablingBuilderFromDb::getFedCabling( *fecCabling_,
1182 //                       *fedCabling_ );
1183 
1184 //   edm::LogVerbatim(mlCabling_)
1185 //     << "[SiStripCommissioningSource::" << __func__ << "]"
1186 //     << " Cabling object rebuilt using on FED and device descriptions!";
1187 
1188 // }