# Measure all of the qubits in the standard basis for i in range(5): ghz.measure(q[i], c[i]) # Create a Bell state bell.h(q[0]) bell.cx(q[0], q[1]) bell.barrier() bell.measure(q[0], c[0]) bell.measure(q[1], c[1]) print(ghz.qasm()) print(bell.qasm()) ############################################################### # Set up the API and execute the program. ############################################################### result = qp.set_api(Qconfig.APItoken, Qconfig.config["url"]) if not result: print("Error setting API") sys.exit(1) qp.compile(["bell"], device='local_qasm_simulator', shots=1024) qp.compile(["ghz"], device='simulator', shots=1024, coupling_map=coupling_map) qp.run() print(qp.get_counts("bell")) # returns error, don't do this print(qp.get_counts("bell", device="local_qasm_simulator")) print(qp.get_counts("ghz"))
for j in range(n): qc.measure(b[j], ans[j]) qc.measure(cout[0], ans[n]) ############################################################### # Set up the API and execute the program. ############################################################### result = qp.set_api(Qconfig.APItoken, Qconfig.config["url"]) if not result: print("Error setting API") sys.exit(1) # First version: not compiled result = qp.execute(["rippleadd"], device=device, coupling_map=None, shots=1024) print(result) print(qp.get_counts("rippleadd")) # Second version: compiled to 2x8 array coupling graph qp.compile(["rippleadd"], device=device, coupling_map=coupling_map, shots=1024) # qp.print_execution_list(verbose=True) result = qp.run() print(result) print(qp.get_compiled_qasm("rippleadd")) print(qp.get_counts("rippleadd")) # Both versions should give the same distribution
qCircuit.cz(qRegister[1], qRegister[2]) # Now, we apply the H-gate to all the qubits again. for i in range(n): qCircuit.h(qRegister[i]) # That's it for this algorithm! Measure the qubits into the classical registers. # For a constant function, we expect a 100% chance of observing all 0s. (if simulated) # For a balanced function, we expect anything else. # This means that when we examine the probability of measuring all 0s, we get 1 for a constant # function (due to constructive interference) and 0 for a balanced function (destructed interference). # This is a deterministic algorithm. # The math behind this algorithm is on IBM's QX Full user guide: # https://quantumexperience.ng.bluemix.net/qx/tutorial?sectionId=8443c4f713521c10b1a56a533958286b&pageIndex=3 # The biggest resource that helped my understand constructive/destructive interference in the algorithm was this video: # https://www.youtube.com/watch?v=mGqyzZ-fnnY # This algorithm can evaluate the function in one call, which is exponentially faster than # a classical computer's 2^(n-1) + 1. qCircuit.measure(qRegister[0], cRegister[0]) qCircuit.measure(qRegister[1], cRegister[1]) qCircuit.measure(qRegister[2], cRegister[2]) device = 'ibmqx_qasm_simulator' # Backend to execute your program, in this case it is the online simulator circuits = ["qCircuit"] # Group of circuits to execute qProgram.compile(circuits, "local_qasm_simulator") # Compile your program # Run your program in the device and check the execution result every 2 seconds result = qProgram.run(wait=2, timeout=240) print(qProgram.get_counts("qCircuit"))
def playGame(device, shipPos): gameOver = False bombPos = [ [0, 0, 0, 0, 0], [0, 0, 0, 0, 0] ] grid = [0, 0] gameOver = False while (not gameOver): bombShip(0, bombPos) bombShip(1, bombPos) for player in range(2): print("Measuring damage to Player " + str(player + 1) + "...") Q_SPECS = { "circuits": [{ "name": "gridScript", "quantum_registers": [{ "name": "q", "size": 5 }], "classical_registers": [{ "name": "c", "size": 5 }]}], } Q_program = QuantumProgram(specs=Q_SPECS) gridScript = Q_program.get_circuit("gridScript") q = Q_program.get_quantum_registers("q") c = Q_program.get_classical_registers("c") for position in range(5): for hit in range(bombPos[(player + 1) % 2][position]): for ship in range(3): if (position == shipPos[player][ship]): frac = 1/(ship + 1) gridScript.u3(frac * math.pi, 0.0, 0.0, q[position]) for qubit in range(5): gridScript.measure(q[qubit], c[qubit]) Q_program.set_api(Qconfig.APItoken, Qconfig.config["url"]) Q_program.execute(["gridScript"], device, SHOTS, wait=2, timeout=60) grid[player] = Q_program.get_counts("gridScript") if (('Error' in grid[0].values()) or ('Error' in grid[1].values())): print("\nThe process timed out. Try this round again.\n") else: damage = calculateDamageToShips(grid) displayBoards(damage) for player in range(2): if ( damage[player][shipPos[player][0]] > 0.95 and damage[player][shipPos[player][1]] > 0.95 and damage[player][shipPos[player][2]] > .95 ): print("All ships on Player " + str(player) + "'s board are destroyed! \n") gameOver = True if (gameOver): print("Game Over")
def runGame(): # this function runs the game! print("\n\n\n\n\n\n\n\n") print( " ██████╗ ██╗ ██╗ █████╗ ███╗ ██╗████████╗██╗ ██╗███╗ ███╗ " ) print( " ██╔═══██╗██║ ██║██╔══██╗████╗ ██║╚══██╔══╝██║ ██║████╗ ████║ " ) print( " ██║ ██║██║ ██║███████║██╔██╗ ██║ ██║ ██║ ██║██╔████╔██║ " ) print( " ██║▄▄ ██║██║ ██║██╔══██║██║╚██╗██║ ██║ ██║ ██║██║╚██╔╝██║ " ) print( " ╚██████╔╝╚██████╔╝██║ ██║██║ ╚████║ ██║ ╚██████╔╝██║ ╚═╝ ██║ " ) print( " ╚══▀▀═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ " ) print("") print( " ██████╗ █████╗ ████████╗████████╗██╗ ███████╗███████╗██╗ ██╗██╗██████╗ ███████╗" ) print( " ██╔══██╗██╔══██╗╚══██╔══╝╚══██╔══╝██║ ██╔════╝██╔════╝██║ ██║██║██╔══██╗██╔════╝" ) print( " ██████╔╝███████║ ██║ ██║ ██║ █████╗ ███████╗███████║██║██████╔╝███████╗" ) print( " ██╔══██╗██╔══██║ ██║ ██║ ██║ ██╔══╝ ╚════██║██╔══██║██║██╔═══╝ ╚════██║" ) print( " ██████╔╝██║ ██║ ██║ ██║ ███████╗███████╗███████║██║ ██║██║██║ ███████║" ) print( " ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝╚══════╝╚══════╝╚═╝ ╚═╝╚═╝╚═╝ ╚══════╝" ) print("") print( " ___ ___ _ _ " ) print( " | _ ) _ _ | \ ___ __ ___ __| | ___ | |__ _ _ " ) print( " | _ \| || | | |) |/ -_)/ _|/ _ \/ _` |/ _ \| / /| || |" ) print( " |___/ \_, | |___/ \___|\__|\___/\__,_|\___/|_\_\ \_,_|" ) print( " |__/ " ) print("") print("") print("") print( " Learn how to make your own game for a quantum computer at decodoku.com" ) print("") print("") print("") print( " =====================================================================================" ) print("") print("") input("> Press Enter to continue...") print("") print("") print(" HOW TO PLAY") print("") print("Quantum Battleships is a game of two players.") print("") print("Both players have a grid with 5 positions, labelled 0 to 4.") print("") print(" 4 0") print(" |\ /|") print(" | \ / |") print(" | \ / |") print(" | 2 |") print(" | / \ |") print(" | / \ |") print(" |/ \|") print(" 3 1") print("") input("> Press Enter to continue...") print("") print("") print("") print("The players start by placing 3 ships on their own grid.") print("") print("Each ship takes up a single position") print("") print( "The first ship placed by each player is the weakest. It can be destroyed by a single bomb." ) print("") print( "Two bombs are needed to destroy the second ship, and three bombs for the third." ) print("") input("> Press Enter to continue...") print("") print("") print("") print( "The players take it in turns to bomb a position on their opponent's grid." ) print("") print("If a ship is hit, the amount of damage is shown.") print("") print( "Once a player destroys all their opponent's ships, the game is over.") print("") input("> Press Enter to start setting up the game...") # we'll start by checking the device status # it seems that this needs a program to be set up, which is a bit of a pain # probably there's a better way, but this is how we are doing it print("") QPS_SPECS = { "name": "program-name", "circuits": [{ "name": "circuitName", "quantum_registers": [{ "name": "qname", "size": 3 }], "classical_registers": [{ "name": "cname", "size": 3 }] }] } temp_program = QuantumProgram(specs=QPS_SPECS) apiconnection = temp_program.set_api(Qconfig.APItoken, Qconfig.config["url"]) deviceStatus = temp_program.get_device_status('ibmqx2') print("") print("") print( " =====================================================================================" ) print("") print("") print(" CHOOSE YOUR DEVICE") print("") # note that device should be 'ibmqx_qasm_simulator', 'ibmqx2' or 'local_qasm_simulator' if (deviceStatus['available']): d = input( "> Do you want to play on the real quantum computer? (y/n)\n") if ((d == "y") | (d == "Y")): device = 'ibmqx2' else: device = 'local_qasm_simulator' print("\nYou've chosen not to use a real quantum device") else: device = 'local_qasm_simulator' print("The real quantum computer is currently unavailable") if (device == 'ibmqx2'): print("\nGreat choice!") print("The device is in IBM's Thomas J. Watson Research Center.") print("We'll send jobs to it and receive results via the internet.\n") else: print("Instead we'll get this computer to simulate one.") print("We can do this only because current quantum devices are small.") print( "Soon we'll build ones that even a planet sized supercomputer could not simulate!\n" ) # while we are at it, let's set the number of shots shots = 1024 # and also populate the wait text wait_text = setText() inputString = input( "> Press Enter to start placing ships, or press R to restart the game...\n" ) # if we chose to restart, we do that if ((inputString == "r") | (inputString == "R")): return print("") print("") print(" PLACE YOUR SHIPS") print("") # The variable ship[X][Y] will hold the position of the Yth ship of player X+1 shipPos = [[-1] * 3 for _ in range(2) ] # all values are initialized to the impossible position -1| # loop over both players and all three ships for each for player in [0, 1]: print("") print("PLAYER " + str(player + 1)) print("") # otherwise we ask for ship positions for ship in [0, 1, 2]: # ask for a position for each ship, and keep asking until a valid answer is given choosing = True while (choosing): # get player input position = getpass.getpass("> Choose a position for ship " + str(ship + 1) + " (0, 1, 2, 3 or 4)\n") # see if the valid input and ask for another if not if position.isdigit(): # valid answers have to be integers position = int(position) if (position in [0, 1, 2, 3, 4]) and ( not position in shipPos[player] ): # they need to be between 0 and 5, and not used for another ship of the same player shipPos[player][ship] = position choosing = False print("") elif position in shipPos[player]: print("\nYou already have a ship there. Try again.\n") else: print("\nThat's not a valid position. Try again.\n") else: print("\nThat's not a valid position. Try again.\n") # the game variable will be set to False once the game is over game = True # the variable bombs[X][Y] will hold the number of times position Y has been bombed by player X+1 bomb = [[0] * 5 for _ in range(2)] # all values are initialized to zero # the variable grid[player] will hold the results for the grid of each player grid = [{}, {}] round = 0 # counter for rounds text_start = 0 # counter for wait_text while (game): round += 1 inputString = input("> Press Enter to start round " + str(round) + ", or press R to restart the game...\n") # if we chose to restart, we do that if ((inputString == "r") | (inputString == "R")): return print("") print("") print(" ROUND " + str(round) + ": CHOOSE WHERE TO BOMB") print("") # ask both players where they want to bomb for player in range(2): print("") print("PLAYER " + str(player + 1)) print("") # keep asking until a valid answer is given choosing = True while (choosing): # get player input position = input( "> Choose a position to bomb (0, 1, 2, 3 or 4)\n") # see if this is a valid input. ask for another if not if position.isdigit(): # valid answers have to be integers position = int(position) if position in range( 5 ): # they need to be between 0 and 5, and not used for another ship of the same player bomb[player][position] = bomb[player][position] + 1 choosing = False print("\n") else: print("\nThat's not a valid position. Try again.\n") else: print("\nThat's not a valid position. Try again.\n") print("") print("") print(" LET THE BOMBING BEGIN!") print("") if device == 'ibmqx2': message = "\n> Press Enter to get the quantum computer to calculate what happens when the bombs hit,\nor press R to restart the game...\n" else: message = "\n> Press Enter to simulate what happens when the bombs hit, or press R to restart the game...\n" inputString = input(message) # if we chose to restart, we do that if ((inputString == "r") | (inputString == "R")): return # now we create and run the quantum programs that implement this on the grid for each player for player in range(2): # create a dictionary with the specifications of the program # we'll use all 5 qubits and bits, to avoid bugs on IBM's end Q_SPECS = { "circuits": [{ "name": "gridScript", "quantum_registers": [{ "name": "q", "size": 5 }], "classical_registers": [{ "name": "c", "size": 5 }] }], } if device == 'ibmqx2': print( "\nWe'll now get the quantum computer to see what happens to Player " + str(player + 1) + "'s ships.\n") else: print("\nWe'll now simulate what happens to Player " + str(player + 1) + "'s ships.\n") # create the program with these specs Q_program = QuantumProgram(specs=Q_SPECS) # get the circuit by name gridScript = Q_program.get_circuit("gridScript") # get the quantum register by name q = Q_program.get_quantum_registers("q") # get the classical register by name c = Q_program.get_classical_registers("c") # add the bombs (of the opposing player) for position in range(5): # add as many bombs as have been placed at this position for n in range(bomb[(player + 1) % 2][position]): # the effectiveness of the bomb # (which means the quantum operation we apply) # depends on which ship it is for ship in [0, 1, 2]: if (position == shipPos[player][ship]): frac = 1 / (ship + 1) # add this fraction of a NOT to the QASM gridScript.u3(frac * math.pi, 0.0, 0.0, q[position]) #finally, measure them for position in range(5): gridScript.measure(q[position], c[position]) # to see what the quantum computer is asked to do, we can print the QASM file # this lines is typically commented out #print( Q_program.get_qasm("gridScript") ) # set the APIToken and API url Q_program.set_api(Qconfig.APItoken, Qconfig.config["url"]) # run the job until actual results are given dataNeeded = True while dataNeeded: try: #if(True): # compile and run the QASM runStatus = Q_program.execute(["gridScript"], device, shots, wait=2, timeout=600, wait_text=wait_text, text_start=text_start) if 'waits' in runStatus.keys(): text_start += runStatus['waits'] # extract data grid[player] = Q_program.get_counts("gridScript") if ('status' not in grid[player].keys()): dataNeeded = False else: input( "\n> This attempt at running on the quantum computer has failed\n" + "Press Enter to try again, or R to restart the game." ) if ((inputString == "r") | (inputString == "R")): return #else: except: print("\n") print("Something went wrong.\n") time.sleep(2.0) print("The quantum computer could be in maintenance.\n") time.sleep(2.0) print("Or your internet connection could be down.\n") time.sleep(2.0) print("Or some other gremlin.\n") time.sleep(2.0) print("Let's restart the game and try again.\n\n") time.sleep(2.0) return time.sleep(2.0) # we can check up on the data if we want # these lines are typically commented out #print( grid[0] ) #print( grid[1] ) # if one of the runs failed, tell the players and start the round again if (('Error' in grid[0].values()) or ('Error' in grid[1].values())): print("\nThe process timed out. Try this round again.\n") else: # look at the damage on all qubits (we'll even do ones with no ships) damage = [ [0] * 5 for _ in range(2) ] # this will hold the prob of a 1 for each qubit for each player # for this we loop over all 5 bit strings for each player for player in range(2): for bitString in grid[player].keys(): # and then over all positions for position in range(5): # if the string has a 1 at that position, we add a contribution to the damage # remember that the bit for position 0 is the rightmost one, and so at bitString[4] if (bitString[4 - position] == "1"): damage[player][ position] += grid[player][bitString] / shots # give results to players for player in [0, 1]: input("\n> Press Enter to see the results for Player " + str(player + 1) + "'s ships...") print("") print("") print("PLAYER " + str(player + 1)) print("") print("") # report damage for qubits that are ships, and which have significant damange # ideally this would be non-zero damage, but noise means that can happen for ships that haven't been hit # so we choose 10% as the threshold display = [" ? "] * 5 # loop over all qubits that are ships for position in shipPos[player]: # if the damage is high enough, display the damage if (damage[player][position] > 0.1): if (damage[player][position] > 0.9): display[position] = "100%" else: display[position] = str( int(100 * damage[player][position])) + "% " print( "Here is the percentage damage for ships that have been bombed.\n" ) print(display[4] + " " + display[0]) print(" |\ /|") print(" | \ / |") print(" | \ / |") print(" | " + display[2] + " |") print(" | / \ |") print(" | / \ |") print(" |/ \|") print(display[3] + " " + display[1]) print("\n") print("Only ships with 100% damage have been destroyed\n") # if a player has all their ships destroyed, the game is over # ideally this would mean 100% damage, but we go for 95% because of noise again if (damage[player][shipPos[player][0]] > .95) and ( damage[player][shipPos[player][1]] > .95) and (damage[player][shipPos[player][2]] > .95): print(" All Player " + str(player + 1) + "'s ships have been destroyed!") print("") game = False if (game is False): print(" GAME OVER") print("") print("") input("> Press Enter for a new game...\n")
# Insert a barrier before measurement qc.barrier() # Measure all of the qubits in the standard basis for j in range(n): qc.measure(q[j], ans[j]) qc.measure(r[j], ans[j + n]) ############################################################### # Set up the API and execute the program. ############################################################### result = qp.set_api(Qconfig.APItoken, Qconfig.config["url"]) if not result: print("Error setting API") sys.exit(1) # First version: not compiled result = qp.execute(["swapping"], device=device, coupling_map=None, shots=1024) print(qp.get_compiled_qasm("swapping")) print(qp.get_counts("swapping")) # Second version: compiled to coupling graph result = qp.execute(["swapping"], device=device, coupling_map=coupling_map, shots=1024) print(qp.get_compiled_qasm("swapping")) print(qp.get_counts("swapping")) # Both versions should give the same distribution
qc.measure(q[1], c1[0]) # Apply a correction qc.z(q[2]).c_if(c0, 1) qc.x(q[2]).c_if(c1, 1) qc.measure(q[2], c2[0]) ############################################################### # Set up the API and execute the program. ############################################################### result = qp.set_api(Qconfig.APItoken, Qconfig.config["url"]) if not result: print("Error setting API") sys.exit(1) # Experiment does not support feedback, so we use the simulator # First version: not compiled result = qp.execute(["teleport"], device=device, coupling_map=None, shots=1024) print(qp.get_counts("teleport")) # Second version: compiled to qx5qv2 coupling graph result = qp.execute(["teleport"], device=device, coupling_map=coupling_map, shots=1024) print(qp.get_compiled_qasm("teleport")) print(qp.get_counts("teleport")) # Both versions should give the same distribution
for i in range(5): qc.measure(q[i], c[i]) ############################################################### # Set up the API and execute the program. ############################################################### result = qp.set_api(Qconfig.APItoken, Qconfig.config["url"]) if not result: print("Error setting API") sys.exit(1) # First version: not compiled print("no compilation, simulator") result = qp.execute(["ghz"], device='simulator', coupling_map=None, shots=1024) print(result) print(qp.get_counts("ghz")) # Second version: compiled to qc5qv2 coupling graph print("compilation to %s, simulator" % device) result = qp.execute(["ghz"], device='simulator', coupling_map=coupling_map, shots=1024) print(result) print(qp.get_counts("ghz")) # Third version: compiled to qc5qv2 coupling graph print("compilation to %s, local qasm simulator" % device) result = qp.execute(["ghz"], device='local_qasm_simulator', coupling_map=coupling_map,