CreateIdealTkAlRecords

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 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
// -*- C++ -*-
//
// Package:    Alignment/TrackerAlignment
// Class:      CreateIdealTkAlRecords
//
/**\class CreateIdealTkAlRecords CreateIdealTkAlRecords.cc Alignment/TrackerAlignment/plugins/CreateIdealTkAlRecords.cc

 Description: Plugin to create ideal tracker alignment records.

 Implementation:
     The plugin takes the geometry stored in the global tag and transfers this
     information to the format needed in the TrackerAlignmentRcd. The APEs are
     set to zero for all det IDs of the tracker geometry and put into an
     TrackerAlignmentErrorExtendedRcd. In addition an empty
     TrackerSurfaceDeformationRcd is created corresponding to ideal surfaces.

     An option exists to align to the content of the used global tag. This is
     useful, if the geometry record and the tracker alignment records do not
     match.

*/
//
// Original Author:  Gregor Mittag
//         Created:  Tue, 26 Apr 2016 09:45:13 GMT
//
//

// system include files
#include <memory>
#include <iostream>

// user include files
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/one/EDAnalyzer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/ServiceRegistry/interface/Service.h"

#include "CondCore/DBOutputService/interface/PoolDBOutputService.h"

#include "CondFormats/Alignment/interface/Alignments.h"
#include "CondFormats/Alignment/interface/AlignTransform.h"
#include "CondFormats/Alignment/interface/AlignmentErrorsExtended.h"
#include "CondFormats/Alignment/interface/AlignTransformError.h"
#include "CondFormats/Alignment/interface/AlignTransformErrorExtended.h"
#include "CondFormats/Alignment/interface/AlignmentSurfaceDeformations.h"
#include "CondFormats/AlignmentRecord/interface/TrackerAlignmentRcd.h"
#include "CondFormats/AlignmentRecord/interface/TrackerAlignmentErrorExtendedRcd.h"
#include "CondFormats/AlignmentRecord/interface/TrackerSurfaceDeformationRcd.h"
#include "CondFormats/GeometryObjects/interface/PTrackerParameters.h"
#include "CondFormats/GeometryObjects/interface/PTrackerAdditionalParametersPerDet.h"

#include "DataFormats/TrackerCommon/interface/TrackerTopology.h"

#include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h"
#include "Geometry/TrackerGeometryBuilder/interface/TrackerGeomBuilderFromGeometricDet.h"
#include "Geometry/Records/interface/IdealGeometryRecord.h"
#include "Geometry/Records/interface/TrackerTopologyRcd.h"
#include "Geometry/Records/interface/PTrackerParametersRcd.h"
#include "Geometry/Records/interface/PTrackerAdditionalParametersPerDetRcd.h"

#include "CLHEP/Vector/RotationInterfaces.h"

//
// class declaration
//

class CreateIdealTkAlRecords : public edm::one::EDAnalyzer<> {
public:
  explicit CreateIdealTkAlRecords(const edm::ParameterSet&);
  ~CreateIdealTkAlRecords() override;

  static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
  static std::string toString(const GeomDetEnumerators::SubDetector&);
  static GeomDetEnumerators::SubDetector toSubDetector(const std::string& sub);
  static std::vector<GeomDetEnumerators::SubDetector> toSubDetectors(const std::vector<std::string>& subs);

private:
  void analyze(const edm::Event&, const edm::EventSetup&) override;
  void clearAlignmentInfos();
  std::unique_ptr<TrackerGeometry> retrieveGeometry(const edm::EventSetup&);
  void addAlignmentInfo(const GeomDet&);
  void alignToGT(const edm::EventSetup&);
  void writeToDB();

  // ----------member data ---------------------------

  const edm::ESGetToken<GeometricDet, IdealGeometryRecord> geomDetToken_;
  const edm::ESGetToken<PTrackerParameters, PTrackerParametersRcd> ptpToken_;
  const edm::ESGetToken<PTrackerAdditionalParametersPerDet, PTrackerAdditionalParametersPerDetRcd> ptitpToken_;
  const edm::ESGetToken<TrackerTopology, TrackerTopologyRcd> topoToken_;
  const edm::ESGetToken<Alignments, TrackerAlignmentRcd> aliToken_;
  const edm::ESGetToken<AlignmentErrorsExtended, TrackerAlignmentErrorExtendedRcd> aliErrorToken_;
  const edm::ESGetToken<AlignmentSurfaceDeformations, TrackerSurfaceDeformationRcd> aliSurfaceToken_;
  const std::vector<GeomDetEnumerators::SubDetector> skipSubDetectors_;
  const bool alignToGlobalTag_;
  const bool createReferenceRcd_;
  bool firstEvent_;
  Alignments alignments_;
  AlignmentErrorsExtended alignmentErrors_;
  AlignmentSurfaceDeformations alignmentSurfaceDeformations_;
  std::vector<uint32_t> rawIDs_;
  std::vector<GeomDetEnumerators::SubDetector> subDets_;
};

