Skip to content

Commit

Permalink
Merge pull request #110 from stevenheidel/pyquil14
Browse files Browse the repository at this point in the history
Upgrade Grove to PyQuil 1.4.0
  • Loading branch information
jotterbach committed Nov 22, 2017
2 parents 7c260dc + e5932eb commit 2824101
Show file tree
Hide file tree
Showing 29 changed files with 184 additions and 247 deletions.
88 changes: 76 additions & 12 deletions examples/DeutschJosza.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,19 @@
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"metadata": {
"ExecuteTime": {
"end_time": "2017-11-22T02:28:27.229545Z",
"start_time": "2017-11-22T02:28:27.039222Z"
}
},
"outputs": [],
"source": [
"from collections import defaultdict\n",
"from mock import patch, Mock\n",
"from itertools import product\n",
"\n",
"from pyquil.api import SyncConnection\n",
"from pyquil.api import JobConnection\n",
"from pyquil.job_results import JobResult, wait_for_job\n",
"import numpy as np\n",
"\n",
Expand All @@ -35,7 +40,12 @@
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"metadata": {
"ExecuteTime": {
"end_time": "2017-11-22T02:28:27.928525Z",
"start_time": "2017-11-22T02:28:27.922346Z"
}
},
"outputs": [],
"source": [
"bit_value = '0'\n",
Expand All @@ -58,7 +68,12 @@
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"metadata": {
"ExecuteTime": {
"end_time": "2017-11-22T02:28:28.660043Z",
"start_time": "2017-11-22T02:28:28.656803Z"
}
},
"outputs": [],
"source": [
"for value in constant_bitmap.values():\n",
Expand All @@ -75,15 +90,16 @@
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"metadata": {
"ExecuteTime": {
"end_time": "2017-11-22T02:28:29.290802Z",
"start_time": "2017-11-22T02:28:29.286847Z"
}
},
"outputs": [],
"source": [
"with patch(\"pyquil.api.SyncConnection\") as cxn:\n",
" # Need to mock multiple returns as an iterable\n",
" mock_job_result = Mock(spec=JobResult)\n",
" mock_job_result.is_done.return_value = True\n",
" mock_job_result.result = {'result': [[0, 0]]}\n",
" cxn.run_and_measure.return_value = mock_job_result"
"with patch(\"pyquil.api.JobConnection\") as cxn:\n",
" cxn.run_and_measure.return_value = [[0], [0]]"
]
},
{
Expand All @@ -97,6 +113,10 @@
"cell_type": "code",
"execution_count": 5,
"metadata": {
"ExecuteTime": {
"end_time": "2017-11-22T02:28:30.267305Z",
"start_time": "2017-11-22T02:28:30.262349Z"
},
"scrolled": true
},
"outputs": [],
Expand All @@ -112,6 +132,13 @@
"source": [
"If the assertion succeeded we know the algorithm returned the zero bitstring and successfully recognized the function as constant."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
Expand All @@ -130,7 +157,44 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.3"
"version": "3.6.1"
},
"latex_envs": {
"LaTeX_envs_menu_present": true,
"autocomplete": true,
"bibliofile": "biblio.bib",
"cite_by": "apalike",
"current_citInitial": 1,
"eqLabelWithNumbers": true,
"eqNumInitial": 1,
"hotkeys": {
"equation": "Ctrl-E",
"itemize": "Ctrl-I"
},
"labels_anchors": false,
"latex_user_defs": false,
"report_style_numbering": false,
"user_envs_cfg": false
},
"toc": {
"colors": {
"hover_highlight": "#DAA520",
"running_highlight": "#FF0000",
"selected_highlight": "#FFD700"
},
"moveMenuLeft": true,
"nav_menu": {
"height": "4px",
"width": "254px"
},
"navigate_menu": true,
"number_sections": true,
"sideBar": true,
"threshold": 4,
"toc_cell": false,
"toc_section_display": "block",
"toc_window_display": false,
"widenNotebook": false
}
},
"nbformat": 4,
Expand Down
6 changes: 3 additions & 3 deletions grove/alpha/arbitrary_state/arbitrary_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"""
import numpy as np
import pyquil.quil as pq
from pyquil.api import SyncConnection
from pyquil.api import QVMConnection
from pyquil.gates import *
from six.moves import input

Expand Down Expand Up @@ -297,8 +297,8 @@ def create_arbitrary_state(vector, qubits=None):
else:
v = list(v)
p = create_arbitrary_state(v)
qvm = SyncConnection()
wf, _ = qvm.wavefunction(p)
qvm = QVMConnection()
wf = qvm.wavefunction(p)
print("Normalized Vector: ", list(v / np.linalg.norm(v)))
print("Generated Wavefunction: ", wf)
if input("Show Program? (y/n): ") == 'y':
Expand Down
9 changes: 4 additions & 5 deletions grove/alpha/arbitrary_state/tests/test_arbitrary_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import pytest

from grove.alpha.arbitrary_state.arbitrary_state import *
from grove.pyqaoa.utils import compare_progs


@pytest.mark.skip(reason="Must add support for Forest connections in testing")
Expand Down Expand Up @@ -149,7 +148,7 @@ def test_length_four_phase_rotations(self):
.inst(CNOT(3, 0)) \
.inst(RZ(-np.pi / 4, 0))

compare_progs(reverse_prog, expected_prog)
assert reverse_prog == expected_prog

def test_length_eight_magnitude_rotations(self):
angles = [0, - np.pi / 12, np.pi / 15, -np.pi / 6,
Expand Down Expand Up @@ -177,14 +176,14 @@ def test_length_eight_magnitude_rotations(self):
.inst(RY(np.pi / 12, 4)) \
.inst(CNOT(1, 4))

compare_progs(reverse_prog, expected_prog)
assert reverse_prog == expected_prog


def _state_generation_test_helper(v, qubits=None):
# encode vector in quantum state
p = create_arbitrary_state(v, qubits)
qvm = SyncConnection()
wf, _ = qvm.wavefunction(p)
qvm = QVMConnection()
wf = qvm.wavefunction(p)

# normalize and pad with zeros
v_norm = v / np.linalg.norm(v)
Expand Down
2 changes: 1 addition & 1 deletion grove/alpha/phaseestimation/phase_estimation.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def phase_estimation(U, accuracy, reg_offset=0):

if __name__ == '__main__':
import pyquil.api as api
qvm = api.SyncConnection()
qvm = api.QVMConnection()
X = np.asarray([[0.0, 1.0], [1.0, 0.0]])
Y = np.asarray([[0.0, -1.0j], [1.0j, 0.0]])
Rx = np.exp(X * np.pi / 8)
Expand Down
2 changes: 1 addition & 1 deletion grove/amplification/grover.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def find_bitstring(self, cxn, bitstring_map):
In particular, this will prepare an initial state in the uniform superposition over all bit-
strings, an then use Grover's Algorithm to pick out the desired bitstring.
:param JobConnection cxn: the connection to the Rigetti cloud to run pyQuil programs.
:param QVMConnection cxn: the connection to the Rigetti cloud to run pyQuil programs.
:param bitstring_map: a mapping from bitstrings to the phases that the oracle should impart
on them. If the oracle should "look" for a bitstring, it should have a ``-1``, otherwise
it should have a ``1``.
Expand Down
7 changes: 2 additions & 5 deletions grove/deutsch_jozsa/deutsch_jozsa.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import numpy as np
import pyquil.quil as pq
from pyquil.gates import X, H, CNOT
from pyquil.job_results import wait_for_job


SWAP_MATRIX = np.array([[1, 0, 0, 0],
Expand All @@ -46,18 +45,16 @@ def is_constant(self, cxn, bitstring_map):
or balanced. Constant means all inputs map to the same value, balanced means half of the
inputs maps to one value, and half to the other.
:param JobConnection cxn: The connection object to the Rigetti cloud to run pyQuil programs.
:param QVMConnection cxn: The connection object to the Rigetti cloud to run pyQuil programs.
:param bitstring_map: A dictionary whose keys are bitstrings, and whose values are bits
represented as strings.
:type bistring_map: Dict[String, String]
:return: True if the bitstring_map represented a constant function, false otherwise.
:rtype: bool
"""
self._init_attr(bitstring_map)
job_result = wait_for_job(cxn.run_and_measure(self.deutsch_jozsa_circuit,
self.computational_qubits))
returned_bitstring = cxn.run_and_measure(self.deutsch_jozsa_circuit, self.computational_qubits)
# We are only running a single shot, so we are only interested in the first element.
returned_bitstring = job_result.result['result'][0]
bitstring = np.array(returned_bitstring, dtype=int)
constant = all([bit == 0 for bit in bitstring])
return constant
Expand Down
2 changes: 1 addition & 1 deletion grove/ising/ising_qaoa.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from scipy.optimize import minimize
import numpy as np

CXN = api.SyncConnection()
CXN = api.QVMConnection()


def energy_value(h, J, sol):
Expand Down
2 changes: 1 addition & 1 deletion grove/pyqaoa/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ us |beta,gamma> and evaluate the wave function using the **qvm**
t = np.hstack((inst.betas, inst.gammas))
param_prog = inst.get_parameterized_program()
prog = param_prog(t)
wf, _ = qvm_connection.wavefunction(prog)
wf = qvm_connection.wavefunction(prog)
wf = wf.amplitudes
```

Expand Down
2 changes: 1 addition & 1 deletion grove/pyqaoa/maxcut_qaoa.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import networkx as nx
from scipy.optimize import minimize
from grove.pyqaoa.qaoa import QAOA
CXN = api.SyncConnection()
CXN = api.QVMConnection()


def print_fun(x):
Expand Down
2 changes: 1 addition & 1 deletion grove/pyqaoa/numpartition_qaoa.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import pyquil.api as api
from scipy.optimize import minimize
from grove.pyqaoa.qaoa import QAOA
CXN = api.SyncConnection()
CXN = api.QVMConnection()


def numpart_qaoa(asset_list, A=1.0, minimizer_kwargs=None, steps=1):
Expand Down
2 changes: 1 addition & 1 deletion grove/pyqaoa/qaoa.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ def probabilities(self, angles):

param_prog = self.get_parameterized_program()
prog = param_prog(angles)
wf, _ = self.qvm.wavefunction(prog)
wf = self.qvm.wavefunction(prog)
wf = wf.amplitudes.reshape((-1, 1))
probs = np.zeros_like(wf)
for xx in range(2 ** self.n_qubits):
Expand Down
24 changes: 0 additions & 24 deletions grove/pyqaoa/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@
# limitations under the License.
##############################################################################

from pyquil.quil import Program


def isclose(a, b, rel_tol=1e-10, abs_tol=0.0):
"""
Expand All @@ -27,25 +25,3 @@ def isclose(a, b, rel_tol=1e-10, abs_tol=0.0):
:return: Boolean telling whether or not the parameters are close enough to be the same
"""
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)


def compare_progs(test, reference):
"""
Compares two programs gate by gate, param by param.
:param Program test: Test program
:param Program reference: Reference program
"""
tinstr = test.actions
rinstr = reference.actions
assert len(tinstr) == len(rinstr)
for idx in range(len(tinstr)):
# check each field of the instruction object
assert tinstr[idx][1].operator_name == rinstr[idx][1].operator_name
assert len(tinstr[idx][1].parameters) == len(rinstr[idx][1].parameters)
for pp in range(len(tinstr[idx][1].parameters)):
cmp_val = isclose(tinstr[idx][1].parameters[pp], rinstr[idx][1].parameters[pp])
assert cmp_val

assert len(tinstr[idx][1].arguments) == len(rinstr[idx][1].arguments)
for aa in range(len(tinstr[idx][1].arguments)):
assert tinstr[idx][1].arguments[aa] == rinstr[idx][1].arguments[aa]
4 changes: 2 additions & 2 deletions grove/pyvqe/vqe.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def vqe_run(self, variational_state_evolve, hamiltonian, initial_params,
models will be ineffective""")

if qvm is None:
qvm = api.SyncConnection(
qvm = api.QVMConnection(
gate_noise=gate_noise,
measurement_noise=measurement_noise)
else:
Expand Down Expand Up @@ -211,7 +211,7 @@ def expectation(pyquil_prog, pauli_sum, samples, qvm):
"""
if isinstance(pauli_sum, np.ndarray):
# debug mode by passing an array
wf, _ = qvm.wavefunction(pyquil_prog)
wf = qvm.wavefunction(pyquil_prog)
wf = np.reshape(wf.amplitudes, (-1, 1))
average_exp = np.conj(wf).T.dot(pauli_sum.dot(wf)).real
return average_exp
Expand Down
5 changes: 3 additions & 2 deletions grove/qft/fourier.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,11 @@ def inverse_qft(qubits):
qft_result = pq.Program().inst(_core_qft(qubits, -1))
qft_result += bit_reversal(qubits)
inverse_qft = pq.Program()
while len(qft_result.actions) > 0:
new_inst = qft_result.actions.pop()[1]
while len(qft_result) > 0:
new_inst = qft_result.pop()
inverse_qft.inst(new_inst)
return inverse_qft


if __name__ == '__main__':
print(qft([0, 1, 2, 3]))
2 changes: 1 addition & 1 deletion grove/simon/simon.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ def find_mask(self, cxn, bitstring_map):
"""
Runs Simon's mask_array algorithm to find the mask.
:param JobConnection cxn: the connection to the Rigetti cloud to run pyQuil programs
:param QVMConnection cxn: the connection to the Rigetti cloud to run pyQuil programs
:param Dict[String, String] bitstring_map: a truth table describing the boolean function,
whose period is to be found.
Expand Down

0 comments on commit 2824101

Please sign in to comment.