Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add helper for parsing tuples using nanobind #3025

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/nrnpython/cast_tuple.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#pragma once
#include <cstddef>
#include <stdexcept>

#include <nanobind/nanobind.h>
#include <fmt/format.h>

namespace nrn {
namespace detail {

template <typename T, size_t I>
T get(const nanobind::tuple& t) {
return nanobind::cast<T>(t[I]);
}

template <typename... Ts, typename Tuple, std::size_t... Is>
auto cast_tuple_impl(Tuple&& tuple, std::index_sequence<Is...>) {
auto count = sizeof...(Is);
if (count > tuple.size()) {
throw std::runtime_error(fmt::format(
"Not enough arguments, expected {}, but only received {}", count, tuple.size()));
}
return std::make_tuple(get<Ts, Is>(std::forward<Tuple>(tuple))...);
}
} // namespace detail

/*!
* Extract an exact number of elements from a tuple, including casting them to certain types.
*
* This uses `nanobind::cast`, so expect a `nanobind::cast_error()` if there are incompatible types.
* If the number of supplied elements in the tuple is fewer than the expected number, a std::runtime
* error is thrown.
*
* @param tuple can either be a nanobind::args or a nanobind::tuple
*/
template <typename... Ts, typename Tuple>
auto cast_tuple(Tuple&& tuple) {
return detail::cast_tuple_impl<Ts...>(std::forward<Tuple>(tuple),
std::make_index_sequence<sizeof...(Ts)>{});
}

} // namespace nrn
10 changes: 5 additions & 5 deletions src/nrnpython/nrnpy_hoc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
#include "nrnpy_utils.h"
#include "nrnpython.h"
#include "convert_cxx_exceptions.hpp"
#include "cast_tuple.hpp"

#include <unordered_map>

#include "nrnwrap_dlfcn.h"
Expand All @@ -23,6 +25,7 @@
#include <sstream>

#include <nanobind/nanobind.h>
#include <nanobind/stl/string.h>

namespace nb = nanobind;

Expand Down Expand Up @@ -157,11 +160,8 @@ static int hoc_evalpointer_err() {
}

