def get_points(num_bits, num_samples): # the max number we can have with the specified number of bits max_num = 2**(num_bits) - 1 qvm = QVMConnection() # create the Quill program # each Qubit is put through an H gate to put it in the Hammard state. Every # time we measure a qubit in this state, it has a 50-50 chance of being a 1 # or 0. By doing this we can generate random bits p = Program() for i in range(0, num_bits): p.inst(H(i)) # put each qubit in the Hammard state p.measure_all() # run the Quill program on the quantum virtual machine xs = qvm.run(p, trials=num_samples) # convert the list of lists of results for each trial into a list of # floating point numbers between 0-1. These will be our x coordinates xs = list(map(lambda x: bits_to_int(x) / max_num, xs)) ys = qvm.run(p, trials=num_samples) ys = list(map(lambda y: bits_to_int(y) / max_num, ys)) return zip(xs, ys)
def qvm(): try: qvm = QVMConnection(random_seed=52) qvm.run(Program(Id(0)), []) return qvm except (RequestException, UnknownApiError, QVMNotRunning, TypeError) as e: return pytest.skip("This test requires QVM connection: {}".format(e))
def cxn(): # DEPRECATED try: cxn = QVMConnection(endpoint='http://localhost:5000') cxn.run(Program(I(0), MEASURE(0, 0)), [0]) return cxn except RequestException as e: return pytest.skip("This test requires a running local QVM: {}".format(e))
def qvm(): try: qvm = QVMConnection(random_seed=52) qvm.run(Program(I(0)), []) return qvm except (RequestException, QVMNotRunning, UnknownApiError) as e: return pytest.skip("This test requires QVM connection: {}".format(e)) except QVMVersionMismatch as e: return pytest.skip("This test requires a different version of the QVM: {}".format(e))
def test_sync_run(qvm: QVMConnection): assert qvm.run(BELL_STATE_MEASURE, [0, 1], trials=2) == [[0, 0], [1, 1]] # Test range as well assert qvm.run(BELL_STATE_MEASURE, range(2), trials=2) == [[0, 0], [1, 1]] # Test no classical addresses assert qvm.run(BELL_STATE_MEASURE, trials=2) == [[0, 0], [1, 1]] with pytest.raises(ValueError): qvm.run(EMPTY_PROGRAM)
def add(a: int, b: int): qvm = QVMConnection() p = Program() # make sure the first number is the greater if a < b: t = a a = b b = t # Number of bits needed to store the sum of # numbers a and b for which bitlen(a) <= n and bitlen(b) <= n is n + 1 bitlen_a = max(bitlen(a), 1) + 1 bitlen_b = max(bitlen(b), 1) a_qubits = list(range(0, bitlen_a)) b_qubits = list(range(bitlen_a, bitlen_a + bitlen_b)) p += prep_qubits(a_qubits, a) p += prep_qubits(b_qubits, b) p += add_qubits(a_qubits, b_qubits) p.inst([MEASURE(j, i) for i, j in enumerate(a_qubits)]) result, = qvm.run(p, trials=1) return sum([k * 2**i for i, k in enumerate(result)])
def test_general(code: stabilizer_code.StabilizerCode, initial_state_prep: Program, error_prog: Program, num_trials: int, inverse_initial_state_prep_param=None): qvm = QVMConnection() # find inverse of initial state prep to be applied at end before measurement if inverse_initial_state_prep_param == None: inverse_initial_state_prep = Program() for instruction in reversed(initial_state_prep): # inverse gate instruction_name = (str(instruction).split())[0] if instruction_name in ['I', 'X', 'Y', 'Z', 'H', 'CNOT', 'CZ']: new_instruction_name = instruction_name else: new_instruction_name = 'DAGGER ' + instruction_name new_instruction_qubits = [str(q.index) for q in instruction.qubits] inverse_initial_state_prep += Program( ' '.join([new_instruction_name] + new_instruction_qubits)) else: inverse_initial_state_prep = inverse_initial_state_prep_param prog = initial_state_prep + code.encoding_program + error_prog + \ code.decoding_program + inverse_initial_state_prep prog.measure_all() measured_bits = np.array(qvm.run(prog, trials=num_trials)) decoded_msg_bits = measured_bits[:, :code.k] # part which contains decoded qubits num_errors = np.count_nonzero(np.sum(decoded_msg_bits, axis=1)) #print('num_trials', num_trials) #print('num_errors', num_errors) return num_errors
def run_t1(qubit, filename): qvm = QVMConnection() # qc = get_qc('9q-square-qvm') model_info = get_model(filename) noisy_p = Program("NOISY-RX-PLUS-180 " + str(qubit)) noisy_p = Program(model_info) + noisy_p probabilities = [] x = [] delay_duration = 0.0 / NANO_SECOND_DENOMINATOR for t in range(NUM_STEPS): # each loop is 50 ns noisy_p_measured = noisy_p.copy().measure_all() result = np.sum(qvm.run(noisy_p_measured, trials=NUM_TRIALS)) # if (t % 10 == 0): # print("T: {} Noisy Result: {}".format(t, result)) probability = float(result) / NUM_TRIALS probabilities.append(probability) x.append(delay_duration) noisy_p = noisy_p + Program( ("NOISY-I " + str(qubit))) # apply noisy I every single loop delay_duration += 50.0 / NANO_SECOND_DENOMINATOR y_np = np.array(probabilities) x_np = np.array(x) plt.plot(x_np, y_np) opt, pcov = curve_fit(func_t1, x_np, y_np, maxfev=1000000, p0=(0.5, 1.0 / 1e-6, 0.5)) plt.plot(x_np, func_t1(x_np, *opt), 'r--') plt.show() a, k, b = opt return 1.0 / k
def quantumcomp(charlist, bytelist, explicitprinting=0, samples=1): # empty list for results for each letter res = [] # 8 bits in 1 byte bit = [None] * 8 for j in range(0, len(bytelist)): # Do quantum stuff now we have our bit string qvm = QVMConnection() prog = Program() # make 8 individual bits for the 8 qubits bit = get_binary_from_byte(bytelist[j]) print('\n#--------------------------------------------------------#') print('# Character= %s Bitstring = %s' % (charlist[j], bit)) print('#--------------------------------------------------------#') # don't what this is for... cr = [] for i in range(0, len(bit)): # do x rotation to get 1 if bit[i] == 1: prog.inst(X(i)) # measure the i-th qubit prog.measure(i, i) # store measurement outcomes, can change number of shots results = (qvm.run(prog, cr, samples)) # use list for results for each char res.append(results[0]) if explicitprinting == 1: print(compiletoquil(prog)) print('\n#--------------------------------------------------------#') print('# Result =', results[0]) print('#--------------------------------------------------------#') return res
def throw_octahedral_die(): """Throws a fair octahedral die.""" qvm = QVMConnection(random_seed=int(time.time() * 10000000)) p = Program(H(0), H(1), H(2)).measure_all() result = qvm.run(p) return bit_list_to_int(result[0]) + 1
def phase_estimation(ancillary_start, ancillary_num, time, atomic_distance, state, trails=5, trotter_order=2): """ Measures the phase by using the phase estimation algorithm (PEA) :param ancillary_start: first ancillary qubit :param ancillary_num: how many ancillaries to use corresponds to precision in PEA algorithm :param time: t in exp(-iHt), where H is the Hamiltonian :param atomic_distance: the distance between to H atoms in H2 molecule :param state: ground state (0) or some excited state (1, 2, 3) :param trails: how many measurement to make in order to estimate the most frequent result :return: the phase from exp(-iHt) |psi> = exp(-i2pi phase) |psi> (Schrodinger) """ # initialization of the state init_qubit = Program() if state == 0: init_qubit.inst(X(0)).inst(X(1)) elif state == 1: init_qubit.inst(X(0)).inst(X(2)) elif state == 2: init_qubit.inst(X(0)).inst(X(3)) elif state == 3: init_qubit.inst(X(2)).inst(X(3)) else: print( "Wrong input of state. State should be 0, 1, 2, 3. Your input is " + str(state)) raise ValueError prog = init_qubit + pea_program(ancillary_start, ancillary_num, time, atomic_distance, trotter_order) ro = prog.declare('ro', memory_type='BIT', memory_size=ancillary_num) # measurement of ancillary qubits for cindex, qindex in enumerate( range(ancillary_start, ancillary_start + ancillary_num)): prog += MEASURE(qindex, ro[cindex]) qvm = QVMConnection() cregister = list(range(0, ancillary_num)) m_reg = qvm.run(prog, cregister, trails) # taking most frequent result from the phase elements. The number of the elements are defined by the trails phase, major_index = majority_and_index( [bitstring_to_value(bitst) for bitst in m_reg]) print(str(phase) + " = " + str(m_reg[major_index])) return phase
def get_dist(program, qubits): bits = [x for x in range(len(qubits))] strs = [bin(x)[2:].zfill(len(qubits)) for x in range(2**len(qubits))] probs = [] qvm = QVMConnection() out = qvm.run(program, bits, trials=10000) for i in strs: matches = [x for x in out if string_checker(i, x)] probs.append(len(matches) / len(out)) print("String {} occurs with probability {}".format(i, probs[-1])) return probs
def grover(marked_element): # Determine number of qubits needed n = len(marked_element) N = 2**n no_marked = int(marked_element, 2) # Determine number of times to iterate T = int(round(np.pi * np.sqrt(N) / 4 - 0.5)) print('Number of iterations T =', T) # Invoking and renaming Program and Connection qvm = QVMConnection() p = Program() # Step 1: Start with qubits in equal superposition for i in range(n): p.inst(H(i)) # Defining Oracle matrices: U_0 and U_f U_0 = np.eye(N) U_0[0][0] = -1 U_f = np.eye(N) U_f[no_marked][no_marked] = -1 # Defining Oracle gates p.defgate("U0", U_0) p.defgate("Uf", U_f) # Step 2: Repeat applications of U_f and D for i in range(T): # Apply U_f p.inst(("Uf", ) + tuple(range(n))) # Apply D for j in range(n): p.inst(H(j)) p.inst(("U0", ) + tuple(range(n))) for j in range(n): p.inst(H(j)) # Step 3: Measure all the qubits and output result for i in range(n): p.measure(i) # Run the program results = qvm.run(p, list(range(n)), 1) print('Element found =', results[0]) return results[0]
class QDice: def __init__(self): self.qvm = QVMConnection() def roll(self, hadamards=3, trials=1): return self.qvm.run(self.magic(hadamards=hadamards).measure_all(), trials=trials) def magic(self, hadamards=3): return P(*list(map(lambda i: H(i), range(hadamards)))) @staticmethod def number(roll): return 1 + reduce(lambda i, j: 2 * i + j, roll)
class QColor: def __init__(self, simulate=False): self.qvm = QVMConnection() self.sim = simulate def run(self, trials=65536, simulate=False): if self.sim: return random.random((trials, 3)).round() else: return self.qvm.run( self.rgb.measure_all(), trials=trials) @property def rgb(self): return Program(H(0), H(1), H(2))
def playGame(self): """Starts the game""" while self.playerHasCards(): for player in self.players: self.displayState() self.theGame.inst(player.turn()) self.theGame.measure_all() #print(self.theGame) qvm = QVMConnection() results = qvm.run(self.theGame) resultsRev = results[0][:] resultsRev.reverse() #So the printed results are in the same order as everything else. print('The bits were measured as: ',resultsRev) winners = self.checkWinner(results[0]) if len(winners) != 1: print("It's a draw!") else: print("Player " + str(winners[0]+1) + " wins!")
def deutsch_jozsa(f): # Determine number of qubits needed N = len(f) n = int(np.log2(N)) # Invoking and renaming qvm = QVMConnection() p = Program() # Applying first round of n Hadamards for i in range(n): p.inst(H(i)) # Defining the Oracle matrix U_f = np.eye(N) for i in range(N): if f[i] == '1': U_f[i][i] = -1 # Adding the Oracle matrix as a gate p.defgate("Uf", U_f) # Applying Oracle gate p.inst(("Uf", ) + tuple(range(n))) # Applying second run of n Hadamards for i in range(n): p.inst(H(i)) # Measure all the qubits and output result for i in range(n): p.measure(i, i) # Run the program classical_reg = list(range(n)) results = qvm.run(p, classical_reg, 1) y = 0 for i in range(n): y = y + 2**i * int(results[0][i]) if y == 0: print('Function is constant.') else: print('Function is balanced.')
def estimate_gradient(f_h, precision, gradient_max=1, n_measurements=50, cxn=None): """Estimate the gradient using function evaluation at perturbation, h :param float f_h: Oracle output at perturbation h. :param int precision: Bit precision of gradient. :param int gradient_max: OOM estimate of largest gradient value :param int n_measurements: Number of times to measure system. :param Connection cxn: Connection to the QPU or QVM. :return: Decimal estimate of gradient. :rtype: float """ # scale f_h by range of values gradient can take on f_h *= 1. / gradient_max # generate gradient program perturbation_sign = np.sign(f_h) p_gradient = gradient_program(f_h, precision) # run gradient program if cxn is None: from pyquil.api import QVMConnection cxn = QVMConnection() measured_qubits = list(range(precision + 1)) measurements = cxn.run(p_gradient, measured_qubits, n_measurements) # summarize measurements bf_estimate = perturbation_sign * measurements_to_bf(measurements) bf_explicit = '{0:.16f}'.format(bf_estimate) deci_estimate = binary_to_real(bf_explicit) # rescale gradient deci_estimate *= gradient_max return deci_estimate
def run_t2(qubit, filename): qvm = QVMConnection() model_info = get_model(filename) # noisy_p = Program(RX(math.pi / 2, qubit)) noisy_p = Program("NOISY-RX-PLUS-90 " + str(qubit)) noisy_p = Program(model_info) + noisy_p probabilities = [] x = [] delay_duration = 0.0 / NANO_SECOND_DENOMINATOR for t in range(NUM_STEPS): noisy_p_measured = noisy_p.copy() noisy_p_measured += Program(RZ(delay_duration * OMEGA_D, qubit)) noisy_p_measured += Program("NOISY-RX-PLUS-90 " + str(qubit)) noisy_p_measured = noisy_p_measured.measure_all() result = np.sum(qvm.run(noisy_p_measured, trials=NUM_TRIALS)) # if (t % 10 == 0): # print("T: {} Noisy Result: {}".format(t, result)) probability = float(result) / NUM_TRIALS probabilities.append(probability) x.append(delay_duration) noisy_p += Program("NOISY-I " + str(qubit)) delay_duration += 50.0 / NANO_SECOND_DENOMINATOR y_np = np.array(probabilities) x_np = np.array(x) plt.plot(x_np, y_np) opt, pcov = curve_fit(func_t2, x_np, y_np, maxfev=1000000, p0=guesses_T2[qubit]) plt.plot(x_np, func_t2(x_np, *opt), 'r--') plt.show() a, k, o, c = opt print(opt) return 1.0 / k
test_run_and_measure_empty = Program() print(test_run_and_measure_empty) result = qvm.run_and_measure(Program(), [0], 1) test_run = Program( H(0), CNOT(0, 1) ) print("test_run") result = qvm.run(test_run, [0], 1) print(result) test_run_async = Program( H(0), CNOT(0, 1) ) print("test_run_async") result = qvm.run(test_run_async, [0], 1) print(result) test_run_and_measure = Program(
program = Program() ro = program.declare('ro', 'BIT', 2 * len(curImg_bits)) #define agents alice = Alice(program, cmem=curImg_bits) bob = Bob(program) charlie = Charlie(program, qubits=qubitsUsed) eve = Eve(program) #connect agents QConnect(alice, bob, charlie, eve) #simulate agents Simulation(alice, charlie, bob, eve).run(trials=1, agent_classes=[Alice, Charlie, Bob, Eve]) results = qvm.run(program) resultsBob.extend(results[0][0:len(curImg_bits)]) resultsEve.extend(results[0][len(curImg_bits):]) start = end if end == len(img_bits): break elif len(img_bits) >= end + 20: end += 20 else: end = len(img_bits) i += 1 print("simulated: ", i) plot_images(resultsEve, resultsBob, img)
#!/usr/bin/env python3 from pyquil.quil import Program from pyquil.api import QVMConnection from pyquil.gates import X, Z, H from compile_for_pyquil import compiletoquil # Q in binary bitstring = '01010001' # Do quantum stuff now we have our bit string qvm = QVMConnection() qprog = Program() # do X on q1, q3, q7 # recall H Z H is X qprog.inst(H(1), Z(1), H(1)) qprog.inst(X(3)) qprog.inst(X(7)) # do measurement over all 8 qubits for i in range(0, 8): qprog.measure(i, i) # store measurement outcomes results = qvm.run(qprog) # show info when compiled to 8 qubit AGAVE compiletoquil(qprog) print('# Result =', results[0])
""" test program creates GHZ state with 10 qubits and sample 100 times """ from pyquil.quil import Program from pyquil.api import QVMConnection, Job from pyquil.gates import * import pyquil.paulis as paulis N_qubit = 10 N_sample = 100 qvm = QVMConnection() p = Program(H(0)) for i in range(N_qubit - 1): p += Program(CNOT(i, i + 1)) print(qvm.wavefunction(p)) print(p) classical_reg = [i for i in range(N_qubit)] for i in range(N_qubit): p.measure(i, i) result = qvm.run(p, classical_reg, trials=100) for r in result: print(r)
## Adapted from Rigetti's documentation # Program is the object that will contain our experiment from pyquil.quil import Program # QVM from pyquil.api import QVMConnection from pyquil.gates import Z, H, CNOT, MEASURE # Instantiating a new qvm instance qvm = QVMConnection() # Our program p requires 2 qubits, labeled 0 & 1 p = Program(H(0), CNOT(0, 1), MEASURE(0, 0), MEASURE(1, 1)) results = qvm.run(p, classical_addresses=[0, 1], trials=10) # Seeing the results is nice! # There are ten trials so this should return an array such that len(results) === 10. print(results) # [[1,1], [1,1], [1,1], [0,0], [1,1], [1,1], [1,1], [1,1], [1,1], [1,1]] # There's also a wavefunction representation of the program from the qvm. wavefunction = qvm.wavefunction(p) print(wavefunction) # (1+0j)|11> ## Large qubit count test p30 = Program( Z(0), Z(1), Z(2), Z(3), Z(4), Z(5),
from openfermion.utils import hermitian_conjugated from forestopenfermion import qubitop_to_pyquilpauli, pyquilpauli_to_qubitop from pyquil.quil import Program from pyquil.gates import X from pyquil.paulis import exponentiate from pyquil.api import QVMConnection hubbard_hamiltonian = FermionOperator() spatial_orbitals = 4 for i in range(spatial_orbitals): electron_hop_alpha = FermionOperator(((2*i, 1), (2*((i+1) % spatial_orbitals), 0))) electron_hop_beta = FermionOperator(((2*i+1, 1), ((2 * ((i+1) % spatial_orbitals) + 1), 0))) hubbard_hamiltonian += -1 * (electron_hop_alpha + hermitian_conjugated(electron_hop_alpha)) hubbard_hamiltonian += -1 * (electron_hop_beta + hermitian_conjugated(electron_hop_beta)) hubbard_hamiltonian += FermionOperator(((2*i, 1), (2*i, 0), (2*i+1, 1), (2*i+1, 0)), 4.0) hubbard_term_generator = jordan_wigner(hubbard_hamiltonian) pyquil_hubbard_generator = qubitop_to_pyquilpauli(hubbard_term_generator) localized_electrons_program = Program() localized_electrons_program.inst([X(0), X(1)]) pyquil_program = Program() for term in pyquil_hubbard_generator.terms: pyquil_program += exponentiate(0.1*term) print (localized_electrons_program + pyquil_program) qvm = QVMConnection() print(qvm.run(pyquil_program, [0], 10)) wf = qvm.wavefunction(pyquil_program) print(wf)
from pyquil.quil import Program from pyquil.api import QVMConnection from pyquil.gates import H, PHASE from pyquilcompiler import compiletoquil import numpy as np # Invoking and renaming qvm = QVMConnection() p = Program() # Gate implementation p.inst(H(0)) theta = np.pi / 2 p.inst(PHASE(theta, 0)) # Measurement p.measure(0, 0) p.measure(1, 1) # Running the program compiletoquil(p) cr = [] results = qvm.run(p, cr, 4) print(results)
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 for i in range(N_ITER): # \psi_2^i: Apply Quantum Oracle gr_prog.inst(tuple([ORACLE_GATE_NAME] + qubits)) #print(qvm.wavefunction(gr_prog)) # \psi_3^i: Apply Inversion around the mean gr_prog.inst(tuple([DIFFUSION_GATE_NAME] + qubits)) #print(qvm.wavefunction(gr_prog)) # \psi_5: Measure for q in qubits: gr_prog.measure(qubit_index=q, classical_reg=q) # Run ret = qvm.run(gr_prog, classical_addresses=qubits) ret_string = ''.join([str(q) for q in ret[0]]) print("The searched string is: {}".format(ret_string))
p = Program() # Prepare psi p += H(2) p += Z(2) p += RZ(1.2, 2) print("Initial Alice State: ") printWF(p) # Create Classical Memory ro = p.declare('ro', 'BIT', 3) # Create Alice, Bob, and Charlie. Give Alice qubit 2 (phi). Give Charlie qubits [0,1] (Bell State Pairs). alice = Alice(p, qubits=[2], name='alice') bob = Bob(p, name='bob') charlie = Charlie(p, qubits=[0, 1], name='charlie') # Connect agents to distribute qubits and report results QConnect(alice, charlie, bob) CConnect(alice, bob) # Run simulation Simulation(alice, bob, charlie).run(trials=1, agent_classes=[Alice, Bob, Charlie]) qvm = QVMConnection() qvm.run(p) print("Final Bob's State: ") printWF(p)
from pyquil.gates import X from pyquil.quil import Program from pyquil.api import QVMConnection p = Program() p.inst(X(0)).measure(0, 0) print(p) qvm = QVMConnection() print(qvm.run(p, [0]))
# 1. Calling Libraries from pyquil.quil import Program from pyquil.api import QVMConnection from pyquil.gates import X, CCNOT # 2. Initialising the program qvm = QVMConnection() p = Program() # 3. Applying gates p.inst(X(0),X(1),X(2)) # so here 111 p.inst(CCNOT(0,1,2)) # 4. Performing measurements p.measure(0,0) p.measure(1,1) p.measure(2,2) # 5. Executing the program results = qvm.run(p, [], 4) print(results)
# prepares the state: # |0> - |+> - |+> - |+> - |+> # where - represents CZ entanglements and |1> and |+> are as usual def prepareEntanglements(): state_prep = Program().inst(I(0), H(1), H(2), H(3), H(4), CZ(0, 1), CZ(1, 2), CZ(2, 3), CZ(3, 4)) return state_prep if __name__ == "__main__": qvm = QVMConnection() # wavefunction = qvm.wavefunction(state_prep) # print(wavefunction) trasportation = prepareEntanglements() + measureX(0) + measureX( 1) + measureX(2) + measureX(3) + correctAndMeasure(4) print(trasportation) results = qvm.run(trasportation, [0, 1, 2, 3, 4], 10) print(results) # see if it all worked out for run in results: if run[4] == 1: print("Failed") quit(1) print("Okay cool, so it looks like it is working")