SiStripBadChannelPatcher

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
// system include files
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>

// user include files
#include "CalibFormats/SiStripObjects/interface/SiStripDetCabling.h"
#include "CalibTracker/Records/interface/SiStripDetCablingRcd.h"
#include "CalibTracker/SiStripCommon/interface/SiStripDetInfoFileReader.h"
#include "CondCore/DBOutputService/interface/PoolDBOutputService.h"
#include "CondFormats/DataRecord/interface/SiStripBadStripRcd.h"
#include "CondFormats/SiStripObjects/interface/SiStripBadStrip.h"
#include "DataFormats/FEDRawData/interface/FEDNumbering.h"
#include "DataFormats/SiStripCommon/interface/ConstantsForHardwareSystems.h" /* for STRIPS_PER_APV*/
#include "FWCore/Framework/interface/one/EDAnalyzer.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
#include "FWCore/ParameterSet/interface/FileInPath.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/ParameterSet/interface/ParameterSetDescription.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "FWCore/Utilities/interface/Exception.h"

namespace sistrip {
  static const uint16_t NOT_A_FEDID = static_cast<uint16_t>(FEDNumbering::NOT_A_FEDID);
}

class SiStripBadChannelPatcher : public edm::one::EDAnalyzer<> {
public:
  explicit SiStripBadChannelPatcher(const edm::ParameterSet& iConfig)
      : record_(iConfig.getParameter<std::string>("Record")),
        printDebug_(iConfig.getParameter<bool>("printDebug")),
        detIdsToExclude_(iConfig.getParameter<std::vector<unsigned int>>("detIdsToExclude")),
        detIdsToInclude_(iConfig.getParameter<std::vector<unsigned int>>("detIdsToInclude")),
        fedsToExclude_(iConfig.getParameter<std::vector<unsigned int>>("FEDsToExclude")),
        fedsToInclude_(iConfig.getParameter<std::vector<unsigned int>>("FEDsToInclude")),
        badStripToken_(esConsumes()),
        cablingToken_(esConsumes()) {}

  static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
  ~SiStripBadChannelPatcher() override = default;

private:
  void analyze(const edm::Event&, const edm::EventSetup&) override;
  std::unique_ptr<SiStripBadStrip> getNewObject(const edm::EventSetup& iSetup);
  unsigned int fedFromDetId(const uint32_t& detid);
  void addDetIdsFromExcludedFEDs(const std::vector<uint32_t>& allDetIds);

  // member data
  const SiStripDetCabling* detCabling_;
  const std::string record_;
  const bool printDebug_;
  std::vector<uint32_t> detIdsToExclude_;
  std::vector<uint32_t> detIdsToInclude_;
  std::vector<unsigned int> fedsToExclude_;
  std::vector<unsigned int> fedsToInclude_;
  const edm::ESGetToken<SiStripBadStrip, SiStripBadStripRcd> badStripToken_;    /*!< ES token for the bad strips */
  const edm::ESGetToken<SiStripDetCabling, SiStripDetCablingRcd> cablingToken_; /*!< ES token for the cabling */
};

//-----------------------------------------------------------------------------------------------//
void SiStripBadChannelPatcher::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
  edm::ParameterSetDescription desc;
  desc.setComment(
      "create a SiStripBadStrip payload starting from one in DB and excluding or adding entire modules from a list");
  desc.add<std::string>("Record", "SiStripBadStrip")->setComment("Record to match in the PoolDBOutputService");
  desc.add<bool>("printDebug", false)->setComment("full debug printout");
  desc.add<std::vector<unsigned int>>("detIdsToExclude", {})->setComment("list of detIds to exclude");
  desc.add<std::vector<unsigned int>>("detIdsToInclude", {})->setComment("list of detIds to include");
  desc.add<std::vector<unsigned int>>("FEDsToExclude", {})->setComment("list of FEDs to exclude");
  desc.add<std::vector<unsigned int>>("FEDsToInclude", {})->setComment("list of FEDs to include");
  descriptions.addWithDefaultLabel(desc);
}

//-----------------------------------------------------------------------------------------------//
unsigned int SiStripBadChannelPatcher::fedFromDetId(const uint32_t& detid) {
  // For the cabled det_id retrieve the FEDid
  const std::vector<const FedChannelConnection*>& conns = detCabling_->getConnections(detid);
  if (conns.empty()) {
    edm::LogWarning("SiStripBadChannelPatcher")
        << " DetId " << detid << " appears to be uncabled, returning NOT_A_FEDID !";
    return sistrip::NOT_A_FEDID;
  }
  unsigned int lFedId = sistrip::NOT_A_FEDID;
  for (uint32_t ch = 0; ch < conns.size(); ch++) {
    if (conns[ch] && conns[ch]->isConnected()) {
      lFedId = conns[ch]->fedId();
      LogDebug("SiStripBadChannelPatcher") << "obtained FED id " << ch << " " << lFedId;
      if (lFedId < sistrip::FED_ID_MIN || lFedId > sistrip::FED_ID_MAX) {
        edm::LogWarning("SiStripBadChannelPatcher") << lFedId << " for detid " << detid << " connection " << ch;
        continue;
      } else {
        break;
      }
    }
  }
  return lFedId;
}

//-----------------------------------------------------------------------------------------------//
void SiStripBadChannelPatcher::addDetIdsFromExcludedFEDs(const std::vector<uint32_t>& allDetIds) {
  for (const auto& detid : allDetIds) {
    const auto& currentFED = this->fedFromDetId(detid);
    if (std::count(fedsToInclude_.begin(), fedsToInclude_.end(), currentFED)) {
      detIdsToInclude_.push_back(detid);
    }
  }
}