//
// constructors and destructor
//
CreateIdealTkAlRecords::CreateIdealTkAlRecords(const edm::ParameterSet& iConfig)
    : geomDetToken_(esConsumes()),
      ptpToken_(esConsumes()),
      ptitpToken_(esConsumes()),
      topoToken_(esConsumes()),
      aliToken_(esConsumes()),
      aliErrorToken_(esConsumes()),
      aliSurfaceToken_(esConsumes()),
      skipSubDetectors_(toSubDetectors(iConfig.getUntrackedParameter<std::vector<std::string> >("skipSubDetectors"))),
      alignToGlobalTag_(iConfig.getUntrackedParameter<bool>("alignToGlobalTag")),
      createReferenceRcd_(iConfig.getUntrackedParameter<bool>("createReferenceRcd")),
      firstEvent_(true) {}

CreateIdealTkAlRecords::~CreateIdealTkAlRecords() {}

//
// member functions
//

// ------------ method called for each event  ------------
void CreateIdealTkAlRecords::analyze(const edm::Event&, const edm::EventSetup& iSetup) {
  if (firstEvent_) {
    clearAlignmentInfos();
    const auto tracker = retrieveGeometry(iSetup);

    auto dets = tracker->dets();
    std::sort(dets.begin(), dets.end(), [](const auto& a, const auto& b) {
      return a->geographicalId().rawId() < b->geographicalId().rawId();
    });

    for (const auto& det : dets)
      addAlignmentInfo(*det);
    if (alignToGlobalTag_ && !createReferenceRcd_)
      alignToGT(iSetup);
    writeToDB();
    firstEvent_ = false;
  }
}

std::string CreateIdealTkAlRecords::toString(const GeomDetEnumerators::SubDetector& sub) {
  switch (sub) {
    case GeomDetEnumerators::PixelBarrel:
      return "PixelBarrel";
    case GeomDetEnumerators::PixelEndcap:
      return "PixelEndcap";
    case GeomDetEnumerators::TIB:
      return "TIB";
    case GeomDetEnumerators::TOB:
      return "TOB";
    case GeomDetEnumerators::TID:
      return "TID";
    case GeomDetEnumerators::TEC:
      return "TEC";
    case GeomDetEnumerators::CSC:
      return "CSC";
    case GeomDetEnumerators::DT:
      return "DT";
    case GeomDetEnumerators::RPCBarrel:
      return "RPCBarrel";
    case GeomDetEnumerators::RPCEndcap:
      return "RPCEndcap";
    case GeomDetEnumerators::GEM:
      return "GEM";
    case GeomDetEnumerators::ME0:
      return "ME0";
    case GeomDetEnumerators::P2OTB:
      return "P2OTB";
    case GeomDetEnumerators::P2OTEC:
      return "P2OTEC";
    case GeomDetEnumerators::P1PXB:
      return "P1PXB";
    case GeomDetEnumerators::P1PXEC:
      return "P1PXEC";
    case GeomDetEnumerators::P2PXB:
      return "P2PXB";
    case GeomDetEnumerators::P2PXEC:
      return "P2PXEC";
    case GeomDetEnumerators::invalidDet:
      return "invalidDet";
    default:
      throw cms::Exception("UnknownSubdetector");
  }
}

GeomDetEnumerators::SubDetector CreateIdealTkAlRecords::toSubDetector(const std::string& sub) {
  if (sub == "PixelBarrel")
    return GeomDetEnumerators::PixelBarrel;
  else if (sub == "PixelEndcap")
    return GeomDetEnumerators::PixelEndcap;
  else if (sub == "TIB")
    return GeomDetEnumerators::TIB;
  else if (sub == "TOB")
    return GeomDetEnumerators::TOB;
  else if (sub == "TID")
    return GeomDetEnumerators::TID;
  else if (sub == "TEC")
    return GeomDetEnumerators::TEC;
  else if (sub == "CSC")
    return GeomDetEnumerators::CSC;
  else if (sub == "DT")
    return GeomDetEnumerators::DT;
  else if (sub == "RPCBarrel")
    return GeomDetEnumerators::RPCBarrel;
  else if (sub == "RPCEndcap")
    return GeomDetEnumerators::RPCEndcap;
  else if (sub == "GEM")
    return GeomDetEnumerators::GEM;
  else if (sub == "ME0")
    return GeomDetEnumerators::ME0;
  else if (sub == "P2OTB")
    return GeomDetEnumerators::P2OTB;
  else if (sub == "P2OTEC")
    return GeomDetEnumerators::P2OTEC;
  else if (sub == "P1PXB")
    return GeomDetEnumerators::P1PXB;
  else if (sub == "P1PXEC")
    return GeomDetEnumerators::P1PXEC;
  else if (sub == "P2PXB")
    return GeomDetEnumerators::P2PXB;
  else if (sub == "P2PXEC")
    return GeomDetEnumerators::P2PXEC;
  else if (sub == "invalidDet")
    return GeomDetEnumerators::invalidDet;
  else
    throw cms::Exception("UnknownSubdetector") << sub;
}

