def test_run_program(self): QP_program = QuantumProgram(specs=QPS_SPECS) qc = QP_program.get_circuit("circuitName") qr = QP_program.get_quantum_registers("qname") cr = QP_program.get_classical_registers("cname") qc2 = QP_program.create_circuit("qc2", ["qname"], ["cname"]) qc3 = QP_program.create_circuit("qc3", ["qname"], ["cname"]) qc2.h(qr[0]) qc3.h(qr[0]) qc2.measure(qr[0], cr[0]) qc3.measure(qr[0], cr[0]) circuits = ['qc2', 'qc3'] device = 'simulator' # the device to run on shots = 1024 # the number of shots in the experiment. credits = 3 coupling_map = None apiconnection = QP_program.set_api(API_TOKEN, URL) QP_program.compile(circuits, device, shots, credits, coupling_map) result = QP_program.run() # print(QP_program()) print(result) # TODO: Revire result self.assertEqual(result['status'], 'COMPLETED')
def test_print_program(self): QP_program = QuantumProgram(specs=QPS_SPECS) qc = QP_program.get_circuit("circuitName") qr = QP_program.get_quantum_registers("qname") cr = QP_program.get_classical_registers("cname") qc.h(qr[1]) result = QP_program.get_qasm("circuitName") self.assertEqual(len(result), 78)
def test_contact_create_circuit_multiregisters(self): QP_program = QuantumProgram(specs=QPS_SPECS) qr = QP_program.get_quantum_registers("qname") cr = QP_program.get_classical_registers("cname") qr2 = QP_program.create_quantum_registers("qr", 3) cr2 = QP_program.create_classical_registers("cr", 3) qc_result = QP_program.create_circuit(name="qc2", qregisters=["qname", "qr"], cregisters=[cr, cr2]) self.assertIsInstance(qc_result, QuantumCircuit) self.assertEqual(len(qc_result.qasm()), 90)
def test_get_individual_components(self): """ Get the program componentes, like Circuits and Registers """ QP_program = QuantumProgram(specs=QPS_SPECS) qc = QP_program.get_circuit("circuitName") qr = QP_program.get_quantum_registers("qname") cr = QP_program.get_classical_registers("cname") self.assertIsInstance(qc, QuantumCircuit) self.assertIsInstance(qr, QuantumRegister) self.assertIsInstance(cr, ClassicalRegister)
def test_contact_multiple_horizontal_circuits(self): QP_program = QuantumProgram(specs=QPS_SPECS) qc = QP_program.get_circuit("circuitName") qr = QP_program.get_quantum_registers("qname") cr = QP_program.get_classical_registers("cname") qc2 = QP_program.create_circuit(name="qc2", qregisters=["qname"], cregisters=["cname"]) qc3 = QP_program.create_circuit("qc3", ["qname"], ["cname"]) qc2.h(qr[0]) qc3.h(qr[0]) qc2.measure(qr[0], cr[0]) qc3.measure(qr[0], cr[0]) qc_result = qc2 + qc3 self.assertIsInstance(qc_result, QuantumCircuit)
def test_execute_program_simulator_online(self): QP_program = QuantumProgram(specs=QPS_SPECS) qc = QP_program.get_circuit("circuitName") qr = QP_program.get_quantum_registers("qname") cr = QP_program.get_classical_registers("cname") qc2 = QP_program.create_circuit("qc2", ["qname"], ["cname"]) qc3 = QP_program.create_circuit("qc3", ["qname"], ["cname"]) qc2.h(qr[0]) qc3.h(qr[0]) qc2.measure(qr[0], cr[0]) qc3.measure(qr[0], cr[0]) device = 'simulator' # the device to run on shots = 1 # the number of shots in the experiment. apiconnection = QP_program.set_api(API_TOKEN, URL) result = QP_program.execute(['qc2'], device, shots, max_credits=3) self.assertEqual(result["status"], "COMPLETED")
def test_compile_program(self): QP_program = QuantumProgram(specs=QPS_SPECS) qc = QP_program.get_circuit("circuitName") qr = QP_program.get_quantum_registers("qname") cr = QP_program.get_classical_registers("cname") qc.h(qr[0]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) device = 'ibmqx2' shots = 1024 credits = 3 coupling_map = None result = QP_program.compile(['circuitName'], device, coupling_map) to_test = QP_program.get_circuit('circuitName') self.assertEqual(len(to_test.qasm()), 120)
def test_create_add_gates(self): QP_program = QuantumProgram(specs=QPS_SPECS) qc = QP_program.get_circuit("circuitName") qr = QP_program.get_quantum_registers("qname") cr = QP_program.get_classical_registers("cname") qc.u3(0.3, 0.2, 0.1, qr[0]) qc.h(qr[1]) qc.cx(qr[1], qr[2]) qc.barrier() qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.z(qr[2]).c_if(cr, 1) qc.x(qr[2]).c_if(cr, 1) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) result = QP_program.get_qasm('circuitName') self.assertEqual(len(result), 348)
def test_local_unitary_simulator(self): QP_program = QuantumProgram(specs=QPS_SPECS) qc = QP_program.get_circuit("circuitName") qr = QP_program.get_quantum_registers("qname") cr = QP_program.get_classical_registers("cname") qc2 = QP_program.create_circuit("qc2", ["qname"], ["cname"]) qc3 = QP_program.create_circuit("qc3", ["qname"], ["cname"]) qc2.h(qr[0]) qc3.h(qr[0]) qc2.measure(qr[0], cr[0]) qc3.measure(qr[0], cr[0]) circuits = ['qc2', 'qc3'] device = 'local_unitary_simulator' # the device to run on shots = 1 # the number of shots in the experiment. credits = 3 coupling_map = None result = QP_program.execute(circuits, device, shots) # print(result) self.assertEqual(result['status'], 'COMPLETED')
"name": "bell", "quantum_registers": [{ "name": "q", "size": 5 }], "classical_registers": [{ "name": "c", "size": 5 }] }] } qp = QuantumProgram(specs=QPS_SPECS) ghz = qp.get_circuit("ghz") bell = qp.get_circuit("bell") q = qp.get_quantum_registers("q") c = qp.get_classical_registers("c") # Create a GHZ state ghz.h(q[0]) for i in range(4): ghz.cx(q[i], q[i + 1]) # Insert a barrier before measurement ghz.barrier() # 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])
}, { "name": "cout", "size": 1 }], "classical_registers": [ { "name": "ans", "size": n + 1 }, ] }] } qp = QuantumProgram(specs=QPS_SPECS) qc = qp.get_circuit("rippleadd") a = qp.get_quantum_registers("a") b = qp.get_quantum_registers("b") cin = qp.get_quantum_registers("cin") cout = qp.get_quantum_registers("cout") ans = qp.get_classical_registers("ans") def majority(p, a, b, c): """Majority gate.""" p.cx(c, b) p.cx(c, a) p.ccx(a, b, c) def unmajority(p, a, b, c): """Unmajority gate."""
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")