SlimmedCount

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
#include "DataFormats/Provenance/interface/ThinnedAssociationsHelper.h"
#include "DataFormats/Provenance/interface/ProductDescription.h"
#include "FWCore/Utilities/interface/EDMException.h"
#include <algorithm>

#include <fmt/format.h>

namespace edm {

  ThinnedAssociationBranches::ThinnedAssociationBranches() {}

  ThinnedAssociationBranches::ThinnedAssociationBranches(BranchID const& parent,
                                                         BranchID const& association,
                                                         BranchID const& thinned,
                                                         bool slimmed)
      : parent_(parent), association_(association), thinned_(thinned), slimmed_(slimmed) {}

  ThinnedAssociationsHelper::ThinnedAssociationsHelper() {}

  std::vector<ThinnedAssociationBranches>::const_iterator ThinnedAssociationsHelper::begin() const {
    return vThinnedAssociationBranches_.begin();
  }

  std::vector<ThinnedAssociationBranches>::const_iterator ThinnedAssociationsHelper::end() const {
    return vThinnedAssociationBranches_.end();
  }

  std::vector<ThinnedAssociationBranches>::const_iterator ThinnedAssociationsHelper::parentBegin(
      BranchID const& parent) const {
    ThinnedAssociationBranches target(parent, BranchID(), BranchID(), false);
    return std::lower_bound(vThinnedAssociationBranches_.begin(),
                            vThinnedAssociationBranches_.end(),
                            target,
                            [](ThinnedAssociationBranches const& x, ThinnedAssociationBranches const& y) {
                              return x.parent() < y.parent();
                            });
  }

  std::vector<ThinnedAssociationBranches>::const_iterator ThinnedAssociationsHelper::parentEnd(
      BranchID const& parent) const {
    ThinnedAssociationBranches target(parent, BranchID(), BranchID(), false);
    return std::upper_bound(vThinnedAssociationBranches_.begin(),
                            vThinnedAssociationBranches_.end(),
                            target,
                            [](ThinnedAssociationBranches const& x, ThinnedAssociationBranches const& y) {
                              return x.parent() < y.parent();
                            });
  }

  std::vector<ThinnedAssociationBranches>::const_iterator ThinnedAssociationsHelper::lower_bound(
      ThinnedAssociationBranches const& branches) const {
    return std::lower_bound(
        vThinnedAssociationBranches_.begin(),
        vThinnedAssociationBranches_.end(),
        branches,
        [](ThinnedAssociationBranches const& x, ThinnedAssociationBranches const& y) {
          return x.parent() < y.parent() ? true : y.parent() < x.parent() ? false : x.association() < y.association();
        });
  }

  void ThinnedAssociationsHelper::addAssociation(BranchID const& parent,
                                                 BranchID const& association,
                                                 BranchID const& thinned,
                                                 bool slimmed) {
    addAssociation(ThinnedAssociationBranches(parent, association, thinned, slimmed));
  }

  void ThinnedAssociationsHelper::addAssociation(ThinnedAssociationBranches const& branches) {
    vThinnedAssociationBranches_.insert(lower_bound(branches), branches);
    if (branches.isSlimmed()) {
      try {
        ensureSlimmingConstraints();
      } catch (edm::Exception& ex) {
        ex.addContext("Calling ThinnedAssociationsHelper::addAssociation()");
        ex.addAdditionalInfo(fmt::format("When adding a slimmed collection with BranchID {}", branches.thinned().id()));
        throw ex;
      }
    }
  }
}  // namespace edm

namespace {
  struct SlimmedCount {
    edm::BranchID parent;
    int slimmedChildrenCount;
  };