std::vector<GeomDetEnumerators::SubDetector> CreateIdealTkAlRecords::toSubDetectors(
    const std::vector<std::string>& subs) {
  std::vector<GeomDetEnumerators::SubDetector> result;
  result.reserve(subs.size());
  for (const auto& sub : subs)
    result.emplace_back(toSubDetector(sub));
  return result;
}

void CreateIdealTkAlRecords::clearAlignmentInfos() {
  alignments_.clear();
  alignmentErrors_.clear();
  alignmentSurfaceDeformations_ = AlignmentSurfaceDeformations{};
  rawIDs_.clear();
}

std::unique_ptr<TrackerGeometry> CreateIdealTkAlRecords::retrieveGeometry(const edm::EventSetup& iSetup) {
  const GeometricDet* geometricDet = &iSetup.getData(geomDetToken_);
  const PTrackerParameters& ptp = iSetup.getData(ptpToken_);
  const PTrackerAdditionalParametersPerDet* ptitp = &iSetup.getData(ptitpToken_);
  const TrackerTopology* tTopo = &iSetup.getData(topoToken_);

  TrackerGeomBuilderFromGeometricDet trackerBuilder;

  return std::unique_ptr<TrackerGeometry>{trackerBuilder.build(geometricDet, ptitp, ptp, tTopo)};
}

void CreateIdealTkAlRecords::addAlignmentInfo(const GeomDet& det) {
  const auto subDetector = toString(det.subDetector());
  const auto& detId = det.geographicalId().rawId();
  const auto& pos = det.position();
  const auto& rot = det.rotation();
  rawIDs_.push_back(detId);
  subDets_.push_back(det.subDetector());

  // TrackerAlignmentRcd entry
  if (createReferenceRcd_) {
    alignments_.m_align.emplace_back(AlignTransform(AlignTransform::Translation(), AlignTransform::Rotation(), detId));
  } else {
    const AlignTransform::Translation translation(pos.x(), pos.y(), pos.z());
    const AlignTransform::Rotation rotation(
        CLHEP::HepRep3x3(rot.xx(), rot.xy(), rot.xz(), rot.yx(), rot.yy(), rot.yz(), rot.zx(), rot.zy(), rot.zz()));
    const auto& eulerAngles = rotation.eulerAngles();
    LogDebug("Alignment") << "============================================================\n"
                          << "subdetector: " << subDetector << "\n"
                          << "detId:       " << detId << "\n"
                          << "------------------------------------------------------------\n"
                          << "     x: " << pos.x() << "\n"
                          << "     y: " << pos.y() << "\n"
                          << "     z: " << pos.z() << "\n"
                          << "   phi: " << eulerAngles.phi() << "\n"
                          << " theta: " << eulerAngles.theta() << "\n"
                          << "   psi: " << eulerAngles.psi() << "\n"
                          << "============================================================\n";
    alignments_.m_align.emplace_back(AlignTransform(translation, rotation, detId));
  }

  // TrackerAlignmentErrorExtendedRcd entry
  const AlignTransformError::SymMatrix zeroAPEs(6, 0);
  alignmentErrors_.m_alignError.emplace_back(AlignTransformErrorExtended(zeroAPEs, detId));
}

