def make_bell_pair(q1, q2): """Makes a bell pair between qubits q1 and q2 """ return Program(H(q1), CNOT(q1, q2))
def test_validate_supported_quil_measure_last(): prog = Program(MEASURE(0, None), H(0)) with pytest.raises(ValueError): validate_supported_quil(prog) assert not prog.is_supported_on_qpu()
def test_validate_supported_quil_multiple_measures(): prog = Program(RESET(), H(1), Pragma("DELAY"), MEASURE(1, None), MEASURE(1, None)) with pytest.raises(ValueError): validate_supported_quil(prog)
def test_nesting_a_program_inside_itself(): p = Program(H(0)).measure(0, MemoryReference("ro", 0)) with pytest.raises(ValueError): p.if_then(MemoryReference("ro", 0), p)
def test_get_classical_addresses_from_program(): p = Program(Declare("ro", "BIT", 4), [H(i) for i in range(4)]) assert get_classical_addresses_from_program(p) == {} p += [MEASURE(i, MemoryReference("ro", i)) for i in [0, 3, 1]] assert get_classical_addresses_from_program(p) == {"ro": [0, 1, 3]}
def test_singles(): p = Program(I(0), X(0), Y(1), Z(1), H(2), T(2), S(1)) assert p.out() == 'I 0\nX 0\nY 1\nZ 1\nH 2\nT 2\nS 1\n'
def test_nesting_a_program_inside_itself(): p = Program(H(0)).measure(0, 0) with pytest.raises(ValueError): p.if_then(0, p)
penny_register = 0 if choice == 1: # You choose to flip the bit your_action = X(0) else: # You choose to do nothing your_action = I(0) prog = (Program(). inst( # the bit starts out in Heads, represented as |1> X(0), # Q puts penny in superposition of states by applying the Hadamard gate H(0), # Your action your_action, # Q again applys the Hadamard gate H(0)). # measurement measure(0, penny_register) ) result = qvm.run(prog, [0]) print(result) if result[0][0] == 1: print('Looks like Q won and you\'re lost in space') else: print('Wow!...\n How\'d you win?')
def test_trotterize(): term_one = PauliTerm("X", 0, 1.0) term_two = PauliTerm("Z", 0, 1.0) with pytest.raises(ValueError): trotterize(term_one, term_two, trotter_order=0) with pytest.raises(ValueError): trotterize(term_one, term_two, trotter_order=5) prog = trotterize(term_one, term_one) result_prog = Program().inst([H(0), RZ(2.0, 0), H(0), H(0), RZ(2.0, 0), H(0)]) assert prog == result_prog # trotter_order 1 steps 1 prog = trotterize(term_one, term_two, trotter_steps=1) result_prog = Program().inst([H(0), RZ(2.0, 0), H(0), RZ(2.0, 0)]) assert prog == result_prog # trotter_order 1 steps 2 prog = trotterize(term_one, term_two, trotter_steps=2) result_prog = Program().inst([H(0), RZ(1.0, 0), H(0), RZ(1.0, 0), H(0), RZ(1.0, 0), H(0), RZ(1.0, 0)]) assert prog == result_prog # trotter_order 2 steps 1 prog = trotterize(term_one, term_two, trotter_order=2) result_prog = Program().inst([H(0), RZ(1.0, 0), H(0), RZ(2.0, 0), H(0), RZ(1.0, 0), H(0)]) assert prog == result_prog # trotter_order 2 steps 2 prog = trotterize(term_one, term_two, trotter_order=2, trotter_steps=2) result_prog = Program().inst([H(0), RZ(0.5, 0), H(0), RZ(1.0, 0), H(0), RZ(0.5, 0), H(0), H(0), RZ(0.5, 0), H(0), RZ(1.0, 0), H(0), RZ(0.5, 0), H(0)]) assert prog == result_prog # trotter_order 3 steps 1 prog = trotterize(term_one, term_two, trotter_order=3, trotter_steps=1) result_prog = Program().inst([H(0), RZ(14.0 / 24, 0), H(0), RZ(4.0 / 3.0, 0), H(0), RZ(1.5, 0), H(0), RZ(-4.0 / 3.0, 0), H(0), RZ(-2.0 / 24, 0), H(0), RZ(2.0, 0)]) assert prog == result_prog
import json import numpy as np import pytest from unittest.mock import patch from pyquil.api import QVMConnection, QPUConnection, CompilerConnection from pyquil.api._base_connection import validate_noise_probabilities, validate_run_items from pyquil.api.qpu import append_measures_to_program from pyquil.quil import Program from pyquil.paulis import PauliTerm from pyquil.gates import CNOT, H, MEASURE, PHASE, Z, RZ, RX, CZ from pyquil.device import ISA from pyquil.quilbase import Pragma EMPTY_PROGRAM = Program() BELL_STATE = Program(H(0), CNOT(0, 1)) BELL_STATE_MEASURE = Program(H(0), CNOT(0, 1), MEASURE(0, 0), MEASURE(1, 1)) COMPILED_BELL_STATE = Program([ Pragma("EXPECTED_REWIRING", ('"#(0 1 2 3)"',)), RZ(pi / 2, 0), RX(pi / 2, 0), RZ(-pi / 2, 1), RX(pi / 2, 1), CZ(1, 0), RZ(-pi / 2, 0), RX(-pi / 2, 1), RZ(pi / 2, 1), Pragma("CURRENT_REWIRING", ('"#(0 1 2 3)"',)), Pragma("EXPECTED_REWIRING", ('"#(0 1 2 3)"',)), Pragma("CURRENT_REWIRING", ('"#(0 1 2 3)"',)), ])
def test_qpu_connection(test_device): qpu = QPUConnection(device=test_device) run_program = { "type": "multishot", "addresses": [0, 1], "trials": 2, "uncompiled-quil": "H 0\nCNOT 0 1\nMEASURE 0 [0]\nMEASURE 1 [1]\n" } run_and_measure_program = { "type": "multishot-measure", "qubits": [0, 1], "trials": 2, "uncompiled-quil": "H 0\nCNOT 0 1\nMEASURE 0 [0]\nMEASURE 1 [1]\n" } reply_program = { "type": "multishot-measure", "qubits": [0, 1], "trials": 2, "uncompiled-quil": "H 0\nCNOT 0 1\nMEASURE 0 [0]\nMEASURE 1 [1]\n", "compiled-quil": "H 0\nCNOT 0 1\nMEASURE 0 [0]\nMEASURE 1 [1]\n" } def mock_queued_response_run(request, context): assert json.loads(request.text) == { "machine": "QPU", "program": run_program, "device": "test_device" } return json.dumps({"jobId": JOB_ID, "status": "QUEUED"}) with requests_mock.Mocker() as m: m.post('https://job.rigetti.com/beta/job', text=mock_queued_response_run) m.get('https://job.rigetti.com/beta/job/' + JOB_ID, [ {'text': json.dumps({"jobId": JOB_ID, "status": "RUNNING"})}, {'text': json.dumps({"jobId": JOB_ID, "status": "FINISHED", "result": [[0, 0], [1, 1]], "program": reply_program})} ]) result = qpu.run(BELL_STATE_MEASURE, [0, 1], trials=2) assert result == [[0, 0], [1, 1]] with requests_mock.Mocker() as m: m.post('https://job.rigetti.com/beta/job', text=mock_queued_response_run) m.get('https://job.rigetti.com/beta/job/' + JOB_ID, [ {'text': json.dumps({"jobId": JOB_ID, "status": "RUNNING"})}, {'text': json.dumps({"jobId": JOB_ID, "status": "FINISHED", "result": [[0, 0], [1, 1]], "program": reply_program, "metadata": { "compiled_quil": "H 0\nCNOT 0 1\nMEASURE 0 [0]\nMEASURE 1 [1]\n", "topological_swaps": 0, "gate_depth": 2 }})} ]) job = qpu.wait_for_job(qpu.run_async(BELL_STATE_MEASURE, [0, 1], trials=2)) assert job.result().tolist() == [[0, 0], [1, 1]] assert job.compiled_quil() == Program(H(0), CNOT(0, 1), MEASURE(0, 0), MEASURE(1, 1)) assert job.topological_swaps() == 0 assert job.gate_depth() == 2 def mock_queued_response_run_and_measure(request, context): assert json.loads(request.text) == { "machine": "QPU", "program": run_and_measure_program, "device": "test_device" } return json.dumps({"jobId": JOB_ID, "status": "QUEUED"}) with requests_mock.Mocker() as m: m.post('https://job.rigetti.com/beta/job', text=mock_queued_response_run_and_measure) m.get('https://job.rigetti.com/beta/job/' + JOB_ID, [ {'text': json.dumps({"jobId": JOB_ID, "status": "RUNNING"})}, {'text': json.dumps({"jobId": JOB_ID, "status": "FINISHED", "result": [[0, 0], [1, 1]], "program": reply_program})} ]) result = qpu.run_and_measure(BELL_STATE, [0, 1], trials=2) assert result == [[0, 0], [1, 1]] with requests_mock.Mocker() as m: m.post('https://job.rigetti.com/beta/job', text=mock_queued_response_run_and_measure) m.get('https://job.rigetti.com/beta/job/' + JOB_ID, [ {'text': json.dumps({"jobId": JOB_ID, "status": "RUNNING"})}, {'text': json.dumps({"jobId": JOB_ID, "status": "FINISHED", "result": [[0, 0], [1, 1]], "program": reply_program, "metadata": { "topological_swaps": 0, "gate_depth": 2 }})} ]) job = qpu.wait_for_job(qpu.run_and_measure_async(BELL_STATE, [0, 1], trials=2)) assert job.result().tolist() == [[0, 0], [1, 1]] assert job.compiled_quil() == Program(H(0), CNOT(0, 1), MEASURE(0, 0), MEASURE(1, 1)) assert job.topological_swaps() == 0 assert job.gate_depth() == 2
_CVXPY_ERROR_LOGGED = True return cvxpy THREE_COLOR_MAP = ['#48737F', '#FFFFFF', '#D6619E'] rigetti_3_color_cm = LinearSegmentedColormap.from_list("Rigetti", THREE_COLOR_MAP[::-1], N=100) FIVE_COLOR_MAP = ['#C671A2', '#545253', '#85B5BE', '#ECE9CC', '#C671A2'] rigetti_4_color_cm = LinearSegmentedColormap.from_list("Rigetti", FIVE_COLOR_MAP[::-1], N=100) EPS = 1e-2 SEED = 137 BELL_STATE_PROGRAM = Program([H(0), H(1), CZ(0, 1), H(1)]) CNOT_PROGRAM = Program([H(1), CZ(0, 1), H(1)]) BAD_1Q_READOUT = np.array([[.9, .15], [.1, .85]]) BAD_2Q_READOUT = np.kron(BAD_1Q_READOUT, BAD_1Q_READOUT) # constants to provide optional fancy progress bars NOTEBOOK_MODE = False TRANGE = tqdm.trange def notebook_mode(m): """ Configure whether this module should assume that it is being run from a jupyter notebook. This sets some global variables related to how progress for long measurement sequences is indicated.
qubits = qpu.device.qubits() print(f'All qubits on {lattice}: {qpu.device.qubits()}') print(f'\nSelected qubits: {qubits}') p101s = [] p100s = [] phis = np.arange(n_points) * 2 * np.pi / n_points for phi in phis: print(phi) program_reset = Program(RESET()) ############### initiate state ########################### program_reset.inst(X(qubits[0])) program_reset.inst(H(qubits[2])) ########################################################### ############## Create the program ######################### ########################################################### program_reset.inst(RSWAP(qubits[:2])) program_reset.inst(RZ(phi, qubits[0])) program_reset.inst(cRSWAP(qubits[2], qubits[:2])) # Measurements ro = program_reset.declare('ro', 'BIT', len(qubits)) program_reset.inst( [MEASURE(qubit, ro[idx]) for idx, qubit in enumerate(qubits)]) program_reset.wrap_in_numshots_loop(N)
def __init__(self, qvm, qubits, steps=1, init_betas=None, init_gammas=None, embedding=None, cost_ham=None, ref_ham=None, driver_ref=None, minimizer=None, minimizer_args=None, minimizer_kwargs=None, rand_seed=None, vqe_options=None, store_basis=False): """ QAOA object. Contains all information for running the QAOA algorthm to find the ground state of the list of cost clauses. :param qvm: (Connection) The qvm connection to use for the algorithm. :param qubits: (list of ints) The number of qubits to use for the algorithm. :param steps: (int) The number of mixing and cost function steps to use. Default=1. :param init_betas: (list) Initial values for the beta parameters on the mixing terms. Default=None. :param init_gammas: (list) Initial values for the gamma parameters on the cost function. Default=None. :param embedding: (dict) Dictionary mapping logical qubits to physical qubits on the Rigetti QPU. Logical qubits must be the dict keys. :param cost_ham: list of clauses in the cost function. Must be PauliSum objects :param ref_ham: list of clauses in the mixer function. Must be PauliSum objects :param driver_ref: (pyQuil.quil.Program()) object to define state prep for the starting state of the QAOA algorithm. Defaults to tensor product of \|+> states. :param rand_seed: integer random seed for initial betas and gammas guess. :param minimizer: (Optional) Minimization function to pass to the Variational-Quantum-Eigensolver method :param minimizer_kwargs: (Optional) (dict) of optional arguments to pass to the minimizer. Default={}. :param minimizer_args: (Optional) (list) of additional arguments to pass to the minimizer. Default=[]. :param minimizer_args: (Optional) (list) of additional arguments to pass to the minimizer. Default=[]. :param vqe_options: (optinal) arguents for VQE run. :param store_basis: (optional) boolean flag for storing basis states. Default=False. """ # Randomize seed if rand_seed is not None: np.random.seed(rand_seed) # Set attributes values, considering their defaults self.qvm = qvm self.steps = steps self.qubits = qubits if embedding is not None: self.embedding = embedding self.inv_embedding = {embedding[k]: k for k in embedding.keys()} else: # create identity dictionary self.embedding = {i: i for i in qubits} self.inv_embedding = None self.nstates = 2**len(qubits) self.cost_ham = cost_ham or [] self.ref_ham = ref_ham or [] self.minimizer = minimizer or optimize.minimize self.minimizer_args = minimizer_args or [] self.minimizer_kwargs = minimizer_kwargs or { 'method': 'Nelder-Mead', 'options': { 'disp': True, 'ftol': 1.0e-2, 'xtol': 1.0e-2 } } self.betas = init_betas or np.random.uniform(0, np.pi, self.steps)[::-1] self.gammas = init_gammas or np.random.uniform(0, 2 * np.pi, self.steps) self.vqe_options = vqe_options or {} self.ref_state_prep = (driver_ref or pq.Program(*[H(i) for i in self.qubits])) if store_basis: self.states = [ np.binary_repr(i, width=len(self.qubits)) for i in range(self.nstates) ] # Check argument types if not isinstance(self.cost_ham, (list, tuple)): raise TypeError("cost_ham must be a list of PauliSum objects.") if not all([isinstance(x, PauliSum) for x in self.cost_ham]): raise TypeError("cost_ham must be a list of PauliSum objects") if not isinstance(self.ref_ham, (list, tuple)): raise TypeError("ref_ham must be a list of PauliSum objects") if not all([isinstance(x, PauliSum) for x in self.ref_ham]): raise TypeError("ref_ham must be a list of PauliSum objects") if not isinstance(self.ref_state_prep, pq.Program): raise TypeError("Please provide a pyQuil Program object " "to generate initial state.")
def test_plus_operator(): p = Program() p += H(0) p += [X(0), Y(0), Z(0)] assert len(p) == 4 assert p.out() == "H 0\nX 0\nY 0\nZ 0\n"
RX, RY, RZ, SWAP, X, QUANTUM_GATES, ) from pyquil.paulis import PauliTerm, exponentiate, sZ, sX, sI, sY from pyquil.pyqvm import PyQVM from pyquil.quil import Program from pyquil.quilatom import MemoryReference from pyquil.quilbase import Declare from pyquil.simulation._reference import ReferenceWavefunctionSimulator QFT_8_INSTRUCTIONS = [ H(7), CPHASE(1.5707963267948966, 6, 7), H(6), CPHASE(0.7853981633974483, 5, 7), CPHASE(1.5707963267948966, 5, 6), H(5), CPHASE(0.39269908169872414, 4, 7), CPHASE(0.7853981633974483, 4, 6), CPHASE(1.5707963267948966, 4, 5), H(4), CPHASE(0.19634954084936207, 3, 7), CPHASE(0.39269908169872414, 3, 6), CPHASE(0.7853981633974483, 3, 5), CPHASE(1.5707963267948966, 3, 4), H(3), CPHASE(0.09817477042468103, 2, 7),
def test_iteration(): gate_list = [H(0), Y(1), CNOT(0, 1)] program = Program(gate_list) for ii, instruction in enumerate(program): assert instruction == gate_list[ii]
def test_against_ref_hadamard(): p = Program(H(0)) qam = PyQVM(n_qubits=1, quantum_simulator_type=ReferenceWavefunctionSimulator) qam.execute(p) np.testing.assert_allclose(HADAMARD_WF, qam.wf_simulator.wf)
def test_multiple_instantiate(): p = Program() q = p.alloc() p.inst(H(q)) assert p.out() == 'H 0\n' assert p.out() == 'H 0\n'
def test_larger_qaoa_circuit(): square_qaoa_circuit = [ H(0), H(1), H(2), H(3), X(0), PHASE(0.3928244130249029, 0), X(0), PHASE(0.3928244130249029, 0), CNOT(0, 1), RZ(0.78564882604980579, 1), CNOT(0, 1), X(0), PHASE(0.3928244130249029, 0), X(0), PHASE(0.3928244130249029, 0), CNOT(0, 3), RZ(0.78564882604980579, 3), CNOT(0, 3), X(0), PHASE(0.3928244130249029, 0), X(0), PHASE(0.3928244130249029, 0), CNOT(1, 2), RZ(0.78564882604980579, 2), CNOT(1, 2), X(0), PHASE(0.3928244130249029, 0), X(0), PHASE(0.3928244130249029, 0), CNOT(2, 3), RZ(0.78564882604980579, 3), CNOT(2, 3), H(0), RZ(-0.77868204192240842, 0), H(0), H(1), RZ(-0.77868204192240842, 1), H(1), H(2), RZ(-0.77868204192240842, 2), H(2), H(3), RZ(-0.77868204192240842, 3), H(3), ] prog = Program(square_qaoa_circuit) qam = PyQVM(n_qubits=4, quantum_simulator_type=ReferenceWavefunctionSimulator) qam.execute(prog) wf = qam.wf_simulator.wf wf_true = np.array( [ 8.43771693e-05 - 0.1233845 * 1j, -1.24927731e-01 + 0.00329533 * 1j, -1.24927731e-01 + 0.00329533 * 1j, -2.50040954e-01 + 0.12661547 * 1j, -1.24927731e-01 + 0.00329533 * 1j, -4.99915497e-01 - 0.12363516 * 1j, -2.50040954e-01 + 0.12661547 * 1j, -1.24927731e-01 + 0.00329533 * 1j, -1.24927731e-01 + 0.00329533 * 1j, -2.50040954e-01 + 0.12661547 * 1j, -4.99915497e-01 - 0.12363516 * 1j, -1.24927731e-01 + 0.00329533 * 1j, -2.50040954e-01 + 0.12661547 * 1j, -1.24927731e-01 + 0.00329533 * 1j, -1.24927731e-01 + 0.00329533 * 1j, 8.43771693e-05 - 0.1233845 * 1j, ] ) np.testing.assert_allclose(wf_true, wf)
def test_inline_alloc(): p = Program() p += H(p.alloc()) assert p.out() == "H 0\n"
def test_default_wf_simulator(): qam = PyQVM(n_qubits=2) qam.execute(Program(H(0), H(1))) assert qam.wf_simulator.wf.reshape(-1).shape == (4,)
def test_inline_placeholder(): p = Program() p += H(QubitPlaceholder()) assert address_qubits(p).out() == "H 0\n"
oracle[b, b] = 1 print(oracle) #============================================================================== # Grover's Search Algorithm #============================================================================== qvm = QVMConnection() gr_prog = Program() # \psi_0: Qubits initilization qubits = list(reversed(range(N))) gr_prog.inst([I(q) for q in qubits]) #print(qvm.wavefunction(gr_prog)) # \psi_1: Apply Hadamard gates gr_prog.inst([H(q) for q in qubits]) #print(qvm.wavefunction(gr_prog)) # Define quantum oracle ORACLE_GATE_NAME = "GROVER_ORACLE" gr_prog.defgate(ORACLE_GATE_NAME, oracle) # Define inversion around the mean DIFFUSION_GATE_NAME = "DIFFUSION" diffusion = 2.0 * np.full((2**N, 2**N), 1/(2**N)) - np.eye(2**N) gr_prog.defgate(DIFFUSION_GATE_NAME, diffusion) # Number of algorithm iterations N_ITER = int(np.pi / 4 * np.sqrt(2**N)) # Loop
def test_validate_supported_quil_reset_first(): prog = Program(H(0), RESET()) with pytest.raises(ValueError): validate_supported_quil(prog) assert not prog.is_supported_on_qpu()
http://grove-docs.readthedocs.io/en/latest/qaoa.html """ from pyquil import get_qc from pyquil.quil import Program from pyquil.gates import H from pyquil.paulis import sI, sX, sZ, exponentiate_commuting_pauli_sum from pyquil.api import QVMConnection # Create a 4-node array graph: 0-1-2-3. graph = [(0, 1), (1, 2), (2, 3)] # Nodes [0, 1, 2, 3]. nodes = range(4) # Create the initial state program, a sum over all bitstrings, via Hadamards on all qubits. init_state_prog = Program([H(i) for i in nodes]) # The cost Hamiltonian is sum of the application of 0.5 * (1 - \sigma_z^i * \sigma_z^j) for all # qubit pairs (i, j). h_cost = -0.5 * sum(sI(nodes[0]) - sZ(i) * sZ(j) for i, j in graph) # The driver Hamiltonian is the sum of the application of \sigma_x^i for all qubits i. h_driver = -1. * sum(sX(i) for i in nodes) def qaoa_ansatz(gammas, betas): """ Function that returns a QAOA ansatz program for a list of angles betas and gammas. len(betas) == len(gammas) == P for a QAOA program of order P. :param list(float) gammas: Angles over which to parameterize the cost Hamiltonian.
def test_validate_supported_quil_with_pragma(): prog = Program(RESET(), H(1), Pragma("DELAY"), MEASURE(1, None)) assert prog.is_supported_on_qpu()
def test_len_nested(): p = Program(H(0)).measure(0, 0) q = Program(H(0), CNOT(0, 1)) p.if_then(0, q) assert len(p) == 8
def test_inst_gates(): p = Program() p.inst(H(0), X(1)) assert len(p) == 2 assert p.out() == "H 0\nX 1\n"
p.measure(start_index, 0) p.measure(ancilla_index, 1) p.if_then(1, X(2)) p.if_then(0, Z(2)) p.measure(end_index, 2) return p if __name__ == '__main__': qvm = forest.SyncConnection() # initialize qubit 0 in |1> teleport_demo = Program(X(0)) teleport_demo += teleport(0, 2, 1) print("Teleporting |1> state: {}".format(qvm.run(teleport_demo, [2]))) # initialize qubit 0 in |0> teleport_demo = Program() teleport_demo += teleport(0, 2, 1) print("Teleporting |0> state: {}".format(qvm.run(teleport_demo, [2]))) # initialize qubit 0 in |+> teleport_demo = Program(H(0)) teleport_demo += teleport(0, 2, 1) print("Teleporting |+> state: {}".format(qvm.run(teleport_demo, [2], 10))) print(Program(X(0)).measure(0, 0).if_then(0, Program(X(1))))