  int countSlimmingChildren(edm::ThinnedAssociationsHelper const& helper,
                            edm::BranchID const& parent,
                            std::vector<SlimmedCount> const& counts);
  void addSlimmingChildrenCount(edm::ThinnedAssociationsHelper const& helper,
                                edm::ThinnedAssociationBranches const& branches,
                                std::vector<SlimmedCount> const& counts,
                                int& slimmedCount) {
    int slimmingChildren = countSlimmingChildren(helper, branches.thinned(), counts);
    if (slimmingChildren > 1) {
      throw edm::Exception(edm::errors::LogicError)
          << "Encountered a parent collection with BranchID " << branches.thinned().id()
          << " that has more than one thinned children that are either themselves slimmed, or have further thinned "
             "children that are slimmed. This is not allowed, but this particular check should not fire (it should "
             "have been caught earlier). Please contact framework developers.";
    }

    if (slimmingChildren == 0 and branches.isSlimmed()) {
      ++slimmingChildren;
    }

    slimmedCount += slimmingChildren;
    if (slimmedCount > 1) {
      throw edm::Exception(edm::errors::LogicError)
          << "Encountered a parent collection with BranchID " << branches.parent().id()
          << " that has more than one thinned children that are either themselves slimmed, or have further thinned "
             "children that are slimmed. This is not allowed. In the thinning parentage tree, any parent may have "
             "slimmed collections in at most one path to any leaf thinned collections of that parent.";
    }
  }

  int countSlimmingChildren(edm::ThinnedAssociationsHelper const& helper,
                            edm::BranchID const& parent,
                            std::vector<SlimmedCount> const& counts) {
    auto begin = helper.parentBegin(parent);
    auto end = helper.parentEnd(parent);
    if (begin == end)
      return 0;

    // if already visited, can just return the count
    auto pos =
        std::lower_bound(counts.begin(), counts.end(), parent, [](SlimmedCount const& c, edm::BranchID const& b) {
          return c.parent < b;
        });
    if (pos != counts.end() && pos->parent == parent) {
      return pos->slimmedChildrenCount;
    }

    int slimmedCount = 0;
    for (auto iItem = begin; iItem != end; ++iItem) {
      addSlimmingChildrenCount(helper, *iItem, counts, slimmedCount);
    }
    return slimmedCount;
  }
}  // namespace

namespace edm {
  void ThinnedAssociationsHelper::ensureSlimmingConstraints() const {
    // ThinnedAssociationBranches defines an edge between a parent and
    // a thinned collection in the parentage tree of the thinned
    // collections. It is required that for a given parentage tree
    // there is at most one path from the root node to any leaf nodes
    // that has slimming edges.

    std::vector<::SlimmedCount> counts;
    BranchID prevParent;
    std::vector<SlimmedCount>::iterator currentCount;
    for (auto iItem = begin(), iEnd = end(); iItem != iEnd; ++iItem) {
      if (iItem->parent() == BranchID()) {
        continue;
      }
      if (iItem->parent() == prevParent) {
        addSlimmingChildrenCount(*this, *iItem, counts, currentCount->slimmedChildrenCount);
      } else {
        currentCount = std::lower_bound(
            counts.begin(), counts.end(), iItem->parent(), [](SlimmedCount const& c, BranchID const& b) {
              return c.parent < b;
            });
        // has the tree with iItem->parent() as root node already been counted?
        if (currentCount != counts.end() && currentCount->parent == iItem->parent()) {
          continue;
        }
        currentCount = counts.insert(currentCount, ::SlimmedCount{iItem->parent(), 0});
        addSlimmingChildrenCount(*this, *iItem, counts, currentCount->slimmedChildrenCount);
        prevParent = iItem->parent();
      }
    }
  }

  std::vector<std::pair<BranchID, ThinnedAssociationBranches const*>> ThinnedAssociationsHelper::associationToBranches()
      const {
    std::vector<std::pair<BranchID, ThinnedAssociationBranches const*>> temp;
    temp.reserve(vThinnedAssociationBranches_.size());
    for (auto const& item : vThinnedAssociationBranches_) {
      temp.push_back(std::make_pair(item.association(), &item));
    }
    std::sort(temp.begin(),
              temp.end(),
              [](std::pair<BranchID, ThinnedAssociationBranches const*> const& x,
                 std::pair<BranchID, ThinnedAssociationBranches const*> const& y) { return x.first < y.first; });
    return temp;
  }

