def use_sympy_backends(): qprogram = QuantumProgram() current_dir = os.path.dirname(os.path.realpath(__file__)) qasm_file = current_dir + "/../qasm/simple.qasm" qasm_circuit = qprogram.load_qasm_file(qasm_file) print("analyzing: " + qasm_file) print(qprogram.get_qasm(qasm_circuit)) # sympy statevector simulator backend = 'local_sympy_qasm_simulator' result = qprogram.execute([qasm_circuit], backend=backend, shots=1, timeout=300) print("final quantum amplitude vector: ") print(result.get_data(qasm_circuit)['quantum_state']) # sympy unitary simulator backend = 'local_sympy_unitary_simulator' result = qprogram.execute([qasm_circuit], backend=backend, shots=1, timeout=300) print("\nunitary matrix of the circuit: ") print(result.get_data(qasm_circuit)['unitary'])
def execute(self, **kwargs): if 'backend' in kwargs: return QuantumProgram.execute(self, [self._circuit_name], **kwargs) elif self._backend is not None: return QuantumProgram.execute(self, [self._circuit_name], backend=self._backend, **kwargs) else: backend = self.get_best_backend(local=True) return QuantumProgram.execute(self, [self._circuit_name], backend=backend, **kwargs)
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_transpiler=True) rfalse = qp.execute(name, seed=seed, skip_transpiler=False) self.assertEqual(rtrue.get_counts(), rfalse.get_counts())
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 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_local_qasm_simulator(self): """Test execute. If all correct should the data. """ QP_program = QuantumProgram(specs=QPS_SPECS) qr = QP_program.get_quantum_register("qname") cr = QP_program.get_classical_register("cname") qc2 = QP_program.create_circuit("qc2", [qr], [cr]) qc3 = QP_program.create_circuit("qc3", [qr], [cr]) qc2.h(qr[0]) qc2.cx(qr[0], qr[1]) qc2.cx(qr[0], qr[2]) qc3.h(qr) qc2.measure(qr[0], cr[0]) qc3.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) qc3.measure(qr[1], cr[1]) qc2.measure(qr[2], cr[2]) qc3.measure(qr[2], cr[2]) circuits = ['qc2', 'qc3'] shots = 1024 # the number of shots in the experiment. backend = 'local_qasm_simulator' out = QP_program.execute(circuits, backend=backend, shots=shots, seed=88) results2 = out.get_counts('qc2') results3 = out.get_counts('qc3') # print(QP_program.get_data('qc3')) self.assertEqual(results2, {'000': 518, '111': 506}) self.assertEqual(results3, {'001': 119, '111': 129, '110': 134, '100': 117, '000': 129, '101': 126, '010': 145, '011': 125})
def test_sympy(self): desired_vector = [ 0, math.cos(math.pi / 3) * complex(0, 1) / math.sqrt(4), math.sin(math.pi / 3) / math.sqrt(4), 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), 1 / math.sqrt(4) * complex(0, 1)] qp = QuantumProgram() qr = QuantumRegister(4, "qr") qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2], qr[3]]) qp.add_circuit("qc", qc) result = qp.execute("qc", backend='local_statevector_simulator') statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, "Initializer has low fidelity {0:.2g}.".format(fidelity))
def test_local_qasm_simulator_one_shot(self): """Test sinlge shot of local simulator . If all correct should the quantum state. """ QP_program = QuantumProgram(specs=QPS_SPECS) qr = QP_program.get_quantum_register("qname") cr = QP_program.get_classical_register("cname") qc2 = QP_program.create_circuit("qc2", [qr], [cr]) qc3 = QP_program.create_circuit("qc3", [qr], [cr]) qc2.h(qr[0]) qc3.h(qr[0]) qc3.cx(qr[0], qr[1]) qc3.cx(qr[0], qr[2]) circuits = ['qc2', 'qc3'] backend = 'local_qasm_simulator' # the backend to run on shots = 1 # the number of shots in the experiment. result = QP_program.execute(circuits, backend=backend, shots=shots, seed=9) quantum_state = np.array([0.70710678+0.j, 0.70710678+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.00000000+0.j]) norm = np.dot(np.conj(quantum_state), result.get_data('qc2')['quantum_state']) self.assertAlmostEqual(norm, 1) quantum_state = np.array([0.70710678+0.j, 0+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.70710678+0.j]) norm = np.dot(np.conj(quantum_state), result.get_data('qc3')['quantum_state']) self.assertAlmostEqual(norm, 1)
def eval_cost_function_with_unlabeled_data(entangler_map, coupling_map, initial_layout, n, m, unlabeled_data, class_labels, backend, shots, seed, train, theta): predicted_results = [] Q_program = QuantumProgram() circuits = [] for c_id, inpt in enumerate(unlabeled_data): circuit_name, sequences = trial_circuit_ML(entangler_map, coupling_map, initial_layout, n, m, theta, inpt, '' + str(c_id), None, True) circuits.append(('', circuit_name)) Q_program.add_circuit(circuit_name, sequences) circuit_list = [c[1] for c in circuits] program_data = Q_program.execute(circuit_list, backend=backend, coupling_map=coupling_map, initial_layout=initial_layout, shots=shots, seed=seed) for v in range(len(circuit_list)): countsloop = program_data.get_counts(circuit_list[v]) probs = return_probabilities(countsloop, class_labels) predicted_results.append( max(probs.items(), key=operator.itemgetter(1))[0]) return predicted_results
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_initialize_middle_circuit(self): desired_vector = [0.5, 0.5, 0.5, 0.5] qp = QuantumProgram() qr = QuantumRegister("qr", 2) cr = ClassicalRegister("cr", 2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.reset(qr[0]) qc.reset(qr[1]) qc.initialize(desired_vector, [qr[0], qr[1]]) qc.measure(qr, cr) qp.add_circuit("qc", qc) # statevector simulator does not support reset shots = 2000 threshold = 0.025 * shots result = qp.execute("qc", backend='local_qasm_simulator', shots=shots) counts = result.get_counts() target = { '00': shots / 4, '01': shots / 4, '10': shots / 4, '11': shots / 4 } self.assertDictAlmostEqual(counts, target, threshold)
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 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 sync_job(Q_program: QuantumProgram, experiment: Experiment): bits = ["0b00", "0b01", "0b10", "0b11"] for a, b in itertools.product(bits, bits): qasm, qobj, expected = draper.create_experiment( Q_program, a, b, experiment) shots = 1000 result: Result = Q_program.execute(["draper"], backend, shots=shots) op_length = len(qasm.split("\n")) computational_result = "" success = False counts = dict() calibrations = [] data = result.get_data("draper") if "counts" in data: counts: dict = data["counts"] computational_result = max(counts.keys(), key=(lambda key: counts[key])) success = expected == computational_result log_msg = "%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s" % ( datetime.isoformat( datetime.now()), backend, a, b, op_length, shots, expected, computational_result, success, counts, calibrations, version) print(log_msg)
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 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 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_local_qasm_simulator(self): """Test execute. If all correct should the data. """ QP_program = QuantumProgram(specs=QPS_SPECS) qr = QP_program.get_quantum_register("qname") cr = QP_program.get_classical_register("cname") qc2 = QP_program.create_circuit("qc2", [qr], [cr]) qc3 = QP_program.create_circuit("qc3", [qr], [cr]) qc2.h(qr[0]) qc2.cx(qr[0], qr[1]) qc2.cx(qr[0], qr[2]) qc3.h(qr) qc2.measure(qr[0], cr[0]) qc3.measure(qr[0], cr[0]) qc2.measure(qr[1], cr[1]) qc3.measure(qr[1], cr[1]) qc2.measure(qr[2], cr[2]) qc3.measure(qr[2], cr[2]) circuits = ['qc2', 'qc3'] shots = 1024 # the number of shots in the experiment. backend = 'local_qasm_simulator' out = QP_program.execute(circuits, backend=backend, shots=shots, seed=88) results2 = out.get_counts('qc2') results3 = out.get_counts('qc3') # print(QP_program.get_data('qc3')) self.assertEqual(results2, {'000': 518, '111': 506}) self.assertEqual(results3, {'001': 119, '111': 129, '110': 134, '100': 117, '000': 129, '101': 126, '010': 145, '011': 125})
def test_local_qasm_simulator_one_shot(self): """Test sinlge shot of local simulator . If all correct should the quantum state. """ QP_program = QuantumProgram(specs=QPS_SPECS) qr = QP_program.get_quantum_register("qname") cr = QP_program.get_classical_register("cname") qc2 = QP_program.create_circuit("qc2", [qr], [cr]) qc3 = QP_program.create_circuit("qc3", [qr], [cr]) qc2.h(qr[0]) qc3.h(qr[0]) qc3.cx(qr[0], qr[1]) qc3.cx(qr[0], qr[2]) circuits = ['qc2', 'qc3'] backend = 'local_qasm_simulator' # the backend to run on shots = 1 # the number of shots in the experiment. result = QP_program.execute(circuits, backend=backend, shots=shots, seed=9) quantum_state = np.array([0.70710678+0.j, 0.70710678+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.00000000+0.j]) norm = np.dot(np.conj(quantum_state), result.get_data('qc2')['quantum_state']) self.assertAlmostEqual(norm, 1) quantum_state = np.array([0.70710678+0.j, 0+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.00000000+0.j, 0.70710678+0.j]) norm = np.dot(np.conj(quantum_state), result.get_data('qc3')['quantum_state']) self.assertAlmostEqual(norm, 1)
def test_execute_program_map(self): """Test execute_program_map. If all correct should return 10010. """ QP_program = QuantumProgram() QP_program.set_api(API_TOKEN, URL) backend = 'local_qasm_simulator' # the backend to run on shots = 100 # the number of shots in the experiment. max_credits = 3 coupling_map = {0: [1], 1: [2], 2: [3], 3: [4]} initial_layout = { ("q", 0): ("q", 0), ("q", 1): ("q", 1), ("q", 2): ("q", 2), ("q", 3): ("q", 3), ("q", 4): ("q", 4) } QP_program.load_qasm_file(QASM_FILE_PATH_2, "circuit-dev") circuits = ["circuit-dev"] result = QP_program.execute(circuits, backend=backend, shots=shots, max_credits=max_credits, coupling_map=coupling_map, initial_layout=initial_layout, seed=5455) self.assertEqual(result.get_counts("circuit-dev"), {'10010': 100})
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_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 MapperTest(QiskitTestCase): """Test the mapper.""" def setUp(self): self.seed = 42 self.qp = QuantumProgram() def tearDown(self): pass def test_mapper_overoptimization(self): """ The mapper should not change the semantics of the input. An overoptimization introduced the issue #81: https://github.com/QISKit/qiskit-sdk-py/issues/81 """ self.qp.load_qasm_file( self._get_resource_path('qasm/overoptimization.qasm'), name='test') coupling_map = {0: [2], 1: [2], 2: [3], 3: []} result1 = self.qp.execute(["test"], backend="local_qasm_simulator", coupling_map=coupling_map) count1 = result1.get_counts("test") result2 = self.qp.execute(["test"], backend="local_qasm_simulator", coupling_map=None) count2 = result2.get_counts("test") self.assertEqual( count1.keys(), count2.keys(), ) def test_math_domain_error(self): """ The math library operates over floats and introduce floating point errors that should be avoid See: https://github.com/QISKit/qiskit-sdk-py/issues/111 """ self.qp.load_qasm_file( self._get_resource_path('qasm/math_domain_error.qasm'), name='test') coupling_map = {0: [2], 1: [2], 2: [3], 3: []} result1 = self.qp.execute(["test"], backend="local_qasm_simulator", coupling_map=coupling_map, seed=self.seed) self.assertEqual(result1.get_counts("test"), { '0001': 507, '0101': 517 })
def test_circuit_C_MOD_GROVER_COIN(d, c, sh): Q_program = QuantumProgram() build_circuit_C_MOD_GROVER_COIN(Q_program, d, c) result = Q_program.execute(["test"], backend="local_qasm_simulator", shots=sh, silent=True) plot_histogram(result.get_counts('test'))
def perform_walks_lollipop(N, sh, I, T, file): for iter in range(I, T): print("Step " + repr(iter)) Q_program = QuantumProgram() build_circuit_lollipop(Q_program, N, iter) result = Q_program.execute(["walk"], backend="local_qasm_simulator", shots=sh, silent=True) counts = result.get_counts('walk') Ncounts = normalizeCounts(counts, sh) append_record(Ncounts, file)
def test_circuit_C_GROVER_DIFF_OPER(c, sh): Q_program = QuantumProgram() initpattern = numpy.zeros((c + 1), dtype=bool) initpattern[0] = True build_circuit_C_GROVER_DIFF_OPER(Q_program, c, initpattern) result = Q_program.execute(["test"], backend="local_qasm_simulator", shots=sh, silent=True) plot_histogram(result.get_counts('test'))
def use_sympy_backends(): qprogram = QuantumProgram() current_dir = os.path.dirname(os.path.realpath(__file__)) qasm_file = current_dir + "/../qasm/simple.qasm" qasm_circuit = qprogram.load_qasm_file(qasm_file) print("analyzing: " + qasm_file) print(qprogram.get_qasm(qasm_circuit)) # sympy statevector simulator backend = 'local_statevector_simulator_sympy' result = qprogram.execute([qasm_circuit], backend=backend, shots=1, timeout=300) print("final quantum amplitude vector: ") print(result.get_data(qasm_circuit)['statevector']) # sympy unitary simulator backend = 'local_unitary_simulator_sympy' result = qprogram.execute([qasm_circuit], backend=backend, shots=1, timeout=300) print("\nunitary matrix of the circuit: ") print(result.get_data(qasm_circuit)['unitary'])
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 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 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_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 state_tomography(state, n_qubits, shots): # cat target state: [1. 0. 0. ... 0. 0. 1.]/sqrt(2.) if state == 'cat': target = np.zeros(pow(2, n_qubits)) target[0] = 1 target[pow(2, n_qubits)-1] = 1.0 target /= np.sqrt(2.0) # random target state: first column of a random unitary elif state == 'random': target = random_unitary_matrix(pow(2, n_qubits))[0] else: raise QISKitError("Unknown state for tomography.") print("target: {}".format(target)) # Use the local qasm simulator backend = 'local_qasm_simulator' qp = QuantumProgram() # Prepared target state and assess quality qp = target_prep(qp, state, target) prep_result = qp.execute(['prep'], backend='local_statevector_simulator') prep_state = prep_result.get_data('prep')['statevector'] F_prep = state_fidelity(prep_state, target) print('Prepared state fidelity =', F_prep) # Run state tomography simulation and fit data to reconstruct circuit qp, tomo_set, tomo_circuits = add_tomo_circuits(qp) tomo_result = qp.execute(tomo_circuits, backend=backend, shots=shots) tomo_data = tomo.tomography_data(tomo_result, 'prep', tomo_set) rho_fit = tomo.fit_tomography_data(tomo_data) # calculate fidelity and purity of fitted state F_fit = state_fidelity(rho_fit, target) pur = purity(rho_fit) print('Fitted state fidelity =', F_fit) print('Fitted state purity =', str(pur)) return qp
def state_tomography(state, n_qubits, shots): # cat target state: [1. 0. 0. ... 0. 0. 1.]/sqrt(2.) if state == 'cat': target = np.zeros(pow(2, n_qubits)) target[0] = 1 target[pow(2, n_qubits)-1] = 1.0 target /= np.sqrt(2.0) # random target state: first column of a random unitary elif state == 'random': target = random_unitary_matrix(pow(2, n_qubits))[0] else: raise QISKitError("Unknown state for tomography.") print("target: {}".format(target)) # Use the local qasm simulator backend = 'local_qasm_simulator' qp = QuantumProgram() # Prepared target state and assess quality qp = target_prep(qp, state, target) prep_result = qp.execute(['prep'], backend='local_statevector_simulator') prep_state = prep_result.get_data('prep')['statevector'] F_prep = state_fidelity(prep_state, target) print('Prepared state fidelity =', F_prep) # Run state tomography simulation and fit data to reconstruct circuit qp, tomo_set, tomo_circuits = add_tomo_circuits(qp) tomo_result = qp.execute(tomo_circuits, backend=backend, shots=shots) tomo_data = tomo.tomography_data(tomo_result, 'prep', tomo_set) rho_fit = tomo.fit_tomography_data(tomo_data) # calculate fidelity and purity of fitted state F_fit = state_fidelity(rho_fit, target) pur = purity(rho_fit) print('Fitted state fidelity =', F_fit) print('Fitted state purity =', str(pur)) return qp
def test_deterministic_state(self): desired_vector = [0, 1, 0, 0] qp = QuantumProgram() qr = QuantumRegister("qr", 2) qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1]]) qp.add_circuit("qc", qc) result = qp.execute("qc", backend='local_statevector_simulator') statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, "Initializer has low fidelity {0:.2g}.".format(fidelity))
def test_single_qubit(self): desired_vector = [1 / math.sqrt(3), math.sqrt(2) / math.sqrt(3)] qp = QuantumProgram() qr = QuantumRegister("qr", 1) qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0]]) qp.add_circuit("qc", qc) result = qp.execute("qc", backend='local_statevector_simulator') statevector = result.get_statevector() fidelity = state_fidelity(statevector, desired_vector) self.assertGreater( fidelity, self._desired_fidelity, "Initializer has low fidelity {0:.2g}.".format(fidelity))
def test_execute_one_circuit_simulator_online(self): QP_program = QuantumProgram(specs=QPS_SPECS) qc = QP_program.get_circuit("circuitName") qr = QP_program.get_quantum_register("qname") cr = QP_program.get_classical_register("cname") qc.h(qr[1]) qc.measure(qr[0], cr[0]) shots = 1024 # the number of shots in the experiment. QP_program.set_api(API_TOKEN, URL) backend = QP_program.online_simulators()[0] # print(backend) result = QP_program.execute(['circuitName'], backend=backend, shots=shots, max_credits=3, silent=True) self.assertIsInstance(result, Result)
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_execute_several_circuits_simulator_online(self): QP_program = QuantumProgram(specs=QPS_SPECS) qr = QP_program.get_quantum_register("qname") cr = QP_program.get_classical_register("cname") qc2 = QP_program.create_circuit("qc2", [qr], [cr]) qc3 = QP_program.create_circuit("qc3", [qr], [cr]) qc2.h(qr[0]) qc3.h(qr[0]) qc2.measure(qr[0], cr[0]) qc3.measure(qr[0], cr[0]) circuits = ['qc2', 'qc3'] shots = 1024 # the number of shots in the experiment. QP_program.set_api(API_TOKEN, URL) backend = QP_program.online_simulators()[0] result = QP_program.execute(circuits, backend=backend, shots=shots, max_credits=3, silent=True) self.assertIsInstance(result, Result)
def test_execute_program_map(self): """Test execute_program_map. If all correct should return 10010. """ QP_program = QuantumProgram() QP_program.set_api(API_TOKEN, URL) backend = 'local_qasm_simulator' # the backend to run on shots = 100 # the number of shots in the experiment. max_credits = 3 coupling_map = {0: [1], 1: [2], 2: [3], 3: [4]} initial_layout = {("q", 0): ("q", 0), ("q", 1): ("q", 1), ("q", 2): ("q", 2), ("q", 3): ("q", 3), ("q", 4): ("q", 4)} QP_program.load_qasm_file(QASM_FILE_PATH_2, "circuit-dev") circuits = ["circuit-dev"] result = QP_program.execute(circuits, backend=backend, shots=shots, max_credits=max_credits, coupling_map=coupling_map, initial_layout=initial_layout, seed=5455) self.assertEqual(result.get_counts("circuit-dev"), {'10010': 100})
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_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})
from pprint import pprint backend = 'ibmqx2' shots = 1000 max_credits = 5 qp = QuantumProgram() qp.set_api(Qconfig.APItoken, Qconfig.config['url']) pprint(qp.available_backends()) qr = qp.create_quantum_register('qr', 1) cr = qp.create_classical_register('cr', 1) qc = qp.create_circuit('Bell', [qr], [cr]) qc.h(qr[0]) for i in range(4): qc.iden(qr[0]) qc.h(qr[0]) qc.measure(qr[0], cr[0]) circuits = ['Bell'] qobj = qp.compile(circuits, backend) #result = qp.run(qobj, wait=2, timeout=240) #print(result.get_counts('Bell')) result = qp.execute(circuits, backend=backend, shots=shots, max_credits=max_credits,wait=20, timeout=240) print(result)
class LocalQasmSimulatorTest(unittest.TestCase): """Test local qasm simulator.""" @classmethod def setUpClass(cls): cls.moduleName = os.path.splitext(__file__)[0] cls.pdf = PdfPages(cls.moduleName + '.pdf') cls.log = logging.getLogger(__name__) cls.log.setLevel(logging.INFO) logFileName = cls.moduleName + '.log' handler = logging.FileHandler(logFileName) handler.setLevel(logging.INFO) log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:' ' %(message)s'.format(cls.__name__)) formatter = logging.Formatter(log_fmt) handler.setFormatter(formatter) cls.log.addHandler(handler) @classmethod def tearDownClass(cls): cls.pdf.close() def setUp(self): self.seed = 88 self.qasmFileName = os.path.join(qiskit.__path__[0], '../test/python/qasm/example.qasm') self.qp = QuantumProgram() def tearDown(self): pass def test_qasm_simulator_single_shot(self): """Test single shot run.""" shots = 1 self.qp.load_qasm_file(self.qasmFileName, name='example') basis_gates = [] # unroll to base gates unroller = unroll.Unroller( qasm.Qasm(data=self.qp.get_qasm("example")).parse(), unroll.JsonBackend(basis_gates)) circuit = unroller.execute() config = {'shots': shots, 'seed': self.seed} job = {'compiled_circuit': circuit, 'config': config} result = QasmSimulator(job).run() self.assertEqual(result['status'], 'DONE') def test_qasm_simulator(self): """Test data counts output for single circuit run against reference.""" shots = 1024 self.qp.load_qasm_file(self.qasmFileName, name='example') basis_gates = [] # unroll to base gates unroller = unroll.Unroller( qasm.Qasm(data=self.qp.get_qasm("example")).parse(), unroll.JsonBackend(basis_gates)) circuit = unroller.execute() config = {'shots': shots, 'seed': self.seed} job = {'compiled_circuit': circuit, 'config': config} result = QasmSimulator(job).run() expected = {'100 100': 137, '011 011': 131, '101 101': 117, '111 111': 127, '000 000': 131, '010 010': 141, '110 110': 116, '001 001': 124} self.assertEqual(result['data']['counts'], expected) 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_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 profile_qasm_simulator(self): """Profile randomly generated circuits. Writes profile results to <this_module>.prof as well as recording to the log file. number of circuits = 100. number of operations/circuit in [1, 40] number of qubits in [1, 5] """ seed = 88 shots = 1024 nCircuits = 100 minDepth = 1 maxDepth = 40 minQubits = 1 maxQubits = 5 pr = cProfile.Profile() randomCircuits = RandomQasmGenerator(seed, minQubits=minQubits, maxQubits=maxQubits, minDepth=minDepth, maxDepth=maxDepth) randomCircuits.add_circuits(nCircuits) self.qp = randomCircuits.getProgram() pr.enable() self.qp.execute(self.qp.get_circuit_names(), backend='local_qasm_simulator', shots=shots) pr.disable() sout = io.StringIO() ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative') self.log.info('------- start profiling QasmSimulator -----------') ps.print_stats() self.log.info(sout.getvalue()) self.log.info('------- stop profiling QasmSimulator -----------') sout.close() pr.dump_stats(self.moduleName + '.prof') def profile_nqubit_speed_grow_depth(self): """simulation time vs the number of qubits where the circuit depth is 10x the number of simulated qubits. Also creates a pdf file with this module name showing a plot of the results. Compilation is not included in speed. """ import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator qubitRangeMax = 15 nQubitList = range(1,qubitRangeMax + 1) nCircuits = 10 shots = 1024 seed = 88 maxTime = 30 # seconds; timing stops when simulation time exceeds this number fmtStr1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1}, elapsed_time:{2:.2f}' fmtStr2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}' fmtStr3 = 'minDepth={minDepth}, maxDepth={maxDepth}, num circuits={nCircuits}, shots={shots}' backendList = ['local_qasm_simulator', 'local_unitary_simulator'] if shutil.which('qasm_simulator'): backendList.append('local_qasm_cpp_simulator') else: self.log.info('profile_nqubit_speed::\"qasm_simulator\" executable not in path...skipping') fig = plt.figure(0) plt.clf() ax = fig.add_axes((0.1, 0.25, 0.8, 0.6)) for i, backend in enumerate(backendList): elapsedTime = np.zeros(len(nQubitList)) if backend is 'local_unitary_simulator': doMeasure = False else: doMeasure = True j, timedOut = 0, False while j < qubitRangeMax and not timedOut: nQubits = nQubitList[j] randomCircuits = RandomQasmGenerator(seed, minQubits=nQubits, maxQubits=nQubits, minDepth=nQubits*10, maxDepth=nQubits*10) randomCircuits.add_circuits(nCircuits, doMeasure=doMeasure) qp = randomCircuits.getProgram() cnames = qp.get_circuit_names() qobj = qp.compile(cnames, backend=backend, shots=shots, seed=seed) start = time.perf_counter() results = qp.run(qobj) stop = time.perf_counter() elapsedTime[j] = stop - start if elapsedTime[j] > maxTime: timedOut = True self.log.info(fmtStr1.format(nQubits, backend, elapsedTime[j])) if backend is not 'local_unitary_simulator': for name in cnames: self.log.info(fmtStr2.format( backend, name, len(qp.get_circuit(name)), results.get_data(name))) j += 1 ax.xaxis.set_major_locator(MaxNLocator(integer=True)) if backend is 'local_unitary_simulator': ax.plot(nQubitList[:j], elapsedTime[:j], label=backend, marker='o') else: ax.plot(nQubitList[:j], elapsedTime[:j]/shots, label=backend, marker='o') ax.set_yscale('log', basey=10) ax.set_xlabel('number of qubits') ax.set_ylabel('process time/shot') ax.set_title('profile_nqubit_speed_grow_depth') fig.text(0.1, 0.05, fmtStr3.format(minDepth='10*nQubits', maxDepth='10*nQubits', nCircuits=nCircuits, shots=shots)) ax.legend() self.pdf.savefig(fig) def profile_nqubit_speed_constant_depth(self): """simulation time vs the number of qubits where the circuit depth is fixed at 40. Also creates a pdf file with this module name showing a plot of the results. Compilation is not included in speed. """ import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator qubitRangeMax = 15 nQubitList = range(1,qubitRangeMax + 1) maxDepth = 40 minDepth = 40 nCircuits = 10 shots = 1024 seed = 88 maxTime = 30 # seconds; timing stops when simulation time exceeds this number fmtStr1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1}, elapsed_time:{2:.2f}' fmtStr2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}' fmtStr3 = 'minDepth={minDepth}, maxDepth={maxDepth}, num circuits={nCircuits}, shots={shots}' backendList = ['local_qasm_simulator', 'local_unitary_simulator'] if shutil.which('qasm_simulator'): backendList.append('local_qasm_cpp_simulator') else: self.log.info('profile_nqubit_speed::\"qasm_simulator\" executable not in path...skipping') fig = plt.figure(0) plt.clf() ax = fig.add_axes((0.1, 0.2, 0.8, 0.6)) for i, backend in enumerate(backendList): elapsedTime = np.zeros(len(nQubitList)) if backend is 'local_unitary_simulator': doMeasure = False else: doMeasure = True j, timedOut = 0, False while j < qubitRangeMax and not timedOut: nQubits = nQubitList[j] randomCircuits = RandomQasmGenerator(seed, minQubits=nQubits, maxQubits=nQubits, minDepth=minDepth, maxDepth=maxDepth) randomCircuits.add_circuits(nCircuits, doMeasure=doMeasure) qp = randomCircuits.getProgram() cnames = qp.get_circuit_names() qobj = qp.compile(cnames, backend=backend, shots=shots, seed=seed) start = time.perf_counter() results = qp.run(qobj) stop = time.perf_counter() elapsedTime[j] = stop - start if elapsedTime[j] > maxTime: timedOut = True self.log.info(fmtStr1.format(nQubits, backend, elapsedTime[j])) if backend is not 'local_unitary_simulator': for name in cnames: self.log.info(fmtStr2.format( backend, name, len(qp.get_circuit(name)), results.get_data(name))) j += 1 ax.xaxis.set_major_locator(MaxNLocator(integer=True)) if backend is 'local_unitary_simulator': ax.plot(nQubitList[:j], elapsedTime[:j], label=backend, marker='o') else: ax.plot(nQubitList[:j], elapsedTime[:j]/shots, label=backend, marker='o') ax.set_yscale('log', basey=10) ax.set_xlabel('number of qubits') ax.set_ylabel('process time/shot') ax.set_title('profile_nqubit_speed_constant_depth') fig.text(0.1, 0.05, fmtStr3.format(minDepth=minDepth, maxDepth=maxDepth, nCircuits=nCircuits, shots=shots)) ax.legend() self.pdf.savefig(fig)
class MapperTest(QiskitTestCase): """Test the mapper.""" def setUp(self): self.seed = 42 self.qp = QuantumProgram() def test_mapper_overoptimization(self): """ The mapper should not change the semantics of the input. An overoptimization introduced the issue #81: https://github.com/QISKit/qiskit-sdk-py/issues/81 """ self.qp.load_qasm_file(self._get_resource_path('qasm/overoptimization.qasm'), name='test') coupling_map = [[0, 2], [1, 2], [2, 3]] result1 = self.qp.execute(["test"], backend="local_qasm_simulator", coupling_map=coupling_map) count1 = result1.get_counts("test") result2 = self.qp.execute(["test"], backend="local_qasm_simulator", coupling_map=None) count2 = result2.get_counts("test") self.assertEqual(count1.keys(), count2.keys(), ) def test_math_domain_error(self): """ The math library operates over floats and introduce floating point errors that should be avoided. See: https://github.com/QISKit/qiskit-sdk-py/issues/111 """ self.qp.load_qasm_file(self._get_resource_path('qasm/math_domain_error.qasm'), name='test') coupling_map = [[0, 2], [1, 2], [2, 3]] shots = 2000 result = self.qp.execute("test", backend="local_qasm_simulator", coupling_map=coupling_map, seed=self.seed, shots=shots) counts = result.get_counts("test") target = {'0001': shots / 2, '0101': shots / 2} threshold = 0.04 * shots self.assertDictAlmostEqual(counts, target, threshold) def test_optimize_1q_gates_issue159(self): """Test change in behavior for optimize_1q_gates that removes u1(2*pi) rotations. See: https://github.com/QISKit/qiskit-sdk-py/issues/159 """ self.qp = QuantumProgram() qr = self.qp.create_quantum_register('qr', 2) cr = self.qp.create_classical_register('cr', 2) qc = self.qp.create_circuit('Bell', [qr], [cr]) qc.h(qr[0]) qc.cx(qr[1], qr[0]) qc.cx(qr[1], qr[0]) qc.cx(qr[1], qr[0]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) backend = 'local_qasm_simulator' coupling_map = [[1, 0], [2, 0], [2, 1], [2, 4], [3, 2], [3, 4]] initial_layout = {('qr', 0): ('q', 1), ('qr', 1): ('q', 0)} qobj = self.qp.compile(["Bell"], backend=backend, initial_layout=initial_layout, coupling_map=coupling_map) self.assertEqual(self.qp.get_compiled_qasm(qobj, "Bell"), EXPECTED_QASM_1Q_GATES_3_5) def test_random_parameter_circuit(self): """Run a circuit with randomly generated parameters.""" self.qp.load_qasm_file(self._get_resource_path('qasm/random_n5_d5.qasm'), name='rand') coupling_map = [[0, 1], [1, 2], [2, 3], [3, 4]] shots = 1024 result1 = self.qp.execute(["rand"], backend="local_qasm_simulator", coupling_map=coupling_map, shots=shots, seed=self.seed) counts = result1.get_counts("rand") expected_probs = { '00000': 0.079239867254200971, '00001': 0.032859032998526903, '00010': 0.10752610993531816, '00011': 0.018818532050952699, '00100': 0.054830807251011054, '00101': 0.0034141983951965164, '00110': 0.041649309748902276, '00111': 0.039967731207338125, '01000': 0.10516937819949743, '01001': 0.026635620063700002, '01010': 0.0053475143548793866, '01011': 0.01940513314416064, '01100': 0.0044028405481225047, '01101': 0.057524760052126644, '01110': 0.010795354134597078, '01111': 0.026491296821535528, '10000': 0.094827455395274859, '10001': 0.0008373965072688836, '10010': 0.029082297894094441, '10011': 0.012386622870598416, '10100': 0.018739140061148799, '10101': 0.01367656456536896, '10110': 0.039184170706009248, '10111': 0.062339335178438288, '11000': 0.00293674365989009, '11001': 0.012848433960739968, '11010': 0.018472497159499782, '11011': 0.0088903691234912003, '11100': 0.031305389080034329, '11101': 0.0004788556283690458, '11110': 0.002232419390471667, '11111': 0.017684822659235985 } target = {key: shots * val for key, val in expected_probs.items()} threshold = 0.04 * shots self.assertDictAlmostEqual(counts, target, threshold) def test_symbolic_unary(self): """Test symbolic math in DAGBackend and optimizer with a prefix. See: https://github.com/QISKit/qiskit-sdk-py/issues/172 """ ast = qasm.Qasm(filename=self._get_resource_path( 'qasm/issue172_unary.qasm')).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_UNARY) def test_symbolic_binary(self): """Test symbolic math in DAGBackend and optimizer with a binary operation. See: https://github.com/QISKit/qiskit-sdk-py/issues/172 """ ast = qasm.Qasm(filename=self._get_resource_path( 'qasm/issue172_binary.qasm')).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_BINARY) def test_symbolic_extern(self): """Test symbolic math in DAGBackend and optimizer with an external function. See: https://github.com/QISKit/qiskit-sdk-py/issues/172 """ ast = qasm.Qasm(filename=self._get_resource_path( 'qasm/issue172_extern.qasm')).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_EXTERN) def test_symbolic_power(self): """Test symbolic math in DAGBackend and optimizer with a power (^). See: https://github.com/QISKit/qiskit-sdk-py/issues/172 """ ast = qasm.Qasm(data=QASM_SYMBOLIC_POWER).parse() unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"])) unr.execute() circ = mapper.optimize_1q_gates(unr.backend.circuit) self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_POWER) def test_already_mapped(self): """Test that if the circuit already matches the backend topology, it is not remapped. See: https://github.com/QISKit/qiskit-sdk-py/issues/342 """ self.qp = QuantumProgram() qr = self.qp.create_quantum_register('qr', 16) cr = self.qp.create_classical_register('cr', 16) qc = self.qp.create_circuit('native_cx', [qr], [cr]) qc.cx(qr[3], qr[14]) qc.cx(qr[5], qr[4]) qc.h(qr[9]) qc.cx(qr[9], qr[8]) qc.x(qr[11]) qc.cx(qr[3], qr[4]) qc.cx(qr[12], qr[11]) qc.cx(qr[13], qr[4]) for j in range(16): qc.measure(qr[j], cr[j]) backend = 'local_qasm_simulator' coupling_map = [[1, 0], [1, 2], [2, 3], [3, 4], [3, 14], [5, 4], [6, 5], [6, 7], [6, 11], [7, 10], [8, 7], [9, 8], [9, 10], [11, 10], [12, 5], [12, 11], [12, 13], [13, 4], [13, 14], [15, 0], [15, 2], [15, 14]] qobj = self.qp.compile(["native_cx"], backend=backend, coupling_map=coupling_map) cx_qubits = [x["qubits"] for x in qobj["circuits"][0]["compiled_circuit"]["operations"] if x["name"] == "cx"] self.assertEqual(sorted(cx_qubits), [[3, 4], [3, 14], [5, 4], [9, 8], [12, 11], [13, 4]])
qc.x(a[0]) # Set input a = 0...0001 qc.x(b) # Set input b = 1...1111 # Apply the adder qc += adder_subcircuit # Measure the output register in the computational basis 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. ############################################################### qp.set_api(Qconfig.APItoken, Qconfig.config["url"]) # First version: not mapped result = qp.execute(["rippleadd"], backend=backend, coupling_map=None, shots=1024) print(result) print(result.get_counts("rippleadd")) # Second version: mapped to 2x8 array coupling graph obj = qp.compile(["rippleadd"], backend=backend, coupling_map=coupling_map, shots=1024) result = qp.run(obj) print(result) print(result.get_ran_qasm("rippleadd")) print(result.get_counts("rippleadd")) # Both versions should give the same distribution
qc.h(q[0]) qc.measure(q[0], c0[0]) 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. ############################################################### qp.set_api(Qconfig.APItoken, Qconfig.config["url"]) # Experiment does not support feedback, so we use the simulator # First version: not mapped result = qp.execute(["teleport"], backend=backend, coupling_map=None, shots=1024) print(result) print(result.get_counts("teleport")) # Second version: mapped to qx2 coupling graph result = qp.execute(["teleport"], backend=backend, coupling_map=coupling_map, shots=1024) print(result) print(result.get_ran_qasm("teleport")) print(result.get_counts("teleport")) # Both versions should give the same distribution
for i in range(4): qc.cx(q[i], q[i+1]) # Insert a barrier before measurement qc.barrier() # Measure all of the qubits in the standard basis for i in range(5): qc.measure(q[i], c[i]) ############################################################### # Set up the API and execute the program. ############################################################### qp.set_api(Qconfig.APItoken, Qconfig.config["url"]) # First version: no mapping print("no mapping, simulator") result = qp.execute(["ghz"], backend='ibmqx_qasm_simulator', coupling_map=None, shots=1024) print(result) print(result.get_counts("ghz")) # Second version: map to qx2 coupling graph and simulate print("map to %s, simulator" % backend) result = qp.execute(["ghz"], backend='ibmqx_qasm_simulator', coupling_map=coupling_map, shots=1024) print(result) print(result.get_counts("ghz")) # Third version: map to qx2 coupling graph and simulate locally print("map to %s, local qasm simulator" % backend) result = qp.execute(["ghz"], backend='local_qasm_simulator', coupling_map=coupling_map, shots=1024) print(result)
class LocalUnitarySimulatorTest(QiskitTestCase): """Test local unitary simulator.""" def setUp(self): self.seed = 88 self.qasm_filename = self._get_resource_path('qasm/example.qasm') self.qp = QuantumProgram() def tearDown(self): pass def test_unitary_simulator(self): """test generation of circuit unitary""" self.qp.load_qasm_file(self.qasm_filename, name='example') basis_gates = [] # unroll to base gates unroller = unroll.Unroller( qasm.Qasm(data=self.qp.get_qasm('example')).parse(), unroll.JsonBackend(basis_gates)) circuit = unroller.execute() # strip measurements from circuit to avoid warnings circuit['operations'] = [op for op in circuit['operations'] if op['name'] != 'measure'] # the simulator is expecting a JSON format, so we need to convert it # back to JSON qobj = { 'id': 'unitary', 'config': { 'max_credits': None, 'shots': 1, 'backend_name': 'local_unitary_simulator_py' }, 'circuits': [ { 'name': 'test', 'compiled_circuit': circuit, 'compiled_circuit_qasm': self.qp.get_qasm('example'), 'config': { 'coupling_map': None, 'basis_gates': None, 'layout': None, 'seed': None } } ] } # numpy.savetxt currently prints complex numbers in a way # loadtxt can't read. To save file do, # fmtstr=['% .4g%+.4gj' for i in range(numCols)] # np.savetxt('example_unitary_matrix.dat', numpyMatrix, fmt=fmtstr, # delimiter=',') expected = np.loadtxt(self._get_resource_path('example_unitary_matrix.dat'), dtype='complex', delimiter=',') q_job = QuantumJob(qobj, backend=UnitarySimulatorPy(), preformatted=True) result = UnitarySimulatorPy().run(q_job).result() self.assertTrue(np.allclose(result.get_unitary('test'), expected, rtol=1e-3)) def test_two_unitary_simulator(self): """test running two circuits This test is similar to one in test_quantumprogram but doesn't use multiprocessing. """ qr = QuantumRegister(2) cr = ClassicalRegister(1) qc1 = QuantumCircuit(qr, cr) qc2 = QuantumCircuit(qr, cr) qc1.h(qr) qc2.cx(qr[0], qr[1]) backend = UnitarySimulatorPy() qobj = compile([qc1, qc2], backend=backend) job = backend.run(QuantumJob(qobj, backend=backend, preformatted=True)) unitary1 = job.result().get_unitary(qc1) unitary2 = job.result().get_unitary(qc2) 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 profile_unitary_simulator(self): """Profile randomly generated circuits. Writes profile results to <this_module>.prof as well as recording to the log file. number of circuits = 100. number of operations/circuit in [1, 40] number of qubits in [1, 5] """ n_circuits = 100 max_depth = 40 max_qubits = 5 pr = cProfile.Profile() random_circuits = RandomQasmGenerator(seed=self.seed, max_depth=max_depth, max_qubits=max_qubits) random_circuits.add_circuits(n_circuits, do_measure=False) self.qp = random_circuits.get_program() pr.enable() self.qp.execute(self.qp.get_circuit_names(), backend=UnitarySimulatorPy()) pr.disable() sout = io.StringIO() ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative') self.log.info('------- start profiling UnitarySimulatorPy -----------') ps.print_stats() self.log.info(sout.getvalue()) self.log.info('------- stop profiling UnitarySimulatorPy -----------') sout.close() pr.dump_stats(self.moduleName + '.prof')
qft(qft5, q, 5) qft5.barrier() for j in range(5): qft5.measure(q[j], c[j]) print(qft3.qasm()) print(qft4.qasm()) print(qft5.qasm()) ############################################################### # Set up the API and execute the program. ############################################################### qp.set_api(Qconfig.APItoken, Qconfig.config["url"]) result = qp.execute(["qft3", "qft4", "qft5"], backend='ibmqx_qasm_simulator', coupling_map=coupling_map, shots=1024) print(result) print(result.get_ran_qasm("qft3")) print(result.get_ran_qasm("qft4")) print(result.get_ran_qasm("qft5")) print(result.get_counts("qft3")) print(result.get_counts("qft4")) print(result.get_counts("qft5")) result = qp.execute(["qft3"], backend=backend, coupling_map=coupling_map, shots=1024, timeout=120) print(result) print(result.get_ran_qasm("qft3")) print(result.get_counts("qft3"))
class TestLocalQasmSimulatorPy(QiskitTestCase): """Test local_qasm_simulator_py.""" @classmethod def setUpClass(cls): super().setUpClass() if do_profiling: cls.pdf = PdfPages(cls.moduleName + '.pdf') @classmethod def tearDownClass(cls): if do_profiling: cls.pdf.close() def setUp(self): self.seed = 88 self.qasm_filename = self._get_resource_path('qasm/example.qasm') self.qp = QuantumProgram() self.qp.load_qasm_file(self.qasm_filename, name='example') basis_gates = [] # unroll to base gates unroller = unroll.Unroller( qasm.Qasm(data=self.qp.get_qasm('example')).parse(), unroll.JsonBackend(basis_gates)) circuit = unroller.execute() circuit_config = {'coupling_map': None, 'basis_gates': 'u1,u2,u3,cx,id', 'layout': None, 'seed': self.seed} resources = {'max_credits': 3} self.qobj = {'id': 'test_sim_single_shot', 'config': { 'max_credits': resources['max_credits'], 'shots': 1024, 'backend_name': 'local_qasm_simulator_py', }, 'circuits': [ { 'name': 'test', 'compiled_circuit': circuit, 'compiled_circuit_qasm': None, 'config': circuit_config } ]} self.q_job = QuantumJob(self.qobj, backend=QasmSimulatorPy(), circuit_config=circuit_config, seed=self.seed, resources=resources, preformatted=True) def tearDown(self): pass def test_qasm_simulator_single_shot(self): """Test single shot run.""" shots = 1 self.qobj['config']['shots'] = shots result = QasmSimulatorPy().run(self.q_job).result() self.assertEqual(result.get_status(), 'COMPLETED') def test_qasm_simulator(self): """Test data counts output for single circuit run against reference.""" result = QasmSimulatorPy().run(self.q_job).result() shots = 1024 threshold = 0.04 * shots counts = result.get_counts('test') target = {'100 100': shots / 8, '011 011': shots / 8, '101 101': shots / 8, '111 111': shots / 8, '000 000': shots / 8, '010 010': shots / 8, '110 110': shots / 8, '001 001': shots / 8} self.assertDictAlmostEqual(counts, target, threshold) 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() qobj = { 'id': 'test_if_qobj', 'config': { 'max_credits': 3, 'shots': shots, 'backend_name': 'local_qasm_simulator_py', }, '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, backend=QasmSimulatorPy(), preformatted=True) result = QasmSimulatorPy().run(q_job).result() 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=%s', 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=%s', result_if_false) self.assertTrue(result_if_true['counts']['111'] == 100) self.assertTrue(result_if_false['counts']['001'] == 100) @unittest.skipIf(version_info.minor == 5, "Due to gate ordering issues with Python 3.5 \ we have to disable this test until fixed") 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_py' 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 %s', data) self.log.info('test_teleport: alice %s', alice) self.log.info('test_teleport: bob %s', 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 = %s', error) self.assertLess(error, 0.05) @unittest.skipIf(not do_profiling, "skipping simulator profiling.") def profile_qasm_simulator(self): """Profile randomly generated circuits. Writes profile results to <this_module>.prof as well as recording to the log file. number of circuits = 100. number of operations/circuit in [1, 40] number of qubits in [1, 5] """ seed = 88 shots = 1024 n_circuits = 100 min_depth = 1 max_depth = 40 min_qubits = 1 max_qubits = 5 pr = cProfile.Profile() random_circuits = RandomQasmGenerator(seed, min_qubits=min_qubits, max_qubits=max_qubits, min_depth=min_depth, max_depth=max_depth) random_circuits.add_circuits(n_circuits) self.qp = random_circuits.get_program() pr.enable() self.qp.execute(self.qp.get_circuit_names(), backend='local_qasm_simulator_py', shots=shots) pr.disable() sout = io.StringIO() ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative') self.log.info('------- start profiling QasmSimulatorPy -----------') ps.print_stats() self.log.info(sout.getvalue()) self.log.info('------- stop profiling QasmSimulatorPy -----------') sout.close() pr.dump_stats(self.moduleName + '.prof') @unittest.skipIf(not do_profiling, "skipping simulator profiling.") def profile_nqubit_speed_grow_depth(self): """simulation time vs the number of qubits where the circuit depth is 10x the number of simulated qubits. Also creates a pdf file with this module name showing a plot of the results. Compilation is not included in speed. """ import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator qubit_range_max = 15 n_qubit_list = range(1, qubit_range_max + 1) n_circuits = 10 shots = 1024 seed = 88 max_time = 30 # seconds; timing stops when simulation time exceeds this number fmt_str1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1}, elapsed_time:{2:.2f}' fmt_str2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}' fmt_str3 = 'minDepth={minDepth}, maxDepth={maxDepth}, num circuits={nCircuits},' \ 'shots={shots}' backend_list = ['local_qasm_simulator_py', 'local_unitary_simulator_py'] if shutil.which('qasm_simulator'): backend_list.append('local_qasm_simulator_cpp') else: self.log.info('profile_nqubit_speed::\"qasm_simulator\" executable' 'not in path...skipping') fig = plt.figure(0) plt.clf() ax = fig.add_axes((0.1, 0.25, 0.8, 0.6)) for _, backend in enumerate(backend_list): elapsed_time = np.zeros(len(n_qubit_list)) if backend == 'local_unitary_simulator_py': do_measure = False else: do_measure = True j, timed_out = 0, False while j < qubit_range_max and not timed_out: n_qubits = n_qubit_list[j] random_circuits = RandomQasmGenerator(seed, min_qubits=n_qubits, max_qubits=n_qubits, min_depth=n_qubits * 10, max_depth=n_qubits * 10) random_circuits.add_circuits(n_circuits, do_measure=do_measure) qp = random_circuits.get_program() c_names = qp.get_circuit_names() qobj = qp.compile(c_names, backend=backend, shots=shots, seed=seed) start = time.perf_counter() results = qp.run(qobj) stop = time.perf_counter() elapsed_time[j] = stop - start if elapsed_time[j] > max_time: timed_out = True self.log.info(fmt_str1.format(n_qubits, backend, elapsed_time[j])) if backend != 'local_unitary_simulator_py': for name in c_names: log_str = fmt_str2.format( backend, name, len(qp.get_circuit(name)), results.get_data(name)) self.log.info(log_str) j += 1 ax.xaxis.set_major_locator(MaxNLocator(integer=True)) if backend == 'local_unitary_simulator_py': ax.plot(n_qubit_list[:j], elapsed_time[:j], label=backend, marker='o') else: ax.plot(n_qubit_list[:j], elapsed_time[:j]/shots, label=backend, marker='o') ax.set_yscale('log', basey=10) ax.set_xlabel('number of qubits') ax.set_ylabel('process time/shot') ax.set_title('profile_nqubit_speed_grow_depth') fig.text(0.1, 0.05, fmt_str3.format(minDepth='10*nQubits', maxDepth='10*nQubits', nCircuits=n_circuits, shots=shots)) ax.legend() self.pdf.savefig(fig) @unittest.skipIf(not do_profiling, "skipping simulator profiling.") def profile_nqubit_speed_constant_depth(self): """simulation time vs the number of qubits where the circuit depth is fixed at 40. Also creates a pdf file with this module name showing a plot of the results. Compilation is not included in speed. """ import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator qubit_range_max = 15 n_qubit_list = range(1, qubit_range_max + 1) max_depth = 40 min_depth = 40 n_circuits = 10 shots = 1024 seed = 88 max_time = 30 # seconds; timing stops when simulation time exceeds this number fmt_str1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1},' \ 'elapsed_time:{2:.2f}' fmt_str2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}' fmt_str3 = 'minDepth={minDepth}, maxDepth={maxDepth},' \ 'num circuits={nCircuits}, shots={shots}' backend_list = ['local_qasm_simulator_py', 'local_unitary_simulator_py'] if shutil.which('qasm_simulator'): backend_list.append('local_qasm_simulator_cpp') else: self.log.info('profile_nqubit_speed::\"qasm_simulator\" executable' 'not in path...skipping') fig = plt.figure(0) plt.clf() ax = fig.add_axes((0.1, 0.2, 0.8, 0.6)) for _, backend in enumerate(backend_list): elapsedTime = np.zeros(len(n_qubit_list)) if backend == 'local_unitary_simulator_py': doMeasure = False else: doMeasure = True j, timedOut = 0, False while j < qubit_range_max and not timedOut: nQubits = n_qubit_list[j] randomCircuits = RandomQasmGenerator(seed, min_qubits=nQubits, max_qubits=nQubits, min_depth=min_depth, max_depth=max_depth) randomCircuits.add_circuits(n_circuits, do_measure=doMeasure) qp = randomCircuits.get_program() cnames = qp.get_circuit_names() qobj = qp.compile(cnames, backend=backend, shots=shots, seed=seed) start = time.perf_counter() results = qp.run(qobj) stop = time.perf_counter() elapsedTime[j] = stop - start if elapsedTime[j] > max_time: timedOut = True self.log.info(fmt_str1.format(nQubits, backend, elapsedTime[j])) if backend != 'local_unitary_simulator_py': for name in cnames: log_str = fmt_str2.format( backend, name, len(qp.get_circuit(name)), results.get_data(name)) self.log.info(log_str) j += 1 ax.xaxis.set_major_locator(MaxNLocator(integer=True)) if backend == 'local_unitary_simulator_py': ax.plot(n_qubit_list[:j], elapsedTime[:j], label=backend, marker='o') else: ax.plot(n_qubit_list[:j], elapsedTime[:j]/shots, label=backend, marker='o') ax.set_yscale('log', basey=10) ax.set_xlabel('number of qubits') ax.set_ylabel('process time/shot') ax.set_title('profile_nqubit_speed_constant_depth') fig.text(0.1, 0.05, fmt_str3.format(minDepth=min_depth, maxDepth=max_depth, nCircuits=n_circuits, shots=shots)) ax.legend() self.pdf.savefig(fig)
class LocalUnitarySimulatorTest(unittest.TestCase): """Test local unitary simulator.""" def setUp(self): self.seed = 88 self.qasmFileName = os.path.join(qiskit.__path__[0], '../test/python/qasm/example.qasm') self.qp = QuantumProgram() self.moduleName = os.path.splitext(__file__)[0] self.modulePath = os.path.dirname(__file__) logFileName = self.moduleName + '.log' logging.basicConfig(filename=logFileName, level=logging.INFO) def tearDown(self): pass def test_unitary_simulator(self): """test generation of circuit unitary""" shots = 1024 self.qp.load_qasm_file(self.qasmFileName, name='example') basis_gates = [] # unroll to base gates unroller = unroll.Unroller( qasm.Qasm(data=self.qp.get_qasm("example")).parse(), unroll.JsonBackend(basis_gates)) circuit = unroller.execute() # if we want to manipulate the circuit, we have to convert it to a dict circuit = json.loads(circuit.decode()) #strip measurements from circuit to avoid warnings circuit['operations'] = [op for op in circuit['operations'] if op['name'] != 'measure'] # the simulator is expecting a JSON format, so we need to convert it back to JSON job = {'compiled_circuit': json.dumps(circuit).encode()} # numpy savetxt is currently prints complex numbers in a way # loadtxt can't read. To save file do, # fmtstr=['% .4g%+.4gj' for i in range(numCols)] # np.savetxt('example_unitary_matrix.dat', numpyMatrix, fmt=fmtstr, delimiter=',') expected = np.loadtxt(os.path.join(self.modulePath, 'example_unitary_matrix.dat'), dtype='complex', delimiter=',') result = UnitarySimulator(job).run() self.assertTrue(np.allclose(result['data']['unitary'], expected, rtol=1e-3)) def profile_unitary_simulator(self): """Profile randomly generated circuits. Writes profile results to <this_module>.prof as well as recording to the log file. number of circuits = 100. number of operations/circuit in [1, 40] number of qubits in [1, 5] """ nCircuits = 100 maxDepth = 40 maxQubits = 5 pr = cProfile.Profile() randomCircuits = RandomQasmGenerator(seed=self.seed, maxDepth=maxDepth, maxQubits=maxQubits) randomCircuits.add_circuits(nCircuits, doMeasure=False) self.qp = randomCircuits.getProgram() pr.enable() self.qp.execute(self.qp.get_circuit_names(), backend='local_unitary_simulator') pr.disable() sout = io.StringIO() ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative') logging.info('------- start profiling UnitarySimulator -----------') ps.print_stats() logging.info(sout.getvalue()) logging.info('------- stop profiling UnitarySimulator -----------') sout.close() pr.dump_stats(self.moduleName + '.prof')
def test_example_swap_bits(self): """Test a toy example swapping a set bit around. Uses the mapper. Pass if results are correct. """ backend = "ibmqx_qasm_simulator" coupling_map = {0: [1, 8], 1: [2, 9], 2: [3, 10], 3: [4, 11], 4: [5, 12], 5: [6, 13], 6: [7, 14], 7: [15], 8: [9], 9: [10], 10: [11], 11: [12], 12: [13], 13: [14], 14: [15]} def swap(qc, q0, q1): """Swap gate.""" qc.cx(q0, q1) qc.cx(q1, q0) qc.cx(q0, q1) n = 3 # make this at least 3 QPS_SPECS = { "circuits": [{ "name": "swapping", "quantum_registers": [{ "name": "q", "size": n}, {"name": "r", "size": n} ], "classical_registers": [ {"name": "ans", "size": 2*n}, ] }] } qp = QuantumProgram(specs=QPS_SPECS) qp.set_api(API_TOKEN, URL) if backend not in qp.online_simulators(): return qc = qp.get_circuit("swapping") q = qp.get_quantum_register("q") r = qp.get_quantum_register("r") ans = qp.get_classical_register("ans") # Set the first bit of q qc.x(q[0]) # Swap the set bit swap(qc, q[0], q[n-1]) swap(qc, q[n-1], r[n-1]) swap(qc, r[n-1], q[1]) swap(qc, q[1], r[1]) # 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]) # First version: no mapping result = qp.execute(["swapping"], backend=backend, coupling_map=None, shots=1024, seed=14) self.assertEqual(result.get_counts("swapping"), {'010000': 1024}) # Second version: map to coupling graph result = qp.execute(["swapping"], backend=backend, coupling_map=coupling_map, shots=1024, seed=14) self.assertEqual(result.get_counts("swapping"), {'010000': 1024})
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')
from qiskit import QuantumProgram qp = QuantumProgram() qr = qp.create_quantum_register('qr',2) cr = qp.create_classical_register('cr',2) qc = qp.create_circuit('Bell',[qr],[cr]) qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) result = qp.execute('Bell') print(result.get_counts('Bell'))
coupling_map = {0: [1, 2], 1: [2], 2: [], 3: [2, 4], 4: [2]} circuits = ['initializer_circ'] shots = 1024 ############################################################### # Set up the API and execute the program. ############################################################### Q_program.set_api(Qconfig.APItoken, Qconfig.config["url"]) # Desired vector print("Desired probabilities...") print(str(list(map(lambda x: format(abs(x * x), '.3f'), desired_vector)))) # Initialize on local simulator result = Q_program.execute(circuits, backend='local_qasm_simulator', wait=2, timeout=240, shots=shots) print("Probabilities from simulator...[%s]" % result) n_qubits_qureg = qr.size counts = result.get_counts("initializer_circ") qubit_strings = [format(i, '0%sb' % n_qubits_qureg) for i in range(2 ** n_qubits_qureg)] print([format(counts.get(s, 0) / shots, '.3f') for s in qubit_strings])