Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-12-02 10:19:03

0001 // -*- C++ -*-
0002 #ifndef RIVET_RivetHandler_HH
0003 #define RIVET_RivetHandler_HH
0004 
0005 #include "Rivet/AnalysisLoader.hh"
0006 #include "Rivet/Particle.hh"
0007 #include "Rivet/ProjectionHandler.hh"
0008 #include "Rivet/Config/RivetCommon.hh"
0009 #include "Rivet/Tools/RivetYODA.hh"
0010 #include "Rivet/Tools/Utils.hh"
0011 #include "YODA/ReaderYODA.h"
0012 
0013 #include <fstream>
0014 #include <unordered_map>
0015 
0016 namespace Rivet {
0017 
0018 
0019   // Forward declaration and smart pointer for Analysis
0020   class Analysis;
0021   using AnaHandle = std::shared_ptr<Analysis>;
0022 
0023 
0024   /// @brief The key class for coordination of Analysis objects and the event loop
0025   ///
0026   /// A class which handles a number of analysis objects to be applied to
0027   /// generated events. An {@link Analysis}' AnalysisHandler is also responsible
0028   /// for handling the final writing-out of histograms.
0029   class AnalysisHandler {
0030 
0031     using TypeHandlePtr = std::shared_ptr<TypeBaseHandle>;
0032     using TypeRegister = std::unordered_map<string, TypeHandlePtr>;
0033     using TypeRegisterItr = typename TypeRegister::const_iterator;
0034 
0035   public:
0036 
0037     using Annotations = std::map<std::string, std::string>;
0038 
0039     /// Preferred / default constructor.
0040     AnalysisHandler();
0041 
0042     /// The copy constructor is deleted, so it can never be called.
0043     AnalysisHandler(const AnalysisHandler&) = delete;
0044 
0045     /// The assignment operator is deleted, so it can never be called.
0046     AnalysisHandler& operator=(const AnalysisHandler&) = delete;
0047 
0048     /// The destructor is not virtual, as this class should not be inherited from.
0049     ~AnalysisHandler();
0050 
0051 
0052     /// @name Run properties
0053     /// @{
0054 
0055     /// Get the number of events seen. Should only really be used by external
0056     /// steering code or analyses in the finalize phase.
0057     ///
0058     /// N.B. This only reports the count for the last collapsed event group
0059     /// and hence ignores any additional sub-events seen so far.
0060     size_t numEvents() const {
0061       const double N = _eventCounter.get()->persistent(defaultWeightIndex())->numEntries();
0062       return size_t(N + 0.5 - (N < 0)); // round to nearest integer
0063     }
0064 
0065     /// Get the effective number of events seen. Should only really be used by external
0066     /// steering code or analyses in the finalize phase.
0067     ///
0068     /// N.B. This only reports the count for the last collapsed event group
0069     /// and hence ignores any additional sub-events seen so far.
0070     double effNumEvents() const {
0071       if ((bool)_eventCounter) {
0072         return _eventCounter->effNumEntries();
0073       }
0074       return _eventCounter.get()->persistent(defaultWeightIndex())->effNumEntries();
0075     }
0076 
0077     /// @brief Access the sum of the event weights seen
0078     ///
0079     /// This is the weighted equivalent of the number of events. It should only
0080     /// be used by external steering code or analyses in the finalize phase.
0081     double sumW() const {
0082       if ((bool)_eventCounter) {
0083         return _eventCounter->sumW();
0084       }
0085       return _eventCounter.get()->persistent(defaultWeightIndex())->sumW();
0086     }
0087     /// Access to the sum of squared-weights
0088     double sumW2() const {
0089       if ((bool)_eventCounter) {
0090         return _eventCounter->sumW2();
0091       }
0092       return _eventCounter.get()->persistent(defaultWeightIndex())->sumW2();
0093     }
0094 
0095     /// @}
0096 
0097 
0098     /// @name Event weights
0099     /// @{
0100 
0101     /// Names of event weight categories
0102     const vector<string>& weightNames() const {
0103       return _weightNames;
0104     }
0105 
0106     /// Are any of the weights non-numeric?
0107     size_t numWeights() const {
0108       return _weightNames.size();
0109     }
0110 
0111     /// Are any of the weights non-numeric?
0112     bool haveNamedWeights() const;
0113 
0114     /// Set the weight names from a GenEvent
0115     void setWeightNames(const GenEvent& ge);
0116 
0117     /// Set the weight names from a vector<string>
0118     void setWeightNames(const vector<string>& weightNames);
0119 
0120     /// Get the index of the nominal weight-stream
0121     size_t defaultWeightIndex() const {
0122       return _rivetDefaultWeightIdx;
0123     }
0124 
0125     /// @brief Access the array of sum of the event weights seen
0126     vector<double> weightSumWs() const;
0127 
0128     /// Set the weight cap
0129     void setWeightCap(const double maxWeight) {
0130       _weightCap = maxWeight;
0131     }
0132 
0133     /// Set the name of the nominal weight stream
0134     void setNominalWeightName(const std::string& name) {
0135       _nominalWeightName = name;
0136     }
0137 
0138     /// Ignore all weight streams other than the nominal
0139     void skipMultiWeights(bool skip = false) {
0140       _skipMultiWeights = skip;
0141     }
0142 
0143     /// Specify weight-name patterns to accept
0144     void matchWeightNames(const std::string& patterns) {
0145       _matchWeightNames = patterns;
0146     }
0147 
0148     /// Specify weight-name patterns to reject
0149     void unmatchWeightNames(const std::string& patterns) {
0150       _unmatchWeightNames = patterns;
0151     }
0152 
0153     /// Set the relative width of the NLO smearing window.
0154     void setNLOSmearing(double frac) {
0155       _NLOSmearing = frac;
0156     }
0157 
0158     /// @}
0159 
0160 
0161     /// @name Cross-sections
0162     /// @{
0163 
0164     /// Get the cross-section known to the handler
0165     Estimate0DPtr crossSection() const {
0166       return _xs;
0167     }
0168 
0169     /// Set all cross-sections for the process being generated specifically (preferred)
0170     void setCrossSection(const vector<pair<double, double>>& xsecs, bool isUserSupplied = false);
0171 
0172     /// Set all cross-sections for the process being generated, based on nominal weight
0173     void setCrossSection(const pair<double, double>& xsec, bool isUserSupplied = false);
0174 
0175     /// Set the cross-section for the process being generated (alternative signature)
0176     void setCrossSection(double xsec, double xsecerr, bool isUserSupplied = false) {
0177       setCrossSection({xsec, xsecerr}, isUserSupplied);
0178     }
0179 
0180     /// Update the internal cross-section average when running over multiple files
0181     ///
0182     /// @note This method should only be called when switching HepMC file mid-run.
0183     void updateCrossSection();
0184 
0185     /// Toggle to signal a change in HepMC input file
0186     void notifyEndOfFile() {
0187       _isEndOfFile = true;
0188     }
0189 
0190     /// Get the nominal cross-section
0191     double nominalCrossSection() const;
0192 
0193     /// Get the nominal cross-section
0194     double nominalCrossSectionError() const;
0195 
0196     /// @}
0197 
0198 
0199     /// @name Beams
0200     /// @{
0201 
0202     /// Set the beam particles for this run
0203     AnalysisHandler& setRunBeams(const ParticlePair& beams);
0204 
0205     /// Get the beam particles for this run, usually determined from the first event
0206     const ParticlePair& runBeams() const {
0207       return _beams;
0208     }
0209 
0210     /// Get beam IDs for this run, usually determined from the first event
0211     PdgIdPair runBeamIDs() const;
0212 
0213     /// Get beam IDs for this run, usually determined from the first event
0214     pair<double, double> runBeamEnergies() const;
0215 
0216     /// Get energy for this run, usually determined from the first event
0217     double runSqrtS() const;
0218 
0219     /// Option to disable analysis-compatibility checks
0220     void setCheckBeams(bool check = true) {
0221       _checkBeams = check;
0222     }
0223 
0224     /// Option to disable run-consistency checks
0225     // void setCheckConsistency(bool check=true) { _checkConsistency = check; }
0226     // Check event consistency with the run, usually determined from the first event
0227     // bool consistentWithRun(Event& event) {
0228 
0229     /// @}
0230 
0231 
0232     /// @name Run-based annotations
0233     /// @{
0234 
0235     // Get all the annotation names
0236     std::vector<std::string> annotations() const {
0237       return _beaminfo->annotations();
0238     }
0239 
0240     /// Check if an annotation is defined
0241     bool hasAnnotation(const std::string& name) const {
0242       return _beaminfo->hasAnnotation(name);
0243     }
0244 
0245     /// Get an annotation by name (as a string)
0246     const std::string& annotation(const std::string& name) const {
0247       return _beaminfo->annotation(name);
0248     }
0249 
0250     /// Get an annotation by name (as a string) with a default in case the annotation is not found
0251     const std::string& annotation(const std::string& name, const std::string& defaultreturn) const {
0252       return _beaminfo->annotation(name, defaultreturn);
0253     }
0254 
0255     /// @brief Get an annotation by name (copied to another type)
0256     ///
0257     /// @note Templated on return type
0258     template <typename T>
0259     const T annotation(const std::string& name) const {
0260       return _beaminfo->annotation<T>(name);
0261     }
0262 
0263     /// @brief Get an annotation by name (copied to another type) with a default in case the annotation is not found
0264     ///
0265     /// @note Templated on return type
0266     template <typename T>
0267     const T annotation(const std::string& name, T&& defaultreturn) const {
0268       return _beaminfo->annotation<T>(name, std::forward<T>(defaultreturn));
0269     }
0270 
0271     /// @brief Add or set an annotation by name (templated for remaining types)
0272     ///
0273     /// @note Templated on arg type, but stored as a string.
0274     template <typename T>
0275     void setAnnotation(const std::string& name, T&& value) {
0276       _beaminfo->setAnnotation<T>(name, std::forward<T>(value));
0277     }
0278 
0279 
0280     /// Set all annotations at once
0281     void setAnnotations(const Annotations& anns) {
0282       _beaminfo->setAnnotations(anns);
0283     }
0284 
0285     /// Delete an annotation by name
0286     void rmAnnotation(const std::string& name) {
0287       _beaminfo->rmAnnotation(name);
0288     }
0289 
0290 
0291     /// Delete an annotation by name
0292     void clearAnnotations() {
0293       _beaminfo->clearAnnotations();
0294     }
0295 
0296     /// @}
0297 
0298 
0299     /// @name AO type handling
0300     /// @{
0301 
0302     /// Register an AO type handle into type map and YODA reader
0303     template <typename T>
0304     void registerType() {
0305       const std::string name = T().type();
0306       const TypeRegisterItr& res = _register.find(name);
0307       if (res == _register.end()) {
0308         _register[name] = make_shared<TypeHandle<T>>();
0309       }
0310       _reader.registerType<T>(); // also let YODA know
0311     }
0312 
0313     /// If @a dst is the same subclass as @a src, copy the contents of
0314     /// @a src into @a dst and return true. Otherwise return false.
0315     bool copyAO(YODA::AnalysisObjectPtr src, YODA::AnalysisObjectPtr dst, const double scale = 1.0);
0316 
0317     /// If @a dst is the same subclass as @a src, scale the contents of @a src with
0318     /// @a scale and add it to @a dst and return true. Otherwise return false.
0319     bool addAO(YODA::AnalysisObjectPtr src, YODA::AnalysisObjectPtr& dst, const double scale);
0320 
0321     /// @}
0322 
0323 
0324     /// @name Analysis handling
0325     /// @{
0326 
0327     /// Get a list of the currently registered analyses' names.
0328     std::vector<std::string> analysisNames() const;
0329 
0330     /// Get a list of the official analysis names for this release.
0331     std::vector<std::string> stdAnalysisNames() const;
0332 
0333     /// Get the collection of currently registered analyses.
0334     const std::map<std::string, AnaHandle>& analysesMap() const {
0335       return _analyses;
0336     }
0337 
0338     /// Get the collection of currently registered analyses.
0339     std::vector<AnaHandle> analyses() const {
0340       std::vector<AnaHandle> rtn;
0341       rtn.reserve(_analyses.size());
0342       for (const auto& apair : _analyses) rtn.push_back(apair.second);
0343       return rtn;
0344     }
0345 
0346     /// Get a registered analysis by name.
0347     AnaHandle analysis(const std::string& analysisname) {
0348       if (_analyses.find(analysisname) == _analyses.end())
0349         throw LookupError("No analysis named '" + analysisname + "' registered in AnalysisHandler");
0350       try {
0351         return _analyses[analysisname];
0352       }
0353       catch (...) {
0354         throw LookupError("No analysis named '" + analysisname + "' registered in AnalysisHandler");
0355       }
0356     }
0357 
0358     /// Add an analysis to the run list by object
0359     AnalysisHandler& addAnalysis(Analysis* analysis);
0360 
0361     /// @brief Add an analysis to the run list using its name.
0362     ///
0363     /// The actual Analysis to be used will be obtained via
0364     /// AnalysisLoader::getAnalysis(string).  If no matching analysis is found,
0365     /// no analysis is added (i.e. the null pointer is checked and discarded.
0366     AnalysisHandler& addAnalysis(const std::string& analysisname);
0367 
0368     /// @brief Add an analysis with a map of analysis options.
0369     ///
0370     /// @todo Either provide a super-complicated vector<map> or similar to addAnalyses, or deprecate
0371     AnalysisHandler& addAnalysis(const std::string& analysisname, std::map<string, string> pars);
0372 
0373     /// @brief Add analyses to the run list using their names.
0374     ///
0375     /// The actual {@link Analysis}' to be used will be obtained via
0376     /// AnalysisHandler::addAnalysis(string), which in turn uses
0377     /// AnalysisLoader::getAnalysis(string). If no matching analysis is found
0378     /// for a given name, no analysis is added, but also no error is thrown.
0379     AnalysisHandler& addAnalyses(const std::vector<std::string>& analysisnames);
0380 
0381 
0382     /// Remove an analysis from the run list using its name.
0383     AnalysisHandler& removeAnalysis(const std::string& analysisname);
0384 
0385     /// Remove analyses from the run list using their names.
0386     AnalysisHandler& removeAnalyses(const std::vector<std::string>& analysisnames);
0387 
0388     /// @}
0389 
0390 
0391     /// @name Main init/execute/finalise
0392     /// @{
0393 
0394     /// Initialize a run, with the run beams taken from the example event
0395     void init(const GenEvent& event);
0396 
0397     /// @brief Analyze the given @a event by reference
0398     ///
0399     /// This function will call the AnalysisBase::analyze() function of all
0400     /// included analysis objects.
0401     ///
0402     /// @note Despite the event being passed as const, its units etc. may be changed, hence non-const.
0403     void analyze(GenEvent& event);
0404 
0405     /// @brief Analyze the given @a event by pointer
0406     ///
0407     /// This function will call the AnalysisBase::analyze() function of all
0408     /// included analysis objects, after checking the event pointer validity.
0409     void analyze(GenEvent* event);
0410 
0411     /// Finalize a run. This function calls the AnalysisBase::finalize()
0412     /// functions of all included analysis objects.
0413     void finalize();
0414 
0415     /// @}
0416 
0417 
0418     /// @name Histogram / data object access
0419     /// @{
0420 
0421     /// After all subevents in an event group have been processed, push
0422     /// all histo fills to the relevant histograms.
0423     void collapseEventGroup();
0424 
0425     /// @brief Read analysis plots into the histo collection from the given stream
0426     ///
0427     /// Use the @a fmt flag to specify the YODA output format (yoda, yoda.gz, yoda.h5, ...)
0428     void readData(std::istream& istr, const string& fmt, bool preload = true);
0429 
0430     /// Read analysis plots into the histo collection (via addData) from the named file.
0431     void readData(const std::string& filename, bool preload = true);
0432 
0433     /// Get all YODA analysis objects (across all weights, optionally including RAW)
0434     ///
0435     /// @note We'll live with the mixed-case "Yoda" here, since the consistent all-caps would be worse!
0436     vector<YODA::AnalysisObjectPtr> getYodaAOs(const bool includeraw = false,
0437                                                const bool mkinert = true) const;
0438 
0439     /// Get all raw YODA analysis objects (across all weights)
0440     vector<YODA::AnalysisObjectPtr> getRawAOs() const;
0441 
0442     /// Get all raw YODA analysis object paths (across all weights)
0443     vector<std::string> getRawAOPaths() const;
0444 
0445     /// Get a pointer to a preloaded yoda object with the given path,
0446     /// or null if path is not found.
0447     const YODA::AnalysisObjectPtr getPreload(const string& path) const {
0448       auto it = _preloads.find(path);
0449       if (it == _preloads.end()) return nullptr;
0450       return it->second;
0451     }
0452 
0453     /// @brief Write all analyses' plots (via getData) to the given stream.
0454     ///
0455     /// Use the @a fmt flag to specify the YODA output format (yoda, yoda.gz, yoda.h5, ...)
0456     void writeData(std::ostream& ostr, const string& fmt) const;
0457 
0458     /// Write all analyses' plots (via getData) to the named file.
0459     void writeData(const string& filename) const;
0460 
0461     /// @brief Configure the AnalysisObject dump rate and destination.
0462     ///
0463     /// Tell Rivet to dump intermediate result to a file named @a
0464     /// dumpfile every @a period'th event. If @a period is not positive,
0465     /// no periodic finalization will be done.
0466     void setFinalizePeriod(const string& dumpfile, int period) {
0467       _dumpPeriod = period;
0468       _dumpFile = dumpfile;
0469     }
0470     /// @brief Configure the AnalysisObject dump rate and destination.
0471     void setNoFinalizePeriod() {
0472       setFinalizePeriod("DUMMY", -1);
0473     }
0474 
0475     /// @brief Set filename of the bootstrap file
0476     void setBootstrapFilename(const string& filename) {
0477       _bootstrapfilename = filename;
0478     }
0479 
0480     /// Return a vector of (AO path, AO numBins) pairs to decode the fills layout
0481     vector<pair<string, size_t>> fillLayout() const;
0482 
0483     /// Return a vector of the binary fill outcome (was/wasn't filled) at each fill position
0484     vector<bool> fillOutcomes() const;
0485 
0486     /// Return a vector of the fill fraction at each fill position
0487     vector<double> fillFractions() const;
0488 
0489     /// @brief Merge the vector of YODA files, using the cross-section and weight information provided in each.
0490     ///
0491     /// Each file in @a aofiles is assumed to have been produced by Rivet. By
0492     /// default the files are assumed to contain different processes (or the
0493     /// same processs but mutually exclusive cuts), but if @a equiv if true, the
0494     /// files are assumed to contain output of completely equivalent (but
0495     /// statistically independent) Rivet runs. The corresponding analyses will
0496     /// be loaded and their analysis objects will be filled with the merged
0497     /// result. finalize() will be run on each relevant analysis. The resulting
0498     /// YODA file can then be written out by writeData().
0499     ///
0500     /// If @a delopts is non-empty, it is assumed to contain names of different
0501     /// options to be merged into the same analysis objects.
0502     ///
0503 
0504     void mergeYODAs(const vector<string>& aofiles,
0505                     const vector<string>& delopts = vector<string>(),
0506                     const vector<string>& addopts = vector<string>(),
0507                     const vector<string>& matches = vector<string>(),
0508                     const vector<string>& unmatches = vector<string>(),
0509                     const bool equiv = false,
0510                     const bool reentrantOnly = true,
0511                     const bool checkbeams = true);
0512 
0513     /// A method to merge another AnalysisHandler into the current one
0514     void merge(AnalysisHandler& other);
0515 
0516     /// @brief A method to prepare a re-entrant run for a given set
0517     /// of AO paths and serialized AO data
0518     ///
0519     /// The @a unscale parameter multiplies fillable objects with sumW/xsec to counteract
0520     /// the cross-section scaling in finalize() when merging different processes (non-equiv)
0521     void loadAOs(const vector<string>& aoPaths, const vector<double>& aoData);
0522 
0523     /// @}
0524 
0525     /// @name MPI (de-)serialisation
0526     ///@{
0527 
0528     vector<double> serializeContent(bool fixed_length = false) {
0529       if (!_initialised) throw Error("AnalysisHandler has not been initialised!");
0530 
0531       collapseEventGroup();
0532 
0533       // Loop over raw AOs and work out the size of the content data
0534       const vector<YODA::AnalysisObjectPtr> raos = getRawAOs();
0535       size_t total = 0;
0536       for (size_t i = 0; i < raos.size(); ++i) {
0537         total += raos[i]->lengthContent(fixed_length) + 1;
0538       }
0539       total += _beaminfo->numBins() + 1;
0540 
0541       // Loop over raw AOs and retrieve the content data
0542       std::vector<double> data; // serialized data vector
0543       data.reserve(total);      // pre-allocate enough memory
0544       // Add beam IDs
0545       data.push_back(_beaminfo->numBins());
0546       for (const string& beamID : _beaminfo->xEdges()) {
0547         data.push_back(_beamInfoLabelToID(beamID));
0548       }
0549       // Add raw YODA AO content
0550       for (size_t i = 0; i < raos.size(); ++i) {
0551         vector<double> tmp = raos[i]->serializeContent(fixed_length);
0552         data.push_back(tmp.size()); // length of the AO
0553         data.insert(std::end(data), std::make_move_iterator(std::begin(tmp)),
0554                     std::make_move_iterator(std::end(tmp)));
0555       }
0556       return data;
0557     }
0558 
0559     void deserializeContent(const vector<double>& data, size_t nprocs = 0) {
0560       if (!_initialised) throw Error("AnalysisHandler has not been initialised!");
0561 
0562       collapseEventGroup();
0563 
0564       // get Rivet AOs for access to raw AO pointers
0565       vector<MultiplexAOPtr> raos = getRivetAOs();
0566 
0567 
0568       // beam info first
0569       size_t iAO = 0, iW = 0, nBeams = data[0], offset = 1;
0570       if (nprocs) nBeams /= nprocs;
0571       const auto itr = data.cbegin();
0572       // set beam IDs
0573       vector<int> edges{itr + offset, itr + offset + nBeams};
0574       vector<string> labels;
0575       labels.reserve(edges.size());
0576       size_t id = 0;
0577       for (int edge : edges) {
0578         if (nprocs >= 2) edge /= nprocs;
0579         labels.push_back(_mkBeamInfoLabel(++id, edge));
0580       }
0581 
0582       _beaminfo = make_shared<YODA::BinnedEstimate<string>>(labels, "/TMP/_BEAMPZ");
0583       offset += nBeams;
0584       // set beam momenta
0585       size_t beamLen = *(itr + offset);
0586       ++offset;
0587       if (nprocs) beamLen /= nprocs;
0588       std::vector<double> energies{itr + offset, itr + offset + beamLen};
0589       if (nprocs >= 2) {
0590         for (double& e : energies) {
0591           e /= nprocs;
0592         }
0593       }
0594       _beaminfo->deserializeContent(energies);
0595       for (auto& b : _beaminfo->bins(true)) b.rmErrs();
0596       offset += beamLen;
0597 
0598       // then the multiweighted AOs
0599       while (offset < data.size()) {
0600         if (iW < numWeights())
0601           raos[iAO].get()->setActiveWeightIdx(iW);
0602         else {
0603           raos[iAO].get()->unsetActiveWeight();
0604           iW = 0;
0605           ++iAO; // move on to next AO
0606           raos[iAO].get()->setActiveWeightIdx(iW);
0607         }
0608 
0609         // obtain content length and set content iterators
0610         size_t aoLen = *(itr + offset);
0611         ++offset;
0612         if (nprocs) aoLen /= nprocs;
0613         auto first = itr + offset;
0614         auto last = first + aoLen;
0615         // load data into AO
0616         raos[iAO].get()->activeAO()->deserializeContent(std::vector<double>{first, last});
0617 
0618         ++iW;
0619         offset += aoLen; // increment offset
0620       }
0621       raos[iAO].get()->unsetActiveWeight();
0622       // Reset cross-section bookkeeping
0623       _ntrials = 0.0;
0624       _fileCounter = CounterPtr(weightNames(), Counter("_FILECOUNT"));
0625       _xserr = CounterPtr(weightNames(), Counter("XSECERR"));
0626       if (nprocs >= 2) {
0627         for (size_t iW = 0; iW < numWeights(); ++iW) {
0628           *_fileCounter.get()->persistent(iW) = *_eventCounter.get()->persistent(iW);
0629           _xs.get()->persistent(iW)->scale(1.0 / nprocs);
0630         }
0631       }
0632     }
0633 
0634     /// @}
0635 
0636 
0637     /// @name Processing stage
0638     /// @{
0639 
0640     /// Indicate which Rivet stage we're in.
0641     /// At the moment, only INIT is used to enable booking.
0642     enum class Stage { OTHER, INIT, FINALIZE };
0643 
0644     /// Return the current processing stage.
0645     Stage stage() const {
0646       return _stage;
0647     }
0648 
0649     /// @}
0650 
0651   private:
0652 
0653     /// @name Internal helper functions
0654     /// @{
0655 
0656     /// Get a logger object.
0657     Log& getLog() const;
0658 
0659     /// Get all multi-weight Rivet analysis object wrappers.
0660     vector<MultiplexAOPtr> getRivetAOs() const;
0661 
0662     /// Helper function to strip specific options from data object paths.
0663     void stripOptions(YODA::AnalysisObjectPtr ao, const vector<string>& delopts) const;
0664 
0665     /// @brief Merge the AO map @a newaos into @a allaos
0666     void mergeAOS(map<string, YODA::AnalysisObjectPtr>& allaos,
0667                   const map<string, YODA::AnalysisObjectPtr>& newaos,
0668                   map<string, std::array<double, 4>>& allxsecs,
0669                   const vector<string>& delopts = vector<string>(),
0670                   const vector<string>& optAnas = vector<string>(),
0671                   const vector<string>& optKeys = vector<string>(),
0672                   const vector<string>& optVals = vector<string>(),
0673                   const bool equiv = false,
0674                   const bool overwrite_xsec = false,
0675                   const double user_xsec = 1.0);
0676 
0677 
0678     /// @brief A method to prepare a re-entrant run for a given set of analysis objects
0679     ///
0680     /// The @a unscale parameter multiplies fillable objects with sumW/xsec to counteract
0681     /// the cross-section scaling in finalize() when merging different processes (non-equiv)
0682     void loadAOs(const map<string, YODA::AnalysisObjectPtr>& allAOs,
0683                  const bool unscale = false,
0684                  const bool reentrantOnly = true);
0685 
0686     /// @brief A method to set the internal _beaminfo object from a pair of beams
0687     void _setRunBeamInfo(const ParticlePair& beams);
0688 
0689     /// Construct beaminfo label from ID
0690     string _mkBeamInfoLabel(size_t n, PdgId id) {
0691       return "BEAM" + std::to_string(n) + "(" + std::to_string(id) + ")";
0692     }
0693 
0694     /// Retrieve ID from beaminfo label
0695     PdgId _beamInfoLabelToID(const string& label) {
0696       size_t pos = label.find("(");
0697       string beamID = label.substr(pos + 1, label.size() - pos - 2);
0698       return std::stoi(beamID);
0699     }
0700 
0701 
0702     /// @}
0703 
0704 
0705   private:
0706 
0707     /// Current handler processing stage.
0708     Stage _stage = Stage::OTHER;
0709 
0710     /// The collection of Analysis objects to be used.
0711     std::map<std::string, AnaHandle> _analyses;
0712 
0713     /// A vector of pre-loaded object which do not have a valid Analysis plugged in.
0714     ///
0715     /// @todo Rename to _preloadedAOs for consistency
0716     map<string, YODA::AnalysisObjectPtr> _preloads;
0717 
0718     /// A vector containing copies of analysis objects after finalize() has been run.
0719     vector<YODA::AnalysisObjectPtr> _finalizedAOs;
0720 
0721     /// Loads a default set of YODA AO types into the TypeHandleMap
0722     template <typename... Args>
0723     void registerDefaultTypes();
0724 
0725     /// The TypeRegister of all registered types
0726     TypeRegister _register;
0727 
0728     /// A reference to the ReaderYODA singleton
0729     YODA::Reader& _reader = YODA::ReaderYODA::create();
0730 
0731 
0732     /// @name Run properties
0733     /// @{
0734 
0735     /// Weight names
0736     std::vector<std::string> _weightNames;
0737     std::vector<std::valarray<double>> _subEventWeights;
0738     //size_t _numWeightTypes; // always == WeightVector.size()
0739 
0740     /// Weight indices
0741     std::vector<size_t> _weightIndices;
0742 
0743     /// Event counter
0744     CounterPtr _eventCounter;
0745 
0746     /// Cross-section known to AH
0747     Estimate0DPtr _xs;
0748 
0749     /// Running average of the cross-section uncertainties
0750     CounterPtr _xserr;
0751 
0752     /// Beam info known to AH
0753     YODA::BinnedEstimatePtr<string> _beaminfo;
0754 
0755     /// Total number of trials
0756     double _ntrials;
0757 
0758     /// Total number of entries of the current HepMC file
0759     CounterPtr _fileCounter;
0760 
0761     /// Toggle for multi-file runs
0762     bool _isEndOfFile;
0763 
0764     /// Toggle for subevent warning
0765     bool _subeventWarning;
0766 
0767     /// Nominal cross-section
0768     std::pair<double, double> _userxs;
0769 
0770     /// Beams used by this run.
0771     ParticlePair _beams;
0772 
0773     /// Flag to check if init has been called
0774     bool _initialised;
0775 
0776     /// Flag whether input event beams should be ignored in compatibility check
0777     bool _checkBeams{true};
0778 
0779     /// @brief Flag whether every input event should be treated as independent
0780     ///
0781     /// @note Setting to true makes Rivet _not_ treat repeated event numbers as indicating correlated event groups.
0782     bool _ignoreEventGroups{false};
0783 
0784     /// Flag to check if multiweights should be ignored
0785     bool _skipMultiWeights{false};
0786 
0787     /// String of weight names (or regex) to select multiweights
0788     std::string _matchWeightNames;
0789 
0790     /// String of weight names (or regex) to veto multiweights
0791     std::string _unmatchWeightNames;
0792 
0793     /// String giving the nominal weight name
0794     std::string _nominalWeightName;
0795 
0796     /// weight cap value
0797     double _weightCap;
0798 
0799     /// The relative width of the NLO smearing window.
0800     ///
0801     /// @todo Improve & standardise name
0802     double _NLOSmearing;
0803 
0804     /// Current event number
0805     int _eventNumber;
0806 
0807     /// The index in the (original) weight vector for the nominal weight stream
0808     size_t _defaultWeightIdx;
0809 
0810     /// The index in the (possibly pruned) weight vector for the nominal weight stream
0811     size_t _rivetDefaultWeightIdx;
0812 
0813     /// The index of the (possibly user-specified) intended default stream
0814     int _customDefaultWeightIdx;
0815 
0816     /// How often Rivet runs finalize() and writes the result to a YODA file.
0817     int _dumpPeriod;
0818 
0819     /// The name of a YODA file to which Rivet periodically dumps results.
0820     string _dumpFile;
0821 
0822     /// Flag to indicate periodic AO dumping is in progress
0823     bool _dumping;
0824 
0825     /// Flag to indicate bootstrap dumping is in progress
0826     ofstream _fbootstrap;
0827 
0828     /// Name of the file that the bootstrap dumping should be written to
0829     std::string _bootstrapfilename;
0830 
0831     /// Projection Handler
0832     ProjectionHandler _projHandler;
0833 
0834     /// @}
0835   };
0836 
0837 
0838 }
0839 
0840 #endif