  void ThinnedAssociationsHelper::selectAssociationProducts(
      std::vector<ProductDescription const*> const& associationDescriptions,
      std::set<BranchID> const& keptProductsInEvent,
      std::map<BranchID, bool>& keepAssociation) const {
    keepAssociation.clear();
    // Copy the elements in vThinnedAssociationBranches_ into a vector sorted on
    // the association BranchID so we can do searches on that BranchID faster.
    std::vector<std::pair<BranchID, ThinnedAssociationBranches const*>> assocToBranches = associationToBranches();

    for (auto association : associationDescriptions) {
      if (association
              ->isAlias()) {  // There is no reason to configure an association product with an EDAlias (ignore and drop them if they exist)
        keepAssociation.insert(std::make_pair(association->branchID(), false));
      } else {
        std::set<BranchID> branchesInRecursion;
        shouldKeepAssociation(
            association->branchID(), assocToBranches, branchesInRecursion, keptProductsInEvent, keepAssociation);
      }
    }
  }

  bool ThinnedAssociationsHelper::shouldKeepAssociation(
      BranchID const& association,
      std::vector<std::pair<BranchID, ThinnedAssociationBranches const*>> const& associationToBranches,
      std::set<BranchID>& branchesInRecursion,
      std::set<BranchID> const& keptProductsInEvent,
      std::map<BranchID, bool>& keepAssociation) const {
    // If we already decided to keep or drop this one, then
    // return the same decision.
    auto decision = keepAssociation.find(association);
    if (decision != keepAssociation.end()) {
      return decision->second;
    }

    // Be careful not to fall into an infinite loop because
    // of a circular recursion.
    if (!branchesInRecursion.insert(association).second) {
      return false;
    }

    // If the thinned collection is being kept then keep the association
    auto branches = std::lower_bound(
        associationToBranches.begin(),
        associationToBranches.end(),
        std::make_pair(association, static_cast<ThinnedAssociationBranches const*>(nullptr)),
        [](std::pair<BranchID, ThinnedAssociationBranches const*> const& x,
           std::pair<BranchID, ThinnedAssociationBranches const*> const& y) { return x.first < y.first; });
    // This should never happen
    if (branches == associationToBranches.end() || branches->first != association) {
      throw edm::Exception(errors::LogicError,
                           "ThinnedAssociationHelper::shouldKeepAssociation could not find branches information, "
                           "contact Framework developers");
    }
    BranchID const& thinnedCollection = branches->second->thinned();
    if (keptProductsInEvent.find(thinnedCollection) != keptProductsInEvent.end()) {
      keepAssociation.insert(std::make_pair(association, true));
      return true;
    }
    // otherwise loop over any associations where the thinned collection
    // is also a parent collection and recursively examine those to see
    // if their thinned collections are being kept.
    auto iterEnd = parentEnd(thinnedCollection);
    for (auto match = parentBegin(thinnedCollection); match != iterEnd; ++match) {
      if (shouldKeepAssociation(
              match->association(), associationToBranches, branchesInRecursion, keptProductsInEvent, keepAssociation)) {
        keepAssociation.insert(std::make_pair(association, true));
        return true;
      }
    }
    // drop the association
    keepAssociation.insert(std::make_pair(association, false));
    return false;
  }

  void ThinnedAssociationsHelper::requireMatch(ThinnedAssociationBranches const& input) const {
    bool foundMatch = false;
    for (auto entry = parentBegin(input.parent()), iEnd = parentEnd(input.parent()); entry != iEnd; ++entry) {
      if (entry->association() == input.association() && entry->thinned() == input.thinned()) {
        foundMatch = true;
        break;
      }
    }
    if (!foundMatch) {
      throw edm::Exception(
          errors::MismatchedInputFiles,
          "ThinnedAssociationHelper::requireMatch, Illegal attempt to merge files with different ThinnedAssociations");
    }
  }

