def test_create_several_circuits_noname(self): """Test create_circuit with several inputs and without names. """ q_program = QuantumProgram() qr1 = q_program.create_quantum_register(size=3) cr1 = q_program.create_classical_register(size=3) qr2 = q_program.create_quantum_register(size=3) cr2 = q_program.create_classical_register(size=3) qc1 = q_program.create_circuit(qregisters=[qr1], cregisters=[cr1]) qc2 = q_program.create_circuit(qregisters=[qr2], cregisters=[cr2]) qc3 = q_program.create_circuit(qregisters=[qr1, qr2], cregisters=[cr1, cr2]) self.assertIsInstance(qc1, QuantumCircuit) self.assertIsInstance(qc2, QuantumCircuit) self.assertIsInstance(qc3, QuantumCircuit)
def test_create_several_circuits_noname(self): """Test create_circuit with several inputs and without names. """ q_program = QuantumProgram() qr1 = q_program.create_quantum_register(size=3) cr1 = q_program.create_classical_register(size=3) qr2 = q_program.create_quantum_register(size=3) cr2 = q_program.create_classical_register(size=3) qc1 = q_program.create_circuit(qregisters=[qr1], cregisters=[cr1]) qc2 = q_program.create_circuit(qregisters=[qr2], cregisters=[cr2]) qc3 = q_program.create_circuit(qregisters=[qr1, qr2], cregisters=[cr1, cr2]) self.assertIsInstance(qc1, QuantumCircuit) self.assertIsInstance(qc2, QuantumCircuit) self.assertIsInstance(qc3, QuantumCircuit)
def test_get_qasms_noname(self): """Test the get_qasms from a qprogram without names. """ q_program = QuantumProgram() qr = q_program.create_quantum_register(size=3) cr = q_program.create_classical_register(size=3) qc1 = q_program.create_circuit(qregisters=[qr], cregisters=[cr]) qc2 = q_program.create_circuit(qregisters=[qr], cregisters=[cr]) qc1.h(qr[0]) qc1.cx(qr[0], qr[1]) qc1.cx(qr[1], qr[2]) qc1.measure(qr[0], cr[0]) qc1.measure(qr[1], cr[1]) qc1.measure(qr[2], cr[2]) qc2.h(qr) qc2.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) qc2.measure(qr[2], cr[2]) results = dict( zip(q_program.get_circuit_names(), q_program.get_qasms())) qr_name_len = len(qr.name) cr_name_len = len(cr.name) self.assertEqual(len(results[qc1.name]), qr_name_len * 9 + cr_name_len * 4 + 147) self.assertEqual(len(results[qc2.name]), qr_name_len * 7 + cr_name_len * 4 + 137)
def qrng(n): qp = QuantumProgram() quantum_r = qp.create_quantum_register("qr", n) classical_r = qp.create_classical_register("cr", n) circuit = qp.create_circuit("QRNG", [quantum_r], [classical_r]) #qp.enable_logs(logging.DEBUG); for i in range(n): circuit.h(quantum_r[i]) for i in range(n): circuit.measure(quantum_r[i], classical_r[i]) #backend='local_qasm_simulator' backend = 'ibmq_qasm_simulator' circuits = ['QRNG'] qp.set_api(Qconfig.APItoken, Qconfig.config['url']) shots = 1024 result = qp.execute(circuits, backend, shots=shots, max_credits=3, timeout=240) counts = result.get_counts('QRNG') bits = "" for v in counts.values(): if v > shots(2**n): bits += "1" else: bits += "0" return int(bits, 2)
def benchmark(): argument = int(sys.argv[1]) for line in sys.stdin: iters = int(line.strip()) # Setup start = time.perf_counter() i = 0 for x in range(iters): qp = QuantumProgram() qr = qp.create_quantum_register('qr', argument) cr = qp.create_classical_register('cr', argument) qc = qp.create_circuit('Bell', [qr], [cr]) for i in range(argument): qc.h(qr[i]) for i in range(argument): qc.measure(qr[i], cr[i]) result = qp.execute('Bell') result.get_counts('Bell') end = time.perf_counter() # Teardown delta = end - start nanos = int(delta * NANOS) print("%d" % nanos) sys.stdout.flush()
def main(): qp = QuantumProgram() #Create 1 qubit quantum_r = qp.create_quantum_register("qr",1) #Create 1 classical register classical_r = qp.create_classical_register("cr",1) #Create a circuit qp.create_circuit("Circuit", [quantum_r], [classical_r]) #Get the circuit by name circuit = qp.get_circuit('Circuit') #enable logging qp.enable_logs(logging.DEBUG); #pauliX gate circuit.x(quantum_r[0]) #measure gate from qubit 0 to classical bit 0 circuit.measure(quantum_r[0], classical_r[0]) #backend simulator backend = 'local_qasm_simulator' #circuits to execute circuits = ['Circuit'] #Compile the program qobj = qp.compile(circuits, backend) #run simulator result = qp.run(qobj, timeout=240) #Show result counts print(str(result.get_counts('Circuit')))
def twoBitsAdder(): Circuit = 'twoBitsAdderCircuit' # Create the quantum program qp = QuantumProgram() # Creating registers n_qubits = 8 qr = qp.create_quantum_register("qr", n_qubits) cr = qp.create_classical_register("cr", n_qubits) # Two-bits adder circuit, where: # qr[0|1] and qr[2|3] are adders # qr[4-5] are the result # qr[6] is the carry_out # qr[7] is the temp reg obc = qp.create_circuit(Circuit, [qr], [cr]) # Prepare bits to add obc.h(qr[0]) obc.h(qr[1]) obc.h(qr[2]) obc.h(qr[3]) # The low-bit result in qr[4] obc.cx(qr[0], qr[4]) obc.cx(qr[2], qr[4]) # The carry in temp reg obc.ccx(qr[0], qr[2], qr[7]) # The high-bit result in qr[5] obc.cx(qr[1], qr[5]) obc.cx(qr[3], qr[5]) obc.cx(qr[7], qr[5]) # The carry_out in qr[6] obc.ccx(qr[1], qr[3], qr[6]) obc.ccx(qr[1], qr[7], qr[6]) obc.ccx(qr[3], qr[7], qr[6]) # Measure for i in range(0, n_qubits): obc.measure(qr[i], cr[i]) # Get qasm source source = qp.get_qasm(Circuit) print(source) # Compile and run backend = 'local_qasm_simulator' circuits = [Circuit] # Group of circuits to execute qobj = qp.compile(circuits, backend) # Compile your program result = qp.run(qobj, wait=2, timeout=240) print(result) results = result.get_counts(Circuit) print(results) validate(results)
def test_add_circuit(self): """Test add two circuits. If all correct should return the data """ QP_program = QuantumProgram() qr = QP_program.create_quantum_register("qr", 2, verbose=False) cr = QP_program.create_classical_register("cr", 2, verbose=False) qc1 = QP_program.create_circuit("qc1", [qr], [cr]) qc2 = QP_program.create_circuit("qc2", [qr], [cr]) QP_program.set_api(API_TOKEN, URL) qc1.h(qr[0]) qc1.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) new_circuit = qc1 + qc2 QP_program.add_circuit('new_circuit', new_circuit) # new_circuit.measure(qr[0], cr[0]) circuits = ['new_circuit'] backend = 'local_qasm_simulator' # the backend to run on shots = 1024 # the number of shots in the experiment. result = QP_program.execute(circuits, backend=backend, shots=shots, seed=78) self.assertEqual(result.get_counts('new_circuit'), { '00': 505, '01': 519 })
def main(): Q_program = QuantumProgram() Q_program.register(Qconfig.APItoken, Qconfig.config["url"]) #Creating registers q = Q_program.create_quantum_register("q", 2) c = Q_program.create_classical_register("c", 2) #Quantum circuit to make shared entangled state superdense = Q_program.create_circuit("superdense", [q], [c]) #Party A : Alice superdense.h(q[0]) superdense.cx(q[0], q[1]) #00:do nothing, 10:apply x, 01:apply z superdense.x(q[0]) superdense.z(q[0]) #11:apply zx superdense.z(q[0]) superdense.x(q[0]) superdense.barrier() #Party B : Bob superdense.cx(q[0], q[1]) superdense.h(q[0]) superdense.measure(q[0], c[0]) superdense.measure(q[1], c[1]) circuits = ["superdense"] print(Q_program.get_qasms(circuits)[0]) backend = "ibmq_qasm_simulator" shots = 1024 result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=3, timeout=240) print("Counts:" + str(result.get_counts("superdense"))) plot_histogram(result.get_counts("superdense"))
def test_random_4qubit(self): desired_vector = [ 1 / math.sqrt(4) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 0, 0, 0, 1 / math.sqrt(4) * complex(1, 0), 1 / math.sqrt(8) * complex(1, 0)] qp = QuantumProgram() qr = qp.create_quantum_register("qr", 4) cr = qp.create_classical_register("cr", 4) qc = qp.create_circuit("qc", [qr], [cr]) qc.initialize("QInit", desired_vector, [qr[0], qr[1], qr[2], qr[3]]) result = qp.execute(["qc"], backend='local_qasm_simulator', shots=1) quantum_state = result.get_data("qc")['quantum_state'] fidelity = state_fidelity(quantum_state, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, "Initializer has low fidelity {0:.2g}.".format(fidelity))
def test_local_unitary_simulator(self): """Test unitary simulator. If all correct should the h otimes h and cx. """ QP_program = QuantumProgram() q = QP_program.create_quantum_register("q", 2, verbose=False) c = QP_program.create_classical_register("c", 2, verbose=False) qc1 = QP_program.create_circuit("qc1", [q], [c]) qc2 = QP_program.create_circuit("qc2", [q], [c]) qc1.h(q) qc2.cx(q[0], q[1]) circuits = ['qc1', 'qc2'] backend = 'local_unitary_simulator' # the backend to run on result = QP_program.execute(circuits, backend=backend) unitary1 = result.get_data('qc1')['unitary'] unitary2 = result.get_data('qc2')['unitary'] unitaryreal1 = np.array([[0.5, 0.5, 0.5, 0.5], [0.5, -0.5, 0.5, -0.5], [0.5, 0.5, -0.5, -0.5], [0.5, -0.5, -0.5, 0.5]]) unitaryreal2 = np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0., 0, 1, 0], [0, 1, 0, 0]]) norm1 = np.trace(np.dot(np.transpose(np.conj(unitaryreal1)), unitary1)) norm2 = np.trace(np.dot(np.transpose(np.conj(unitaryreal2)), unitary2)) self.assertAlmostEqual(norm1, 4) self.assertAlmostEqual(norm2, 4)
def test_get_qasms(self): """Test the get_qasms. If all correct the qasm output for each circuit should be of a certain lenght Previusly: Libraries: from qiskit import QuantumProgram """ QP_program = QuantumProgram() qr = QP_program.create_quantum_register("qr", 3, verbose=False) cr = QP_program.create_classical_register("cr", 3, verbose=False) qc1 = QP_program.create_circuit("qc1", [qr], [cr]) qc2 = QP_program.create_circuit("qc2", [qr], [cr]) qc1.h(qr[0]) qc1.cx(qr[0], qr[1]) qc1.cx(qr[1], qr[2]) qc1.measure(qr[0], cr[0]) qc1.measure(qr[1], cr[1]) qc1.measure(qr[2], cr[2]) qc2.h(qr) qc2.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) qc2.measure(qr[2], cr[2]) result = QP_program.get_qasms(["qc1", "qc2"]) self.assertEqual(len(result[0]), 173) self.assertEqual(len(result[1]), 159)
def test_compile_coupling_map(self): """Test compile_coupling_map. If all correct should return data with the same stats. The circuit may be different. """ QP_program = QuantumProgram() q = QP_program.create_quantum_register("q", 3, verbose=False) c = QP_program.create_classical_register("c", 3, verbose=False) qc = QP_program.create_circuit("circuitName", [q], [c]) qc.h(q[0]) qc.cx(q[0], q[1]) qc.cx(q[0], q[2]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) backend = 'local_qasm_simulator' # the backend to run on shots = 1024 # the number of shots in the experiment. coupling_map = {0: [1], 1: [2]} initial_layout = {("q", 0): ("q", 0), ("q", 1): ("q", 1), ("q", 2): ("q", 2)} circuits = ["circuitName"] qobj = QP_program.compile(circuits, backend=backend, shots=shots, coupling_map=coupling_map, initial_layout=initial_layout, seed=88) result = QP_program.run(qobj) to_check = QP_program.get_qasm("circuitName") self.assertEqual(len(to_check), 160) self.assertEqual(result.get_counts("circuitName"), {'000': 518, '111': 506})
def test_get_qasms(self): """Test the get_qasms. If all correct the qasm output for each circuit should be of a certain lenght Previusly: Libraries: from qiskit import QuantumProgram """ QP_program = QuantumProgram() qr = QP_program.create_quantum_register("qr", 3, verbose=False) cr = QP_program.create_classical_register("cr", 3, verbose=False) qc1 = QP_program.create_circuit("qc1", [qr], [cr]) qc2 = QP_program.create_circuit("qc2", [qr], [cr]) qc1.h(qr[0]) qc1.cx(qr[0], qr[1]) qc1.cx(qr[1], qr[2]) qc1.measure(qr[0], cr[0]) qc1.measure(qr[1], cr[1]) qc1.measure(qr[2], cr[2]) qc2.h(qr) qc2.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) qc2.measure(qr[2], cr[2]) result = QP_program.get_qasms(["qc1", "qc2"]) self.assertEqual(len(result[0]), 173) self.assertEqual(len(result[1]), 159)
def test_compile_coupling_map(self): """Test compile_coupling_map. If all correct should return data with the same stats. The circuit may be different. """ QP_program = QuantumProgram() q = QP_program.create_quantum_register("q", 3, verbose=False) c = QP_program.create_classical_register("c", 3, verbose=False) qc = QP_program.create_circuit("circuitName", [q], [c]) qc.h(q[0]) qc.cx(q[0], q[1]) qc.cx(q[0], q[2]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) qc.measure(q[2], c[2]) backend = 'local_qasm_simulator' # the backend to run on shots = 1024 # the number of shots in the experiment. coupling_map = {0: [1], 1: [2]} initial_layout = {("q", 0): ("q", 0), ("q", 1): ("q", 1), ("q", 2): ("q", 2)} circuits = ["circuitName"] qobj = QP_program.compile(circuits, backend=backend, shots=shots, coupling_map=coupling_map, initial_layout=initial_layout, seed=88) result = QP_program.run(qobj) to_check = QP_program.get_qasm("circuitName") self.assertEqual(len(to_check), 160) self.assertEqual(result.get_counts("circuitName"), {'000': 518, '111': 506})
def test_local_unitary_simulator(self): """Test unitary simulator. If all correct should the h otimes h and cx. """ QP_program = QuantumProgram() q = QP_program.create_quantum_register("q", 2, verbose=False) c = QP_program.create_classical_register("c", 2, verbose=False) qc1 = QP_program.create_circuit("qc1", [q], [c]) qc2 = QP_program.create_circuit("qc2", [q], [c]) qc1.h(q) qc2.cx(q[0], q[1]) circuits = ['qc1', 'qc2'] backend = 'local_unitary_simulator' # the backend to run on result = QP_program.execute(circuits, backend=backend) unitary1 = result.get_data('qc1')['unitary'] unitary2 = result.get_data('qc2')['unitary'] unitaryreal1 = np.array([[0.5, 0.5, 0.5, 0.5], [0.5, -0.5, 0.5, -0.5], [0.5, 0.5, -0.5, -0.5], [0.5, -0.5, -0.5, 0.5]]) unitaryreal2 = np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0., 0, 1, 0], [0, 1, 0, 0]]) norm1 = np.trace(np.dot(np.transpose(np.conj(unitaryreal1)), unitary1)) norm2 = np.trace(np.dot(np.transpose(np.conj(unitaryreal2)), unitary2)) self.assertAlmostEqual(norm1, 4) self.assertAlmostEqual(norm2, 4)
def test_average_data(self): """Test average_data. If all correct should the data. """ QP_program = QuantumProgram() q = QP_program.create_quantum_register("q", 2, verbose=False) c = QP_program.create_classical_register("c", 2, verbose=False) qc = QP_program.create_circuit("qc", [q], [c]) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) circuits = ['qc'] shots = 10000 # the number of shots in the experiment. backend = 'local_qasm_simulator' results = QP_program.execute(circuits, backend=backend, shots=shots) observable = {"00": 1, "11": 1, "01": -1, "10": -1} meanzz = results.average_data("qc", observable) observable = {"00": 1, "11": -1, "01": 1, "10": -1} meanzi = results.average_data("qc", observable) observable = {"00": 1, "11": -1, "01": -1, "10": 1} meaniz = results.average_data("qc", observable) self.assertAlmostEqual(meanzz, 1, places=1) self.assertAlmostEqual(meanzi, 0, places=1) self.assertAlmostEqual(meaniz, 0, places=1)
def test_average_data(self): """Test average_data. If all correct should the data. """ QP_program = QuantumProgram() q = QP_program.create_quantum_register("q", 2, verbose=False) c = QP_program.create_classical_register("c", 2, verbose=False) qc = QP_program.create_circuit("qc", [q], [c]) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q[0], c[0]) qc.measure(q[1], c[1]) circuits = ['qc'] shots = 10000 # the number of shots in the experiment. backend = 'local_qasm_simulator' results = QP_program.execute(circuits, backend=backend, shots=shots) observable = {"00": 1, "11": 1, "01": -1, "10": -1} meanzz = results.average_data("qc", observable) observable = {"00": 1, "11": -1, "01": 1, "10": -1} meanzi = results.average_data("qc", observable) observable = {"00": 1, "11": -1, "01": -1, "10": 1} meaniz = results.average_data("qc", observable) self.assertAlmostEqual(meanzz, 1, places=1) self.assertAlmostEqual(meanzi, 0, places=1) self.assertAlmostEqual(meaniz, 0, places=1)
def build_model_circuits(name, n): qp = QuantumProgram() q = qp.create_quantum_register("q", n) c = qp.create_classical_register("c", n) qft(qftcirc, q, n) for j in range(n): qp.add_circuit("%s_%d" % (name, n), qftcirc) return qp def main(): parser = argparse.ArgumentParser(description="Create circuits \ of Quantum Fourier \ Transform for \ quantum volume analysis.") parser.add_argument('--name', default='qft', help='circuit name') parser.add_argument('-n', '--qubits', default=5, type=int, help='number of circuit qubits') args = parser.parse_args() qp = build_model_circuits(name=args.name, n=args.qubits) circuit_name = args.name+'_n'+str(args.qubits) f = open(circuit_name+'.qasm', 'w') f.write(qp.get_qasm(name="%s_%d" % (args.name, args.qubits))) f.close() if __name__ == "__main__": main()
def test_execute_one_circuit_real_online(self): """Test execute_one_circuit_real_online. If all correct should return a result object """ QP_program = QuantumProgram() qr = QP_program.create_quantum_register("qr", 1, verbose=False) cr = QP_program.create_classical_register("cr", 1, verbose=False) qc = QP_program.create_circuit("circuitName", [qr], [cr]) qc.h(qr) qc.measure(qr[0], cr[0]) QP_program.set_api(API_TOKEN, URL) backend_list = QP_program.online_backends() if backend_list: backend = backend_list[0] shots = 1 # the number of shots in the experiment. status = QP_program.get_backend_status(backend) if status['available'] is False: pass else: result = QP_program.execute(['circuitName'], backend=backend, shots=shots, max_credits=3) self.assertIsInstance(result, Result)
def test_create_circuit_noname(self): """Test create_circuit with no name """ q_program = QuantumProgram() qr = q_program.create_quantum_register(size=3) cr = q_program.create_classical_register(size=3) qc = q_program.create_circuit(qregisters=[qr], cregisters=[cr]) self.assertIsInstance(qc, QuantumCircuit)
def test_create_circuit_noname(self): """Test create_circuit with no name """ q_program = QuantumProgram() qr = q_program.create_quantum_register(size=3) cr = q_program.create_classical_register(size=3) qc = q_program.create_circuit(qregisters=[qr], cregisters=[cr]) self.assertIsInstance(qc, QuantumCircuit)
def test_malformed_amplitudes(self): desired_vector = [1 / math.sqrt(3), math.sqrt(2) / math.sqrt(3), 0] qp = QuantumProgram() qr = qp.create_quantum_register("qr", 2) cr = qp.create_classical_register("cr", 2) qc = qp.create_circuit("qc", [qr], [cr]) self.assertRaises(QISKitError, qc.initialize, desired_vector, [qr[0], qr[1]])
def test_get_register_and_circuit_names_nonames(self): """Get the names of the circuits and registers after create them without a name """ q_program = QuantumProgram() qr1 = q_program.create_quantum_register(size=3) cr1 = q_program.create_classical_register(size=3) qr2 = q_program.create_quantum_register(size=3) cr2 = q_program.create_classical_register(size=3) q_program.create_circuit(qregisters=[qr1], cregisters=[cr1]) q_program.create_circuit(qregisters=[qr2], cregisters=[cr2]) q_program.create_circuit(qregisters=[qr1, qr2], cregisters=[cr1, cr2]) qrn = q_program.get_quantum_register_names() crn = q_program.get_classical_register_names() qcn = q_program.get_circuit_names() self.assertEqual(len(qrn), 2) self.assertEqual(len(crn), 2) self.assertEqual(len(qcn), 3)
def test_non_unit_probability(self): desired_vector = [1, 1] qp = QuantumProgram() qr = qp.create_quantum_register("qr", 2) cr = qp.create_classical_register("cr", 2) qc = qp.create_circuit("qc", [qr], [cr]) self.assertRaises(QISKitError, qc.initialize, desired_vector, [qr[0], qr[1]])
def test_get_register_and_circuit_names_nonames(self): """Get the names of the circuits and registers after create them without a name """ q_program = QuantumProgram() qr1 = q_program.create_quantum_register(size=3) cr1 = q_program.create_classical_register(size=3) qr2 = q_program.create_quantum_register(size=3) cr2 = q_program.create_classical_register(size=3) q_program.create_circuit(qregisters=[qr1], cregisters=[cr1]) q_program.create_circuit(qregisters=[qr2], cregisters=[cr2]) q_program.create_circuit(qregisters=[qr1, qr2], cregisters=[cr1, cr2]) qrn = q_program.get_quantum_register_names() crn = q_program.get_classical_register_names() qcn = q_program.get_circuit_names() self.assertEqual(len(qrn), 2) self.assertEqual(len(crn), 2) self.assertEqual(len(qcn), 3)
def _get_quantum_program(): quantum_program = QuantumProgram() qr = quantum_program.create_quantum_register("q", 1) cr = quantum_program.create_classical_register("c", 1) qc = quantum_program.create_circuit("qc", [qr], [cr]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) return quantum_program
def _get_quantum_program(self): quantum_program = QuantumProgram() qr = quantum_program.create_quantum_register("q", 1) cr = quantum_program.create_classical_register("c", 1) qc = quantum_program.create_circuit("qc", [qr], [cr]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) return quantum_program
def main(): # Quantum program setup qp = QuantumProgram() qp.set_api(Qconfig.APItoken, Qconfig.config["url"]) # enable logging #qp.enable_logs(logging.DEBUG); print("Backends=" + str(qp.available_backends())) # Create qubits/registers size = 2 q = qp.create_quantum_register('q', size) c = qp.create_classical_register('c', size) # Quantum circuit grover = qp.create_circuit('grover', [q], [c]) # loops = sqrt(2^n) * PI/4 #loops = math.floor(math.sqrt(2**size) * (math.pi/4)) # 1. put all qubits in superposition for i in range(size): grover.h(q[i]) # Set the input input_phase(grover, q) # 2. Phase inversion invert_phase(grover, q) input_phase(grover, q) # 3. Invert over the mean invert_over_the_mean(grover, q) # measure for i in range(size): grover.measure(q[i], c[i]) circuits = ['grover'] # Execute the quantum circuits on the simulator backend = "local_qasm_simulator" #backend = "ibmq_qasm_simulator" # the number of shots in the experiment shots = 1024 result = qp.execute(circuits, backend=backend, shots=shots, max_credits=3, timeout=240) counts = result.get_counts("grover") print("Counts:" + str(counts))
def gen_cc_main(nCoins, indexOfFalseCoin): """ generate a circuit of the counterfeit coin problem """ Q_program = QuantumProgram() # using the last qubit for storing the oracle's answer nQubits = nCoins + 1 # Creating registers # qubits for querying coins and storing the balance result qr = Q_program.create_quantum_register("qr", nQubits) # for recording the measurement on qr cr = Q_program.create_classical_register("cr", nQubits) circuitName = "CounterfeitCoinProblem" ccCircuit = Q_program.create_circuit(circuitName, [qr], [cr]) # Apply Hadamard gates to the first nCoins quantum register # create uniform superposition for i in range(nCoins): ccCircuit.h(qr[i]) # check if there are even number of coins placed on the pan for i in range(nCoins): ccCircuit.cx(qr[i], qr[nCoins]) # perform intermediate measurement to check if the last qubit is zero ccCircuit.measure(qr[nCoins], cr[nCoins]) # proceed to query the quantum beam balance if cr is zero ccCircuit.x(qr[nCoins]).c_if(cr, 0) ccCircuit.h(qr[nCoins]).c_if(cr, 0) # we rewind the computation when cr[N] is not zero for i in range(nCoins): ccCircuit.h(qr[i]).c_if(cr, 2**nCoins) # apply barrier for marking the beginning of the oracle ccCircuit.barrier() ccCircuit.cx(qr[indexOfFalseCoin], qr[nCoins]).c_if(cr, 0) # apply barrier for marking the end of the oracle ccCircuit.barrier() # apply Hadamard gates to the first nCoins qubits for i in range(nCoins): ccCircuit.h(qr[i]).c_if(cr, 0) # measure qr and store the result to cr for i in range(nCoins): ccCircuit.measure(qr[i], cr[i]) return Q_program, [ circuitName, ]
def qrng(n): # create a program qp = QuantumProgram() # create n qubit(s) quantum_r = qp.create_quantum_register("qr", n) # create n classical registers classical_r = qp.create_classical_register("cr", n) # create a circuit circuit = qp.create_circuit("QRNG", [quantum_r], [classical_r]) # enable logging #qp.enable_logs(logging.DEBUG); # Hadamard gate to all qubits for i in range(n): circuit.h(quantum_r[i]) # measure qubit n and store in classical n for i in range(n): circuit.measure(quantum_r[i], classical_r[i]) # backend simulator #backend = 'local_qasm_simulator' backend = 'ibmq_qasm_simulator' # Group of circuits to execute circuits = ['QRNG'] # Compile your program: ASM print(qp.get_qasm('Circuit')), JSON: print(str(qobj)) # set the APIToken and Q Experience API url qp.set_api(Qconfig.APItoken, Qconfig.config['url']) shots = 1024 result = qp.execute(circuits, backend, shots=shots, max_credits=3, timeout=240) # Show result counts # counts={'100': 133, '101': 134, '011': 131, '110': 125, '001': 109, '111': 128, '010': 138, '000': 126} counts = result.get_counts('QRNG') bits = "" for v in counts.values(): if v > shots / (2**n): bits += "1" else: bits += "0" #print ("counts=" + str(counts) ) #print ("items=" + str(counts.values()) ) return int(bits, 2)
def test_quantum_program_online(self, QE_TOKEN, QE_URL): qp = QuantumProgram() qp.set_api(QE_TOKEN, QE_URL) qr = qp.create_quantum_register('qr', 2) cr = qp.create_classical_register('cr', 2) qc = qp.create_circuit('qc', [qr], [cr]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) backend = 'ibmq_qasm_simulator' shots = 1024 _ = qp.execute(['qc'], backend=backend, shots=shots, seed=78)
def test_quantum_program_online(self): qp = QuantumProgram() qr = qp.create_quantum_register('qr', 2) cr = qp.create_classical_register('cr', 2) qc = qp.create_circuit('qc', [qr], [cr]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) backend = 'ibmqx_qasm_simulator' # the backend to run on shots = 1024 # the number of shots in the experiment. qp.set_api(self.QE_TOKEN, self.QE_URL) result = qp.execute(['qc'], backend=backend, shots=shots, seed=78)
def test_create_several_circuits(self): """Test create_circuit with several inputs. If all is correct we get a object intstance of QuantumCircuit Previusly: Libraries: from qiskit import QuantumProgram from qiskit import QuantumCircuit """ QP_program = QuantumProgram() qr1 = QP_program.create_quantum_register("qr1", 3, verbose=False) cr1 = QP_program.create_classical_register("cr1", 3, verbose=False) qr2 = QP_program.create_quantum_register("qr2", 3, verbose=False) cr2 = QP_program.create_classical_register("cr2", 3, verbose=False) qc1 = QP_program.create_circuit("qc1", [qr1], [cr1]) qc2 = QP_program.create_circuit("qc2", [qr2], [cr2]) qc3 = QP_program.create_circuit("qc2", [qr1, qr2], [cr1, cr2]) self.assertIsInstance(qc1, QuantumCircuit) self.assertIsInstance(qc2, QuantumCircuit) self.assertIsInstance(qc3, QuantumCircuit)
def test_quantum_program_online(self): qp = QuantumProgram() qr = qp.create_quantum_register('qr', 2) cr = qp.create_classical_register('cr', 2) qc = qp.create_circuit('qc', [qr], [cr]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) backend = 'ibmqx_qasm_simulator' # the backend to run on shots = 1024 # the number of shots in the experiment. qp.set_api(self.QE_TOKEN, self.QE_URL) result = qp.execute(['qc'], backend=backend, shots=shots, seed=78)
def test_create_several_circuits(self): """Test create_circuit with several inputs. If all is correct we get a object intstance of QuantumCircuit Previusly: Libraries: from qiskit import QuantumProgram from qiskit import QuantumCircuit """ QP_program = QuantumProgram() qr1 = QP_program.create_quantum_register("qr1", 3, verbose=False) cr1 = QP_program.create_classical_register("cr1", 3, verbose=False) qr2 = QP_program.create_quantum_register("qr2", 3, verbose=False) cr2 = QP_program.create_classical_register("cr2", 3, verbose=False) qc1 = QP_program.create_circuit("qc1", [qr1], [cr1]) qc2 = QP_program.create_circuit("qc2", [qr2], [cr2]) qc3 = QP_program.create_circuit("qc2", [qr1, qr2], [cr1, cr2]) self.assertIsInstance(qc1, QuantumCircuit) self.assertIsInstance(qc2, QuantumCircuit) self.assertIsInstance(qc3, QuantumCircuit)
def qft3u(g): Q_program = QuantumProgram() qr = Q_program.create_quantum_register("qr", 3) cr = Q_program.create_classical_register("cr", 3) qc = Q_program.create_circuit("superposition", [qr], [cr]) #Entradas #qc.h(qr[1]) qc.h(qr[0]) #qc.x(qr[0]) #qc.x(qr[1]) #qc.x(qr[2]) #QFT 3 qc.h(qr[2]) #aplica H no 1 qubit #S controlada de 2 para 1 qc.u1(pi/4, qr[2]) qc.cx(qr[1], qr[2]) qc.u1(pi/4, qr[1]) qc.u1(-pi/4, qr[2]) qc.cx(qr[1], qr[2]) #T controlada de 0 para 2 qc.u1(pi/8, qr[2]) #u1=sqrt(T) qc.cx(qr[0], qr[2]) qc.u1(pi/8, qr[0]) qc.u1(-pi/8, qr[2]) qc.cx(qr[0], qr[2]) qc.h(qr[1]) #aplica H no 2 qubit #S controlada de 1 para 2 qc.u1(pi/4, qr[1]) qc.cx(qr[0], qr[1]) qc.u1(pi/4, qr[0]) qc.u1(-pi/4, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) #aplica H no 3 qubit qc.swap(qr[2], qr[0]) # troca o 1 e 3 qubit qc.measure(qr, cr) result = Q_program.execute(["superposition"], backend='local_qasm_simulator', shots=g) print(result) print(result.get_data("superposition")) tmp = result.get_data("superposition") plot_histogram(tmp['counts'])
def _test_circuits_2qubit(): qp = QuantumProgram() qr = qp.create_quantum_register('qr', 2) cr = qp.create_classical_register('cr', 2) # Test Circuits Bell state circ = qp.create_circuit('Bell', [qr], [cr]) circ.h(qr[0]) circ.cx(qr[0], qr[1]) circ = qp.create_circuit('X1Id0', [qr], [cr]) circ.x(qr[1]) return qp, qr, cr
def _test_circuits_2qubit(): qp = QuantumProgram() qr = qp.create_quantum_register('qr', 2) cr = qp.create_classical_register('cr', 2) # Test Circuits Bell state circ = qp.create_circuit('Bell', [qr], [cr]) circ.h(qr[0]) circ.cx(qr[0], qr[1]) circ = qp.create_circuit('X1Id0', [qr], [cr]) circ.x(qr[1]) return qp, qr, cr
def test_create_quantum_register(self): """Test create_quantum_register. If all is correct we get a object intstance of QuantumRegister Previusly: Libraries: from qiskit import QuantumProgram from qiskit import QuantumRegister """ QP_program = QuantumProgram() qr = QP_program.create_quantum_register("qr", 3, verbose=False) self.assertIsInstance(qr, QuantumRegister)
def test_create_quantum_register(self): """Test create_quantum_register. If all is correct we get a object intstance of QuantumRegister Previusly: Libraries: from qiskit import QuantumProgram from qiskit import QuantumRegister """ QP_program = QuantumProgram() qr = QP_program.create_quantum_register("qr", 3, verbose=False) self.assertIsInstance(qr, QuantumRegister)
def test_deterministic_state(self): desired_vector = [0, 1, 0, 0] qp = QuantumProgram() qr = qp.create_quantum_register("qr", 2) cr = qp.create_classical_register("cr", 2) qc = qp.create_circuit("qc", [qr], [cr]) qc.initialize("QInit", desired_vector, [qr[0], qr[1]]) result = qp.execute(["qc"], backend='local_qasm_simulator', shots=1) quantum_state = result.get_data("qc")['quantum_state'] fidelity = state_fidelity(quantum_state, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, "Initializer has low fidelity {0:.2g}.".format(fidelity))
def test_simple_execute(self): name = 'test_simple' seed = 42 qp = QuantumProgram() qr = qp.create_quantum_register('qr', 2) cr = qp.create_classical_register('cr', 2) qc = qp.create_circuit(name, [qr], [cr]) qc.u1(3.14, qr[0]) qc.u2(3.14, 1.57, qr[0]) qc.measure(qr, cr) rtrue = qp.execute(name, seed=seed, skip_translation=True) rfalse = qp.execute(name, seed=seed, skip_translation=False) self.assertEqual(rtrue.get_counts(), rfalse.get_counts())
def test_get_register_and_circuit_names(self): """Get the names of the circuits and registers. If all is correct we should get the arrays of the names Previusly: Libraries: from qiskit import QuantumProgram """ QP_program = QuantumProgram() qr1 = QP_program.create_quantum_register("qr1", 3, verbose=False) cr1 = QP_program.create_classical_register("cr1", 3, verbose=False) qr2 = QP_program.create_quantum_register("qr2", 3, verbose=False) cr2 = QP_program.create_classical_register("cr2", 3, verbose=False) QP_program.create_circuit("qc1", [qr1], [cr1]) QP_program.create_circuit("qc2", [qr2], [cr2]) QP_program.create_circuit("qc2", [qr1, qr2], [cr1, cr2]) qrn = QP_program.get_quantum_register_names() crn = QP_program.get_classical_register_names() qcn = QP_program.get_circuit_names() self.assertEqual(qrn, {'qr1', 'qr2'}) self.assertEqual(crn, {'cr1', 'cr2'}) self.assertEqual(qcn, {'qc1', 'qc2'})
def test_create_quantum_register_same(self): """Test create_quantum_register of same name and size. If all is correct we get a single classical register Previusly: Libraries: from qiskit import QuantumProgram from qiskit import QuantumRegister """ QP_program = QuantumProgram() qr1 = QP_program.create_quantum_register("qr", 3, verbose=False) qr2 = QP_program.create_quantum_register("qr", 3, verbose=False) self.assertIs(qr1, qr2)
def test_if_statement(self): self.log.info('test_if_statement_x') shots = 100 max_qubits = 3 qp = QuantumProgram() qr = qp.create_quantum_register('qr', max_qubits) cr = qp.create_classical_register('cr', max_qubits) circuit = qp.create_circuit('test_if', [qr], [cr]) circuit.x(qr[0]) circuit.x(qr[1]) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[1]) circuit.x(qr[2]).c_if(cr, 0x3) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[1]) circuit.measure(qr[2], cr[2]) circuit2 = qp.create_circuit('test_if_case_2', [qr], [cr]) circuit2.x(qr[0]) circuit2.measure(qr[0], cr[0]) circuit2.measure(qr[1], cr[1]) circuit2.x(qr[2]).c_if(cr, 0x3) circuit2.measure(qr[0], cr[0]) circuit2.measure(qr[1], cr[1]) circuit2.measure(qr[2], cr[2]) basis_gates = [] # unroll to base gates unroller = unroll.Unroller( qasm.Qasm(data=qp.get_qasm('test_if')).parse(), unroll.JsonBackend(basis_gates)) ucircuit = unroller.execute() unroller = unroll.Unroller( qasm.Qasm(data=qp.get_qasm('test_if_case_2')).parse(), unroll.JsonBackend(basis_gates)) ucircuit2 = unroller.execute() config = {'shots': shots, 'seed': self.seed} job = {'compiled_circuit': ucircuit, 'config': config} result_if_true = QasmSimulator(job).run() job = {'compiled_circuit': ucircuit2, 'config': config} result_if_false = QasmSimulator(job).run() self.log.info('result_if_true circuit:') self.log.info(circuit.qasm()) self.log.info('result_if_true={0}'.format(result_if_true)) del circuit.data[1] self.log.info('result_if_false circuit:') self.log.info(circuit.qasm()) self.log.info('result_if_false={0}'.format(result_if_false)) self.assertTrue(result_if_true['data']['counts']['111'] == 100) self.assertTrue(result_if_false['data']['counts']['001'] == 100)
def test_create_circuit(self): """Test create_circuit. If all is correct we get a object intstance of QuantumCircuit Previusly: Libraries: from qiskit import QuantumProgram from qiskit import QuantumCircuit """ QP_program = QuantumProgram() qr = QP_program.create_quantum_register("qr", 3, verbose=False) cr = QP_program.create_classical_register("cr", 3, verbose=False) qc = QP_program.create_circuit("qc", [qr], [cr]) self.assertIsInstance(qc, QuantumCircuit)
def simulate(grid): qp = QuantumProgram() qr = qp.create_quantum_register('qr', 2) cr = qp.create_classical_register('cr', 2) qc = qp.create_circuit('pi', [qr], [cr]) qc = build_qc(qc, grid, qr, cr) result = qp.execute('pi') tmp = result.get_counts('pi') tmp = dict([(x[0], round(x[1] / 1024, 2)) for x in list(tmp.items())]) return tmp
def test_teleport(self): """test teleportation as in tutorials""" self.log.info('test_teleport') pi = np.pi shots = 1000 qp = QuantumProgram() qr = qp.create_quantum_register('qr', 3) cr0 = qp.create_classical_register('cr0', 1) cr1 = qp.create_classical_register('cr1', 1) cr2 = qp.create_classical_register('cr2', 1) circuit = qp.create_circuit('teleport', [qr], [cr0, cr1, cr2]) circuit.h(qr[1]) circuit.cx(qr[1], qr[2]) circuit.ry(pi/4, qr[0]) circuit.cx(qr[0], qr[1]) circuit.h(qr[0]) circuit.barrier(qr) circuit.measure(qr[0], cr0[0]) circuit.measure(qr[1], cr1[0]) circuit.z(qr[2]).c_if(cr0, 1) circuit.x(qr[2]).c_if(cr1, 1) circuit.measure(qr[2], cr2[0]) backend = 'local_qasm_simulator' qobj = qp.compile('teleport', backend=backend, shots=shots, seed=self.seed) results = qp.run(qobj) data = results.get_counts('teleport') alice = {} bob = {} alice['00'] = data['0 0 0'] + data['1 0 0'] alice['01'] = data['0 1 0'] + data['1 1 0'] alice['10'] = data['0 0 1'] + data['1 0 1'] alice['11'] = data['0 1 1'] + data['1 1 1'] bob['0'] = data['0 0 0'] + data['0 1 0'] + data['0 0 1'] + data['0 1 1'] bob['1'] = data['1 0 0'] + data['1 1 0'] + data['1 0 1'] + data['1 1 1'] self.log.info('test_telport: circuit:') self.log.info( circuit.qasm() ) self.log.info('test_teleport: data {0}'.format(data)) self.log.info('test_teleport: alice {0}'.format(alice)) self.log.info('test_teleport: bob {0}'.format(bob)) alice_ratio = 1/np.tan(pi/8)**2 bob_ratio = bob['0']/float(bob['1']) error = abs(alice_ratio - bob_ratio) / alice_ratio self.log.info('test_teleport: relative error = {0:.4f}'.format(error)) self.assertLess(error, 0.05)
def test_fail_create_quantum_register(self): """Test create_quantum_register. If all is correct we get a object intstance of QuantumRegister and QISKitError Previusly: Libraries: from qiskit import QuantumProgram from qiskit import QuantumRegister from qiskit import QISKitError """ QP_program = QuantumProgram() qr1 = QP_program.create_quantum_register("qr", 3, verbose=False) self.assertIsInstance(qr1, QuantumRegister) self.assertRaises(QISKitError, QP_program.create_quantum_register, "qr", 2, verbose=False)
def test_simple_compile(self): """ Compares with and without skip_translation """ name = 'test_simple' qp = QuantumProgram() qr = qp.create_quantum_register('qr', 2) cr = qp.create_classical_register('cr', 2) qc = qp.create_circuit(name, [qr], [cr]) qc.u1(3.14, qr[0]) qc.u2(3.14, 1.57, qr[0]) qc.measure(qr, cr) rtrue = qp.compile([name], backend='local_qasm_simulator', shots=1024, skip_translation=True) rfalse = qp.compile([name], backend='local_qasm_simulator', shots=1024, skip_translation=False) self.assertEqual(rtrue['config'], rfalse['config']) self.assertEqual(rtrue['circuits'], rfalse['circuits'])
def test_add_circuit_noname(self): """Test add two circuits without names. Also tests get_counts without circuit name. """ q_program = QuantumProgram() qr = q_program.create_quantum_register(size=2) cr = q_program.create_classical_register(size=2) qc1 = q_program.create_circuit(qregisters=[qr], cregisters=[cr]) qc2 = q_program.create_circuit(qregisters=[qr], cregisters=[cr]) qc1.h(qr[0]) qc1.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) new_circuit = qc1 + qc2 q_program.add_circuit(quantum_circuit=new_circuit) backend = 'local_qasm_simulator_py' # cpp simulator rejects non string IDs (FIXME) shots = 1024 result = q_program.execute(backend=backend, shots=shots, seed=78) counts = result.get_counts(new_circuit.name) target = {'00': shots / 2, '01': shots / 2} threshold = 0.04 * shots self.assertDictAlmostEqual(counts, target, threshold) self.assertRaises(QISKitError, result.get_counts)
def test_combine_results(self): """Test run. If all correct should the data. """ QP_program = QuantumProgram() qr = QP_program.create_quantum_register("qr", 1) cr = QP_program.create_classical_register("cr", 1) qc1 = QP_program.create_circuit("qc1", [qr], [cr]) qc2 = QP_program.create_circuit("qc2", [qr], [cr]) qc1.measure(qr[0], cr[0]) qc2.x(qr[0]) qc2.measure(qr[0], cr[0]) shots = 1024 # the number of shots in the experiment. backend = 'local_qasm_simulator' res1 = QP_program.execute(['qc1'], backend=backend, shots=shots) res2 = QP_program.execute(['qc2'], backend=backend, shots=shots) counts1 = res1.get_counts('qc1') counts2 = res2.get_counts('qc2') res1 += res2 # combine results counts12 = [res1.get_counts('qc1'), res1.get_counts('qc2')] self.assertEqual(counts12, [counts1, counts2])
def test_execute_one_circuit_real_online(self): """Test execute_one_circuit_real_online. If all correct should return a result object """ QP_program = QuantumProgram() qr = QP_program.create_quantum_register("qr", 1, verbose=False) cr = QP_program.create_classical_register("cr", 1, verbose=False) qc = QP_program.create_circuit("circuitName", [qr], [cr]) qc.h(qr) qc.measure(qr[0], cr[0]) QP_program.set_api(API_TOKEN, URL) backend_list = QP_program.online_backends() if backend_list: backend = backend_list[0] shots = 1 # the number of shots in the experiment. status = QP_program.get_backend_status(backend) if status['available'] is False: pass else: result = QP_program.execute(['circuitName'], backend=backend, shots=shots, max_credits=3) self.assertIsInstance(result, Result)
def test_get_qasms_noname(self): """Test the get_qasms from a qprogram without names. """ q_program = QuantumProgram() qr = q_program.create_quantum_register(size=3) cr = q_program.create_classical_register(size=3) qc1 = q_program.create_circuit(qregisters=[qr], cregisters=[cr]) qc2 = q_program.create_circuit(qregisters=[qr], cregisters=[cr]) qc1.h(qr[0]) qc1.cx(qr[0], qr[1]) qc1.cx(qr[1], qr[2]) qc1.measure(qr[0], cr[0]) qc1.measure(qr[1], cr[1]) qc1.measure(qr[2], cr[2]) qc2.h(qr) qc2.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) qc2.measure(qr[2], cr[2]) results = dict(zip(q_program.get_circuit_names(), q_program.get_qasms())) qr_name_len = len(qr.name) cr_name_len = len(cr.name) self.assertEqual(len(results[qc1.name]), qr_name_len * 9 + cr_name_len * 4 + 147) self.assertEqual(len(results[qc2.name]), qr_name_len * 7 + cr_name_len * 4 + 137)
def _test_circuits_1qubit(): qp = QuantumProgram() qr = qp.create_quantum_register('qr', 1) cr = qp.create_classical_register('cr', 1) # Test Circuits Z eigenstate circ = qp.create_circuit('Zp', [qr], [cr]) circ = qp.create_circuit('Zm', [qr], [cr]) circ.x(qr[0]) # Test Circuits X eigenstate circ = qp.create_circuit('Xp', [qr], [cr]) circ.h(qr[0]) circ = qp.create_circuit('Xm', [qr], [cr]) circ.h(qr[0]) circ.z(qr[0]) # Test Circuits Y eigenstate circ = qp.create_circuit('Yp', [qr], [cr]) circ.h(qr[0]) circ.s(qr[0]) circ = qp.create_circuit('Ym', [qr], [cr]) circ.h(qr[0]) circ.s(qr[0]) circ.z(qr[0]) return qp, qr, cr
def test_add_circuit(self): """Test add two circuits. If all correct should return the data """ QP_program = QuantumProgram() qr = QP_program.create_quantum_register("qr", 2, verbose=False) cr = QP_program.create_classical_register("cr", 2, verbose=False) qc1 = QP_program.create_circuit("qc1", [qr], [cr]) qc2 = QP_program.create_circuit("qc2", [qr], [cr]) QP_program.set_api(API_TOKEN, URL) qc1.h(qr[0]) qc1.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) new_circuit = qc1 + qc2 QP_program.add_circuit('new_circuit', new_circuit) # new_circuit.measure(qr[0], cr[0]) circuits = ['new_circuit'] backend = 'local_qasm_simulator' # the backend to run on shots = 1024 # the number of shots in the experiment. result = QP_program.execute(circuits, backend=backend, shots=shots, seed=78) self.assertEqual(result.get_counts('new_circuit'), {'00': 505, '01': 519})
class RandomQasmGenerator(): """ Generate circuits with random operations for profiling. """ def __init__(self, seed=None, qubits=16, depth=40): """ Args: seed: Random number seed. If none, don't seed the generator. depth: Number of operations in the circuit. qubits: Number of qubits in the circuit. """ self.depth = depth self.qubits = qubits self.quantum_program = QuantumProgram() self.quantum_register = self.quantum_program.create_quantum_register( 'qr', qubits) self.classical_register = self.quantum_program.create_classical_register( 'cr', qubits) if seed is not None: random.seed(a=seed) def create_circuit(self, do_measure=True): """Creates a circuit Generates a circuit with a random number of operations equally weighted between U3 and CX. Also adds a random number of measurements in [1,self.qubits] to end of circuit. Args: do_measure (boolean): whether to add measurements Returns: A string representing the QASM circuit """ circuit_name = str(uuid.uuid4()) circuit = self.quantum_program.create_circuit(circuit_name, [self.quantum_register], [self.classical_register]) for j in range(self.depth): if self.qubits == 1: op_ind = 0 else: op_ind = random.randint(0, 1) if op_ind == 0: # U3 qind = random.randint(0, self.qubits - 1) circuit.u3(random.random(), random.random(), random.random(), self.quantum_register[qind]) elif op_ind == 1: # CX source, target = random.sample(range(self.qubits), 2) circuit.cx(self.quantum_register[source], self.quantum_register[target]) if do_measure: nmeasure = random.randint(1, self.qubits) for j in range(nmeasure): qind = random.randint(0, self.qubits - 1) # doing this if here keeps the RNG from depending on # whether measurements are done. circuit.measure(self.quantum_register[qind], self.classical_register[qind]) return circuit.qasm()
def test_if_statement(self): self.log.info('test_if_statement_x') shots = 100 max_qubits = 3 qp = QuantumProgram() qr = qp.create_quantum_register('qr', max_qubits) cr = qp.create_classical_register('cr', max_qubits) circuit_if_true = qp.create_circuit('test_if_true', [qr], [cr]) circuit_if_true.x(qr[0]) circuit_if_true.x(qr[1]) circuit_if_true.measure(qr[0], cr[0]) circuit_if_true.measure(qr[1], cr[1]) circuit_if_true.x(qr[2]).c_if(cr, 0x3) circuit_if_true.measure(qr[0], cr[0]) circuit_if_true.measure(qr[1], cr[1]) circuit_if_true.measure(qr[2], cr[2]) circuit_if_false = qp.create_circuit('test_if_false', [qr], [cr]) circuit_if_false.x(qr[0]) circuit_if_false.measure(qr[0], cr[0]) circuit_if_false.measure(qr[1], cr[1]) circuit_if_false.x(qr[2]).c_if(cr, 0x3) circuit_if_false.measure(qr[0], cr[0]) circuit_if_false.measure(qr[1], cr[1]) circuit_if_false.measure(qr[2], cr[2]) basis_gates = [] # unroll to base gates unroller = unroll.Unroller( qasm.Qasm(data=qp.get_qasm('test_if_true')).parse(), unroll.JsonBackend(basis_gates)) ucircuit_true = unroller.execute() unroller = unroll.Unroller( qasm.Qasm(data=qp.get_qasm('test_if_false')).parse(), unroll.JsonBackend(basis_gates)) ucircuit_false = unroller.execute() config = {'shots': shots, 'seed': self.seed} qobj = {'id': 'test_if_qobj', 'config': { 'max_credits': 3, 'shots': shots, 'backend': 'local_qasm_simulator', }, 'circuits': [ { 'name': 'test_if_true', 'compiled_circuit': ucircuit_true, 'compiled_circuit_qasm': None, 'config': {'coupling_map': None, 'basis_gates': 'u1,u2,u3,cx,id', 'layout': None, 'seed': None } }, { 'name': 'test_if_false', 'compiled_circuit': ucircuit_false, 'compiled_circuit_qasm': None, 'config': {'coupling_map': None, 'basis_gates': 'u1,u2,u3,cx,id', 'layout': None, 'seed': None } } ] } q_job = QuantumJob(qobj, preformatted=True) result = QasmSimulator().run(q_job) result_if_true = result.get_data('test_if_true') self.log.info('result_if_true circuit:') self.log.info(circuit_if_true.qasm()) self.log.info('result_if_true={0}'.format(result_if_true)) result_if_false = result.get_data('test_if_false') self.log.info('result_if_false circuit:') self.log.info(circuit_if_false.qasm()) self.log.info('result_if_false={0}'.format(result_if_false)) self.assertTrue(result_if_true['counts']['111'] == 100) self.assertTrue(result_if_false['counts']['001'] == 100)
import numpy as np from qiskit import QuantumCircuit, QuantumProgram import Qconfig import qiskit.tools.qcvv.tomography as tomography from qiskit.tools.visualization import plot_state, plot_histogram from qiskit.tools.qi.qi import state_fidelity, concurrence, purity, outer QProgram = QuantumProgram() QProgram.set_api(Qconfig.APItoken, Qconfig.config['url']) qr = QProgram.create_quantum_register('qr',2) cr = QProgram.create_classical_register('cr',2) bell = QProgram.create_circuit('bell', [qr], [cr]) bell.h(qr[0]) bell.cx(qr[0], qr[1]) bell_result = QProgram.execute(['bell'], backend = 'local_qasm_simulator', shots = 1) bell_psi = bell_result.get_data('bell') ['quantum_state'] bell_rho = outer(bell_psi) plot_state(bell_rho, 'paulivec')