Rat bindings

Rat is split into a suite of interdependent C++ libraries which define many classes and items to be used together to model magnets and compute 3D magnetic simulations.

Rat classes

Each Rat class is usually defined in their own translation units in each repository, for instance rat-common/include/log.hh defines the interface for the rat::cmn::Log class which is a utility to log information to console during calculations. Its implementation is done in rat-common/src/log.cpp.

Most Rat classes use type definitions to implement a factory pattern that returns a shared pointer to the underlying instance of class. This eases memory management for most users by avoiding to manually free memory afterwards.

log.hh example
namespace rat{namespace cmn{
    // shared pointer definition for log
    typedef std::shared_ptr<class Log> ShLogPr;

    // shared pointer definition for no-output log
    typedef std::shared_ptr<class NullLog> ShNullLogPr;

    // logging to the terminal
    class Log{
        // properties
        protected:
            ...

        // methods
        public:
            // logo options
            enum LogoType{RAT,NONE};

            // constructor
            explicit Log(
                LogoType logo = NONE,
                const std::shared_ptr<std::atomic_bool>& cancel_flag = nullptr);

            // factory
            static ShLogPr create(LogoType logo = NONE);

    ...

This factory pattern utilizes the create method to return the corresponding shared pointer to a Log instance. pyRat takes advantage of this workflow by using the shared pointer as the container type for pybind11. That way Python users can interact with Rat C++ libraries through the shared pointer.

Binding Rat classes

pyRat follows the Project-Rat structures by defining translation units for all classes to bind within each separated submodules: common, distmesh, etc…

pyRat also splits:

  • pyrat/include for bindings documentations and docstrings,

  • pyrat/src for bindings implementations and modules.

For instance the pyrat/src/common submodule for binding Rat-Common items has the following structure:

pyrat/src/common
├── common.cpp     ← Submodule binding
├── elements.cpp   ← Elements namespace bindings
├── extra.cpp      ← Extra namespace bindings
├── freecad.cpp    ← FreeCAD class bindings
├── gauss.cpp      ← Gauss class bindings
├── gmshfile.cpp   ← GmshFile class bindings
├── log.cpp        ← Log class bindings
├── ...

Every source includes utils/prelude.hh first: pybind11 with its STL, NumPy, filesystem and std::function casters, pyRat’s Armadillo casters and binding utilities. It is also the precompiled header of the build.

Binding a class then looks like this, here the PathCircle class of Rat-Models:

src/models/pathcircle.cpp
namespace pyrat { namespace mdl { namespace PathCircle {
// Bind
void bind(py::module_ &m) {

    // Rat shorthands
    using rat::mdl::PathCircle;
    using rat::mdl::Path;
    using rat::mdl::Transformations;
    using rat::mdl::ShPathCirclePr;

    // Class wrapper: methods first, then the property macros
    auto cls =
        py::class_<PathCircle, Path, Transformations, ShPathCirclePr>(m, "PathCircle", doc::item)

        // Base properties macros
        PYRAT_PROPERTY(PathCircle, transverse) //
        PYRAT_PROPERTY(PathCircle, offset) //
        PYRAT_PROPERTY(PathCircle, radius) //
        PYRAT_PROPERTY(PathCircle, element_size) //
        PYRAT_PROPERTY(PathCircle, num_sections);

    // Constructors
    utils::add_constructors(cls, py::overload_cast<>(&PathCircle::create), doc::create);
    utils::add_constructors(
        cls,
        py::overload_cast<const rat::fltp, const arma::uword, const rat::fltp, const rat::fltp>(
            &PathCircle::create),
        doc::create__plus,
        py::arg("radius"),
        py::arg("num_sections"),
        py::arg("element_size"),
        py::arg("offset") = 0);
}
}}}

The class wrapper is held by the Rat shared pointer type (ShPathCirclePr) and names its Rat base classes, so that Python sees the same hierarchy.

PYRAT_PROPERTY(cls, prop) binds the get_<prop> and set_<prop> methods and a <prop> property; PYRAT_PROPERTY_RO and the other macros of utils/macros.hh cover read-only, write-only and default-argument cases. Each line after a macro ends with //, so that clang-format does not nest what follows into it.

The utils::add_constructors function binds a Rat create factory in Python in two ways:

  • using the PathCircle.create() static method

  • using the PathCircle() constructor syntax.

Both ways are identical but the latter enables a more pythonic way of instantiating classes.

Important

pybind11 writes the type names of a signature when the method is bound: a class must be bound before the methods that take or return it, or its signature (and the stubs) name the C++ type, e.g. rat::mdl::MeshData. tests/rat/cmn/test_signatures.py fails when that happens.

The PathCircle class is then added to the models submodule among other classes, in src/models/models.cpp, the same way as in common.cpp:

src/common/common.cpp (excerpt)
void init(py::module_ &m) {

    // Common module doc
    m.doc() = doc::module_doc;

    // Bind Common module items
    Quadrilateral::bind(m); // Elements

    Node::bind(m);
    Log::bind(m);
    Gauss::bind(m);
    Serializer::bind(m);
    ...

    Extra::bind(m);         // Standalone, might use other items as types
    NewtonRaphson::bind(m); // Standalone, might use other items as types
}

which is itself added to the rat core module:

src/rat.cpp (excerpt)
// Python core module
PYBIND11_MODULE(rat, m) {

    // Module documentation
    m.doc() = pyrat::doc::module_doc;

    // Module metadata
    ...

    // Exceptions: RatError, IndexError/ValueError for C++ errors
    utils::register_exceptions(m);

// Common submodule
#ifdef PYRAT2_COMMON
    auto common = m.def_submodule(pyrat::cmn::doc::module_name);
    pyrat::cmn::init(common);
#endif // PYRAT2_COMMON

    ...

Each Rat submodule has its own binding of the same name, here common.cpp, which aggregates all bindings defined in other source files, exposing a cmn submodule which is later added to the top pyrat.rat submodule in the main pyrat/src/rat.cpp source file. Each is compiled only when its CMake option (PYRAT2_COMMON, …) is on.

For instance the PathCircle class should be accessed in Python with the pyrat.rat.mdl.PathCircle dot syntax.

Namespaces

pyRat makes use of C++ namespaces to have clean scopes.

The general structure is as follows:

  • pyrat::<module>::<item>::bind for the main bind function,

  • pyrat::<module>::<item>::doc::<name> for the docstring.

For instance:

  • pyrat::mdl::PathCircle::bind for the main bind function,

  • pyrat::mdl::PathCircle::doc::item for the class docstring,

  • pyrat::mdl::PathCircle::doc::create for the constructors documentation docstring,

  • pyrat::mdl::PathCircle::doc::offset for the offset property documentation docstring,

and many others.

This clarifies where items come from and generalizes imports and usages.