  void ThinnedAssociationsHelper::updateFromPrimaryInput(ThinnedAssociationsHelper const& helper) {
    if (vThinnedAssociationBranches_.empty()) {
      vThinnedAssociationBranches_ = helper.data();
      return;
    }
    std::vector<ThinnedAssociationBranches> const& inputData = helper.data();
    for (auto const& inputEntry : inputData) {
      requireMatch(inputEntry);
    }
  }

  void ThinnedAssociationsHelper::updateFromSecondaryInput(ThinnedAssociationsHelper const& helper,
                                                           std::vector<BranchID> const& associationsFromSecondary) {
    if (associationsFromSecondary.empty())
      return;

    std::vector<std::pair<BranchID, ThinnedAssociationBranches const*>> assocToBranches =
        helper.associationToBranches();

    for (BranchID const& association : associationsFromSecondary) {
      auto branches = std::lower_bound(
          assocToBranches.begin(),
          assocToBranches.end(),
          std::make_pair(association, static_cast<ThinnedAssociationBranches const*>(nullptr)),
          [](std::pair<BranchID, ThinnedAssociationBranches const*> const& x,
             std::pair<BranchID, ThinnedAssociationBranches const*> const& y) { return x.first < y.first; });
      // This should never happen
      if (branches == assocToBranches.end() || branches->first != association) {
        throw edm::Exception(errors::LogicError,
                             "ThinnedAssociationHelper::initAssociationsFromSecondary could not find branches "
                             "information, contact Framework developers");
      }
      requireMatch(*(branches->second));
    }
  }

  void ThinnedAssociationsHelper::updateFromParentProcess(
      ThinnedAssociationsHelper const& parentThinnedAssociationsHelper,
      std::map<BranchID, bool> const& keepAssociation,
      std::map<BranchID::value_type, BranchID::value_type> const& droppedBranchIDToKeptBranchID) {
    clear();
    for (auto const& associationBranches : parentThinnedAssociationsHelper.data()) {
      auto keep = keepAssociation.find(associationBranches.association());
      if (keep != keepAssociation.end() && keep->second) {
        BranchID parent = associationBranches.parent();
        auto iter = droppedBranchIDToKeptBranchID.find(parent.id());
        if (iter != droppedBranchIDToKeptBranchID.end()) {
          parent = BranchID(iter->second);
        }
        BranchID thinned = associationBranches.thinned();
        iter = droppedBranchIDToKeptBranchID.find(thinned.id());
        if (iter != droppedBranchIDToKeptBranchID.end()) {
          thinned = BranchID(iter->second);
        }
        addAssociation(parent, associationBranches.association(), thinned, associationBranches.isSlimmed());
      }
    }
  }

  void ThinnedAssociationsHelper::initAssociationsFromSecondary(
      std::vector<BranchID> const& associationsFromSecondary, ThinnedAssociationsHelper const& fileAssociationsHelper) {
    if (associationsFromSecondary.empty())
      return;

    std::vector<std::pair<BranchID, ThinnedAssociationBranches const*>> assocToBranches =
        fileAssociationsHelper.associationToBranches();

    for (BranchID const& association : associationsFromSecondary) {
      auto branches = std::lower_bound(
          assocToBranches.begin(),
          assocToBranches.end(),
          std::make_pair(association, static_cast<ThinnedAssociationBranches const*>(nullptr)),
          [](std::pair<BranchID, ThinnedAssociationBranches const*> const& x,
             std::pair<BranchID, ThinnedAssociationBranches const*> const& y) { return x.first < y.first; });
      // This should never happen
      if (branches == assocToBranches.end() || branches->first != association) {
        throw edm::Exception(errors::LogicError,
                             "ThinnedAssociationHelper::initAssociationsFromSecondary could not find branches "
                             "information, contact Framework developers");
      }
      addAssociation(*(branches->second));
    }
  }
}  // namespace edm