void init_ex10(py::module &m) { // Vectorize all arguments of a function (though non-vector arguments are also allowed) m.def("vectorized_func", py::vectorize(my_func)); // Vectorize a lambda function with a capture object (e.g. to exclude some arguments from the vectorization) m.def("vectorized_func2", [](py::array_dtype<int> x, py::array_dtype<float> y, float z) { return py::vectorize([z](int x, float y) { return my_func(x, y, z); })(x, y); } ); // Vectorize a complex-valued function m.def("vectorized_func3", py::vectorize(my_func3)); }
void init_ex12(py::module &m) { /* Important: use the wrapper type as a template argument to class_<>, but use the original name to denote the type */ py::class_<PyExample12>(m, "Example12") /* Declare that 'PyExample12' is really an alias for the original type 'Example12' */ .alias<Example12>() .def(py::init<int>()) /* Reference original class in function definitions */ .def("run", &Example12::run) .def("pure_virtual", &Example12::pure_virtual); m.def("runExample12", &runExample12); m.def("runExample12Virtual", &runExample12Virtual); }
void define_target(py::module &m) { // Disambiguate some ambigious methods int (Target::*natural_vector_size_method)(const Type &t) const = &Target::natural_vector_size; bool (Target::*supports_type1_method)(const Type &t) const = &Target::supports_type; bool (Target::*supports_type2_method)(const Type &t, DeviceAPI device) const = &Target::supports_type; auto target_class = py::class_<Target>(m, "Target") .def(py::init<>()) .def(py::init<const std::string &>()) .def(py::init<Target::OS, Target::Arch, int>()) .def(py::init<Target::OS, Target::Arch, int, std::vector<Target::Feature>>()) .def("__eq__", [](const Target &value, Target *value2) { return value2 && value == *value2; }) .def("__ne__", [](const Target &value, Target *value2) { return !value2 || value != *value2; }) .def_readwrite("os", &Target::os) .def_readwrite("arch", &Target::arch) .def_readwrite("bits", &Target::bits) .def("__repr__", &target_repr) .def("__str__", &Target::to_string) .def("to_string", &Target::to_string) .def("has_feature", &Target::has_feature) .def("features_any_of", &Target::features_any_of, py::arg("features")) .def("features_all_of", &Target::features_all_of, py::arg("features")) .def("set_feature", &Target::set_feature, py::arg("f"), py::arg("value") = true) .def("set_features", &Target::set_features, py::arg("features"), py::arg("value") = true) .def("with_feature", &Target::with_feature, py::arg("feature")) .def("without_feature", &Target::without_feature, py::arg("feature")) .def("has_gpu_feature", &Target::has_gpu_feature) .def("supports_type", supports_type1_method, py::arg("type")) .def("supports_type", supports_type2_method, py::arg("type"), py::arg("device")) .def("supports_device_api", &Target::supports_device_api, py::arg("device")) .def("natural_vector_size", natural_vector_size_method, py::arg("type")) .def("has_large_buffers", &Target::has_large_buffers) .def("maximum_buffer_size", &Target::maximum_buffer_size) .def("supported", &Target::supported) .def_static("validate_target_string", &Target::validate_target_string, py::arg("name")); ; m.def("get_host_target", &get_host_target); m.def("get_target_from_environment", &get_target_from_environment); m.def("get_jit_target_from_environment", &get_jit_target_from_environment); m.def("target_feature_for_device_api", &target_feature_for_device_api); }
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; }); }
void define_module(py::module &m) { auto module_class = py::class_<Module>(m, "Module") .def(py::init<const std::string &, const Target &>(), py::arg("name"), py::arg("target")) .def("target", &Module::target) .def("name", &Module::name) .def("auto_schedule", &Module::auto_schedule) .def("buffers", &Module::buffers) .def("submodules", &Module::submodules) .def("append", (void (Module::*)(const Buffer<> &)) &Module::append, py::arg("buffer")) .def("append", (void (Module::*)(const Module &)) &Module::append, py::arg("module")) .def("compile", &Module::compile, py::arg("outputs")) .def("compile_to_buffer", &Module::compile_to_buffer) .def("resolve_submodules", &Module::resolve_submodules) .def("remap_metadata_name", &Module::remap_metadata_name) .def("get_metadata_name_map", &Module::get_metadata_name_map) .def("set_auto_schedule", &Module::set_auto_schedule) // TODO: ExternalCode-related methods deliberately skipped for now. // .def("append", (void (Module::*)(const ExternalCode &)) &Module::append, py::arg("external_code")) // .def("external_code", &Module::external_code) // TODO: Internal::LoweredFunc-related methods deliberately skipped for now. // .def("functions", &Module::functions) // .def("get_function_by_name", &Module::get_function_by_name, py::arg("name")) // .def("append", (void (Module::*)(const Internal::LoweredFunc &)) &Module::append, py::arg("function")) .def("__repr__", [](const Module &m) -> std::string { std::ostringstream o; o << "<halide.Module '" << m.name() << "'>"; return o.str(); }) ; m.def("link_modules", &link_modules, py::arg("name"), py::arg("modules")); m.def("compile_standalone_runtime", (void (*)(const std::string &, Target)) &compile_standalone_runtime, py::arg("filename"), py::arg("target")); m.def("compile_standalone_runtime", (Outputs (*)(const Outputs &, Target)) &compile_standalone_runtime, py::arg("outputs"), py::arg("target")); // TODO: compile_multitarget() deliberately skipped for now. }
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"); }
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" }
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" }
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" }
void define_lambda(py::module &m) { // TODO: 'lambda' is a reserved word in Python, so we // can't use it for a function. Using 'lambda_func' for now. m.def("lambda_func", [](py::args args) -> Func { auto vars = args_to_vector<Var>(args, 0, 1); Expr e = args[args.size() - 1].cast<Expr>(); Func f("lambda" + Internal::unique_name('_')); f(vars) = e; return f; }); }
void init_ex4(py::module &m) { m.def("test_function", &test_function1); m.def("test_function", &test_function2); m.def("test_function", &test_function3); m.attr("some_constant") = py::int_(14); py::enum_<EMyEnumeration>(m, "EMyEnumeration") .value("EFirstEntry", EFirstEntry) .value("ESecondEntry", ESecondEntry) .export_values(); py::class_<Example4> ex4_class(m, "Example4"); ex4_class.def_static("test_function", &Example4::test_function); py::enum_<Example4::EMode>(ex4_class, "EMode") .value("EFirstMode", Example4::EFirstMode) .value("ESecondMode", Example4::ESecondMode) .export_values(); m.def("return_bytes", &return_bytes); m.def("print_bytes", &print_bytes); }
bool Context::import(py::module m) { if (!m) return false; string name = PyModule_GetName(m.ptr()); if (!name.empty()) { py_global[name.c_str()] = m; } return true; }
void pyqpp_cell_export (py::module m) { py_cell_export<float>(m, "periodic_cell_f"); qpp::gen_cell<float, qpp::matrix3<float> >::py_export( m, "point_group_f"); qpp::gen_cell<float, qpp::rotrans<float,false> >::py_export( m, "crystal_group_f"); qpp::gen_cell<float, qpp::rotrans<float,true> >::py_export( m, "finite_crystal_group_f"); qpp::array_group<qpp::matrix3<float> >::py_export( m, "array_point_group_f"); qpp::array_group<qpp::rotrans<float,true> >::py_export( m, "array_fincryst_group_f"); m.def("generator_form", py_generator_form<float, qpp::matrix3<float>, qpp::array_group<qpp::matrix3<float> > > ); m.def("generator_form", py_generator_form<float, qpp::rotrans<float,true>, qpp::array_group<qpp::rotrans<float,true> > >); #ifdef PYTHON_EXP_EXT py_cell_export<double>(m, "periodic_cell_d"); qpp::gen_cell<double, qpp::matrix3<double> >::py_export( m, "point_group_d"); qpp::gen_cell<double, qpp::rotrans<double,false> >::py_export( m, "crystal_group_d"); qpp::gen_cell<double, qpp::rotrans<double,true> >::py_export( m, "finite_crystal_group_d"); qpp::array_group<qpp::matrix3<double> >::py_export( m, "array_point_group_d"); qpp::array_group<qpp::rotrans<double,true> >::py_export( m, "array_fincryst_group_d"); m.def("generator_form", py_generator_form<double, qpp::matrix3<double>, qpp::array_group<qpp::matrix3<double> > >); m.def("generator_form", py_generator_form<double, qpp::rotrans<double,true>, qpp::array_group<qpp::rotrans<double,true> > >); #endif }
// 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); }); }
void init_ex11(py::module &m) { m.def("kw_func", &kw_func, py::arg("x"), py::arg("y")); m.def("kw_func2", &kw_func, py::arg("x") = 100, py::arg("y") = 200); m.def("kw_func3", [](const char *) { }, py::arg("data") = std::string("Hello world!")); /* A fancier default argument */ std::vector<int> list; list.push_back(13); list.push_back(17); m.def("kw_func4", &kw_func4, py::arg("myList") = list); m.def("call_kw_func", &call_kw_func); m.def("args_function", &args_function); m.def("args_kwargs_function", &args_kwargs_function); using namespace py::literals; m.def("kw_func_udl", &kw_func, "x"_a, "y"_a=300); m.def("kw_func_udl_z", &kw_func, "x"_a, "y"_a=0); }
// ---------------------------------------------------------------------------------------- void bind_vector(py::module& m) { { py::class_<cv, std::shared_ptr<cv>>(m, "vector", "This object represents the mathematical idea of a column vector.") .def(py::init()) .def("set_size", &cv_set_size) .def("resize", &cv_set_size) .def(py::init(&cv_from_object)) .def("__repr__", &cv__repr__) .def("__str__", &cv__str__) .def("__len__", &cv__len__) .def("__getitem__", &cv__getitem__) .def("__getitem__", &cv__getitem2__) .def("__setitem__", &cv__setitem__) .def_property_readonly("shape", &cv_get_matrix_size) .def(py::pickle(&getstate<cv>, &setstate<cv>)); m.def("dot", &dotprod, "Compute the dot product between two dense column vectors."); } { typedef point type; py::class_<type>(m, "point", "This object represents a single point of integer coordinates that maps directly to a dlib::point.") .def(py::init<long,long>(), py::arg("x"), py::arg("y")) .def("__repr__", &point__repr__) .def("__str__", &point__str__) .def_property_readonly("x", &point_x, "The x-coordinate of the point.") .def_property_readonly("y", &point_y, "The y-coordinate of the point.") .def(py::pickle(&getstate<type>, &setstate<type>)); } { typedef std::vector<point> type; py::bind_vector<type>(m, "points", "An array of point objects.") .def("clear", &type::clear) .def("resize", resize<type>) .def("extend", extend_vector_with_python_list<point>) .def(py::pickle(&getstate<type>, &setstate<type>)); } }
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()) + "]"; }) ; }
void init_ex18(py::module & m) { m.def("example18", &example18); }
void define_operators(py::module &m) { m.def("max", [](py::args args) -> Expr { if (args.size() < 2) { throw py::value_error("max() must have at least 2 arguments"); } int pos = (int) args.size() - 1; Expr value = args[pos--].cast<Expr>(); while (pos >= 0) { value = max(args[pos--].cast<Expr>(), value); } return value; }); m.def("min", [](py::args args) -> Expr { if (args.size() < 2) { throw py::value_error("min() must have at least 2 arguments"); } int pos = (int) args.size() - 1; Expr value = args[pos--].cast<Expr>(); while (pos >= 0) { value = min(args[pos--].cast<Expr>(), value); } return value; }); m.def("clamp", &clamp); m.def("abs", &abs); m.def("absd", &absd); m.def("select", [](py::args args) -> Expr { if (args.size() < 3) { throw py::value_error("select() must have at least 3 arguments"); } if ((args.size() % 2) == 0) { throw py::value_error("select() must have an odd number of arguments"); } int pos = (int) args.size() - 1; Expr false_value = args[pos--].cast<Expr>(); while (pos > 0) { Expr true_value = args[pos--].cast<Expr>(); Expr condition = args[pos--].cast<Expr>(); false_value = select(condition, true_value, false_value); } return false_value; }); m.def("tuple_select", [](py::args args) -> py::tuple { _halide_user_assert(args.size() >= 3) << "tuple_select() must have at least 3 arguments"; _halide_user_assert((args.size() % 2) != 0) << "tuple_select() must have an odd number of arguments"; int pos = (int) args.size() - 1; Tuple false_value = args[pos--].cast<Tuple>(); bool has_tuple_cond = false, has_expr_cond = false; while (pos > 0) { Tuple true_value = args[pos--].cast<Tuple>();; // Note that 'condition' can be either Expr or Tuple, but must be consistent across all py::object py_cond = args[pos--]; Expr expr_cond; Tuple tuple_cond(expr_cond); try { tuple_cond = py_cond.cast<Tuple>(); has_tuple_cond = true; } catch (...) { expr_cond = py_cond.cast<Expr>(); has_expr_cond = true; } if (expr_cond.defined()) { false_value = tuple_select(expr_cond, true_value, false_value); } else { false_value = tuple_select(tuple_cond, true_value, false_value); } } _halide_user_assert(!(has_tuple_cond && has_expr_cond)) <<"tuple_select() may not mix Expr and Tuple for the condition elements."; return to_python_tuple(false_value); }); m.def("sin", &sin); m.def("asin", &asin); m.def("cos", &cos); m.def("acos", &acos); m.def("tan", &tan); m.def("atan", &atan); m.def("atan", &atan2); m.def("atan2", &atan2); m.def("sinh", &sinh); m.def("asinh", &asinh); m.def("cosh", &cosh); m.def("acosh", &acosh); m.def("tanh", &tanh); m.def("atanh", &atanh); m.def("sqrt", &sqrt); m.def("hypot", &hypot); m.def("exp", &exp); m.def("log", &log); m.def("pow", &pow); m.def("erf", &erf); m.def("fast_log", &fast_log); m.def("fast_exp", &fast_exp); m.def("fast_pow", &fast_pow); m.def("fast_inverse", &fast_inverse); m.def("fast_inverse_sqrt", &fast_inverse_sqrt); m.def("floor", &floor); m.def("ceil", &ceil); m.def("round", &round); m.def("trunc", &trunc); m.def("fract", &fract); m.def("is_nan", &is_nan); m.def("reinterpret", (Expr (*)(Type, Expr)) &reinterpret); m.def("cast", (Expr (*)(Type, Expr)) &cast); m.def("print", [](py::args args) -> Expr { return print(args_to_vector_for_print(args)); }); m.def("print_when", [](Expr condition, py::args args) -> Expr { return print_when(condition, args_to_vector_for_print(args)); }, py::arg("condition")); m.def("require", [](Expr condition, Expr value, py::args args) -> Expr { auto v = args_to_vector<Expr>(args); v.insert(v.begin(), value); return require(condition, v); }, py::arg("condition"), py::arg("value")); m.def("lerp", &lerp); m.def("popcount", &popcount); m.def("count_leading_zeros", &count_leading_zeros); m.def("count_trailing_zeros", &count_trailing_zeros); m.def("div_round_to_zero", &div_round_to_zero); m.def("mod_round_to_zero", &mod_round_to_zero); m.def("random_float", (Expr (*)()) &random_float); m.def("random_uint", (Expr (*)()) &random_uint); m.def("random_int", (Expr (*)()) &random_int); m.def("random_float", (Expr (*)(Expr)) &random_float, py::arg("seed")); m.def("random_uint", (Expr (*)(Expr)) &random_uint, py::arg("seed")); m.def("random_int", (Expr (*)(Expr)) &random_int, py::arg("seed")); m.def("undef", (Expr (*)(Type)) &undef); m.def("memoize_tag", [](Expr result, py::args cache_key_values) -> Expr { return Internal::memoize_tag_helper(result, args_to_vector<Expr>(cache_key_values)); }, py::arg("result")); m.def("likely", &likely); m.def("likely_if_innermost", &likely_if_innermost); m.def("saturating_cast", (Expr (*)(Type, Expr))&saturating_cast); }
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>()); }
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>(); }
void init_eigen(py::module &m) { typedef Eigen::Matrix<float, 5, 6, Eigen::RowMajor> FixedMatrixR; typedef Eigen::Matrix<float, 5, 6> FixedMatrixC; typedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> DenseMatrixR; typedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> DenseMatrixC; typedef Eigen::SparseMatrix<float, Eigen::RowMajor> SparseMatrixR; typedef Eigen::SparseMatrix<float> SparseMatrixC; // Non-symmetric matrix with zero elements Eigen::MatrixXf mat(5, 6); mat << 0, 3, 0, 0, 0, 11, 22, 0, 0, 0, 17, 11, 7, 5, 0, 1, 0, 11, 0, 0, 0, 0, 0, 11, 0, 0, 14, 0, 8, 11; m.def("fixed_r", [mat]() -> FixedMatrixR { return FixedMatrixR(mat); }); m.def("fixed_c", [mat]() -> FixedMatrixC { return FixedMatrixC(mat); }); m.def("fixed_passthrough_r", [](const FixedMatrixR &m) -> FixedMatrixR { return m; }); m.def("fixed_passthrough_c", [](const FixedMatrixC &m) -> FixedMatrixC { return m; }); m.def("dense_r", [mat]() -> DenseMatrixR { return DenseMatrixR(mat); }); m.def("dense_c", [mat]() -> DenseMatrixC { return DenseMatrixC(mat); }); m.def("dense_passthrough_r", [](const DenseMatrixR &m) -> DenseMatrixR { return m; }); m.def("dense_passthrough_c", [](const DenseMatrixC &m) -> DenseMatrixC { return m; }); m.def("sparse_r", [mat]() -> SparseMatrixR { return Eigen::SparseView<Eigen::MatrixXf>(mat); }); m.def("sparse_c", [mat]() -> SparseMatrixC { return Eigen::SparseView<Eigen::MatrixXf>(mat); }); m.def("sparse_passthrough_r", [](const SparseMatrixR &m) -> SparseMatrixR { return m; }); m.def("sparse_passthrough_c", [](const SparseMatrixC &m) -> SparseMatrixC { return m; }); }
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)); }
void NGS_DLL_HEADER ExportNgsolve(py::module &m ) { m.def ("Tcl_Eval", &Ng_TclCmd); m.def ("_Redraw", ([](bool blocking, double fr) { static auto last_time = std::chrono::system_clock::now()-std::chrono::seconds(10); auto now = std::chrono::system_clock::now(); double elapsed = std::chrono::duration<double>(now-last_time).count(); if (elapsed * fr > 1) { Ng_Redraw(blocking); last_time = std::chrono::system_clock::now(); } }), py::arg("blocking")=false, py::arg("fr") = 25 ); m.def ("Draw",[](shared_ptr<MeshAccess> mesh) { mesh->SelectMesh(); Ng_TclCmd ("set ::selectvisual mesh;\n"); } ); m.def("SetVisualization", [](py::object deformation, py::object min, py::object max, /* py::object clippnt, */ py::object clipnormal, py::object clipping) { bool need_redraw = false; if (py::extract<bool>(deformation).check()) { bool def = py::extract<bool>(deformation)(); Ng_TclCmd ("set ::visoptions.deformation "+ToString(def)+";\n"); Ng_TclCmd ("Ng_Vis_Set parameters;\n"); need_redraw = true; } if (py::extract<double>(min).check()) { Ng_TclCmd ("set ::visoptions.autoscale 0\n"); Ng_TclCmd ("set ::visoptions.mminval "+ToString(py::extract<double>(min)())+";\n"); Ng_TclCmd ("Ng_Vis_Set parameters;\n"); need_redraw = true; } if (py::extract<double>(max).check()) { Ng_TclCmd ("set ::visoptions.autoscale 0\n"); Ng_TclCmd ("set ::visoptions.mmaxval "+ToString(py::extract<double>(max)())+";\n"); Ng_TclCmd ("Ng_Vis_Set parameters;\n"); need_redraw = true; } if (py::extract<py::tuple>(clipnormal).check()) { py::tuple norm = py::extract<py::tuple>(clipnormal)(); if (py::len(norm)==3) { // cout << "setting clipping normal" << endl; // tclstring << "set ::viewoptions.clipping.enable 1" << endl Ng_TclCmd ("set ::viewoptions.clipping.nx "+ToString(py::extract<double>(norm[0])())+";\n"); Ng_TclCmd ("set ::viewoptions.clipping.ny "+ToString(py::extract<double>(norm[1])())+";\n"); Ng_TclCmd ("set ::viewoptions.clipping.nz "+ToString(py::extract<double>(norm[2])())+";\n"); // << "set ::viewoptions.clipping.dist " << clipdist << endl; need_redraw = true; } } if (py::extract<bool>(clipping).check()) { bool clip = py::extract<bool>(clipping)(); Ng_TclCmd ("set ::viewoptions.clipping.enable "+ToString(int(clip))+";\n"); Ng_TclCmd ("Ng_SetVisParameters"); need_redraw = true; } if (need_redraw) Ng_Redraw(true); }, py::arg("deformation")=DummyArgument(), py::arg("min")=DummyArgument(), py::arg("max")=DummyArgument(), // py::arg("clippnt")=DummyArgument(), py::arg("clipnormal")=DummyArgument(), py::arg("clipping")=DummyArgument() ) ; m.def ("Draw", [](shared_ptr<GridFunction> gf, int sd, bool autoscale, double min, double max) { // cout << "in draw" << endl; // cout << "gf in draw = " << *gf << endl; // cout << "dims of gf = " << gf->Dimensions() << endl; gf->GetMeshAccess()->SelectMesh(); // Visualize (gf, gf->GetName()); // netgen::SolutionData * vis = new VisualizeCoefficientFunction (gf->GetMeshAccess(), gf); auto gfcf = make_shared<GridFunctionCoefficientFunction> (gf); netgen::SolutionData * vis = new VisualizeCoefficientFunction (gf->GetMeshAccess(), gfcf); Ng_SolutionData soldata; Ng_InitSolutionData (&soldata); soldata.name = gf->GetName().c_str(); soldata.data = 0; soldata.components = gf -> Dimension(); if (gf->IsComplex()) soldata.components *= 2; soldata.iscomplex = gf -> IsComplex(); soldata.draw_surface = true; // draw_surf; soldata.draw_volume = true; // draw_vol; /* if (flags.GetDefineFlag("volume")) soldata.draw_surface = false; if (flags.GetDefineFlag("boundary")) soldata.draw_volume = false; */ soldata.dist = 1; soldata.soltype = NG_SOLUTION_VIRTUAL_FUNCTION; soldata.solclass = vis; Ng_SetSolutionData (&soldata); if (gf->Dimension() == 1) Ng_TclCmd (string("set ::visoptions.scalfunction ")+gf->GetName()+":1;\n"); else Ng_TclCmd (string("set ::visoptions.vecfunction ")+gf->GetName()+";\n"); Ng_TclCmd (string("set ::visoptions.subdivisions ")+ToString(sd)+";\n"); Ng_TclCmd ("set ::visoptions.autoscale "+ToString(autoscale)+";\n"); if(!autoscale){ Ng_TclCmd ("set ::visoptions.mminval "+ToString(min)+";\n"); Ng_TclCmd ("set ::visoptions.mmaxval "+ToString(max)+";\n"); } Ng_TclCmd ("Ng_Vis_Set parameters;\n"); Ng_TclCmd ("set ::selectvisual solution;\n"); }, py::arg("gf"),py::arg("sd")=2,py::arg("autoscale")=true, py::arg("min")=0.0,py::arg("max")=1.0 ); m.def ("Draw", [](shared_ptr<CoefficientFunction> cf, shared_ptr<MeshAccess> ma, string name, int sd, bool autoscale, double min, double max, bool draw_vol, bool draw_surf) { ma->SelectMesh(); netgen::SolutionData * vis; if(dynamic_cast<ProlongateCoefficientFunction *>(cf.get())) { shared_ptr<CoefficientFunction> wrapper(new ProlongateCoefficientFunctionVisualization(*static_cast<ProlongateCoefficientFunction *>(cf.get()))); vis = new VisualizeCoefficientFunction (ma, wrapper); } else vis = new VisualizeCoefficientFunction (ma, cf); Ng_SolutionData soldata; Ng_InitSolutionData (&soldata); soldata.name = (char*)name.c_str(); soldata.data = 0; soldata.components = cf -> Dimension(); if (cf->IsComplex()) soldata.components *= 2; soldata.iscomplex = cf -> IsComplex(); soldata.draw_surface = draw_surf; soldata.draw_volume = draw_vol; /* if (flags.GetDefineFlag("volume")) soldata.draw_surface = false; if (flags.GetDefineFlag("boundary")) soldata.draw_volume = false; */ soldata.dist = 1; soldata.soltype = NG_SOLUTION_VIRTUAL_FUNCTION; soldata.solclass = vis; Ng_SetSolutionData (&soldata); if (cf->Dimension() == 1) Ng_TclCmd (string("set ::visoptions.scalfunction ")+name+":1;\n"); else if (cf->Dimension() == 3 || cf->Dimension() == ma->GetDimension()) Ng_TclCmd (string("set ::visoptions.vecfunction ")+name+";\n"); Ng_TclCmd (string("set ::visoptions.subdivisions ")+ToString(sd)+";\n"); Ng_TclCmd ("set ::visoptions.autoscale "+ToString(autoscale)+";\n"); if(!autoscale){ Ng_TclCmd ("set ::visoptions.mminval "+ToString(min)+";\n"); Ng_TclCmd ("set ::visoptions.mmaxval "+ToString(max)+";\n"); } Ng_TclCmd ("Ng_Vis_Set parameters;\n"); Ng_TclCmd ("set ::selectvisual solution;\n"); }, py::arg("cf"),py::arg("mesh"),py::arg("name"), py::arg("sd")=2,py::arg("autoscale")=true, py::arg("min")=0.0,py::arg("max")=1.0, py::arg("draw_vol")=true,py::arg("draw_surf")=true ); ExportBVP(m); ExportDrawFlux(m); }
void init_ex8(py::module &m) { py::class_<Object, ref<Object>> obj(m, "Object"); obj.def("getRefCount", &Object::getRefCount); py::class_<MyObject1, ref<MyObject1>>(m, "MyObject1", obj) .def(py::init<int>()); m.def("make_object_1", &make_object_1); m.def("make_object_2", &make_object_2); m.def("make_myobject1_1", &make_myobject1_1); m.def("make_myobject1_2", &make_myobject1_2); m.def("print_object_1", &print_object_1); m.def("print_object_2", &print_object_2); m.def("print_object_3", &print_object_3); m.def("print_object_4", &print_object_4); m.def("print_myobject1_1", &print_myobject1_1); m.def("print_myobject1_2", &print_myobject1_2); m.def("print_myobject1_3", &print_myobject1_3); m.def("print_myobject1_4", &print_myobject1_4); py::class_<MyObject2, std::shared_ptr<MyObject2>>(m, "MyObject2") .def(py::init<int>()); m.def("make_myobject2_1", &make_myobject2_1); m.def("make_myobject2_2", &make_myobject2_2); m.def("print_myobject2_1", &print_myobject2_1); m.def("print_myobject2_2", &print_myobject2_2); m.def("print_myobject2_3", &print_myobject2_3); m.def("print_myobject2_4", &print_myobject2_4); py::class_<MyObject3, std::shared_ptr<MyObject3>>(m, "MyObject3") .def(py::init<int>()); m.def("make_myobject3_1", &make_myobject3_1); m.def("make_myobject3_2", &make_myobject3_2); m.def("print_myobject3_1", &print_myobject3_1); m.def("print_myobject3_2", &print_myobject3_2); m.def("print_myobject3_3", &print_myobject3_3); m.def("print_myobject3_4", &print_myobject3_4); py::implicitly_convertible<py::int_, MyObject1>(); }