Exemplo n.º 1
0
void wrap_messaging(py::module &m) {
  py::module mMessaging = m.def_submodule("messaging");

  mMessaging.def("init_transport", &xmessaging::init_transport);
  mMessaging.def("stop_transport", &xmessaging::stop_transport);
  mMessaging.def("alloc_read_buffer", []() {
    xmessaging::alloc_read_buffer(BUFFER_LEN);
  });
  mMessaging.def("dealloc_read_buffer", []() {
    xmessaging::dealloc_read_buffer();
  });
  
  // this will change to a buffer object
  mMessaging.def("send_bytes", [](py::buffer pb) {
        py::buffer_info req = pb.request();
        xmessaging::queue((const char*)req.ptr, req.size);
      });
  mMessaging.def("update", []() -> bool {
    bool message_read = false;
    char *buffer;
    size_t buffer_len;
    xmessaging::update(message_read, buffer, buffer_len);
    if (message_read)
    {
      simulation::process_step(buffer, buffer_len);
    }
    return message_read;
  });
}
Exemplo n.º 2
0
void python_export_igl_tetgen(py::module &me) {

  py::module m = me.def_submodule(
    "tetgen", "Wrappers for libigl functions that use tetgen");

  #include "../../py_igl/copyleft/tetgen/py_tetrahedralize.cpp"

}
Exemplo n.º 3
0
void python_export_igl_png(py::module &me) {

  py::module m = me.def_submodule(
    "png", "Wrappers for libigl functions that use png");

  #include "../py_igl/png/py_readPNG.cpp"
  #include "../py_igl/png/py_writePNG.cpp"

}
Exemplo n.º 4
0
void python_export_igl_embree(py::module &me) {

  py::module m = me.def_submodule(
    "embree", "Wrappers for libigl functions that use embree");

  #include "../py_igl/embree/py_ambient_occlusion.cpp"
  #include "../py_igl/embree/py_reorient_facets_raycast.cpp"
  #include "../py_igl/embree/py_line_mesh_intersection.cpp"

}
Exemplo n.º 5
0
// World map is generally a point of danger
// A global static contains all of the tiles
// Python accesses those by reference, and is not necessarily aware of mutations to the global static map of tiles
void wrap_world_map(py::module &m)
{
  py::module mMap = m.def_submodule("map");

  mMap.def("get_map", &world_map::get_map, py::return_value_policy::reference);
  mMap.def("get_tile", &world_map::get_tile, py::return_value_policy::reference);
  mMap.def("tile_owner", &world_map::tile_owner);
  mMap.def("get_map_size", &world_map::get_map_size);
  mMap.def("save_file_fb", &world_map::save_file_fb);

  mMap.def("for_each_tile", [](py::function func) { 
    auto fp = [&func](const sf::Vector3i& coord, const Tile& tile) { func(coord, tile); };
    world_map::for_each_tile(fp);
  });
}
Exemplo n.º 6
0
void init_ex9(py::module &m) {
    py::module m_sub = m.def_submodule("submodule");
    m_sub.def("submodule_func", &submodule_func);

    py::class_<A>(m_sub, "A")
        .def(py::init<int>())
        .def("__repr__", &A::toString);

    py::class_<B>(m_sub, "B")
        .def(py::init<>())
        .def("get_a1", &B::get_a1, "Return the internal A 1", py::return_value_policy::reference_internal)
        .def("get_a2", &B::get_a2, "Return the internal A 2", py::return_value_policy::reference_internal)
        .def_readwrite("a1", &B::a1)  // def_readonly uses an internal reference return policy by default
        .def_readwrite("a2", &B::a2);

    m.attr("OD") = py::module::import("collections").attr("OrderedDict");
}
Exemplo n.º 7
0
void init_issues(py::module &m) {
    py::module m2 = m.def_submodule("issues");

#if !defined(_MSC_VER)
    // Visual Studio 2015 currently cannot compile this test
    // (see the comment in type_caster_base::make_copy_constructor)
    // #70 compilation issue if operator new is not public
    class NonConstructible { private: void *operator new(size_t bytes) throw(); };
    py::class_<NonConstructible>(m, "Foo");
    m2.def("getstmt", []() -> NonConstructible * { return nullptr; },
        py::return_value_policy::reference);
#endif

    // #137: const char* isn't handled properly
    m2.def("print_cchar", [](const char *string) { std::cout << string << std::endl; });

    // #150: char bindings broken
    m2.def("print_char", [](char c) { std::cout << c << std::endl; });

    // #159: virtual function dispatch has problems with similar-named functions
    struct Base { virtual void dispatch(void) const {
        /* for some reason MSVC2015 can't compile this if the function is pure virtual */
    }; };

    struct DispatchIssue : Base {
        virtual void dispatch(void) const {
            PYBIND11_OVERLOAD_PURE(void, Base, dispatch, /* no arguments */);
        }
    };

    py::class_<Base, std::unique_ptr<Base>, DispatchIssue>(m2, "DispatchIssue")
        .def(py::init<>())
        .def("dispatch", &Base::dispatch);

    m2.def("dispatch_issue_go", [](const Base * b) { b->dispatch(); });

    struct Placeholder { int i; Placeholder(int i) : i(i) { } };

    py::class_<Placeholder>(m2, "Placeholder")
        .def(py::init<int>())
        .def("__repr__", [](const Placeholder &p) { return "Placeholder[" + std::to_string(p.i) + "]"; });

    // #171: Can't return reference wrappers (or STL datastructures containing them)
    m2.def("return_vec_of_reference_wrapper", [](std::reference_wrapper<Placeholder> p4){
        Placeholder *p1 = new Placeholder{1};
        Placeholder *p2 = new Placeholder{2};
        Placeholder *p3 = new Placeholder{3};
        std::vector<std::reference_wrapper<Placeholder>> v;
        v.push_back(std::ref(*p1));
        v.push_back(std::ref(*p2));
        v.push_back(std::ref(*p3));
        v.push_back(p4);
        return v;
    });

    // #181: iterator passthrough did not compile
    m2.def("iterator_passthrough", [](py::iterator s) -> py::iterator {
        return py::make_iterator(std::begin(s), std::end(s));
    });

    // #187: issue involving std::shared_ptr<> return value policy & garbage collection
    struct ElementBase { virtual void foo() { } /* Force creation of virtual table */ };
    struct ElementA : ElementBase {
        ElementA(int v) : v(v) { }
        int value() { return v; }
        int v;
    };

    struct ElementList {
        void add(std::shared_ptr<ElementBase> e) { l.push_back(e); }
        std::vector<std::shared_ptr<ElementBase>> l;
    };

    py::class_<ElementBase, std::shared_ptr<ElementBase>> (m2, "ElementBase");

    py::class_<ElementA, std::shared_ptr<ElementA>>(m2, "ElementA", py::base<ElementBase>())
        .def(py::init<int>())
        .def("value", &ElementA::value);

    py::class_<ElementList, std::shared_ptr<ElementList>>(m2, "ElementList")
        .def(py::init<>())
        .def("add", &ElementList::add)
        .def("get", [](ElementList &el){
            py::list list;
            for (auto &e : el.l)
                list.append(py::cast(e));
            return list;
        });

    // (no id): should not be able to pass 'None' to a reference argument
    m2.def("print_element", [](ElementA &el) { std::cout << el.value() << std::endl; });

    // (no id): don't cast doubles to ints
    m2.def("expect_float", [](float f) { return f; });
    m2.def("expect_int", [](int i) { return i; });

    // (no id): don't invoke Python dispatch code when instantiating C++
    // classes that were not extended on the Python side
    struct A {
        virtual ~A() {}
        virtual void f() { std::cout << "A.f()" << std::endl; }
    };

    struct PyA : A {
        PyA() { std::cout << "PyA.PyA()" << std::endl; }

        void f() override {
            std::cout << "PyA.f()" << std::endl;
            PYBIND11_OVERLOAD(void, A, f);
        }
    };

    auto call_f = [](A *a) { a->f(); };

    pybind11::class_<A, std::unique_ptr<A>, PyA>(m2, "A")
        .def(py::init<>())
        .def("f", &A::f);

    m2.def("call_f", call_f);

    try {
        py::class_<Placeholder>(m2, "Placeholder");
        throw std::logic_error("Expected an exception!");
    } catch (std::runtime_error &) {
        /* All good */
    }

    // Issue #283: __str__ called on uninitialized instance when constructor arguments invalid
    class StrIssue {
    public:
        StrIssue(int i) : val{i} {}
        StrIssue() : StrIssue(-1) {}
        int value() const { return val; }
    private:
        int val;
    };
    py::class_<StrIssue> si(m2, "StrIssue");
    si  .def(py::init<int>())
        .def(py::init<>())
        .def("__str__", [](const StrIssue &si) {
                std::cout << "StrIssue.__str__ called" << std::endl;
                return "StrIssue[" + std::to_string(si.value()) + "]";
                })
        ;

}
Exemplo n.º 8
0
void python_export_filesystem(py::module &m) {
    using namespace fs;

    py::module fs_module =
        m.def_submodule("filesystem", "Cross-platform filesystem support");

    py::class_<path> path_class(fs_module, "path");

    path_class
        .def(py::init<>())
        .def(py::init<const path &>())
        .def(py::init<const std::string &>())
        .def("__len__", &path::length)
        .def("file_size", &path::file_size)
        .def("empty", &path::empty)
        .def("is_absolute", &path::is_absolute)
        .def("make_absolute", &path::make_absolute)
        .def("exists", &path::exists)
        .def("is_directory", &path::is_directory)
        .def("is_file", &path::is_file)
        .def("extension", &path::extension)
        .def("parent_path", &path::parent_path)
        .def("remove_file", &path::remove_file)
        .def("resize_file", &path::resize_file)
        .def("str", [](const path &p) { return p.str(); })
        .def("str", [](const path &p, path::path_type t) { return p.str(t); })
        .def("set", [](path &p, const std::string &v, path::path_type t) { p.set(v, t); })
        .def("set", [](path &p, const std::string &v) { p.set(v); })
        .def(py::self / py::self)
        .def("__repr__", [](const path &p) { return p.str(); })
        .def_static("getcwd", &path::getcwd);

    py::enum_<path::path_type>(path_class, "path_type")
        .value("windows_path", path::windows_path)
        .value("posix_path", path::posix_path)
        .value("native_path", path::native_path)
        .export_values();

    py::class_<resolver>(fs_module, "resolver")
        .def(py::init<>())
        .def("__len__", &resolver::size)
        .def("append", &resolver::append)
        .def("prepend", &resolver::prepend)
        .def("resolve", &resolver::resolve)
        .def("__getitem__", [](const resolver &r, size_t i) {
             if (i >= r.size())
                 throw py::index_error();
             return r[i];
         })
        .def("__setitem__", [](resolver &r, size_t i, path &v) {
             if (i >= r.size())
                 throw py::index_error();
             r[i] = v;
         })
        .def("__delitem__", [](resolver &r, size_t i) {
             if (i >= r.size())
                 throw py::index_error();
             r.erase(r.begin() + i);
         })
        .def("__repr__", [](const resolver &r) {
            std::ostringstream oss;
            oss << r;
            return oss.str();
        });

    py::class_<MemoryMappedFile>(fs_module, "MemoryMappedFile")
        .def(py::init<fs::path, size_t>())
        .def(py::init<fs::path, bool>())
        .def(py::init<fs::path>())
        .def("resize", &MemoryMappedFile::resize)
        .def("__repr__", &MemoryMappedFile::toString)
        .def("size", &MemoryMappedFile::size)
        .def("filename", &MemoryMappedFile::filename)
        .def("readOnly", &MemoryMappedFile::readOnly)
        .def_static("createTemporary", &MemoryMappedFile::createTemporary)
        .def_buffer([](MemoryMappedFile &m) -> py::buffer_info {
            return py::buffer_info(
                m.data(),
                sizeof(uint8_t),
                py::format_descriptor<uint8_t>::format(),
                1,
                { (size_t) m.size() },
                { sizeof(uint8_t) }
            );
        });

    py::implicitly_convertible<std::string, path>();
}
Exemplo n.º 9
0
void python_export_spline(py::module &m) {
    /* spline.h bindings */
    py::module spline = m.def_submodule(
        "spline", "Functions for evaluating and sampling Catmull-Rom splines");

    spline.def("evalSpline",   evalSpline<Float>, D(spline, evalSpline));
    spline.def("evalSplineD", evalSplineD<Float>, D(spline, evalSplineD));
    spline.def("evalSplineI", evalSplineI<Float>, D(spline, evalSplineI));

    spline.def("eval1D", [](Float min, Float max, const VectorX &values,
                            Float x, bool extrapolate) {
        return eval1D(min, max, values.data(), values.size(), x, extrapolate);
    }, D(spline, eval1D));

    spline.def("eval1D", [](Float min, Float max, const VectorX &values,
                            const MatrixX &x, bool extrapolate) -> MatrixX {
        MatrixX result(x.rows(), x.cols());
        for (int i=0; i<x.rows(); ++i)
            for (int j=0; j<x.cols(); ++j)
                result(i, j) = eval1D(min, max, values.data(), values.size(), x(i, j), extrapolate);
        return result;
    }, D(spline, eval1D));

    spline.def("eval1D", [](VectorX &nodes, const VectorX &values,
                            Float x, bool extrapolate) {
        if (nodes.size() != values.size())
            throw std::runtime_error("'nodes' and 'values' must have a matching size!");
        return eval1D(nodes.data(), values.data(), nodes.size(), x, extrapolate);
    }, D(spline, eval1D, 2));

    spline.def("eval1D", [](VectorX &nodes, const VectorX &values,
                            const MatrixX &x, bool extrapolate) -> MatrixX {
        if (nodes.size() != values.size())
            throw std::runtime_error("'nodes' and 'values' must have a matching size!");
        MatrixX result(x.rows(), x.cols());
        for (int i=0; i<x.rows(); ++i)
            for (int j=0; j<x.cols(); ++j)
                result(i, j) = eval1D(nodes.data(), values.data(), nodes.size(), x(i, j), extrapolate);
        return result;
    }, D(spline, eval1D, 2));

    spline.def("invert1D", [](Float min, Float max, const VectorX &values,
                              Float y) {
        return invert1D(min, max, values.data(), values.size(), y);
    }, D(spline, invert1D));

    spline.def("invert1D", [](const VectorX &nodes, const VectorX &values,
                              Float y) {
        if (nodes.size() != values.size())
            throw std::runtime_error("'nodes' and 'values' must have a matching size!");
        return invert1D(nodes.data(), values.data(), values.size(), y);
    }, D(spline, invert1D, 2));

    spline.def("integrate1D", [](Float min, Float max, const VectorX &values) {
        VectorX result(values.size());
        integrate1D(min, max, values.data(), values.size(), result.data());
        return result;
    }, D(spline, integrate1D));

    spline.def("integrate1D", [](const VectorX &nodes, const VectorX &values) {
        if (nodes.size() != values.size())
            throw std::runtime_error("'nodes' and 'values' must have a matching size!");
        std::vector<Float> result(values.size());
        integrate1D(nodes.data(), values.data(), values.size(), result.data());
        return result;
    }, D(spline, integrate1D, 2));

    spline.def("sample1D", [](Float min, Float max, const VectorX &values,
                              const VectorX &cdf, Float sample) {
        if (values.size() != cdf.size())
            throw std::runtime_error("'values' and 'cdf' must have a matching size!");
        Float pos, fval, pdf;
        pos = sample1D(min, max, values.data(), cdf.data(), values.size(),
                       sample, &fval, &pdf);
        return std::make_tuple(pos, fval, pdf);
    }, D(spline, sample1D));

    spline.def("sample1D", [](const VectorX &nodes, const VectorX &values,
                              const VectorX &cdf, Float sample) {
        if (nodes.size() != values.size() || nodes.size() != cdf.size())
            throw std::runtime_error("'nodes', 'values', and 'cdf' must have a matching size!");
        Float pos, fval, pdf;
        pos = sample1D(nodes.data(), values.data(), cdf.data(), nodes.size(), sample, &fval, &pdf);
        return std::make_tuple(pos, fval, pdf);
    }, D(spline, sample1D, 2));

    spline.def("evalSplineWeights", [](Float min, Float max, size_t size, Float x, bool extrapolate) {
        Float weights[4] = { 0, 0, 0, 0 };
        ssize_t offset = 0;
        bool success = evalSplineWeights(min, max, size, x, offset, weights, extrapolate);
        return std::make_tuple(
            success, offset, std::make_tuple(weights[0], weights[1], weights[2], weights[3])
        );
    }, D(spline, evalSplineWeights));

    spline.def("evalSplineWeights", [](const VectorX &nodes, Float x, bool extrapolate) {
        Float weights[4] = { 0, 0, 0, 0};
        ssize_t offset = 0;
        bool success = evalSplineWeights(nodes.data(), nodes.size(), x, offset, weights, extrapolate);
        return std::make_tuple(
            success, offset, std::make_tuple(weights[0], weights[1], weights[2], weights[3])
        );
    }, D(spline, evalSplineWeights, 2));

    spline.def("eval2D", [](const VectorX &nodes1, const VectorX &nodes2,
                            const MatrixX &values, Float x, Float y,
                            bool extrapolate) {
        if (values.rows() != nodes1.size() || values.cols() != nodes2.size())
            throw std::runtime_error("'nodes' and 'values' must have a matching size!");

        return eval2D(nodes1.data(), nodes1.size(), nodes2.data(), nodes2.size(), values.data(), y, x, extrapolate);
    }, D(spline, eval2D));

    spline.def("eval2D", [](const VectorX &nodes1, const VectorX &nodes2,
                            const MatrixX &values, const MatrixX &x, const MatrixX &y,
                            bool extrapolate) {
        if (values.rows() != nodes1.size() || values.cols() != nodes2.size())
            throw std::runtime_error("'nodes' and 'values' must have a matching size!");
        if (x.rows() != nodes1.size() || x.cols() != y.size())
            throw std::runtime_error("'x' and 'y' must have a matching size!");

        MatrixX result(x.rows(), x.cols());
        for (int i=0; i<x.rows(); ++i)
            for (int j=0; j<x.cols(); ++j)
                result(i, j) = eval2D(
                    nodes1.data(), nodes1.size(), nodes2.data(), nodes2.size(),
                    values.data(), y(i, j), x(i, j), extrapolate);
        return result;

    }, D(spline, eval2D));
}
Exemplo n.º 10
0
void init_ResonancePdf(py::module &m) {
    auto m_ls = m.def_submodule("Resonances");

    py::class_<ResonancePdf, GooPdf>(m, "ResonancePdf").def_static("help", []() {
        return HelpPrinter(ResonancePdf_docs);
    });

    py::class_<Resonances::RBW, ResonancePdf>(m_ls, "RBW")
        .def(py::init<std::string, Variable, Variable, Variable, Variable, unsigned int, unsigned int, bool>(),
             "Constructor for regular BW",
             "name"_a,
             "ar"_a,
             "ai"_a,
             "mass"_a,
             "width"_a,
             "sp"_a,
             "cyc"_a,
             "sym"_a = false);

    py::class_<Resonances::GS, ResonancePdf>(m_ls, "GS")
        .def(py::init<std::string, Variable, Variable, Variable, Variable, unsigned int, unsigned int>(),
             "Constructor for regular Gounaris-Sakurai",
             "name"_a,
             "ar"_a,
             "ai"_a,
             "mass"_a,
             "width"_a,
             "sp"_a,
             "cyc"_a);

    py::class_<Resonances::LASS, ResonancePdf>(m_ls, "LASS")
        .def(py::init<std::string, Variable, Variable, Variable, Variable, unsigned int, unsigned int>(),
             "Constructor for LASS",
             "name"_a,
             "ar"_a,
             "ai"_a,
             "mass"_a,
             "width"_a,
             "sp"_a,
             "cyc"_a);

    py::class_<Resonances::NonRes, ResonancePdf>(m_ls, "NonRes")
        .def(py::init<std::string, Variable, Variable>(), "Constructor for NonResonant", "name"_a, "ar"_a, "ai"_a);

    py::class_<Resonances::Gauss, ResonancePdf>(m_ls, "Gauss")
        .def(py::init<std::string, Variable, Variable, Variable, Variable, unsigned int>(),
             "Constructor for regular GAUSS",
             "name"_a,
             "ar"_a,
             "ai"_a,
             "mean"_a,
             "sigma"_a,
             "cyc"_a);

    py::class_<Resonances::FLATTE, ResonancePdf>(m_ls, "FLATTE")
        .def(py::init<std::string, Variable, Variable, Variable, Variable, Variable, unsigned int, bool>(),
             "Constructor for regular FLATTE",
             "name"_a,
             "ar"_a,
             "ai"_a,
             "mean"_a,
             "g1"_a,
             "rg2og1"_a,
             "cyc"_a,
             "symmDP"_a);

    py::class_<Resonances::Spline, ResonancePdf>(m_ls, "Spline")
        .def(py::init<std::string,
                      Variable,
                      Variable,
                      std::vector<fptype> &,
                      std::vector<Variable> &,
                      std::vector<Variable> &,
                      unsigned int,
                      bool>(),
             "Constructor for regular cubic spline",
             "name"_a,
             "ar"_a,
             "ai"_a,
             "HH_bin_limits"_a,
             "pwa_coefs_reals"_a,
             "pwa_coefs_imags"_a,
             "cyc"_a,
             "symmDP"_a = false,
             py::keep_alive<1, 5>(),
             py::keep_alive<1, 6>(),
             py::keep_alive<1, 7>());
}