void CreateIdealTkAlRecords::alignToGT(const edm::EventSetup& iSetup) {
  LogDebug("Alignment") << "Aligning to global tag\n";

  const Alignments* alignments = &iSetup.getData(aliToken_);
  const AlignmentErrorsExtended* alignmentErrors = &iSetup.getData(aliErrorToken_);
  const AlignmentSurfaceDeformations* surfaceDeformations = &iSetup.getData(aliSurfaceToken_);

  if (alignments->m_align.size() != alignmentErrors->m_alignError.size())
    throw cms::Exception("GeometryMismatch")
        << "Size mismatch between alignments (size=" << alignments->m_align.size()
        << ") and alignment errors (size=" << alignmentErrors->m_alignError.size() << ")";

  std::vector<uint32_t> commonIDs;
  auto itAlignErr = alignmentErrors->m_alignError.cbegin();
  for (auto itAlign = alignments->m_align.cbegin(); itAlign != alignments->m_align.cend(); ++itAlign, ++itAlignErr) {
    const auto id = itAlign->rawId();
    auto found = std::find(rawIDs_.cbegin(), rawIDs_.cend(), id);
    if (found != rawIDs_.cend()) {
      if (id != itAlignErr->rawId())
        throw cms::Exception("GeometryMismatch") << "DetId mismatch between alignments (rawId=" << id
                                                 << ") and alignment errors (rawId=" << itAlignErr->rawId() << ")";

      const auto index = std::distance(rawIDs_.cbegin(), found);
      if (std::find(skipSubDetectors_.begin(), skipSubDetectors_.end(), subDets_[index]) != skipSubDetectors_.end())
        continue;

      if (alignments_.m_align[index].rawId() != alignmentErrors_.m_alignError[index].rawId())
        throw cms::Exception("GeometryMismatch")
            << "DetId mismatch between alignments (rawId=" << alignments_.m_align[index].rawId()
            << ") and alignment errors (rawId=" << alignmentErrors_.m_alignError[index].rawId() << ")";

      LogDebug("Alignment") << "============================================================\n"
                            << "\nGeometry content (" << toString(subDets_[index]) << ", "
                            << alignments_.m_align[index].rawId() << "):\n"
                            << "\tx: " << alignments_.m_align[index].translation().x()
                            << "\ty: " << alignments_.m_align[index].translation().y()
                            << "\tz: " << alignments_.m_align[index].translation().z()
                            << "\tphi: " << alignments_.m_align[index].rotation().phi()
                            << "\ttheta: " << alignments_.m_align[index].rotation().theta()
                            << "\tpsi: " << alignments_.m_align[index].rotation().psi()
                            << "============================================================\n";
      alignments_.m_align[index] = *itAlign;
      alignmentErrors_.m_alignError[index] = *itAlignErr;
      commonIDs.push_back(id);
      LogDebug("Alignment") << "============================================================\n"
                            << "Global tag content (" << toString(subDets_[index]) << ", "
                            << alignments_.m_align[index].rawId() << "):\n"
                            << "\tx: " << alignments_.m_align[index].translation().x()
                            << "\ty: " << alignments_.m_align[index].translation().y()
                            << "\tz: " << alignments_.m_align[index].translation().z()
                            << "\tphi: " << alignments_.m_align[index].rotation().phi()
                            << "\ttheta: " << alignments_.m_align[index].rotation().theta()
                            << "\tpsi: " << alignments_.m_align[index].rotation().psi()
                            << "============================================================\n";
    }
  }

  // - surface deformations are stored differently
  //   -> different treatment
  // - the above payloads contain also entries for ideal modules
  // - no entry is created for ideal surfaces
  //   -> size of surface deformation payload does not necessarily match the
  //      size of the other tracker alignment payload
  for (const auto& id : commonIDs) {
    // search for common raw ID in surface deformation items
    auto item = std::find_if(surfaceDeformations->items().cbegin(),
                             surfaceDeformations->items().cend(),
                             [&id](const auto& i) { return i.m_rawId == id; });
    if (item == surfaceDeformations->items().cend())
      continue;  // not found

    // copy surface deformation item
    const auto index = std::distance(surfaceDeformations->items().cbegin(), item);
    const auto beginEndPair = surfaceDeformations->parameters(index);
    std::vector<align::Scalar> params(beginEndPair.first, beginEndPair.second);
    alignmentSurfaceDeformations_.add(item->m_rawId, item->m_parametrizationType, params);
  }
}

void CreateIdealTkAlRecords::writeToDB() {
  const auto& since = cond::timeTypeSpecs[cond::runnumber].beginValue;

  edm::Service<cond::service::PoolDBOutputService> poolDb;
  if (!poolDb.isAvailable()) {
    throw cms::Exception("NotAvailable") << "PoolDBOutputService not available";
  }

  edm::LogInfo("Alignment") << "Writing ideal tracker-alignment records.";
  poolDb->writeOneIOV(alignments_, since, "TrackerAlignmentRcd");
  poolDb->writeOneIOV(alignmentErrors_, since, "TrackerAlignmentErrorExtendedRcd");
  poolDb->writeOneIOV(alignmentSurfaceDeformations_, since, "TrackerSurfaceDeformationRcd");
}

// ------------ method fills 'descriptions' with the allowed parameters for the module  ------------
void CreateIdealTkAlRecords::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
  edm::ParameterSetDescription desc;
  desc.setComment(
      "Creates ideal TrackerAlignmentRcd and TrackerAlignmentErrorExtendedRcd "
      "from the loaded tracker geometry. "
      "PoolDBOutputService must be set up for these records.");
  desc.addUntracked<bool>("alignToGlobalTag", false);
  desc.addUntracked<std::vector<std::string> >("skipSubDetectors", std::vector<std::string>{});
  desc.addUntracked<bool>("createReferenceRcd", false);
  descriptions.add("createIdealTkAlRecords", desc);
}

//define this as a plug-in
DEFINE_FWK_MODULE(CreateIdealTkAlRecords);