def test_measure_all_noncontig(): prog = Program(H(0), H(10)) prog.measure_all() assert prog.out() == "\n".join([ "H 0", "H 10", "DECLARE ro BIT[11]", "MEASURE 0 ro[0]", "MEASURE 10 ro[10]", "" ])
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 MagicNBall(N): """ Takes N, number of options and creates required number of Qubits into a super position and returns an integer out of the number of possible combinations of N. Example N=5, returns a number {0, 1, 2, 3, 4}. """ # We can only deal with 2^nQubits possibilities, so this places limits on N. r = math.log(N) / math.log(2) nQubits = int(r) if r > int(r): nQubits += 1 # Now create the required number of qubits in the correct initial Hadamard State using the H gate. Each qubit is specified by i up to the nQubits. p = Program() for i in range(0, nQubits): p += Program(H(i)) p.measure_all() result = quantum_simulator.run(p) option = sum([result[0][i] * 2**i for i in range(0, nQubits)]) # Deal with the addition options over specified N print("Number of Qubits: ", nQubits) print("Number of Quantum possibilities: ", 2**nQubits) print("Number of possibilities you chose: ", N) return option % N
def build_circuit(self, qubit_ops): program = Program() self.qubits = [program.alloc() for _ in range(len(qubit_ops))] program_readout_reg = program.declare("ro", memory_type="BIT", memory_size=len(self.qubits)) for qb, gatestr in zip(self.qubits, qubit_ops): if gatestr == "I": pass elif gatestr == "X": program.gate("X", qubits=[qb], params=[]) elif gatestr == "H": program.gate("H", qubits=[qb], params=[]) elif gatestr == "K": # our one char CX label program.gate( "CNOT", qubits=[self.qubits[self.qubits.index(qb) - 1], qb], params=[]) program.measure_all(*zip(self.qubits, program_readout_reg)) program = address_qubits(program) program.wrap_in_numshots_loop(shots=10) self.program = program
def test_measure_all_noncontig(): prog = Program( H(0), H(10), ) prog.measure_all() assert prog.out() == '\n'.join([ 'H 0', 'H 10', 'DECLARE ro BIT[11]', 'MEASURE 0 ro[0]', 'MEASURE 10 ro[10]', '', ])
def test_measure_all(): p = Program() mem = p.declare("ro", memory_size=4) p.measure_all((0, mem[0]), (1, mem[1]), (2, mem[3])) assert p.out( ) == "DECLARE ro BIT[4]\nMEASURE 0 ro[0]\nMEASURE 1 ro[1]\nMEASURE 2 ro[3]\n" p = Program([H(idx) for idx in range(4)]) p.measure_all() for idx in range(4): assert p[idx + 5] == MEASURE(idx, MemoryReference("ro", idx)) p = Program() p.measure_all() assert p.out() == ""
def test_measure_all(): p = Program() p.measure_all((0, 0), (1, 1), (2, 3)) assert p.out() == 'MEASURE 0 [0]\n' \ 'MEASURE 1 [1]\n' \ 'MEASURE 2 [3]\n' p = Program([H(idx) for idx in range(4)]) p.measure_all() for idx in range(4): assert p[idx + 4] == MEASURE(idx, idx) p = Program() p.measure_all() assert p.out() == ''
def test_measure_all(): p = Program() p.measure_all((0, 0), (1, 1), (2, 3)) assert p.out() == 'DECLARE ro BIT[4]\n' \ 'MEASURE 0 ro[0]\n' \ 'MEASURE 1 ro[1]\n' \ 'MEASURE 2 ro[3]\n' p = Program([H(idx) for idx in range(4)]) p.measure_all() for idx in range(4): assert p[idx + 5] == MEASURE(idx, idx) p = Program() p.measure_all() assert p.out() == ''
def test_measure_all(): p = Program() p.measure_all((0, 0), (1, 1), (2, 3)) assert p.out() == 'MEASURE 0 [0]\n' \ 'MEASURE 1 [1]\n' \ 'MEASURE 2 [3]\n'
from pyquil.api import QVMConnection from pyquil.gates import H from functools import reduce import math qvm = QVMConnection() n = float(input('N: ')) sides = math.ceil(math.log(n, 2)) gates = [] for i in range(0, sides): gates.append(H(i)) dice = Program(gates) roll_dice = dice.measure_all() dice_value = n + 1 while dice_value > n: result = qvm.run(roll_dice) dice_value = reduce(lambda x, y: 2 * x + y, result[0], 0) + 1 print("Quantum roll:", dice_value) ''' # Testing to see if truly N-sided die num_dict = {} for i in range (0, 10000): # print ("Attempt #", i) dice_value = n + 1 while dice_value > n: result = qvm.run(roll_dice)
from pyquil.quil import Program from pyquil.gates import * from pyquil import get_qc outcomes = {'heads': 1, 'tails': 0} p = Program() ro = p.declare('ro', 'BIT', 1) p += H(0) p += MEASURE(0, ro[0]) qc = get_qc('1q-qvm') exe = qc.compile(p) print("Guess the outcome!\n") coin_toss = p.measure_all() guess = input("heads or tails?") result = qc.run(exe) try: if (result == outcomes[guess]): print("Your guessed right!!\n") else: print("Oops! Wrong guess") except: pass
class Game(object): """ Holds the players, the gate-deck. Manages turns, checking up on player state. Instantiates with certain paramaters: how many players, how many bits per player, how is the game started, etc. """ deckContents = [['H',4],['CNOT',2],['X',2],['SWAP',2],['MEASURE',2]] numPlayers = 2 numOfBits = 4 #number of bits, to be divided amongst the players. start = '0' #What operation to start each bit with deal = 'Random' #'Random' or 'Identical' longLineSuppress = True #Supress wavefunctions and state probabilites if more than 4 bits. def __init__(self): if self.numOfBits % self.numPlayers != 0: raise ValueError("numOfBits must be evenly divisible by numPlayers") self.theGame = Program() #Create the deck self.deck = self.makeDeck() self.handSize = int(len(self.deck)/self.numPlayers) #Initialize the bits to be used in the game. if self.start == 'H': #Start every player with every state being equally likely. for bit in range(self.numOfBits): self.theGame.inst(sg['H'](bit)) elif self.start == '0': #Start every player with all bits zero. for bit in range(self.numOfBits): self.theGame.inst(sg['MEASURE'](bit,0)) elif self.start == '1': #Start every player with all bits one. for bit in range(self.numOfBits): self.theGame.inst(sg['X'](bit)) elif self.start == 'Random': #Start every player with all bits having a random gate applied from the deck. for bit in range(self.numOfBits): randGateFunc = rd.choice(self.deck) try: randGate = randGateFunc(bit) if str(randGate).split()[0] == 'MEASURE': self.theGame.inst(randGateFunc(bit)(0)) else: self.theGame.inst(randGate) except: self.theGame.inst(randGateFunc(bit,(bit+1)%self.numOfBits)) #Initialize the players self.players = [Player(i+1,self.deck,self.handSize) for i in range(self.numPlayers)] #Start the Game! self.playGame() def makeDeck(self): """Creates the deck for the game based on deckContents""" deckList = self.deckContents.copy() for i in range(len(deckList)): if len(deckList[i]) == 2: #No parameters for the gate deckList[i] = [sg[deckList[i][0]],deckList[i][1]] elif len(deckList[i]) == 3: #1 parameter for the gate deckList[i] = [sg[deckList[i][0]](deckList[i][1]),deckList[i][2]] deck = [] for g,num in deckList: deck += [g]*num if (self.deal == 'Random'): if (len(deck) % self.numPlayers != 0): raise ValueError("Length of deck must be evenly divisible by numPlayers") rd.shuffle(deck) return deck 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 playerHasCards(self): """Returns true iff there exists a player with a non-empty hand""" for player in self.players: if player.hand != []: return True return False def displayState(self): qvm = QVMConnection() wf = qvm.wavefunction(self.theGame) probs = wf.probabilities() if self.numOfBits <= 4 or not self.longLineSuppress: #Avoids printing long wavefunctions. print('Wavefunction:',wf) print('State Probabilities:',[round(i,2) for i in probs]) print('Win Probabilities:', self.winProbabilities(probs)) def winProbabilities(self, probs): """Displays the probabilites that each player will win based on the current wavefunction""" winProbs = [0 for i in range(self.numPlayers + 1)] #the last entry is probability of draw for prob,bits in zip(probs,it.product([0,1],repeat=self.numOfBits)): winners = self.checkWinner(bits) if len(winners) != 1: winProbs[-1] += prob else: winProbs[winners[0]] += prob winProbs = [round(i,3) for i in winProbs] return winProbs def checkWinner(self,bitList): #grouper method from https://docs.python.org/3/library/itertools.html#itertools-recipes def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" args = [iter(iterable)] * n return it.zip_longest(*args, fillvalue=fillvalue) totals = [0 for i in range(self.numPlayers)] groupedBits = list(grouper(bitList,int(self.numOfBits/self.numPlayers))) for groupedBitsIndex in range(len(groupedBits)): totals[groupedBitsIndex] = sum(groupedBits[groupedBitsIndex]) maxScore = max(totals) winners = [] while maxScore in totals: winners.append(totals.index(maxScore)) totals.remove(maxScore) return winners
def randomq(): circ = Program(H(0), H(1), H(2), H(3)) mes = circ.measure_all() result = qvm.run(mes) value = reduce(lambda x, y: 2 * x + y, result[0], 0) return value