| 25 | namespace cudaq { |
| 26 | |
| 27 | void bindExecutionContext(nanobind::module_ &mod) { |
| 28 | nanobind::class_<cudaq::ExecutionContext>(mod, "ExecutionContext") |
| 29 | .def(nanobind::init<std::string>()) |
| 30 | .def(nanobind::init<std::string, std::size_t, std::size_t>(), |
| 31 | nanobind::arg("name"), nanobind::arg("shots"), |
| 32 | nanobind::arg("qpu_id") = 0) |
| 33 | .def_rw("kernelName", &cudaq::ExecutionContext::kernelName) |
| 34 | .def_ro("result", &cudaq::ExecutionContext::result) |
| 35 | .def_rw("asyncExec", &cudaq::ExecutionContext::asyncExec) |
| 36 | .def_ro("asyncResult", &cudaq::ExecutionContext::asyncResult) |
| 37 | .def_rw("hasConditionalsOnMeasureResults", |
| 38 | &cudaq::ExecutionContext::hasConditionalsOnMeasureResults) |
| 39 | .def_rw("totalIterations", &cudaq::ExecutionContext::totalIterations) |
| 40 | .def_rw("batchIteration", &cudaq::ExecutionContext::batchIteration) |
| 41 | .def_rw("numberTrajectories", |
| 42 | &cudaq::ExecutionContext::numberTrajectories) |
| 43 | .def_rw("explicitMeasurements", |
| 44 | &cudaq::ExecutionContext::explicitMeasurements) |
| 45 | .def_rw("allowJitEngineCaching", |
| 46 | &cudaq::ExecutionContext::allowCompiledModuleCaching) |
| 47 | .def_rw("useParametricJit", &cudaq::ExecutionContext::useParametricJit) |
| 48 | .def_ro("invocationResultBuffer", |
| 49 | &cudaq::ExecutionContext::invocationResultBuffer) |
| 50 | .def("unset_jit_engine", |
| 51 | [&](cudaq::ExecutionContext &execCtx) { |
| 52 | if (execCtx.cachedCompiledModule) { |
| 53 | execCtx.cachedCompiledModule = std::nullopt; |
| 54 | execCtx.allowCompiledModuleCaching = false; |
| 55 | } |
| 56 | }) |
| 57 | .def("setSpinOperator", |
| 58 | [](cudaq::ExecutionContext &ctx, cudaq::spin_op &spin) { |
| 59 | ctx.spin = spin; |
| 60 | assert(cudaq::spin_op::canonicalize(spin) == spin); |
| 61 | }) |
| 62 | .def("getExpectationValue", |
| 63 | [](cudaq::ExecutionContext &ctx) { return ctx.expectationValue; }) |
| 64 | // ----- Context management using with blocks ----- |
| 65 | // Unlike in C++, we do not support nested execution contexts in Python. |
| 66 | .def( |
| 67 | "__enter__", |
| 68 | [](cudaq::ExecutionContext &ctx) -> ExecutionContext & { |
| 69 | if (cudaq::getExecutionContext()) { |
| 70 | throw std::runtime_error("Context already set. Nested execution " |
| 71 | "contexts are not supported in Python"); |
| 72 | } |
| 73 | auto &platform = cudaq::get_platform(); |
| 74 | platform.configureExecutionContext(ctx); |
| 75 | cudaq::detail::setExecutionContext(&ctx); |
| 76 | platform.beginExecution(); |
| 77 | return ctx; |
| 78 | }, |
| 79 | nanobind::rv_policy::reference) |
| 80 | .def( |
| 81 | "__exit__", |
| 82 | [](cudaq::ExecutionContext &ctx, nanobind::object type, |
| 83 | nanobind::object value, nanobind::object traceback) { |
| 84 | if (type.is_none()) { |
no test coverage detected