//-----------------------------------------------------------------------------------------------//
void SiStripBadChannelPatcher::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) {
  using namespace edm;

  // create the patched bad strips payload
  std::unique_ptr<SiStripBadStrip> theBadStrips = this->getNewObject(iSetup);

  // write out the BadStrip record
  edm::Service<cond::service::PoolDBOutputService> poolDbService;

  if (poolDbService.isAvailable()) {
    poolDbService->writeOneIOV(*theBadStrips, poolDbService->currentTime(), record_);
  } else {
    throw std::runtime_error("PoolDBService required.");
  }
}

//-----------------------------------------------------------------------------------------------//
std::unique_ptr<SiStripBadStrip> SiStripBadChannelPatcher::getNewObject(const edm::EventSetup& iSetup) {
  edm::LogInfo("SiStripBadChannelPatcher") << "... creating dummy SiStripBadStrip Data";

  // this is the output object
  auto obj = std::make_unique<SiStripBadStrip>();

  // get the cabling object
  detCabling_ = &iSetup.getData(cablingToken_);

  // get the strips to add
  std::vector<uint32_t> detids;
  const auto& payload = iSetup.getData(badStripToken_);
  payload.getDetIds(detids);

  // copy the exisiting channels (excluding the ones to remove)
  for (const auto& id : detids) {
    // check on the detids to exclude
    if (std::count(detIdsToExclude_.begin(), detIdsToExclude_.end(), id)) {
      edm::LogInfo("SiStripBadChannelPatcher") << "I AM GOING TO EXCLUDE DETID: " << id;
      continue;
    } else {
      LogDebug("SiStripBadChannelPatcher") << "I AM GOING TO KEEP DETID: " << id;
    }

    // check on the FEDs to exclude
    const auto& currentFED = this->fedFromDetId(id);
    if (std::count(fedsToExclude_.begin(), fedsToExclude_.end(), currentFED)) {
      edm::LogInfo("SiStripBadChannelPatcher") << "I AM GOING TO EXCLUDE DETID: " << id;
      continue;
    } else {
      LogDebug("SiStripBadChannelPatcher") << "I AM GOING TO KEEP DETID: " << id;
    }

    SiStripBadStrip::Range range = payload.getRange(id);
    std::vector<unsigned int> theSiStripVector;
    unsigned int theBadStripRange;
    for (std::vector<unsigned int>::const_iterator badStrip = range.first; badStrip != range.second; ++badStrip) {
      unsigned short firstBadStrip = payload.decode(*badStrip).firstStrip;
      unsigned short nConsecutiveBadStrips = payload.decode(*badStrip).range;
      theBadStripRange = obj->encode(firstBadStrip, nConsecutiveBadStrips);
      theSiStripVector.push_back(theBadStripRange);
    }
    SiStripBadStrip::Range outRange(theSiStripVector.begin(), theSiStripVector.end());
    if (!obj->put(id, outRange))
      edm::LogError("SiStripBadChannelPatcher") << "[SiStripBadChannelPatcher::analyze] detid already exists";
  }  // loop on the detids of the original payload

  const auto& detInfo =
      SiStripDetInfoFileReader::read(edm::FileInPath{SiStripDetInfoFileReader::kDefaultFile}.fullPath());

  // add to the list of DetIds to include also the one from the list of FEDs
  const std::vector<uint32_t>& allDetIds = detInfo.getAllDetIds();
  this->addDetIdsFromExcludedFEDs(allDetIds);

  // add more full bad detids
  if (!detIdsToInclude_.empty()) {
    edm::LogInfo("SiStripBadChannelPatcher") << "I AM GOING TO ADD MORE DETIDS";

    std::stringstream ss;
    for (const auto& detid : detIdsToInclude_) {
      edm::LogInfo("SiStripBadChannelPatcher") << "I AM GOING TO ADD DETID: " << detid;
      const auto& nAPVs = detInfo.getNumberOfApvsAndStripLength(detid).first;

      std::vector<unsigned int> theSiStripVector;
      unsigned short firstBadStrip{0}, nConsecutiveBadStrips{0};
      unsigned int theBadStripRange;

      for (unsigned int n = 0; n < nAPVs; n++) {
        firstBadStrip = n * sistrip::STRIPS_PER_APV;
        nConsecutiveBadStrips = sistrip::STRIPS_PER_APV;
        theBadStripRange = obj->encode(firstBadStrip, nConsecutiveBadStrips);

        if (printDebug_) {
          ss << "detid " << detid << " \t"
             << " firstBadStrip " << firstBadStrip << "\t "
             << " nConsecutiveBadStrips " << nConsecutiveBadStrips << "\t "
             << " packed integer " << std::hex << theBadStripRange << std::dec << std::endl;
        }

        theSiStripVector.push_back(theBadStripRange);
      }

      SiStripBadStrip::Range outRange(theSiStripVector.begin(), theSiStripVector.end());
      if (!obj->put(detid, outRange))
        edm::LogError("SiStripBadChannelPatcher") << "[SiStripBadChannelPatcher::analyze] detid already exists";
    }  // loop on detids to include

    if (printDebug_) {
      // print the added strips
      edm::LogInfo("SiStripBadChannelPatcher") << ss.str();
    }

  }  // if there is any new channel to append

  return obj;
}

#include "FWCore/PluginManager/interface/ModuleDef.h"
#include "FWCore/Framework/interface/MakerMacros.h"

DEFINE_FWK_MODULE(SiStripBadChannelPatcher);