static PyObject* nrnexec(PyObject* self, PyObject* args) {
const char* cmd;
if (!PyArg_ParseTuple(args, "s", &cmd)) {
return NULL;
}
bool b = hoc_valid_stmt(cmd, 0);
auto [cmd] = nrn::cast_tuple<const std::string>(nb::tuple(args));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have noticed that some of these constructors are the equivalent of the python constructor of the same name, which is also the case here. nb::tuple() calls either PySequence_Tuple or PyTuple_New effectively behaving as python's tuple()
I have manually steal or borrow and let the object be moved
(nb::tuple(nb::borrow(args)) in this case). Not sure if there is anything to be gained, it's mostly for info.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure I follow what you mean by:

I have manually steal or borrow and let the object be moved (nb::tuple(nb::borrow(args)) in this case)

ie: what you mean by moved in the above, and why would one add the extra nb::borrow()?

Copy link
Member

@ferdonline ferdonline Aug 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My comment is basically, there's a lot going on in the background when you do nb::tuple(), whereas if you would have done nb::tuple(nb::borrow(args) there's an explicit creation of nb::object with a borrowed reference, which being an rvalue-ref it's moved to be a nb::tuple in an almost-no-op.
Since I don't fully know what your direct call implicitly does, sometimes being explicit is better. But if you find out it does the very right (and minimal) thing I'd be glad to know.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, I was on vacation and missed this.

whereas if you would have done nb::tuple(nb::borrow(args) there's an explicit creation of nb::object with a borrowed reference

I'm all for being explicit, but I'm not sure why I want to nb::borrow; the refcnt doesn't need to be incremented from what I can tell, why would we need to do that?

Copy link
Member

@ferdonline ferdonline Sep 23, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nb::tuple extends nb::object, so there will be decref at the end of its life. I believe in this case we must borrow, not steal. Hence my comment, maybe we would better be explicit about it.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nb::tuple extends nb::object, so there will be decref at the end of its life.

I don't see why that is a problem. The nb::tuple calls https://github.com/wjakob/nanobind/blob/master/include/nanobind/nb_types.h#L478 which then calls https://github.com/wjakob/nanobind/blob/master/src/common.cpp#L623
This is then used to initialize the nb::object, so it has the correct refcount, and thus when it is dtor'd, everything is correct.

Note that both code paths go through PySequence_Tuple, so a new python tuple is created with its own lifetime and refcount.

bool b = hoc_valid_stmt(cmd.c_str(), 0);
return b ? Py_True : Py_False;
}

Expand Down
31 changes: 18 additions & 13 deletions test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,24 @@ include(NeuronTestHelper)
# =============================================================================
# Test executables
# =============================================================================
add_executable(
testneuron
common/catch2_main.cpp
unit_tests/basic.cpp
unit_tests/iovec.cpp
unit_tests/container/container.cpp
unit_tests/container/generic_data_handle.cpp
unit_tests/container/mechanism.cpp
unit_tests/container/node.cpp
unit_tests/node_order_optim/permutations.cpp
unit_tests/utils/enumerate.cpp
unit_tests/oc/hoc_interpreter.cpp
cover/unit_tests/cover.cpp)
set(TESTNEURON_SRC
common/catch2_main.cpp
unit_tests/basic.cpp
unit_tests/iovec.cpp
unit_tests/container/container.cpp
unit_tests/container/generic_data_handle.cpp
unit_tests/container/mechanism.cpp
unit_tests/container/node.cpp
unit_tests/node_order_optim/permutations.cpp
unit_tests/utils/enumerate.cpp
unit_tests/oc/hoc_interpreter.cpp
cover/unit_tests/cover.cpp)

if(NRN_ENABLE_PYTHON)
list(APPEND TESTNEURON_SRC "unit_tests/utils/cast_tuple.cpp")
endif()

add_executable(testneuron ${TESTNEURON_SRC})
set(catch2_targets testneuron)
if(NRN_ENABLE_THREADS)
add_executable(nrn-benchmarks common/catch2_main.cpp benchmarks/threads/test_multicore.cpp)
Expand Down
38 changes: 38 additions & 0 deletions test/unit_tests/utils/cast_tuple.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#include <nanobind/nanobind.h>
#include <nanobind/stl/string.h>

#include "cast_tuple.hpp"

#include <catch2/catch_test_macros.hpp>

TEST_CASE("can_cast_nanobind_tuple", "[Neuron][nrnpython]") {
auto tup = nanobind::make_tuple(42, "test", 3.14);
auto [i, s, d] = nrn::cast_tuple<int, std::string, double>(tup);
REQUIRE(i == 42);
REQUIRE(s == "test");
REQUIRE(d == 3.14);
}

TEST_CASE("can_cast_nanobind_args", "[Neuron][nrnpython]") {
auto tup = nanobind::make_tuple(42, "test", 3.14);
auto args = nanobind::cast<nanobind::args>(tup);
auto [i, s, d] = nrn::cast_tuple<int, std::string, double>(args);
REQUIRE(i == 42);
REQUIRE(s == "test");
REQUIRE(d == 3.14);
}

TEST_CASE("can_cast_extra_arguments", "[Neuron][nrnpython]") {
auto tup = nanobind::make_tuple("test", 3.14, 42);
auto [s, d] = nrn::cast_tuple<std::string, double>(tup);
REQUIRE(s == "test");
REQUIRE(d == 3.14);
}

TEST_CASE("not_enough_arguments", "[Neuron][nrnpython]") {
auto tup = nanobind::make_tuple(42, std::string("test"));
REQUIRE_THROWS(nrn::cast_tuple<int, std::string, double>(tup));

auto empty_tuple = nanobind::tuple();
REQUIRE_THROWS(nrn::cast_tuple<int>(empty_tuple));
}