Commit 7c9e8126 authored by Mccaskey, Alex's avatar Mccaskey, Alex
Browse files

adding observe method to python qjit



Signed-off-by: Mccaskey, Alex's avatarAlex McCaskey <mccaskeyaj@ornl.gov>
parent cec804e2
Pipeline #123685 passed with stage
in 16 minutes and 37 seconds
......@@ -369,6 +369,15 @@ PYBIND11_MODULE(_pyqcor, m) {
},
"");
m.def(
"internal_observe",
[](std::shared_ptr<CompositeInstruction> kernel,
qcor::PauliOperator &obs) {
auto q = ::qalloc(obs.nBits());
return qcor::observe(kernel, obs, q);
},
"");
// qsim sub-module bindings:
{
py::module qsim = m.def_submodule("qsim", "QCOR's python qsim submodule");
......
......@@ -268,9 +268,17 @@ class qjit(object):
args_dict = {}
for i, arg_name in enumerate(self.arg_names):
args_dict[arg_name] = list(args)[i]
return self._qjit.extract_composite(self.function.__name__, args_dict)
def observe(self, observable, *args):
"""
Return the expectation value of <observable> with
respect to the state given by this qjit kernel evaluated
at the given arguments.
"""
program = self.extract_composite(*args)
return internal_observe(program, observable)
def openqasm(self, *args):
"""
Return an OpenQasm string representation of this
......
......@@ -50,6 +50,28 @@ class TestVQEObjectiveFunction(unittest.TestCase):
self.assertAlmostEqual(results[0], -1.74, places=1)
print(results)
def test_observe(self):
H = -2.1433 * X(0) * X(1) - 2.1433 * \
Y(0) * Y(1) + .21829 * Z(0) - 6.125 * Z(1) + 5.907
@qjit
def ansatz(q : qreg, theta : float):
X(q[0])
Ry(q[1], theta)
CX(q[1], q[0])
target_energy = -1.74
def objective_function(x):
q = qalloc(H.nBits())
energy = ansatz.observe(H, q, x[0])
return abs(target_energy - energy)
optimizer = createOptimizer('nlopt', {'nlopt-maxeval':20})
opt_val, opt_params = optimizer.optimize(objective_function, 1)
self.assertAlmostEqual(opt_val, 0.0, places=1)
self.assertAlmostEqual(opt_params[0], .5, places=1)
if __name__ == '__main__':
unittest.main()
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment