9 #include <boost/python/register_ptr_to_python.hpp>
10 #include <boost/python/class.hpp>
11 #include <boost/python/list.hpp>
12 #include <boost/python/docstring_options.hpp>
15 #include <framework/core/Path.h>
16 #include <framework/core/Module.h>
17 #include <framework/core/ModuleManager.h>
18 #include <framework/core/SubEventModule.h>
19 #include <framework/core/SwitchDataStoreModule.h>
20 #include <framework/core/PyObjConvUtils.h>
23 using namespace boost::python;
31 m_elements.push_back(module);
36 if (path.get() ==
this) {
37 B2FATAL(
"Attempting to add a path to itself!");
39 m_elements.push_back(path);
44 return m_elements.empty();
49 std::list<ModulePtr> modules;
50 for (
const std::shared_ptr<PathElement>& elem : m_elements) {
51 if (
dynamic_cast<Module*
>(elem.get()) !=
nullptr) {
53 modules.push_back(std::static_pointer_cast<Module>(elem));
56 const std::list<ModulePtr>& modulesInElem = elem->getModules();
57 modules.insert(modules.end(), modulesInElem.begin(), modulesInElem.end());
67 for (
const ModulePtr& module : getModules()) {
68 if (!unique or find(modList.begin(), modList.end(), module) == modList.end()) {
69 modList.push_back(module);
72 if (module->hasCondition()) {
73 for (
const auto& conditionPath : module->getAllConditionPaths()) {
75 if (conditionPath.get() ==
this) B2FATAL(
"Found recursion in conditional path");
76 const std::list<ModulePtr>& modulesInElem = conditionPath->buildModulePathList(unique);
77 modList.insert(modList.end(), modulesInElem.begin(), modulesInElem.end());
88 m_elements.assign(mlist.begin(), mlist.end());
109 static int dscount = 1;
110 ds_ID =
"DS " + std::to_string(dscount++);
117 switchStart->setName(
"SwitchDataStore ('' -> '" + ds_ID +
"')");
118 switchEnd->setName(
"SwitchDataStore ('' <- '" + ds_ID +
"')");
123 switchStart->setPropertyFlags(flag);
124 switchEnd->setPropertyFlags(flag);
127 addModule(switchStart);
128 addPath(independent_path);
129 addModule(switchEnd);
134 const std::list<ModulePtr>& modules = getModules();
136 auto sameTypeFunc = [moduleType](
const ModulePtr & m) ->
bool {
return m->getType() == moduleType; };
137 return std::find_if(modules.begin(), modules.end(), sameTypeFunc) != modules.end();
143 for (
const auto& elem : m_elements) {
144 const auto* m =
dynamic_cast<const Module*
>(elem.get());
145 if (m and m->getType() ==
"PyModule") {
147 path->addModule(std::static_pointer_cast<Module>(elem));
149 path->m_elements.push_back(elem->clone());
163 bool firstElem =
true;
164 for (
const std::shared_ptr<PathElement>& elem : m_elements) {
171 out += elem->getPathString();
173 return "[" + out +
"]";
181 boost::python::list _getModulesPython(
const Path* path)
183 boost::python::list returnList;
185 for (
const ModulePtr& module : path->getModules())
186 returnList.append(boost::python::object(
ModulePtr(module)));
194 docstring_options options(
true,
false,
false);
195 using bparg = boost::python::arg;
198 R
"(Implements a path consisting of Module and/or Path objects (arranged in a linear order).
200 .. seealso:: :func:`basf2.process`)")
203 .def(
"add_path", &
Path::addPath, args(
"path"), R
"(add_path(path)
205 Insert another path at the end of this one.
208 >>> path.add_module('A')
209 >>> path.add_path(otherPath)
210 >>> path.add_module('B')
212 would create a path [ A -> [ contents of otherPath ] -> B ].)
215 path (Path): path to add to this path)")
216 .def("modules", &_getModulesPython, R
"(modules()
218 Returns an ordered list of all modules in this path.)")
219 .def("for_each", &
Path::forEach, R
"(for_each(loop_object_name, array_name, path)
221 Similar to `add_path()`, this will
222 execute the given ``path`` at the current position, but in each event it will
223 execute it once for each object in the given StoreArray ``arrayName``. It will
224 create a StoreObject named ``loop_object_name`` of same type as array which will
225 point to each element in turn for each execution.
227 This has the effect of calling the ``event()`` methods of modules in ``path``
228 for each entry in ``arrayName``.
230 The main use case is to use it after using the `RestOfEventBuilder` on a
231 ``ParticeList``, where you can use this feature to perform actions on only a part
232 of the event for a given list of candidates:
234 >>> path.for_each('RestOfEvent', 'RestOfEvents', roe_path)
238 "for each ``RestOfEvent`` in the array of "RestOfEvents", execute ``roe_path``"
240 For example, if 'RestOfEvents' contains two elements then ``roe_path`` will be
241 executed twice and during the execution a StoreObjectPtr 'RestOfEvent' will be
242 available, which will point to the first element in the first execution, and
243 the second element in the second execution.
246 A working example of this `for_each` RestOfEvent is to build a veto against
247 photons from :math:`\pi^0\to\gamma\gamma`. It is described in `HowToVeto`.
249 .. note:: This feature is used by both the `FlavorTagger` and :ref:`FullEventInterpretation` algorithms.
251 Changes to existing arrays / objects will be available to all modules after the
252 `for_each()`, including those made to the loop object itself (it will simply modify
253 the i'th item in the array looped over.)
255 StoreArrays / StoreObjects (of event durability) *created* inside the loop will
256 be removed at the end of each iteration. So if you create a new particle list
257 inside a `for_each()` path execution the particle list will not exist for the
258 next iteration or after the `for_each()` is complete.
261 loop_object_name (str): The name of the object in the datastore during each execution
262 array_name (str): The name of the StoreArray to loop over where the i-th
263 element will be available as ``loop_object_name`` during the i-th execution
265 path (basf2.Path): The path to execute for each element in ``array_name``)",
266 args("loop_object_name",
"array_name",
"path"))
267 .def(
"do_while", &
Path::doWhile, R
"(do_while(path, condition='<1', max_iterations=10000)
269 Similar to `add_path()` this will execute a path at the current position but it
270 will repeat execution of this path as long as the return value of the last
271 module in the path fulfills the given ``condition``.
273 This is useful for event generation with special cuts like inclusive particle generation.
276 `Module.if_value` for an explanation of the condition expression.
279 path (basf2.Path): sub path to execute repeatedly
280 condition (str): condition on the return value of the last module in ``path``.
281 The execution will be repeated as long as this condition is fulfilled.
282 max_iterations (int): Maximum number of iterations per event. If this number is exceeded
283 the execution is aborted.
284 )", (bparg("path"), bparg(
"condition") =
"<1", bparg(
"max_iterations") = 10000))
286 .def(
"__contains__", &
Path::contains, R
"(Does this Path contain a module of the given type?
288 >>> path = basf2.Path()
289 >>> 'RootInput' in path
291 >>> path.add_module('RootInput')
292 >>> 'RootInput' in path
293 True)", args("moduleType"))
296 register_ptr_to_python<PathPtr>();
std::shared_ptr< Module > registerModule(const std::string &moduleName, std::string sharedLibPath="") noexcept(false)
Creates an instance of a module and registers it to the ModuleManager.
static bool allModulesHaveFlag(const std::list< std::shared_ptr< Module >> &list, unsigned int flag)
Returns true if and only if all modules in list have the given flag (or list is empty).
static ModuleManager & Instance()
Exception is thrown if the requested module could not be created by the ModuleManager.
@ c_ParallelProcessingCertified
This module can be run in parallel processing mode safely (All I/O must be done through the data stor...
Implements a path consisting of Module and/or Path objects.
void forEach(const std::string &loopObjectName, const std::string &arrayName, PathPtr path)
See 'pydoc3 basf2.Path'.
void doWhile(PathPtr path, const std::string &condition, unsigned int maxIterations)
See 'pydoc3 basf2.Path'.
std::list< std::shared_ptr< Module > > buildModulePathList(bool unique=true) const
Builds a list of all modules which could be executed during the data processing.
static void exposePythonAPI()
Exposes methods of the Path class to Python.
void putModules(const std::list< std::shared_ptr< Module > > &mlist)
Replaces all Modules and sub-Paths with the specified Module list.
void addPath(const PathPtr &path)
See 'pydoc3 basf2.Path'.
void addModule(const std::shared_ptr< Module > &module)
Adds a module to the path.
bool isEmpty() const
Returns true if this Path doesn't contain any elements.
std::shared_ptr< PathElement > clone() const override
Create an independent copy of this path, recreating all contained modules with the same parameters.
void addIndependentPath(const PathPtr &independent_path, std::string ds_ID, const boost::python::list &merge_back)
See 'pydoc3 basf2.Path'.
bool contains(const std::string &moduleType) const
Does this Path contain a module of the given type?
std::list< std::shared_ptr< Module > > getModules() const override
Returns a list of the modules in this path.
std::string getPathString() const override
return a string of the form [module a -> module b -> [another path]]
Framework-internal module that implements the functionality of Path::forEach() as well as Path::doWhi...
void initSubLoop(std::shared_ptr< Path > path, const std::string &condition, unsigned int maxIterations)
ised by Path::doWhile() to actually set parameters
void initSubEvent(const std::string &objectName, const std::string &loopOver, std::shared_ptr< Path > path)
used by Path::forEach() to actually set parameters.
Internal module used by Path.add_independent_path().
void init(const std::string &to, bool doCopy, const std::vector< std::string > &mergeBack)
setter for Path.
std::shared_ptr< Path > PathPtr
Defines a pointer to a path object as a boost shared pointer.
std::shared_ptr< Module > ModulePtr
Defines a pointer to a module object as a boost shared pointer.
std::list< ModulePtr > ModulePtrList
Defines a std::list of shared module pointers.
Scalar convertPythonObject(const boost::python::object &pyObject, Scalar)
Convert from Python to given type.
Abstract base class for different kinds of events.