cepgen is hosted by Hepforge, IPPP Durham
CepGen 1.2.5
Central exclusive processes event generator
Loading...
Searching...
No Matches
CardHandler.cpp
Go to the documentation of this file.
1/*
2 * CepGen: a central exclusive processes event generator
3 * Copyright (C) 2018-2024 Laurent Forthomme
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19// clang-format off
23// clang-format on
24
25#include <algorithm>
26
33#include "CepGen/Generator.h" // for library loading
41#include "CepGen/Physics/PDG.h"
44#include "CepGen/Utils/String.h"
47
48#define Py_DEBUG
49
50namespace cepgen {
51 namespace python {
53 class CardHandler final : public card::Handler {
54 public:
56 explicit CardHandler(const ParametersList& params)
57 : Handler(params), env_(new Environment(params_)), plist_(params_.operator[]<ParametersList>("parsed")) {}
58
59 CardHandler& parseFile(const std::string& file) override {
60 const auto filename = pythonPath(file);
61 env_->setProgramName(filename);
62 auto cfg = ObjectPtr::importModule(filename) /* new */;
63 if (!cfg)
64 throw PY_ERROR << "Failed to import the configuration card '" << filename << "'\n"
65 << " (parsed from '" << file << "').";
66 parseParameters(cfg);
67 parse();
68 return *this;
69 }
70 CardHandler& parseCommands(const std::vector<std::string>& str) override {
71 const std::string name = "Cards.Core";
72 env_->setProgramName(name);
73 auto cfg = ObjectPtr::defineModule(name, utils::merge(str, "\n")) /* new */;
74 if (!cfg)
75 throw PY_ERROR << "Failed to parse a configuration string:\n"
76 << std::string(80, '-') << "\n"
77 << str << "\n"
78 << std::string(80, '-');
79 parseParameters(cfg);
80 parse();
81 return *this;
82 }
83
85 auto desc = Handler::description();
86 desc.setDescription("Python 2/3 cards parser");
87 desc.add<int>("debugging", 0).setDescription("debugging level");
88 desc.add<int>("verbosity", 0).setDescription("verbosity level");
89 return desc;
90 }
91
92 private:
94 void parseParameters(const ObjectPtr& cfg) {
95 CG_ASSERT(cfg);
96 for (const auto& attr : cfg.attribute("__dir__")().vector<std::string>()) {
97 if (attr[0] == '_')
98 continue;
99 const auto obj = cfg.attribute(attr);
100 if (obj.is<ParametersList>())
101 plist_.set(attr, obj.value<ParametersList>());
102 else if (obj.isVector<ParametersList>())
103 plist_.set(attr, obj.vector<ParametersList>());
104 else if (obj.is<int>())
105 plist_.set(attr, obj.value<int>());
106 else if (obj.isVector<int>())
107 plist_.set(attr, obj.vector<int>());
108 else if (obj.is<double>())
109 plist_.set(attr, obj.value<double>());
110 else if (obj.isVector<double>()) {
111 if (obj.is<Limits>())
112 plist_.set(attr, obj.value<Limits>());
113 plist_.set(attr, obj.vector<double>());
114 } else if (obj.is<std::string>())
115 plist_.set(attr, obj.value<std::string>());
116 else if (obj.isVector<std::string>())
117 plist_.set(attr, obj.vector<std::string>());
118 else if (obj.isVector<Limits>())
119 plist_.set(attr, obj.vector<Limits>());
120 }
121 }
122 void parse() {
123 // logging module
124 auto logging = plist_.get<ParametersList>("logger");
125 utils::Logger::get().setLevel(logging.getAs<int, utils::Logger::Level>("level", utils::Logger::get().level()));
126 utils::Logger::get().setExtended(logging.get<bool>("extended", utils::Logger::get().extended()));
127 for (const auto& log_mod : logging.get<std::vector<std::string> >("enabledModules"))
128 utils::Logger::get().addExceptionRule(log_mod);
129
130 // external libraries
131 for (const auto& lib : plist_.get<std::vector<std::string> >("addons")) // additional libraries to load
132 loadLibrary(lib);
133
134 CG_DEBUG("python:CardHandler").log([](auto& log) {
135 log << "Initialised the Python cards parser.";
136 for (const auto& ln : info())
137 log << "\n\t" << ln;
138 });
139
140 // timekeeper definition (currently, does not parse the object, just check its presence)
141 if (!plist_.get<ParametersList>("timer").empty())
142 runParameters()->setTimeKeeper(new utils::TimeKeeper);
143
144 // general particles definition
145 if (const auto mcd_file = plist_.get<std::string>("mcdFile"); !mcd_file.empty())
147
148 // additional particles definition
149 const auto parts = plist_.get<ParametersList>("PDG");
150 for (const auto& k : parts.keys(true)) {
151 auto props = parts.get<ParametersList>(k);
152 if (props.has<int>("pdgid"))
153 props.set<pdgid_t>("pdgid", props.get<int>("pdgid"));
154 const ParticleProperties part(props);
155 if (part.mass <= 0. && part.width <= 0.) // skip aliases
156 continue;
157 if (!PDG::get().has(part.pdgid) || PDG::get()(part.pdgid) != part) {
158 CG_INFO("python:CardHandler:particles") << "Adding a new particle with PDG id=" << part.pdgid
159 << " and name \"" << part.name << "\" to the PDG dictionary.";
160 PDG::get().define(part);
161 }
162 }
163
164 // process definition
165 if (auto process = plist_.get<ParametersList>("process"); !process.empty()) {
166 auto& pkin = process.operator[]<ParametersList>("kinematics");
167 { // remove extra layer of 'processParameters' and move it to the main process parameters block
168 process += process.get<ParametersList>("processParameters");
169 process.erase("processParameters");
170 if (process.has<int>("mode")) { // move the kinematics mode from process to the main kinematics block
171 pkin.set("mode", (int)process.getAs<int, mode::Kinematics>("mode"));
172 process.erase("mode");
173 }
174 }
175 { // remove extra layers of 'inKinematics' and 'outKinematics' and move them to the main kinematics block
176 pkin += process.get<ParametersList>("inKinematics");
177 process.erase("inKinematics");
178 pkin += process.get<ParametersList>("outKinematics");
179 process.erase("outKinematics");
180 }
181 if (auto& pkgen = process.operator[]<ParametersList>("kinematicsGenerator"); pkgen.name().empty())
182 pkgen.setName(process.get<bool>("ktFactorised", true) ? "kt2to4" : "coll2to4");
183 runParameters()->setProcess(ProcessFactory::get().build(process));
184
185 for (const auto& tf : process.get<std::vector<ParametersList> >("tamingFunctions"))
186 runParameters()->addTamingFunction(FunctionalFactory::get().build("python", tf));
187 }
188
189 // generation parameters
190 runParameters()->integrator() += plist_.get<ParametersList>("integrator");
191 if (auto pgen = plist_.get<ParametersList>("generator"); !pgen.empty()) {
192 runParameters()->generation().setParameters(plist_.get<ParametersList>("generator"));
193 if (auto maxgen = pgen.get<int>("numEvents", -1); maxgen > 0)
195 }
196
197 // event modification algorithms / hadronisers
198 auto parse_evtmod_module = [&](const ParametersList& mod) {
199 runParameters()->addModifier(EventModifierFactory::get().build(mod));
200 auto h = runParameters()->eventModifiersSequence().rbegin()->get();
201 // split the configuration into a pre-initialisation and a post-initialisation of the module parts
202 h->readStrings(mod.get<std::vector<std::string> >("preConfiguration"));
203 h->initialise(*runParameters());
204 for (const auto& block : mod.get<std::vector<std::string> >("processConfiguration"))
205 h->readStrings(mod.get<std::vector<std::string> >(block));
206 };
207 if (const auto had = plist_.get<ParametersList>("hadroniser");
208 !had.empty()) // hadronisation algorithms (legacy)
209 parse_evtmod_module(had);
210 for (const auto& mod :
211 plist_.get<std::vector<ParametersList> >("eventSequence")) // event modification algorithms
212 parse_evtmod_module(mod);
213
214 // output modules
215 for (const auto& mod : plist_.get<std::vector<ParametersList> >("output"))
216 runParameters()->addEventExporter(EventExporterFactory::get().build(mod));
217 }
218 void write(const std::string& filename) const override {
219 ConfigWriter writer(ParametersList().set("filename", filename));
220 writer << *runParameters();
221 }
222 std::unique_ptr<Environment> env_;
223 ParametersList& plist_;
224 };
225 } // namespace python
226} // namespace cepgen
#define REGISTER_CARD_HANDLER(name, obj)
Add a cards handler definition to the list of handled parsers.
#define PY_ERROR
Definition Error.h:25
#define CG_ASSERT(assertion)
Definition Exception.h:62
#define CG_DEBUG(mod)
Definition Message.h:220
#define CG_INFO(mod)
Definition Message.h:216
Validity interval for a variable.
Definition Limits.h:28
const std::string & name() const
Module unique indexing name.
Definition NamedModule.h:42
void define(const ParticleProperties &)
Add a new particle definition to the library.
Definition PDG.cpp:60
static PDG & get()
Retrieve a unique instance of this particles info collection.
Definition PDG.cpp:41
A description object for parameters collection.
T get(const std::string &key, const T &def=default_arg< T >::get()) const
Get a parameter value.
ParametersList & set(const std::string &, const T &)
Set a parameter value Set a recast parameter value.
void setMaxGen(size_t max_gen)
Set the maximal number of events to generate.
void addModifier(std::unique_ptr< EventModifier >)
Add a new event modification algorithm to the sequence.
void setProcess(std::unique_ptr< proc::Process >)
Set a process configuration.
EventModifiersSequence & eventModifiersSequence()
List of event modification algos List of event modification algos.
ParametersList & integrator()
Integrator specific user-defined parameters.
void setTimeKeeper(utils::TimeKeeper *)
Initialise the timekeeper instance.
Generation & generation()
Event generation parameters.
ParametersList params_
Module parameters.
Definition Steerable.h:50
virtual void setParameters(const ParametersList &params) override
Set module parameters.
Base steering card module.
Definition Handler.h:31
const RunParameters * runParameters() const
Parsed runtime parameters.
Definition Handler.h:45
Handler(const ParametersList &)
Build a configuration from an external steering card.
Definition Handler.cpp:25
CepGen Python configuration cards reader/writer.
static ParametersDescription description()
CardHandler & parseFile(const std::string &file) override
Read configuration from steering card.
CardHandler & parseCommands(const std::vector< std::string > &str) override
Read configuration from command strings.
CardHandler(const ParametersList &params)
Read a standard configuration card.
Smart pointer to a Python object and its dereferencing operator.
Definition ObjectPtr.h:36
ObjectPtr attribute(const std::string &) const
Retrieve the attribute from a python object.
static ObjectPtr importModule(const std::string &)
Import a Python module in a new reference-counted Python object.
static ObjectPtr defineModule(const std::string &, const std::string &)
Define a Python module from a Python code in a new reference-counted Python object.
Level
Logging threshold for the output stream.
Definition Logger.h:44
static Logger & get(std::ostream *=nullptr)
Retrieve the running instance of the logger.
Definition Logger.cpp:31
bool extended() const
Also show extended information?
Definition Logger.h:54
void setLevel(Level level)
Set the logging threshold.
Definition Logger.h:52
Level level() const
Logging threshold.
Definition Logger.h:50
void setExtended(bool ext=true)
Set the extended information flag.
Definition Logger.h:56
static void parse(const std::string &path)
Parse an external MCD file and retrieve all particles definition.
Kinematics
Type of scattering.
Definition Modes.h:28
std::vector< std::wstring > info()
Definition Utils.cpp:42
std::string pythonPath(const std::string &file)
Translate a filename into a python-compatible path.
Definition Utils.cpp:29
std::string get(const std::string &var, const std::string &def)
Get an environment variable.
void set(const std::string &var, const std::string &value)
Set an environment variable.
std::vector< K > keys(const std::map< K, T > &coll)
Retrieve all keys from a map.
Definition Collections.h:33
std::string merge(const std::vector< T > &vec, const std::string &delim)
Merge a collection of a printable type in a single string.
Definition String.cpp:248
Common namespace for this Monte Carlo generator.
bool loadLibrary(const std::string &path, bool match)
Import a shared library in RTE Launch the initialisation procedure.
unsigned long long pdgid_t
Alias for the integer-like particle PDG id.