def test_2q_local_invariance_simple(self): """Check the local invariance parameters for known simple cases. """ sim = UnitarySimulatorPy() qr = QuantumRegister(2, name='q') qc = QuantumCircuit(qr) U = execute(qc, sim).result().get_unitary() vec = two_qubit_local_invariants(U) assert_allclose(vec, [1, 0, 3]) qr = QuantumRegister(2, name='q') qc = QuantumCircuit(qr) qc.cx(qr[1], qr[0]) U = execute(qc, sim).result().get_unitary() vec = two_qubit_local_invariants(U) assert_allclose(vec, [0, 0, 1]) qr = QuantumRegister(2, name='q') qc = QuantumCircuit(qr) qc.cx(qr[1], qr[0]) qc.cx(qr[0], qr[1]) U = execute(qc, sim).result().get_unitary() vec = two_qubit_local_invariants(U) assert_allclose(vec, [0, 0, -1]) qr = QuantumRegister(2, name='q') qc = QuantumCircuit(qr) qc.swap(qr[1], qr[0]) U = execute(qc, sim).result().get_unitary() vec = two_qubit_local_invariants(U) assert_allclose(vec, [-1, 0, -3])
def test_executing_parameterized_instruction_bound_early( self, target_type): """Verify bind-before-execute preserves bound values.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2482 theta = Parameter('theta') sub_qc = QuantumCircuit(2) sub_qc.h(0) sub_qc.cx(0, 1) sub_qc.rz(theta, [0, 1]) sub_qc.cx(0, 1) sub_qc.h(0) if target_type == 'gate': sub_inst = sub_qc.to_gate() elif target_type == 'instruction': sub_inst = sub_qc.to_instruction() unbound_qc = QuantumCircuit(2, 1) unbound_qc.append(sub_inst, [0, 1], []) unbound_qc.measure(0, 0) for assign_fun in ['bind_parameters', 'assign_parameters']: with self.subTest(assign_fun=assign_fun): bound_qc = getattr(unbound_qc, assign_fun)({ theta: numpy.pi / 2 }) shots = 1024 job = execute(bound_qc, backend=BasicAer.get_backend('qasm_simulator'), shots=shots) self.assertDictAlmostEqual(job.result().get_counts(), {'1': shots}, 0.05 * shots)
def simulate_circuit(circuit: QuantumCircuit): simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=1000) result = job.result() counts = result.get_counts(circuit) figure = plot_histogram(counts) figure.savefig("./test/results/plot.pdf")
def test_execute_two_remote(self): """Test executing two circuits on a remote backend.""" qc = ReferenceCircuits.bell() qc_extra = QuantumCircuit(2, 2) qc_extra.measure_all() job = execute([qc, qc_extra], self.sim_backend, seed_transpiler=self.seed) results = job.result() self.assertIsInstance(results, Result)
def test_ibmq_result_fields(self, provider): """Test components of a result from a remote simulator.""" remote_backend = provider.get_backend(local=False, simulator=True) remote_result = execute(self._qc1, remote_backend).result() self.assertEqual(remote_result.backend_name, remote_backend.name()) self.assertIsInstance(remote_result.job_id, str) self.assertEqual(remote_result.status, 'COMPLETED') self.assertEqual(remote_result.results[0].status, 'DONE')
def test_ibmq_result_fields(self): """Test components of a result from a remote simulator.""" remote_result = execute(self._qc1, self.sim_backend).result() self.assertIsInstance(remote_result, Result) self.assertEqual(remote_result.backend_name, self.sim_backend.name()) self.assertIsInstance(remote_result.job_id, str) self.assertEqual(remote_result.status, 'COMPLETED') self.assertEqual(remote_result.results[0].status, 'DONE')
def quick_simulate(circuit, shots=1024, x="0", verbose=False): """simulates circuit with given input Args: circuit (QuantumCircuit): Circuit to simulate. Currently no more than 2 registers supported shots (int, optional): number of shots to simulate. Default 1024 x (str, optional): input string eg "11" would apply an X gate to first 2 qubits. Default "0" verbose (bool, optional): prints extra output Returns: dict[str:int]: results.get_counts() Raises: QiskitError: if circuit has more than two registers """ names = [] regs = [] for q in circuit.qubits: name = q.register.name size = len(q.register) if name not in names: names.append(name) regs.append(size) if verbose: print(names, regs) # assuming that we only have 2: control + ancillary qra = QuantumRegister(regs[0], name=names[0]) if len(regs) == 1: qa = QuantumCircuit(qra) elif len(regs) == 2: qran = QuantumRegister(regs[1], name=names[1]) qa = QuantumCircuit(qra, qran) else: raise QiskitError("Not yet implemented for more than 2 registers") if len(x) != sum(regs): x += "0" * (sum(regs) - len(x)) if verbose: print(x) for i, bit in enumerate(x): if verbose: print(bit, type(bit)) if bit != "0": qa.x(i) qa.barrier() qa.extend(circuit) if verbose: print(qa) backend = BasicAer.get_backend('qasm_simulator') results = execute(qa, backend=backend, shots=shots).result() answer = results.get_counts() return answer
def test_ibmq_result_fields(self, qe_token, qe_url): """Test components of a result from a remote simulator.""" IBMQ.enable_account(qe_token, qe_url) remote_backend = IBMQ.get_backend(local=False, simulator=True) remote_result = execute(self._qc1, remote_backend).result() self.assertEqual(remote_result.backend_name, remote_backend.name()) self.assertIsInstance(remote_result.job_id, str) self.assertEqual(remote_result.status, 'COMPLETED') self.assertEqual(remote_result.results[0].status, 'DONE')
def test_entanglement(self): """ Test entanglement circuits of Ignis verification - GHZ, MQC, parity oscillations """ num_qubits = 5 # number of qubits sim = BasicAer.get_backend('qasm_simulator') # test simple GHZc circ = linear.get_ghz_simple(num_qubits, measure=True) counts = execute(circ, sim, shots=1024).result().get_counts(circ) self.assertTrue( counts.get('00000', 0) + counts.get('11111', 0) == 1024) # test MQC circ, delta = linear.get_ghz_mqc_para(num_qubits) theta_range = np.linspace(0, 2 * np.pi, 16) circuits = [ circ.bind_parameters({delta: theta_val}) for theta_val in theta_range ] for circ in circuits: counts = execute(circ, sim, shots=1024).result().get_counts(circ) self.assertTrue( (counts.get('00000', 0) == 1024) or (counts.get('00000', 0) + counts.get('00001', 0)) == 1024) # test parity oscillations circ, params = linear.get_ghz_po_para(num_qubits) theta_range = np.linspace(0, 2 * np.pi, 16) circuits = [ circ.bind_parameters({ params[0]: theta_val, params[1]: -theta_val }) for theta_val in theta_range ] for circ in circuits: counts = execute(circ, sim, shots=1024).result().get_counts(circ) even_counts = sum(key.count('1') % 2 == 0 for key in counts.keys()) odd_counts = sum(key.count('1') % 2 == 1 for key in counts.keys()) self.assertTrue(even_counts in (0, 16)) self.assertTrue(odd_counts in (0, 16))
def optmization_levels(self): backend = BasicAer.get_backend('qasm_simulator') circuit = self.circuit seed_simulator = self.seed_simulator seed_transpiler = seed_simulator counts_0 = execute( deepcopy(circuit), backend, optimization_level=0, seed_simulator=seed_simulator, seed_transpiler=seed_transpiler).result().get_counts() counts_1 = execute( deepcopy(circuit), backend, optimization_level=1, seed_simulator=seed_simulator, seed_transpiler=seed_transpiler, ).result().get_counts() counts_2 = execute( deepcopy(circuit), backend, optimization_level=2, seed_simulator=seed_simulator, seed_transpiler=seed_transpiler, ).result().get_counts() if self.random_bool: counts_3 = execute( deepcopy(circuit), backend, optimization_level=3, seed_simulator=seed_simulator, seed_transpiler=seed_transpiler, ).result().get_counts() else: counts_3 = deepcopy(counts_2) self.assertEqualCounts(counts_0, counts_1, counts_2, counts_3)
def test_circuit_on_fake_backend(self, backend, optimization_level): if not HAS_AER and backend.configuration().num_qubits > 20: self.skipTest('Unable to run fake_backend %s without qiskit-aer' % backend.configuration().backend_name) job = execute(self.circuit, backend, optimization_level=optimization_level, seed_simulator=42, seed_transpiler=42) result = job.result() counts = result.get_counts() max_count = max(counts.items(), key=operator.itemgetter(1))[0] self.assertEqual(max_count, '11')
def test_private_job(self, provider): """Test a private job.""" backend = provider.get_backend('ibmq_qasm_simulator') qc = ReferenceCircuits.bell() job = execute(qc, backend=backend) self.assertIsNotNone(job.qobj()) self.assertIsNotNone(job.result()) # Wait a bit for databases to update. time.sleep(2) with self.assertRaises(IBMQBackendApiError) as err_cm: backend.retrieve_job(job.job_id()) self.assertIn('3250', str(err_cm.exception))
def test_execute_remote(self, provider): """Test Execute remote.""" backend = provider.get_backend(local=False, simulator=True) qubit_reg = QuantumRegister(2) clbit_reg = ClassicalRegister(2) qc = QuantumCircuit(qubit_reg, clbit_reg) qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) job = execute(qc, backend, seed_transpiler=self.seed) results = job.result() self.assertIsInstance(results, Result)
def test_block_spanning_two_regs_different_index(self): """blocks spanning wires on different quantum registers work when the wires could have conflicting indices. This was raised in #2806 when a CX was applied across multiple registers and their indices collided, raising an error.""" qr0 = QuantumRegister(1, "qr0") qr1 = QuantumRegister(2, "qr1") qc = QuantumCircuit(qr0, qr1) qc.cx(qr0[0], qr1[1]) dag = circuit_to_dag(qc) pass_ = ConsolidateBlocks(force_consolidate=True) pass_.property_set['block_list'] = [list(dag.topological_op_nodes())] new_dag = pass_.run(dag) sim = UnitarySimulatorPy() original_result = execute(qc, sim).result() original_unitary = UnitaryGate(original_result.get_unitary()) from qiskit.converters import dag_to_circuit new_result = execute(dag_to_circuit(new_dag), sim).result() new_unitary = UnitaryGate(new_result.get_unitary()) self.assertEqual(original_unitary, new_unitary)
def test_execute_remote(self, qe_token, qe_url): """Test Execute remote.""" IBMQ.enable_account(qe_token, qe_url) backend = IBMQ.get_backend(local=False, simulator=True) qubit_reg = QuantumRegister(2) clbit_reg = ClassicalRegister(2) qc = QuantumCircuit(qubit_reg, clbit_reg) qc.h(qubit_reg[0]) qc.cx(qubit_reg[0], qubit_reg[1]) qc.measure(qubit_reg, clbit_reg) job = execute(qc, backend, seed=self.seed) results = job.result() self.assertIsInstance(results, Result)
def test_consolidate_small_block(self): """test a small block of gates can be turned into a unitary on same wires""" qr = QuantumRegister(2, "qr") qc = QuantumCircuit(qr) qc.u1(0.5, qr[0]) qc.u2(0.2, 0.6, qr[1]) qc.cx(qr[0], qr[1]) dag = circuit_to_dag(qc) pass_ = ConsolidateBlocks(force_consolidate=True) pass_.property_set['block_list'] = [list(dag.topological_op_nodes())] new_dag = pass_.run(dag) sim = UnitarySimulatorPy() result = execute(qc, sim).result() unitary = UnitaryGate(result.get_unitary()) self.assertEqual(len(new_dag.op_nodes()), 1) fidelity = process_fidelity(new_dag.op_nodes()[0].op.to_matrix(), unitary.to_matrix()) self.assertAlmostEqual(fidelity, 1.0, places=7)
def test_3q_blocks(self): """blocks of more than 2 qubits work.""" qr = QuantumRegister(3, "qr") qc = QuantumCircuit(qr) qc.u1(0.5, qr[0]) qc.u2(0.2, 0.6, qr[1]) qc.cx(qr[2], qr[1]) qc.cx(qr[0], qr[1]) dag = circuit_to_dag(qc) pass_ = ConsolidateBlocks(force_consolidate=True) pass_.property_set['block_list'] = [list(dag.topological_op_nodes())] new_dag = pass_.run(dag) sim = UnitarySimulatorPy() result = execute(qc, sim).result() unitary = UnitaryGate(result.get_unitary()) self.assertEqual(len(new_dag.op_nodes()), 1) fidelity = process_fidelity(new_dag.op_nodes()[0].op.to_matrix(), unitary.to_matrix()) self.assertAlmostEqual(fidelity, 1.0, places=7)
def test_block_spanning_two_regs(self): """blocks spanning wires on different quantum registers work.""" qr0 = QuantumRegister(1, "qr0") qr1 = QuantumRegister(1, "qr1") qc = QuantumCircuit(qr0, qr1) qc.u1(0.5, qr0[0]) qc.u2(0.2, 0.6, qr1[0]) qc.cx(qr0[0], qr1[0]) dag = circuit_to_dag(qc) pass_ = ConsolidateBlocks(force_consolidate=True) pass_.property_set['block_list'] = [list(dag.topological_op_nodes())] new_dag = pass_.run(dag) sim = UnitarySimulatorPy() result = execute(qc, sim).result() unitary = UnitaryGate(result.get_unitary()) self.assertEqual(len(new_dag.op_nodes()), 1) fidelity = process_fidelity(new_dag.op_nodes()[0].op.to_matrix(), unitary.to_matrix()) self.assertAlmostEqual(fidelity, 1.0, places=7)
def test_transpiling_multiple_parameterized_circuits(self): """Verify several parameterized circuits can be transpiled at once.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2864 qr = QuantumRegister(1) qc1 = QuantumCircuit(qr) qc2 = QuantumCircuit(qr) theta = Parameter('theta') qc1.u3(theta, 0, 0, qr[0]) qc2.u3(theta, 3.14, 0, qr[0]) circuits = [qc1, qc2] job = execute(circuits, BasicAer.get_backend('unitary_simulator'), shots=512, parameter_binds=[{theta: 1}]) self.assertTrue(len(job.result().results), 2)
def applyIQFT_circuit(L: int, current_state: np.ndarray) -> np.ndarray: """ Apply IQFT on control register of current state and returns final state using qiskit circuit :param L: number of qubits in target register :param current_state: state to apply IQFT on :return: state after IQFT """ circuit = QuantumCircuit(3 * L) circuit.initialize(current_state.reshape(2**(3 * L)), circuit.qubits) circuit = QFT.construct_circuit(circuit=circuit, qubits=circuit.qubits[L:3 * L], inverse=True, do_swaps=True) backend = qt.Aer.get_backend('statevector_simulator') # backend = QCGPUProvider().get_backend('statevector_simulator') final_state = execute(circuit, backend, shots=1).result().get_statevector() return final_state
def simulate(self, shots=1000): simulator = QasmSimulator() result = execute(self.circuit, simulator, shots=shots).result() counts = result.get_counts(self.circuit) return counts