Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-12-01 10:05:25

0001 //------------------------------- -*- C++ -*- -------------------------------//
0002 // Copyright Celeritas contributors: see top-level COPYRIGHT file for details
0003 // SPDX-License-Identifier: (Apache-2.0 OR MIT)
0004 //---------------------------------------------------------------------------//
0005 //! \file corecel/cont/LabelIdMultiMap.hh
0006 //---------------------------------------------------------------------------//
0007 #pragma once
0008 
0009 #include <algorithm>
0010 #include <string>
0011 #include <unordered_map>
0012 #include <vector>
0013 
0014 #include "corecel/Assert.hh"
0015 #include "corecel/OpaqueId.hh"
0016 #include "corecel/io/Label.hh"
0017 
0018 #include "Range.hh"
0019 #include "Span.hh"
0020 
0021 namespace celeritas
0022 {
0023 //---------------------------------------------------------------------------//
0024 /*!
0025  * Map IDs to label+sublabel.
0026  *
0027  * Many Geant4 geometry definitions reuse a label for material or volume
0028  * definitions, and we need to track the unique name across multiple codes
0029  * (Geant4, VecGeom+GDML) to differentiate between materials or volumes. This
0030  * class maps a "label" to a name plus a range of "extensions", each of which
0031  * corresponds to a unique ID. It also provides the reverse mapping so that an
0032  * ID can retrieve the corresponding name/extension pair.
0033  *
0034  * There is no requirement that sublabels be ordered adjacent to each other:
0035  * the IDs corresponding to a label may be noncontiguous.
0036  *
0037  * Duplicate labels are allowed but will be added to a list of duplicate IDs
0038  * that can be warned about downstream. Empty labels will be ignored.
0039  *
0040  * If no sublabels or labels are available for a \c find_X call, an empty span
0041  * or "false" OpaqueId will be returned.
0042  *
0043  * The three kinds of \c find methods are named differently to avoid ambiguity:
0044  * - \c find_all returns the full set of IDs that match the given name;
0045  * - \c find_unique is a convenience accessor for locating a volume by name,
0046  *   but it only works if there are no duplicates; and
0047  * - \c find_exact looks for the full label, both name and extension.
0048  */
0049 template<class I>
0050 class LabelIdMultiMap
0051 {
0052     static_assert(is_opaque_id_v<I>, "invalid template type");
0053 
0054   public:
0055     //!@{
0056     //! \name Type aliases
0057     using IdT = I;
0058     using SpanConstIdT = Span<IdT const>;
0059     using VecLabel = std::vector<Label>;
0060     using size_type = typename IdT::size_type;
0061     //!@}
0062 
0063   public:
0064     // Empty constructor for delayed build
0065     LabelIdMultiMap() = default;
0066 
0067     // Construct from a vector of label+sublabel pairs, with a type string
0068     inline LabelIdMultiMap(std::string&& label, VecLabel&& keys);
0069 
0070     // Construct from a vector of label+sublabel pairs, with no type
0071     inline explicit LabelIdMultiMap(VecLabel&& keys);
0072 
0073     // Construct from a vector of items that each have a .label member
0074     template<class T>
0075     static inline LabelIdMultiMap from_labeled_items(
0076         std::string type_label, std::vector<T> const& items);
0077 
0078     // Access the range of IDs corresponding to a name
0079     inline SpanConstIdT find_all(std::string const& name) const;
0080 
0081     // Find an ID by name, throwing if not unique
0082     inline IdT find_unique(std::string const& name) const;
0083 
0084     // Access an ID by name/extension pair
0085     inline IdT find_exact(Label const& label) const;
0086 
0087     // Access the label+sublabel pair for an Id
0088     inline Label const& at(IdT id) const;
0089 
0090     //! Get the number of elements
0091     CELER_FORCEINLINE size_type size() const { return keys_.size(); }
0092 
0093     //! Whether no elements are present
0094     CELER_FORCEINLINE bool empty() const { return keys_.empty(); }
0095 
0096     // Whether this map is initialized
0097     inline explicit operator bool() const;
0098 
0099     //! Get duplicate labels to warn about
0100     SpanConstIdT duplicates() const { return make_span(duplicates_); }
0101 
0102   private:
0103     std::string type_label_;
0104     VecLabel keys_;
0105     std::vector<IdT> id_data_;
0106     std::vector<size_type> id_offsets_;
0107     std::vector<IdT> duplicates_;
0108     std::unordered_map<std::string, size_type> ids_;
0109 };
0110 
0111 //---------------------------------------------------------------------------//
0112 // INLINE DEFINITIONS
0113 //---------------------------------------------------------------------------//
0114 /*!
0115  * Construct from a vector of label+sublabel pairs, with no type.
0116  */
0117 template<class I>
0118 LabelIdMultiMap<I>::LabelIdMultiMap(VecLabel&& keys)
0119     : LabelIdMultiMap{{}, std::move(keys)}
0120 {
0121 }
0122 
0123 //---------------------------------------------------------------------------//
0124 /*!
0125  * Construct from a vector of items that each have a .label member.
0126  */
0127 template<class I>
0128 template<class T>
0129 LabelIdMultiMap<I> LabelIdMultiMap<I>::from_labeled_items(
0130     std::string type_label, std::vector<T> const& items)
0131 {
0132     VecLabel labels;
0133     labels.reserve(items.size());
0134     for (auto const& item : items)
0135     {
0136         labels.push_back(item.label);
0137     }
0138     return LabelIdMultiMap{std::move(type_label), std::move(labels)};
0139 }
0140 
0141 //---------------------------------------------------------------------------//
0142 /*!
0143  * Construct from a vector of label+sublabel pairs, with a type string.
0144  */
0145 template<class I>
0146 LabelIdMultiMap<I>::LabelIdMultiMap(std::string&& label, VecLabel&& keys)
0147     : type_label_{std::move(label)}, keys_{std::move(keys)}
0148 {
0149     if (keys_.empty())
0150     {
0151         // Sometimes we don't have any items to map. Rely on the
0152         // default-constructed values.
0153         return;
0154     }
0155 
0156     // Build list of IDs corresponding to each key
0157     id_data_.resize(keys_.size());
0158     for (auto idx : range<size_type>(keys_.size()))
0159     {
0160         id_data_[idx] = IdT{idx};
0161     }
0162     // Reorder consecutive ID data based on string lexicographic ordering
0163     std::sort(id_data_.begin(), id_data_.end(), [&keys = keys_](IdT a, IdT b) {
0164         return keys[a.unchecked_get()] < keys[b.unchecked_get()];
0165     });
0166 
0167     // Reserve space for groups
0168     id_offsets_.reserve(keys_.size() / 2 + 2);
0169     ids_.reserve(id_offsets_.capacity());
0170 
0171     // Search for when the label changes
0172     id_offsets_.push_back(0);
0173     ids_.insert({keys_[id_data_[0].unchecked_get()].name, 0});
0174     for (auto idx : range<size_type>(1, id_data_.size()))
0175     {
0176         Label const& prev = keys_[id_data_[idx - 1].unchecked_get()];
0177         Label const& cur = keys_[id_data_[idx].unchecked_get()];
0178         if (prev == cur && !cur.empty())
0179         {
0180             if (duplicates_.empty()
0181                 || keys_[duplicates_.back().unchecked_get()] != prev)
0182             {
0183                 // Push back previous entry if it's not already there
0184                 duplicates_.push_back(id_data_[idx - 1]);
0185             }
0186             duplicates_.push_back(id_data_[idx]);
0187         }
0188         if (prev.name != cur.name)
0189         {
0190             // Add start index of the new name
0191             size_type offset_idx = id_offsets_.size();
0192             id_offsets_.push_back(idx);
0193             auto insert_ok = ids_.insert({cur.name, offset_idx});
0194             CELER_ASSERT(insert_ok.second);
0195         }
0196     }
0197     id_offsets_.push_back(id_data_.size());
0198 
0199     CELER_ENSURE(keys_.size() == id_data_.size());
0200     CELER_ENSURE(id_offsets_.size() == ids_.size() + 1);
0201 }
0202 
0203 //---------------------------------------------------------------------------//
0204 /*!
0205  * Access the range of IDs corresponding to a label.
0206  *
0207  * This is useful for identifiers that may be repeated in a problem definition
0208  * with uniquifying "extensions", such as pointer addresses from Geant4.
0209  */
0210 template<class I>
0211 auto LabelIdMultiMap<I>::find_all(std::string const& name) const
0212     -> SpanConstIdT
0213 {
0214     auto iter = ids_.find(name);
0215     if (iter == ids_.end())
0216         return {};
0217 
0218     size_type offset_idx = iter->second;
0219     CELER_ASSERT(offset_idx + 1 < id_offsets_.size());
0220     size_type start = id_offsets_[offset_idx];
0221     size_type stop = id_offsets_[offset_idx + 1];
0222     CELER_ENSURE(start < stop && stop <= id_data_.size());
0223     return {id_data_.data() + start, stop - start};
0224 }
0225 
0226 //---------------------------------------------------------------------------//
0227 /*!
0228  * Find the ID corresponding to a label if exactly one exists.
0229  *
0230  * This will return an null ID if no labels match the given name, and it
0231  * will raise an exception if multiple labels do.
0232  */
0233 template<class I>
0234 auto LabelIdMultiMap<I>::find_unique(std::string const& name) const -> IdT
0235 {
0236     auto items = this->find_all(name);
0237     if (items.empty())
0238         return {};
0239     CELER_VALIDATE(items.size() == 1,
0240                    << type_label_ << " '" << name << "' is not unique");
0241     return items.front();
0242 }
0243 
0244 //---------------------------------------------------------------------------//
0245 /*!
0246  * Access an ID by exact label (name plus extension).
0247  *
0248  * This returns a \c false OpaqueId if no such label pair exists.
0249  */
0250 template<class I>
0251 auto LabelIdMultiMap<I>::find_exact(Label const& label_sub) const -> IdT
0252 {
0253     auto items = this->find_all(label_sub.name);
0254 
0255     // Just do a linear search on sublabels
0256     auto iter = std::find_if(
0257         items.begin(), items.end(), [&keys = keys_, &label_sub](IdT id) {
0258             CELER_EXPECT(id < keys.size());
0259             return keys[id.unchecked_get()].ext == label_sub.ext;
0260         });
0261     if (iter == items.end())
0262     {
0263         // No sublabel matches
0264         return {};
0265     }
0266     CELER_ENSURE(keys_[iter->unchecked_get()] == label_sub);
0267     return *iter;
0268 }
0269 
0270 //---------------------------------------------------------------------------//
0271 /*!
0272  * Access the label+sublabel pair for an Id.
0273  *
0274  * This raises an exception if the ID is outside of the valid range.
0275  */
0276 template<class I>
0277 Label const& LabelIdMultiMap<I>::at(IdT id) const
0278 {
0279     CELER_EXPECT(id < this->size());
0280     return keys_[id.unchecked_get()];
0281 }
0282 
0283 //---------------------------------------------------------------------------//
0284 /*!
0285  * Whether this map is initialized.
0286  */
0287 template<class I>
0288 CELER_FORCEINLINE LabelIdMultiMap<I>::operator bool() const
0289 {
0290     return !keys_.empty() || !type_label_.empty();
0291 }
0292 
0293 //---------------------------------------------------------------------------//
0294 }  // namespace celeritas