Skip to content

Commit

Permalink
Add gradient test (#46)
Browse files Browse the repository at this point in the history
* Bump version number and update requirements

* Leaving the changing of Variables for a bugfix PR (using PL 0.8.0 for now)

* Modifying comment

Co-authored-by: Josh Izaac <josh146@gmail.com>
  • Loading branch information
antalszava and josh146 committed Feb 28, 2020
1 parent 3dab35e commit 6f0edf6
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions tests/test_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -1221,3 +1221,46 @@ def circuit_reg(a):
return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))

assert np.array_equal(circuit.jacobian([angle]), circuit_reg.jacobian([angle]))

THETA = np.linspace(0.11, 3, 5)
PHI = np.linspace(0.32, 3, 5)
VARPHI = np.linspace(0.02, 3, 5)

@pytest.mark.parametrize("analytic", [True])
@pytest.mark.parametrize("theta,phi,varphi", list(zip(THETA, PHI, VARPHI)))
def test_gradient(self, theta, phi, varphi, analytic, tol):
"""Test that the gradient works correctly"""
program = pyquil.Program()

delta1 = program.declare("delta1", "REAL")
delta2 = program.declare("delta2", "REAL")
delta3 = program.declare("delta3", "REAL")

program += g.RX(delta1, 0)
program += g.RX(delta2, 1)
program += g.RX(delta3, 2)
program += g.CNOT(0, 1)
program += g.CNOT(1, 2)

# Convert to a PennyLane circuit
program_pl = qml.load(program, format="pyquil_program")

dev = qml.device("default.qubit", wires=3, analytic=analytic)

@qml.qnode(dev)
def circuit(params):
program_pl(parameter_map={delta1: params[0],
delta2: params[1],
delta3: params[2]},
wires=range(len(program_pl.defined_qubits)))
return qml.expval(qml.PauliX(0) @ qml.PauliY(2))

dcircuit = qml.grad(circuit, 0)
res = dcircuit([theta, phi, varphi])
expected = [
np.cos(theta) * np.sin(phi) * np.sin(varphi),
np.sin(theta) * np.cos(phi) * np.sin(varphi),
np.sin(theta) * np.sin(phi) * np.cos(varphi)
]

assert np.allclose(res, expected, tol)

0 comments on commit 6f0edf6

Please sign in to comment.