repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/AbdulahAmer/PHYS-31415-Summer-2021
AbdulahAmer
# Do not forget to Import Qiskit from qiskit.visualization import * from qiskit import * S_simulator=Aer.backends(name='statevector_simulator')[0] M_simulator=Aer.backends(name='qasm_simulator')[0] from math import pi # lets make a fucntions called rotate we do this in python by using def and # then the function name along with the variables we want our function to take and a colon def rotations(circuit, n): # if we went through the whole circuit, we do not have to do anymore work # just return the circuit we made if n == 0: return circuit # circuit is the QuantumCircuit we want to use the qft on, # n is the number of qubits in the circuit n-=1 # 4th qubit is in the n=3 spot on the circuit # mth qubit is on the n=m-1 spot on the circuit # also allows us to reduce down to n = 0 and to stop doing the rotations circuit.h(n) # Apply Hadamard gate to the qubit we are currently working on for qubit in range(n): # now use controlled phase gate to rotate # also divide the rotation angle by 2 each time circuit.cp(pi/2**(n-qubit), qubit, n) # circuit.cp() takes three arguments # (theta, target qubit, control qubit) #so the first time through in this loop the dummy variable # "qubit" is 0 , so we will do rotation of of pi/2**(n-0) on the 0th qubit using the # nth qubit as a control qubit. And so on and so forth. rotations(circuit, n) # do the same thing to the next qubit qc = QuantumCircuit(5,5) rotations(qc,5) qc.draw(output='mpl') def swap_qubits(circuit,n): # only need to loop through half of the circuit, since we swap two qubits at a time for qubit in range(n//2): # // floor function helps us round down when we have odd qubits circuit.swap(qubit, n-qubit-1) return circuit def qft(circuit, n): rotations(circuit, n) swap_qubits(circuit,n) return circuit qc=QuantumCircuit(5,5) qft(qc,5) qc.draw(output='mpl') # Note see how the 3rd qubit does not get swapped since it would swap with itself # Lets take some state x and put it in the QFT and see what we get out x=10 from math import log def find_number_of_qubits(x): powers_of_two=0 exponent=0 while powers_of_two<x: powers_of_two=2**exponent exponent+=1 number_of_qubits = int(log(powers_of_two,2)) return number_of_qubits n = find_number_of_qubits(x) encoding = bin(x) # encoding has an extra '0b' that just says hey i am a binary number we can chop it off # by replacing it with nothing print('State we need to encode to try out qft: ', encoding.replace('0b', '')) qc = QuantumCircuit(n,n) # number of qubits calculated before qc.x(0) qc.x(2) qc.barrier() # seperate steps with a barrier. print('state before QFT: ', execute(qc, S_simulator).result().get_statevector()) qft(qc, n) print('state after QFT: ', execute(qc, S_simulator).result().get_statevector()) # Our output is a little messy lets grab the state and clean it up state = execute(qc, S_simulator).result().get_statevector() # we use formatting %f to print trimmed version of the real and complex parts of each amplitude # this is cool to pick up but do not worry too much about this real=[] imag=[] for i in state: print('%f' % i.real, '%f' % i.imag , 'j') # We see that we get a weird repeating signal or wave of values for a constant state real.append(i.real) imag.append(i.imag) from matplotlib import pyplot as plt plt.plot(range(len(state)), real) plt.plot(range(len(state)), imag) plt.show() # What would we get if we take an input where we have an even superposition of all states. from math import sqrt n=3 a= sqrt(1/(2**n)) # amplitude state=[a,a,a,a,a,a,a,a] qc=QuantumCircuit(3) qc.initialize(state, [0,1,2]) qc.barrier() # seperate steps with a barrier. print('state before QFT: ', execute(qc, S_simulator).result().get_statevector()) qft(qc, n) print('state after QFT: ', execute(qc, S_simulator).result().get_statevector()) # Our output is a little messy lets grab the state and clean it up state = execute(qc, S_simulator).result().get_statevector() # we use formatting %f to print trimmed version of the real and complex parts of each amplitude # this is cool to pick up but do not worry too much about this real=[] imag=[] for i in state: print('%f' % i.real, '%f' % i.imag , 'j') # We see that we get a weird repeating signal or wave of values for a constant state real.append(i.real) imag.append(i.imag) from matplotlib import pyplot as plt plt.plot(range(len(state)), real) plt.plot(range(len(state)), imag) plt.show()
https://github.com/Brogis1/2020_SCS_Qiskit_Workshop
Brogis1
import numpy as np from qiskit import __qiskit_version__ from qiskit.chemistry.drivers import PySCFDriver, PyQuanteDriver, UnitsType from qiskit.chemistry import FermionicOperator from qiskit.aqua.algorithms import VQE, ExactEigensolver from qiskit.chemistry.components.variational_forms import UCCSD from qiskit.chemistry.components.initial_states import HartreeFock from qiskit.aqua.components.optimizers import COBYLA from qiskit.aqua import QuantumInstance from qiskit import Aer from qiskit.chemistry.algorithms.q_equation_of_motion.q_equation_of_motion import QEquationOfMotion from qiskit.visualization import plot_histogram from qiskit import IBMQ from qiskit.providers.aer import noise __qiskit_version__ driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.735', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') molecule = driver.run() h1 = molecule.one_body_integrals h2 = molecule.two_body_integrals nuclear_repulsion_energy = molecule.nuclear_repulsion_energy num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 print("HF energy: {}".format(molecule.hf_energy - molecule.nuclear_repulsion_energy)) print("# of electrons: {}".format(num_particles)) print("# of spin orbitals: {}".format(num_spin_orbitals)) ferop = FermionicOperator(h1=h1, h2=h2) map_type = 'jordan_wigner' qubitop = ferop.mapping(map_type=map_type) print(qubitop.print_details()) exact_eigensolver = ExactEigensolver(qubitop, k=1<<qubitop.num_qubits) ret = exact_eigensolver.run() print('The ground state energy is: {:.12f}'.format(ret['eigvals'][0].real)) print('The ground state is:') for i in range(1<<qubitop.num_qubits): print(np.binary_repr(i, width=qubitop.num_qubits), ret['eigvecs'][0][i]) qubit_reduction = False HF_state = HartreeFock(qubitop.num_qubits, num_spin_orbitals, num_particles, map_type, qubit_reduction) var_form = UCCSD(qubitop.num_qubits, depth=1, num_orbitals=num_spin_orbitals, num_particles=num_particles, initial_state=HF_state, qubit_mapping=map_type, two_qubit_reduction=qubit_reduction) params = np.random.rand(var_form._num_parameters) circuit = var_form.construct_circuit(params) circuit.decompose().draw(output='mpl') backend = Aer.get_backend('statevector_simulator') import logging from qiskit.chemistry import set_qiskit_chemistry_logging set_qiskit_chemistry_logging(logging.INFO) # choose among DEBUG, INFO, WARNING, ERROR, CRITICAL and NOTSET max_eval = 200 cobyla = COBYLA(maxiter=max_eval) vqe = VQE(qubitop, var_form, cobyla) quantum_instance = QuantumInstance(backend=backend) results = vqe.run(quantum_instance) print('The computed ground state energy is: {:.12f}'.format(results['eigvals'][0])) print("Parameters: {}".format(results['opt_params'])) h1_nop = np.identity(qubitop.num_qubits) fermionic_nop = FermionicOperator(h1=h1_nop) qubit_nop = fermionic_nop.mapping(map_type=map_type) print(qubit_nop.print_details()) wavefn = var_form.construct_circuit(results['opt_params']) statevector_mode = True use_simulator_snapshot_mode = True circuits = qubit_nop.construct_evaluation_circuit(wavefn, statevector_mode, use_simulator_snapshot_mode=use_simulator_snapshot_mode) results_2 = quantum_instance.execute(circuits) avg, std = qubit_nop.evaluate_with_result(results_2, statevector_mode, use_simulator_snapshot_mode=use_simulator_snapshot_mode) print(round(np.real(avg),1)) eom = QEquationOfMotion(qubitop, qubitop.num_qubits, num_particles, qubit_mapping=map_type) gaps, _ = eom.calculate_excited_states(wavefn, quantum_instance = quantum_instance) exact_energies = [] for i in range(1<<qubitop.num_qubits): state = ret['eigvecs'][i] nop_exp = qubit_nop.evaluate_with_statevector(state) if round(np.real(nop_exp[0]),1) == 2: exact_energies.append(np.real(ret['eigvals'][i])) qeom_energies = [results['eigvals'][0]] for i in range(len(gaps)): qeom_energies.append(qeom_energies[0]+gaps[i]) print('The exact energies are {}'.format(exact_energies)) print('The qEOM energies are {}'.format(qeom_energies)) backend_2 = Aer.get_backend('qasm_simulator') shots = 1000 quantum_instance_2 = QuantumInstance(backend=backend_2, shots = shots) results_3 = vqe.run(quantum_instance_2) print('The computed ground state energy is: {:.12f}'.format(results_3['eigvals'][0])) print("Parameters: {}".format(results_3['opt_params'])) plot_histogram(results_3['eigvecs'][0], color='midnightblue', title="H2 ground state, 1000 shots") IBMQ.save_account('679268b65869103438b43782543ef1cb532068e8dbc53d8acc34f160430eeb37655fbaf0351df831623d8bd5cf7496f8e21bd266cab2a963342dd737775465db', overwrite=True) provider = IBMQ.load_account() print(provider.backends()) device = provider.get_backend('ibmqx2') properties = device.properties() coupling_map = device.configuration().coupling_map noise_model = noise.device.basic_device_noise_model(properties) basis_gates = noise_model.basis_gates quantum_instance_3 = QuantumInstance(backend_2, shots=shots, basis_gates=basis_gates, coupling_map=coupling_map, noise_model=noise_model) results_4 = vqe.run(quantum_instance_3) print('The computed ground state energy is: {:.12f}'.format(results_3['eigvals'][0])) print("Parameters: {}".format(results_3['opt_params'])) plot_histogram(results_4['eigvecs'][0], color='midnightblue', title="H2 ground state, 1000 shots")
https://github.com/Simultonian/hamilutor-qiskit
Simultonian
from qiskit import QuantumCircuit from qiskit.compiler import transpile DEFAULT_GATES = ["rz", "h", "s", "cx", "cz"] def decompose(circ: QuantumCircuit, basis=None) -> QuantumCircuit: if basis is None: basis = DEFAULT_GATES return transpile(circ, basis_gates=basis)
https://github.com/Simultonian/hamilutor-qiskit
Simultonian
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the decompose pass""" from numpy import pi from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.transpiler.passes import Decompose from qiskit.converters import circuit_to_dag from qiskit.circuit.library import HGate, CCXGate, U2Gate from qiskit.quantum_info.operators import Operator from qiskit.test import QiskitTestCase class TestDecompose(QiskitTestCase): """Tests the decompose pass.""" def setUp(self): super().setUp() # example complex circuit # ┌────────┐ ┌───┐┌─────────────┐ # q2_0: ┤0 ├────────────■──┤ H ├┤0 ├ # │ │ │ └───┘│ circuit-57 │ # q2_1: ┤1 gate1 ├────────────■───────┤1 ├ # │ │┌────────┐ │ └─────────────┘ # q2_2: ┤2 ├┤0 ├──■────────────────────── # └────────┘│ │ │ # q2_3: ──────────┤1 gate2 ├──■────────────────────── # │ │┌─┴─┐ # q2_4: ──────────┤2 ├┤ X ├──────────────────── # └────────┘└───┘ circ1 = QuantumCircuit(3) circ1.h(0) circ1.t(1) circ1.x(2) my_gate = circ1.to_gate(label="gate1") circ2 = QuantumCircuit(3) circ2.h(0) circ2.cx(0, 1) circ2.x(2) my_gate2 = circ2.to_gate(label="gate2") circ3 = QuantumCircuit(2) circ3.x(0) q_bits = QuantumRegister(5) qc = QuantumCircuit(q_bits) qc.append(my_gate, q_bits[:3]) qc.append(my_gate2, q_bits[2:]) qc.mct(q_bits[:4], q_bits[4]) qc.h(0) qc.append(circ3, [0, 1]) self.complex_circuit = qc def test_basic(self): """Test decompose a single H into u2.""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) dag = circuit_to_dag(circuit) pass_ = Decompose(HGate) after_dag = pass_.run(dag) op_nodes = after_dag.op_nodes() self.assertEqual(len(op_nodes), 1) self.assertEqual(op_nodes[0].name, "u2") def test_decompose_none(self): """Test decompose a single H into u2.""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) dag = circuit_to_dag(circuit) pass_ = Decompose() after_dag = pass_.run(dag) op_nodes = after_dag.op_nodes() self.assertEqual(len(op_nodes), 1) self.assertEqual(op_nodes[0].name, "u2") def test_decompose_only_h(self): """Test to decompose a single H, without the rest""" qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) dag = circuit_to_dag(circuit) pass_ = Decompose(HGate) after_dag = pass_.run(dag) op_nodes = after_dag.op_nodes() self.assertEqual(len(op_nodes), 2) for node in op_nodes: self.assertIn(node.name, ["cx", "u2"]) def test_decompose_toffoli(self): """Test decompose CCX.""" qr1 = QuantumRegister(2, "qr1") qr2 = QuantumRegister(1, "qr2") circuit = QuantumCircuit(qr1, qr2) circuit.ccx(qr1[0], qr1[1], qr2[0]) dag = circuit_to_dag(circuit) pass_ = Decompose(CCXGate) after_dag = pass_.run(dag) op_nodes = after_dag.op_nodes() self.assertEqual(len(op_nodes), 15) for node in op_nodes: self.assertIn(node.name, ["h", "t", "tdg", "cx"]) def test_decompose_conditional(self): """Test decompose a 1-qubit gates with a conditional.""" qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr).c_if(cr, 1) circuit.x(qr).c_if(cr, 1) dag = circuit_to_dag(circuit) pass_ = Decompose(HGate) after_dag = pass_.run(dag) ref_circuit = QuantumCircuit(qr, cr) ref_circuit.append(U2Gate(0, pi), [qr[0]]).c_if(cr, 1) ref_circuit.x(qr).c_if(cr, 1) ref_dag = circuit_to_dag(ref_circuit) self.assertEqual(after_dag, ref_dag) def test_decompose_oversized_instruction(self): """Test decompose on a single-op gate that doesn't use all qubits.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/3440 qc1 = QuantumCircuit(2) qc1.x(0) gate = qc1.to_gate() qc2 = QuantumCircuit(2) qc2.append(gate, [0, 1]) output = qc2.decompose() self.assertEqual(qc1, output) def test_decomposition_preserves_qregs_order(self): """Test decomposing a gate preserves it's definition registers order""" qr = QuantumRegister(2, "qr1") qc1 = QuantumCircuit(qr) qc1.cx(1, 0) gate = qc1.to_gate() qr2 = QuantumRegister(2, "qr2") qc2 = QuantumCircuit(qr2) qc2.append(gate, qr2) expected = QuantumCircuit(qr2) expected.cx(1, 0) self.assertEqual(qc2.decompose(), expected) def test_decompose_global_phase_1q(self): """Test decomposition of circuit with global phase""" qc1 = QuantumCircuit(1) qc1.rz(0.1, 0) qc1.ry(0.5, 0) qc1.global_phase += pi / 4 qcd = qc1.decompose() self.assertEqual(Operator(qc1), Operator(qcd)) def test_decompose_global_phase_2q(self): """Test decomposition of circuit with global phase""" qc1 = QuantumCircuit(2, global_phase=pi / 4) qc1.rz(0.1, 0) qc1.rxx(0.2, 0, 1) qcd = qc1.decompose() self.assertEqual(Operator(qc1), Operator(qcd)) def test_decompose_global_phase_1q_composite(self): """Test decomposition of circuit with global phase in a composite gate.""" circ = QuantumCircuit(1, global_phase=pi / 2) circ.x(0) circ.h(0) v = circ.to_gate() qc1 = QuantumCircuit(1) qc1.append(v, [0]) qcd = qc1.decompose() self.assertEqual(Operator(qc1), Operator(qcd)) def test_decompose_only_h_gate(self): """Test decomposition parameters so that only a certain gate is decomposed.""" circ = QuantumCircuit(2, 1) circ.h(0) circ.cz(0, 1) decom_circ = circ.decompose(["h"]) dag = circuit_to_dag(decom_circ) self.assertEqual(len(dag.op_nodes()), 2) self.assertEqual(dag.op_nodes()[0].name, "u2") self.assertEqual(dag.op_nodes()[1].name, "cz") def test_decompose_only_given_label(self): """Test decomposition parameters so that only a given label is decomposed.""" decom_circ = self.complex_circuit.decompose(["gate2"]) dag = circuit_to_dag(decom_circ) self.assertEqual(len(dag.op_nodes()), 7) self.assertEqual(dag.op_nodes()[0].op.label, "gate1") self.assertEqual(dag.op_nodes()[1].name, "h") self.assertEqual(dag.op_nodes()[2].name, "cx") self.assertEqual(dag.op_nodes()[3].name, "x") self.assertEqual(dag.op_nodes()[4].name, "mcx") self.assertEqual(dag.op_nodes()[5].name, "h") self.assertRegex(dag.op_nodes()[6].name, "circuit-") def test_decompose_only_given_name(self): """Test decomposition parameters so that only given name is decomposed.""" decom_circ = self.complex_circuit.decompose(["mcx"]) dag = circuit_to_dag(decom_circ) self.assertEqual(len(dag.op_nodes()), 13) self.assertEqual(dag.op_nodes()[0].op.label, "gate1") self.assertEqual(dag.op_nodes()[1].op.label, "gate2") self.assertEqual(dag.op_nodes()[2].name, "h") self.assertEqual(dag.op_nodes()[3].name, "cu1") self.assertEqual(dag.op_nodes()[4].name, "rcccx") self.assertEqual(dag.op_nodes()[5].name, "h") self.assertEqual(dag.op_nodes()[6].name, "h") self.assertEqual(dag.op_nodes()[7].name, "cu1") self.assertEqual(dag.op_nodes()[8].name, "rcccx_dg") self.assertEqual(dag.op_nodes()[9].name, "h") self.assertEqual(dag.op_nodes()[10].name, "c3sx") self.assertEqual(dag.op_nodes()[11].name, "h") self.assertRegex(dag.op_nodes()[12].name, "circuit-") def test_decompose_mixture_of_names_and_labels(self): """Test decomposition parameters so that mixture of names and labels is decomposed""" decom_circ = self.complex_circuit.decompose(["mcx", "gate2"]) dag = circuit_to_dag(decom_circ) self.assertEqual(len(dag.op_nodes()), 15) self.assertEqual(dag.op_nodes()[0].op.label, "gate1") self.assertEqual(dag.op_nodes()[1].name, "h") self.assertEqual(dag.op_nodes()[2].name, "cx") self.assertEqual(dag.op_nodes()[3].name, "x") self.assertEqual(dag.op_nodes()[4].name, "h") self.assertEqual(dag.op_nodes()[5].name, "cu1") self.assertEqual(dag.op_nodes()[6].name, "rcccx") self.assertEqual(dag.op_nodes()[7].name, "h") self.assertEqual(dag.op_nodes()[8].name, "h") self.assertEqual(dag.op_nodes()[9].name, "cu1") self.assertEqual(dag.op_nodes()[10].name, "rcccx_dg") self.assertEqual(dag.op_nodes()[11].name, "h") self.assertEqual(dag.op_nodes()[12].name, "c3sx") self.assertEqual(dag.op_nodes()[13].name, "h") self.assertRegex(dag.op_nodes()[14].name, "circuit-") def test_decompose_name_wildcards(self): """Test decomposition parameters so that name wildcards is decomposed""" decom_circ = self.complex_circuit.decompose(["circuit-*"]) dag = circuit_to_dag(decom_circ) self.assertEqual(len(dag.op_nodes()), 9) self.assertEqual(dag.op_nodes()[0].name, "h") self.assertEqual(dag.op_nodes()[1].name, "t") self.assertEqual(dag.op_nodes()[2].name, "x") self.assertEqual(dag.op_nodes()[3].name, "h") self.assertRegex(dag.op_nodes()[4].name, "cx") self.assertEqual(dag.op_nodes()[5].name, "x") self.assertEqual(dag.op_nodes()[6].name, "mcx") self.assertEqual(dag.op_nodes()[7].name, "h") self.assertEqual(dag.op_nodes()[8].name, "x") def test_decompose_label_wildcards(self): """Test decomposition parameters so that label wildcards is decomposed""" decom_circ = self.complex_circuit.decompose(["gate*"]) dag = circuit_to_dag(decom_circ) self.assertEqual(len(dag.op_nodes()), 9) self.assertEqual(dag.op_nodes()[0].name, "h") self.assertEqual(dag.op_nodes()[1].name, "t") self.assertEqual(dag.op_nodes()[2].name, "x") self.assertEqual(dag.op_nodes()[3].name, "h") self.assertEqual(dag.op_nodes()[4].name, "cx") self.assertEqual(dag.op_nodes()[5].name, "x") self.assertEqual(dag.op_nodes()[6].name, "mcx") self.assertEqual(dag.op_nodes()[7].name, "h") self.assertRegex(dag.op_nodes()[8].name, "circuit-") def test_decompose_empty_gate(self): """Test a gate where the definition is an empty circuit is decomposed.""" empty = QuantumCircuit(1) circuit = QuantumCircuit(1) circuit.append(empty.to_gate(), [0]) decomposed = circuit.decompose() self.assertEqual(len(decomposed.data), 0) def test_decompose_reps(self): """Test decompose reps function is decomposed correctly""" decom_circ = self.complex_circuit.decompose(reps=2) decomposed = self.complex_circuit.decompose().decompose() self.assertEqual(decom_circ, decomposed) def test_decompose_single_qubit_clbit(self): """Test the decomposition of a block with a single qubit and clbit works. Regression test of Qiskit/qiskit-terra#8591. """ block = QuantumCircuit(1, 1) block.h(0) circuit = QuantumCircuit(1, 1) circuit.append(block, [0], [0]) decomposed = circuit.decompose() self.assertEqual(decomposed, block)
https://github.com/Simultonian/hamilutor-qiskit
Simultonian
from qiskit import QuantumCircuit from qiskit.opflow import PauliTrotterEvolution, X, Y, Z, I # For `eval` from ..utils.repr import qiskit_string_repr, qiskit_string_repr_pauli def trotter_from_terms(terms: list[tuple[str, float]]) -> QuantumCircuit: """ API that takes a list of terms that must be exponentiated in the specific order, that may or may not have repetitions. The coefficients are assumed to already account the time scaling. Input: - terms: list of pairs of pauli operator and the coefficient. Returns: Quantum Circuit with exponentiation in the defined ordered. """ num_qubits = len(terms[0][0]) final_circuit = QuantumCircuit(num_qubits) for term in terms: final_circuit = final_circuit.compose(trotter_from_term(term)) return final_circuit def trotter_from_term(term: tuple[str, float]) -> QuantumCircuit: pauli_op = eval(qiskit_string_repr_pauli(term)) evolution_op = pauli_op.exp_i() trotterized_op = PauliTrotterEvolution(trotter_mode="trotter").convert(evolution_op) return trotterized_op.to_circuit() def trotter(h: dict[str, float], t: float = 1.0, reps: int = 1) -> QuantumCircuit: """ API that takes Hamiltonian in a familiar format along with time and creates circuit that simulates the same using simple Trotterization. Input: - h: Hamiltonian in Pauli basis along with coefficients - t: Time - reps: The number of times to repeat trotterization steps. Returns: Quantum Circuit for simulation """ hamiltonian = eval(qiskit_string_repr(h)) # evolution operator evolution_op = ((t / reps) * hamiltonian).exp_i() # into circuit trotterized_op = PauliTrotterEvolution(trotter_mode="trotter", reps=reps).convert( evolution_op ) return trotterized_op.to_circuit()
https://github.com/Simultonian/hamilutor-qiskit
Simultonian
from qiskit import QuantumCircuit from ..utils import circuit_eq from .simple import qdrift from ..trotter.simple import trotter import numpy as np import pytest hamiltonians = [ {"xx": 1.0, "iy": 1.0}, {"xi": 1.0}, ] order_list = [ ["iy", "iy", "iy", "iy", "xx", "iy", "xx", "iy"], ["xi", "xi"], ] @pytest.mark.parametrize("h,order", zip(hamiltonians, order_list)) def test_qdrift(h, order): # Setting random seed for testing np.random.seed(0) result = qdrift(h, 1.0) num_qubits = len(list(h.keys())[0]) lambd = sum(list(h.values())) N = 2 * (lambd**2) factor = lambd / N # It is equivalent of constructing individual term exponentiated and then # concatanating them. expected = QuantumCircuit(num_qubits) for term in order: cur = trotter({term: factor / h[term]}) expected = expected.compose(cur) assert circuit_eq(expected, result)
https://github.com/Simultonian/hamilutor-qiskit
Simultonian
from qiskit import QuantumCircuit from qiskit.opflow import PauliTrotterEvolution, X, Y, Z, I # For `eval` from ..utils.repr import qiskit_string_repr, qiskit_string_repr_pauli def trotter_from_terms(terms: list[tuple[str, float]]) -> QuantumCircuit: """ API that takes a list of terms that must be exponentiated in the specific order, that may or may not have repetitions. The coefficients are assumed to already account the time scaling. Input: - terms: list of pairs of pauli operator and the coefficient. Returns: Quantum Circuit with exponentiation in the defined ordered. """ num_qubits = len(terms[0][0]) final_circuit = QuantumCircuit(num_qubits) for term in terms: final_circuit = final_circuit.compose(trotter_from_term(term)) return final_circuit def trotter_from_term(term: tuple[str, float]) -> QuantumCircuit: pauli_op = eval(qiskit_string_repr_pauli(term)) evolution_op = pauli_op.exp_i() trotterized_op = PauliTrotterEvolution(trotter_mode="trotter").convert(evolution_op) return trotterized_op.to_circuit() def trotter(h: dict[str, float], t: float = 1.0, reps: int = 1) -> QuantumCircuit: """ API that takes Hamiltonian in a familiar format along with time and creates circuit that simulates the same using simple Trotterization. Input: - h: Hamiltonian in Pauli basis along with coefficients - t: Time - reps: The number of times to repeat trotterization steps. Returns: Quantum Circuit for simulation """ hamiltonian = eval(qiskit_string_repr(h)) # evolution operator evolution_op = ((t / reps) * hamiltonian).exp_i() # into circuit trotterized_op = PauliTrotterEvolution(trotter_mode="trotter", reps=reps).convert( evolution_op ) return trotterized_op.to_circuit()
https://github.com/Simultonian/hamilutor-qiskit
Simultonian
from qiskit import QuantumCircuit from qiskit.opflow import X, Y, Z, I from ..utils import qiskit_string_repr, circuit_eq from .simple import trotter, trotter_from_terms, trotter_from_term import pytest repr_hams = [ {"xiizi": 1.0, "iyiiy": 2.0}, {"iiizi": 1.0, "iyiiy": 2.0}, ] q_objs = [ (1.0 * X ^ I ^ I ^ Z ^ I) + (2.0 * I ^ Y ^ I ^ I ^ Y), ((1.0) * I ^ I ^ I ^ Z ^ I) + ((2.0) * I ^ Y ^ I ^ I ^ Y), ] gate_list = [["i", "i"], ["h", "i"], ["h", "hs"], ["i", "i"], ["i", "h"]] @pytest.mark.parametrize("h,q_obj", zip(repr_hams, q_objs)) def test_qiskit_repr(h, q_obj): result = eval(qiskit_string_repr(h)) assert result == q_obj hamiltonians = [ {"xiizi": 1.0}, {"xiizi": 1.0, "iyiiy": 2.0}, ] @pytest.mark.parametrize("h", hamiltonians) def test_trotter(h): result = trotter(h, 1.0) num_qubits = len(list(h.keys())[0]) # It is equivalent of constructing individual term exponentiated and then # concatanating them. expected = QuantumCircuit(num_qubits) for pauli, coeff in h.items(): cur = trotter({pauli: coeff}) expected = expected.compose(cur) assert circuit_eq(expected, result) terms_list = [ [("xy", 1.0), ("iy", 2.0)], [("xi", 1.0), ("iy", 2.0), ("xi", 3.0)], [("xi", 1.0), ("iy", 2.0), ("xi", 3.0), ("ii", -1.0)], ] @pytest.mark.parametrize("terms", terms_list) def test_from_terms(terms): num_qubits = len(terms[0][0]) result = trotter_from_terms(terms) expected = QuantumCircuit(num_qubits) for pauli, coeff in terms: cur = trotter({pauli: coeff}) expected = expected.compose(cur) assert circuit_eq(expected, result) term_list = [ ("xy", 1.0), ("iy", 2.0), ("zz", -3.0), ] @pytest.mark.parametrize("term", term_list) def test_from_term(term: tuple[str, float]): num_qubits = len(term[0]) result = trotter_from_term(term) expected = QuantumCircuit(num_qubits) pauli, coeff = term expected = trotter({pauli: coeff}) assert circuit_eq(expected, result)
https://github.com/Simultonian/hamilutor-qiskit
Simultonian
from qiskit import QuantumCircuit from ..grouping.bitwise import Bitwise from .group_trotter import generic from ..ordering import lexico def bitwise_simple( h: dict[str, float], t: float = 1.0, reps: int = 1 ) -> QuantumCircuit: """ Takes in a Hamiltonian and constructs the simple Trotterization circuit after grouping the terms using bitwise Pauli grouping. Inputs: - h: Hamiltonian in dictionary form. - t: Float representing time of evolution. - reps: Repetitions for Trotterization. Returns: QuantumCircuit that will simulate the Hamiltonian """ return generic(Bitwise, lexico, h, t, reps)
https://github.com/Simultonian/hamilutor-qiskit
Simultonian
from typing import Callable from qiskit import QuantumCircuit from ..grouping.grouper import Grouper from ..trotter.simple import trotter_from_terms from ..utils import circuit_constructor, get_el def generic( grouper_class: Callable[[set[str]], Grouper], orderer: Callable[[set[str]], list[str]], h: dict[str, float], t: float = 1.0, reps: int = 1, ) -> QuantumCircuit: """ A generic trotterization constructor. Inputs: - grouper: Pauli grouper - orderer: Function that orders the diagonalized terms - h: Hamiltonian in dictionary form - t: Float representing time of evolution - reps: Repetitions for Trotterization. Returns: QuantumCircuit that will simulate the Hamiltonian """ pauli_list = set(h.keys()) if len(pauli_list) == 0: raise ValueError("Input Hamiltonian was empty.") # size of any pauli operator first = get_el(pauli_list) num_qubits = len(first) grouper = grouper_class(pauli_list) groups = grouper.groups group_circs = [] # Get relevant circuits for all the groups for group in groups: pauli = get_el(group) # Diagonalizing circuits diag_circ = circuit_constructor(grouper.circuit(pauli)) diag_circ_c = diag_circ.inverse() # Setting the order according to ordere ordered = orderer(group) ordered_tuples = [] for p in ordered: coeff, term = grouper.diagonalize(p) coeff = (t / reps) * h[p] * coeff ordered_tuples.append((term, coeff)) # time will be scaled down by reps exp_circ = trotter_from_terms(ordered_tuples) final_circuit = QuantumCircuit(num_qubits) # TODO: Issue 30 # Combining the three sections final_circuit = diag_circ.compose(exp_circ) final_circuit = final_circuit.compose(diag_circ_c) group_circs.append(final_circuit) final_circuit = QuantumCircuit(num_qubits) for _ in range(reps): for group_circ in group_circs: final_circuit = final_circuit.compose(group_circ) return final_circuit
https://github.com/Simultonian/hamilutor-qiskit
Simultonian
import pytest from qiskit import QuantumCircuit from ..trotter.simple import trotter from ..utils import circuit_eq from .bitwise_simple import bitwise_simple import itertools def test_bitwise_simple_single_group(): group = {"ix": 1.0, "xi": -1.0} # Checking for multiple number of repetitions for reps in range(1, 5): result = bitwise_simple(group, t=1.0, reps=reps) expected = QuantumCircuit(2) for _ in range(reps): # Rotation expected.h(0) expected.h(1) # Exponentiate circuit = trotter({"iz": 1.0, "zi": -1.0}, t=1.0 / reps) expected = expected.compose(circuit) # Anti-rotation expected.h(0) expected.h(1) assert circuit_eq(result, expected) two_group_hams = [ {"xx": 1.0, "zz": 2.0}, {"xx": 1.0, "zz": 2.0, "zi": 3.0}, {"xx": 1.0, "zz": 2.0, "zi": 3.0, "xy": 4.0}, ] two_group_groups = [ [ {"xx": 1.0}, {"zz": 2.0}, ], [ {"xx": 1.0}, {"zz": 2.0, "zi": 3.0}, ], [{"xx": 1.0}, {"zz": 2.0, "zi": 3.0}, {"xy": 4.0}], ] two_num_qubits = [2, 2] @pytest.mark.parametrize( "h,groups,qubits", zip(two_group_hams, two_group_groups, two_num_qubits) ) def test_bitwise_simple_multiple_groups(h, groups, qubits): # Checking for multiple number of repetitions. for reps in range(1, 5): result = bitwise_simple(h, t=1.0, reps=reps) # Runs reps loop and trotters individual group. check = False for order in itertools.permutations(groups): expected = QuantumCircuit(qubits) for _ in range(reps): for group in order: circuit = trotter(group, t=1.0 / reps) expected = expected.compose(circuit) check = check or circuit_eq(result, expected) assert check
https://github.com/Simultonian/hamilutor-qiskit
Simultonian
import pytest from qiskit import QuantumCircuit from ..trotter.simple import trotter from ..utils import circuit_eq from .group_trotter import generic from ..grouping import Bitwise from ..ordering import lexico import itertools def test_single_group_trotter_grouper(): group = {"ix": 1.0, "xi": -1.0} result = generic(Bitwise, lexico, group) expected = QuantumCircuit(2) # Rotation expected.h(0) expected.h(1) # Exponentiate circuit = trotter({"iz": 1.0, "zi": -1.0}) expected = expected.compose(circuit) # Anti-rotation expected.h(0) expected.h(1) assert circuit_eq(result, expected) def test_bitwise_simple_single_group(): group = {"ix": 1.0, "xi": -1.0} # Checking for multiple number of repetitions for reps in range(1, 5): result = generic(Bitwise, lexico, group, t=1.0, reps=reps) expected = QuantumCircuit(2) for _ in range(reps): # Rotation expected.h(0) expected.h(1) # Exponentiate circuit = trotter({"iz": 1.0, "zi": -1.0}, t=1.0 / reps) expected = expected.compose(circuit) # Anti-rotation expected.h(0) expected.h(1) assert circuit_eq(result, expected) two_group_hams = [ {"xx": 1.0, "zz": 2.0}, {"xx": 1.0, "zz": 2.0, "zi": 3.0}, {"xx": 1.0, "zz": 2.0, "zi": 3.0, "xy": 4.0}, ] two_group_groups = [ [ {"xx": 1.0}, {"zz": 2.0}, ], [ {"xx": 1.0}, {"zz": 2.0, "zi": 3.0}, ], [{"xx": 1.0}, {"zz": 2.0, "zi": 3.0}, {"xy": 4.0}], ] two_num_qubits = [2, 2] @pytest.mark.parametrize("reps", range(1, 5)) @pytest.mark.parametrize( "h,groups,qubits", zip(two_group_hams, two_group_groups, two_num_qubits) ) def test_bitwise_simple_multiple_groups(reps, h, groups, qubits): # Checking for multiple number of repetitions. result = generic(Bitwise, lexico, h, t=1.0, reps=reps) check = False # Check for all possible orders of the group for order in itertools.permutations(groups): expected = QuantumCircuit(qubits) # Runs reps loop and trotters individual group. for _ in range(reps): for group in order: circuit = trotter(group, t=1.0 / reps) expected = expected.compose(circuit) check = check or circuit_eq(result, expected) assert check
https://github.com/Simultonian/hamilutor-qiskit
Simultonian
from math import sqrt, pi from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import oracle_simple import composed_gates def get_circuit(n, oracles): """ Build the circuit composed by the oracle black box and the other quantum gates. :param n: The number of qubits (not including the ancillas) :param oracles: A list of black box (quantum) oracles; each of them selects a specific state :returns: The proper quantum circuit :rtype: qiskit.QuantumCircuit """ cr = ClassicalRegister(n) ## Testing if n > 3: #anc = QuantumRegister(n - 1, 'anc') # n qubits for the real number # n - 1 qubits for the ancillas qr = QuantumRegister(n + n - 1) qc = QuantumCircuit(qr, cr) else: # We don't need ancillas qr = QuantumRegister(n) qc = QuantumCircuit(qr, cr) ## /Testing print("Number of qubits is {0}".format(len(qr))) print(qr) # Initial superposition for j in range(n): qc.h(qr[j]) # The length of the oracles list, or, in other words, how many roots of the function do we have m = len(oracles) # Grover's algorithm is a repetition of an oracle box and a diffusion box. # The number of repetitions is given by the following formula. print("n is ", n) r = int(round((pi / 2 * sqrt((2**n) / m) - 1) / 2)) print("Repetition of ORACLE+DIFFUSION boxes required: {0}".format(r)) oracle_t1 = oracle_simple.OracleSimple(n, 5) oracle_t2 = oracle_simple.OracleSimple(n, 0) for j in range(r): for i in range(len(oracles)): oracles[i].get_circuit(qr, qc) diffusion(n, qr, qc) for j in range(n): qc.measure(qr[j], cr[j]) return qc, len(qr) def diffusion(n, qr, qc): """ The Grover diffusion operator. Given the arry of qiskit QuantumRegister qr and the qiskit QuantumCircuit qc, it adds the diffusion operator to the appropriate qubits in the circuit. """ for j in range(n): qc.h(qr[j]) # D matrix, flips state |000> only (instead of flipping all the others) for j in range(n): qc.x(qr[j]) # 0..n-2 control bits, n-1 target, n.. if n > 3: composed_gates.n_controlled_Z_circuit( qc, [qr[j] for j in range(n - 1)], qr[n - 1], [qr[j] for j in range(n, n + n - 1)]) else: composed_gates.n_controlled_Z_circuit( qc, [qr[j] for j in range(n - 1)], qr[n - 1], None) for j in range(n): qc.x(qr[j]) for j in range(n): qc.h(qr[j])
https://github.com/Simultonian/hamilutor-qiskit
Simultonian
from qiskit import QuantumCircuit def gate_count(circuit: QuantumCircuit): return dict(circuit.count_ops())
https://github.com/Simultonian/hamilutor-qiskit
Simultonian
from qiskit import QuantumCircuit from . import circuit_constructor, circuit_eq def test_circuit_constructor(): gates_list = ["h", "hs", "hs", "i", "i", "h"] result = circuit_constructor(gates_list) result_dag = circuit_constructor(gates_list, True) expected = QuantumCircuit(6) expected.h(0) _ = expected.s(1), expected.h(1) _ = expected.s(2), expected.h(2) expected.h(5) expected_dag = QuantumCircuit(6) expected_dag.h(0) _ = expected_dag.h(1), expected_dag.sdg(1) _ = expected_dag.h(2), expected_dag.sdg(2) expected_dag.h(5) assert circuit_eq(result, expected) assert circuit_eq(result_dag, expected_dag)
https://github.com/Simultonian/hamilutor-qiskit
Simultonian
import pytest from qiskit import QuantumCircuit from qiskit.circuit.library import HGate, XGate, CXGate from .gate_count import gate_count circuits = [ [(HGate, [1]), (XGate, [1]), (CXGate, [0, 1])], ] count_objs = [{"h": 1, "x": 1, "cx": 1}] qubit_counts = [2] @pytest.mark.parametrize("gates,count, qubit", zip(circuits, count_objs, qubit_counts)) def test_gate_count_simple(gates, count, qubit): circ = QuantumCircuit(qubit) for gate, qubits in gates: circ.append(gate(), qubits) result = gate_count(circ) assert result == count
https://github.com/Simultonian/hamilutor-qiskit
Simultonian
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/DanKim44/CodingWithQiskitS2
DanKim44
#Coding With Qiskit S2E6 Quantum Machine Learning import qiskit from matplotlib import pyplot as plt import numpy as np from qiskit.ml.datasets import ad_hoc_data from qiskit import BasicAer from qiskit.aqua import QuantumInstance from qiskit.circuit.library import ZZFeatureMap from qiskit.aqua.algorithms import QSVM from qiskit.aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name feature_dim = 2 training_data_set_size = 20 testing_data_set_size = 10 random_seed = 10598 shot = 10000 sample_Total, training_input, test_input, class_labels = ad_hoc_data(training_size=training_data_set_size, test_size=testing_data_set_size, gap = 0.3, n=feature_dim, plot_data=True) datapoints, class_to_label = split_dataset_to_data_and_labels(test_input) print(class_to_label) backend = BasicAer.get_backend('qasm_simulator') feature_map = ZZFeatureMap(feature_dim, reps=2) svm = QSVM(feature_map, training_input, test_input, None) svm.random_seed = random_seed quantum_instance = QuantumInstance(backend, shots=shot, seed_simulator=random_seed, seed_transpiler=random_seed) result = svm.run(quantum_instance) print("kernel matrix during the training:") kernel_matrix = result['kernel_matrix_training'] img = plt.imshow(np.asmatrix(kernel_matrix), interpolation='nearest', origin='upper', cmap='bone_r') plt.show() #computed distance from kernel in higher dimensional space #diagonal black line shows that the distance from each point to itself is 0 predicted_labels = svm.predict(datapoints[0]) predicted_classes = map_label_to_class_name(predicted_labels, svm.label_to_class) print("ground truth: {}".format(datapoints[1])) print("prediction: {}".format(predicted_labels)) print("testing success reation: ", result['testing_accuracy'])
https://github.com/DanKim44/CodingWithQiskitS2
DanKim44
#Coding With Qiskit S2E7 Shor's Algorithm %matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.tools.visualization import plot_histogram from qiskit.visualization import * from qiskit.aqua.algorithms import Shor from qiskit.aqua import QuantumInstance import numpy as np import pandas as pd from fractions import Fraction backend = Aer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1000) my_shor=Shor(N=15,a=2,quantum_instance=quantum_instance) Shor.run(my_shor) def c_amod15(a,power): #modular exponentiation function, hard coded for factorizing 15, guess number 7 U = QuantumCircuit(4) for iteration in range(power): U.swap(2,3) U.swap(1,2) U.swap(0,1) for q in range(4): U.x(q) U=U.to_gate() #turns the circuit into a gate to use later U.name="%i^%i mod 15" %(a,power) c_U = U.control() return c_U n_count = 8 a = 7 def qft_dagger(n): qc = QuantumCircuit(n) for qubit in range(n//2): qc.swap(qubit,n-qubit-1) for j in range(n): for m in range(j): qc.cp(-np.pi/float(2**(j-m)),m,j) #replaced cu1 with cp gate due to deprec warning qc.h(j) qc.name="QFT dagger" return qc qc = QuantumCircuit(n_count + 4, n_count) #4 ancilla for q in range(n_count): #intialize counting qubits into superposition state qc.h(q) qc.x(3+n_count) #initialize first ancilla in the excited state for q in range(n_count): qc.append(c_amod15(a,2**q), [q]+[i+n_count for i in range(4) ]) qc.append(qft_dagger(n_count), range(n_count)) qc.measure(range(n_count), range(n_count)) qc.draw() results = execute(qc, backend, shots=2048).result() counts = results.get_counts() plot_histogram(counts) #phases of 0/256, 64/256, 128/256, 192/256 #gives guesses for r of 1,2,4 #plug into p=a^(r/2)-1, q=a^(r/2)+1 #for r = 4: p=48, q=50 #p has a common factor with N=15 of 3 #q has a common factor with of 5 #the rest is taken from the qiskit textbook https://qiskit.org/textbook/ch-algorithms/shor.html rows, measured_phases = [], [] for output in counts: decimal = int(output, 2) # Convert (base 2) string to decimal phase = decimal/(2**n_count) # Find corresponding eigenvalue measured_phases.append(phase) # Add these values to the rows in our table: rows.append(["%s(bin) = %i(dec)" % (output, decimal), "%i/%i = %.2f" % (decimal, 2**n_count, phase)]) # Print the rows in a table headers=["Register Output", "Phase"] df = pd.DataFrame(rows, columns=headers) print(df) rows = [] for phase in measured_phases: frac = Fraction(phase).limit_denominator(15) rows.append([phase, "%i/%i" % (frac.numerator, frac.denominator), frac.denominator]) # Print as a table headers=["Phase", "Fraction", "Guess for r"] df = pd.DataFrame(rows, columns=headers) print(df)
https://github.com/DanKim44/CodingWithQiskitS2
DanKim44
#Coding With Qiskit S2E5 Dinner Party using Grover's Algorithm %matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import * from qiskit.aqua.algorithms import Grover from qiskit.aqua.components.oracles import LogicalExpressionOracle from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit.tools.visualization import * from qiskit.tools.monitor import job_monitor # Loading your IBM Q account(s) provider = IBMQ.load_account() log_expr = '((Olivia & Abe) | (Jin & Amira)) & ~(Abe & Amira)' algorithm = Grover(LogicalExpressionOracle(log_expr)) backend = BasicAer.get_backend('qasm_simulator') result = algorithm.run(backend) plot_histogram(result['measurement'], title="Possible Party Combinations", bar_labels=True) #Top to bottom: #Abe Amira Jin Oliva #Mapping to random Digital Logic Homework: F=(~A+~B+C)(~A+B+C)(A+~B+C)(A+B+~C)(A+B+C) log_expr2 = '( ~A & ~B & C ) | ( ~A & B & C ) | ( A & ~B & C ) | ( A & B & ~C ) | ( A & B & C )' algorithm2 = Grover(LogicalExpressionOracle(log_expr2)) result2 = algorithm2.run(backend) plot_histogram(result2['measurement'], title="Homework:)", bar_labels=True) #Matches with homework problem & LogicAid:)
https://github.com/iremsener/Quantum-Programming-Algorithms-with-Qiskit
iremsener
from qiskit import * %matplotlib inline circuit = QuantumCircuit(2,2) circuit.draw() circuit.h(0) circuit.draw() circuit.cx(0,1) # 0-> control qubit, 1-> target qubit circuit.measure([0,1],[0,1]) circuit.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(circuit,backend=simulator).result() from qiskit.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) from qiskit.tools.visualization import plot_bloch_multivector from qiskit.visualization import plot_histogram import math # simülatörlerin tanımlanması qasm_simulator = Aer.get_backend('qasm_simulator') statevector_simulator = Aer.get_backend('statevector_simulator') # Tek bir fonksiyon kullanarak tanımladığımız simülatörlerde devremizi çalıştırıyoruz. def run_on_simulators(circuit): statevec_job = execute(circuit, backend=statevector_simulator) result = statevec_job.result() statevec = result.get_statevector() num_qubits = circuit.num_qubits circuit.measure([i for i in range(num_qubits)], [i for i in range(num_qubits)]) qasm_job = execute(circuit, backend=qasm_simulator, shots=1024).result() counts = qasm_job.get_counts() return statevec, counts circuit = QuantumCircuit(2,2) statevec, counts = run_on_simulators(circuit) plot_bloch_multivector(statevec) # Qubit 0 hadamard ile süperpozisyon durumuna girer circuit.h(0) statevec, counts = run_on_simulators(circuit) plot_bloch_multivector(statevec) circuit = QuantumCircuit(2,2) circuit.h(0) circuit.cx(0,1) # Controlled-X (CX) statevec, counts = run_on_simulators(circuit) plot_bloch_multivector(statevec) plot_histogram([counts]) circuit = QuantumCircuit(2,2) circuit.rx(math.pi/4, 0) # rx() , X ekseninde döndürme gerçekleştirir. circuit.rx(math.pi / 2, 1) # rx() , X ekseninde döndürme gerçekleştirir. statevec, counts = run_on_simulators(circuit) plot_bloch_multivector(statevec) circuit = QuantumCircuit(2,2) circuit.ry(math.pi/4, 0) # ry() , Y ekseninde döndürme gerçekleştirir. circuit.ry(math.pi / 2, 1) # ry() , Y ekseninde döndürme gerçekleştirir. statevec, counts = run_on_simulators(circuit) plot_bloch_multivector(statevec) circuit = QuantumCircuit(1,1) circuit.h(0) statevec, counts = run_on_simulators(circuit) plot_bloch_multivector(statevec) circuit = QuantumCircuit(1,1) circuit.h(0) circuit.z(0) # Z Kapısı statevec, counts = run_on_simulators(circuit) plot_bloch_multivector(statevec) plot_histogram([counts]) circuit = QuantumCircuit(3,3) circuit.x(0) # isteğe bağlı, bu örnekte 1. durumu aktarmak istiyoruz circuit.barrier() circuit.h(1) circuit.cx(1,2) circuit.barrier() circuit.draw() circuit.cx(0,1) circuit.h(0) circuit.barrier() circuit.draw() circuit.measure([0, 1], [0, 1]) circuit.barrier() circuit.draw() circuit.measure([0, 1], [0, 1]) circuit.barrier() circuit.draw() circuit.cx(1, 2) circuit.cz(0, 2) # Controlled-Z (CZ) Kapısı circuit.measure([2], [2]) circuit.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=simulator, shots=1024).result() from qiskit.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) secretNumber = '10101010100' circuit = QuantumCircuit(len(secretNumber)+1,len(secretNumber)) circuit.h(range(len(secretNumber))) circuit.x(len(secretNumber)) circuit.h(len(secretNumber)) circuit.barrier() for index, one in enumerate(reversed(secretNumber)): print(f"index{index} is {one}") if one == "1": circuit.cx(index,len(secretNumber)) circuit.barrier() circuit.h(range(len(secretNumber))) circuit.barrier() circuit.measure(range(len(secretNumber)),range(len(secretNumber))) circuit.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=simulator, shots=1).result() counts = result.get_counts() print(counts) plot_histogram([counts]) circuit = QuantumCircuit(2,1) circuit.h(0) circuit.x(1) circuit.h(1) circuit.barrier() circuit.draw() circuit.cx(0,1) circuit.barrier() circuit.h(0) circuit.barrier() circuit.draw() circuit.measure(0,0) circuit.draw() backend = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=backend, shots=1024).result() counts = result.get_counts(circuit) plot_histogram([counts]) myList = [5,4,6,9,1,2,3,7,8,0] def oracle(number): winningNumber = 8 if number == winningNumber: response = True else: response = False return response for index, number in enumerate(myList): if oracle(number) is True: print(f"winning number index: {index}") print(f"execution count: {index+1}") break oracleCircuit = QuantumCircuit(2,name='oracleCircuit') oracleCircuit.cz(0,1) oracleCircuit.to_gate() oracleCircuit.draw() mainCircuit = QuantumCircuit(2,2) mainCircuit.h([0,1]) mainCircuit.append(oracleCircuit,[0,1]) mainCircuit.draw() reflectionCircuit = QuantumCircuit(2,name="reflectionCircuit") reflectionCircuit.h([0,1]) reflectionCircuit.z([0,1]) reflectionCircuit.cz(0,1) reflectionCircuit.h([0,1]) reflectionCircuit.to_gate() reflectionCircuit.draw() mainCircuit.append(reflectionCircuit,[0,1]) mainCircuit.measure([0,1],[0,1]) mainCircuit.draw() backend = Aer.get_backend('qasm_simulator') result = execute(mainCircuit,backend=backend,shots=1).result() counts = result.get_counts(mainCircuit) plot_histogram([counts])
https://github.com/iremsener/Quantum-Programming-Algorithms-with-Qiskit
iremsener
from qiskit import * %matplotlib inline circuit = QuantumCircuit(2,2) #quantum_register = QuantumRegister(2) #classical_register = ClassicalRegister(2) #circuit = QuantumCircuit(quantum_register,classical_register) circuit.draw() circuit.h(0) circuit.draw() circuit.cx(0,1) # 0-> control qubit, 1-> target qubit circuit.measure([0,1],[0,1]) circuit.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(circuit,backend=simulator).result() from qiskit.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) from qiskit.tools.visualization import plot_bloch_multivector from qiskit.visualization import plot_histogram import math # identification of simulators qasm_simulator = Aer.get_backend('qasm_simulator') statevector_simulator = Aer.get_backend('statevector_simulator') # We run our circuit in the simulators we define using a single function. def run_on_simulators(circuit): statevec_job = execute(circuit, backend=statevector_simulator) result = statevec_job.result() statevec = result.get_statevector() num_qubits = circuit.num_qubits circuit.measure([i for i in range(num_qubits)], [i for i in range(num_qubits)]) qasm_job = execute(circuit, backend=qasm_simulator, shots=1024).result() counts = qasm_job.get_counts() return statevec, counts circuit = QuantumCircuit(2,2) statevec, counts = run_on_simulators(circuit) plot_bloch_multivector(statevec) # Qubit 0 enters superposition state with hadamard circuit.h(0) statevec, counts = run_on_simulators(circuit) plot_bloch_multivector(statevec) circuit = QuantumCircuit(2,2) circuit.h(0) circuit.cx(0,1) # Controlled-X (CX) statevec, counts = run_on_simulators(circuit) plot_bloch_multivector(statevec) plot_histogram([counts]) circuit = QuantumCircuit(2,2) circuit.rx(math.pi/4, 0) # rx() , performs rotation on the X axis. circuit.rx(math.pi / 2, 1) # rx() , performs rotation on the X axis. statevec, counts = run_on_simulators(circuit) plot_bloch_multivector(statevec) circuit = QuantumCircuit(2,2) circuit.ry(math.pi/4, 0) # ry() , performs rotation on the Y axis. circuit.ry(math.pi / 2, 1) # ry() , performs rotation on the Y axis. statevec, counts = run_on_simulators(circuit) plot_bloch_multivector(statevec) circuit = QuantumCircuit(1,1) circuit.h(0) statevec, counts = run_on_simulators(circuit) plot_bloch_multivector(statevec) circuit = QuantumCircuit(1,1) circuit.h(0) circuit.z(0) # Z Gate statevec, counts = run_on_simulators(circuit) plot_bloch_multivector(statevec) plot_histogram([counts]) circuit = QuantumCircuit(3,3) circuit.x(0) # optional, we want to transfer state 1 in this example circuit.barrier() circuit.h(1) circuit.cx(1,2) circuit.barrier() circuit.draw() circuit.cx(0,1) circuit.h(0) circuit.barrier() circuit.draw() circuit.measure([0, 1], [0, 1]) circuit.barrier() circuit.draw() circuit.cx(1, 2) circuit.cz(0, 2) # Controlled-Z (CZ) Gate circuit.measure([2], [2]) circuit.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=simulator, shots=1024).result() from qiskit.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) secretNumber = '10101010100' circuit = QuantumCircuit(len(secretNumber)+1,len(secretNumber)) circuit.h(range(len(secretNumber))) circuit.x(len(secretNumber)) circuit.h(len(secretNumber)) circuit.barrier() for index, one in enumerate(reversed(secretNumber)): print(f"index{index} is {one}") if one == "1": circuit.cx(index,len(secretNumber)) circuit.barrier() circuit.h(range(len(secretNumber))) circuit.barrier() circuit.measure(range(len(secretNumber)),range(len(secretNumber))) circuit.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=simulator, shots=1).result() counts = result.get_counts() print(counts) plot_histogram([counts]) circuit = QuantumCircuit(2,1) circuit.h(0) circuit.x(1) circuit.h(1) circuit.barrier() circuit.draw() circuit.cx(0,1) circuit.barrier() circuit.h(0) circuit.barrier() circuit.draw() circuit.measure(0,0) circuit.draw() backend = Aer.get_backend('qasm_simulator') result = execute(circuit, backend=backend, shots=1024).result() counts = result.get_counts(circuit) plot_histogram([counts]) myList = [5,4,6,9,1,2,3,7,8,0] def oracle(number): winningNumber = 8 if number == winningNumber: response = True else: response = False return response for index, number in enumerate(myList): if oracle(number) is True: print(f"winning number index: {index}") print(f"execution count: {index+1}") break oracleCircuit = QuantumCircuit(2,name='oracleCircuit') oracleCircuit.cz(0,1) oracleCircuit.to_gate() oracleCircuit.draw() mainCircuit = QuantumCircuit(2,2) mainCircuit.h([0,1]) mainCircuit.append(oracleCircuit,[0,1]) mainCircuit.draw(output='mpl') reflectionCircuit = QuantumCircuit(2,name="reflectionCircuit") reflectionCircuit.h([0,1]) reflectionCircuit.z([0,1]) reflectionCircuit.cz(0,1) reflectionCircuit.h([0,1]) reflectionCircuit.to_gate() reflectionCircuit.draw() mainCircuit.append(reflectionCircuit,[0,1]) mainCircuit.measure([0,1],[0,1]) mainCircuit.draw() backend = Aer.get_backend('qasm_simulator') result = execute(mainCircuit,backend=backend,shots=1).result() counts = result.get_counts(mainCircuit) plot_histogram([counts])
https://github.com/nickk124/quantumsearch
nickk124
import sys sys.path.insert(0, 'qrw/') from qrw import QRWsearch %config InlineBackend.figure_format = 'svg' # Makes the images look nice search_circuit = QRWsearch(2,0) # display the matrix the shift operator search_circuit.S(display_matrix=True); # display the matrix the shift operator search_circuit.C(display_matrix=True); # display the matrix the U search_circuit.Uprime(display_matrix=True); # display the operator U search_circuit.Uprime() search_circuit.draw_circuit() search_circuit.plot_states_hist() import sys sys.path.insert(0, 'quantum_decomp/') import quantum_decomp as qd gates = qd.matrix_to_gates(search_circuit.Uprime().data) gates from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister n_steps=1 q = QuantumRegister (3, name='q') #3 qubit register c = ClassicalRegister (3, name='c') #3 bit classical register circ = QuantumCircuit (q,c) #Main circuit for i in range(1): circ.h(0) circ.ccx(0, 2, 1) circ.ccx(1, 2, 0) circ.x(0) circ.ccx(0, 1, 2) circ.x(0) circ.x(2) circ.ccx(1, 2, 0) circ.ccx(0, 2, 1) circ.x(1) circ.ccx(1, 2, 0) circ.x(1) circ.x(2) circ.ccx(1, 2, 0) circ.x(0) circ.ccx(0, 1, 2) circ.x(0) circ.x(2) circ.ccx(1, 2, 0) circ.x(2) circ.ccx(0, 2, 1) circ.ccx(1, 2, 0) circ.x(0) circ.ccx(0, 1, 2) circ.x(0) circ.x(1) circ.ccx(1, 2, 0) circ.x(1) circ.ccx(0, 2, 1) circ.ccx(1, 2, 0) circ.barrier() circ.measure ([q[0],q[1],q[2]], [c[0],c[1],c[2]]) circ.draw('mpl') from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.visualization import plot_histogram, plot_state_city from qiskit import execute, Aer n_steps=4 q = QuantumRegister (3, name='q') #3 qubit register c = ClassicalRegister (3, name='c') #3 bit classical register circ = QuantumCircuit (q,c) #Main circuit for i in range(n_steps): circ.h(q[0]) # coin circ.ccx(q[0],q[1],q[2]) # Toffoli circ.cx (q[0], q[1]) # CNOT circ.x(q[0]) circ.x(q[1]) circ.ccx(q[0], q[1], q[2]) circ.x(q[1]) circ.cx(q[0],q[1]) circ.barrier() circ.measure([q[0],q[1],q[2]], [c[0],c[1],c[2]]) circ.draw('mpl') backend = Aer.get_backend('qasm_simulator') shots = 1024 # number of times circuit is run, for sampling results = execute(circ, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/nickk124/quantumsearch
nickk124
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jun 27 12:07:22 2020 @author: ericyelton """ #Imports import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit,execute, Aer # gates/operators from qiskit.quantum_info.operators import Operator from qiskit.quantum_info import random_unitary #visualization from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt import matplotlib.patches as patch from matplotlib.path import Path from matplotlib.animation import FuncAnimation #in this algorithm we have a dimension of n for the state space #then we have log2(n) states in the coin space #defining the dimensions of the quantum circuit class QRWreg: """ QRWreg initializes a Quantum Random Walk registry it inputs the variable dim which is the number of qubits in the state space """ #dim is the number of qubits #c is the number of coin qubits def __init__(self,dim): c = (np.log2(dim)) if c.is_integer() != 1: raise TypeError("The number of qubits n must have log2(n) be an integer") self.c = int(c) self.dim = dim n = int(dim+c) #the total number of qubits used will be given by self.n = n qr = QuantumRegister(n,'q') cl = ClassicalRegister(n,"c") self.qr = qr self.cl = cl circ = QuantumCircuit(qr, cl) self.circuit = circ #defining the QRW search algorithm as a subclass of the QRW registry class QRWsearch(QRWreg): """ QRWsearch is an implimentation of the quantum random walk search algorithm based on the paper titled "Quantum random-walk search algorithm" from N. Shenvi et al this class ineherits the QRWreg class dim - number of qubits in the state space state_search - the state that the algorithm searches for """ def __init__(self,dim,state_search): QRWreg.__init__(self,dim) self.circuit = QRWreg(dim).circuit quan_reg = QRWreg(dim).qr clas_reg = QRWreg(dim).cl self.search = state_search circ = self.circuit #hadamards on all of the states circ.h(quan_reg[0:self.n]) #operating U prime pi/2 sqrt(2) times times = np.ceil(0.5*np.pi*np.sqrt(2**(self.dim))) for i in range(int(times)): circ.unitary(self.Uprime(),quan_reg,label="U'") #measure the registry onto the classical bits circ.measure(quan_reg,clas_reg) #defining all of the operators for the QRW search def S(self, display_matrix=False): coin = self.c num_dir = int(2 ** coin) state = self.dim S = np.zeros((2**(coin+state),2**(coin+state))) for i in range(num_dir): for j in range(2**state): #performing the bit flip using an XOR j_bin = int(j) e_i = int(i+1) xor = j_bin ^ e_i row = xor+(i*(2**state)) S[row][j+(i*(2**state))] =1 if display_matrix: print('Matrix for the shift operator:') print(S) return Operator(S) def C(self, display_matrix=False): #definition of the C operator is an outer product in the coin space #tensor product with the identity in state spac coin = self.c num_dir = int(2 ** coin) state = self.dim num_state = int(2**state) #defining the operator in just the coin space s_c = np.zeros((2**(coin),2**(coin))) I_c = np.zeros((2**(coin),2**(coin))) for i in range(num_dir): I_c[i][i] = 1 for j in range(num_dir): s_c[i][j] =num_dir**-1 s_c = 2*s_c s_c = Operator(s_c) I_c = Operator(I_c) G = s_c-I_c #defining the identity in the state space I_s = np.zeros((2**(state),2**(state))) for i in range(num_state): I_s[i][i] = 1 I = Operator(I_s) C = G.tensor(I) if display_matrix: print('Matrix for the quantum coin operator:') print(np.real(C.data)) return C def U(self, display_matrix=False): S_= self.S() C_ = self.C() U = C_.compose(S_) if display_matrix: print('Matrix for U:') print(np.real(U.data)) return U def Uprime(self, display_matrix=False): #state_search is the state we are searching for #we will focus on the second term #Note that state search must be in decimal if self.search >= 2**self.dim: raise TypeError("Search State parameter is outside of state space values") elif self.search < 0: raise TypeError("Search State parameter is outside of state space values") else: #focusings on the second term of Uprime coin = self.c num_dir = int(2**coin) state = self.dim num_state = int(2**state) search_array = np.zeros((num_state,num_state)) search_array[self.search][self.search] = 1 search = Operator(search_array) s_c = np.zeros((2**(coin),2**(coin))) for i in range(num_dir): for j in range(num_dir): s_c[i][j] = num_dir**-1 coin_ = Operator(s_c) search_op = coin_.tensor(search) S_ = self.S() term2 = search_op.compose(S_) U_ = self.U() Uprime = U_-(2*term2) if display_matrix: print("Matrix for U':") print(np.real(Uprime.data)) return Uprime #Visualization def draw_circuit(self): return self.circuit.draw(output='mpl') def plot_states_hist(self): # plots by actually measuring the circuit #self.circuit.measure_all() backend = Aer.get_backend('qasm_simulator') shots = 1024 # number of times circuit is run, for sampling results = execute(self.circuit, backend=backend, shots=shots).result() answer = results.get_counts() return plot_histogram(answer, figsize=(5,5)) #defining the QRW algorithm as a subclass of the QRW registry class QRW(QRWreg): """ The QRW Class is an arbitrary implementation of a QRW dim - number of qubits in the state space c_label = is a string that determines what coin operator to use on the coin space - Hadamard = Hadamard operator tensor product with the Identity -Random = Is a random unitary operator step - is the number of 'steps' the QRW completes it is the number of times the operator U is called """ def __init__(self,dim,c_label,step): QRWreg.__init__(self,dim) self.circuit = QRWreg(dim).circuit quan_reg = QRWreg(dim).qr clas_reg = QRWreg(dim).cl circ = self.circuit #hadamards on all of the states circ.h(quan_reg[0:self.n]) for i in range(int(step)): circ.unitary(self.U(c_label),quan_reg,label="Step") #measure the registry onto the classical bits circ.measure(quan_reg,clas_reg) #defining all of the operators for the QRW search def S(self): coin = self.c num_dir = int(2 ** coin) state = self.dim S = np.zeros((2**(coin+state),2**(coin+state))) for i in range(num_dir): for j in range(2**state): #performing the bit flip using an XOR j_bin = int(j) e_i = int(i+1) xor = j_bin ^ e_i row = xor+(i*(2**state)) S[row][j+(i*(2**state))] =1 return Operator(S) def C(self,c_label): coin = self.c state = self.dim #creating the identity in the S space I = np.zeros((2**state,2**state)) for i in range(2**state): I[i][i] = 1 I = Operator(I) if c_label == "Hadamard": result= np.zeros((2**coin,2**coin)) for i in range(2**coin): for j in range(2**coin): #bin_i = bin(i) #bin_j = bin(j) if i >= 2 and j >= 2: result[i][j] = -1*(-1)**(i * j)*(2**(-1*(0.5*coin))) else: result[i][j] = (-1)**(i * j)*(2**(-1*(0.5*coin))) res_op = (Operator(result)) C_final = res_op.tensor(I) return C_final elif c_label == "Random": dim = [] for i in range(coin): dim.append(2) res_op = random_unitary(tuple(dim)) C_final = res_op.tensor(I) return C_final else: raise TypeError("Label string for C is not a valid input") def U(self,c_label): S_= self.S() C_ = self.C(c_label) U = C_.compose(S_) return U #Visualization def draw_circuit(self): return self.circuit.draw() def plot_states_hist(self): # plots by actually measuring the circuit backend = Aer.get_backend('qasm_simulator') print(backend) shots = 1024 # number of times circuit is run, for sampling results = execute(self.circuit, backend=backend, shots=shots).result() print(results.get_counts()) answer = results.get_counts() return plot_histogram(answer, figsize=(15,5)) #controlling the circuit def execute(self): backend = Aer.get_backend('qasm_simulator') results = execute(self.circuit, backend=backend,shots = 1).result() answer = results.get_counts() #one execution means there will be one state in the answer dict state = list(answer.keys()) return state[0] #animating the 2D 'mapping' for the QRW it inherits the QRW class class QRW_Automata(QRW): """ QRW_Automata is a class that inherits the QRW class it animates multiple executions of the QRW algorithm into a cellular automata board Note this algorithm has only been defined for the cases of 2 and 4 state qubits! dim - number of qubits in the state space c_label = is a string that determines what coin operator to use on the coin space - Hadamard = Hadamard operator tensor product with the Identity -Random = Is a random unitary operator step - is the number of 'steps' the QRW completes it is the number of times the operator U is called iters - number of times the circuit is executed (also determines the number of frames in the animation) """ def __init__(self,dim,c_label,step,iters): QRW.__init__(self,dim,c_label,step) self.n = QRW(dim,c_label,step).n self.c = QRW(dim,c_label,step).c self.circ = QRW(dim,c_label,step).circuit state = [] for i in range(iters): state.append(QRW(dim,c_label,step).execute()) self.state = state print("state") print(state) c_state = [] s_state = [] for i in state: c_state.append(i[0:self.c]) s_state.append(i[self.c:]) self.c_state = c_state self.s_state = s_state if (dim/2).is_integer() != True: raise ValueError("The one-half of the number of qubits in the state space must be an integer") #dividing up the board according to number of bits #n is the number of rows and columns #we are just doing the case for n = 4 if int(self.dim) !=4 and int(self.dim) !=2: raise ValueError("Grid is implemented for only for the cases where n=2 and n=4 in the state space") figure,axes = plt.subplots(nrows = 2,ncols = 1) plt.title("QRW Automata {step}".format(step=c_label)) axes[0].set_facecolor((0,0,0)) axes[0].get_xaxis().set_ticks([]) axes[0].get_yaxis().set_ticks([]) axes[1].get_xaxis().set_ticks([]) axes[1].get_yaxis().set_ticks([]) self.fig = figure self.ax = axes self.circuit.draw('mpl',scale = 0.9,ax=axes[1]) n_v = (2*self.dim) if self.c % 2 !=0: n_h = self.dim else: n_h = n_v v_lines = np.arange(0,1,1/n_v) h_lines = np.arange(0,1,1/n_h) #drawing the frames for the board for i in v_lines: axes[0].axvline(x=i,ymin=0,ymax=1,color='r') for i in h_lines: axes[0].axhline(y=i,xmin=0,xmax=1,color='r') anim = FuncAnimation(self.fig,self.animate, frames =int(len(state)), interval = 200) anim.save("QRW_{n}qubits_{op}_{st}steps.mp4".format(n = self.dim,op = c_label,st = step),) def animate(self,i): #ploting the state space : if self.dim ==2: c_ = self.c_state[i] s_ = self.s_state[i] n_v = (2*self.dim) n_h = self.dim verts = [ (0.+int(s_[-1])*(1/n_v)+0.5*int(c_), 1.-int(s_[0])*(1/n_h)-(1/n_h)), # left, bottom (0.+int(s_[-1])*(1/n_v)+0.5*int(c_), 1.-int(s_[0])*(1/n_h)), # left, top ((1/n_v)+int(s_[-1])*(1/n_v)+0.5*int(c_), 1.-int(s_[0])*(1/n_h)), # right, top ((1/n_v)+int(s_[-1])*(1/n_v)+0.5*int(c_), 1.-int(s_[0])*(1/n_h)-(1/n_h)), # right, bottom (0.+int(s_[-1])*(1/n_v)+0.5*int(c_), 1.-int(s_[0])*(1/n_h)-(1/n_h)), # ignored ] codes = [ Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY, ] path = Path(verts,codes) cell = patch.PathPatch(path,facecolor = 'w') self.ax[0].set_xlabel("Measured state:{state_}".format(state_=self.state[i])) self.ax[0].add_patch(cell) return patch elif self.dim ==4: c_ = self.c_state[i] s_ = self.s_state[i] n_v = (2*self.dim) n_h = (2*self.dim) verts = [ (0.+int(s_[-1])*(1/n_v)+int(s_[-2])*(2/n_v)+0.5*int(c_[1]), 1.-int(s_[0])*2*(1/n_h)-int(s_[1])*(1/n_h)-(1/n_h)-0.5*int(c_[0])), # left, bottom (0.+int(s_[-1])*(1/n_v)+int(s_[-2])*(2/n_v)+0.5*int(c_[1]), 1.-int(s_[0])*2*(1/n_h)-int(s_[1])*(1/n_h)-0.5*int(c_[0])), # left, top ((1/n_v)+int(s_[-1])*(1/n_v)+int(s_[-2])*(2/n_v)+0.5*int(c_[1]), 1.-int(s_[0])*2*(1/n_h)-int(s_[1])*(1/n_h)-0.5*int(c_[0])), # right, top ((1/n_v)+int(s_[-1])*(1/n_v)+int(s_[-2])*(2/n_v)+0.5*int(c_[1]), 1.-int(s_[0])*2*(1/n_h)-int(s_[1])*(1/n_h)-(1/n_h)-0.5*int(c_[0])), # right, bottom (0.+int(s_[-1])*(1/n_v)+int(s_[-2])*(2/n_v)+0.5*int(c_[1]), 1.-int(s_[0])*2*(1/n_h)-int(s_[1])*(1/n_h)-(1/n_h)-0.5*int(c_[0])), # ignored ] codes = [ Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY, ] path = Path(verts,codes) cell = patch.PathPatch(path,facecolor = 'w') self.ax[0].set_xlabel("Measured state:{state_}".format(state_=self.state[i])) self.ax[0].add_patch(cell) return patch if __name__=='main': QRW_Automata(4,"Hadamard",4,15)
https://github.com/nickk124/quantumsearch
nickk124
# Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * # Loading your IBM Q account(s) # provider = IBMQ.load_account() from qiskit import * from qiskit.providers.ibmq import least_busy # imports import qiskit import math # imports import matplotlib.pyplot as plt import numpy as np %matplotlib inline %config InlineBackend.figure_format = 'svg' # Makes the images look nice # import qiskit from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute # import basic plot tools from qiskit.visualization import plot_histogram, plot_state_city # gates/operators from qiskit.quantum_info.operators import Operator qiskit.__qiskit_version__ # CONVERSION TOOLS def int_to_binary(i, length): # returns binary string of int with some length raw_str = "{0:b}".format(i) return raw_str.zfill(length) def get_binary_basis_vec(d, n): # returns vec e_d from equation 2, string form # d is direction, n is number of dimensions/qubits e_d = ''.zfill(n - 1 - d) + '1' + ''.zfill(d) return e_d def bitwise_xor(a, b): # get bitwise addition/xor of two strings, length preserved y = int(a, 2)^int(b,2) return bin(y)[2:].zfill(len(a)) # VISUALIZATION TOOLS def draw_circuit(self): return self.circuit.draw('mpl') def plot_states_hist(self): # plots by actually measuring the circuit self.circuit.measure_all() backend = Aer.get_backend('qasm_simulator') shots = 1024 # number of times circuit is run, for sampling results = execute(self.circuit, backend=backend, shots=shots).result() answer = results.get_counts() return plot_histogram(answer) def plot_states_3D(self): # plots current states in 3D backend = Aer.get_backend('statevector_simulator') # the device to run on results = execute(self.circuit, backend).result() answer = result.get_statevector(self.circuit) return plot_state_city(answer) # CIRCUIT TOOLS def get_n_qubits_coin(self): # number of qubits needed for the coin/ # number of bits needed to specify direction in n-cube return int(math.ceil(np.log2(self.n))) def initialize_circuit(self): # initializes quantum computer # need to initialize an equal superposition over all states self.n_qubits_coin = get_n_qubits_coin(self) # qubits needed for coin self.n_qubits_total = self.n + self.n_qubits_coin coin_register = QuantumRegister(self.n_qubits_coin, 'coin') cube_register = QuantumRegister(self.n, 'node') circuit = QuantumCircuit(coin_register, cube_register) for qubit in range(self.n_qubits_total): circuit.h(qubit) # perform hadamard on each qubit return circuit # OPERATORS/GATES def get_sC_matrix(self): # gets |s^C><s^C| matrix sC_matrix = np.ones((self.n, self.n)) / n return sC_matrix def get_sC_operator(self): sC_matrix = get_sC_matrix(self) return Operator(sC_matrix) def get_shift_matrix(self): # get matrix form of S operator S = np.zeros((self.dim_U, self.dim_U)) # following equation 2 of the paper for d in range(self.n): # sum over each cartesian direction for x in range(self.N): # loop over each position on hypercube d_str = int_to_binary(d, self.n_qubits_coin) x_str = int_to_binary(x, self.n) e_d_str = get_binary_basis_vec(d, self.n) # print(d_str,x_str,e_d_str) # binary string that shows row: row_str = d_str + bitwise_xor(x_str, e_d_str) # same, for col: col_str = d_str + x_str row_index = int(row_str, 2) col_index = int(col_str, 2) # print(row_index, col_index) S[row_index][col_index] = 1 return S def get_shift_operator(self): # S operator, from the paper # get matrix from of the operator S_matrix = get_shift_matrix(self) return Operator(S_matrix) def get_c_matrices(self): #C matrix grovers = np.full((self.n, self.n), 2/self.n) np.fill_diagonal(grovers, 2/self.n-1) coin_operator = np.kron(grovers, np.eye(self.N)) return grovers, coin_operator def get_coin_matrix(self): C_0, C = get_c_matrices(self) tens1 = -np.eye(self.n)- C_0 tens2 = np.zeros((self.N,self.N)) # |000…00><000…00| term tens2[0][0] = 1 right_term = np.kron(tens1, tens2) return C+right_term def get_perturbed_coin_operator(self): # C' operator, from the paper coin_matrix = get_coin_matrix(self) return Operator(coin_matrix) def get_perturbed_evolution_matrix(self): # U' matrix in the paper Cprime = get_coin_matrix(self) S = get_shift_matrix(self) return np.matmul(Cprime,S) def get_perturbed_evolution_operator(self): # U' operator in the paper S = get_shift_operator(self) Cprime = get_perturbed_coin_operator(self) Uprime = Cprime.compose(S) return Uprime class QRW: # INITIALIZATION HELPERS def __init__(self, num_qubits_cube): self.n = num_qubits_cube # total number of qubits in cube; n-cube will have N = 2^n nodes self.N = int(2**n) self.dim_U = self.n * int(2**n) # no. of rows/cols for U/S/C self.circuit = self.initialize_circuit() # CIRCUIT TOOLS initialize_circuit = initialize_circuit # VISUALIZATION TOOLS draw_circuit = draw_circuit plot_states_hist = plot_states_hist plot_states_3D = plot_states_3D n = 2 qrw = QRW(n) # initialize computer qrw.draw_circuit() #qrw_instance.plot_states_hist() fig, axes = plt.subplots(1,3,figsize=(10,10)) S = get_shift_matrix(qrw) sC = get_sC_matrix(qrw) axes[0].imshow(S) cprime = get_coin_matrix(qrw) axes[1].imshow(np.real(cprime.data)) Uprime = get_perturbed_evolution_operator(qrw) axes[2].imshow(np.real(Uprime.data)) plt.show() from qiskit.extensions import UnitaryGate uprime = get_perturbed_evolution_operator(qrw) uprime = UnitaryGate(uprime,label="U'") cx_circ = QuantumCircuit(3) cx_circ.unitary(uprime, [x for x in range(3)],label="U'") def is_unitary(m): return np.allclose(np.eye(m.shape[0]), m.H * m) uprime = get_perturbed_evolution_matrix(qrw) is_unitary(np.matrix(uprime)) shift = get_shift_matrix(qrw) is_unitary(np.matrix(shift)) n = 10 for d in range(n): print(get_binary_basis_vec(d, n)) from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute n_steps = 1 #Number of steps #Defining the shift gate shift_q = QuantumRegister(3) #3 qubit register shift_circ = QuantumCircuit (shift_q, name='shift gate') #shift operator shift_circ.ccx (shift_q[0], shift_q[1], shift_q[2]) #Toffoli shift_circ.cx (shift_q[0], shift_q[1]) #CNOT shift_circ.x ( shift_q[0]) shift_circ.x ( shift_q[1] ) shift_circ.ccx (shift_q[0], shift_q[1], shift_q[2]) shift_circ.x ( shift_q[1] ) shift_circ.cx ( shift_q[0], shift_q[1] ) shift_gate = shift_circ.to_instruction() #Convert the circuit to a gate q = QuantumRegister (3, name='q') #3 qubit register c = ClassicalRegister (3, name='c') #3 bit classical register circ = QuantumCircuit (q,c) #Main circuit for i in range(n_steps): circ.h (q[0]) #Coin step circ.ccx (q[0], q[1], q[2]) #Toffoli circ.cx (q[0], q[1]) #CNOT circ.x ( q[0]) circ.x ( q[1] ) circ.ccx (q[0], q[1], q[2]) circ.x ( q[1] ) circ.cx ( q[0], q[1] ) circ.barrier() circ.measure ([q[0],q[1],q[2]], [c[0],c[1],c[2]]) circ.draw('mpl') from qiskit.visualization import plot_histogram, plot_state_city backend = Aer.get_backend('qasm_simulator') shots = 1024 # number of times circuit is run, for sampling results = execute(circ, backend=backend, shots=shots).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/nickk124/quantumsearch
nickk124
# Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * # Loading your IBM Q account(s) # provider = IBMQ.load_account() from qiskit import * from qiskit.providers.ibmq import least_busy # imports import qiskit import math # imports import matplotlib.pyplot as plt import numpy as np %matplotlib inline %config InlineBackend.figure_format = 'svg' # Makes the images look nice # import qiskit from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute # import basic plot tools from qiskit.visualization import plot_histogram, plot_state_city # gates/operators from qiskit.quantum_info.operators import Operator from qiskit.extensions import UnitaryGate qiskit.__qiskit_version__ # CONVERSION TOOLS def int_to_binary(i, length): # returns binary string of int with some length raw_str = "{0:b}".format(i) return raw_str.zfill(length) def get_binary_basis_vec(d, n): # returns vec e_d from equation 2, string form # d is direction, n is number of dimensions/qubits e_d = ''.zfill(n - 1 - d) + '1' + ''.zfill(d) return e_d def bitwise_xor(a, b): # get bitwise addition/xor of two strings, length preserved y = int(a, 2)^int(b,2) return bin(y)[2:].zfill(len(a)) # VISUALIZATION TOOLS def draw_circuit(self): return self.circuit.draw('mpl') def plot_states_hist(self): # plots by actually measuring the circuit self.circuit.measure_all() backend = Aer.get_backend('qasm_simulator') shots = 1024 # number of times circuit is run, for sampling results = execute(self.circuit, backend=backend, shots=shots).result() answer = results.get_counts() return plot_histogram(answer) def plot_states_3D(self): # plots current states in 3D backend = Aer.get_backend('statevector_simulator') # the device to run on results = execute(self.circuit, backend).result() answer = result.get_statevector(self.circuit) return plot_state_city(answer) # CIRCUIT TOOLS def get_n_qubits_coin(self): # number of qubits needed for the coin/ # number of bits needed to specify direction in n-cube return int(math.ceil(np.log2(self.n))) def initialize_circuit(self): # initializes quantum computer # need to initialize an equal superposition over all states self.n_qubits_coin = get_n_qubits_coin(self) # qubits needed for coin self.n_qubits_total = self.n + self.n_qubits_coin coin_register = QuantumRegister(self.n_qubits_coin, 'coin') cube_register = QuantumRegister(self.n, 'node') circuit = QuantumCircuit(coin_register, cube_register) for qubit in range(self.n_qubits_total): circuit.h(qubit) # perform hadamard on each qubit self.circuit_initialized = True return circuit def make_gates_n_2(self): # add one set of U' gates for n = 2 case circ = self.circuit # circ.h(0) // davis # circ.ccx(0, 1, 2) # circ.cx(0, 1) # circ.x(0) # circ.x(1) # circ.ccx(0, 1, 2) # circ.x(1) # circ.cx(0, 1) circ.ccx(0, 2, 1) circ.ccx(1, 2, 0) circ.x(0) circ.ccx(0, 1, 2) circ.x(0) circ.x(2) circ.ccx(1, 2, 0) circ.ccx(0, 2, 1) circ.x(1) circ.ccx(1, 2, 0) circ.x(1) circ.x(2) circ.ccx(1, 2, 0) circ.x(0) circ.ccx(0, 1, 2) circ.x(0) circ.x(2) circ.ccx(1, 2, 0) circ.x(2) circ.ccx(0, 2, 1) circ.ccx(1, 2, 0) circ.x(0) circ.ccx(0, 1, 2) circ.x(0) circ.x(1) circ.ccx(1, 2, 0) circ.x(1) circ.ccx(0, 2, 1) circ.ccx(1, 2, 0) return def perform_evolution_gates(self, tF): # use explicit gates, n-dependent supported_qubit_counts = [2] # supported values for n if self.n in supported_qubit_counts: for it in range(tF): make_gates_n_2(self) else: print("Error: n = {} qubits not currently supported\nfor explicit gate implementation.".format(self.n)) return def perform_evolution_operators(self, tF): # use the qiskit Operator API Uprime = get_perturbed_evolution_operator(self) Uprime = UnitaryGate(Uprime,label="U'") for it in range(tF): self.circuit.unitary(Uprime, [i for i in range(self.n_qubits_total)], label="Uprime") return def perform_evolution(self, num_iters=None, use_operators=False): # perform step 2 of algorithm if not self.circuit_initialized: print("Error: initialize circuit first!") return if num_iters is None: tF = math.ceil(np.pi * np.sqrt(self.N) / 2) # number of times to apply evolution op else: tF = num_iters if use_operators: perform_evolution_operators(self, tF) else: perform_evolution_gates(self, tF) return self.draw_circuit() # OPERATORS/GATES def get_sC_matrix(self): # gets |s^C><s^C| matrix sC_matrix = np.ones((self.n, self.n)) / n return sC_matrix def get_sC_operator(self): sC_matrix = get_sC_matrix(self) return Operator(sC_matrix) def get_shift_matrix(self): # get matrix form of S operator S = np.zeros((self.dim_U, self.dim_U)) # following equation 2 of the paper for d in range(self.n): # sum over each cartesian direction for x in range(self.N): # loop over each position on hypercube d_str = int_to_binary(d, self.n_qubits_coin) x_str = int_to_binary(x, self.n) e_d_str = get_binary_basis_vec(d, self.n) # print(d_str,x_str,e_d_str) # binary string that shows row: row_str = d_str + bitwise_xor(x_str, e_d_str) # same, for col: col_str = d_str + x_str row_index = int(row_str, 2) col_index = int(col_str, 2) # print(row_index, col_index) S[row_index][col_index] = 1 print(S) return S def get_shift_operator(self): # S operator, from the paper # get matrix from of the operator S_matrix = get_shift_matrix(self) return Operator(S_matrix) def get_c_matrices(self): #C matrix grovers = np.full((self.n, self.n), 2/self.n) np.fill_diagonal(grovers, 2/self.n-1) coin_operator = np.kron(grovers, np.eye(self.N)) return grovers, coin_operator def get_coin_matrix(self): C_0, C = get_c_matrices(self) tens1 = -np.eye(self.n)- C_0 tens2 = np.zeros((self.N,self.N)) # |000…00><000…00| term tens2[1][1] = 1 right_term = np.kron(tens1, tens2) return C+right_term def get_perturbed_coin_operator(self): # C' operator, from the paper coin_matrix = get_coin_matrix(self) return Operator(coin_matrix) def get_perturbed_evolution_matrix(self): # U' matrix in the paper Cprime = get_coin_matrix(self) S = get_shift_matrix(self) return np.matmul(Cprime,S) def get_perturbed_evolution_operator(self): # U' operator in the paper S = get_shift_operator(self) Cprime = get_perturbed_coin_operator(self) #print(Cprime.data.shape) #self.circuit.append(S) Uprime = S.compose(Cprime, front=True) return Uprime class QRW: # INITIALIZATION HELPERS def __init__(self, num_qubits_cube): self.n = num_qubits_cube # total number of qubits in cube; n-cube will have N = 2^n nodes self.N = int(2**n) self.dim_U = self.n * int(2**n) # no. of rows/cols for U/S/C self.circuit = self.initialize_circuit() # CIRCUIT TOOLS initialize_circuit = initialize_circuit perform_evolution = perform_evolution # VISUALIZATION TOOLS draw_circuit = draw_circuit plot_states_hist = plot_states_hist plot_states_3D = plot_states_3D n = 2 qrw = QRW(n) # initialize computer #qrw_instance.plot_states_hist() qrw.perform_evolution() qrw.draw_circuit() #qrw.plot_states_hist() qrw.plot_states_hist() Uprime = get_perturbed_evolution_operator(qrw) print(Uprime.data.shape) circuit = QuantumCircuit(3) from qiskit.extensions import UnitaryGate uprime = get_perturbed_evolution_operator(qrw) uprime = UnitaryGate(uprime,label="U'") circuit.unitary(uprime, [0, 1, 2]) circuit.draw('mpl') fig, axes = plt.subplots(1,3,figsize=(10,10)) S = get_shift_matrix(qrw) sC = get_sC_matrix(qrw) axes[0].imshow(S) cprime = get_coin_matrix(qrw) axes[1].imshow(np.real(cprime.data)) Uprime = get_perturbed_evolution_operator(qrw) print(np.array(Uprime.data)) axes[2].imshow(np.real(Uprime.data)) plt.show() from qiskit.extensions import UnitaryGate uprime = get_perturbed_evolution_operator(qrw) uprime = UnitaryGate(uprime,label="U'") qrw.unitary(uprime, [0,1,2]) draw_circuit(qrw) def is_unitary(m): return np.allclose(np.eye(m.shape[0]), m.H * m) uprime = get_perturbed_evolution_matrix(qrw) is_unitary(np.matrix(uprime)) shift = get_shift_matrix(qrw) is_unitary(np.matrix(shift)) import quantum_decomp as qd Uprime.data print(qd.matrix_to_qsharp(Uprime.data)) # gates = qd.matrix_to_gates(Uprime.data) # print('\n'.join(map(str, gates)))
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Exception for errors raised by Qiskit Aer simulators backends. """ from qiskit import QiskitError class QrackError(QiskitError): """Base class for errors raised by simulators.""" def __init__(self, *message): """Set the error message.""" super().__init__(*message) self.message = ' '.join(message) def __str__(self): """Return the message.""" return repr(self.message)
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
import numpy as np import math from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, QiskitError from qiskit.compiler import assemble from qiskit.providers.aer import QasmSimulator from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info.synthesis import two_qubit_cnot_decompose class QuantumFourierTransformFusionSuite: def __init__(self): self.timeout = 60 * 20 self.backend = QasmSimulator() num_qubits = [5, 10, 15, 20, 25] self.circuit = {} for num_qubit in num_qubits: for use_cu1 in [True, False]: circuit = self.qft_circuit(num_qubit, use_cu1) self.circuit[(num_qubit, use_cu1)] = assemble(circuit, self.backend, shots=1) self.param_names = ["Quantum Fourier Transform", "Fusion Activated", "Use cu1 gate"] self.params = (num_qubits, [True, False], [True, False]) @staticmethod def qft_circuit(num_qubit, use_cu1): qreg = QuantumRegister(num_qubit,"q") creg = ClassicalRegister(num_qubit, "c") circuit = QuantumCircuit(qreg, creg) for i in range(num_qubit): circuit.h(qreg[i]) for i in range(num_qubit): for j in range(i): l = math.pi/float(2**(i-j)) if use_cu1: circuit.cu1(l, qreg[i], qreg[j]) else: circuit.u1(l/2, qreg[i]) circuit.cx(qreg[i], qreg[j]) circuit.u1(-l/2, qreg[j]) circuit.cx(qreg[i], qreg[j]) circuit.u1(l/2, qreg[j]) circuit.h(qreg[i]) circuit.barrier() for i in range(num_qubit): circuit.measure(qreg[i], creg[i]) return circuit def time_quantum_fourier_transform(self, num_qubit, fusion_enable, use_cu1): """ Benchmark QFT """ result = self.backend.run(self.circuit[(num_qubit, use_cu1)], fusion_enable=fusion_enable).result() if result.status != 'COMPLETED': raise QiskitError("Simulation failed. Status: " + result.status) class RandomFusionSuite: def __init__(self): self.timeout = 60 * 20 self.backend = QasmSimulator() self.param_names = ["Number of Qubits", "Fusion Activated"] self.params = ([5, 10, 15, 20, 25], [True, False]) @staticmethod def build_model_circuit_kak(width, depth, seed=None): """Create quantum volume model circuit on quantum register qreg of given depth (default depth is equal to width) and random seed. The model circuits consist of layers of Haar random elements of U(4) applied between corresponding pairs of qubits in a random bipartition. """ qreg = QuantumRegister(width) depth = depth or width np.random.seed(seed) circuit = QuantumCircuit(qreg, name="Qvolume: %s by %s, seed: %s" % (width, depth, seed)) for _ in range(depth): # Generate uniformly random permutation Pj of [0...n-1] perm = np.random.permutation(width) # For each pair p in Pj, generate Haar random U(4) # Decompose each U(4) into CNOT + SU(2) for k in range(width // 2): U = random_unitary(4, seed).data for gate in two_qubit_cnot_decompose(U): qs = [qreg[int(perm[2 * k + i.index])] for i in gate[1]] pars = gate[0].params name = gate[0].name if name == "cx": circuit.cx(qs[0], qs[1]) elif name == "u1": circuit.u1(pars[0], qs[0]) elif name == "u2": circuit.u2(*pars[:2], qs[0]) elif name == "u3": circuit.u3(*pars[:3], qs[0]) elif name == "id": pass # do nothing else: raise Exception("Unexpected gate name: %s" % name) return circuit def time_random_transform(self, num_qubits, fusion_enable): circ = self.build_model_circuit_kak(num_qubits, num_qubits, 1) qobj = assemble(circ) result = self.backend.run(qobj, fusion_enable=fusion_enable).result() if result.status != 'COMPLETED': raise QiskitError("Simulation failed. Status: " + result.status)
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Quantum Fourier Transform benchmark suite""" # Write the benchmarking functions here. # See "Writing benchmarks" in the asv docs for more information. from qiskit import QiskitError from qiskit.compiler import transpile, assemble from qiskit.providers.aer import QasmSimulator from .tools import quantum_fourier_transform_circuit, \ mixed_unitary_noise_model, reset_noise_model, \ kraus_noise_model, no_noise class QuantumFourierTransformQasmSimulatorBenchSuite: """ Benchmarking times for Quantum Fourier Transform with various noise configurations: - ideal (no noise) - mixed state - reset - kraus and different simulator methods For each noise model, we want to test various configurations of number of qubits The methods defined in this class will be executed by ASV framework as many times as the combination of all parameters exist in `self.params`, for exmaple: self.params = ([1,2,3],[4,5,6]), will run all methdos 9 times: time_method(1,4) time_method(1,5) time_method(1,6) time_method(2,4) time_method(2,5) time_method(2,6) time_method(3,4) time_method(3,5) time_method(3,6) """ def __init__(self): self.timeout = 60 * 20 self.qft_circuits = [] self.backend = QasmSimulator() for num_qubits in (5, 10, 15, 20): circ = quantum_fourier_transform_circuit(num_qubits) circ = transpile(circ, basis_gates=['u1', 'u2', 'u3', 'cx'], optimization_level=0, seed_transpiler=1) qobj = assemble(circ, self.backend, shots=1) self.qft_circuits.append(qobj) self.param_names = ["Quantum Fourier Transform", "Noise Model", "Simulator Method"] # This will run every benchmark for one of the combinations we have: # bench(qft_circuits, None) => bench(qft_circuits, mixed()) => # bench(qft_circuits, reset) => bench(qft_circuits, kraus()) self.params = ( self.qft_circuits, [no_noise(), mixed_unitary_noise_model(), reset_noise_model(), kraus_noise_model()], ['statevector', 'density_matrix', 'stabilizer', 'extended_stabilizer', 'matrix_product_state']) def setup(self, qobj, noise_model_wrapper, simulator_method): """ Setup env before benchmarks start """ def time_quantum_fourier_transform(self, qobj, noise_model_wrapper, simulator_method): """ Benchmark QFT """ backend_options = { 'method': simulator_method, 'noise_model': noise_model_wrapper(), } result = self.backend.run( qobj, noise_model=noise_model_wrapper() ).result() if result.status != 'COMPLETED': raise QiskitError("Simulation failed. Status: " + result.status) def peakmem_quantum_fourier_transform(self, qobj, noise_model_wrapper, simulator_method): """ Benchmark QFT """ backend_options = { 'method': simulator_method, 'noise_model': noise_model_wrapper(), } result = self.backend.run( qobj, noise_model=noise_model_wrapper() ).result() if result.status != 'COMPLETED': raise QiskitError("Simulation failed. Status: " + result.status)
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Quantum Voluming benchmark suite""" # Write the benchmarking functions here. # See "Writing benchmarks" in the asv docs for more information. from qiskit import QiskitError from qiskit.compiler import transpile, assemble from qiskit.providers.aer import QasmSimulator from .tools import quantum_volume_circuit, mixed_unitary_noise_model, \ reset_noise_model, kraus_noise_model, no_noise class QuantumVolumeTimeSuite: """ Benchmarking times for Quantum Volume with various noise configurations - ideal (no noise) - mixed state - reset - kraus For each noise model, we want to test various configurations of number of qubits The methods defined in this class will be executed by ASV framework as many times as the combination of all parameters exist in `self.params`, for exmaple: self.params = ([1,2,3],[4,5,6]), will run all methdos 9 times: time_method(1,4) time_method(1,5) time_method(1,6) time_method(2,4) time_method(2,5) time_method(2,6) time_method(3,4) time_method(3,5) time_method(3,6) """ def __init__(self): self.timeout = 60 * 20 self.qv_circuits = [] self.backend = QasmSimulator() for num_qubits in (5, 10, 15): for depth in (10, ): # We want always the same seed, as we want always the same # circuits for the same value pairs of qubits and depth circ = quantum_volume_circuit(num_qubits, depth, seed=1) circ = transpile(circ, basis_gates=['u1', 'u2', 'u3', 'cx'], optimization_level=0, seed_transpiler=1) qobj = assemble(circ, self.backend, shots=1) self.qv_circuits.append(qobj) self.param_names = ["Quantum Volume", "Noise Model"] # This will run every benchmark for one of the combinations we have: # bench(qv_circuits, None) => bench(qv_circuits, mixed()) => # bench(qv_circuits, reset) => bench(qv_circuits, kraus()) self.params = (self.qv_circuits, [ no_noise(), mixed_unitary_noise_model(), reset_noise_model(), kraus_noise_model() ]) def setup(self, qobj, noise_model_wrapper): """ Setup enviornment before running the tests """ def time_quantum_volume(self, qobj, noise_model_wrapper): """ Benchmark for quantum volume """ result = self.backend.run( qobj, noise_model=noise_model_wrapper() ).result() if result.status != 'COMPLETED': raise QiskitError("Simulation failed. Status: " + result.status)
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object import numpy as np from qiskit import assemble from qiskit import transpile from qiskit import Aer import qiskit.ignis.verification.randomized_benchmarking as rb from .tools import kraus_noise_model, no_noise, mixed_unitary_noise_model, \ reset_noise_model def build_rb_circuit(nseeds=1, length_vector=None, rb_pattern=None, length_multiplier=1, seed_offset=0, align_cliffs=False, seed=None): """ Randomized Benchmarking sequences. """ if not seed: np.random.seed(10) else: np.random.seed(seed) rb_opts = {} rb_opts['nseeds'] = nseeds rb_opts['length_vector'] = length_vector rb_opts['rb_pattern'] = rb_pattern rb_opts['length_multiplier'] = length_multiplier rb_opts['seed_offset'] = seed_offset rb_opts['align_cliffs'] = align_cliffs # Generate the sequences try: rb_circs, _ = rb.randomized_benchmarking_seq(**rb_opts) except OSError: skip_msg = ('Skipping tests because ' 'tables are missing') raise NotImplementedError(skip_msg) all_circuits = [] for seq in rb_circs: all_circuits += seq return all_circuits class RandomizedBenchmarkingQasmSimBenchmark: # parameters for RB (1&2 qubits): params = ([[[0]], [[0, 1]], [[0, 2], [1]]], ['statevector', 'density_matrix', 'stabilizer', 'extended_stabilizer', 'matrix_product_state'], [no_noise(), mixed_unitary_noise_model(), reset_noise_model(), kraus_noise_model()]) param_names = ['rb_pattern', 'simulator_method', 'noise_model'] version = '0.2.0' timeout = 600 def setup(self, rb_pattern, _, __): length_vector = np.arange(1, 200, 4) nseeds = 1 self.seed = 10 self.circuits = build_rb_circuit(nseeds=nseeds, length_vector=length_vector, rb_pattern=rb_pattern, seed=self.seed) self.sim_backend = Aer.get_backend('qasm_simulator') trans_circ = transpile(self.circuits, backend=self.sim_backend, seed_transpiler=self.seed) self.qobj = assemble(trans_circ, backend=self.sim_backend) def time_run_rb_circuit(self, _, simulator_method, noise_model): backend_options = { 'method': simulator_method, 'noise_model': noise_model(), } job = self.sim_backend.run(self.qobj, **backend_options) job.result() def peakmem_run_rb_circuit(self, _, simulator_method, noise_model): backend_options = { 'method': simulator_method, 'noise_model': noise_model(), } job = self.sim_backend.run(self.qobj, **backend_options) job.result()
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Airspeed Velocity (ASV) benchmarks suite for simple 1-qubit/2-qubit gates """ from qiskit import QiskitError from qiskit.compiler import assemble from qiskit.providers.aer import QasmSimulator from .tools import mixed_unitary_noise_model, \ reset_noise_model, kraus_noise_model, no_noise, \ simple_cnot_circuit, simple_u3_circuit # Write the benchmarking functions here. # See "Writing benchmarks" in the asv docs for more information. class SimpleU3TimeSuite: """ Benchmark simple circuits with just one U3 gate The methods defined in this class will be executed by ASV framework as many times as the combination of all parameters exist in `self.params`, for exmaple: self.params = ([1,2,3],[4,5,6]), will run all methdos 9 times: time_method(1,4) time_method(1,5) time_method(1,6) time_method(2,4) time_method(2,5) time_method(2,6) time_method(3,4) time_method(3,5) time_method(3,6) For each noise model, we want to test various configurations of number of qubits """ def __init__(self): self.timeout = 60 * 20 self.backend = QasmSimulator() self.circuits = [] for i in 5, 10, 15: circuit = simple_u3_circuit(i) self.circuits.append(assemble(circuit, self.backend, shots=1)) self.param_names = [ "Simple u3 circuits", "Noise Model" ] self.params = (self.circuits, [ no_noise(), mixed_unitary_noise_model(), reset_noise_model(), kraus_noise_model() ]) def time_simple_u3(self, qobj, noise_model_wrapper): """ Benchmark for circuits with a simple u3 gate """ result = self.backend.run( qobj, noise_model=noise_model_wrapper() ).result() if result.status != 'COMPLETED': raise QiskitError("Simulation failed. Status: " + result.status) class SimpleCxTimeSuite: """ Benchmark simple circuits with just on CX gate For each noise model, we want to test various configurations of number of qubits """ def __init__(self): self.timeout = 60 * 20 self.backend = QasmSimulator() self.circuits = [] self.param_names = [ "Simple cnot circuits", "Noise Model" ] for i in 5, 10, 15: circuit = simple_cnot_circuit(i) self.circuits.append(assemble(circuit, self.backend, shots=1)) self.params = (self.circuits, [ no_noise(), mixed_unitary_noise_model(), reset_noise_model(), kraus_noise_model() ]) def time_simple_cx(self, qobj, noise_model_wrapper): """ Benchmark for circuits with a simple cx gate """ result = self.backend.run( qobj, noise_model=noise_model_wrapper() ).result() if result.status != 'COMPLETED': raise QiskitError("Simulation failed. Status: " + result.status)
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
from datetime import datetime import matplotlib.pyplot as plt from qiskit import QuantumCircuit, BasicAer, execute, IBMQ, transpile from qiskit.providers import BaseJob from qiskit.providers.ibmq import least_busy, IBMQJobManager from qiskit.providers.ibmq.managed import ManagedJobSet from qiskit.visualization import plot_histogram import constants from QCLG_lvl3.classical.bernstein_vazirani_classical import BersteinVaziraniClassical from QCLG_lvl3.classical.classical_xor import ClassicalXor from QCLG_lvl3.classical.random_binary import RandomBinary from QCLG_lvl3.quantum_algorithms.bernstein_vazirani import BernsteinVazirani from QCLG_lvl3.quantum_algorithms.deutsch_josza import DeutschJosza from credentials import account_details class Tools: @classmethod def calculate_elapsed_time(cls, first_step: datetime, last_step: datetime): difference = last_step - first_step return difference.total_seconds() @classmethod def run_on_simulator(cls, circuit: QuantumCircuit): # use local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1024 results = execute(circuit, backend=backend, shots=shots).result() answer = results.get_counts() max_value = 0 max_key = "" for key, value in answer.items(): if value > max_value: max_value = value max_key = key return max_key[::-1] @classmethod def run_on_real_device(cls, circuit: QuantumCircuit, least_busy_backend): from qiskit.tools.monitor import job_monitor shots = int(input("Number of shots (distinct executions to run this experiment: )")) job = execute(circuit, backend=least_busy_backend, shots=shots, optimization_level=3) job_monitor(job, interval=2) return job @classmethod def find_least_busy_backend_from_open(cls, n): if account_details.account_token_open is None: account_token = input("Insert your account token: ") else: account_token = account_details.account_token_open if IBMQ.active_account() is None: IBMQ.enable_account(account_token) provider = IBMQ.get_provider(hub='ibm-q') return least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n + 1) and not x.configuration().simulator and x.status().operational == True)) @classmethod def find_least_busy_backend_from_research(cls, n): if account_details.account_token_research is None \ or account_details.hub is None \ or account_details.group is None \ or account_details.project is None: account_token = input("Insert your account token: ") hub = input("Insert your hub: ") group = input("Insert your group: ") project = input("Insert your project: ") else: account_token = account_details.account_token_research hub = account_details.hub group = account_details.group project = account_details.project IBMQ.enable_account(account_token) provider = IBMQ.get_provider(hub=hub, group=group, project=project) print(provider) return least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n + 1) and not x.configuration().simulator and x.status().operational == True)) @classmethod def print_simul(cls, answer_of_simul, algorithm: str): print(constants.algorithms[int(algorithm)]) print("\nMeasurements: ", answer_of_simul) return @classmethod def print_real(cls, job: BaseJob, least_busy_backend, algorithm: str): results = job.result() answer = results.get_counts() print("\nTotal counts are:", answer) elapsed = results.time_taken print(f"The time it took for the experiment to complete after validation was {elapsed} seconds") plot_histogram(data=answer, title=f"{constants.algorithms[int(algorithm)]} on {least_busy_backend}") plt.show() return @classmethod def execute_classically(cls, algorithm): if algorithm == "0": return cls.execute_deutsch_josza_classically() elif algorithm == "1": return cls.execute_bernstein_vazirani_classically() @classmethod def execute_in_simulator(cls, algorithm): dj_circuit = None if algorithm == "0": bits = str(input("Enter a bit sequence for the quantum circuit:")) dj_circuit = DeutschJosza.deutsch_josza(bits, eval_mode=False) elif algorithm == "1": decimals = int(input("Give the upper limit of the random number: ")) random_binary = RandomBinary.generate_random_binary(decimals) dj_circuit = BernsteinVazirani.bernstein_vazirani(random_binary, eval_mode=False) return cls.run_on_simulator(dj_circuit) @classmethod def execute_in_real_device(cls, algorithm): if algorithm == "0": answer = cls.execute_dj_in_real_device() return answer elif algorithm == "1": decimals = int(input("Give the upper limit of the random number: ")) random_binary = RandomBinary.generate_random_binary(decimals) answer = cls.execute_bv_in_real_device(random_binary) return answer @classmethod def execute_dj_in_real_device(cls): bits = str(input("Enter a bit sequence for the quantum circuit:")) least_busy_backend = Tools.choose_from_provider(len(bits) + 1) dj_circuit = DeutschJosza.deutsch_josza(bits, eval_mode=False) answer_of_real = Tools.run_on_real_device(dj_circuit, least_busy_backend) print(f"least busy is {least_busy_backend}") return answer_of_real @classmethod def execute_bv_in_real_device(cls, random_binary: str): dj_circuit = BernsteinVazirani.bernstein_vazirani(random_binary, eval_mode=False) least_busy_backend = Tools.choose_from_provider(dj_circuit.qubits) answer_of_real = Tools.run_on_real_device(dj_circuit, least_busy_backend) print(f"least busy is {least_busy_backend}") return answer_of_real @classmethod def choose_from_provider(cls, size: int): least_busy_backend = None research = input("Do you want to run this experiment on the research backends? (Y/N)") while research != "Y" and research != "N": research = input("Do you want to run this experiment on the research backends? (Y/N)") if research == "N": least_busy_backend = Tools.find_least_busy_backend_from_open(size) elif research == "Y": least_busy_backend = Tools.find_least_busy_backend_from_research(size) return least_busy_backend @classmethod def execute_deutsch_josza_classically(cls): number_of_bits = int(input("Enter number of bits for a the classical solution:")) return ClassicalXor.execute_classical_xor(bits=number_of_bits) @classmethod def execute_bernstein_vazirani_classically(cls): decimals = int(input("Give the upper limit of the random number: ")) random_binary = RandomBinary.generate_random_binary(decimals) return BersteinVaziraniClassical.guess_number(random_binary) @classmethod def print_classical_answer(cls, classical_answer, algorithm): time_to_generate_worst_input = classical_answer[0] execution_time = classical_answer[1] bits = classical_answer[2] function_nature = classical_answer[3] print(f"Results of classical implementation for the {constants.algorithms[int(algorithm)]} Algorithm:") print(f"Function is {function_nature}") print(f"Time to generate worse input for {bits} bits took {time_to_generate_worst_input} seconds.") print(f"Determining if xor is balanced for {bits} bits took {execution_time} seconds.") print(classical_answer) @classmethod def execute_both(cls, algorithm): answer = [] if algorithm == "0": classical = cls.execute_deutsch_josza_classically() real = cls.execute_dj_in_real_device() answer.append(classical) answer.append(real) elif algorithm == " 1": classical = cls.execute_bernstein_vazirani_classically() real = cls.execute_bv_in_real_device(classical) answer.append(classical) answer.append(real) return answer # ################################################################################################################# # Evaluation methods @classmethod def prepare_dj(cls, bits: int): bit_sequence = "0" * bits dj_circuit = DeutschJosza.deutsch_josza(bit_sequence, eval_mode=True) return dj_circuit @classmethod def prepare_bv(cls, random_binary: str): bj_circuit = BernsteinVazirani.bernstein_vazirani(random_binary, eval_mode=True) return bj_circuit @classmethod def deutsch_josza_classical(cls, bits: int): return ClassicalXor.execute_classical_xor(bits=bits) @classmethod def bernstein_vazirani_classical(cls, bits: int): random_binary = RandomBinary.generate_random_binary_v2(bits) return BersteinVaziraniClassical.guess_number(random_binary) @classmethod def run_batch_job(cls, circuits: list, least_busy_backend) -> ManagedJobSet: transpiled_circuits = transpile(circuits, backend=least_busy_backend) # Use Job Manager to break the circuits into multiple jobs. job_manager = IBMQJobManager() job_set_eval = job_manager.run(transpiled_circuits, backend=least_busy_backend, name='eval', max_experiments_per_job=1) # max_experiments_per_job =1 very important to get # individual execution times return job_set_eval
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Shared functionality and helpers for the unit tests. """ from enum import Enum import inspect import logging import os import unittest from unittest.util import safe_repr from itertools import repeat from random import choice, sample from math import pi import numpy as np import fixtures from qiskit.quantum_info import Operator, Statevector from qiskit.quantum_info.operators.predicates import matrix_equal from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.providers.aer import __path__ as main_path from qiskit.test.base import FullQiskitTestCase class Path(Enum): """Helper with paths commonly used during the tests.""" MAIN = main_path[0] TEST = os.path.dirname(__file__) # Examples path: examples/ EXAMPLES = os.path.join(MAIN, '../examples') class QiskitAerTestCase(FullQiskitTestCase): """Helper class that contains common functionality.""" def setUp(self): super().setUp() self.useFixture(fixtures.Timeout(120, gentle=False)) @classmethod def setUpClass(cls): super().setUpClass() allow_DeprecationWarning_modules = [ "cvxpy", ] # for mod in allow_DeprecationWarning_modules: # warnings.filterwarnings("default", category=DeprecationWarning, module=mod) cls.moduleName = os.path.splitext(inspect.getfile(cls))[0] cls.log = logging.getLogger(cls.__name__) # Set logging to file and stdout if the LOG_LEVEL environment variable # is set. if os.getenv("LOG_LEVEL"): # Set up formatter. log_fmt = "{}.%(funcName)s:%(levelname)s:%(asctime)s:" " %(message)s".format( cls.__name__ ) formatter = logging.Formatter(log_fmt) # Set up the file handler. log_file_name = "%s.log" % cls.moduleName file_handler = logging.FileHandler(log_file_name) file_handler.setFormatter(formatter) cls.log.addHandler(file_handler) # Set the logging level from the environment variable, defaulting # to INFO if it is not a valid level. level = logging._nameToLevel.get(os.getenv("LOG_LEVEL"), logging.INFO) cls.log.setLevel(level) @staticmethod def _get_resource_path(filename, path=Path.TEST): """ Get the absolute path to a resource. Args: filename (string): filename or relative path to the resource. path (Path): path used as relative to the filename. Returns: str: the absolute path to the resource. """ return os.path.normpath(os.path.join(path.value, filename)) # def assertNoLogs(self, logger=None, level=None): # """ # Context manager to test that no message is sent to the specified # logger and level (the opposite of TestCase.assertLogs()). # """ # # pylint: disable=invalid-name # return _AssertNoLogsContext(self, logger, level) def assertSuccess(self, result): """Assert that simulation executed without errors""" success = getattr(result, 'success', False) msg = result.status if not success: for i, res in enumerate(getattr(result, 'results', [])): if res.status != 'DONE': msg += ', (Circuit {}) {}'.format(i, res.status) self.assertTrue(success, msg=msg) @staticmethod def gate_circuit(gate_cls, num_params=0, rng=None): """Construct a circuit from a gate class.""" if num_params: if rng is None: rng = np.random.default_rng() params = rng.random(num_params) gate = gate_cls(*params, label=None) else: gate = gate_cls() circ = QuantumCircuit(gate.num_qubits) circ.append(gate, range(gate.num_qubits)) return circ @staticmethod def check_position(obj, items, precision=15): """Return position of numeric object in a list.""" for pos, item in enumerate(items): # Try numeric difference first try: delta = round(np.linalg.norm(np.array(obj) - np.array(item)), precision) if delta == 0: return pos # If objects aren't numeric try direct equality comparison except: try: if obj == item: return pos except: return None return None @staticmethod def remove_if_found(obj, items, precision=15): """If obj is in list of items, remove first instance""" pos = QiskitAerTestCase.check_position(obj, items) if pos is not None: items.pop(pos) def compare_statevector(self, result, circuits, targets, ignore_phase=True, atol=1e-8, rtol=1e-5): """Compare final statevectors to targets.""" for pos, test_case in enumerate(zip(circuits, targets)): circuit, target = test_case target = Statevector(target) output = Statevector(result.get_statevector(circuit)) test_msg = "Circuit ({}/{}):".format(pos + 1, len(circuits)) with self.subTest(msg=test_msg): msg = " {} != {}".format(output, target) delta = matrix_equal(output.data, target.data, ignore_phase=True, atol=atol, rtol=rtol) self.assertTrue(delta, msg=msg) def compare_unitary(self, result, circuits, targets, ignore_phase=True, atol=1e-8, rtol=1e-5): """Compare final unitary matrices to targets.""" for pos, test_case in enumerate(zip(circuits, targets)): circuit, target = test_case target = Operator(target) output = Operator(result.get_unitary(circuit)) test_msg = "Circuit ({}/{}):".format(pos + 1, len(circuits)) with self.subTest(msg=test_msg): msg = test_msg + " {} != {}".format(output.data, target.data) delta = matrix_equal(output.data, target.data, ignore_phase=True, atol=atol, rtol=rtol) self.assertTrue(delta, msg=msg) def compare_counts(self, result, circuits, targets, hex_counts=True, delta=0): """Compare counts dictionary to targets.""" for pos, test_case in enumerate(zip(circuits, targets)): circuit, target = test_case if hex_counts: # Don't use get_counts method which converts hex output = result.data(circuit)["counts"] else: # Use get counts method which converts hex output = result.get_counts(circuit) test_msg = "Circuit ({}/{}):".format(pos + 1, len(circuits)) with self.subTest(msg=test_msg): msg = test_msg + " {} != {}".format(output, target) self.assertDictAlmostEqual( output, target, delta=delta, msg=msg) def compare_memory(self, result, circuits, targets, hex_counts=True): """Compare memory list to target.""" for pos, test_case in enumerate(zip(circuits, targets)): circuit, target = test_case self.assertIn("memory", result.data(circuit)) if hex_counts: # Don't use get_counts method which converts hex output = result.data(circuit)["memory"] else: # Use get counts method which converts hex output = result.get_memory(circuit) test_msg = "Circuit ({}/{}):".format(pos + 1, len(circuits)) with self.subTest(msg=test_msg): msg = " {} != {}".format(output, target) self.assertEqual(output, target, msg=msg) def compare_result_metadata(self, result, circuits, key, targets): """Compare result metadata key value.""" if not isinstance(targets, (list, tuple)): targets = len(circuits) * [targets] for pos, test_case in enumerate(zip(circuits, targets)): circuit, target = test_case value = None metadata = getattr(result.results[0], 'metadata') if metadata: value = metadata.get(key) test_msg = "Circuit ({}/{}):".format(pos + 1, len(circuits)) with self.subTest(msg=test_msg): msg = " metadata {} value {} != {}".format(key, value, target) self.assertEqual(value, target, msg=msg) def assertDictAlmostEqual(self, dict1, dict2, delta=None, msg=None, places=None, default_value=0): """ Assert two dictionaries with numeric values are almost equal. Fail if the two dictionaries are unequal as determined by comparing that the difference between values with the same key are not greater than delta (default 1e-8), or that difference rounded to the given number of decimal places is not zero. If a key in one dictionary is not in the other the default_value keyword argument will be used for the missing value (default 0). If the two objects compare equal then they will automatically compare almost equal. Args: dict1 (dict): a dictionary. dict2 (dict): a dictionary. delta (number): threshold for comparison (defaults to 1e-8). msg (str): return a custom message on failure. places (int): number of decimal places for comparison. default_value (number): default value for missing keys. Raises: TypeError: raises TestCase failureException if the test fails. """ if dict1 == dict2: # Shortcut return if delta is not None and places is not None: raise TypeError("specify delta or places not both") if places is not None: success = True standard_msg = '' # check value for keys in target keys1 = set(dict1.keys()) for key in keys1: val1 = dict1.get(key, default_value) val2 = dict2.get(key, default_value) if round(abs(val1 - val2), places) != 0: success = False standard_msg += '(%s: %s != %s), ' % (safe_repr(key), safe_repr(val1), safe_repr(val2)) # check values for keys in counts, not in target keys2 = set(dict2.keys()) - keys1 for key in keys2: val1 = dict1.get(key, default_value) val2 = dict2.get(key, default_value) if round(abs(val1 - val2), places) != 0: success = False standard_msg += '(%s: %s != %s), ' % (safe_repr(key), safe_repr(val1), safe_repr(val2)) if success is True: return standard_msg = standard_msg[:-2] + ' within %s places' % places else: if delta is None: delta = 1e-8 # default delta value success = True standard_msg = '' # check value for keys in target keys1 = set(dict1.keys()) for key in keys1: val1 = dict1.get(key, default_value) val2 = dict2.get(key, default_value) if abs(val1 - val2) > delta: success = False standard_msg += '(%s: %s != %s), ' % (safe_repr(key), safe_repr(val1), safe_repr(val2)) # check values for keys in counts, not in target keys2 = set(dict2.keys()) - keys1 for key in keys2: val1 = dict1.get(key, default_value) val2 = dict2.get(key, default_value) if abs(val1 - val2) > delta: success = False standard_msg += '(%s: %s != %s), ' % (safe_repr(key), safe_repr(val1), safe_repr(val2)) if success is True: return standard_msg = standard_msg[:-2] + ' within %s delta' % delta msg = self._formatMessage(msg, standard_msg) raise self.failureException(msg) # class _AssertNoLogsContext(unittest.case._AssertLogsContext): # """A context manager used to implement TestCase.assertNoLogs().""" # # # pylint: disable=inconsistent-return-statements # def __exit__(self, exc_type, exc_value, tb): # """ # This is a modified version of TestCase._AssertLogsContext.__exit__(...) # """ # self.logger.handlers = self.old_handlers # self.logger.propagate = self.old_propagate # self.logger.setLevel(self.old_level) # if exc_type is not None: # # let unexpected exceptions pass through # return False # # if self.watcher.records: # msg = 'logs of level {} or higher triggered on {}:\n'.format( # logging.getLevelName(self.level), self.logger.name) # for record in self.watcher.records: # msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname, # record.lineno, # record.getMessage()) # # self._raiseFailure(msg) def _is_ci_fork_pull_request(): """ Check if the tests are being run in a CI environment and if it is a pull request. Returns: bool: True if the tests are executed inside a CI tool, and the changes are not against the "master" branch. """ if os.getenv('TRAVIS'): # Using Travis CI. if os.getenv('TRAVIS_PULL_REQUEST_BRANCH'): return True elif os.getenv('APPVEYOR'): # Using AppVeyor CI. if os.getenv('APPVEYOR_PULL_REQUEST_NUMBER'): return True return False def generate_random_circuit(n_qubits, n_gates, gate_types): """ Generation of a random circuit has a history in Qiskit. Terra used to have a file _random_circuit_generator.py, but it is not there anymore. This file was located in folder `test`, hence accessible only to Qiskit developers and not to users. Currently, as far as I know, each test that requires random circuits has its own implementation of a random circuit generator. This includes tests in qiskit-addon-sympy and test_visualization in terra. Aqua had an issue of writing a random circuit generator, which was closed with the justification that it is moved to ignes. """ qr = QuantumRegister(n_qubits, 'qr') cr = ClassicalRegister(n_qubits, 'cr') circuit = QuantumCircuit(qr, cr) for _ in repeat(None, n_gates): # Choose the next gate op_name = choice(gate_types) if op_name == 'id': op_name = 'iden' operation = eval('QuantumCircuit.' + op_name) # Check if operation is one of u1, u2, u3 if op_name[0] == 'u' and op_name[1].isdigit(): # Number of angles n_angles = int(op_name[1]) # Number of qubits manipulated by the gate n_params = 1 else: n_angles = 0 if op_name == 'measure': n_params = 1 else: n_params = len(inspect.signature(operation).parameters) - 1 # Choose qubits qubit_indices = sample(range(n_qubits), n_params) qubits = [qr[i] for i in qubit_indices] # Choose angles angles = np.random.rand(n_angles) * pi # Measurement operation # In all measure operations, the classical register is not random, # but has the same index as the quantum register if op_name == 'measure': classical_regs = [cr[i] for i in qubit_indices] else: classical_regs = [] # Add operation to the circuit operation(circuit, *angles, *qubits, *classical_regs) return circuit
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Decorator for using with Qiskit unit tests.""" import functools import os import sys import unittest from .utils import Path from .http_recorder import http_recorder from .testing_options import get_test_options def is_aer_provider_available(): """Check if the C++ simulator can be instantiated. Returns: bool: True if simulator executable is available """ # TODO: HACK FROM THE DEPTHS OF DESPAIR AS AER DOES NOT WORK ON MAC if sys.platform == 'darwin': return False try: import qiskit.providers.aer # pylint: disable=unused-import except ImportError: return False return True def requires_aer_provider(test_item): """Decorator that skips test if qiskit aer provider is not available Args: test_item (callable): function or class to be decorated. Returns: callable: the decorated function. """ reason = 'Aer provider not found, skipping test' return unittest.skipIf(not is_aer_provider_available(), reason)(test_item) def slow_test(func): """Decorator that signals that the test takes minutes to run. Args: func (callable): test function to be decorated. Returns: callable: the decorated function. """ @functools.wraps(func) def _wrapper(*args, **kwargs): skip_slow = not TEST_OPTIONS['run_slow'] if skip_slow: raise unittest.SkipTest('Skipping slow tests') return func(*args, **kwargs) return _wrapper def _get_credentials(test_object, test_options): """Finds the credentials for a specific test and options. Args: test_object (QiskitTestCase): The test object asking for credentials test_options (dict): Options after QISKIT_TESTS was parsed by get_test_options. Returns: Credentials: set of credentials Raises: ImportError: if the Exception: when the credential could not be set and they are needed for that set of options """ try: from qiskit.providers.ibmq.credentials import (Credentials, discover_credentials) except ImportError: raise ImportError('qiskit-ibmq-provider could not be found, and is ' 'required for mocking or executing online tests.') dummy_credentials = Credentials( 'dummyapiusersloginWithTokenid01', 'https://quantumexperience.ng.bluemix.net/api') if test_options['mock_online']: return dummy_credentials if os.getenv('USE_ALTERNATE_ENV_CREDENTIALS', ''): # Special case: instead of using the standard credentials mechanism, # load them from different environment variables. This assumes they # will always be in place, as is used by the Travis setup. return Credentials(os.getenv('IBMQ_TOKEN'), os.getenv('IBMQ_URL')) else: # Attempt to read the standard credentials. discovered_credentials = discover_credentials() if discovered_credentials: # Decide which credentials to use for testing. if len(discovered_credentials) > 1: try: # Attempt to use QE credentials. return discovered_credentials[dummy_credentials.unique_id()] except KeyError: pass # Use the first available credentials. return list(discovered_credentials.values())[0] # No user credentials were found. if test_options['rec']: raise Exception('Could not locate valid credentials. You need them for ' 'recording tests against the remote API.') test_object.log.warning('No user credentials were detected. ' 'Running with mocked data.') test_options['mock_online'] = True return dummy_credentials def requires_qe_access(func): """Decorator that signals that the test uses the online API: It involves: * determines if the test should be skipped by checking environment variables. * if the `USE_ALTERNATE_ENV_CREDENTIALS` environment variable is set, it reads the credentials from an alternative set of environment variables. * if the test is not skipped, it reads `qe_token` and `qe_url` from `Qconfig.py`, environment variables or qiskitrc. * if the test is not skipped, it appends `qe_token` and `qe_url` as arguments to the test function. Args: func (callable): test function to be decorated. Returns: callable: the decorated function. """ @functools.wraps(func) def _wrapper(self, *args, **kwargs): if TEST_OPTIONS['skip_online']: raise unittest.SkipTest('Skipping online tests') credentials = _get_credentials(self, TEST_OPTIONS) self.using_ibmq_credentials = credentials.is_ibmq() kwargs.update({'qe_token': credentials.token, 'qe_url': credentials.url}) decorated_func = func if TEST_OPTIONS['rec'] or TEST_OPTIONS['mock_online']: # For recording or for replaying existing cassettes, the test # should be decorated with @use_cassette. vcr_mode = 'new_episodes' if TEST_OPTIONS['rec'] else 'none' decorated_func = http_recorder( vcr_mode, Path.CASSETTES.value).use_cassette()(decorated_func) return decorated_func(self, *args, **kwargs) return _wrapper TEST_OPTIONS = get_test_options()
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Integration Tests for Parameterized Qobj execution, testing qasm_simulator, statevector_simulator, and expectation value snapshots. """ import unittest import numpy as np from test.terra import common from qiskit import assemble from test.terra.reference.ref_snapshot_expval import ( snapshot_expval_circuits, snapshot_expval_counts, snapshot_expval_labels, snapshot_expval_pre_meas_values, snapshot_expval_circuit_parameterized, snapshot_expval_final_statevecs) from qiskit.providers.qrack import QasmSimulator class TestParameterizedQobj(common.QiskitAerTestCase): """Parameterized Qobj extension tests""" BACKEND_OPTS = { "seed_simulator": 2113 } @staticmethod def expval_snapshots(data, labels): """Format snapshots as nested dicts""" # Check snapshot entry exists in data output = {} for label in labels: snaps = data.get("snapshots", {}).get("expectation_value", {}).get(label, []) # Convert list into dict inner = {} for snap_dict in snaps: inner[snap_dict['memory']] = snap_dict['value'] output[label] = inner return output @staticmethod def parameterized_qobj(backend, shots=1000, measure=True, snapshot=False): """Return ParameterizedQobj for settings.""" single_shot = shots == 1 pcirc1, param1 = snapshot_expval_circuit_parameterized(single_shot=single_shot, measure=measure, snapshot=snapshot) circuits2to4 = snapshot_expval_circuits(pauli=True, skip_measure=(not measure), single_shot=single_shot) pcirc2, param2 = snapshot_expval_circuit_parameterized(single_shot=single_shot, measure=measure, snapshot=snapshot) circuits = [pcirc1] + circuits2to4 + [pcirc2] params = [param1, [], [], [], param2] qobj = assemble(circuits, backend=backend, shots=shots, parameterizations=params) return qobj #def test_parameterized_qobj_qasm_snapshot_expval(self): # """Test parameterized qobj with Expectation Value snapshot and qasm simulator.""" # shots = 1000 # labels = snapshot_expval_labels() * 3 # counts_targets = snapshot_expval_counts(shots) * 3 # value_targets = snapshot_expval_pre_meas_values() * 3 # # backend = QasmSimulator() # qobj = self.parameterized_qobj(backend=backend, # shots=1000, # measure=True, # snapshot=True) # self.assertIn('parameterizations', qobj.to_dict()['config']) # job = backend.run(qobj, self.BACKEND_OPTS) # result = job.result() # success = getattr(result, 'success', False) # num_circs = len(result.to_dict()['results']) # self.assertTrue(success) # self.compare_counts(result, # range(num_circs), # counts_targets, # delta=0.1 * shots) # # Check snapshots # for j in range(num_circs): # data = result.data(j) # all_snapshots = self.expval_snapshots(data, labels) # for label in labels: # snaps = all_snapshots.get(label, {}) # self.assertTrue(len(snaps), 1) # for memory, value in snaps.items(): # target = value_targets[j].get(label, # {}).get(memory, {}) # self.assertAlmostEqual(value, target, delta=1e-7) #def test_parameterized_qobj_statevector(self): # """Test parameterized qobj with Expectation Value snapshot and qasm simulator.""" # statevec_targets = snapshot_expval_final_statevecs() * 3 # # backend = StatevectorSimulator() # qobj = self.parameterized_qobj(backend=backend, # measure=False, # snapshot=False) # self.assertIn('parameterizations', qobj.to_dict()['config']) # job = backend.run(qobj, self.BACKEND_OPTS) # result = job.result() # success = getattr(result, 'success', False) # num_circs = len(result.to_dict()['results']) # self.assertTrue(success) # # for j in range(num_circs): # statevector = result.get_statevector(j) # np.testing.assert_array_almost_equal(statevector, statevec_targets[j].data, decimal=7) if __name__ == '__main__': unittest.main()
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ QasmSimulator Integration Tests """ from test.terra.reference import ref_algorithms from qiskit import execute from qiskit.providers.qrack import QasmSimulator class QasmAlgorithmTests: """QasmSimulator algorithm tests in the default basis""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} # --------------------------------------------------------------------- # Test algorithms # --------------------------------------------------------------------- def test_grovers_default_basis_gates(self): """Test grovers circuits compiling to backend default basis_gates.""" shots = 4000 circuits = ref_algorithms.grovers_circuit( final_measure=True, allow_sampling=True) targets = ref_algorithms.grovers_counts(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) def test_teleport_default_basis_gates(self): """Test teleport circuits compiling to backend default basis_gates.""" shots = 4000 circuits = ref_algorithms.teleport_circuit() targets = ref_algorithms.teleport_counts(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) class QasmAlgorithmTestsWaltzBasis: """QasmSimulator algorithm tests in the Waltz u1,u2,u3,cx basis""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} # --------------------------------------------------------------------- # Test algorithms # --------------------------------------------------------------------- def test_grovers_waltz_basis_gates(self): """Test grovers gate circuits compiling to u1,u2,u3,cx""" shots = 4000 circuits = ref_algorithms.grovers_circuit( final_measure=True, allow_sampling=True) targets = ref_algorithms.grovers_counts(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) def test_teleport_waltz_basis_gates(self): """Test teleport gate circuits compiling to u1,u2,u3,cx""" shots = 4000 circuits = ref_algorithms.teleport_circuit() targets = ref_algorithms.teleport_counts(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) class QasmAlgorithmTestsMinimalBasis: """QasmSimulator algorithm tests in the minimal U,CX basis""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} # --------------------------------------------------------------------- # Test algorithms # --------------------------------------------------------------------- def test_grovers_minimal_basis_gates(self): """Test grovers circuits compiling to u3,cx""" shots = 4000 circuits = ref_algorithms.grovers_circuit( final_measure=True, allow_sampling=True) targets = ref_algorithms.grovers_counts(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) def test_teleport_minimal_basis_gates(self): """Test teleport gate circuits compiling to u3,cx""" shots = 4000 circuits = ref_algorithms.teleport_circuit() targets = ref_algorithms.teleport_counts(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots)
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ QasmSimulator Integration Tests """ from test.terra.utils.mock import FakeFailureQasmSimulator, FakeSuccessQasmSimulator from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.compiler import transpile, assemble from qiskit.providers.aer import AerError class QasmBasicsTests: """QasmSimulator basic tests.""" def test_simulation_succeed(self): """Test the we properly manage simulation failures.""" mocked_backend = FakeSuccessQasmSimulator(time_alive=0) qr = QuantumRegister(1) cr = ClassicalRegister(1) succeed_circuit = QuantumCircuit(qr, cr) quantum_circuit = transpile(succeed_circuit, mocked_backend) qobj = assemble(quantum_circuit) result = mocked_backend.run(qobj).result() self.assertSuccess(result) def test_simulation_failed(self): """Test the we properly manage simulation failures.""" mocked_backend = FakeFailureQasmSimulator(time_alive=0) qr = QuantumRegister(1) cr = ClassicalRegister(1) failed_circuit = QuantumCircuit(qr, cr) quantum_circuit = transpile(failed_circuit, mocked_backend) qobj = assemble(quantum_circuit) job = mocked_backend.run(qobj) self.assertRaises(AerError, job.result)
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ QasmSimulator Integration Tests """ from test.terra.reference import ref_1q_clifford from test.terra.reference import ref_2q_clifford from qiskit import execute from qiskit.providers.qrack import QasmSimulator class QasmCliffordTests: """QasmSimulator Clifford gate tests in default basis.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} # --------------------------------------------------------------------- # Test h-gate # --------------------------------------------------------------------- def test_h_gate_deterministic_default_basis_gates(self): """Test h-gate circuits compiling to backend default basis_gates.""" shots = 100 circuits = ref_1q_clifford.h_gate_circuits_deterministic( final_measure=True) targets = ref_1q_clifford.h_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) def test_h_gate_nondeterministic_default_basis_gates(self): """Test h-gate circuits compiling to backend default basis_gates.""" shots = 4000 circuits = ref_1q_clifford.h_gate_circuits_nondeterministic( final_measure=True) targets = ref_1q_clifford.h_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test x-gate # --------------------------------------------------------------------- def test_x_gate_deterministic_default_basis_gates(self): """Test x-gate circuits compiling to backend default basis_gates.""" shots = 100 circuits = ref_1q_clifford.x_gate_circuits_deterministic( final_measure=True) targets = ref_1q_clifford.x_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) # --------------------------------------------------------------------- # Test z-gate # --------------------------------------------------------------------- def test_z_gate_deterministic_default_basis_gates(self): """Test z-gate circuits compiling to backend default basis_gates.""" shots = 100 circuits = ref_1q_clifford.z_gate_circuits_deterministic( final_measure=True) targets = ref_1q_clifford.z_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) # --------------------------------------------------------------------- # Test y-gate # --------------------------------------------------------------------- def test_y_gate_deterministic_default_basis_gates(self): """Test y-gate circuits compiling to backend default basis_gates.""" shots = 100 circuits = ref_1q_clifford.y_gate_circuits_deterministic( final_measure=True) targets = ref_1q_clifford.y_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) # --------------------------------------------------------------------- # Test s-gate # --------------------------------------------------------------------- def test_s_gate_deterministic_default_basis_gates(self): """Test s-gate circuits compiling to backend default basis_gates.""" shots = 100 circuits = ref_1q_clifford.s_gate_circuits_deterministic( final_measure=True) targets = ref_1q_clifford.s_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_s_gate_nondeterministic_default_basis_gates(self): """Test s-gate circuits compiling to backend default basis_gates.""" shots = 4000 circuits = ref_1q_clifford.s_gate_circuits_nondeterministic( final_measure=True) targets = ref_1q_clifford.s_gate_counts_nondeterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test sdg-gate # --------------------------------------------------------------------- def test_sdg_gate_deterministic_default_basis_gates(self): """Test sdg-gate circuits compiling to backend default basis_gates.""" shots = 100 circuits = ref_1q_clifford.sdg_gate_circuits_deterministic( final_measure=True) targets = ref_1q_clifford.sdg_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_sdg_gate_nondeterministic_default_basis_gates(self): shots = 4000 """Test sdg-gate circuits compiling to backend default basis_gates.""" circuits = ref_1q_clifford.sdg_gate_circuits_nondeterministic( final_measure=True) targets = ref_1q_clifford.sdg_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test cx-gate # --------------------------------------------------------------------- def test_cx_gate_deterministic_default_basis_gates(self): """Test cx-gate circuits compiling to backend default basis_gates.""" shots = 100 circuits = ref_2q_clifford.cx_gate_circuits_deterministic( final_measure=True) targets = ref_2q_clifford.cx_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_cx_gate_nondeterministic_default_basis_gates(self): """Test cx-gate circuits compiling to backend default basis_gates.""" shots = 4000 circuits = ref_2q_clifford.cx_gate_circuits_nondeterministic( final_measure=True) targets = ref_2q_clifford.cx_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test cz-gate # --------------------------------------------------------------------- def test_cz_gate_deterministic_default_basis_gates(self): """Test cz-gate circuits compiling to backend default basis_gates.""" shots = 100 circuits = ref_2q_clifford.cz_gate_circuits_deterministic( final_measure=True) targets = ref_2q_clifford.cz_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_cz_gate_nondeterministic_default_basis_gates(self): """Test cz-gate circuits compiling to backend default basis_gates.""" shots = 4000 circuits = ref_2q_clifford.cz_gate_circuits_nondeterministic( final_measure=True) targets = ref_2q_clifford.cz_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test swap-gate # --------------------------------------------------------------------- def test_swap_gate_deterministic_default_basis_gates(self): """Test swap-gate circuits compiling to backend default basis_gates.""" shots = 100 circuits = ref_2q_clifford.swap_gate_circuits_deterministic( final_measure=True) targets = ref_2q_clifford.swap_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_swap_gate_nondeterministic_default_basis_gates(self): """Test swap-gate circuits compiling to backend default basis_gates.""" shots = 4000 circuits = ref_2q_clifford.swap_gate_circuits_nondeterministic( final_measure=True) targets = ref_2q_clifford.swap_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) class QasmCliffordTestsWaltzBasis: """QasmSimulator Clifford gate tests in Waltz u1,u2,u3,cx basis.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} # --------------------------------------------------------------------- # Test h-gate # --------------------------------------------------------------------- def test_h_gate_deterministic_waltz_basis_gates(self): """Test h-gate gate circuits compiling to u1,u2,u3,cx""" shots = 100 circuits = ref_1q_clifford.h_gate_circuits_deterministic( final_measure=True) targets = ref_1q_clifford.h_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) def test_h_gate_nondeterministic_waltz_basis_gates(self): """Test h-gate gate circuits compiling to u1,u2,u3,cx""" shots = 4000 circuits = ref_1q_clifford.h_gate_circuits_nondeterministic( final_measure=True) targets = ref_1q_clifford.h_gate_counts_nondeterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test x-gate # --------------------------------------------------------------------- def test_x_gate_deterministic_waltz_basis_gates(self): """Test x-gate gate circuits compiling to u1,u2,u3,cx""" shots = 100 circuits = ref_1q_clifford.x_gate_circuits_deterministic( final_measure=True) targets = ref_1q_clifford.x_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) # --------------------------------------------------------------------- # Test z-gate # --------------------------------------------------------------------- def test_z_gate_deterministic_waltz_basis_gates(self): """Test z-gate gate circuits compiling to u1,u2,u3,cx""" shots = 100 circuits = ref_1q_clifford.z_gate_circuits_deterministic( final_measure=True) targets = ref_1q_clifford.z_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_z_gate_deterministic_minimal_basis_gates(self): """Test z-gate gate circuits compiling to u3,cx""" shots = 100 circuits = ref_1q_clifford.z_gate_circuits_deterministic( final_measure=True) targets = ref_1q_clifford.z_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) # --------------------------------------------------------------------- # Test y-gate # --------------------------------------------------------------------- def test_y_gate_deterministic_default_basis_gates(self): """Test y-gate circuits compiling to backend default basis_gates.""" shots = 100 circuits = ref_1q_clifford.y_gate_circuits_deterministic( final_measure=True) targets = ref_1q_clifford.y_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_y_gate_deterministic_waltz_basis_gates(self): shots = 100 """Test y-gate gate circuits compiling to u1,u2,u3,cx""" circuits = ref_1q_clifford.y_gate_circuits_deterministic( final_measure=True) targets = ref_1q_clifford.y_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) # --------------------------------------------------------------------- # Test s-gate # --------------------------------------------------------------------- def test_s_gate_deterministic_waltz_basis_gates(self): """Test s-gate gate circuits compiling to u1,u2,u3,cx""" shots = 100 circuits = ref_1q_clifford.s_gate_circuits_deterministic( final_measure=True) targets = ref_1q_clifford.s_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_s_gate_nondeterministic_waltz_basis_gates(self): """Test s-gate gate circuits compiling to u1,u2,u3,cx""" shots = 4000 circuits = ref_1q_clifford.s_gate_circuits_nondeterministic( final_measure=True) targets = ref_1q_clifford.s_gate_counts_nondeterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test sdg-gate # --------------------------------------------------------------------- def test_sdg_gate_deterministic_waltz_basis_gates(self): """Test sdg-gate gate circuits compiling to u1,u2,u3,cx""" shots = 100 circuits = ref_1q_clifford.sdg_gate_circuits_deterministic( final_measure=True) targets = ref_1q_clifford.sdg_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx']) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_sdg_gate_nondeterministic_waltz_basis_gates(self): """Test sdg-gate gate circuits compiling to u1,u2,u3,cx""" shots = 4000 circuits = ref_1q_clifford.sdg_gate_circuits_nondeterministic( final_measure=True) targets = ref_1q_clifford.sdg_gate_counts_nondeterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test cx-gate # --------------------------------------------------------------------- def test_cx_gate_deterministic_waltz_basis_gates(self): shots = 100 """Test cx-gate gate circuits compiling to u1,u2,u3,cx""" circuits = ref_2q_clifford.cx_gate_circuits_deterministic( final_measure=True) targets = ref_2q_clifford.cx_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_cx_gate_nondeterministic_waltz_basis_gates(self): """Test cx-gate gate circuits compiling to u1,u2,u3,cx""" shots = 4000 circuits = ref_2q_clifford.cx_gate_circuits_nondeterministic( final_measure=True) targets = ref_2q_clifford.cx_gate_counts_nondeterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx']) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test cz-gate # --------------------------------------------------------------------- def test_cz_gate_deterministic_waltz_basis_gates(self): """Test cz-gate gate circuits compiling to u1,u2,u3,cx""" shots = 100 circuits = ref_2q_clifford.cz_gate_circuits_deterministic( final_measure=True) targets = ref_2q_clifford.cz_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx']) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_cz_gate_nondeterministic_waltz_basis_gates(self): """Test cz-gate gate circuits compiling to u1,u2,u3,cx""" shots = 4000 circuits = ref_2q_clifford.cz_gate_circuits_nondeterministic( final_measure=True) targets = ref_2q_clifford.cz_gate_counts_nondeterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test swap-gate # --------------------------------------------------------------------- def test_swap_gate_deterministic_waltz_basis_gates(self): """Test swap-gate gate circuits compiling to u1,u2,u3,cx""" shots = 100 circuits = ref_2q_clifford.swap_gate_circuits_deterministic( final_measure=True) targets = ref_2q_clifford.swap_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_swap_gate_nondeterministic_waltz_basis_gates(self): """Test swap-gate gate circuits compiling to u1,u2,u3,cx""" shots = 4000 circuits = ref_2q_clifford.swap_gate_circuits_nondeterministic( final_measure=True) targets = ref_2q_clifford.swap_gate_counts_nondeterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) class QasmCliffordTestsMinimalBasis: """QasmSimulator Clifford gate tests in minimam U,CX basis.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} # --------------------------------------------------------------------- # Test h-gate # --------------------------------------------------------------------- def test_h_gate_deterministic_minimal_basis_gates(self): """Test h-gate gate circuits compiling to u3,cx""" shots = 100 circuits = ref_1q_clifford.h_gate_circuits_deterministic( final_measure=True) targets = ref_1q_clifford.h_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) def test_h_gate_nondeterministic_minimal_basis_gates(self): """Test h-gate gate circuits compiling to u3,cx""" shots = 4000 circuits = ref_1q_clifford.h_gate_circuits_nondeterministic( final_measure=True) targets = ref_1q_clifford.h_gate_counts_nondeterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test x-gate # --------------------------------------------------------------------- def test_x_gate_deterministic_minimal_basis_gates(self): """Test x-gate gate circuits compiling to u3,cx""" shots = 100 circuits = ref_1q_clifford.x_gate_circuits_deterministic( final_measure=True) targets = ref_1q_clifford.x_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx']) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) # --------------------------------------------------------------------- # Test z-gate # --------------------------------------------------------------------- def test_z_gate_deterministic_minimal_basis_gates(self): """Test z-gate gate circuits compiling to u3,cx""" shots = 100 circuits = ref_1q_clifford.z_gate_circuits_deterministic( final_measure=True) targets = ref_1q_clifford.z_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) # --------------------------------------------------------------------- # Test y-gate # --------------------------------------------------------------------- def test_y_gate_deterministic_minimal_basis_gates(self): """Test y-gate gate circuits compiling to u3,cx""" shots = 100 circuits = ref_1q_clifford.y_gate_circuits_deterministic( final_measure=True) targets = ref_1q_clifford.y_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) # --------------------------------------------------------------------- # Test s-gate # --------------------------------------------------------------------- def test_s_gate_deterministic_minimal_basis_gates(self): """Test s-gate gate circuits compiling to u3,cx""" shots = 100 circuits = ref_1q_clifford.s_gate_circuits_deterministic( final_measure=True) targets = ref_1q_clifford.s_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_s_gate_nondeterministic_minimal_basis_gates(self): """Test s-gate gate circuits compiling to u3,cx""" shots = 4000 circuits = ref_1q_clifford.s_gate_circuits_nondeterministic( final_measure=True) targets = ref_1q_clifford.s_gate_counts_nondeterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test sdg-gate # --------------------------------------------------------------------- def test_sdg_gate_deterministic_minimal_basis_gates(self): """Test sdg-gate gate circuits compiling to u3,cx""" shots = 100 circuits = ref_1q_clifford.sdg_gate_circuits_deterministic( final_measure=True) targets = ref_1q_clifford.sdg_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_sdg_gate_nondeterministic_minimal_basis_gates(self): """Test sdg-gate gate circuits compiling to u3,cx""" shots = 4000 circuits = ref_1q_clifford.sdg_gate_circuits_nondeterministic( final_measure=True) targets = ref_1q_clifford.sdg_gate_counts_nondeterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test cx-gate # --------------------------------------------------------------------- def test_cx_gate_deterministic_minimal_basis_gates(self): """Test cx-gate gate circuits compiling to u3,cx""" shots = 100 circuits = ref_2q_clifford.cx_gate_circuits_deterministic( final_measure=True) targets = ref_2q_clifford.cx_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_cx_gate_nondeterministic_minimal_basis_gates(self): """Test cx-gate gate circuits compiling to u3,cx""" shots = 4000 circuits = ref_2q_clifford.cx_gate_circuits_nondeterministic( final_measure=True) targets = ref_2q_clifford.cx_gate_counts_nondeterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test cz-gate # --------------------------------------------------------------------- def test_cz_gate_deterministic_minimal_basis_gates(self): """Test cz-gate gate circuits compiling to u3,cx""" shots = 100 circuits = ref_2q_clifford.cz_gate_circuits_deterministic( final_measure=True) targets = ref_2q_clifford.cz_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_cz_gate_nondeterministic_minimal_basis_gates(self): """Test cz-gate gate circuits compiling to u3,cx""" shots = 4000 circuits = ref_2q_clifford.cz_gate_circuits_nondeterministic( final_measure=True) targets = ref_2q_clifford.cz_gate_counts_nondeterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test swap-gate # --------------------------------------------------------------------- def test_swap_gate_deterministic_minimal_basis_gates(self): """Test swap-gate gate circuits compiling to u3,cx""" shots = 100 circuits = ref_2q_clifford.swap_gate_circuits_deterministic( final_measure=True) targets = ref_2q_clifford.swap_gate_counts_deterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_swap_gate_nondeterministic_minimal_basis_gates(self): """Test swap-gate gate circuits compiling to u3,cx""" shots = 4000 circuits = ref_2q_clifford.swap_gate_circuits_nondeterministic( final_measure=True) targets = ref_2q_clifford.swap_gate_counts_nondeterministic(shots) job = execute( circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots)
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ QasmSimulator Integration Tests """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit.library import QFT, QuantumVolume from qiskit.compiler import assemble, transpile from qiskit.providers.qrack import QasmSimulator from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors import ReadoutError, depolarizing_error class QasmDelayMeasureTests: """QasmSimulator delay measure sampling optimization tests.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} def delay_measure_circuit(self): """Test circuit that allows measure delay optimization""" qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.x(0) circuit.measure(0, 0) circuit.barrier([0, 1]) circuit.x(1) circuit.measure(0, 1) return circuit def test_delay_measure_enable(self): """Test measure sampling works with delay measure optimization""" # Circuit that allows delay measure circuit = self.delay_measure_circuit() shots = 100 qobj = assemble([circuit], self.SIMULATOR, shots=shots, seed_simulator=1) # Delay measure default backend_options = self.BACKEND_OPTS.copy() backend_options['optimize_ideal_threshold'] = 0 result = self.SIMULATOR.run( qobj, **backend_options).result() self.assertSuccess(result) #metadata = result.results[0].metadata #self.assertTrue(metadata.get('measure_sampling')) # Delay measure enabled backend_options = self.BACKEND_OPTS.copy() backend_options['delay_measure_enable'] = True backend_options['optimize_ideal_threshold'] = 0 result = self.SIMULATOR.run( qobj, **backend_options).result() self.assertSuccess(result) #metadata = result.results[0].metadata #self.assertTrue(metadata.get('measure_sampling')) # Delay measure disabled backend_options = self.BACKEND_OPTS.copy() backend_options['delay_measure_enable'] = False backend_options['optimize_ideal_threshold'] = 0 result = self.SIMULATOR.run( qobj, **backend_options).result() self.assertSuccess(result) #metadata = result.results[0].metadata #self.assertFalse(metadata.get('measure_sampling')) def test_delay_measure_verbose(self): """Test delay measure with verbose option""" circuit = self.delay_measure_circuit() shots = 100 qobj = assemble([circuit], self.SIMULATOR, shots=shots, seed_simulator=1) # Delay measure verbose enabled backend_options = self.BACKEND_OPTS.copy() backend_options['delay_measure_enable'] = True backend_options['delay_measure_verbose'] = True backend_options['optimize_ideal_threshold'] = 0 result = self.SIMULATOR.run( qobj, **backend_options).result() self.assertSuccess(result) #metadata = result.results[0].metadata #self.assertIn('delay_measure_verbose', metadata) # Delay measure verbose disabled backend_options = self.BACKEND_OPTS.copy() backend_options['delay_measure_enable'] = True backend_options['delay_measure_verbose'] = False backend_options['optimize_ideal_threshold'] = 0 result = self.SIMULATOR.run( qobj, **backend_options).result() self.assertSuccess(result) #metadata = result.results[0].metadata #self.assertNotIn('delay_measure_verbose', metadata) # Delay measure verbose default backend_options = self.BACKEND_OPTS.copy() backend_options['delay_measure_enable'] = True backend_options['optimize_ideal_threshold'] = 1 backend_options['optimize_noise_threshold'] = 1 result = self.SIMULATOR.run( qobj, **backend_options).result() self.assertSuccess(result) #metadata = result.results[0].metadata #self.assertNotIn('delay_measure_verbose', metadata)
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ QasmSimulator Integration Tests """ # pylint: disable=no-member import copy from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit.library import QuantumVolume, QFT from qiskit.compiler import assemble, transpile from qiskit.providers.qrack import QasmSimulator from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors import (ReadoutError, depolarizing_error, amplitude_damping_error) class QasmFusionTests: """QasmSimulator fusion tests.""" SIMULATOR = QasmSimulator() def create_statevector_circuit(self): """ Creates a simple circuit for running in the statevector """ qr = QuantumRegister(5) cr = ClassicalRegister(5) circuit = QuantumCircuit(qr, cr) circuit.u(0.1, 0.1, 0.1, qr[0]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.u(0.1, 0.1, 0.1, qr[0]) circuit.barrier(qr) circuit.measure(qr, cr) return circuit def noise_model_depol(self): """ Creates a new noise model for testing purposes """ readout_error = [0.01, 0.1] params = {'u': (1, 0.001), 'cx': (2, 0.02)} noise = NoiseModel() readout = [[1.0 - readout_error[0], readout_error[0]], [readout_error[1], 1.0 - readout_error[1]]] noise.add_all_qubit_readout_error(ReadoutError(readout)) for gate, (num_qubits, gate_error) in params.items(): noise.add_all_qubit_quantum_error( depolarizing_error(gate_error, num_qubits), gate) return noise def noise_model_kraus(self): """ Creates a new noise model for testing purposes """ readout_error = [0.01, 0.1] params = {'u': (1, 0.001), 'cx': (2, 0.02)} noise = NoiseModel() readout = [[1.0 - readout_error[0], readout_error[0]], [readout_error[1], 1.0 - readout_error[1]]] noise.add_all_qubit_readout_error(ReadoutError(readout)) for gate, (num_qubits, gate_error) in params.items(): noise.add_all_qubit_quantum_error( amplitude_damping_error(gate_error, num_qubits), gate) return noise def fusion_options(self, enabled=None, threshold=None, verbose=None): """Return default backend_options dict.""" backend_options = self.BACKEND_OPTS.copy() if enabled is not None: backend_options['fusion_enable'] = enabled if verbose is not None: backend_options['fusion_verbose'] = verbose if threshold is not None: backend_options['fusion_threshold'] = threshold return backend_options def fusion_metadata(self, result): """Return fusion metadata dict""" metadata = result.results[0].metadata return metadata.get('fusion', {}) def test_fusion_theshold(self): """Test fusion threhsold""" shots = 100 threshold = 6 backend_options = self.fusion_options(enabled=True, threshold=threshold) with self.subTest(msg='below fusion threshold'): circuit = transpile(QFT(threshold - 1), self.SIMULATOR, basis_gates=['u1', 'u2', 'u', 'cx', 'cz'], optimization_level=0) circuit.measure_all() qobj = assemble(circuit, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( qobj, **backend_options).result() self.assertSuccess(result) #meta = self.fusion_metadata(result) #self.assertTrue(meta.get('enabled')) #self.assertFalse(meta.get('applied')) with self.subTest(msg='at fusion threshold'): circuit = transpile(QFT(threshold), self.SIMULATOR, basis_gates=['u1', 'u2', 'u', 'cx', 'cz'], optimization_level=0) circuit.measure_all() qobj = assemble(circuit, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( qobj, **backend_options).result() self.assertSuccess(result) #meta = self.fusion_metadata(result) #self.assertTrue(meta.get('enabled')) #self.assertFalse(meta.get('applied')) with self.subTest(msg='above fusion threshold'): circuit = transpile(QFT(threshold + 1), self.SIMULATOR, basis_gates=['u1', 'u2', 'u', 'cx', 'cz'], optimization_level=0) circuit.measure_all() qobj = assemble(circuit, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run( qobj, **backend_options).result() self.assertSuccess(result) #meta = self.fusion_metadata(result) #self.assertTrue(meta.get('enabled')) #self.assertTrue(meta.get('applied')) def test_fusion_verbose(self): """Test Fusion with verbose option""" circuit = self.create_statevector_circuit() shots = 100 qobj = assemble(transpile([circuit], self.SIMULATOR, optimization_level=0), shots=shots) with self.subTest(msg='verbose enabled'): backend_options = self.fusion_options(enabled=True, verbose=True, threshold=1) result = self.SIMULATOR.run( qobj, **backend_options).result() # Assert fusion applied succesfully self.assertSuccess(result) #meta = self.fusion_metadata(result) #self.assertTrue(meta.get('applied', False)) # Assert verbose meta data in output #self.assertIn('input_ops', meta) #self.assertIn('output_ops', meta) with self.subTest(msg='verbose disabled'): backend_options = self.fusion_options(enabled=True, verbose=False, threshold=1) result = self.SIMULATOR.run( qobj, **backend_options).result() # Assert fusion applied succesfully self.assertSuccess(result) #meta = self.fusion_metadata(result) #self.assertTrue(meta.get('applied', False)) # Assert verbose meta data not in output #self.assertNotIn('input_ops', meta) #self.assertNotIn('output_ops', meta) with self.subTest(msg='verbose default'): backend_options = self.fusion_options(enabled=True, threshold=1) result = self.SIMULATOR.run( qobj, **backend_options).result() # Assert fusion applied succesfully self.assertSuccess(result) #meta = self.fusion_metadata(result) #self.assertTrue(meta.get('applied', False)) # Assert verbose meta data not in output #self.assertNotIn('input_ops', meta) #self.assertNotIn('output_ops', meta) #def test_kraus_noise_fusion(self): # """Test Fusion with kraus noise model option""" # shots = 100 # circuit = self.create_statevector_circuit() # noise_model = self.noise_model_kraus() # circuit = transpile([circuit], # backend=self.SIMULATOR, # basis_gates=noise_model.basis_gates, # optimization_level=0) # qobj = assemble([circuit], # self.SIMULATOR, # shots=shots, # seed_simulator=1) # backend_options = self.fusion_options(enabled=True, threshold=1) # result = self.SIMULATOR.run(qobj, # noise_model=noise_model, # **backend_options).result() # method = result.results[0].metadata.get('method') # #meta = self.fusion_metadata(result) # if method in ['density_matrix', 'density_matrix_thrust', 'density_matrix_gpu']: # target_method = 'superop' # else: # target_method = 'kraus' # self.assertSuccess(result) # #self.assertTrue(meta.get('applied', False), # # msg='fusion should have been applied.') # #self.assertEqual(meta.get('method', None), target_method) #def test_non_kraus_noise_fusion(self): # """Test Fusion with non-kraus noise model option""" # shots = 100 # circuit = self.create_statevector_circuit() # noise_model = self.noise_model_depol() # circuit = transpile([circuit], # backend=self.SIMULATOR, # basis_gates=noise_model.basis_gates, # optimization_level=0) # qobj = assemble([circuit], # self.SIMULATOR, # shots=shots, # seed_simulator=1) # backend_options = self.fusion_options(enabled=True, threshold=1) # result = self.SIMULATOR.run(qobj, # noise_model=noise_model, # **backend_options).result() # #meta = self.fusion_metadata(result) # method = result.results[0].metadata.get('method') # if method in ['density_matrix', 'density_matrix_thrust', 'density_matrix_gpu']: # target_method = 'superop' # else: # target_method = 'unitary' # self.assertSuccess(result) # #self.assertTrue(meta.get('applied', False), # # msg='fusion should have been applied.') # #self.assertEqual(meta.get('method', None), target_method) def test_control_fusion(self): """Test Fusion enable/disable option""" shots = 100 circuit = transpile(self.create_statevector_circuit(), backend=self.SIMULATOR, optimization_level=0) qobj = assemble([circuit], self.SIMULATOR, shots=shots, seed_simulator=1) with self.subTest(msg='fusion enabled'): backend_options = self.fusion_options(enabled=True, threshold=1) result = self.SIMULATOR.run( copy.deepcopy(qobj), **backend_options).result() #meta = self.fusion_metadata(result) self.assertSuccess(result) #self.assertTrue(meta.get('enabled')) #self.assertTrue(meta.get('applied', False)) with self.subTest(msg='fusion disabled'): backend_options = backend_options = self.fusion_options(enabled=False, threshold=1) result = self.SIMULATOR.run( copy.deepcopy(qobj), **backend_options).result() #meta = self.fusion_metadata(result) self.assertSuccess(result) #self.assertFalse(meta.get('enabled')) with self.subTest(msg='fusion default'): backend_options = self.fusion_options() result = self.SIMULATOR.run( copy.deepcopy(qobj), **backend_options).result() #meta = self.fusion_metadata(result) self.assertSuccess(result) #self.assertTrue(meta.get('enabled')) #self.assertFalse(meta.get('applied', False), msg=meta) def test_fusion_operations(self): """Test Fusion enable/disable option""" shots = 100 num_qubits = 8 qr = QuantumRegister(num_qubits) cr = ClassicalRegister(num_qubits) circuit = QuantumCircuit(qr, cr) circuit.h(qr) circuit.barrier(qr) circuit.u(0.1, 0.1, 0.1, qr[0]) circuit.barrier(qr) circuit.u(0.1, 0.1, 0.1, qr[1]) circuit.barrier(qr) circuit.cx(qr[1], qr[0]) circuit.barrier(qr) circuit.u(0.1, 0.1, 0.1, qr[0]) circuit.barrier(qr) circuit.u(0.1, 0.1, 0.1, qr[1]) circuit.barrier(qr) circuit.u(0.1, 0.1, 0.1, qr[3]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.cx(qr[2], qr[3]) circuit.barrier(qr) circuit.u(0.1, 0.1, 0.1, qr[3]) circuit.barrier(qr) circuit.u(0.1, 0.1, 0.1, qr[3]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.cx(qr[2], qr[3]) circuit.barrier(qr) circuit.u(0.1, 0.1, 0.1, qr[3]) circuit.barrier(qr) circuit.u(0.1, 0.1, 0.1, qr[3]) circuit.barrier(qr) circuit.measure(qr, cr) circuit = transpile(circuit, backend=self.SIMULATOR, optimization_level=0) qobj = assemble([circuit], self.SIMULATOR, shots=shots, seed_simulator=1) backend_options = self.fusion_options(enabled=False, threshold=1) result_disabled = self.SIMULATOR.run( qobj, **backend_options).result() #meta_disabled = self.fusion_metadata(result_disabled) backend_options = self.fusion_options(enabled=True, threshold=1) result_enabled = self.SIMULATOR.run( qobj, **backend_options).result() #meta_enabled = self.fusion_metadata(result_enabled) #self.assertTrue(getattr(result_disabled, 'success', 'False')) #self.assertTrue(getattr(result_enabled, 'success', 'False')) #self.assertFalse(meta_disabled.get('enabled')) #self.assertTrue(meta_enabled.get('enabled')) #self.assertTrue(meta_enabled.get('applied')) #self.assertDictAlmostEqual(result_enabled.get_counts(circuit), # result_disabled.get_counts(circuit), # delta=0.0, # msg="fusion for qft was failed") def test_fusion_qv(self): """Test Fusion with quantum volume""" shots = 100 num_qubits = 6 depth = 2 circuit = transpile(QuantumVolume(num_qubits, depth, seed=0), backend=self.SIMULATOR, optimization_level=0) circuit.measure_all() qobj_disabled = assemble([circuit], self.SIMULATOR, shots=shots, **self.fusion_options(enabled=False, threshold=1, verbose=True)) result_disabled = self.SIMULATOR.run(qobj_disabled).result() #meta_disabled = self.fusion_metadata(result_disabled) qobj_enabled = assemble([circuit], self.SIMULATOR, shots=shots, **self.fusion_options(enabled=True, threshold=1, verbose=True)) result_enabled = self.SIMULATOR.run(qobj_enabled).result() #meta_enabled = self.fusion_metadata(result_enabled) #self.assertTrue(getattr(result_disabled, 'success', 'False')) #self.assertTrue(getattr(result_enabled, 'success', 'False')) #self.assertFalse(meta_disabled.get('applied', False)) #self.assertTrue(meta_enabled.get('applied', False)) #self.assertDictAlmostEqual(result_enabled.get_counts(circuit), # result_disabled.get_counts(circuit), # delta=0.0, # msg="fusion for qft was failed") def test_fusion_qft(self): """Test Fusion with qft""" shots = 100 num_qubits = 8 circuit = transpile(QFT(num_qubits), backend=self.SIMULATOR, basis_gates=['u1', 'u2', 'u', 'cx', 'cz'], optimization_level=0) circuit.measure_all() qobj = assemble([circuit], self.SIMULATOR, shots=shots, seed_simulator=1) backend_options = self.fusion_options(enabled=False, threshold=1) result_disabled = self.SIMULATOR.run( qobj, **backend_options).result() #meta_disabled = self.fusion_metadata(result_disabled) backend_options = self.fusion_options(enabled=True, threshold=1) result_enabled = self.SIMULATOR.run( qobj, **backend_options).result() #meta_enabled = self.fusion_metadata(result_enabled) #self.assertTrue(getattr(result_disabled, 'success', 'False')) #self.assertTrue(getattr(result_enabled, 'success', 'False')) #self.assertFalse(meta_disabled.get('enabled')) #self.assertTrue(meta_enabled.get('enabled')) #self.assertTrue(meta_enabled.get('applied')) #self.assertDictAlmostEqual(result_enabled.get_counts(circuit), # result_disabled.get_counts(circuit), # delta=0.0, # msg="fusion for qft was failed")
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ QasmSimulator Integration Tests """ from test.terra.reference import ref_multiplexer from qiskit import execute from qiskit.providers.qrack import QasmSimulator class QasmMultiplexerTests: """QasmSimulator multiplexer gate tests in default basis.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} # --------------------------------------------------------------------- # Test multiplexer-cx-gate # --------------------------------------------------------------------- def test_multiplexer_cx_gate_deterministic(self): """Test multiplxer cx-gate circuits compiling to backend default basis_gates.""" shots = 100 circuits = ref_multiplexer.multiplexer_cx_gate_circuits_deterministic( final_measure=True) targets = ref_multiplexer.multiplexer_cx_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_multiplexer_cx_gate_nondeterministic(self): """Test multiplexer cx-gate circuits compiling to backend default basis_gates.""" shots = 4000 circuits = ref_multiplexer.multiplexer_cx_gate_circuits_nondeterministic( final_measure=True) targets = ref_multiplexer.multiplexer_cx_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test multiplexer-gate # --------------------------------------------------------------------- def test_multiplexer_cxx_gate_deterministic(self): """Test multiplexer-gate gate circuits """ shots = 100 circuits = ref_multiplexer.multiplexer_ccx_gate_circuits_deterministic( final_measure=True) targets = ref_multiplexer.multiplexer_ccx_gate_counts_deterministic( shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_multiplexer_cxx_gate_nondeterministic(self): """Test multiplexer ccx-gate gate circuits """ shots = 4000 circuits = ref_multiplexer.multiplexer_ccx_gate_circuits_nondeterministic( final_measure=True) targets = ref_multiplexer.multiplexer_ccx_gate_counts_nondeterministic( shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots)
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ QasmSimulator Integration Tests """ from test.terra.reference import ref_non_clifford from qiskit import execute from qiskit.providers.qrack import QasmSimulator class QasmNonCliffordTestsTGate: """QasmSimulator T gate tests in default basis.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} # --------------------------------------------------------------------- # Test t-gate # --------------------------------------------------------------------- def test_t_gate_deterministic_default_basis_gates(self): """Test t-gate circuits compiling to backend default basis_gates.""" shots = 100 circuits = ref_non_clifford.t_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.t_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_t_gate_nondeterministic_default_basis_gates(self): """Test t-gate circuits compiling to backend default basis_gates.""" shots = 4000 circuits = ref_non_clifford.t_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.t_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test tdg-gate # --------------------------------------------------------------------- def test_tdg_gate_deterministic_default_basis_gates(self): """Test tdg-gate circuits compiling to backend default basis_gates.""" shots = 100 circuits = ref_non_clifford.tdg_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.tdg_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_tdg_gate_nondeterministic_default_basis_gates(self): """Test tdg-gate circuits compiling to backend default basis_gates.""" shots = 4000 circuits = ref_non_clifford.tdg_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.tdg_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) class QasmNonCliffordTestsCCXGate: """QasmSimulator CCX gate tests in default basis.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} # --------------------------------------------------------------------- # Test ccx-gate # --------------------------------------------------------------------- def test_ccx_gate_deterministic_default_basis_gates(self): """Test ccx-gate circuits compiling to backend default basis_gates.""" shots = 100 circuits = ref_non_clifford.ccx_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.ccx_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_ccx_gate_nondeterministic_default_basis_gates(self): """Test ccx-gate circuits compiling to backend default basis_gates.""" shots = 4000 circuits = ref_non_clifford.ccx_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.ccx_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) class QasmNonCliffordTestsCGates: """QasmSimulator CSwap gate tests in default basis.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} # --------------------------------------------------------------------- # Test cswap-gate (Fredkin) # --------------------------------------------------------------------- def test_cswap_gate_deterministic_default_basis_gates(self): shots = 100 circuits = ref_non_clifford.cswap_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.cswap_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_cswap_gate_nondeterministic_default_basis_gates(self): shots = 4000 circuits = ref_non_clifford.cswap_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.cswap_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test cu1 gate # --------------------------------------------------------------------- def test_cu1_gate_nondeterministic_default_basis_gates(self): """Test cu1-gate gate circuits compiling to default basis.""" shots = 4000 circuits = ref_non_clifford.cu1_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.cu1_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test cu3 gate # --------------------------------------------------------------------- def test_cu3_gate_deterministic_default_basis_gates(self): """Test cu3-gate gate circuits compiling to default basis.""" shots = 100 circuits = ref_non_clifford.cu3_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.cu3_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) class QasmNonCliffordTestsWaltzBasis: """QasmSimulator non-Clifford gate tests in minimal u1,u2,u3,cx basis.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} # --------------------------------------------------------------------- # Test t-gate # --------------------------------------------------------------------- def test_t_gate_deterministic_waltz_basis_gates(self): """Test t-gate gate circuits compiling to u1,u2,u3,cx""" shots = 100 circuits = ref_non_clifford.t_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.t_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_t_gate_nondeterministic_waltz_basis_gates(self): """Test t-gate gate circuits compiling to u1,u2,u3,cx""" shots = 4000 circuits = ref_non_clifford.t_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.t_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test tdg-gate # --------------------------------------------------------------------- def test_tdg_gate_deterministic_waltz_basis_gates(self): """Test tdg-gate gate circuits compiling to u1,u2,u3,cx""" shots = 100 circuits = ref_non_clifford.tdg_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.tdg_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_tdg_gate_nondeterministic_waltz_basis_gates(self): """Test tdg-gate gate circuits compiling to u1,u2,u3,cx""" shots = 4000 circuits = ref_non_clifford.tdg_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.tdg_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test ccx-gate # --------------------------------------------------------------------- def test_ccx_gate_deterministic_waltz_basis_gates(self): """Test ccx-gate gate circuits compiling to u1,u2,u3,cx""" shots = 100 circuits = ref_non_clifford.ccx_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.ccx_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_ccx_gate_nondeterministic_waltz_basis_gates(self): """Test ccx-gate gate circuits compiling to u1,u2,u3,cx""" shots = 4000 circuits = ref_non_clifford.ccx_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.ccx_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test cswap-gate (Fredkin) # --------------------------------------------------------------------- def test_cswap_gate_deterministic_waltz_basis_gates(self): """Test cswap-gate gate circuits compiling to u1,u2,u3,cx""" shots = 100 circuits = ref_non_clifford.cswap_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.cswap_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_cswap_gate_nondeterministic_waltz_basis_gates(self): """Test cswap-gate gate circuits compiling to u1,u2,u3,cx""" shots = 4000 circuits = ref_non_clifford.cswap_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.cswap_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test cu1 gate # --------------------------------------------------------------------- def test_cu1_gate_nondeterministic_waltz_basis_gates(self): """Test cu1-gate gate circuits compiling to u1,u2,u3,cx""" shots = 4000 circuits = ref_non_clifford.cu1_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.cu1_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test cu3 gate # --------------------------------------------------------------------- def test_cu3_gate_deterministic_waltz_basis_gates(self): """Test cu3-gate gate circuits compiling to u1,u2,u3,cx.""" shots = 100 circuits = ref_non_clifford.cu3_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.cu3_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) class QasmNonCliffordTestsMinimalBasis: """QasmSimulator non-Clifford gate tests in minimal U,CX basis.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} # --------------------------------------------------------------------- # Test t-gate # --------------------------------------------------------------------- def test_t_gate_deterministic_minimal_basis_gates(self): """Test t-gate gate circuits compiling to u3,cx""" shots = 100 circuits = ref_non_clifford.t_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.t_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx']) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_t_gate_nondeterministic_minimal_basis_gates(self): """Test t-gate gate circuits compiling to u3,cx""" shots = 4000 circuits = ref_non_clifford.t_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.t_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test tdg-gate # --------------------------------------------------------------------- def test_tdg_gate_deterministic_minimal_basis_gates(self): """Test tdg-gate gate circuits compiling to u3,cx""" shots = 100 circuits = ref_non_clifford.tdg_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.tdg_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_tdg_gate_nondeterministic_minimal_basis_gates(self): """Test tdg-gate gate circuits compiling to u3,cx""" shots = 4000 circuits = ref_non_clifford.tdg_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.tdg_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test ccx-gate # --------------------------------------------------------------------- def test_ccx_gate_deterministic_minimal_basis_gates(self): """Test ccx-gate gate circuits compiling to u3,cx""" shots = 100 circuits = ref_non_clifford.ccx_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.ccx_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_ccx_gate_nondeterministic_minimal_basis_gates(self): """Test ccx-gate gate circuits compiling to u3,cx""" shots = 4000 circuits = ref_non_clifford.ccx_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.ccx_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.1 * shots) # --------------------------------------------------------------------- # Test cu1 gate # --------------------------------------------------------------------- def test_cu1_gate_nondeterministic_minimal_basis_gates(self): """Test cu1-gate gate circuits compiling to u3,cx""" shots = 4000 circuits = ref_non_clifford.cu1_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.cu1_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.1 * shots) # --------------------------------------------------------------------- # Test cswap-gate (Fredkin) # --------------------------------------------------------------------- def test_cswap_gate_deterministic_minimal_basis_gates(self): """Test cswap-gate gate circuits compiling to u3,cx""" shots = 100 circuits = ref_non_clifford.cswap_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.cswap_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_cswap_gate_nondeterministic_minimal_basis_gates(self): """Test cswap-gate gate circuits compiling to u3,cx""" shots = 4000 circuits = ref_non_clifford.cswap_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.cswap_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.1 * shots) # --------------------------------------------------------------------- # Test cu3 gate # --------------------------------------------------------------------- def test_cu3_gate_deterministic_default_basis_gates(self): """Test cu3-gate gate circuits compiling to u3, cx.""" shots = 100 circuits = ref_non_clifford.cu3_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.cu3_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0)
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ QasmSimulator Integration Tests for circuit library standard gates """ from ddt import ddt, unpack, data from numpy.random import default_rng from qiskit import execute from qiskit.quantum_info import Statevector, state_fidelity from qiskit.providers.qrack import QasmSimulator # from qiskit.providers.aer.extensions import * from qiskit.circuit.library.standard_gates import ( CXGate, CYGate, CZGate, DCXGate, HGate, IGate, SGate, SXGate, SXdgGate, SdgGate, SwapGate, XGate, YGate, ZGate, TGate, TdgGate, iSwapGate, C3XGate, C4XGate, CCXGate, CHGate, CSXGate, CSwapGate, CPhaseGate, CRXGate, CRYGate, CRZGate, CU1Gate, CU3Gate, CUGate, PhaseGate, RC3XGate, RCCXGate, RGate, RXGate, RXXGate, RYGate, RYYGate, RZGate, RZXGate, RZZGate, U1Gate, U2Gate, U3Gate, UGate) GATES = [ # Clifford Gates (CXGate, 0), (CYGate, 0), (CZGate, 0), (DCXGate, 0), (HGate, 0), (IGate, 0), (SGate, 0), (SXGate, 0), (SXdgGate, 0), (SdgGate, 0), (SwapGate, 0), (XGate, 0), (YGate, 0), (ZGate, 0), (TGate, 0), # Non-Clifford Gates (TdgGate, 0), (iSwapGate, 0), (C3XGate, 0), (C4XGate, 0), (CCXGate, 0), (CHGate, 0), (CSXGate, 0), (CSwapGate, 0), # Parameterized Gates (CPhaseGate, 1), (CRXGate, 1), (CRYGate, 1), (CRZGate, 1), (CU1Gate, 1), (CU3Gate, 3), (CUGate, 4), (PhaseGate, 1), (RC3XGate, 0), (RCCXGate, 0), (RGate, 2), (RXGate, 1), (RXXGate, 1), (RYGate, 1), (RYYGate, 1), (RZGate, 1), (RZXGate, 1), (RZZGate, 1), (U1Gate, 1), (U2Gate, 2), (U3Gate, 3), (UGate, 3) ] @ddt class QasmStandardGateStatevectorTests: """QasmSimulator standard gate library tests.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} SEED = 8181 RNG = default_rng(seed=SEED) @data(*GATES) @unpack def test_gate_statevector(self, gate_cls, num_params): """Test standard gate simulation test.""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'matrix_product_state' ] circuit = self.gate_circuit(gate_cls, num_params=num_params, rng=self.RNG) target = Statevector.from_instruction(circuit) # Add snapshot and execute #circuit.snapshot_statevector('final') backend_options = self.BACKEND_OPTS method = backend_options.pop('method', 'automatic') backend = self.SIMULATOR backend.set_options(method=method) result = execute(circuit, backend, shots=1, **backend_options).result() # Check results success = getattr(result, 'success', False) msg = '{}, method = {}'.format(gate_cls.__name__, method) if method not in SUPPORTED_METHODS: self.assertFalse(success) else: self.assertTrue(success, msg=msg) self.assertSuccess(result) #snapshots = result.data(0).get("snapshots", {}).get("statevector", {}) #value = snapshots.get('final', [None])[0] #fidelity = state_fidelity(target, value) #self.assertGreater(fidelity, 0.99999, msg=msg) @ddt class QasmStandardGateDensityMatrixTests: """QasmSimulator standard gate library tests.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} SEED = 9997 RNG = default_rng(seed=SEED) @data(*GATES) @unpack def test_gate_density_matrix(self, gate_cls, num_params): """Test standard gate simulation test.""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'density_matrix', 'density_matrix_gpu', 'density_matrix_thrust' ] circuit = self.gate_circuit(gate_cls, num_params=num_params, rng=self.RNG) target = Statevector.from_instruction(circuit) # Add snapshot and execute #circuit.snapshot_density_matrix('final') backend_options = self.BACKEND_OPTS method = backend_options.pop('method', 'automatic') backend = self.SIMULATOR backend.set_options(method=method) result = execute(circuit, backend, shots=1, **backend_options).result() # Check results success = getattr(result, 'success', False) msg = '{}, method = {}'.format(gate_cls.__name__, method) if method not in SUPPORTED_METHODS: self.assertFalse(success) else: self.assertTrue(success, msg=msg) self.assertSuccess(result) #snapshots = result.data(0).get("snapshots", # {}).get("density_matrix", {}) #value = snapshots.get('final', [{'value': None}])[0]['value'] #fidelity = state_fidelity(target, value) #self.assertGreater(fidelity, 0.99999, msg=msg)
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ QasmSimulator Integration Tests """ import multiprocessing import psutil from qiskit import execute, QuantumCircuit from qiskit.circuit.library import QuantumVolume from qiskit.providers.qrack import QasmSimulator from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors.standard_errors import pauli_error from test.terra.decorators import requires_omp, requires_multiprocessing # pylint: disable=no-member class QasmThreadManagementTests: """QasmSimulator thread tests.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} def backend_options_parallel(self, total_threads=None, state_threads=None, shot_threads=None, exp_threads=None): """Backend options with thread manangement.""" opts = self.BACKEND_OPTS.copy() if total_threads: opts['max_parallel_threads'] = total_threads else: opts['max_parallel_threads'] = 0 if shot_threads: opts['max_parallel_shots'] = shot_threads if state_threads: opts['max_parallel_state_update'] = state_threads if exp_threads: opts['max_parallel_experiments'] = exp_threads return opts def dummy_noise_model(self): """Return dummy noise model for dummy circuit""" noise_model = NoiseModel() error = pauli_error([('X', 0.25), ('I', 0.75)]) noise_model.add_all_qubit_quantum_error(error, 'x') return noise_model def dummy_circuit(self, num_qubits): """Dummy circuit for testing thread settings""" circ = QuantumCircuit(num_qubits, num_qubits) circ.x(range(num_qubits)) circ.measure(range(num_qubits), range(num_qubits)) return circ def measure_in_middle_circuit(self, num_qubits): """Dummy circuit for testing thread settings""" circ = QuantumCircuit(num_qubits, num_qubits) circ.measure(range(num_qubits), range(num_qubits)) circ.x(range(num_qubits)) circ.measure(range(num_qubits), range(num_qubits)) return circ def threads_used(self, result): """Return a list of threads used for each execution""" exp_threads = getattr(result, 'metadata', {}).get('parallel_experiments', 1) threads = [] for exp_result in getattr(result, 'results', []): exp_meta = getattr(exp_result, 'metadata', {}) shot_threads = exp_meta.get('parallel_shots', 1) state_threads = exp_meta.get('parallel_state_update', 1) threads.append({ 'experiments': exp_threads, 'shots': shot_threads, 'state_update': state_threads, 'total': exp_threads * shot_threads * state_threads }) return threads def test_max_memory_settings(self): """test max memory configuration""" # 4-qubit quantum circuit shots = 100 circuit = QuantumVolume(4, 1, seed=0) circuit.measure_all() system_memory = int(psutil.virtual_memory().total / 1024 / 1024) # Test defaults opts = self.backend_options_parallel() result = execute(circuit, self.SIMULATOR, shots=shots, **opts).result() max_mem_result = result.metadata.get('max_memory_mb') self.assertGreaterEqual(max_mem_result, int(system_memory / 2), msg="Default 'max_memory_mb' is too small.") self.assertLessEqual(max_mem_result, system_memory, msg="Default 'max_memory_mb' is too large.") # Test custom value max_mem_target = 128 opts = self.backend_options_parallel() opts['max_memory_mb'] = max_mem_target result = execute(circuit, self.SIMULATOR, shots=shots, **opts).result() max_mem_result = result.metadata.get('max_memory_mb') self.assertEqual(max_mem_result, max_mem_target, msg="Custom 'max_memory_mb' is not being set correctly.") def available_threads(self): """"Return the threads reported by the simulator""" opts = self.backend_options_parallel() result = execute(self.dummy_circuit(1), self.SIMULATOR, shots=1, **opts).result() return self.threads_used(result)[0]['total'] @requires_omp @requires_multiprocessing def test_parallel_thread_defaults(self): """Test parallel thread assignment defaults""" opts = self.backend_options_parallel() max_threads = self.available_threads() # Test single circuit, no noise # Parallel experiments and shots should always be 1 result = execute(self.dummy_circuit(1), self.SIMULATOR, shots=10*max_threads, **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, 'shots': 1, 'state_update': max_threads, 'total': max_threads } self.assertEqual(threads, target) # Test single circuit, with noise # Parallel experiments should always be 1 # parallel shots should be greater than 1 result = execute(self.dummy_circuit(1), self.SIMULATOR, shots=10*max_threads, noise_model=self.dummy_noise_model(), **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, 'shots': max_threads, 'state_update': 1, 'total': max_threads } self.assertEqual(threads, target) # Test single circuit, with measure in middle, no noise # Parallel experiments should always be 1 # parallel shots should be greater than 1 result = execute(self.measure_in_middle_circuit(1), self.SIMULATOR, shots=10*max_threads, **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, 'shots': max_threads, 'state_update': 1, 'total': max_threads } self.assertEqual(threads, target) # Test multiple circuit, no noise # Parallel experiments always be 1 # parallel shots should always be 1 result = execute(max_threads*[self.dummy_circuit(1)], self.SIMULATOR, shots=10*max_threads, **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, 'shots': 1, 'state_update': max_threads, 'total': max_threads } self.assertEqual(threads, target) # Test multiple circuits, with noise # Parallel experiments should always be 1 # parallel shots should be greater than 1 result = execute(max_threads*[self.dummy_circuit(1)], self.SIMULATOR, shots=10*max_threads, noise_model=self.dummy_noise_model(), **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, 'shots': max_threads, 'state_update': 1, 'total': max_threads } self.assertEqual(threads, target) # Test multiple circuit, with measure in middle, no noise # Parallel experiments should always be 1 # parallel shots should be greater than 1 result = execute(max_threads*[self.measure_in_middle_circuit(1)], self.SIMULATOR, shots=10*max_threads, noise_model=self.dummy_noise_model(), **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, 'shots': max_threads, 'state_update': 1, 'total': max_threads } self.assertEqual(threads, target) @requires_omp @requires_multiprocessing def test_parallel_thread_assignment_priority(self): """Test parallel thread assignment priority""" # If we set all values to max test output # We intentionally set the max shot and experiment threads to # twice the max threads to check they are limited correctly for custom_max_threads in [0, 1, 2, 4]: opts = self.backend_options_parallel() opts['max_parallel_threads'] = custom_max_threads opts['max_parallel_experiments'] = 2 * custom_max_threads opts['max_parallel_shots'] = 2 * custom_max_threads # Calculate actual max threads from custom max and CPU number max_threads = self.available_threads() if custom_max_threads > 0: max_threads = min(max_threads, custom_max_threads) # Test single circuit, no noise # Parallel experiments and shots should always be 1 result = execute(self.dummy_circuit(1), self.SIMULATOR, shots=10*max_threads, **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, 'shots': 1, 'state_update': max_threads, 'total': max_threads } self.assertEqual(threads, target) # Test single circuit, with noise # Parallel experiments should always be 1 # parallel shots should be greater than 1 result = execute(self.dummy_circuit(1), self.SIMULATOR, shots=10*max_threads, noise_model=self.dummy_noise_model(), **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, 'shots': max_threads, 'state_update': 1, 'total': max_threads } self.assertEqual(threads, target) # Test single circuit, with measure in middle, no noise # Parallel experiments should always be 1 # parallel shots should be greater than 1 result = execute(self.measure_in_middle_circuit(1), self.SIMULATOR, shots=10*max_threads, **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, 'shots': max_threads, 'state_update': 1, 'total': max_threads } self.assertEqual(threads, target) # Test multiple circuit, no noise # Parallel experiments always be greater than 1 # parallel shots should always be 1 result = execute(max_threads*[self.dummy_circuit(1)], self.SIMULATOR, shots=10*max_threads, **opts).result() for threads in self.threads_used(result): target = { 'experiments': max_threads, 'shots': 1, 'state_update': 1, 'total': max_threads } self.assertEqual(threads, target) # Test multiple circuits, with noise # Parallel experiments always be greater than 1 # parallel shots should always be 1 result = execute(max_threads*[self.dummy_circuit(1)], self.SIMULATOR, shots=10*max_threads, noise_model=self.dummy_noise_model(), **opts).result() for threads in self.threads_used(result): target = { 'experiments': max_threads, 'shots': 1, 'state_update': 1, 'total': max_threads } self.assertEqual(threads, target) # Test multiple circuit, with measure in middle, no noise # Parallel experiments always be greater than 1 # parallel shots should always be 1 result = execute(max_threads*[self.measure_in_middle_circuit(1)], self.SIMULATOR, shots=10*max_threads, noise_model=self.dummy_noise_model(), **opts).result() for threads in self.threads_used(result): target = { 'experiments': max_threads, 'shots': 1, 'state_update': 1, 'total': max_threads } self.assertEqual(threads, target) @requires_omp @requires_multiprocessing def test_parallel_experiment_thread_assignment(self): """Test parallel experiment thread assignment""" max_threads = self.available_threads() opts = self.backend_options_parallel(exp_threads=max_threads) # Test single circuit # Parallel experiments and shots should always be 1 result = execute(self.dummy_circuit(1), self.SIMULATOR, shots=10*max_threads, **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, 'shots': 1, 'state_update': max_threads, 'total': max_threads } self.assertEqual(threads, target) # Test multiple circuit, no noise # Parallel experiments should take priority result = execute(max_threads*[self.dummy_circuit(1)], self.SIMULATOR, shots=10*max_threads, **opts).result() for threads in self.threads_used(result): target = { 'experiments': max_threads, 'shots': 1, 'state_update': 1, 'total': max_threads } self.assertEqual(threads, target) # Test multiple circuits, with noise # Parallel experiments should take priority result = execute(max_threads*[self.dummy_circuit(1)], self.SIMULATOR, shots=10*max_threads, noise_model=self.dummy_noise_model(), **opts).result() for threads in self.threads_used(result): target = { 'experiments': max_threads, 'shots': 1, 'state_update': 1, 'total': max_threads } self.assertEqual(threads, target) # Test multiple circuit, with measure in middle, no noise # Parallel experiments should take priority result = execute(max_threads*[self.measure_in_middle_circuit(1)], self.SIMULATOR, shots=10*max_threads, noise_model=self.dummy_noise_model(), **opts).result() for threads in self.threads_used(result): target = { 'experiments': max_threads, 'shots': 1, 'state_update': 1, 'total': max_threads } self.assertEqual(threads, target) # Test multiple circuits, with memory limitation # NOTE: this assumes execution on statevector simulator # which required approx 2 MB for 16 qubit circuit. opts['max_memory_mb'] = 1 circuit = QuantumVolume(16, 1, seed=0) circuit.measure_all() result = execute(2 * [circuit], self.SIMULATOR, shots=10*max_threads, **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, 'shots': 1, 'state_update': max_threads, 'total': max_threads } self.assertEqual(threads, target) @requires_omp @requires_multiprocessing def test_parallel_shot_thread_assignment(self): """Test parallel shot thread assignment""" max_threads = self.available_threads() opts = self.backend_options_parallel(shot_threads=max_threads) # Test single circuit # Parallel experiments and shots should always be 1 result = execute(self.dummy_circuit(1), self.SIMULATOR, shots=10*max_threads, **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, 'shots': 1, 'state_update': max_threads, 'total': max_threads } self.assertEqual(threads, target) # Test multiple circuit, no noise # Parallel experiments and shots should always be 1 result = execute(max_threads*[self.dummy_circuit(1)], self.SIMULATOR, shots=10*max_threads, **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, 'shots': 1, 'state_update': max_threads, 'total': max_threads } self.assertEqual(threads, target) # Test multiple circuits, with noise # Parallel shots should take priority result = execute(max_threads*[self.dummy_circuit(1)], self.SIMULATOR, shots=10*max_threads, noise_model=self.dummy_noise_model(), **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, 'shots': max_threads, 'state_update': 1, 'total': max_threads } self.assertEqual(threads, target) # Test multiple circuit, with measure in middle, no noise # Parallel shots should take priority result = execute(max_threads*[self.measure_in_middle_circuit(1)], self.SIMULATOR, shots=10*max_threads, noise_model=self.dummy_noise_model(), **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, 'shots': max_threads, 'state_update': 1, 'total': max_threads } self.assertEqual(threads, target) # Test multiple circuits, with memory limitation # NOTE: this assumes execution on statevector simulator # which required approx 2 MB for 16 qubit circuit. opts['max_memory_mb'] = 1 circuit = QuantumVolume(16, 1, seed=0) circuit.measure_all() result = execute(2 * [circuit], self.SIMULATOR, shots=10*max_threads, **opts).result() for threads in self.threads_used(result): target = { 'experiments': 1, 'shots': 1, 'state_update': max_threads, 'total': max_threads } self.assertEqual(threads, target) @requires_omp @requires_multiprocessing def _test_qasm_explicit_parallelization(self): """test disabling parallel shots because max_parallel_shots is 1""" # Test circuit shots = multiprocessing.cpu_count() circuit = QuantumVolume(16, 1, seed=0) circuit.measure_all() backend_opts = self.backend_options_parallel(shot_threads=1, exp_threads=1) backend_opts['noise_model'] = self.dummy_noise_model() backend_opts['_parallel_experiments'] = 2 backend_opts['_parallel_shots'] = 3 backend_opts['_parallel_state_update'] = 4 result = execute( circuit, self.SIMULATOR, shots=shots, **backend_opts).result() if result.metadata['omp_enabled']: self.assertEqual( result.metadata['parallel_experiments'], 2, msg="parallel_experiments should be 2") self.assertEqual( result.to_dict()['results'][0]['metadata']['parallel_shots'], 3, msg="parallel_shots must be 3") self.assertEqual( result.to_dict()['results'][0]['metadata'] ['parallel_state_update'], 4, msg="parallel_state_update should be 4")
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# -*- coding: utf-8 -*- # Copyright 2018, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. """ QasmSimulator Integration Tests """ import json from qiskit import execute, QuantumRegister, ClassicalRegister, QuantumCircuit, Aer from qiskit.providers.qrack import QasmSimulator from qiskit.providers.aer import noise from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors import ReadoutError, depolarizing_error from qiskit.providers.models import BackendProperties class QasmQubitsTruncateTests: """QasmSimulator Qubits Truncate tests.""" SIMULATOR = QasmSimulator() def create_circuit_for_truncate(self): qr = QuantumRegister(4) cr = ClassicalRegister(4) circuit = QuantumCircuit(qr, cr) circuit.u3(0.1,0.1,0.1,qr[1]) circuit.barrier(qr) circuit.x(qr[2]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.x(qr[3]) circuit.barrier(qr) circuit.u3(0.1,0.1,0.1,qr[0]) circuit.barrier(qr) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[1]) return circuit def device_properties(self): properties = {"general": [], "last_update_date": "2019-04-22T03:26:08+00:00", "gates": [ {"gate": "u1", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [0]}, {"gate": "u2", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [0]}, {"gate": "u3", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [0]}, {"gate": "u1", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [1]}, {"gate": "u2", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [1]}, {"gate": "u3", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [1]}, {"gate": "u1", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [2]}, {"gate": "u2", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [2]}, {"gate": "u3", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [2]}, {"gate": "u1", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [3]}, {"gate": "u2", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [3]}, {"gate": "u3", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [3]}, {"gate": "u1", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [4]}, {"gate": "u2", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [4]}, {"gate": "u3", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [4]}, {"gate": "u1", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [5]}, {"gate": "u2", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [5]}, {"gate": "u3", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [5]}, {"gate": "u1", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [6]}, {"gate": "u2", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [6]}, {"gate": "u3", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [6]}, {"gate": "u1", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [7]}, {"gate": "u2", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [7]}, {"gate": "u3", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [7]}, {"gate": "u1", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [8]}, {"gate": "u2", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [8]}, {"gate": "u3", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [8]}, {"gate": "u1", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [9]}, {"gate": "u2", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [9]}, {"gate": "u3", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-23T01:45:04+00:00", "unit": ""}], "qubits": [9]}, {"gate": "cx", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-22T02:26:00+00:00", "unit": ""}], "qubits": [0, 1], "name": "CX0_1"}, {"gate": "cx", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-22T02:29:15+00:00", "unit": ""}], "qubits": [1, 2], "name": "CX1_2"}, {"gate": "cx", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-22T02:32:48+00:00", "unit": ""}], "qubits": [2, 3], "name": "CX2_3"}, {"gate": "cx", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-22T02:26:00+00:00", "unit": ""}], "qubits": [3, 4], "name": "CX3_4"}, {"gate": "cx", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-22T02:29:15+00:00", "unit": ""}], "qubits": [4, 5], "name": "CX4_5"}, {"gate": "cx", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-22T02:32:48+00:00", "unit": ""}], "qubits": [5, 6], "name": "CX5_6"}, {"gate": "cx", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-22T02:26:00+00:00", "unit": ""}], "qubits": [6, 7], "name": "CX6_7"}, {"gate": "cx", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-22T02:29:15+00:00", "unit": ""}], "qubits": [7, 8], "name": "CX7_8"}, {"gate": "cx", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-22T02:32:48+00:00", "unit": ""}], "qubits": [8, 9], "name": "CX8_9"}, {"gate": "cx", "parameters": [{"name": "gate_error", "value": 0.001, "date": "2019-04-22T02:26:00+00:00", "unit": ""}], "qubits": [9, 0], "name": "CX9_0"}], "qubits": [ [ {"name": "T1", "value": 23.809868955712616, "date": "2019-04-22T01:30:15+00:00", "unit": "\u00b5s"}, {"name": "T2", "value": 43.41142418044261, "date": "2019-04-22T01:33:33+00:00", "unit": "\u00b5s"}, {"name": "frequency", "value": 5.032871440179164, "date": "2019-04-22T03:26:08+00:00", "unit": "GHz"}, {"name": "readout_error", "value": 0.03489999999999993, "date": "2019-04-22T01:29:47+00:00", "unit": ""}], [ {"name": "T1", "value": 68.14048367144501, "date": "2019-04-22T01:30:15+00:00", "unit": "\u00b5s"}, {"name": "T2", "value": 56.95903203933663, "date": "2019-04-22T01:34:36+00:00", "unit": "\u00b5s"}, {"name": "frequency", "value": 4.896209948700639, "date": "2019-04-22T03:26:08+00:00", "unit": "GHz"}, {"name": "readout_error", "value": 0.19589999999999996, "date": "2019-04-22T01:29:47+00:00", "unit": ""}], [ {"name": "T1", "value": 83.26776276928099, "date": "2019-04-22T01:30:15+00:00", "unit": "\u00b5s"}, {"name": "T2", "value": 23.49615795695734, "date": "2019-04-22T01:31:32+00:00", "unit": "\u00b5s"}, {"name": "frequency", "value": 5.100093544085939, "date": "2019-04-22T03:26:08+00:00", "unit": "GHz"}, {"name": "readout_error", "value": 0.09050000000000002, "date": "2019-04-22T01:29:47+00:00", "unit": ""}], [ {"name": "T1", "value": 57.397746445609975, "date": "2019-04-22T01:30:15+00:00", "unit": "\u00b5s"}, {"name": "T2", "value": 98.47976889309517, "date": "2019-04-22T01:32:32+00:00", "unit": "\u00b5s"}, {"name": "frequency", "value": 5.238526396839902, "date": "2019-04-22T03:26:08+00:00", "unit": "GHz"}, {"name": "readout_error", "value": 0.24350000000000005, "date": "2019-04-20T15:31:39+00:00", "unit": ""}], [ {"name": "T1", "value": 23.809868955712616, "date": "2019-04-22T01:30:15+00:00", "unit": "\u00b5s"}, {"name": "T2", "value": 43.41142418044261, "date": "2019-04-22T01:33:33+00:00", "unit": "\u00b5s"}, {"name": "frequency", "value": 5.032871440179164, "date": "2019-04-22T03:26:08+00:00", "unit": "GHz"}, {"name": "readout_error", "value": 0.03489999999999993, "date": "2019-04-22T01:29:47+00:00", "unit": ""}], [ {"name": "T1", "value": 68.14048367144501, "date": "2019-04-22T01:30:15+00:00", "unit": "\u00b5s"}, {"name": "T2", "value": 56.95903203933663, "date": "2019-04-22T01:34:36+00:00", "unit": "\u00b5s"}, {"name": "frequency", "value": 4.896209948700639, "date": "2019-04-22T03:26:08+00:00", "unit": "GHz"}, {"name": "readout_error", "value": 0.19589999999999996, "date": "2019-04-22T01:29:47+00:00", "unit": ""}], [ {"name": "T1", "value": 83.26776276928099, "date": "2019-04-22T01:30:15+00:00", "unit": "\u00b5s"}, {"name": "T2", "value": 23.49615795695734, "date": "2019-04-22T01:31:32+00:00", "unit": "\u00b5s"}, {"name": "frequency", "value": 5.100093544085939, "date": "2019-04-22T03:26:08+00:00", "unit": "GHz"}, {"name": "readout_error", "value": 0.09050000000000002, "date": "2019-04-22T01:29:47+00:00", "unit": ""}], [ {"name": "T1", "value": 57.397746445609975, "date": "2019-04-22T01:30:15+00:00", "unit": "\u00b5s"}, {"name": "T2", "value": 98.47976889309517, "date": "2019-04-22T01:32:32+00:00", "unit": "\u00b5s"}, {"name": "frequency", "value": 5.238526396839902, "date": "2019-04-22T03:26:08+00:00", "unit": "GHz"}, {"name": "readout_error", "value": 0.24350000000000005, "date": "2019-04-20T15:31:39+00:00", "unit": ""}], [ {"name": "T1", "value": 23.809868955712616, "date": "2019-04-22T01:30:15+00:00", "unit": "\u00b5s"}, {"name": "T2", "value": 43.41142418044261, "date": "2019-04-22T01:33:33+00:00", "unit": "\u00b5s"}, {"name": "frequency", "value": 5.032871440179164, "date": "2019-04-22T03:26:08+00:00", "unit": "GHz"}, {"name": "readout_error", "value": 0.03489999999999993, "date": "2019-04-22T01:29:47+00:00", "unit": ""}], [ {"name": "T1", "value": 68.14048367144501, "date": "2019-04-22T01:30:15+00:00", "unit": "\u00b5s"}, {"name": "T2", "value": 56.95903203933663, "date": "2019-04-22T01:34:36+00:00", "unit": "\u00b5s"}, {"name": "frequency", "value": 4.896209948700639, "date": "2019-04-22T03:26:08+00:00", "unit": "GHz"}, {"name": "readout_error", "value": 0.19589999999999996, "date": "2019-04-22T01:29:47+00:00", "unit": ""}], ], "backend_name": "mock_4q", "backend_version": "1.0.0"} return BackendProperties.from_dict(properties) def test_truncate_ideal_sparse_circuit(self): """Test qubit truncation for large circuit with unused qubits.""" # Circuit that uses just 2-qubits circuit = QuantumCircuit(50, 2) circuit.x(10) circuit.x(20) circuit.measure(10, 0) circuit.measure(20, 1) qasm_sim = Aer.get_backend('qasm_simulator') backend_options = self.BACKEND_OPTS.copy() backend_options["truncate_verbose"] = True backend_options['optimize_ideal_threshold'] = 1 backend_options['optimize_noise_threshold'] = 1 result = execute(circuit, qasm_sim, shots=100, **backend_options).result() metadata = result.results[0].metadata self.assertTrue('truncate_qubits' in metadata, msg="truncate_qubits must work.") active_qubits = sorted(metadata['truncate_qubits'].get('active_qubits', [])) mapping = sorted(metadata['truncate_qubits'].get('mapping', [])) self.assertEqual(active_qubits, [10, 20]) self.assertIn(mapping, [[[10, 0], [20, 1]], [[10, 1], [20, 0]]]) def test_truncate_nonlocal_noise(self): """Test qubit truncation with non-local noise.""" # Circuit that uses just 2-qubits circuit = QuantumCircuit(10, 1) circuit.x(5) circuit.measure(5, 0) # Add non-local 2-qubit depolarizing error # that acts on qubits [4, 6] when X applied to qubit 5 noise_model = NoiseModel() error = depolarizing_error(0.1, 2) noise_model.add_nonlocal_quantum_error(error, ['x'], [5], [4, 6]) qasm_sim = Aer.get_backend('qasm_simulator') backend_options = self.BACKEND_OPTS.copy() backend_options["truncate_verbose"] = True backend_options['optimize_ideal_threshold'] = 1 backend_options['optimize_noise_threshold'] = 1 result = execute(circuit, qasm_sim, shots=100, noise_model=noise_model, **backend_options).result() metadata = result.results[0].metadata self.assertTrue('truncate_qubits' in metadata, msg="truncate_qubits must work.") active_qubits = sorted(metadata['truncate_qubits'].get('active_qubits', [])) mapping = metadata['truncate_qubits'].get('mapping', []) active_remapped = sorted([i[1] for i in mapping if i[0] in active_qubits]) self.assertEqual(active_qubits, [4, 5, 6]) self.assertEqual(active_remapped, [0, 1, 2]) def test_truncate(self): """Test truncation with noise model option""" circuit = self.create_circuit_for_truncate() qasm_sim = Aer.get_backend('qasm_simulator') backend_options = self.BACKEND_OPTS.copy() backend_options["truncate_verbose"] = True backend_options['optimize_ideal_threshold'] = 1 backend_options['optimize_noise_threshold'] = 1 result = execute(circuit, qasm_sim, noise_model=NoiseModel.from_backend(self.device_properties()), shots=100, coupling_map=[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 0]], # 10-qubit device **backend_options).result() self.assertTrue('truncate_qubits' in result.to_dict()['results'][0]['metadata'], msg="truncate_qubits must work.") def test_no_truncate(self): """Test truncation with noise model option""" circuit = self.create_circuit_for_truncate() qasm_sim = Aer.get_backend('qasm_simulator') backend_options = self.BACKEND_OPTS.copy() backend_options["truncate_verbose"] = True backend_options['optimize_ideal_threshold'] = 1 backend_options['optimize_noise_threshold'] = 1 result = execute(circuit, qasm_sim, noise_model=NoiseModel.from_backend(self.device_properties()), shots=100, coupling_map=[[1, 0], [1, 2], [1, 3], [2, 0], [2, 1], [2, 3], [3, 0], [3, 1], [3, 2]], # 4-qubit device **backend_options).result() self.assertFalse('truncate_qubits' in result.to_dict()['results'][0]['metadata'], msg="truncate_qubits must work.") def test_truncate_disable(self): """Test explicitly disabling truncation with noise model option""" circuit = self.create_circuit_for_truncate() qasm_sim = Aer.get_backend('qasm_simulator') backend_options = self.BACKEND_OPTS.copy() backend_options["truncate_verbose"] = True backend_options["truncate_enable"] = False backend_options['optimize_ideal_threshold'] = 1 backend_options['optimize_noise_threshold'] = 1 result = execute(circuit, qasm_sim, noise_model=NoiseModel.from_backend(self.device_properties()), shots=100, coupling_map=[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 0]], # 10-qubit device **backend_options).result() self.assertFalse('truncate_qubits' in result.to_dict()['results'][0]['metadata'], msg="truncate_qubits must not work.")
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ QasmSimulator Integration Tests """ from test.terra.reference import ref_unitary_gate, ref_diagonal_gate from qiskit import execute from qiskit.providers.qrack import QasmSimulator import numpy as np class QasmUnitaryGateTests: """QasmSimulator unitary gate tests.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} # --------------------------------------------------------------------- # Test unitary gate qobj instruction # --------------------------------------------------------------------- def test_unitary_gate(self): """Test simulation with unitary gate circuit instructions.""" shots = 100 circuits = ref_unitary_gate.unitary_gate_circuits_deterministic( final_measure=True) targets = ref_unitary_gate.unitary_gate_counts_deterministic( shots) result = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_random_unitary_gate(self): """Test simulation with random unitary gate circuit instructions.""" shots = 4000 circuits = ref_unitary_gate.unitary_random_gate_circuits_nondeterministic(final_measure=True) targets = ref_unitary_gate.unitary_random_gate_counts_nondeterministic(shots) result = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) class QasmDiagonalGateTests: """QasmSimulator diagonal gate tests.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} # --------------------------------------------------------------------- # Test unitary gate qobj instruction # --------------------------------------------------------------------- def test_diagonal_gate(self): """Test simulation with unitary gate circuit instructions.""" shots = 100 circuits = ref_diagonal_gate.diagonal_gate_circuits_deterministic( final_measure=True) targets = ref_diagonal_gate.diagonal_gate_counts_deterministic( shots) result = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS).result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0)
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. import unittest import copy import pickle from multiprocessing import Pool from qiskit import assemble, transpile, QuantumCircuit from qiskit.providers.qrack.backends import QasmSimulator #from qiskit.providers.aer.backends.controller_wrappers import qasm_controller_execute from test.terra.reference import ref_algorithms, ref_measure, ref_1q_clifford from test.terra.common import QiskitAerTestCase class TestControllerExecuteWrappers(QiskitAerTestCase): """Basic functionality tests for pybind-generated wrappers""" #CFUNCS = [qasm_controller_execute()] #def test_deepcopy(self): # """Test that the functors are deepcopy-able.""" # for cfunc in self.CFUNCS: # cahpy = copy.deepcopy(cfunc) #def test_pickleable(self): # """Test that the functors are pickle-able (directly).""" # for cfunc in self.CFUNCS: # bites = pickle.dumps(cfunc) # cahpy = pickle.loads(bites) def _create_qobj(self, backend, noise_model=None): num_qubits = 2 circuit = QuantumCircuit(num_qubits) circuit.x(list(range(num_qubits))) qobj = assemble(transpile(circuit, backend), backend) opts = {'max_parallel_threads': 1} fqobj = backend._format_qobj(qobj, **opts, noise_model=noise_model) return fqobj.to_dict() def _map_and_test(self, cfunc, qobj): n = 2 with Pool(processes=1) as p: rs = p.map(cfunc, [copy.deepcopy(qobj) for _ in range(n)]) self.assertEqual(len(rs), n) for r in rs: self.assertTrue(r['success']) #def test_mappable_qasm(self): # """Test that the qasm controller can be mapped.""" # cfunc = qasm_controller_execute() # sim = QasmSimulator() # fqobj = self._create_qobj(sim) # self._map_and_test(cfunc, fqobj) #def test_mappable_statevector(self): # """Test that the statevector controller can be mapped.""" # cfunc = statevector_controller_execute() # sim = StatevectorSimulator() # fqobj = self._create_qobj(sim) # self._map_and_test(cfunc, fqobj) if __name__ == '__main__': unittest.main()
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test circuits and reference outputs for 1-qubit Clifford gate instructions. """ import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit # ========================================================================== # H-gate # ========================================================================== def h_gate_circuits_deterministic(final_measure=True): """H-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # HH=I circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def h_gate_counts_deterministic(shots, hex_counts=True): """H-gate circuits reference counts.""" targets = [] if hex_counts: # HH=I targets.append({'0x0': shots}) else: # HH=I targets.append({'0': shots}) return targets def h_gate_statevector_deterministic(): """H-gate circuits reference statevectors.""" targets = [] # HH=I targets.append(np.array([1, 0])) return targets def h_gate_unitary_deterministic(): """H-gate circuits reference unitaries.""" targets = [] # HH=I targets.append(np.eye(2)) return targets def h_gate_circuits_nondeterministic(final_measure=True): """X-gate test circuits with non-deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # H circuit = QuantumCircuit(*regs) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def h_gate_counts_nondeterministic(shots, hex_counts=True): """H-gate circuits reference counts.""" targets = [] if hex_counts: # H targets.append({'0x0': shots / 2, '0x1': shots / 2}) else: # H targets.append({'0': shots / 2, '1': shots / 2}) return targets def h_gate_statevector_nondeterministic(): """H-gate circuits reference statevectors.""" targets = [] # H targets.append(np.array([1, 1]) / np.sqrt(2)) return targets def h_gate_unitary_nondeterministic(): """H-gate circuits reference unitaries.""" targets = [] # HH=I targets.append(np.array([[1, 1], [1, -1]]) / np.sqrt(2)) return targets # ========================================================================== # X-gate # ========================================================================== def x_gate_circuits_deterministic(final_measure=True): """X-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # X circuit = QuantumCircuit(*regs) circuit.x(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # XX = I circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.barrier(qr) circuit.x(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # HXH=Z circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.x(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def x_gate_counts_deterministic(shots, hex_counts=True): """X-gate circuits reference counts.""" targets = [] if hex_counts: # X targets.append({'0x1': shots}) # XX = I targets.append({'0x0': shots}) # HXH=Z targets.append({'0x0': shots}) else: # X targets.append({'1': shots}) # XX = I targets.append({'0': shots}) # HXH=Z targets.append({'0': shots}) return targets def x_gate_statevector_deterministic(): """X-gate circuits reference statevectors.""" targets = [] # X targets.append(np.array([0, 1])) # XX = I targets.append(np.array([1, 0])) # HXH=Z targets.append(np.array([1, 0])) return targets def x_gate_unitary_deterministic(): """X-gate circuits reference unitaries.""" targets = [] # X targets.append(np.array([[0, 1], [1, 0]])) # XX = I targets.append(np.eye(2)) # HXH=Z targets.append(np.array([[1, 0], [0, -1]])) return targets # ========================================================================== # Z-gate # ========================================================================== def z_gate_circuits_deterministic(final_measure=True): """Z-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # Z alone circuit = QuantumCircuit(*regs) circuit.z(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # HZH = X circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.z(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # HZZH = I circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.z(qr) circuit.barrier(qr) circuit.z(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def z_gate_counts_deterministic(shots, hex_counts=True): """Z-gate circuits reference counts.""" targets = [] if hex_counts: # Z targets.append({'0x0': shots}) # HZH = X targets.append({'0x1': shots}) # HZZH = I targets.append({'0x0': shots}) else: # Z targets.append({'0': shots}) # HZH = X targets.append({'1': shots}) # HZZH = I targets.append({'0': shots}) return targets def z_gate_statevector_deterministic(): """Z-gate circuits reference statevectors.""" targets = [] # Z targets.append(np.array([1, 0])) # HZH = X targets.append(np.array([0, 1])) # HZZH = I targets.append(np.array([1, 0])) return targets def z_gate_unitary_deterministic(): """Z-gate circuits reference unitaries.""" targets = [] # Z targets.append(np.array([[1, 0], [0, -1]])) # HZH = X targets.append(np.array([[0, 1], [1, 0]])) # HZZH = I targets.append(np.eye(2)) return targets # ========================================================================== # Y-gate # ========================================================================== def y_gate_circuits_deterministic(final_measure=True): """Y-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # Y circuit = QuantumCircuit(*regs) circuit.y(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # YY = I circuit = QuantumCircuit(*regs) circuit.y(qr) circuit.barrier(qr) circuit.y(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # HYH = -Y circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.y(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def y_gate_counts_deterministic(shots, hex_counts=True): """Y-gate circuits reference counts.""" targets = [] if hex_counts: # Y targets.append({'0x1': shots}) # YY = I targets.append({'0x0': shots}) # HYH = -Y targets.append({'0x1': shots}) else: # Y targets.append({'1': shots}) # YY = I targets.append({'0': shots}) # HYH = -Y targets.append({'1': shots}) return targets def y_gate_statevector_deterministic(): """Y-gate circuits reference statevectors.""" targets = [] # Y targets.append(np.array([0, 1j])) # YY = I targets.append(np.array([1, 0])) # HYH = -Y targets.append(np.array([0, -1j])) return targets def y_gate_unitary_deterministic(): """Y-gate circuits reference unitaries.""" targets = [] # Y targets.append(np.array([[0, -1j], [1j, 0]])) # YY = I targets.append(np.eye(2)) # HYH = -Y targets.append(np.array([[0, 1j], [-1j, 0]])) return targets # ========================================================================== # S-gate # ========================================================================== def s_gate_circuits_deterministic(final_measure=True): """S-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # S circuit = QuantumCircuit(*regs) circuit.s(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # S.X circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.barrier(qr) circuit.s(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # HSSH = HZH = X circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.s(qr) circuit.barrier(qr) circuit.s(qr) circuit.barrier(qr) circuit.h(qr) circuit.barrier(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) return circuits def s_gate_counts_deterministic(shots, hex_counts=True): """S-gate circuits reference counts.""" targets = [] if hex_counts: # S targets.append({'0x0': shots}) # S.X targets.append({'0x1': shots}) # HSSH = HZH = X targets.append({'0x1': shots}) else: # S targets.append({'0': shots}) # S.X targets.append({'1': shots}) # HSSH = HZH = X targets.append({'1': shots}) return targets def s_gate_statevector_deterministic(): """S-gate circuits reference statevectors.""" targets = [] # S targets.append(np.array([1, 0])) # S.X targets.append(np.array([0, 1j])) # HSSH = HZH = X targets.append(np.array([0, 1])) return targets def s_gate_unitary_deterministic(): """S-gate circuits reference unitaries.""" targets = [] # S targets.append(np.diag([1, 1j])) # S.X targets.append(np.array([[0, 1], [1j, 0]])) # HSSH = HZH = X targets.append(np.array([[0, 1], [1, 0]])) return targets def s_gate_circuits_nondeterministic(final_measure=True): """S-gate test circuits with non-deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # SH circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.s(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # HSH circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.s(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def s_gate_counts_nondeterministic(shots, hex_counts=True): """S-gate circuits reference counts.""" targets = [] if hex_counts: # S.H targets.append({'0x0': shots / 2, '0x1': shots / 2}) # H.S.H targets.append({'0x0': shots / 2, '0x1': shots / 2}) else: # S.H targets.append({'0': shots / 2, '1': shots / 2}) # H.S.H targets.append({'0': shots / 2, '1': shots / 2}) return targets def s_gate_statevector_nondeterministic(): """S-gate circuits reference statevectors.""" targets = [] # S.H targets.append(np.array([1, 1j]) / np.sqrt(2)) # H.S.H targets.append(np.array([1 + 1j, 1 - 1j]) / 2) return targets def s_gate_unitary_nondeterministic(): """S-gate circuits reference unitaries.""" targets = [] # S.H targets.append(np.array([[1, 1], [1j, -1j]]) / np.sqrt(2)) # H.S.H targets.append(np.array([[1 + 1j, 1 - 1j], [1 - 1j, 1 + 1j]]) / 2) return targets # ========================================================================== # S^dagger-gate # ========================================================================== def sdg_gate_circuits_deterministic(final_measure=True): """Sdg-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # Sdg circuit = QuantumCircuit(*regs) circuit.sdg(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H.Sdg.Sdg.H = H.Z.H = X circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.sdg(qr) circuit.barrier(qr) circuit.sdg(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H.Sdg.S.H = I circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.s(qr) circuit.barrier(qr) circuit.sdg(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def sdg_gate_counts_deterministic(shots, hex_counts=True): """Sdg-gate circuits reference counts.""" targets = [] if hex_counts: # Sdg targets.append({'0x0': shots}) # H.Sdg.Sdg.H = H.Z.H = X targets.append({'0x1': shots}) # H.Sdg.S.H = I targets.append({'0x0': shots}) else: # Sdg targets.append({'0': shots}) # H.Sdg.Sdg.H = H.Z.H = X targets.append({'1': shots}) # H.Sdg.S.H = I targets.append({'0': shots}) return targets def sdg_gate_statevector_deterministic(): """Sdg-gate circuits reference statevectors.""" targets = [] # Sdg targets.append(np.array([1, 0])) # H.Sdg.Sdg.H = H.Z.H = X targets.append(np.array([0, 1])) # H.Sdg.S.H = I targets.append(np.array([1, 0])) return targets def sdg_gate_unitary_deterministic(): """Sdg-gate circuits reference unitaries.""" targets = [] # Sdg targets.append(np.diag([1, -1j])) # H.Sdg.Sdg.H = H.Z.H = X targets.append(np.array([[0, 1], [1, 0]])) # H.Sdg.S.H = I targets.append(np.eye(2)) return targets def sdg_gate_circuits_nondeterministic(final_measure=True): """Sdg-gate test circuits with non-deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # Sdg.H circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.sdg(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H.Sdg.H circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.sdg(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def sdg_gate_counts_nondeterministic(shots, hex_counts=True): """Sdg-gate circuits reference counts.""" targets = [] if hex_counts: # Sdg.H targets.append({'0x0': shots / 2, '0x1': shots / 2}) # H.Sdg.H targets.append({'0x0': shots / 2, '0x1': shots / 2}) else: # Sdg.H targets.append({'0': shots / 2, '1': shots / 2}) # H.Sdg.H targets.append({'0': shots / 2, '1': shots / 2}) return targets def sdg_gate_statevector_nondeterministic(): """Sdg-gate circuits reference statevectors.""" targets = [] # Sdg.H targets.append(np.array([1, -1j]) / np.sqrt(2)) # H.Sdg.H targets.append(np.array([1 - 1j, 1 + 1j]) / 2) return targets def sdg_gate_unitary_nondeterministic(): """Sdg-gate circuits reference unitaries.""" targets = [] # Sdg.H targets.append(np.array([[1, 1], [-1j, 1j]]) / np.sqrt(2)) # H.Sdg.H targets.append(np.array([[1 - 1j, 1 + 1j], [1 + 1j, 1 - 1j]]) / 2) return targets
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test circuits and reference outputs for 2-qubit Clifford gate instructions. """ import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit # ========================================================================== # CX-gate # ========================================================================== def cx_gate_circuits_deterministic(final_measure=True): """CX-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(2) if final_measure: cr = ClassicalRegister(2) regs = (qr, cr) else: regs = (qr, ) # CX01, |00> state circuit = QuantumCircuit(*regs) circuit.cx(qr[0], qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX10, |00> state circuit = QuantumCircuit(*regs) circuit.cx(qr[1], qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX01.(X^I), |10> state circuit = QuantumCircuit(*regs) circuit.x(qr[1]) circuit.barrier(qr) circuit.cx(qr[0], qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX10.(I^X), |01> state circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.barrier(qr) circuit.cx(qr[1], qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX01.(I^X), |11> state circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.barrier(qr) circuit.cx(qr[0], qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX10.(X^I), |11> state circuit = QuantumCircuit(*regs) circuit.x(qr[1]) circuit.barrier(qr) circuit.cx(qr[1], qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX01.(X^X), |01> state circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.barrier(qr) circuit.cx(qr[0], qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX10.(X^X), |10> state circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.barrier(qr) circuit.cx(qr[1], qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def cx_gate_counts_deterministic(shots, hex_counts=True): """CX-gate circuits reference counts.""" targets = [] if hex_counts: # CX01, |00> state targets.append({'0x0': shots}) # {"00": shots} # CX10, |00> state targets.append({'0x0': shots}) # {"00": shots} # CX01.(X^I), |10> state targets.append({'0x2': shots}) # {"00": shots} # CX10.(I^X), |01> state targets.append({'0x1': shots}) # {"00": shots} # CX01.(I^X), |11> state targets.append({'0x3': shots}) # {"00": shots} # CX10.(X^I), |11> state targets.append({'0x3': shots}) # {"00": shots} # CX01.(X^X), |01> state targets.append({'0x1': shots}) # {"00": shots} # CX10.(X^X), |10> state targets.append({'0x2': shots}) # {"00": shots} else: # CX01, |00> state targets.append({'00': shots}) # {"00": shots} # CX10, |00> state targets.append({'00': shots}) # {"00": shots} # CX01.(X^I), |10> state targets.append({'10': shots}) # {"00": shots} # CX10.(I^X), |01> state targets.append({'01': shots}) # {"00": shots} # CX01.(I^X), |11> state targets.append({'11': shots}) # {"00": shots} # CX10.(X^I), |11> state targets.append({'11': shots}) # {"00": shots} # CX01.(X^X), |01> state targets.append({'01': shots}) # {"00": shots} # CX10.(X^X), |10> state targets.append({'10': shots}) # {"00": shots} return targets def cx_gate_statevector_deterministic(): """CX-gate test circuits with deterministic counts.""" targets = [] # CX01, |00> state targets.append(np.array([1, 0, 0, 0])) # CX10, |00> state targets.append(np.array([1, 0, 0, 0])) # CX01.(X^I), |10> state targets.append(np.array([0, 0, 1, 0])) # CX10.(I^X), |01> state targets.append(np.array([0, 1, 0, 0])) # CX01.(I^X), |11> state targets.append(np.array([0, 0, 0, 1])) # CX10.(X^I), |11> state targets.append(np.array([0, 0, 0, 1])) # CX01.(X^X), |01> state targets.append(np.array([0, 1, 0, 0])) # CX10.(X^X), |10> state targets.append(np.array([0, 0, 1, 0])) return targets def cx_gate_unitary_deterministic(): """CX-gate circuits reference unitaries.""" targets = [] # CX01, |00> state targets.append(np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]])) # CX10, |00> state targets.append(np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])) # CX01.(X^I), |10> state targets.append(np.array([[0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1]])) # CX10.(I^X), |01> state targets.append(np.array([[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])) # CX01.(I^X), |11> state targets.append(np.array([[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0]])) # CX10.(X^I), |11> state targets.append(np.array([[0, 0, 1, 0], [0, 0, 0, 1], [0, 1, 0, 0], [1, 0, 0, 0]])) # CX01.(X^X), |01> state targets.append(np.array([[0, 0, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]])) # CX10.(X^X), |10> state targets.append(np.array([[0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0], [0, 1, 0, 0]])) return targets def cx_gate_circuits_nondeterministic(final_measure=True): """CX-gate test circuits with non-deterministic counts.""" circuits = [] qr = QuantumRegister(2) if final_measure: cr = ClassicalRegister(2) regs = (qr, cr) else: regs = (qr, ) # CX01.(I^H), Bell state circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.barrier(qr) circuit.cx(qr[0], qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX10.(H^I), Bell state circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.barrier(qr) circuit.cx(qr[1], qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def cx_gate_counts_nondeterministic(shots, hex_counts=True): """CX-gate circuits reference counts.""" targets = [] if hex_counts: # CX01.(I^H), Bell state targets.append({'0x0': shots / 2, '0x3': shots / 2}) # CX10.(I^H), Bell state targets.append({'0x0': shots / 2, '0x3': shots / 2}) else: # CX01.(I^H), Bell state targets.append({'00': shots / 2, '11': shots / 2}) # CX10.(I^H), Bell state targets.append({'00': shots / 2, '11': shots / 2}) return targets def cx_gate_statevector_nondeterministic(): """CX-gate circuits reference statevectors.""" targets = [] # CX01.(I^H), Bell state targets.append(np.array([1, 0, 0, 1]) / np.sqrt(2)) # CX10.(I^H), Bell state targets.append(np.array([1, 0, 0, 1]) / np.sqrt(2)) return targets def cx_gate_unitary_nondeterministic(): """CX-gate circuits reference unitaries.""" targets = [] # CX01.(I^H), Bell state targets.append(np.array([[1, 1, 0, 0], [0, 0, 1, -1], [0, 0, 1, 1], [1, -1, 0, 0]]) / np.sqrt(2)) # CX10.(I^H), Bell state targets.append(np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 1, 0, -1], [1, 0, -1, 0]]) / np.sqrt(2)) return targets # ========================================================================== # CZ-gate # ========================================================================== def cz_gate_circuits_deterministic(final_measure=True): """CZ-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(2) if final_measure: cr = ClassicalRegister(2) regs = (qr, cr) else: regs = (qr, ) # CZ, |00> state circuit = QuantumCircuit(*regs) circuit.cz(qr[0], qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX10, |00> state circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.cz(qr[0], qr[1]) circuit.h(qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX01, |00> state circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.cz(qr[1], qr[0]) circuit.h(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # (I^H).CZ.(X^H) = CX10.(X^I), |11> state circuit = QuantumCircuit(*regs) circuit.x(qr[1]) circuit.barrier(qr) circuit.h(qr[0]) circuit.barrier(qr) circuit.cz(qr[0], qr[1]) circuit.barrier(qr) circuit.h(qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # (H^I).CZ.(H^X) = CX01.(I^X), |11> state circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.barrier(qr) circuit.h(qr[1]) circuit.barrier(qr) circuit.cz(qr[0], qr[1]) circuit.barrier(qr) circuit.h(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def cz_gate_counts_deterministic(shots, hex_counts=True): """CZ-gate circuits reference counts.""" targets = [] if hex_counts: # CZ, |00> state targets.append({'0x0': shots}) # CX10, |00> state targets.append({'0x0': shots}) # CX01, |00> state targets.append({'0x0': shots}) # (I^H).CZ.(X^H) = CX10.(X^I), |11> state targets.append({'0x3': shots}) # (H^I).CZ.(H^X) = CX01.(I^H), |11> state targets.append({'0x3': shots}) else: # CZ, |00> state targets.append({'00': shots}) # CX10, |00> state targets.append({'00': shots}) # CX01, |00> state targets.append({'00': shots}) # (I^H).CZ.(X^H) = CX10.(X^I), |11> state targets.append({'11': shots}) # (H^I).CZ.(H^X) = CX01.(I^H), |11> state targets.append({'11': shots}) return targets def cz_gate_statevector_deterministic(): """CZ-gate test circuits with deterministic counts.""" targets = [] # CZ, |00> state targets.append(np.array([1, 0, 0, 0])) # CX10, |00> state targets.append(np.array([1, 0, 0, 0])) # CX01, |00> state targets.append(np.array([1, 0, 0, 0])) # (I^H).CZ.(X^H) = CX10.(X^I), |11> state targets.append(np.array([0, 0, 0, 1])) # (H^I).CZ.(H^X) = CX01.(I^H), |11> state targets.append(np.array([0, 0, 0, 1])) return targets def cz_gate_unitary_deterministic(): """CZ-gate circuits reference unitaries.""" targets = [] # CZ, |00> state targets.append(np.diag([1, 1, 1, -1])) # CX10, |00> state targets.append(np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])) # CX01, |00> state targets.append(np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]])) # (I^H).CZ.(X^H) = CX10.(X^I), |11> state targets.append(np.array([[0, 0, 1, 0], [0, 0, 0, 1], [0, 1, 0, 0], [1, 0, 0, 0]])) # (H^I).CZ.(H^X) = CX01.(I^X), |11> state targets.append(np.array([[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0]])) return targets def cz_gate_circuits_nondeterministic(final_measure=True): """CZ-gate test circuits with non-deterministic counts.""" circuits = [] qr = QuantumRegister(2) qr = QuantumRegister(2) if final_measure: cr = ClassicalRegister(2) regs = (qr, cr) else: regs = (qr, ) # (I^H).CZ.(H^H) = CX10.(H^I), Bell state circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.cz(qr[0], qr[1]) circuit.barrier(qr) circuit.h(qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # (H^I).CZ.(H^H) = CX01.(I^H), Bell state circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.cz(qr[0], qr[1]) circuit.h(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def cz_gate_counts_nondeterministic(shots, hex_counts=True): """CZ-gate circuits reference counts.""" targets = [] if hex_counts: # (I^H).CZ.(H^H) = CX10.(H^I), Bell state targets.append({'0x0': shots / 2, '0x3': shots / 2}) # (H^I).CZ.(H^H) = CX01.(I^H), Bell state targets.append({'0x0': shots / 2, '0x3': shots / 2}) else: # (I^H).CZ.(H^H) = CX10.(H^I), Bell state targets.append({'00': shots / 2, '11': shots / 2}) # (H^I).CZ.(H^H) = CX01.(I^H), Bell state targets.append({'00': shots / 2, '11': shots / 2}) return targets def cz_gate_statevector_nondeterministic(): """CZ-gate circuits reference statevectors.""" targets = [] # (I^H).CZ.(H^H) = CX10.(H^I), Bell state targets.append(np.array([1, 0, 0, 1]) / np.sqrt(2)) # (H^I).CZ.(H^H) = CX01.(I^H), Bell state targets.append(np.array([1, 0, 0, 1]) / np.sqrt(2)) return targets def cz_gate_unitary_nondeterministic(): """CZ-gate circuits reference unitaries.""" targets = [] # (I^H).CZ.(H^H) = CX10.(H^I), Bell state targets.append(np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 1, 0, -1], [1, 0, -1, 0]]) / np.sqrt(2)) # (H^I).CZ.(H^H) = CX01.(I^H), Bell state targets.append(np.array([[1, 1, 0, 0], [0, 0, 1, -1], [0, 0, 1, 1], [1, -1, 0, 0]]) / np.sqrt(2)) return targets # ========================================================================== # SWAP-gate # ========================================================================== def swap_gate_circuits_deterministic(final_measure=True): """SWAP-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(2) if final_measure: cr = ClassicalRegister(2) regs = (qr, cr) else: regs = (qr, ) # Swap(0,1), |00> state circuit = QuantumCircuit(*regs) circuit.swap(qr[0], qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Swap(0,1).(I^X), |10> state circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.barrier(qr) circuit.swap(qr[0], qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def swap_gate_counts_deterministic(shots, hex_counts=True): """SWAP-gate circuits reference counts.""" targets = [] if hex_counts: # Swap(0,1), |00> state targets.append({'0x0': shots}) # Swap(0,1).(I^X), |10> state targets.append({'0x2': shots}) else: # Swap(0,1), |00> state targets.append({'00': shots}) # Swap(0,1).(I^X), |10> state targets.append({'10': shots}) return targets def swap_gate_statevector_deterministic(): """SWAP-gate test circuits with deterministic counts.""" targets = [] # Swap(0,1), |00> state targets.append(np.array([1, 0, 0, 0])) # Swap(0,1).(I^X), |10> state targets.append(np.array([0, 0, 1, 0])) return targets def swap_gate_unitary_deterministic(): """SWAP-gate circuits reference unitaries.""" targets = [] # Swap(0,1), |00> state targets.append(np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]])) # Swap(0,1).(I^X), |10> state targets.append(np.array([[0, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 0]])) return targets def swap_gate_circuits_nondeterministic(final_measure=True): """SWAP-gate test circuits with non-deterministic counts.""" circuits = [] qr = QuantumRegister(3) if final_measure: cr = ClassicalRegister(3) regs = (qr, cr) else: regs = (qr, ) # initial state as |10+> # Swap(0,1).(X^I^H), Permutation (0,1,2) -> (1,0,2) circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.barrier(qr) circuit.x(qr[2]) circuit.barrier(qr) circuit.swap(qr[0], qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Swap(0,2).(X^I^H), # Permutation (0,1,2) -> (2,1,0), circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.barrier(qr) circuit.x(qr[2]) circuit.barrier(qr) circuit.swap(qr[0], qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Swap(2,0).Swap(0,1).(X^I^H), Permutation (0,1,2) -> (2,0,1) circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.barrier(qr) circuit.x(qr[2]) circuit.barrier(qr) circuit.swap(qr[0], qr[1]) circuit.barrier(qr) circuit.swap(qr[2], qr[0]) circuit.barrier(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) return circuits def swap_gate_counts_nondeterministic(shots, hex_counts=True): """SWAP-gate circuits reference counts.""" targets = [] if hex_counts: # initial state as |10+> # Swap(0,1).(X^I^H), Permutation (0,1,2) -> (1,0,2) targets.append({'0x4': shots / 2, '0x6': shots / 2}) # Swap(0,2).(X^I^H), # Permutation (0,1,2) -> (2,1,0), targets.append({'0x1': shots / 2, '0x5': shots / 2}) # Swap(2,0).Swap(0,1).(X^I^H), Permutation (0,1,2) -> (2,0,1) targets.append({'0x1': shots / 2, '0x3': shots / 2}) else: # initial state as |10+> # Swap(0,1).(X^I^H), Permutation (0,1,2) -> (1,0,2) targets.append({'100': shots / 2, '110': shots / 2}) # Swap(0,2).(X^I^H), # Permutation (0,1,2) -> (2,1,0), targets.append({'001': shots / 2, '101': shots / 2}) # Swap(2,0).Swap(0,1).(X^I^H), Permutation (0,1,2) -> (2,0,1) targets.append({'001': shots / 2, '011': shots / 2}) return targets def swap_gate_statevector_nondeterministic(): """SWAP-gate circuits reference statevectors.""" targets = [] # initial state as |10+> # Swap(0,1).(X^I^H), Permutation (0,1,2) -> (1,0,2), |1+0> targets.append(np.array([0, 0, 0, 0, 1, 0, 1, 0]) / np.sqrt(2)) # Swap(0,2).(X^I^H), # Permutation (0,1,2) -> (2,1,0), targets.append(np.array([0, 1, 0, 0, 0, 1, 0, 0]) / np.sqrt(2)) # Swap(2,0).Swap(0,1).(X^I^H), Permutation (0,1,2) -> (2,0,1) targets.append(np.array([0, 1, 0, 1, 0, 0, 0, 0]) / np.sqrt(2)) return targets def swap_gate_unitary_nondeterministic(): """SWAP-gate circuits reference unitaries.""" targets = [] # initial state as |10+> # Swap(0,1).(X^I^H), Permutation (0,1,2) -> (1,0,2) targets.append(np.array([[0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 1, -1, 0, 0], [0, 0, 0, 0, 0, 0, 1, -1], [1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0], [1, -1, 0, 0, 0, 0, 0, 0], [0, 0, 1, -1, 0, 0, 0, 0]]) / np.sqrt(2)) # Swap(0,2).(X^I^H), # Permutation (0,1,2) -> (2,1,0), targets.append(np.array([[0, 0, 0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, -1, 0, 0], [1, -1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, -1], [0, 0, 1, -1, 0, 0, 0, 0]]) / np.sqrt(2)) # Swap(2,0).Swap(0,1).(X^I^H), Permutation (0,1,2) -> (2,0,1) targets.append(np.array([[0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 1, -1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, -1], [1, 1, 0, 0, 0, 0, 0, 0], [1, -1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 1, -1, 0, 0, 0, 0]]) / np.sqrt(2)) return targets
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test circuits and reference outputs for standard algorithms. """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit # Backwards compatibility for Terra <= 0.13 if not hasattr(QuantumCircuit, 'i'): QuantumCircuit.i = QuantumCircuit.iden def grovers_circuit(final_measure=True, allow_sampling=True): """Testing a circuit originated in the Grover algorithm""" circuits = [] # 6-qubit grovers qr = QuantumRegister(6) if final_measure: cr = ClassicalRegister(2) regs = (qr, cr) else: regs = (qr, ) circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.h(qr[1]) circuit.x(qr[2]) circuit.x(qr[3]) circuit.x(qr[0]) circuit.cx(qr[0], qr[2]) circuit.x(qr[0]) circuit.cx(qr[1], qr[3]) circuit.ccx(qr[2], qr[3], qr[4]) circuit.cx(qr[1], qr[3]) circuit.x(qr[0]) circuit.cx(qr[0], qr[2]) circuit.x(qr[0]) circuit.x(qr[1]) circuit.x(qr[4]) circuit.h(qr[4]) circuit.ccx(qr[0], qr[1], qr[4]) circuit.h(qr[4]) circuit.x(qr[0]) circuit.x(qr[1]) circuit.x(qr[4]) circuit.h(qr[0]) circuit.h(qr[1]) circuit.h(qr[4]) if final_measure: circuit.barrier(qr) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[1]) if not allow_sampling: circuit.barrier(qr) circuit.i(qr) circuits.append(circuit) return circuits def grovers_counts(shots, hex_counts=True): """Reference counts for Grovers algorithm""" targets = [] if hex_counts: # 6-qubit grovers targets.append({'0x0': 5 * shots / 8, '0x1': shots / 8, '0x2': shots / 8, '0x3': shots / 8}) else: # 6-qubit grovers targets.append({'00': 5 * shots / 8, '01': shots / 8, '10': shots / 8, '11': shots / 8}) return targets def teleport_circuit(): """Testing a circuit originated in the teleportation algorithm""" circuits = [] # Classic 3-qubit teleportation qr = QuantumRegister(3) c0 = ClassicalRegister(1) c1 = ClassicalRegister(1) c2 = ClassicalRegister(1) # Compiles to creg order [c2, c1, c0] circuit = QuantumCircuit(qr, c0, c1, c2) # Teleport the |0> state from qr[0] to qr[2] circuit.h(qr[1]) circuit.cx(qr[1], qr[2]) circuit.barrier(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[0]) circuit.measure(qr[0], c0[0]) circuit.measure(qr[1], c1[0]) circuit.z(qr[2]).c_if(c0, 1) circuit.x(qr[2]).c_if(c1, 1) circuit.measure(qr[2], c2[0]) circuits.append(circuit) return circuits def teleport_counts(shots, hex_counts=True): """Reference counts for teleport circuits""" targets = [] if hex_counts: # Classical 3-qubit teleport targets.append({'0x0': shots / 4, '0x1': shots / 4, '0x2': shots / 4, '0x3': shots / 4}) else: # Classical 3-qubit teleport targets.append({'0 0 0': shots / 4, '0 0 1': shots / 4, '0 1 0': shots / 4, '0 1 1': shots / 4}) return targets
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test circuits and reference outputs for conditional gates. """ import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Instruction def add_conditional_x(circuit, qreg, creg, val, conditional_type): """Add a conditional instruction to a circuit. Args: circuit (QuantumCircuit): circuit to add instruction to. qreg (QuantumRegister): qubit to apply conditional X to creg (ClassicalRegister): classical reg to condition on val (int): Classical reg value to condition on. conditional_type (string): instruction type to add conditional X as. Conditional type can be 'gate', 'unitary', 'kraus', 'superop' and will apply a conditional X-gate in that representation """ # X-gate matrix x_mat = np.array([[0, 1], [1, 0]], dtype=complex) x_superop = Instruction('superop', 1, 0, [np.kron(x_mat, x_mat)]) x_kraus = Instruction('kraus', 1, 0, [x_mat]) if conditional_type == 'unitary': circuit.unitary(x_mat, [qreg]).c_if(creg, val) elif conditional_type == 'kraus': circuit.append(x_kraus, [qreg]).c_if(creg, val) elif conditional_type == 'superop': circuit.append(x_superop, [qreg]).c_if(creg, val) else: circuit.x(qreg).c_if(creg, val) # ========================================================================== # Conditionals on 1-bit register # ========================================================================== def conditional_circuits_1bit(final_measure=True, conditional_type='gate'): """Conditional gates on single bit classical register.""" circuits = [] qr = QuantumRegister(1) cond = ClassicalRegister(1, 'cond') if final_measure: cr = ClassicalRegister(1, 'meas') regs = (qr, cr, cond) else: regs = (qr, cond) # Conditional on 0 (cond = 0) circuit = QuantumCircuit(*regs) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 0, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 0 (cond = 1) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[0]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 0, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 1 (cond = 0) circuit = QuantumCircuit(*regs) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 1, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 1 (cond = 1) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[0]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 1, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def conditional_counts_1bit(shots, hex_counts=True): """Conditional circuits reference counts.""" targets = [] if hex_counts: # Conditional on 0 (cond = 0), result "0 1" targets.append({'0x1': shots}) # Conditional on 0 (cond = 1), result "1 0" targets.append({'0x2': shots}) # Conditional on 1 (cond = 0), # result "0 0" targets.append({'0x0': shots}) # Conditional on 1 (cond = 1), # result "1 1" targets.append({'0x3': shots}) else: # Conditional on 0 (cond = 0), result "0 1" targets.append({'0 1': shots}) # Conditional on 0 (cond = 1), result "1 0" targets.append({'1 0': shots}) # Conditional on 1 (cond = 0), # result "0 0" targets.append({'0 0': shots}) # Conditional on 1 (cond = 1), # result "1 1" targets.append({'1 1': shots}) return targets def conditional_statevector_1bit(): """Conditional circuits reference statevector.""" targets = [] # Conditional on 0 (cond = 0) targets.append(np.array([0, 1])) # Conditional on 0 (cond = 1) targets.append(np.array([1, 0])) # Conditional on 1 (cond = 0) targets.append(np.array([1, 0])) # Conditional on 1 (cond = 1) targets.append(np.array([0, 1])) return targets # ========================================================================== # Conditionals on 2-bit register # ========================================================================== def conditional_circuits_2bit(final_measure=True, conditional_type='gate'): """Conditional test circuits on 2-bit classical register.""" circuits = [] qr = QuantumRegister(1) cond = ClassicalRegister(2, 'cond') if final_measure: cr = ClassicalRegister(1, 'meas') regs = (qr, cr, cond) else: regs = (qr, cond) # Conditional on 00 (cr = 00) circuit = QuantumCircuit(*regs) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 0, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 00 (cr = 01) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[0]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 0, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 00 (cr = 10) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[1]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 0, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 00 (cr = 11) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[0]) circuit.measure(qr[0], cond[1]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 0, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 01 (cr = 00) circuit = QuantumCircuit(*regs) add_conditional_x(circuit, qr[0], cond, 1, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 01 (cr = 01) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[0]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 1, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 01 (cr = 10) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[1]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 1, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 01 (cr = 11) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[0]) circuit.measure(qr[0], cond[1]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 1, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 10 (cr = 00) circuit = QuantumCircuit(*regs) circuit.x(qr).c_if(cond, 2) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 10 (cr = 01) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[0]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 2, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 10 (cr = 10) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[1]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 2, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 10 (cr = 11) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[0]) circuit.measure(qr[0], cond[1]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 2, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 11 (cr = 00) circuit = QuantumCircuit(*regs) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 3, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 11 (cr = 01) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[0]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 3, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 11 (cr = 10) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[1]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 3, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Conditional on 11 (cr = 11) circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.measure(qr[0], cond[0]) circuit.measure(qr[0], cond[1]) circuit.x(qr) circuit.barrier(qr) add_conditional_x(circuit, qr[0], cond, 3, conditional_type) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def conditional_counts_2bit(shots, hex_counts=True): """2-bit conditional circuits reference counts.""" targets = [] if hex_counts: # Conditional on 00 (cr = 00), result "00 1" targets.append({'0x1': shots}) # Conditional on 00 (cr = 01), result "01 0" targets.append({'0x2': shots}) # Conditional on 00 (cr = 10), result "10 0" targets.append({'0x4': shots}) # Conditional on 00 (cr = 11), result "11 0" targets.append({'0x6': shots}) # Conditional on 01 (cr = 00), result "00 0" targets.append({'0x0': shots}) # Conditional on 01 (cr = 01), result "01 1" targets.append({'0x3': shots}) # Conditional on 01 (cr = 10), result "10 0" targets.append({'0x4': shots}) # Conditional on 01 (cr = 11), result "11 0" targets.append({'0x6': shots}) # Conditional on 10 (cr = 00), result "00 0" targets.append({'0x0': shots}) # Conditional on 10 (cr = 01), result "01 0" targets.append({'0x2': shots}) # Conditional on 10 (cr = 10), result "10 1" targets.append({'0x5': shots}) # Conditional on 10 (cr = 11), result "11 0" targets.append({'0x6': shots}) # Conditional on 11 (cr = 00), result "00 0" targets.append({'0x0': shots}) # Conditional on 11 (cr = 01), result "01 0" targets.append({'0x2': shots}) # Conditional on 11 (cr = 10), result "10 0" targets.append({'0x4': shots}) # Conditional on 11 (cr = 11), result "11 1" targets.append({'0x7': shots}) else: # Conditional on 00 (cr = 00), result "00 1" targets.append({'00 1': shots}) # Conditional on 00 (cr = 01), result "01 0" targets.append({'01 0': shots}) # Conditional on 00 (cr = 10), result "10 0" targets.append({'10 0': shots}) # Conditional on 00 (cr = 11), result "11 0" targets.append({'11 0': shots}) # Conditional on 01 (cr = 00), result "00 0" targets.append({'00 0': shots}) # Conditional on 01 (cr = 01), result "01 1" targets.append({'01 1': shots}) # Conditional on 01 (cr = 10), result "10 0" targets.append({'10 0': shots}) # Conditional on 01 (cr = 11), result "11 0" targets.append({'11 0': shots}) # Conditional on 10 (cr = 00), result "00 0" targets.append({'00 0': shots}) # Conditional on 10 (cr = 01), result "01 0" targets.append({'01 0': shots}) # Conditional on 10 (cr = 10), result "10 1" targets.append({'10 0': shots}) # Conditional on 10 (cr = 11), result "11 0" targets.append({'11 0': shots}) # Conditional on 11 (cr = 00), result "00 0" targets.append({'00 0': shots}) # Conditional on 11 (cr = 01), result "01 0" targets.append({'01 0': shots}) # Conditional on 11 (cr = 10), result "10 0" targets.append({'10 0': shots}) # Conditional on 11 (cr = 11), result "11 1" targets.append({'11 1': shots}) return targets def conditional_statevector_2bit(): """2-bit conditional circuits reference statevector.""" state_0 = np.array([1, 0]) state_1 = np.array([0, 1]) targets = [] # Conditional on 00 (cr = 00) targets.append(state_1) # Conditional on 00 (cr = 01) targets.append(state_0) # Conditional on 00 (cr = 10) targets.append(state_0) # Conditional on 00 (cr = 11) targets.append(state_0) # Conditional on 01 (cr = 00) targets.append(state_0) # Conditional on 01 (cr = 01) targets.append(state_1) # Conditional on 01 (cr = 10) targets.append(state_0) # Conditional on 01 (cr = 11) targets.append(state_0) # Conditional on 10 (cr = 00) targets.append(state_0) # Conditional on 10 (cr = 01) targets.append(state_0) # Conditional on 10 (cr = 10) targets.append(state_1) # Conditional on 10 (cr = 11) targets.append(state_0) # Conditional on 11 (cr = 00) targets.append(state_0) # Conditional on 11 (cr = 01) targets.append(state_0) # Conditional on 11 (cr = 10) targets.append(state_0) # Conditional on 11 (cr = 11) targets.append(state_1) return targets
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test circuits and reference outputs for diagonal instruction. """ import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister # Backwards compatibility for Terra <= 0.13 if not hasattr(QuantumCircuit, 'diagonal'): QuantumCircuit.diagonal = QuantumCircuit.diag_gate def diagonal_gate_circuits_deterministic(final_measure=True): """Diagonal gate test circuits with deterministic count output.""" circuits = [] qr = QuantumRegister(2, 'qr') if final_measure: cr = ClassicalRegister(2, 'cr') regs = (qr, cr) else: regs = (qr, ) # 4 x Swap |00> <--> |01> states # 4 x Swap |00> <--> |10> states arg = [1, -1] for qubit in [0, 1]: for diag in [arg, np.array(arg), np.array(arg, dtype=float), np.array(arg, dtype=complex)]: circuit = QuantumCircuit(*regs) circuit.h(qubit) circuit.diagonal(list(diag), [qubit]) circuit.h(qubit) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # 4 x Swap |00> <--> |11> states arg = [1, -1, -1, 1] for diag in [arg, np.array(arg), np.array(arg, dtype=float), np.array(arg, dtype=complex)]: circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.diagonal(list(diag), qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CS01.XX, exp(-1j * np.pi/k)|11> state for diag in [np.array([1, 1, 1, np.exp(-1j * np.pi / k)]) for k in [10, 100, 1000, 10000]]: circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.diagonal(list(diag), qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def diagonal_gate_counts_deterministic(shots, hex_counts=True): """Diagonal gate circuits reference counts.""" targets = [] if hex_counts: # Swap |00> <--> |01> states targets += 4 * [{'0x1': shots}] # Swap |00> <--> |10> states targets += 4 * [{'0x2': shots}] # Swap |00> <--> |11> states targets += 4 * [{'0x3': shots}] # CS01.XX, exp(-1j * np.pi/N)|11> state targets += 4 * [{'0x3': shots}] else: # Swap |00> <--> |01> states targets += 4 * [{'01': shots}] # Swap |00> <--> |10> states targets += 4 * [{'10': shots}] # Swap |00> <--> |11> states targets += 4 * [{'11': shots}] # CS01.XX, exp(-1j * np.pi/k)|11> state targets += 4 * [{'11': shots}] return targets def diagonal_gate_statevector_deterministic(): """Diagonal gate test circuits with deterministic counts.""" targets = [] # Swap |00> <--> |01> states targets += 4 * [np.array([0, 1, 0, 0])] # Swap |00> <--> |10> states targets += 4 * [np.array([0, 0, 1, 0])] # Swap |00> <--> |11> states targets += 4 * [np.array([0, 0, 0, 1])] # CS01.XX, exp(-1j * np.pi/k)|11> state targets += [np.array([0, 0, 0, np.exp(-1j * np.pi / k)]) for k in [10, 100, 1000, 10000]] return targets def diagonal_gate_unitary_deterministic(): """Diagonal gate circuits reference unitaries.""" targets = [] # Swap |00> <--> |01> states targets += 4 * [np.array([[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])] # Swap |00> <--> |10> states targets += 4 * [np.array([[0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0]])] # Swap |00> <--> |11> states targets += 4 * [np.array([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]])] # CS01.XX, 1j|11> state targets += [np.array([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [np.exp(-1j * np.pi / k), 0, 0, 0]]) for k in [10, 100, 1000, 10000]] return targets
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test circuits and reference outputs for initialize instruction. """ from numpy import array, sqrt from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit def initialize_circuits_w_1(init_state, final_measure=True): """Initialize test circuits""" circuits = [] qr = QuantumRegister(3) if final_measure: cr = ClassicalRegister(3) regs = (qr, cr) else: regs = (qr, ) # Start with |+++> state # Initialize qr[i] to |1> for i=0,1,2 for qubit in range(3): circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.h(qr[1]) circuit.h(qr[2]) circuit.initialize(init_state, [qr[qubit]]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def initialize_circuits_w_2(init_state, final_measure=True): """Initialize test circuits""" circuits = [] qr = QuantumRegister(3) if final_measure: cr = ClassicalRegister(3) regs = (qr, cr) else: regs = (qr, ) # Start with |+++> state # Initialize qr[i] to |1> and qr[j] to |0> # For [i,j] = [0,1], [1, 0], [0, 2], [2, 0], [1, 2], [2, 1] for qubit_i in range(3): for qubit_j in range(3): if (qubit_i != qubit_j): circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.h(qr[1]) circuit.h(qr[2]) circuit.initialize(init_state, [qr[qubit_i], qr[qubit_j]]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def initialize_circuits_1(final_measure=True): """Initialize test circuits""" circuits = [] qr = QuantumRegister(3) if final_measure: cr = ClassicalRegister(3) regs = (qr, cr) else: regs = (qr, ) # Start with |+++> state # Initialize qr[i] to |1> for i=0,1,2 for qubit in range(3): circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.h(qr[1]) circuit.h(qr[2]) circuit.initialize([0, 1], [qr[qubit]]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Start with |+++> state # Initialize qr[i] to |1> and qr[j] to |0> # For [i,j] = [0,1], [1, 0], [0, 2], [2, 0], [1, 2], [2, 1] for qubit_i in range(3): for qubit_j in range(3): if (qubit_i != qubit_j): circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.h(qr[1]) circuit.h(qr[2]) circuit.initialize([0, 1, 0, 0], [qr[qubit_i], qr[qubit_j]]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Start with |+++> state # Initialize qr[i] to |1>, qr[j] to |0> and qr[k] to |-> # For [i,j,k] = [0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0] for qubit_i in range(3): for qubit_j in range(3): for qubit_k in range(3): if (qubit_i != qubit_j) & (qubit_i != qubit_k) & (qubit_k != qubit_j): circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.h(qr[1]) circuit.h(qr[2]) circuit.initialize([0, 1, 0, 0, 0, -1, 0, 0] / sqrt(2), \ [qr[qubit_i], qr[qubit_j], qr[qubit_k]]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def initialize_counts_1(shots, hex_counts=True): """Initialize test circuits reference counts.""" targets = [] if hex_counts: # Initialize 0 to |1> from |+++> targets.append({'0x1': shots/4, '0x3': shots/4, '0x5': shots/4, '0x7': shots/4}) # Initialize 1 to |1> from |+++> targets.append({'0x2': shots/4, '0x3': shots/4, '0x6': shots/4, '0x7': shots/4}) # Initialize 2 to |1> from |+++> targets.append({'0x4': shots/4, '0x5': shots/4, '0x6': shots/4, '0x7': shots/4}) # Initialize 0,1 to |01> from |+++> targets.append({'0x1': shots/2, '0x5': shots/2}) # Initialize 0,2 to |01> from |+++> targets.append({'0x1': shots/2, '0x3': shots/2}) # Initialize 1,0 to |01> from |+++> targets.append({'0x2': shots/2, '0x6': shots/2}) # Initialize 1,2 to |01> from |+++> targets.append({'0x2': shots/2, '0x3': shots/2}) # Initialize 2,0 to |01> from |+++> targets.append({'0x4': shots/2, '0x6': shots/2}) # Initialize 2,1 to |01> from |+++> targets.append({'0x4': shots/2, '0x5': shots/2}) # Initialize 0,1,2 to |01-> from |+++> targets.append({'0x1': shots/2, '0x5': shots/2}) # Initialize 0,2,1 to |01-> from |+++> targets.append({'0x1': shots/2, '0x3': shots/2}) # Initialize 1,0,2 to |01-> from |+++> targets.append({'0x2': shots/2, '0x6': shots/2}) # Initialize 1,2,0 to |01-> from |+++> targets.append({'0x2': shots/2, '0x3': shots/2}) # Initialize 2,0,1 to |01-> from |+++> targets.append({'0x4': shots/2, '0x6': shots/2}) # Initialize 2,1,0 to |01-> from |+++> targets.append({'0x4': shots/2, '0x5': shots/2}) else: # Initialize 0 to |1> from |+++> targets.append({'001': shots/4, '011': shots/4, '101': shots/4, '111': shots/4}) # Initialize 1 to |1> from |+++> targets.append({'010': shots/4, '011': shots/4, '110': shots/4, '111': shots/4}) # Initialize 2 to |1> from |+++> targets.append({'100': shots/4, '101': shots/4, '110': shots/4, '111': shots/4}) # Initialize 0,1 to |01> from |+++> targets.append({'001': shots/2, '101': shots/2}) # Initialize 0,2 to |01> from |+++> targets.append({'001': shots/2, '011': shots/2}) # Initialize 1,0 to |01> from |+++> targets.append({'010': shots/2, '110': shots/2}) # Initialize 1,2 to |01> from |+++> targets.append({'010': shots/2, '011': shots/2}) # Initialize 2,0 to |01> from |+++> targets.append({'100': shots/2, '110': shots/2}) # Initialize 2,1 to |01> from |+++> targets.append({'100': shots/2, '101': shots/2}) # Initialize 0,1,2 to |01-> from |+++> targets.append({'001': shots/2, '101': shots/2}) # Initialize 0,2,1 to |01-> from |+++> targets.append({'001': shots/2, '011': shots/2}) # Initialize 1,0,2 to |01-> from |+++> targets.append({'010': shots/2, '110': shots/2}) # Initialize 1,2,0 to |01-> from |+++> targets.append({'010': shots/2, '011': shots/2}) # Initialize 2,0,1 to |01-> from |+++> targets.append({'100': shots/2, '110': shots/2}) # Initialize 2,1,0 to |01-> from |+++> targets.append({'100': shots/2, '101': shots/2}) return targets def initialize_statevector_1(): """Initialize test circuits reference counts.""" targets = [] # Start with |+++> state # Initialize qr[i] to |1> for i=0,1,2 targets.append(array([0. +0.j, 0.5+0.j, 0. +0.j, 0.5+0.j, 0. +0.j, 0.5+0.j, 0. +0.j, 0.5+0.j])) targets.append(array([0. +0.j, 0. +0.j, 0.5+0.j, 0.5+0.j, 0. +0.j, 0. +0.j, 0.5+0.j, 0.5+0.j])) targets.append(array([0. +0.j, 0. +0.j, 0. +0.j, 0. +0.j, 0.5+0.j, 0.5+0.j, 0.5+0.j, 0.5+0.j])) # Start with |+++> state # Initialize qr[i] to |1> and qr[j] to |0> # For [i,j] = [0,1], [1, 0], [0, 2], [2, 0], [1, 2], [2, 1] targets.append(array([0. + 0.j, 1.0 + 0.j, 0. + 0.j, 0. + 0.j, \ 0. + 0.j, 1.0 + 0.j, 0. + 0.j, 0. + 0.j] / sqrt(2))) targets.append(array([0. + 0.j, 1.0 + 0.j, 0. + 0.j, 1.0 + 0.j, \ 0. + 0.j, 0. + 0.j, 0. + 0.j, 0. + 0.j] / sqrt(2))) targets.append(array([0. + 0.j, 0. + 0.j, 1.0 + 0.j, 0. + 0.j, \ 0. + 0.j, 0. + 0.j, 1.0 + 0.j, 0. + 0.j] / sqrt(2))) targets.append(array([0. + 0.j, 0. + 0.j, 1.0 + 0.j, 1.0 + 0.j, \ 0. + 0.j, 0. + 0.j, 0 + 0.j, 0. + 0.j] / sqrt(2))) targets.append(array([0. + 0.j, 0. + 0.j, 0 + 0.j, 0. + 0.j, \ 1.0 + 0.j, 0. + 0.j, 1.0 + 0.j, 0. + 0.j] / sqrt(2))) targets.append(array([0. + 0.j, 0. + 0.j, 0 + 0.j, 0. + 0.j, \ 1.0 + 0.j, 1.0 + 0.j, 0. + 0.j, 0. + 0.j] / sqrt(2))) # Start with |+++> state # Initialize qr[i] to |1>, qr[j] to |0> and qr[k] to |-> # For [i,j,k] = [0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0] targets.append(array([0. + 0.j, 1.0 + 0.j, 0. + 0.j, 0. + 0.j, \ 0. + 0.j, -1.0 + 0.j, 0. + 0.j, 0. + 0.j] / sqrt(2))) targets.append(array([0. + 0.j, 1.0 + 0.j, 0. + 0.j, -1.0 + 0.j, 0. + 0.j, 0. + 0.j, 0. + 0.j, 0. + 0.j] / sqrt(2))) targets.append(array([0. + 0.j, 0. + 0.j, 1.0 + 0.j, 0. + 0.j, \ 0. + 0.j, 0. + 0.j, -1.0 + 0.j, 0. + 0.j] / sqrt(2))) targets.append(array([0. + 0.j, 0. + 0.j, 1.0 + 0.j, -1.0 + 0.j, \ 0. + 0.j, 0. + 0.j, 0. + 0.j, 0. + 0.j] / sqrt(2))) targets.append(array([0. + 0.j, 0. + 0.j, 0. + 0.j, 0. + 0.j, \ 1.0 + 0.j, 0. + 0.j, -1.0 + 0.j, 0. + 0.j] / sqrt(2))) targets.append(array([0. + 0.j, 0. + 0.j, 0. + 0.j, 0. + 0.j, \ 1.0 + 0.j, -1.0 + 0.j, 0. + 0.j, 0. + 0.j] / sqrt(2))) return targets def initialize_circuits_2(final_measure=True): """Initialize test circuits""" circuits = [] qr = QuantumRegister(2) if final_measure: cr = ClassicalRegister(2) regs = (qr, cr) else: regs = (qr, ) # Initialize 0 to |1> from |++> circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.initialize([0, 1], [qr[0]]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Initialize 1 to |1> from |++> circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.initialize([0, 1], [qr[1]]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def initialize_counts_2(shots, hex_counts=True): """Initialize test circuits reference counts.""" targets = [] if hex_counts: # Initialize 0 to |1> from |++> targets.append({'0x1': shots / 2, '0x3': shots / 2}) # Initialize 1 to |1> from |++> targets.append({'0x2': shots / 2, '0x3': shots / 2}) else: # Initialize 0 to |1> from |++> targets.append({'01': shots / 2, '11': shots / 2}) # Initialize 1 to |1> from |++> targets.append({'10': shots / 2, '11': shots / 2}) return targets def initialize_statevector_2(): """Initialize test circuits reference counts.""" targets = [] # Initialize 0 to |1> from |++> targets.append(array([0, 1, 0, 1]) / sqrt(2)) # Initialize 1 to |1> from |++> targets.append(array([0, 0, 1, 1]) / sqrt(2)) return targets # ========================================================================== # Sampling optimization # ========================================================================== def initialize_sampling_optimization(): """Test sampling optimization""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) # The optimization should not be triggerred # because the initialize operation performs randomizations qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.initialize([1, 0], [qr[0]]) qc.measure(qr, cr) return [qc] def initialize_counts_sampling_optimization(shots, hex_counts=True): """Sampling optimization counts""" if hex_counts: return [{'0x0': shots/2, '0x2': shots/2}] else: return [{'0x00': shots/2, '0x10': shots/2}]
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ QasmSimulator kraus error NoiseModel integration tests """ from test.terra.utils.utils import list2dict from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors.standard_errors import amplitude_damping_error # Backwards compatibility for Terra <= 0.13 if not hasattr(QuantumCircuit, 'i'): QuantumCircuit.i = QuantumCircuit.iden # ========================================================================== # Amplitude damping error # ========================================================================== def kraus_gate_error_circuits(): """Kraus gate error noise model circuits""" circuits = [] # Repeated amplitude damping to diagonal state qr = QuantumRegister(1, 'qr') cr = ClassicalRegister(1, 'cr') circuit = QuantumCircuit(qr, cr) circuit.x(qr) # prepare + state for _ in range(30): # Add noisy identities circuit.barrier(qr) circuit.i(qr) circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def kraus_gate_error_noise_models(): """Kraus gate error noise models""" noise_models = [] # Amplitude damping error on "id" error = amplitude_damping_error(0.75, 0.25) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error, 'id') noise_models.append(noise_model) return noise_models def kraus_gate_error_counts(shots, hex_counts=True): """Kraus gate error circuits reference counts""" counts_lists = [] # 100% all-qubit Pauli error on "id" gates counts = [3 * shots / 4, shots / 4, 0, 0] counts_lists.append(counts) # Convert to counts dict return [list2dict(i, hex_counts) for i in counts_lists]
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test circuits and reference outputs for measure instruction. """ from numpy import array from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Instruction # Backwards compatibility for Terra <= 0.13 if not hasattr(QuantumCircuit, 'i'): QuantumCircuit.i = QuantumCircuit.iden # ========================================================================== # Single-qubit measurements with deterministic output # ========================================================================== def measure_circuits_deterministic(allow_sampling=True): """Measure test circuits with deterministic count output.""" circuits = [] qr = QuantumRegister(2) cr = ClassicalRegister(2) # Measure |00> state circuit = QuantumCircuit(qr, cr) circuit.barrier(qr) circuit.measure(qr, cr) if not allow_sampling: circuit.barrier(qr) circuit.i(qr) circuits.append(circuit) # Measure |01> state circuit = QuantumCircuit(qr, cr) circuit.x(qr[0]) circuit.barrier(qr) circuit.measure(qr, cr) if not allow_sampling: circuit.barrier(qr) circuit.i(qr) circuits.append(circuit) # Measure |10> state circuit = QuantumCircuit(qr, cr) circuit.x(qr[1]) circuit.barrier(qr) circuit.measure(qr, cr) if not allow_sampling: circuit.barrier(qr) circuit.i(qr) circuits.append(circuit) # Measure |11> state circuit = QuantumCircuit(qr, cr) circuit.x(qr) circuit.barrier(qr) circuit.measure(qr, cr) if not allow_sampling: circuit.barrier(qr) circuit.i(qr) circuits.append(circuit) return circuits def measure_counts_deterministic(shots, hex_counts=True): """Measure test circuits reference counts.""" targets = [] if hex_counts: # Measure |00> state targets.append({'0x0': shots}) # Measure |01> state targets.append({'0x1': shots}) # Measure |10> state targets.append({'0x2': shots}) # Measure |11> state targets.append({'0x3': shots}) else: # Measure |00> state targets.append({'00': shots}) # Measure |01> state targets.append({'01': shots}) # Measure |10> state targets.append({'10': shots}) # Measure |11> state targets.append({'11': shots}) return targets def measure_memory_deterministic(shots, hex_counts=True): """Measure test circuits reference memory.""" targets = [] if hex_counts: # Measure |00> state targets.append(shots * ['0x0']) # Measure |01> state targets.append(shots * ['0x1']) # Measure |10> state targets.append(shots * ['0x2']) # Measure |11> state targets.append(shots * ['0x3']) else: # Measure |00> state targets.append(shots * ['00']) # Measure |01> state targets.append(shots * ['01']) # Measure |10> state targets.append(shots * ['10']) # Measure |11> state targets.append(shots * ['11']) return targets def measure_statevector_deterministic(): """Measure test circuits reference counts.""" targets = [] # Measure |00> state targets.append(array([1, 0, 0, 0])) # Measure |01> state targets.append(array([0, 1, 0, 0])) # Measure |10> state targets.append(array([0, 0, 1, 0])) # Measure |11> state targets.append(array([0, 0, 0, 1])) return targets # ========================================================================== # Single-qubit measurements with non-deterministic output # ========================================================================== def measure_circuits_nondeterministic(allow_sampling=True): """"Measure test circuits with non-deterministic count output.""" circuits = [] qr = QuantumRegister(2) cr = ClassicalRegister(2) # Measure |++> state (sampled) circuit = QuantumCircuit(qr, cr) circuit.h(qr) circuit.barrier(qr) circuit.measure(qr, cr) if not allow_sampling: circuit.barrier(qr) circuit.i(qr) circuits.append(circuit) return circuits def measure_counts_nondeterministic(shots, hex_counts=True): """Measure test circuits reference counts.""" targets = [] if hex_counts: # Measure |++> state targets.append({'0x0': shots / 4, '0x1': shots / 4, '0x2': shots / 4, '0x3': shots / 4}) else: # Measure |++> state targets.append({'00': shots / 4, '01': shots / 4, '10': shots / 4, '11': shots / 4}) return targets # ========================================================================== # Multi-qubit measurements with deterministic output # ========================================================================== def multiqubit_measure_circuits_deterministic(allow_sampling=True): """Multi-qubit measure test circuits with deterministic count output.""" circuits = [] def measure_n(num_qubits): """Multi-qubit measure instruction.""" return Instruction("measure", num_qubits, num_qubits, []) qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.x(qr[1]) circuit.barrier(qr) circuit.append(measure_n(2), [0, 1], [0, 1]) if not allow_sampling: circuit.barrier(qr) circuit.i(qr) circuits.append(circuit) # 3-qubit measure |101> qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr, cr) circuit.x(qr[0]) circuit.x(qr[2]) circuit.barrier(qr) circuit.append(measure_n(3), [0, 1, 2], [0, 1, 2]) if not allow_sampling: circuit.barrier(qr) circuit.i(qr) circuits.append(circuit) # 4-qubit measure |1010> qr = QuantumRegister(4) cr = ClassicalRegister(4) circuit = QuantumCircuit(qr, cr) circuit.x(qr[1]) circuit.x(qr[3]) circuit.barrier(qr) circuit.append(measure_n(4), [0, 1, 2, 3], [0, 1, 2, 3]) if not allow_sampling: circuit.barrier(qr) circuit.i(qr) circuits.append(circuit) return circuits def multiqubit_measure_counts_deterministic(shots, hex_counts=True): """Multi-qubit measure test circuits reference counts.""" targets = [] if hex_counts: # 2-qubit measure |10> targets.append({'0x2': shots}) # 3-qubit measure |101> targets.append({'0x5': shots}) # 4-qubit measure |1010> targets.append({'0xa': shots}) else: # 2-qubit measure |10> targets.append({'10': shots}) # 3-qubit measure |101> targets.append({'101': shots}) # 4-qubit measure |1010> targets.append({'1010': shots}) return targets def multiqubit_measure_memory_deterministic(shots, hex_counts=True): """Multi-qubit measure test circuits reference memory.""" targets = [] if hex_counts: # 2-qubit measure |10> targets.append(shots * ['0x2']) # 3-qubit measure |101> targets.append(shots * ['0x5']) # 4-qubit measure |1010> targets.append(shots * ['0xa']) else: # 2-qubit measure |10> targets.append(shots * ['10']) # 3-qubit measure |101> targets.append(shots * ['101']) # 4-qubit measure |1010> targets.append(shots * ['1010']) return targets def multiqubit_measure_statevector_deterministic(): """Multi-qubit measure test circuits reference counts.""" targets = [] # 2-qubit measure |10> targets.append(array([0, 0, 1, 0])) # 3-qubit measure |101> targets.append(array([0, 0, 0, 0, 0, 1, 0, 0])) # 4-qubit measure |1010> targets.append(array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0])) return targets # ========================================================================== # Multi-qubit measurements with non-deterministic output # ========================================================================== def multiqubit_measure_circuits_nondeterministic(allow_sampling=True): """Multi-qubit measure test circuits with non-deterministic count output.""" circuits = [] def measure_n(num_qubits): """Multi-qubit measure instruction.""" return Instruction("measure", num_qubits, num_qubits, []) # 2-qubit measure |++> qr = QuantumRegister(2) cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.h(qr[1]) circuit.barrier(qr) circuit.append(measure_n(2), [0, 1], [0, 1]) if not allow_sampling: circuit.barrier(qr) circuit.i(qr) circuits.append(circuit) # 3-qubit measure |++0> qr = QuantumRegister(3) cr = ClassicalRegister(3) circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.h(qr[1]) circuit.barrier(qr) circuit.append(measure_n(3), [0, 1, 2], [0, 1, 2]) if not allow_sampling: circuit.barrier(qr) circuit.i(qr) circuits.append(circuit) return circuits def multiqubit_measure_counts_nondeterministic(shots, hex_counts=True): """Multi-qubit measure test circuits reference counts.""" targets = [] if hex_counts: # 2-qubit measure |++> targets.append({'0x0': shots / 4, '0x1': shots / 4, '0x2': shots / 4, '0x3': shots / 4}) # 3-qubit measure |0++> targets.append({'0x0': shots / 4, '0x1': shots / 4, '0x2': shots / 4, '0x3': shots / 4}) else: # 2-qubit measure |++> targets.append({'00': shots / 4, '01': shots / 4, '10': shots / 4, '11': shots / 4}) # 3-qubit measure |0++> targets.append({'000': shots / 4, '001': shots / 4, '010': shots / 4, '011': shots / 4}) return targets
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test circuits and reference outputs for multiplexer gates. """ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from test.terra.utils.multiplexer import multiplexer_multi_controlled_x from test.terra.reference.ref_2q_clifford import (cx_gate_counts_nondeterministic, cx_gate_counts_deterministic) from test.terra.reference.ref_non_clifford import (ccx_gate_counts_nondeterministic, ccx_gate_counts_deterministic) def multiplexer_cx_gate_circuits_deterministic(final_measure=True): """multiplexer-gate simulating cx gate, test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(2) if final_measure: cr = ClassicalRegister(2) regs = (qr, cr) else: regs = (qr, ) num_control_qubits = 1 # CX01, |00> state circuit = QuantumCircuit(*regs) circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[0], qr[1]]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX10, |00> state circuit = QuantumCircuit(*regs) circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[1], qr[0]]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX01.(X^I), |10> state circuit = QuantumCircuit(*regs) circuit.x(qr[1]) circuit.barrier(qr) circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[0], qr[1]]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX10.(I^X), |01> state circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.barrier(qr) circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[1], qr[0]]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX01.(I^X), |11> state circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.barrier(qr) circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[0], qr[1]]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX10.(X^I), |11> state circuit = QuantumCircuit(*regs) circuit.x(qr[1]) circuit.barrier(qr) circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[1], qr[0]]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX01.(X^X), |01> state circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.barrier(qr) circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[0], qr[1]]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX10.(X^X), |10> state circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.barrier(qr) circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[1], qr[0]]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def multiplexer_cx_gate_circuits_nondeterministic(final_measure=True): """Multiplexer CX-like gate test circuits with non-deterministic counts.""" circuits = [] qr = QuantumRegister(2) if final_measure: cr = ClassicalRegister(2) regs = (qr, cr) else: regs = (qr, ) # cx gate only has one control qubit num_control_qubits = 1 # CX01.(I^H), Bell state circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.barrier(qr) circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[0], qr[1]]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX10.(H^I), Bell state circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.barrier(qr) circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[1], qr[0]]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def multiplexer_cx_gate_counts_deterministic(shots, hex_counts=True): """ The counts are exactly the same as the cx gate """ return cx_gate_counts_deterministic(shots, hex_counts) def multiplexer_cx_gate_counts_nondeterministic(shots, hex_counts=True): """ The counts are exactly the same as the cx gate """ return cx_gate_counts_nondeterministic(shots, hex_counts) # ========================================================================== # Multiplexer-gate (CCX-like) # ========================================================================== def multiplexer_ccx_gate_circuits_deterministic(final_measure=True): """multiplexer-gate simulating ccx gate, test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(3) if final_measure: cr = ClassicalRegister(3) regs = (qr, cr) else: regs = (qr, ) # because ccx has two control qubits and one target num_control_qubits = 2 # CCX(0,1,2) circuit = QuantumCircuit(*regs) circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[0], qr[1], qr[2]]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # (I^X^X).CCX(0,1,2).(I^X^X) -> |100> circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[0], qr[1], qr[2]]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CCX(2,1,0) circuit = QuantumCircuit(*regs) circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[2], qr[1], qr[0]]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # (X^X^I).CCX(2,1,0).(X^X^I) -> |001> circuit = QuantumCircuit(*regs) circuit.x(qr[1]) circuit.barrier(qr) circuit.x(qr[2]) circuit.barrier(qr) circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[2], qr[1], qr[0]]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.x(qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def multiplexer_ccx_gate_circuits_nondeterministic(final_measure=True): """mukltiplexer CCX-like gate test circuits with non-deterministic counts.""" circuits = [] qr = QuantumRegister(3) if final_measure: cr = ClassicalRegister(3) regs = (qr, cr) else: regs = (qr, ) # because ccx has two control qubits and one target num_control_qubits = 2 # (I^X^I).CCX(0,1,2).(I^X^H) -> |000> + |101> circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[0], qr[1], qr[2]]) circuit.barrier(qr) circuit.x(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # (X^I^I).CCX(2,1,0).(X^H^I) -> |000> + |011> circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.barrier(qr) circuit.x(qr[2]) circuit.barrier(qr) circuit.append(multiplexer_multi_controlled_x(num_control_qubits), [qr[2], qr[1], qr[0]]) circuit.barrier(qr) circuit.x(qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def multiplexer_ccx_gate_counts_deterministic(shots, hex_counts=True): """ The counts are exactly the same as the ccx gate """ return ccx_gate_counts_deterministic(shots, hex_counts) def multiplexer_ccx_gate_counts_nondeterministic(shots, hex_counts=True): """ The counts are exactly the same as the ccx gate """ return ccx_gate_counts_nondeterministic(shots, hex_counts)
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test circuits and reference outputs for non-Clifford gate instructions. """ import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit # ========================================================================== # T-gate # ========================================================================== def t_gate_circuits_deterministic(final_measure=True): """T-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # T circuit = QuantumCircuit(*regs) circuit.t(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # T.X circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.barrier(qr) circuit.t(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def t_gate_counts_deterministic(shots, hex_counts=True): """T-gate circuits reference counts.""" targets = [] if hex_counts: # T targets.append({'0x0': shots}) # T.X targets.append({'0x1': shots}) else: # T targets.append({'0': shots}) # T.X targets.append({'1': shots}) return targets def t_gate_statevector_deterministic(): """T-gate circuits reference statevectors.""" targets = [] # T targets.append(np.array([1, 0])) # T.X targets.append(np.array([0, 1 + 1j]) / np.sqrt(2)) return targets def t_gate_unitary_deterministic(): """T-gate circuits reference unitaries.""" targets = [] # T targets.append(np.diag([1, (1 + 1j) / np.sqrt(2)])) # T.X targets.append(np.array([[0, 1], [(1 + 1j) / np.sqrt(2), 0]])) return targets def t_gate_circuits_nondeterministic(final_measure=True): """T-gate test circuits with non-deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # T.H circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.t(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # X.T.H circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.t(qr) circuit.barrier(qr) circuit.x(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H.T.T.H = H.S.H circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.t(qr) circuit.barrier(qr) circuit.t(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def t_gate_counts_nondeterministic(shots, hex_counts=True): """T-gate circuits reference counts.""" targets = [] if hex_counts: # T.H targets.append({'0x0': shots / 2, '0x1': shots / 2}) # X.T.H targets.append({'0x0': shots / 2, '0x1': shots / 2}) # H.T.T.H = H.S.H targets.append({'0x0': shots / 2, '0x1': shots / 2}) else: # T.H targets.append({'0': shots / 2, '1': shots / 2}) # X.T.H targets.append({'0': shots / 2, '1': shots / 2}) # H.T.T.H = H.S.H targets.append({'0': shots / 2, '1': shots / 2}) return targets def t_gate_statevector_nondeterministic(): """T-gate circuits reference statevectors.""" targets = [] # T.H targets.append(np.array([1 / np.sqrt(2), 0.5 + 0.5j])) # X.T.H targets.append(np.array([0.5 + 0.5j, 1 / np.sqrt(2)])) # H.T.T.H = H.S.H targets.append(np.array([1 + 1j, 1 - 1j]) / 2) return targets def t_gate_unitary_nondeterministic(): """T-gate circuits reference unitaries.""" targets = [] # T.H targets.append( np.array([[1 / np.sqrt(2), 1 / np.sqrt(2)], [0.5 + 0.5j, -0.5 - 0.5j]])) # X.T.H targets.append( np.array([[0.5 + 0.5j, -0.5 - 0.5j], [1 / np.sqrt(2), 1 / np.sqrt(2)]])) # H.T.T.H = H.S.H targets.append(np.array([[1 + 1j, 1 - 1j], [1 - 1j, 1 + 1j]]) / 2) return targets # ========================================================================== # T^dagger-gate # ========================================================================== def tdg_gate_circuits_deterministic(final_measure=True): """Tdg-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # Tdg circuit = QuantumCircuit(*regs) circuit.tdg(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H.Tdg.T.H = I circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.t(qr) circuit.barrier(qr) circuit.tdg(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def tdg_gate_counts_deterministic(shots, hex_counts=True): """Sdg-gate circuits reference counts.""" targets = [] if hex_counts: # Tdg targets.append({'0x0': shots}) # H.Tdg.T.H = I targets.append({'0x0': shots}) else: # Tdg targets.append({'0': shots}) # H.Tdg.T.H = I targets.append({'0': shots}) return targets def tdg_gate_statevector_deterministic(): """Sdg-gate circuits reference statevectors.""" targets = [] # Tdg targets.append(np.array([1, 0])) # H.Tdg.T.H = I targets.append(np.array([1, 0])) return targets def tdg_gate_unitary_deterministic(): """Tdg-gate circuits reference unitaries.""" targets = [] # Tdg targets.append(np.diag([1, (1 - 1j) / np.sqrt(2)])) # H.Tdg.T.H = I targets.append(np.eye(2)) return targets def tdg_gate_circuits_nondeterministic(final_measure=True): """Tdg-gate test circuits with non-deterministic counts.""" circuits = [] qr = QuantumRegister(1) if final_measure: cr = ClassicalRegister(1) regs = (qr, cr) else: regs = (qr, ) # Tdg.H circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.tdg(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # X.Tdg.H circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.tdg(qr) circuit.barrier(qr) circuit.x(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H.Tdg.Tdg.H = H.Sdg.H circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.barrier(qr) circuit.tdg(qr) circuit.barrier(qr) circuit.tdg(qr) circuit.barrier(qr) circuit.h(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def tdg_gate_counts_nondeterministic(shots, hex_counts=True): """Tdg-gate circuits reference counts.""" targets = [] if hex_counts: # Tdg.H targets.append({'0x0': shots / 2, '0x1': shots / 2}) # X.Tdg.H targets.append({'0x0': shots / 2, '0x1': shots / 2}) # H.Tdg.Tdg.H = H.Sdg.H targets.append({'0x0': shots / 2, '0x1': shots / 2}) else: # Tdg.H targets.append({'0': shots / 2, '1': shots / 2}) # X.Tdg.H targets.append({'0': shots / 2, '1': shots / 2}) # H.Tdg.Tdg.H = H.Sdg.H targets.append({'0': shots / 2, '1': shots / 2}) return targets def tdg_gate_statevector_nondeterministic(): """Tdg-gate circuits reference statevectors.""" targets = [] # Tdg.H targets.append(np.array([1 / np.sqrt(2), 0.5 - 0.5j])) # X.Tdg.H targets.append(np.array([0.5 - 0.5j, 1 / np.sqrt(2)])) # H.Tdg.Tdg.H = H.Sdg.H targets.append(np.array([1 - 1j, 1 + 1j]) / 2) return targets def tdg_gate_unitary_nondeterministic(): """Tdg-gate circuits reference unitaries.""" targets = [] # Tdg.H targets.append( np.array([[1 / np.sqrt(2), 1 / np.sqrt(2)], [0.5 - 0.5j, -0.5 + 0.5j]])) # X.Tdg.H targets.append( np.array([[0.5 - 0.5j, -0.5 + 0.5j], [1 / np.sqrt(2), 1 / np.sqrt(2)]])) # H.Tdg.Tdg.H = H.Sdg.H targets.append(np.array([[1 - 1j, 1 + 1j], [1 + 1j, 1 - 1j]]) / 2) return targets # ========================================================================== # CCX-gate # ========================================================================== def ccx_gate_circuits_deterministic(final_measure=True): """CCX-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(3) if final_measure: cr = ClassicalRegister(3) regs = (qr, cr) else: regs = (qr, ) # CCX(0,1,2) circuit = QuantumCircuit(*regs) circuit.ccx(qr[0], qr[1], qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # (I^X^X).CCX(0,1,2).(I^X^X) -> |100> circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.ccx(qr[0], qr[1], qr[2]) circuit.barrier(qr) circuit.x(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CCX(2,1,0) circuit = QuantumCircuit(*regs) circuit.ccx(qr[2], qr[1], qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # (X^X^I).CCX(2,1,0).(X^X^I) -> |001> circuit = QuantumCircuit(*regs) circuit.x(qr[1]) circuit.barrier(qr) circuit.x(qr[2]) circuit.barrier(qr) circuit.ccx(qr[2], qr[1], qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.x(qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def ccx_gate_counts_deterministic(shots, hex_counts=True): """CCX-gate circuits reference counts.""" targets = [] if hex_counts: # CCX(0,1,2) targets.append({'0x0': shots}) # (I^X^X).CCX(0,1,2).(I^X^X) -> |100> targets.append({'0x4': shots}) # CCX(2,1,0) targets.append({'0x0': shots}) # (X^X^I).CCX(2,1,0).(X^X^I) -> |001> targets.append({'0x1': shots}) else: # CCX(0,1,2) targets.append({'000': shots}) # (I^X^X).CCX(0,1,2).(I^X^X) -> |100> targets.append({'000': shots}) # CCX(2,1,0) targets.append({'000': shots}) # (X^X^I).CCX(2,1,0).(X^X^I) -> |001> targets.append({'001': shots}) return targets def ccx_gate_statevector_deterministic(): """CCX-gate circuits reference statevectors.""" targets = [] zero_state = np.array([1, 0, 0, 0, 0, 0, 0, 0]) # CCX(0,1,2) targets.append(zero_state) # (I^X^X).CCX(0,1,2).(I^X^X) -> |100> targets.append(np.array([0, 0, 0, 0, 1, 0, 0, 0])) # CCX(2,1,0) targets.append(zero_state) # (X^X^I).CCX(2,1,0).(X^X^I) -> |001> targets.append(np.array([0, 1, 0, 0, 0, 0, 0, 0])) return targets def ccx_gate_unitary_deterministic(): """CCX-gate circuits reference unitaries.""" targets = [] # CCX(0,1,2) targets.append( np.array([[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0, 0, 0]])) # (I^X^X).CCX(0,1,2).(I^X^X) -> |100> targets.append( np.array([[0, 0, 0, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1]])) # CCX(2,1,0) targets.append( np.array([[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0]])) # (X^X^I).CCX(2,1,0).(X^X^I) -> |001> targets.append( np.array([[0, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1]])) return targets def ccx_gate_circuits_nondeterministic(final_measure=True): """CCX-gate test circuits with non-deterministic counts.""" circuits = [] qr = QuantumRegister(3) if final_measure: cr = ClassicalRegister(3) regs = (qr, cr) else: regs = (qr, ) # (I^X^I).CCX(0,1,2).(I^X^H) -> |000> + |101> circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.barrier(qr) circuit.x(qr[1]) circuit.barrier(qr) circuit.ccx(qr[0], qr[1], qr[2]) circuit.barrier(qr) circuit.x(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # (X^I^I).CCX(2,1,0).(X^H^I) -> |000> + |011> circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.barrier(qr) circuit.x(qr[2]) circuit.barrier(qr) circuit.ccx(qr[2], qr[1], qr[0]) circuit.barrier(qr) circuit.x(qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def ccx_gate_counts_nondeterministic(shots, hex_counts=True): """CCX-gate circuits reference counts.""" targets = [] if hex_counts: # (I^X^I).CCX(0,1,2).(I^X^H) -> |000> + |101> targets.append({'0x0': shots / 2, '0x5': shots / 2}) # (X^I^I).CCX(2,1,0).(X^H^I) -> |000> + |011> targets.append({'0x0': shots / 2, '0x3': shots / 2}) else: # (I^X^I).CCX(0,1,2).(I^X^H) -> |000> + |101> targets.append({'000': shots / 2, '101': shots / 2}) # (X^I^I).CCX(2,1,0).(X^H^I) -> |000> + |011> targets.append({'000': shots / 2, '011': shots / 2}) return targets def ccx_gate_statevector_nondeterministic(): """CCX-gate circuits reference statevectors.""" targets = [] # (I^X^I).CCX(0,1,2).(I^X^H) -> |000> + |101> targets.append(np.array([1, 0, 0, 0, 0, 1, 0, 0]) / np.sqrt(2)) # (X^I^I).CCX(2,1,0).(X^H^I) -> |000> + |011> targets.append(np.array([1, 0, 0, 1, 0, 0, 0, 0]) / np.sqrt(2)) return targets def ccx_gate_unitary_nondeterministic(): """CCX-gate circuits reference unitaries.""" targets = [] # (I^X^I).CCX(0,1,2).(I^X^H) -> |000> + |101> targets.append( np.array([[1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, -1, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 1, -1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0], [1, -1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, -1]]) / np.sqrt(2)) # (X^I^I).CCX(2,1,0).(X^H^I) -> |000> + |011> targets.append( np.array([[1, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 1, 0, 0, 0, 0], [0, 1, 0, -1, 0, 0, 0, 0], [1, 0, -1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 1, 0], [0, 0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 0, 1, 0, -1, 0], [0, 0, 0, 0, 0, 1, 0, -1]]) / np.sqrt(2)) return targets # ========================================================================== # CSWAP-gate (Fredkin) # ========================================================================== def cswap_gate_circuits_deterministic(final_measure): """cswap-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(3) if final_measure: cr = ClassicalRegister(3) regs = (qr, cr) else: regs = (qr, ) # CSWAP(0,1,2) # -> |000> circuit = QuantumCircuit(*regs) circuit.cswap(qr[0], qr[1], qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(X^I^I) -> |100> circuit = QuantumCircuit(*regs) circuit.x(qr[2]) circuit.barrier(qr) circuit.cswap(qr[0], qr[1], qr[2]) circuit.barrier(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(I^X^I) -> |010> circuit = QuantumCircuit(*regs) circuit.x(qr[1]) circuit.barrier(qr) circuit.cswap(qr[0], qr[1], qr[2]) circuit.barrier(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(X^X^I) -> |110> circuit = QuantumCircuit(*regs) circuit.x(qr[1]) circuit.x(qr[2]) circuit.barrier(qr) circuit.cswap(qr[0], qr[1], qr[2]) circuit.barrier(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(I^I^X) -> |001> circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.barrier(qr) circuit.cswap(qr[0], qr[1], qr[2]) circuit.barrier(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(I^X^X -> |101> circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.x(qr[1]) circuit.barrier(qr) circuit.cswap(qr[0], qr[1], qr[2]) circuit.barrier(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(X^I^X) -> |011> circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.x(qr[2]) circuit.barrier(qr) circuit.cswap(qr[0], qr[1], qr[2]) circuit.barrier(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(X^X^X) -> |111> circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.x(qr[1]) circuit.x(qr[2]) circuit.barrier(qr) circuit.cswap(qr[0], qr[1], qr[2]) circuit.barrier(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(1,0,2).(I^X^X) -> |110> circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.x(qr[1]) circuit.barrier(qr) circuit.cswap(qr[1], qr[0], qr[2]) circuit.barrier(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(2,1,0).(X^I^X) -> |110> circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.x(qr[2]) circuit.barrier(qr) circuit.cswap(qr[2], qr[1], qr[0]) circuit.barrier(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def cswap_gate_counts_deterministic(shots, hex_counts=True): """"cswap-gate circuits reference counts.""" targets = [] if hex_counts: # CSWAP(0,1,2) # -> |000> targets.append({'0x0': shots}) # CSWAP(0,1,2).(X^I^I) -> |100> targets.append({'0x4': shots}) # CSWAP(0,1,2).(I^X^I) -> |010> targets.append({'0x2': shots}) # CSWAP(0,1,2).(X^X^I) -> |110> targets.append({'0x6': shots}) # CSWAP(0,1,2).(I^I^X). -> |001> targets.append({'0x1': shots}) # CSWAP(0,1,2).(I^X^X) -> |101> targets.append({'0x5': shots}) # CSWAP(0,1,2).(X^I^X) -> |011> targets.append({'0x3': shots}) # CSWAP(0,1,2).(X^X^X) -> |111> targets.append({'0x7': shots}) # CSWAP(1,0,2).(I^X^X) -> |110> targets.append({'0x6': shots}) # CSWAP(2,1,0).(X^I^X) -> |110> targets.append({'0x6': shots}) else: # CSWAP(0,1,2) # -> |000> targets.append({'000': shots}) # CSWAP(0,1,2).(X^I^I) -> |100> targets.append({'100': shots}) # CSWAP(0,1,2).(I^X^I) -> |010> targets.append({'010': shots}) # CSWAP(0,1,2).(X^X^I) -> |110> targets.append({'110': shots}) # CSWAP(0,1,2).(I^I^X) -> |001> targets.append({'001': shots}) # CSWAP(0,1,2).(I^X^X) -> |101> targets.append({'101': shots}) # CSWAP(0,1,2).(X^I^X) -> |011> targets.append({'011': shots}) # CSWAP(0,1,2).(X^X^X) -> |111> targets.append({'111': shots}) # CSWAP(1,0,2).(I^X^X) -> |110> targets.append({'110': shots}) # CSWAP(2,1,0).(X^I^X) -> |110> targets.append({'110': shots}) return targets def cswap_gate_circuits_nondeterministic(final_measure=True): """cswap-gate test circuits with deterministic counts.""" circuits = [] qr = QuantumRegister(3) if final_measure: cr = ClassicalRegister(3) regs = (qr, cr) else: regs = (qr, ) # CSWAP(0,1,2).(H^H^H) circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.h(qr[1]) circuit.h(qr[2]) circuit.cswap(qr[0], qr[1], qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(X^I^H). -> |100> + |011> circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.x(qr[2]) circuit.cswap(qr[0], qr[1], qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(I^X^H). -> |010> + |101> circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.x(qr[1]) circuit.cswap(qr[0], qr[1], qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(I^H^I) -> |010>+|000> circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.cswap(qr[0], qr[1], qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(H^I^I) -> |100>+|000> circuit = QuantumCircuit(*regs) circuit.h(qr[2]) circuit.cswap(qr[0], qr[1], qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(I^I^H) -> |001>+|000> circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.cswap(qr[0], qr[1], qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CSWAP(0,1,2).(X^X^H) -> |110> + |111> circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.x(qr[1]) circuit.x(qr[2]) circuit.cswap(qr[0], qr[1], qr[2]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def cswap_gate_counts_nondeterministic(shots, hex_counts=True): targets = [] if hex_counts: # CSWAP(0,1,2).(H^H^H) -> |---> targets.append({ '0x0': shots / 8, '0x1': shots / 8, '0x2': shots / 8, '0x3': shots / 8, '0x4': shots / 8, '0x5': shots / 8, '0x6': shots / 8, '0x7': shots / 8, }) # CSWAP(0,1,2).(X^I^H). -> |100> + |011> targets.append({'0x3': shots / 2, '0x4': shots / 2}) # CSWAP(0,1,2).(I^X^H). -> |010> + |101> targets.append({'0x2': shots / 2, '0x5': shots / 2}) # CSWAP(0,1,2).(I^H^I) -> |0-0> targets.append({'0x2': shots / 2, '0x0': shots / 2}) # CSWAP(0,1,2).(H^I^I) -> |-00> targets.append({'0x4': shots / 2, '0x0': shots / 2}) # CSWAP(0,1,2).(I^I^H) -> |00-> targets.append({'0x0': shots / 2, '0x1': shots / 2}) # CSWAP(0,1,2).(X^X^H) -> |110> + |111> targets.append({'0x6': shots / 2, '0x7': shots / 2}) else: # CSWAP(0,1,2).(H^H^H) -> |---> targets.append({ '000': shots / 8, '001': shots / 8, '010': shots / 8, '011': shots / 8, '100': shots / 8, '101': shots / 8, '110': shots / 8, '111': shots / 8, }) # CSWAP(0,1,2).(X^I^H). -> |100> + |011> targets.append({'011': shots / 2, '100': shots / 2}) # CSWAP(0,1,2).(I^X^H). -> |010> + |101> targets.append({'010': shots / 2, '101': shots / 2}) # CSWAP(0,1,2).(I^H^I) -> |0-0> targets.append({'010': shots / 2, '000': shots / 2}) # CSWAP(0,1,2).(H^I^I) -> |-00> targets.append({'100': shots / 2, '000': shots / 2}) # CSWAP(0,1,2).(I^I^H) -> |00-> targets.append({'001': shots / 2, '000': shots / 2}) # CSWAP(0,1,2).(X^X^H) -> |110> + |111> targets.append({'110': shots / 2, '111': shots / 2}) return targets def cswap_gate_statevector_deterministic(): targets = [] # CSWAP(0,1,2) # -> |000> targets.append(np.array([1, 0, 0, 0, 0, 0, 0, 0])) # CSWAP(0,1,2).(X^I^I) -> |100> targets.append(np.array([0, 0, 0, 0, 1, 0, 0, 0])) # CSWAP(0,1,2).(I^X^I) -> |010> targets.append(np.array([0, 0, 1, 0, 0, 0, 0, 0])) # CSWAP(0,1,2).(X^X^I) -> |110> targets.append(np.array([0, 0, 0, 0, 0, 0, 1, 0])) # CSWAP(0,1,2).(I^I^X) -> |001> targets.append(np.array([0, 1, 0, 0, 0, 0, 0, 0])) # CSWAP(0,1,2).(I^X^X) -> |101> targets.append(np.array([0, 0, 0, 0, 0, 1, 0, 0])) # CSWAP(0,1,2).(X^I^X) -> |011> targets.append(np.array([0, 0, 0, 1, 0, 0, 0, 0])) # CSWAP(0,1,2).(X^X^X) -> |111> targets.append(np.array([0, 0, 0, 0, 0, 0, 0, 1])) # CSWAP(1,0,2).(I^X^X) -> |110> targets.append(np.array([0, 0, 0, 0, 0, 0, 1, 0])) # CSWAP(2,1,0).(X^I^X) -> |110> targets.append(np.array([0, 0, 0, 0, 0, 0, 1, 0])) return targets def cswap_gate_statevector_nondeterministic(): targets = [] # CSWAP(0,1,2).(H^H^H) -> |---> targets.append(np.array([1, 1, 1, 1, 1, 1, 1, 1]) / np.sqrt(8)) # CSWAP(0,1,2).(X^I^H). -> |100> + |011> targets.append(np.array([0, 0, 0, 1, 1, 0, 0, 0]) / np.sqrt(2)) # CSWAP(0,1,2).(I^X^H). -> |010> + |101> targets.append(np.array([0, 0, 1, 0, 0, 1, 0, 0]) / np.sqrt(2)) # CSWAP(0,1,2).(I^H^I) -> |0-0> targets.append(np.array([1, 0, 1, 0, 0, 0, 0, 0]) / np.sqrt(2)) # CSWAP(0,1,2).(H^I^I) -> |-00> targets.append(np.array([1, 0, 0, 0, 1, 0, 0, 0]) / np.sqrt(2)) # CSWAP(0,1,2).(I^I^H) -> |00-> targets.append(np.array([1, 1, 0, 0, 0, 0, 0, 0]) / np.sqrt(2)) # CSWAP(0,1,2).(X^X^H) -> |110> + |111> targets.append(np.array([0, 0, 0, 0, 0, 0, 1, 1]) / np.sqrt(2)) return targets def cswap_gate_unitary_deterministic(): """cswap-gate circuits reference unitaries.""" targets = [] # CSWAP(0,1,2) # -> |000> targets.append( np.array([[1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1]])) # CSWAP(0,1,2).(X^I^I) -> |100> targets.append( np.array([[0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0]])) # CSWAP(0,1,2).(I^X^I) -> |010> targets.append( np.array([[0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0]])) # CSWAP(0,1,2).(X^X^I) -> |110> targets.append( np.array([[0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0]])) # CSWAP(0,1,2).(I^I^X) -> |001> targets.append( np.array([[0, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0]])) # CSWAP(0,1,2).(I^X^X) -> |101> targets.append( np.array([[0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0]])) # CSWAP(0,1,2).(X^I^X) -> |011> targets.append( np.array([[0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0]])) # CSWAP(0,1,2).(X^X^X) -> |111> targets.append( np.array([[0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0]])) # CSWAP(1,0,2).(I^X^X) -> |110> targets.append( np.array([[0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0]])) # CSWAP(2,1,0).(X^I^X) -> |110> targets.append( np.array([[0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0]])) return targets def cswap_gate_unitary_nondeterministic(): """cswap-gate circuits reference unitaries.""" targets = [] targets.append( np.array([[ 0.35355339, 0.35355339, 0.35355339, 0.35355339, 0.35355339, 0.35355339, 0.35355339, 0.35355339 ], [ 0.35355339, -0.35355339, 0.35355339, -0.35355339, 0.35355339, -0.35355339, 0.35355339, -0.35355339 ], [ 0.35355339, 0.35355339, -0.35355339, -0.35355339, 0.35355339, 0.35355339, -0.35355339, -0.35355339 ], [ 0.35355339, -0.35355339, 0.35355339, -0.35355339, -0.35355339, 0.35355339, -0.35355339, 0.35355339 ], [ 0.35355339, 0.35355339, 0.35355339, 0.35355339, -0.35355339, -0.35355339, -0.35355339, -0.35355339 ], [ 0.35355339, -0.35355339, -0.35355339, 0.35355339, 0.35355339, -0.35355339, -0.35355339, 0.35355339 ], [ 0.35355339, 0.35355339, -0.35355339, -0.35355339, -0.35355339, -0.35355339, 0.35355339, 0.35355339 ], [ 0.35355339, -0.35355339, -0.35355339, 0.35355339, -0.35355339, 0.35355339, 0.35355339, -0.35355339 ]])) targets.append( np.array([[0, 0, 0, 0, 0.70710678, 0.70710678, 0, 0], [0, 0, 0, 0, 0.70710678, -0.70710678, 0, 0], [0, 0, 0, 0, 0, 0, 0.70710678, 0.70710678], [0.70710678, -0.70710678, 0, 0, 0, 0, 0, 0], [0.70710678, 0.70710678, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0.70710678, -0.70710678], [0, 0, 0.70710678, 0.70710678, 0, 0, 0, 0], [0, 0, 0.70710678, -0.70710678, 0, 0, 0, 0]])) targets.append( np.array([[0, 0, 0.70710678, 0.70710678, 0, 0, 0, 0], [0, 0, 0.70710678, -0.70710678, 0, 0, 0, 0], [0.70710678, 0.70710678, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0.70710678, -0.70710678], [0, 0, 0, 0, 0, 0, 0.70710678, 0.70710678], [0.70710678, -0.70710678, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0.70710678, 0.70710678, 0, 0], [0, 0, 0, 0, 0.70710678, -0.70710678, 0, 0]])) targets.append( np.array([[0.70710678, 0, 0.70710678, 0, 0, 0, 0, 0], [0, 0.70710678, 0, 0.70710678, 0, 0, 0, 0], [0.70710678, 0, -0.70710678, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0.70710678, 0, 0.70710678], [0, 0, 0, 0, 0.70710678, 0, 0.70710678, 0], [0, 0.70710678, 0, -0.70710678, 0, 0, 0, 0], [0, 0, 0, 0, 0.70710678, 0, -0.70710678, 0], [0, 0, 0, 0, 0, 0.70710678, 0, -0.70710678]])) targets.append( np.array([[0.70710678, 0, 0, 0, 0.70710678, 0, 0, 0], [0, 0.70710678, 0, 0, 0, 0.70710678, 0, 0], [0, 0, 0.70710678, 0, 0, 0, 0.70710678, 0], [0, 0.70710678, 0, 0, 0, -0.70710678, 0, 0], [0.70710678, 0, 0, 0, -0.70710678, 0, 0, 0], [0, 0, 0, 0.70710678, 0, 0, 0, 0.70710678], [0, 0, 0.70710678, 0, 0, 0, -0.70710678, 0], [0, 0, 0, 0.70710678, 0, 0, 0, -0.70710678]])) targets.append( np.array([[0.70710678, 0.70710678, 0, 0, 0, 0, 0, 0], [0.70710678, -0.70710678, 0, 0, 0, 0, 0, 0], [0, 0, 0.70710678, 0.70710678, 0, 0, 0, 0], [0, 0, 0, 0, 0.70710678, -0.70710678, 0, 0], [0, 0, 0, 0, 0.70710678, 0.70710678, 0, 0], [0, 0, 0.70710678, -0.70710678, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0.70710678, 0.70710678], [0, 0, 0, 0, 0, 0, 0.70710678, -0.70710678]])) targets.append( np.array([[0, 0, 0, 0, 0, 0, 0.70710678, 0.70710678], [0, 0, 0, 0, 0, 0, 0.70710678, -0.70710678], [0, 0, 0, 0, 0.70710678, 0.70710678, 0, 0], [0, 0, 0.70710678, -0.70710678, 0, 0, 0, 0], [0, 0, 0.70710678, 0.70710678, 0, 0, 0, 0], [0, 0, 0, 0, 0.70710678, -0.70710678, 0, 0], [0.70710678, 0.70710678, 0, 0, 0, 0, 0, 0], [0.70710678, -0.70710678, 0, 0, 0, 0, 0, 0]])) return targets # ========================================================================== # CU1 # ========================================================================== def cu1_gate_circuits_nondeterministic(final_measure): circuits = [] qr = QuantumRegister(2) if final_measure: cr = ClassicalRegister(2) regs = (qr, cr) else: regs = (qr, ) # H^X.CU1(0,0,1).H^X circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.x(qr[0]) circuit.cp(0, qr[0], qr[1]) circuit.x(qr[0]) circuit.h(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H^I.CU1(pi,0,1).H^I circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.cp(np.pi, qr[0], qr[1]) circuit.h(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H^X.CU1(pi/4,0,1).H^X circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.x(qr[0]) circuit.cp(np.pi / 4, qr[0], qr[1]) circuit.x(qr[0]) circuit.h(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H^X.CU1(pi/2,0,1).H^X circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.x(qr[0]) circuit.cp(np.pi / 2, qr[0], qr[1]) circuit.x(qr[0]) circuit.h(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H^X.CU1(pi,0,1).H^X circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.x(qr[0]) circuit.cp(np.pi, qr[0], qr[1]) circuit.x(qr[0]) circuit.h(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H^H.CU1(0,0,1).H^H circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.h(qr[0]) circuit.cp(0, qr[0], qr[1]) circuit.h(qr[0]) circuit.h(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H^H.CU1(pi/2,0,1).H^H circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.h(qr[0]) circuit.cp(np.pi / 2, qr[0], qr[1]) circuit.h(qr[0]) circuit.h(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H^H.CU1(pi,0,1).H^H circuit = QuantumCircuit(*regs) circuit.h(qr[1]) circuit.h(qr[0]) circuit.cp(np.pi, qr[0], qr[1]) circuit.h(qr[0]) circuit.h(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def cu1_gate_counts_nondeterministic(shots, hex_counts=True): """CU1-gate circuits reference counts.""" targets = [] if hex_counts: # H^X.CU1(0,0,1).H^X targets.append({'0x0': shots}) # H^I.CU1(pi,0,1).H^I targets.append({'0x0': shots}) # H^X.CU1(pi/4,0,1).H^X targets.append({ '0x0': shots * (0.25 * (2 + np.sqrt(2))), '0x2': shots * (0.25 * (2 - np.sqrt(2))) }) # H^X.CU1(pi/2,0,1).H^X targets.append({'0x0': shots * 0.5, '0x2': shots * 0.5}) # H^X.CU1(pi,0,1).H^X targets.append({'0x2': shots}) # H^H.CU1(0,0,1).H^H targets.append({'0x0': shots}) # H^H.CU1(pi/2,0,1).H^H targets.append({ '0x0': shots * 0.625, '0x1': shots * 0.125, '0x2': shots * 0.125, '0x3': shots * 0.125 }) # H^H.CU1(pi,0,1).H^H targets.append({ '0x0': shots * 0.25, '0x1': shots * 0.25, '0x2': shots * 0.25, '0x3': shots * 0.25 }) else: # H^X.CU1(0,0,1).H^X targets.append({'00': shots}) # H^I.CU1(pi,0,1).H^I targets.append({'00': shots}) # H^X.CU1(pi/4,0,1).H^X targets.append({'00': shots * 0.85, '10': shots * 0.15}) # H^X.CU1(pi/2,0,1).H^X targets.append({'00': shots * 0.5, '10': shots * 0.5}) # H^X.CU1(pi,0,1).H^X targets.append({'10': shots}) # H^H.CU1(0,0,1).H^H targets.append({'00': shots}) # H^H.CU1(pi/2,0,1).H^H targets.append({ '00': shots * 0.5125, '01': shots * 0.125, '10': shots * 0.125, '11': shots * 0.125 }) # H^H.CU1(pi,0,1).H^H targets.append({ '00': shots * 0.25, '01': shots * 0.25, '10': shots * 0.25, '11': shots * 0.25 }) return targets def cu1_gate_statevector_nondeterministic(): targets = [] # H^X.CU1(0,0,1).H^X targets.append(np.array([1, 0, 0, 0])) # H^I.CU1(pi,0,1).H^I targets.append(np.array([1, 0, 0, 0])) # H^X.CU1(pi/4,0,1).H^X targets.append( np.array([(0.25 * (2 + np.sqrt(2))) + (1 / (2 * np.sqrt(2))) * 1j, 0, (0.25 * (2 - np.sqrt(2))) - (1 / (2 * np.sqrt(2))) * 1j, 0])) # H^X.CU1(pi/2,0,1).H^X targets.append(np.array([0.5 + 0.5j, 0, 0.5 - 0.5j, 0])) # H^X.CU1(pi,0,1).H^X targets.append(np.array([0, 0, 1, 0])) # H^H.CU1(0,0,1).H^H targets.append(np.array([1, 0, 0, 0])) # H^H.CU1(pi/2,0,1).H^H targets.append( np.array([0.75 + 0.25j, 0.25 - 0.25j, 0.25 - 0.25j, -0.25 + 0.25j])) # H^H.CU1(pi,0,1).H^H targets.append(np.array([0.5, 0.5, 0.5, -0.5])) return targets def cu1_gate_unitary_nondeterministic(): targets = [] # H^X.CU1(0,0,1).H^X targets.append(np.eye(4)) # H^I.CU1(pi,0,1).H^I targets.append( np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]])) # H^X.CU1(pi/4,0,1).H^X targets.append( np.array([[(0.25 * (2 + np.sqrt(2))) + (1 / (2 * np.sqrt(2))) * 1j, 0, (0.25 * (2 - np.sqrt(2))) - (1 / (2 * np.sqrt(2))) * 1j, 0], [0, 1, 0, 0], [(0.25 * (2 - np.sqrt(2))) - (1 / (2 * np.sqrt(2))) * 1j, 0, (0.25 * (2 + np.sqrt(2))) + (1 / (2 * np.sqrt(2))) * 1j, 0], [0, 0, 0, 1]])) # H^X.CU1(pi/2,0,1).H^X targets.append( np.array([[0.5 + 0.5j, 0, 0.5 - 0.5j, 0], [0, 1, 0, 0], [0.5 - 0.5j, 0, 0.5 + 0.5j, 0], [0, 0, 0, 1]])) # H^X.CU1(pi,0,1).H^X targets.append( np.array([[0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1]])) # H^H.CU1(0,0,1).H^H targets.append(np.eye(4)) # H^H.CU1(pi/2,0,1).H^H targets.append( (0.75 + 0.25j) * np.eye(4) + (0.25 - 0.25j) * np.array([[0, 1, 1, -1], [1, 0, -1, 1], [1, -1, 0, 1], [-1, 1, 1, 0]])) # H^H.CU1(pi,0,1).H^H targets.append( 0.5 * np.array([[1, 1, 1, -1], [1, 1, -1, 1], [1, -1, 1, 1], [-1, 1, 1, 1]])) return targets # ========================================================================== # CU3 # ========================================================================== def cu3_gate_circuits_deterministic(final_measure): circuits = [] qr = QuantumRegister(2) if final_measure: cr = ClassicalRegister(2) regs = (qr, cr) else: regs = (qr, ) # I^X.CI.I^X circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.cu(0, 0, 0, 0, qr[0], qr[1]) circuit.x(qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX circuit = QuantumCircuit(*regs) circuit.cu(np.pi, 0, np.pi, 0, qr[0], qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # I^X.CX.I^X circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.cu(np.pi, 0, np.pi, 0, qr[0], qr[1]) circuit.x(qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # H^X.CH.I^X circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.cu(np.pi / 2, 0, np.pi, 0, qr[0], qr[1]) circuit.x(qr[0]) circuit.h(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # I^X.CRX(pi).I^X circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.cu(np.pi, -np.pi / 2, np.pi / 2, 0, qr[0], qr[1]) circuit.x(qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # I^X.CRY(pi).I^X circuit = QuantumCircuit(*regs) circuit.x(qr[0]) circuit.cu(np.pi, 0, 0, 0, qr[0], qr[1]) circuit.x(qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def cu3_gate_unitary_deterministic(): targets = [] # I^X.CI.I^X targets.append(np.eye(4)) # CX targets.append( np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]])) # I^X.CX.I^X targets.append( np.array([[0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1]])) # H^X.CH.I^X targets.append( np.array([[1, 0, 0, 0], [0, 1 / np.sqrt(2), 0, 1 / np.sqrt(2)], [0, 0, 1, 0], [0, 1 / np.sqrt(2), 0, -1 / np.sqrt(2)]])) # I^X.CRX(pi).I^X targets.append( np.array([[0, 0, -1j, 0], [0, 1, 0, 0], [-1j, 0, 0, 0], [0, 0, 0, 1]])) # I^X.CRY(pi).I^X targets.append( np.array([[0, 0, -1, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1]])) return targets def cu3_gate_statevector_deterministic(): init_state = np.array([1, 0, 0, 0]) targets = [mat.dot(init_state) for mat in cu3_gate_unitary_deterministic()] return targets def cu3_gate_counts_deterministic(shots, hex_counts=True): """CU2-gate circuits reference counts.""" probs = [np.abs(vec)**2 for vec in cu3_gate_statevector_deterministic()] targets = [] for prob in probs: if hex_counts: targets.append({hex(i): shots * p for i, p in enumerate(prob)}) else: counts = {} for i, p in enumerate(prob): key = bin(i)[2:] key = (2 - len(key)) * '0' + key counts[key] = shots * p targets.append(counts) return targets
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ QasmSimulator readout error NoiseModel integration tests """ from test.terra.utils.utils import list2dict from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors.standard_errors import pauli_error # Backwards compatibility for Terra <= 0.13 if not hasattr(QuantumCircuit, 'i'): QuantumCircuit.i = QuantumCircuit.iden # ========================================================================== # Pauli Gate Errors # ========================================================================== def pauli_gate_error_circuits(): """Local Pauli gate error noise model circuits""" circuits = [] qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') # 100% all-qubit Pauli error on "id" gate circuit = QuantumCircuit(qr, cr) circuit.i(qr) circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # 25% all-qubit Pauli error on "id" gates circuit = QuantumCircuit(qr, cr) circuit.i(qr) circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # 100% Pauli error on "id" gates on qubit-1 circuit = QuantumCircuit(qr, cr) circuit.i(qr) circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # 25% all-qubit Pauli error on "id" gates on qubit-0 circuit = QuantumCircuit(qr, cr) circuit.i(qr) circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # 25% Pauli-X error on spectator for CX gate on [0, 1] qr = QuantumRegister(3, 'qr') cr = ClassicalRegister(3, 'cr') circuit = QuantumCircuit(qr, cr) circuit.cx(qr[0], qr[1]) circuit.barrier(qr) circuit.cx(qr[1], qr[0]) circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def pauli_gate_error_noise_models(): """Local Pauli gate error noise models""" noise_models = [] # 100% all-qubit Pauli error on "id" gates error = pauli_error([('X', 1)]) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error, 'id') noise_models.append(noise_model) # 25% all-qubit Pauli error on "id" gates error = pauli_error([('X', 0.25), ('I', 0.75)]) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error, 'id') noise_models.append(noise_model) # 100% Pauli error on "id" gates on qubit-1 error = pauli_error([('X', 1)]) noise_model = NoiseModel() noise_model.add_quantum_error(error, 'id', [1]) noise_models.append(noise_model) # 25% all-qubit Pauli error on "id" gates on qubit-0 error = pauli_error([('X', 0.25), ('I', 0.75)]) noise_model = NoiseModel() noise_model.add_quantum_error(error, 'id', [0]) noise_models.append(noise_model) # 25% Pauli-X error on spectator for CX gate on [0, 1] error = pauli_error([('XII', 0.25), ('III', 0.75)]) noise_model = NoiseModel() noise_model.add_nonlocal_quantum_error(error, 'cx', [0, 1], [0, 1, 2]) noise_models.append(noise_model) return noise_models def pauli_gate_error_counts(shots, hex_counts=True): """Pauli gate error circuits reference counts""" counts_lists = [] # 100% all-qubit Pauli error on "id" gates counts = [0, 0, 0, shots] counts_lists.append(counts) # 25% all-qubit Pauli error on "id" gates counts = [9 * shots / 16, 3 * shots / 16, 3 * shots / 16, shots / 16] counts_lists.append(counts) # 100% Pauli error on "id" gates on qubit-1 counts = [0, 0, shots, 0] counts_lists.append(counts) # 25% all-qubit Pauli error on "id" gates on qubit-0 counts = [3 * shots / 4, shots / 4, 0, 0] counts_lists.append(counts) # 25% Pauli-X error on spectator for CX gate on [0, 1] counts = [3 * shots / 4, 0, 0, 0, shots / 4, 0, 0, 0] counts_lists.append(counts) # Convert to counts dict return [list2dict(i, hex_counts) for i in counts_lists] # ========================================================================== # Pauli Measure Errors # ========================================================================== def pauli_measure_error_circuits(): """Local Pauli measure error noise model circuits""" circuits = [] qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') # 25% all-qubit Pauli error on measure circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) circuits.append(circuit) # 25% local Pauli error on measure of qubit 1 circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) circuits.append(circuit) # 25 % non-local Pauli error on qubit 1 for measure of qubit-1 circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def pauli_measure_error_noise_models(): """Local Pauli measure error noise models""" noise_models = [] # 25% all-qubit Pauli error on measure error = pauli_error([('X', 0.25), ('I', 0.75)]) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error, 'measure') noise_models.append(noise_model) # 25% local Pauli error on measure of qubit 1 error = pauli_error([('X', 0.25), ('I', 0.75)]) noise_model = NoiseModel() noise_model.add_quantum_error(error, 'measure', [1]) noise_models.append(noise_model) # 25 % non-local Pauli error on qubit 1 for measure of qubit-1 error = pauli_error([('X', 0.25), ('I', 0.75)]) noise_model = NoiseModel() noise_model.add_nonlocal_quantum_error(error, 'measure', [0], [1]) noise_models.append(noise_model) return noise_models def pauli_measure_error_counts(shots, hex_counts=True): """Local Pauli measure error circuits reference counts""" counts_lists = [] # 25% all-qubit Pauli error on measure counts = [9 * shots / 16, 3 * shots / 16, 3 * shots / 16, shots / 16] counts_lists.append(counts) # 25% local Pauli error on measure of qubit 1 counts = [3 * shots / 4, 0, shots / 4, 0] counts_lists.append(counts) # 25 % non-local Pauli error on qubit 1 for measure of qubit-1 counts = [3 * shots / 4, 0, shots / 4, 0] counts_lists.append(counts) # Convert to counts dict return [list2dict(i, hex_counts) for i in counts_lists] # ========================================================================== # Pauli Reset Errors # ========================================================================== def pauli_reset_error_circuits(): """Local Pauli reset error noise model circuits""" circuits = [] qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') # 25% all-qubit Pauli error on reset circuit = QuantumCircuit(qr, cr) circuit.barrier(qr) circuit.reset(qr) circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # 25% local Pauli error on reset of qubit 1 circuit = QuantumCircuit(qr, cr) circuit.barrier(qr) circuit.reset(qr) circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # 25 % non-local Pauli error on qubit 1 for reset of qubit-0 circuit = QuantumCircuit(qr, cr) circuit.barrier(qr) circuit.reset(qr[1]) circuit.barrier(qr) circuit.reset(qr[0]) circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def pauli_reset_error_noise_models(): """Local Pauli reset error noise models""" noise_models = [] # 25% all-qubit Pauli error on reset error = pauli_error([('X', 0.25), ('I', 0.75)]) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error, 'reset') noise_models.append(noise_model) # 25% local Pauli error on reset of qubit 1 error = pauli_error([('X', 0.25), ('I', 0.75)]) noise_model = NoiseModel() noise_model.add_quantum_error(error, 'reset', [1]) noise_models.append(noise_model) # 25 % non-local Pauli error on qubit 1 for reset of qubit-0 error = pauli_error([('X', 0.25), ('I', 0.75)]) noise_model = NoiseModel() noise_model.add_nonlocal_quantum_error(error, 'reset', [0], [1]) noise_models.append(noise_model) return noise_models def pauli_reset_error_counts(shots, hex_counts=True): """Local Pauli reset error circuits reference counts""" counts_lists = [] # 25% all-qubit Pauli error on reset counts = [9 * shots / 16, 3 * shots / 16, 3 * shots / 16, shots / 16] counts_lists.append(counts) # 25% local Pauli error on reset of qubit 1 counts = [3 * shots / 4, 0, shots / 4, 0] counts_lists.append(counts) # 25 % non-local Pauli error on qubit 1 for reset of qubit-0 counts = [3 * shots / 4, 0, shots / 4, 0] counts_lists.append(counts) # Convert to counts dict return [list2dict(i, hex_counts) for i in counts_lists]
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ QasmSimulator readout error NoiseModel integration tests """ from test.terra.utils.utils import list2dict from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Instruction from qiskit.providers.aer.noise import NoiseModel # ========================================================================== # Readout error # ========================================================================== # Error matrices used in tests ROERROR_1Q = [[0.9, 0.1], [0.3, 0.7]] ROERROR_2Q = [[0.3, 0, 0, 0.7], [0, 0.6, 0.4, 0], [0, 0, 1, 0], [0.1, 0, 0, 0.9]] def readout_error_circuits(): """Readout error test circuits""" circuits = [] # Test circuit: ideal bell state for 1-qubit readout errors qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) # Ensure qubit 0 is measured before qubit 1 circuit.barrier(qr) circuit.measure(qr[0], cr[0]) circuit.barrier(qr) circuit.measure(qr[1], cr[1]) # Add three copies of circuit circuits += 3 * [circuit] # 2-qubit correlated readout error circuit measure2 = Instruction("measure", 2, 2, []) # 2-qubit measure qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.h(qr) circuit.barrier(qr) circuit.append(measure2, [0, 1], [0, 1]) circuits.append(circuit) return circuits def readout_error_noise_models(): """Readout error test circuit noise models.""" noise_models = [] # 1-qubit readout error on qubit 0 noise_model = NoiseModel() noise_model.add_readout_error(ROERROR_1Q, [0]) noise_models.append(noise_model) # 1-qubit readout error on qubit 1 noise_model = NoiseModel() noise_model.add_readout_error(ROERROR_1Q, [1]) noise_models.append(noise_model) # 1-qubit readout error on qubit 1 noise_model = NoiseModel() noise_model.add_all_qubit_readout_error(ROERROR_1Q) noise_models.append(noise_model) # 2-qubit readout error on qubits 0,1 noise_model = NoiseModel() noise_model.add_readout_error(ROERROR_2Q, [0, 1]) noise_models.append(noise_model) return noise_models def readout_error_counts(shots, hex_counts=True): """Readout error test circuits reference counts.""" counts_lists = [] # 1-qubit readout error on qubit 0 counts = [ ROERROR_1Q[0][0] * shots / 2, ROERROR_1Q[0][1] * shots / 2, ROERROR_1Q[1][0] * shots / 2, ROERROR_1Q[1][1] * shots / 2 ] counts_lists.append(counts) # 1-qubit readout error on qubit 1 counts = [ ROERROR_1Q[0][0] * shots / 2, ROERROR_1Q[1][0] * shots / 2, ROERROR_1Q[0][1] * shots / 2, ROERROR_1Q[1][1] * shots / 2 ] counts_lists.append(counts) # 1-qubit readout error on qubit 1 p00 = 0.5 * (ROERROR_1Q[0][0]**2 + ROERROR_1Q[1][0]**2) p01 = 0.5 * ( ROERROR_1Q[0][0] * ROERROR_1Q[0][1] + ROERROR_1Q[1][0] * ROERROR_1Q[1][1]) p10 = 0.5 * ( ROERROR_1Q[0][0] * ROERROR_1Q[0][1] + ROERROR_1Q[1][0] * ROERROR_1Q[1][1]) p11 = 0.5 * (ROERROR_1Q[0][1]**2 + ROERROR_1Q[1][1]**2) counts = [p00 * shots, p01 * shots, p10 * shots, p11 * shots] counts_lists.append(counts) # 2-qubit readout error on qubits 0,1 probs_ideal = [0.25, 0.25, 0.25, 0.25] p00 = sum([ ideal * noise[0] for ideal, noise in zip(probs_ideal, ROERROR_2Q) ]) p01 = sum([ ideal * noise[1] for ideal, noise in zip(probs_ideal, ROERROR_2Q) ]) p10 = sum([ ideal * noise[2] for ideal, noise in zip(probs_ideal, ROERROR_2Q) ]) p11 = sum([ ideal * noise[3] for ideal, noise in zip(probs_ideal, ROERROR_2Q) ]) counts = [p00 * shots, p01 * shots, p10 * shots, p11 * shots] counts_lists.append(counts) return [list2dict(i, hex_counts) for i in counts_lists]
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test circuits and reference outputs for reset instruction. """ from numpy import array, sqrt from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit # ========================================================================== # Deterministic output # ========================================================================== def reset_circuits_deterministic(final_measure=True): """Reset test circuits with deterministic count output""" circuits = [] qr = QuantumRegister(2) if final_measure: cr = ClassicalRegister(2) regs = (qr, cr) else: regs = (qr, ) # Reset 0 from |11> circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.reset(qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Reset 1 from |11> circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.reset(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Reset 0,1 from |11> circuit = QuantumCircuit(*regs) circuit.x(qr) circuit.reset(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Reset 0,1 from |++> circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.reset(qr) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def reset_counts_deterministic(shots, hex_counts=True): """Reset test circuits reference counts.""" targets = [] if hex_counts: # Reset 0 from |11> targets.append({'0x2': shots}) # Reset 1 from |11> targets.append({'0x1': shots}) # Reset 0,1 from |11> targets.append({'0x0': shots}) # Reset 0,1 from |++> targets.append({'0x0': shots}) else: # Reset 0 from |11> targets.append({'10': shots}) # Reset 1 from |11> targets.append({'01': shots}) # Reset 0,1 from |11> targets.append({'00': shots}) # Reset 0,1 from |++> targets.append({'00': shots}) return targets def reset_statevector_deterministic(): """Reset test circuits reference counts.""" targets = [] # Reset 0 from |11> targets.append(array([0, 0, 1, 0])) # Reset 1 from |11> targets.append(array([0, 1, 0, 0])) # Reset 0,1 from |11> targets.append(array([1, 0, 0, 0])) # Reset 0,1 from |++> targets.append(array([1, 0, 0, 0])) return targets # ========================================================================== # Non-Deterministic output # ========================================================================== def reset_circuits_nondeterministic(final_measure=True): """Reset test circuits with deterministic count output""" circuits = [] qr = QuantumRegister(2) if final_measure: cr = ClassicalRegister(2) regs = (qr, cr) else: regs = (qr, ) # Reset 0 from |++> circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.reset(qr[0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # Reset 1 from |++> circuit = QuantumCircuit(*regs) circuit.h(qr) circuit.reset(qr[1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def reset_counts_nondeterministic(shots, hex_counts=True): """Reset test circuits reference counts.""" targets = [] if hex_counts: # Reset 0 from |++> targets.append({'0x0': shots / 2, '0x2': shots / 2}) # Reset 1 from |++> targets.append({'0x0': shots / 2, '0x1': shots / 2}) else: # Reset 0 from |++> targets.append({'00': shots / 2, '10': shots / 2}) # Reset 1 from |++> targets.append({'00': shots / 2, '01': shots / 2}) return targets def reset_statevector_nondeterministic(): """Reset test circuits reference counts.""" targets = [] # Reset 0 from |++> targets.append(array([1, 0, 1, 0]) / sqrt(2)) # Reset 1 from |++> targets.append(array([1, 1, 0, 0]) / sqrt(2)) return targets # ========================================================================== # Repeated Resets # ========================================================================== def reset_circuits_repeated(): """Test circuit for repeated measure reset""" qr = QuantumRegister(1) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.x(qr[0]) qc.measure(qr[0], cr[0]) qc.reset(qr[0]) qc.measure(qr[0], cr[1]) qc.reset(qr[0]) return [qc] def reset_counts_repeated(shots, hex_counts=True): """Sampling optimization counts""" if hex_counts: return [{'0x1': shots}] else: return [{'01': shots}] # ========================================================================== # Sampling optimization # ========================================================================== def reset_circuits_sampling_optimization(): """Test sampling optimization""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) # The optimization should not be triggerred # because the reset operation performs randomizations qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.reset([qr[0]]) qc.measure(qr, cr) return [qc] def reset_counts_sampling_optimization(shots, hex_counts=True): """Sampling optimization counts""" if hex_counts: return [{'0x0': shots/2, '0x2': shots/2}] else: return [{'00': shots/2, '10': shots/2}]
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ QasmSimulator reset error NoiseModel integration tests """ from test.terra.utils.utils import list2dict from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors.standard_errors import reset_error # Backwards compatibility for Terra <= 0.13 if not hasattr(QuantumCircuit, 'i'): QuantumCircuit.i = QuantumCircuit.iden # ========================================================================== # Reset Gate Errors # ========================================================================== def reset_gate_error_circuits(): """Reset gate error noise model circuits""" circuits = [] # 50% reset to 0 state on qubit 0 qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.x(qr) circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # 25% reset to 0 state on qubit 1 qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.x(qr) circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # 100% reset error to 0 on all qubits qr = QuantumRegister(1, 'qr') cr = ClassicalRegister(1, 'cr') circuit = QuantumCircuit(qr, cr) circuit.x(qr) circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # 100% reset error to 1 on all qubits qr = QuantumRegister(1, 'qr') cr = ClassicalRegister(1, 'cr') circuit = QuantumCircuit(qr, cr) circuit.i(qr) circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # 25% reset error to 0 and 1 on all qubits qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.i(qr[0]) circuit.x(qr[1]) circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def reset_gate_error_noise_models(): """Reset gate error noise models""" noise_models = [] # 50% reset to 0 state on qubit 0 error = reset_error(0.5) noise_model = NoiseModel() noise_model.add_quantum_error(error, 'x', [0]) noise_models.append(noise_model) # 25% reset to 0 state on qubit 1 error = reset_error(0.25) noise_model = NoiseModel() noise_model.add_quantum_error(error, 'x', [1]) noise_models.append(noise_model) # 100% reset error to 0 on all qubits error = reset_error(1) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error, ['id', 'x']) noise_models.append(noise_model) # 100% reset error to 1 on all qubits error = reset_error(0, 1) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error, ['id', 'x']) noise_models.append(noise_model) # 25% reset error to 0 and 1 on all qubits error = reset_error(0.25, 0.25) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error, ['id', 'x']) noise_models.append(noise_model) return noise_models def reset_gate_error_counts(shots, hex_counts=True): """Reset gate error circuits reference counts""" counts_lists = [] # 50% reset to 0 state on qubit 0 counts = [0, 0, shots / 2, shots / 2] counts_lists.append(counts) # 25% reset to 0 state on qubit 1 counts = [0, shots / 4, 0, 3 * shots / 4] counts_lists.append(counts) # 100% reset error to 0 on all qubits counts = [shots, 0, 0, 0] counts_lists.append(counts) # 100% reset error to 1 on all qubits counts = [0, shots, 0, 0] counts_lists.append(counts) # 25% reset error to 0 and 1 on all qubits counts = [3 * shots / 16, shots / 16, 9 * shots / 16, 3 * shots / 16] counts_lists.append(counts) # Convert to counts dict return [list2dict(i, hex_counts) for i in counts_lists]
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test circuits and reference outputs for snapshot state instructions. """ import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.quantum_info.states import Statevector # from qiskit.providers.aer.extensions.snapshot_expectation_value import * # Backwards compatibility for Terra <= 0.13 if not hasattr(QuantumCircuit, 'i'): QuantumCircuit.i = QuantumCircuit.iden def snapshot_expval_labels(): """List of labels for exp val snapshots.""" return [ "<H[0]>", "<H[1]>", "<X[0]>", "<X[1]>", "<Z[0]>", "<Z[1]>", "<H[0], I[1]>", "<I[0], H[1]>", "<X[0], I[1]>", "<I[0], X[1]>", "<Z[0], I[1]>", "<I[0], Z[1]>", "<X[0], X[1]>", "<Z[0], Z[1]>" ] def snapshot_expval_params(pauli=False): """Dictionary of labels and params, qubits for exp val snapshots.""" if pauli: X_wpo = [[1, 'X']] Y_wpo = [[1, 'Y']] Z_wpo = [[1, 'Z']] H_wpo = [[1 / np.sqrt(2), 'X'], [1 / np.sqrt(2), 'Z']] IX_wpo = [[1, 'IX']] IY_wpo = [[1, 'IY']] IZ_wpo = [[1, 'IZ']] IH_wpo = [[1 / np.sqrt(2), 'IX'], [1 / np.sqrt(2), 'IZ']] XX_wpo = [[1, 'XX']] YY_wpo = [[1, 'YY']] ZZ_wpo = [[1, 'ZZ']] else: X_wpo = np.array([[0, 1], [1, 0]], dtype=complex) Y_wpo = np.array([[0, -1j], [1j, 0]], dtype=complex) Z_wpo = np.array([[1, 0], [0, -1]], dtype=complex) H_wpo = np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2) IX_wpo = np.kron(np.eye(2), X_wpo) IY_wpo = np.kron(np.eye(2), Y_wpo) IZ_wpo = np.kron(np.eye(2), Z_wpo) IH_wpo = np.kron(np.eye(2), H_wpo) XX_wpo = np.kron(X_wpo, X_wpo) YY_wpo = np.kron(Y_wpo, Y_wpo) ZZ_wpo = np.kron(Z_wpo, Z_wpo) return { "<H[0]>": (H_wpo, [0]), "<H[1]>": (H_wpo, [1]), "<X[0]>": (X_wpo, [0]), "<X[1]>": (X_wpo, [1]), "<Y[1]>": (Y_wpo, [0]), "<Y[1]>": (Y_wpo, [1]), "<Z[0]>": (Z_wpo, [0]), "<Z[1]>": (Z_wpo, [1]), "<H[0], I[1]>": (IH_wpo, [0, 1]), "<I[0], H[1]>": (IH_wpo, [1, 0]), "<X[0], I[1]>": (IX_wpo, [0, 1]), "<I[0], X[1]>": (IX_wpo, [1, 0]), "<Y[0], I[1]>": (IY_wpo, [0, 1]), "<I[0], Y[1]>": (IY_wpo, [1, 0]), "<Z[0], I[1]>": (IZ_wpo, [0, 1]), "<I[0], Z[1]>": (IZ_wpo, [1, 0]), "<X[0], X[1]>": (XX_wpo, [0, 1]), "<Y[0], Y[1]>": (YY_wpo, [0, 1]), "<Z[0], Z[1]>": (ZZ_wpo, [0, 1]), } def snapshot_expval_circuits(pauli=False, single_shot=False, variance=False, post_measure=False, skip_measure=False): """SnapshotExpectationValue test circuits with deterministic counts""" circuits = [] num_qubits = 2 qr = QuantumRegister(num_qubits) cr = ClassicalRegister(num_qubits) regs = (qr, cr) # State |+1> circuit = QuantumCircuit(*regs) circuit.x(0) circuit.h(1) if not post_measure: for label, (params, qubits) in snapshot_expval_params(pauli=pauli).items(): circuit.snapshot_expectation_value(label, params, qubits, single_shot=single_shot, variance=variance) circuit.barrier(qr) if not skip_measure: circuit.measure(qr, cr) circuit.barrier(qr) if post_measure: for label, (params, qubits) in snapshot_expval_params(pauli=pauli).items(): circuit.snapshot_expectation_value(label, params, qubits, single_shot=single_shot, variance=variance) circuits.append(circuit) # State |00> + |11> circuit = QuantumCircuit(*regs) circuit.h(0) circuit.cx(0, 1) if not post_measure: for label, (params, qubits) in snapshot_expval_params(pauli=pauli).items(): circuit.snapshot_expectation_value(label, params, qubits, single_shot=single_shot, variance=variance) circuit.barrier(qr) if not skip_measure: circuit.measure(qr, cr) circuit.barrier(qr) if post_measure: for label, (params, qubits) in snapshot_expval_params(pauli=pauli).items(): circuit.snapshot_expectation_value(label, params, qubits, single_shot=single_shot, variance=variance) circuits.append(circuit) # State |10> -i|01> circuit = QuantumCircuit(*regs) circuit.h(0) circuit.sdg(0) circuit.cx(0, 1) circuit.x(1) if not post_measure: for label, (params, qubits) in snapshot_expval_params(pauli=pauli).items(): circuit.snapshot_expectation_value(label, params, qubits, single_shot=single_shot, variance=variance) circuit.barrier(qr) if not skip_measure: circuit.measure(qr, cr) circuit.barrier(qr) if post_measure: for label, (params, qubits) in snapshot_expval_params(pauli=pauli).items(): circuit.snapshot_expectation_value(label, params, qubits, single_shot=single_shot, variance=variance) circuits.append(circuit) return circuits def snapshot_expval_counts(shots): """SnapshotExpectationValue test circuits reference counts.""" targets = [] # State |+1> targets.append({'0x1': shots / 2, '0x3': shots / 2}) # State |00> + |11> targets.append({'0x0': shots / 2, '0x3': shots / 2}) # State |01> -i|01> targets.append({'0x1': shots / 2, '0x2': shots / 2}) return targets def snapshot_expval_final_statevecs(): """SnapshotExpectationValue test circuits pre meas statevecs""" # Get pre-measurement statevectors statevecs = [] # State |+1> statevec = Statevector.from_label('+1') statevecs.append(statevec) # State |00> + |11> statevec = (Statevector.from_label('00') + Statevector.from_label('11')) / np.sqrt(2) statevecs.append(statevec) # State |10> -i|01> statevec = (Statevector.from_label('10') - 1j * Statevector.from_label('01')) / np.sqrt(2) statevecs.append(statevec) return statevecs def snapshot_expval_pre_meas_values(): """SnapshotExpectationValue test circuits reference final probs""" targets = [] for statevec in snapshot_expval_final_statevecs(): values = {} for label, (mat, qubits) in snapshot_expval_params().items(): values[label] = { '0x0': statevec.data.conj().dot(statevec.evolve(mat, qubits).data) } targets.append(values) return targets def snapshot_expval_post_meas_values(): """SnapshotExpectationValue test circuits reference final statevector""" targets = [] for statevec in snapshot_expval_final_statevecs(): values = {} for label, (mat, qubits) in snapshot_expval_params().items(): inner_dict = {} for j in ['00', '01', '10', '11']: # Check if non-zero measurement probability for given # measurement outcome for final statevector vec = Statevector.from_label(j) if not np.isclose(vec.data.dot(statevec.data), 0): # If outcome is non-zero compute expectation value # with post-selected outcome state inner_dict[hex(int(j, 2))] = vec.data.conj().dot(vec.evolve(mat, qubits).data) values[label] = inner_dict targets.append(values) return targets def snapshot_expval_circuit_parameterized(single_shot=False, measure=True, snapshot=False): """SnapshotExpectationValue test circuits, rewritten as a single parameterized circuit and parameterizations array. """ num_qubits = 2 qr = QuantumRegister(num_qubits) cr = ClassicalRegister(num_qubits) regs = (qr, cr) circuit = QuantumCircuit(*regs) circuit.u3(0, 0, 0, 0) circuit.u1(0, 0) circuit.u3(0, 0, 0, 1) circuit.cu3(0, 0, 0, 0, 1) circuit.u3(0, 0, 0, 1) circuit.i(0) if snapshot: for label, (params, qubits) in snapshot_expval_params(pauli=True).items(): circuit.snapshot_expectation_value(label, params, qubits, single_shot=single_shot) if measure: circuit.barrier(qr) circuit.measure(qr, cr) circuit.barrier(qr) # Parameterizations # State |+1> plus_one_params = { # X on 0 (0, 0): np.pi, (0, 1): 0, (0, 2): np.pi, # No rZ (1, 0): 0, # H on 1 (2, 0): np.pi / 2, (2, 2): np.pi, # No CrX (3, 0): 0, (3, 1): 0, (3, 2): 0, # No X (4, 0): 0, (4, 1): 0, (4, 2): 0, } # State |00> + |11> bell_params = { # H 0 (0, 0): np.pi / 2, (0, 1): 0, (0, 2): np.pi, # No rZ (1, 0): 0, # No H (2, 0): 0, (2, 2): 0, # CX from 0 on 1 (3, 0): np.pi, (3, 1): 0, (3, 2): np.pi, # No X (4, 0): 0, (4, 1): 0, (4, 2): 0, } # State |10> -i|01> iminus_bell_params = { # H 0 (0, 0): np.pi / 2, (0, 1): 0, (0, 2): np.pi, # S 0 (1, 0): - np.pi / 2, # No H (2, 0): 0, (2, 2): 0, # CX from 0 on 1 (3, 0): np.pi, (3, 1): 0, (3, 2): np.pi, # X 1 (4, 0): np.pi, (4, 1): 0, (4, 2): np.pi, } param_mat = np.transpose([list(plus_one_params.values()), list(bell_params.values()), list(iminus_bell_params.values())]).tolist() parameterizations = [[list(index), params] for (index, params) in zip(plus_one_params.keys(), param_mat)] return circuit, parameterizations
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test circuits and reference outputs for snapshot state instructions. """ from numpy import array from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.providers.aer.extensions.snapshot_probabilities import * def snapshot_probabilities_labels_qubits(): """Dictionary of labels and qubits for 3-qubit probability snapshots""" return { "[0]": [0], "[1]": [1], "[2]": [2], "[0, 1]": [0, 1], "[1, 0]": [1, 0], "[0, 2]": [0, 2], "[2, 0]": [2, 0], "[1, 2]": [1, 2], "[2, 1]": [2, 1], "[0, 1, 2]": [0, 1, 2], "[1, 2, 0]": [1, 2, 0], "[2, 0, 1]": [2, 0, 1] } def snapshot_probabilities_circuits(post_measure=False): """Snapshot Probabilities test circuits with deterministic counts""" circuits = [] num_qubits = 3 qr = QuantumRegister(num_qubits) cr = ClassicalRegister(num_qubits) regs = (qr, cr) # State |01+> circuit = QuantumCircuit(*regs) circuit.h(0) circuit.x(1) if not post_measure: for label, qubits in snapshot_probabilities_labels_qubits().items(): circuit.snapshot_probabilities(label, qubits) circuit.barrier(qr) circuit.measure(qr, cr) circuit.barrier(qr) if post_measure: for label, qubits in snapshot_probabilities_labels_qubits().items(): circuit.snapshot_probabilities(label, qubits) circuits.append(circuit) # State |010> -i|101> circuit = QuantumCircuit(*regs) circuit.h(0) circuit.sdg(0) circuit.cx(0, 1) circuit.cx(0, 2) circuit.x(1) if not post_measure: for label, qubits in snapshot_probabilities_labels_qubits().items(): circuit.snapshot_probabilities(label, qubits) circuit.barrier(qr) circuit.measure(qr, cr) circuit.barrier(qr) if post_measure: for label, qubits in snapshot_probabilities_labels_qubits().items(): circuit.snapshot_probabilities(label, qubits) circuits.append(circuit) return circuits def snapshot_probabilities_counts(shots): """Snapshot Probabilities test circuits reference counts.""" targets = [] # State |01+> targets.append({'0x2': shots / 2, '0x3': shots / 2}) # State |010> -i|101> targets.append({'0x2': shots / 2, '0x5': shots / 2}) return targets def snapshot_probabilities_pre_meas_probs(): """Snapshot Probabilities test circuits reference final probs""" targets = [] # State |01+> probs = { "[0]": {'0x0': {'0x0': 0.5, '0x1': 0.5}}, "[1]": {'0x0': {'0x1': 1.0}}, "[2]": {'0x0': {'0x0': 1.0}}, "[0, 1]": {'0x0': {'0x2': 0.5, '0x3': 0.5}}, "[1, 0]": {'0x0': {'0x1': 0.5, '0x3': 0.5}}, "[0, 2]": {'0x0': {'0x0': 0.5, '0x1': 0.5}}, "[2, 0]": {'0x0': {'0x0': 0.5, '0x2': 0.5}}, "[1, 2]": {'0x0': {'0x1': 1.0}}, "[2, 1]": {'0x0': {'0x2': 1.0}}, "[0, 1, 2]": {'0x0': {'0x2': 0.5, '0x3': 0.5}}, "[1, 2, 0]": {'0x0': {'0x1': 0.5, '0x5': 0.5}}, "[2, 0, 1]": {'0x0': {'0x4': 0.5, '0x6': 0.5}}, } targets.append(probs) # State |010> -i|101> probs = { "[0]": {'0x0': {'0x0': 0.5, '0x1': 0.5}}, "[1]": {'0x0': {'0x0': 0.5, '0x1': 0.5}}, "[2]": {'0x0': {'0x0': 0.5, '0x1': 0.5}}, "[0, 1]": {'0x0': {'0x1': 0.5, '0x2': 0.5}}, "[1, 0]": {'0x0': {'0x1': 0.5, '0x2': 0.5}}, "[0, 2]": {'0x0': {'0x0': 0.5, '0x3': 0.5}}, "[2, 0]": {'0x0': {'0x0': 0.5, '0x3': 0.5}}, "[1, 2]": {'0x0': {'0x1': 0.5, '0x2': 0.5}}, "[2, 1]": {'0x0': {'0x1': 0.5, '0x2': 0.5}}, "[0, 1, 2]": {'0x0': {'0x2': 0.5, '0x5': 0.5}}, "[1, 2, 0]": {'0x0': {'0x1': 0.5, '0x6': 0.5}}, "[2, 0, 1]": {'0x0': {'0x3': 0.5, '0x4': 0.5}}, } targets.append(probs) return targets def snapshot_probabilities_post_meas_probs(): """Snapshot Probabilities test circuits reference final statevector""" targets = [] # State |01+> probs = { "[0]": {'0x2': {'0x0': 1.0}, '0x3': {'0x1': 1.0}}, "[1]": {'0x2': {'0x1': 1.0}, '0x3': {'0x1': 1.0}}, "[2]": {'0x2': {'0x0': 1.0}, '0x3': {'0x0': 1.0}}, "[0, 1]": {'0x2': {'0x2': 1.0}, '0x3': {'0x3': 1.0}}, "[1, 0]": {'0x2': {'0x1': 1.0}, '0x3': {'0x3': 1.0}}, "[0, 2]": {'0x2': {'0x0': 1.0}, '0x3': {'0x1': 1.0}}, "[2, 0]": {'0x2': {'0x0': 1.0}, '0x3': {'0x2': 1.0}}, "[1, 2]": {'0x2': {'0x1': 1.0}, '0x3': {'0x1': 1.0}}, "[2, 1]": {'0x2': {'0x2': 1.0}, '0x3': {'0x2': 1.0}}, "[0, 1, 2]": {'0x2': {'0x2': 1.0}, '0x3': {'0x3': 1.0}}, "[1, 2, 0]": {'0x2': {'0x1': 1.0}, '0x3': {'0x5': 1.0}}, "[2, 0, 1]": {'0x2': {'0x4': 1.0}, '0x3': {'0x6': 1.0}}, } targets.append(probs) # State |010> -i|101> probs = { "[0]": {'0x2': {'0x0': 1.0}, '0x5': {'0x1': 1.0}}, "[1]": {'0x2': {'0x1': 1.0}, '0x5': {'0x0': 1.0}}, "[2]": {'0x2': {'0x0': 1.0}, '0x5': {'0x1': 1.0}}, "[0, 1]": {'0x2': {'0x2': 1.0}, '0x5': {'0x1': 1.0}}, "[1, 0]": {'0x2': {'0x1': 1.0}, '0x5': {'0x2': 1.0}}, "[0, 2]": {'0x2': {'0x0': 1.0}, '0x5': {'0x3': 1.0}}, "[2, 0]": {'0x2': {'0x0': 1.0}, '0x5': {'0x3': 1.0}}, "[1, 2]": {'0x2': {'0x1': 1.0}, '0x5': {'0x2': 1.0}}, "[2, 1]": {'0x2': {'0x2': 1.0}, '0x5': {'0x1': 1.0}}, "[0, 1, 2]": {'0x2': {'0x2': 1.0}, '0x5': {'0x5': 1.0}}, "[1, 2, 0]": {'0x2': {'0x1': 1.0}, '0x5': {'0x6': 1.0}}, "[2, 0, 1]": {'0x2': {'0x4': 1.0}, '0x5': {'0x3': 1.0}}, } targets.append(probs) return targets
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test circuits and reference outputs for snapshot state instructions. """ from numpy import array, sqrt from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.providers.aer.extensions.snapshot import Snapshot from qiskit.providers.aer.extensions.snapshot_statevector import * def snapshot_state_circuits_deterministic(snapshot_label='snap', snapshot_type='statevector', post_measure=False): """Snapshot Statevector test circuits""" circuits = [] num_qubits = 3 qr = QuantumRegister(num_qubits) cr = ClassicalRegister(num_qubits) regs = (qr, cr) # State snapshot instruction acting on all qubits snapshot = Snapshot(snapshot_label, snapshot_type, num_qubits) # Snapshot |000> circuit = QuantumCircuit(*regs) if not post_measure: circuit.append(snapshot, qr) circuit.barrier(qr) circuit.measure(qr, cr) if post_measure: circuit.append(snapshot, qr) circuits.append(circuit) # Snapshot |111> circuit = QuantumCircuit(*regs) circuit.x(qr) if not post_measure: circuit.append(snapshot, qr) circuit.barrier(qr) circuit.measure(qr, cr) if post_measure: circuit.append(snapshot, qr) circuits.append(circuit) return circuits def snapshot_state_counts_deterministic(shots): """Snapshot Statevector test circuits reference counts.""" targets = [] # Snapshot |000> targets.append({'0x0': shots}) # Snapshot |111> targets.append({'0x7': shots}) return targets def snapshot_state_pre_measure_statevector_deterministic(): """Snapshot Statevector test circuits reference final statevector""" targets = [] # Snapshot |000> targets.append(array([1, 0, 0, 0, 0, 0, 0, 0], dtype=complex)) # Snapshot |111> targets.append(array([0, 0, 0, 0, 0, 0, 0, 1], dtype=complex)) return targets def snapshot_state_post_measure_statevector_deterministic(): """Snapshot Statevector test circuits reference final statevector""" targets = [] # Snapshot |000> targets.append({'0x0': array([1, 0, 0, 0, 0, 0, 0, 0], dtype=complex)}) # Snapshot |111> targets.append({'0x7': array([0, 0, 0, 0, 0, 0, 0, 1], dtype=complex)}) return targets def snapshot_state_circuits_nondeterministic(snapshot_label='snap', snapshot_type='statevector', post_measure=False): """Snapshot Statevector test circuits""" circuits = [] num_qubits = 3 qr = QuantumRegister(num_qubits) cr = ClassicalRegister(num_qubits) regs = (qr, cr) # State snapshot instruction acting on all qubits snapshot = Snapshot(snapshot_label, snapshot_type, num_qubits) # Snapshot |000> + i|111> circuit = QuantumCircuit(*regs) circuit.h(qr[0]) circuit.s(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[2]) if not post_measure: circuit.append(snapshot, qr) circuit.barrier(qr) circuit.measure(qr, cr) if post_measure: circuit.append(snapshot, qr) circuits.append(circuit) # Snapshot |+++> circuit = QuantumCircuit(*regs) circuit.h(qr) if not post_measure: circuit.append(snapshot, qr) circuit.barrier(qr) circuit.measure(qr, cr) if post_measure: circuit.append(snapshot, qr) circuits.append(circuit) return circuits def snapshot_state_counts_nondeterministic(shots): """Snapshot Statevector test circuits reference counts.""" targets = [] # Snapshot |000> + i|111> targets.append({'0x0': shots/2, '0x7': shots/2}) # Snapshot |+++> targets.append({'0x0': shots/8, '0x1': shots/8, '0x2': shots/8, '0x3': shots/8, '0x4': shots/8, '0x5': shots/8, '0x6': shots/8, '0x7': shots/8}) return targets def snapshot_state_pre_measure_statevector_nondeterministic(): """Snapshot Statevector test circuits reference final statevector""" targets = [] # Snapshot |000> + i|111> targets.append(array([1, 0, 0, 0, 0, 0, 0, 1j], dtype=complex) / sqrt(2)) # Snapshot |+++> targets.append(array([1, 1, 1, 1, 1, 1, 1, 1], dtype=complex) / sqrt(8)) return targets def snapshot_state_post_measure_statevector_nondeterministic(): """Snapshot Statevector test circuits reference final statevector""" targets = [] # Snapshot |000> + i|111> targets.append({'0x0': array([1, 0, 0, 0, 0, 0, 0, 0], dtype=complex), '0x7': array([0, 0, 0, 0, 0, 0, 0, 1j], dtype=complex)}) # Snapshot |+++> targets.append({'0x0': array([1, 0, 0, 0, 0, 0, 0, 0], dtype=complex), '0x1': array([0, 1, 0, 0, 0, 0, 0, 0], dtype=complex), '0x2': array([0, 0, 1, 0, 0, 0, 0, 0], dtype=complex), '0x3': array([0, 0, 0, 1, 0, 0, 0, 0], dtype=complex), '0x4': array([0, 0, 0, 0, 1, 0, 0, 0], dtype=complex), '0x5': array([0, 0, 0, 0, 0, 1, 0, 0], dtype=complex), '0x6': array([0, 0, 0, 0, 0, 0, 1, 0], dtype=complex), '0x7': array([0, 0, 0, 0, 0, 0, 0, 1], dtype=complex)}) return targets
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Test circuits and reference outputs for measure instruction. """ import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info import Statevector def unitary_gate_circuits_deterministic(final_measure=True): """Unitary gate test circuits with deterministic count output.""" circuits = [] qr = QuantumRegister(2, 'qr') if final_measure: cr = ClassicalRegister(2, 'cr') regs = (qr, cr) else: regs = (qr, ) y_mat = np.array([[0, -1j], [1j, 0]], dtype=complex) cx_mat = np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]], dtype=complex) # CX01, |00> state circuit = QuantumCircuit(*regs) circuit.unitary(cx_mat, [0, 1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX10, |00> state circuit = QuantumCircuit(*regs) circuit.unitary(cx_mat, [1, 0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX01.(Y^I), |10> state circuit = QuantumCircuit(*regs) circuit.unitary(y_mat, [1]) circuit.unitary(cx_mat, [0, 1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX10.(I^Y), |01> state circuit = QuantumCircuit(*regs) circuit.unitary(y_mat, [0]) circuit.unitary(cx_mat, [1, 0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX01.(I^Y), |11> state circuit = QuantumCircuit(*regs) circuit.unitary(y_mat, [0]) circuit.unitary(cx_mat, [0, 1]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) # CX10.(Y^I), |11> state circuit = QuantumCircuit(*regs) circuit.unitary(y_mat, [1]) circuit.unitary(cx_mat, [1, 0]) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def unitary_gate_counts_deterministic(shots, hex_counts=True): """Unitary gate circuits reference counts.""" targets = [] if hex_counts: # CX01, |00> state targets.append({'0x0': shots}) # {"00": shots} # CX10, |00> state targets.append({'0x0': shots}) # {"00": shots} # CX01.(Y^I), |10> state targets.append({'0x2': shots}) # {"00": shots} # CX10.(I^Y), |01> state targets.append({'0x1': shots}) # {"00": shots} # CX01.(I^Y), |11> state targets.append({'0x3': shots}) # {"00": shots} # CX10.(Y^I), |11> state targets.append({'0x3': shots}) # {"00": shots} else: # CX01, |00> state targets.append({'00': shots}) # {"00": shots} # CX10, |00> state targets.append({'00': shots}) # {"00": shots} # CX01.(Y^I), |10> state targets.append({'10': shots}) # {"00": shots} # CX10.(I^Y), |01> state targets.append({'01': shots}) # {"00": shots} # CX01.(I^Y), |11> state targets.append({'11': shots}) # {"00": shots} # CX10.(Y^I), |11> state return targets def unitary_gate_statevector_deterministic(): """Unitary gate test circuits with deterministic counts.""" targets = [] # CX01, |00> state targets.append(np.array([1, 0, 0, 0])) # CX10, |00> state targets.append(np.array([1, 0, 0, 0])) # CX01.(Y^I), |10> state targets.append(np.array([0, 0, 1j, 0])) # CX10.(I^Y), |01> state targets.append(np.array([0, 1j, 0, 0])) # CX01.(I^Y), |11> state targets.append(np.array([0, 0, 0, 1j])) # CX10.(Y^I), |11> state targets.append(np.array([0, 0, 0, 1j])) return targets def unitary_gate_unitary_deterministic(): """Unitary gate circuits reference unitaries.""" targets = [] # CX01, |00> state targets.append(np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]])) # CX10, |00> state targets.append(np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])) # CX01.(Y^I), |10> state targets.append(np.array([[0, 0, -1j, 0], [0, 1j, 0, 0], [1j, 0, 0, 0], [0, 0, 0, -1j]])) # CX10.(I^Y), |01> state targets.append(np.array([[0, -1j, 0, 0], [1j, 0, 0, 0], [0, 0, 1j, 0], [0, 0, 0, -1j]])) # CX01.(I^Y), |11> state targets.append(np.array([[0, -1j, 0, 0], [0, 0, 1j, 0], [0, 0, 0, -1j], [1j, 0, 0, 0]])) # CX10.(Y^I), |11> state targets.append(np.array([[0, 0, -1j, 0], [0, 0, 0, -1j], [0, 1j, 0, 0], [1j, 0, 0, 0]])) return targets def unitary_random_gate_circuits_nondeterministic(final_measure=True): """Unitary gate test circuits with random unitary gate and nondeterministic count output.""" # random_unitary seed = nq circuits = [] for n in range(1, 5): qr = QuantumRegister(n, 'qr') if final_measure: cr = ClassicalRegister(n, 'cr') regs = (qr, cr) else: regs = (qr, ) circuit = QuantumCircuit(*regs) circuit.unitary(random_unitary(2 ** n, seed=n), list(range(n))) if final_measure: circuit.barrier(qr) circuit.measure(qr, cr) circuits.append(circuit) return circuits def unitary_random_gate_counts_nondeterministic(shots): """Unitary gate test circuits with nondeterministic counts.""" # random_unitary seed = nq targets = [] for n in range(1, 5): unitary1 = random_unitary(2 ** n, seed=n) state = Statevector.from_label(n * '0').evolve(unitary1) state.seed(10) counts = state.sample_counts(shots=shots) hex_counts = {hex(int(key, 2)): val for key, val in counts.items()} targets.append(hex_counts) return targets
https://github.com/papaaannn/Circuit
papaaannn
import numpy as np from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import circuit_drawer from qiskit.tools.visualization import plot_histogram # Total number of inputs n = 8 # Random n numbers a = np.random.randint(0, 2**n, size=n) # Check if n is a power of 2 if not (n and (not (n & (n - 1)))) or len(a) != n: raise ValueError("n must be a power of 2 and len(a) must be n") # Initialize the circuit and the registers circuit = QuantumCircuit(2*n, name="bitonic_sort") a_reg = [i for i in range(n)] c_reg = [i + n for i in range(n)] # Apply Hadamard gates to all input qubits circuit.h(a_reg) # Apply the bitonic sort operations recursively for k in range(1, n): for j in range(k, 0, -1): circuit.cswap(j + k - 1, j - 1, c_reg[k]) for i in range(j - 1): circuit.cswap(j + k - 1, i, c_reg[k]) # Measure the qubits and run the circuit circuit.measure_all() circuit_drawer(circuit, output='mpl') backend = Aer.get_backend('qasm_simulator') shots = 1024 job = execute(circuit, backend=backend, shots=shots) result = job.result() counts = result.get_counts() plot_histogram(counts, figsize=(100,30)) # Extract the sorted output from the measurement results output = [int(key[::-1], 2) for key in sorted(counts.keys())] print(f"Input array: {a}") print(f"Sorted array: {output}")
https://github.com/jfraxanet/BasQ_industry_workshop_Qiskit
jfraxanet
import rustworkx as rx from rustworkx.visualization import mpl_draw num_nodes = 5 edges = [(0, 1, 1), (0, 2, 1), (0, 3, 1), (0, 4, 1)]# The edge syntax is (start, end, weight) G = rx.PyGraph() G.add_nodes_from(range(num_nodes)) G.add_edges_from(edges) mpl_draw( G, pos=rx.bipartite_layout(G, {0}), with_labels=True, node_color='tab:purple', font_color='white' ) import numpy as np from qiskit.quantum_info import SparsePauliOp # Problem to Hamiltonian operator hamiltonian = SparsePauliOp.from_list([("IIIZZ", 1), ("IIZIZ", 1), ("IZIIZ", 1), ("ZIIIZ", 1)]) print(hamiltonian) from qiskit.circuit.library import QAOAAnsatz # QAOA ansatz circuit ansatz = QAOAAnsatz(hamiltonian, reps=2) ansatz.decompose(reps=3).draw(output="mpl", style="clifford") ansatz.decompose(reps=1).draw(output="mpl", style="clifford") from qiskit.primitives import Estimator estimator = Estimator() # If we want to run it on the real device, use these lines instead: #from qiskit_ibm_runtime import QiskitRuntimeService #from qiskit_ibm_runtime import Estimator, Sampler, Session, Options #service = QiskitRuntimeService(channel="ibm_quantum", token=<YOUR TOKEN>) #backend = service.least_busy(operational=True, simulator=False) #print(backend.name) #options = Options() #options.resilience_level = 1 #options.optimization_level = 3 #estimator = Estimator(backend, options=options) def cost_func(params, ansatz, hamiltonian, estimator): """Return estimate of energy from estimator Parameters: params (ndarray): Array of ansatz parameters ansatz (QuantumCircuit): Parameterized ansatz circuit hamiltonian (SparsePauliOp): Operator representation of Hamiltonian estimator (Estimator): Estimator primitive instance Returns: float: Energy estimate """ cost = estimator.run(ansatz, hamiltonian, parameter_values=params).result().values[0] return cost from scipy.optimize import minimize # Randomly initialize the parameters of the ansatz x0 = 2 * np.pi * np.random.rand(ansatz.num_parameters) # Run the variational algorithm res = minimize(cost_func, x0, args=(ansatz, hamiltonian, estimator), method="COBYLA") print(res) from qiskit.primitives import Sampler sampler = Sampler() # If instead we want to run it on the device # we need the sampler from runtime # sampler = Sampler(backend, options=options) # Assign solution parameters to ansatz qc = ansatz.assign_parameters(res.x) qc.measure_all() # Draw circuit with optimal parameters #qc_ibm.draw(output="mpl", idle_wires=False, style="iqp") from qiskit.visualization import plot_distribution # Sample ansatz at optimal parameters samp_dist = sampler.run(qc).result().quasi_dists[0] plot_distribution(samp_dist.binary_probabilities(), figsize=(15, 5))
https://github.com/jfraxanet/BasQ_industry_workshop_Qiskit
jfraxanet
from qiskit import QuantumCircuit # Create circuit circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) circuit.draw('mpl',style="iqp",initial_state=True) import qiskit.quantum_info as qi from qiskit.visualization import array_to_latex qc = QuantumCircuit(2) qc.x(0) qc.h(0) qc.cx(0, 1) psi = qi.Statevector.from_instruction(qc) array_to_latex(psi) # quiz-time! from qiskit.visualization import plot_state_qsphere plot_state_qsphere(psi) from qiskit.visualization import plot_state_city plot_state_city(psi) from qiskit.visualization import plot_state_hinton plot_state_hinton(psi) from qiskit.visualization import plot_state_paulivec plot_state_paulivec(psi) circuit.measure_all() circuit.draw('mpl',style="iqp",initial_state=True) from qiskit_aer import AerSimulator backend = AerSimulator() # this is the simulator we'll use job = backend.run(circuit,shots=1000) # this runs the experiment result = job.result() counts = result.get_counts() # quiz-time! # quiz-time! from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Options # set account here https://quantum.ibm.com/ service = QiskitRuntimeService(instance="ibm-q-ikerbasque/industry-qiskit-/generic-project") # when loading your IBM Quantum account for the first time you need to specify your token: #service = QiskitRuntimeService(instance="ibm-q-ikerbasque/industry-qiskit-/generic-project", token="token") [(b.name, b.configuration().n_qubits) for b in service.backends()] from qiskit_ibm_provider import least_busy backend = service.least_busy(simulator=False, operational=True) #backend = service.backend("ibm_brisbane") print(backend) from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager pm = generate_preset_pass_manager(backend=backend, initial_layout=[0,6], optimization_level=3) t_qc = pm.run(circuit) t_qc.draw('mpl',style="iqp",idle_wires=False) from qiskit.visualization import plot_circuit_layout, plot_gate_map display(plot_circuit_layout(t_qc, backend)) pm = generate_preset_pass_manager(backend=backend, optimization_level=3) t_qc = pm.run(circuit) t_qc.draw('mpl',style="iqp",idle_wires=False) options = Options() options.resilience_level = 1 options.optimization_level = 3 # Create a Sampler object sampler = Sampler(backend=backend, options=options) # Submit the circuit to Sampler job = sampler.run(t_qc,shots=1000) print(job.job_id()) job.status() # get results job = service.job('cqcbzgyapgkg008jxcwg') result = job.result() counts = result.quasi_dists plot_histogram(counts) from qiskit.quantum_info import Operator def phase_oracle(n, indices_to_mark, name = 'Oracle'): qc = QuantumCircuit(n, name=name) oracle_matrix = np.identity(2**n) for index_to_mark in indices_to_mark: oracle_matrix[index_to_mark, index_to_mark] = -1 qc.unitary(Operator(oracle_matrix), range(n)) return qc def diffuser(n): qc = QuantumCircuit(n, name='Diff') qc.h(range(n)) qc.append(phase_oracle(n,[0]),range(n)) qc.h(range(n)) return qc def Grover(n, marked): qc = QuantumCircuit(n, n) r = int(np.round(np.pi/(4*np.arcsin(np.sqrt(len(marked)/2**n)))-1/2)) print(f'{n} qubits, basis state {marked} marked, {r} rounds') qc.h(range(n)) for _ in range(r): qc.append(phase_oracle(n,marked), range(n)) qc.append(diffuser(n), range(n)) qc.measure(range(n), range(n)) return qc import numpy as np n = 5 x = np.random.randint(2**n) marked = [x] qc = Grover(n, marked) qc.draw('mpl',style="iqp",initial_state=True) from qiskit_aer import AerSimulator from qiskit import transpile backend = AerSimulator() tqc = transpile(qc, backend) result = backend.run(tqc, shots=10000).result() counts = result.get_counts(qc) print(counts) plot_histogram(counts) # quiz-time! def Grover_run_roundwise(n, marked): r = int(np.round(np.pi/(4*np.arcsin(np.sqrt(len(marked)/2**n)))-1/2)) print(f'{n} qubits, basis state {marked} marked, {r} rounds') counts = [] for i in range(r): qc = QuantumCircuit(n, n) qc.h(range(n)) for _ in range(i+1): qc.append(phase_oracle(n,marked), range(n)) qc.append(diffuser(n), range(n)) qc.measure(range(n), range(n)) tqc = transpile(qc, backend) result = backend.run(tqc, shots=10000).result() counts.append(result.get_counts()) return counts backend = AerSimulator() counts = Grover_run_roundwise(n,marked) # quiz-time! n = 3 x = np.random.randint(2**n) y = np.random.randint(2**n) while y==x: y = np.random.randint(2**n) marked = [x,y] qc = Grover(n, marked) backend = service.least_busy(simulator=False, operational=True) print("least busy backend: ", backend) #backend = provider.get_backend('ibm_osaka') shots = 10000 pm = generate_preset_pass_manager(backend=backend, optimization_level=3) tqc = pm.run(qc) job = sampler.run(tqc,shots=1000) print(job.job_id()) old_job = service.job('cqcc09sqgrzg008cw7ng') results = old_job.result() counts = results.quasi_dists plot_histogram(counts) from qiskit.circuit.library import PhaseOracle # this indicates that the input is CNF with five variables and seven clauses input_3sat = ''' c example DIMACS-CNF 3-SAT p cnf 5 7 -1 -5 0 1 -3 0 -1 3 0 2 4 0 -2 -3 -4 0 1 -2 0 2 -4 0 ''' with open("3sat.dimacs", "w") as text_file: text_file.write(input_3sat) oracle = PhaseOracle.from_dimacs_file("3sat.dimacs") from qiskit_algorithms import Grover, AmplificationProblem from qiskit.utils import QuantumInstance from qiskit.primitives import Sampler import warnings #warnings.filterwarnings('ignore') problem = AmplificationProblem(oracle=oracle) # Use Grover's algorithm to solve the problem grover = Grover(sampler = Sampler()) result = grover.amplify(problem) result.top_measurement plot_histogram(result.circuit_results) # quiz-time! # transpile the circuit for our backend qc = grover.construct_circuit(problem, max(result.iterations)) qc.measure_all() backend = service.backend("ibm_osaka") grover_compiled = transpile(qc, backend=backend, optimization_level=3) print('gates = ', grover_compiled.count_ops()) print('depth = ', grover_compiled.depth()) from qiskit import QuantumCircuit, transpile # GHZ state n = 3 qc = QuantumCircuit(n, n) qc.h(1) qc.cx(1, 0) qc.cx(1, 2) qc.measure(range(n), range(n)) layout = [0,14,18] pm = generate_preset_pass_manager(backend=backend, initial_layout=layout, optimization_level=3) t_qc = pm.run(qc) from qiskit_ibm_runtime import Sampler options.resilience_level = 1 sampler = Sampler(backend=backend,options=options) #job = sampler.run(t_qc, shots=shots) #print(job.job_id()) options.resilience_level = 0 sampler = Sampler(backend=backend,options=options) #job = sampler.run(t_qc, shots=shots) #print(job.job_id()) ghz_mem = service.job('cqdryehfejeg0085wt00') # [0,14,18] ghz_nomem = service.job('cqdryfsgtagg008qr8s0') results = ghz_nomem.result() counts_nomem = results.quasi_dists results = ghz_mem.result() counts_mem = results.quasi_dists plot_histogram([counts_nomem[0],counts_mem[0]], legend=['noisy', 'mitigated']) # quiz-time! print(counts_nomem[0]) print(counts_mem[0]) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/jfraxanet/BasQ_industry_workshop_Qiskit
jfraxanet
from qiskit import QuantumCircuit #define quantum circuit qc = QuantumCircuit(4) #add gates qc.h(0) qc.cx(0,1) qc.h(2) qc.x(3) qc.cx(2,3) qc.measure_all() #draw qc.draw('mpl', style='clifford') #draw result = sampler.run(qc) print(result) from qiskit.primitives import Sampler from qiskit.visualization import plot_distribution sampler = Sampler() samp_dist = sampler.run(qc).result().quasi_dists[0] plot_distribution(samp_dist.binary_probabilities(), figsize=(15, 5)) from qiskit.circuit.library import NLocal, CZGate, RZGate, RXGate from qiskit.circuit import Parameter from qiskit import QuantumCircuit qc = QuantumCircuit(5) qc.x(0) qc.barrier() theta = Parameter("θ") ansatz = NLocal( initial_state = qc, num_qubits=5, rotation_blocks=[RXGate(theta), RZGate(theta)], entanglement_blocks = [CZGate()], entanglement=[[0, 1], [0, 2], [2, 1], [2, 4]], reps=2, insert_barriers=True, ) ansatz.decompose().draw("mpl") from qiskit.primitives import Estimator from qiskit import QuantumCircuit from qiskit.quantum_info import SparsePauliOp O = SparsePauliOp(["X", "Z"], [2, -1]) estimator = Estimator() qc1 = QuantumCircuit(1) job = estimator.run(qc1, O) expvals1 = job.result().values print("Exp. val qs1: ", expvals1) qc2 = QuantumCircuit(1) qc2.h(0) job = estimator.run(qc2, O) expvals2 = job.result().values print("Exp. val qs2: ", expvals2) from qiskit.circuit.library import NLocal, CXGate, RZGate, RXGate from qiskit.circuit import Parameter from qiskit import QuantumCircuit # Define an initial state with two qubits qc = QuantumCircuit(2) qc.x(0) qc.barrier() # Define an general ansatz theta = Parameter("θ") ansatz = NLocal( initial_state = qc, num_qubits=2, rotation_blocks=[RXGate(theta), RZGate(theta)], entanglement_blocks = [CXGate()], entanglement=[[0, 1]], reps=1, insert_barriers=True, ) ansatz.decompose().draw("mpl", style='Clifford') from scipy.optimize import minimize from qiskit.quantum_info import SparsePauliOp from qiskit.primitives import Estimator import numpy as np # Define observable and estimator observable = SparsePauliOp(["IZ", "ZI"], [-1,-1]) estimator = Estimator() # Define cost function def cost_func(params, ansatz, observable, estimator): cost = estimator.run(ansatz, observable, parameter_values=params).result().values[0] return cost # Define initial state of parameters randomly x0 = 2 * np.pi * np.random.rand(ansatz.num_parameters) # Minimize using an optimization method like COBYLA, SLSQP... res = minimize(cost_func, x0, args=(ansatz, observable, estimator), method="COBYLA") print(res) qc = ansatz.assign_parameters(res.x) qc.measure_all() qc.draw("mpl", style="clifford") from qiskit.visualization import plot_distribution samp_dist = sampler.run(qc).result().quasi_dists[0] plot_distribution(samp_dist.binary_probabilities(), figsize=(15, 5))
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
jonasmaziero
from IPython.display import IFrame; IFrame("https://www.ibm.com/quantum", 900,500) import csv with open('ibm_lagos_calibrations_2023-09-28T17_22_25Z.csv', newline='') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in spamreader: print(', '.join(row)) import qiskit qiskit.__qiskit_version__ # Copie se API Token no IBMQ e cole aqui qiskit.IBMQ.save_account('ee8631db565e87e97b066d08e02cafb9bfa745be07e573095b666daa608a37ce58ae6ef5c174aff56a935dadfe1fa9c82edfe37aec6b24774bc94613658cc7d8', overwrite = True) # Execute esse comando uma vez só qiskit.IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider.backends() from qiskit import * qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr,cr) qc.h(qr[0]) qc.cx(qr[0],qr[1]) qc.measure(qr[0],cr[0]) qc.measure(qr[1],cr[1]) qc.draw('mpl') simulator = Aer.get_backend('qasm_simulator') nshots = 8192 # número de "prepara-e-mede" job = execute(qc, backend = simulator, shots = nshots) from qiskit.tools.visualization import plot_histogram plot_histogram(job.result().get_counts(qc)) # Acessando as contagens com numpy counts = job.result().get_counts(qc) counts counts['00'] # probabilidade p00 = 0; p01 = 0; p10 = 0; p11 = 0 for j in (0,2): for k in (0,2): if '00' in counts: p00 = counts['00']/nshots if '01' in counts: p01 = counts['01']/nshots if '10' in counts: p10 = counts['10']/nshots if '11' in counts: p11 = counts['11']/nshots p00, p01, p10, p11 device = provider.get_backend('ibm_lagos') from qiskit.tools.monitor import job_monitor job = execute(qc, backend = device, shots = nshots) job_monitor(job) plot_histogram(job.result().get_counts(qc)) counts = job.result().get_counts(qc) counts counts['00'] # probabilidade p00 = 0; p01 = 0; p10 = 0; p11 = 0 for j in (0,2): for k in (0,2): if '00' in counts: p00 = counts['00']/nshots if '01' in counts: p01 = counts['01']/nshots if '10' in counts: p10 = counts['10']/nshots if '11' in counts: p11 = counts['11']/nshots p00, p01, p10, p11
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
jonasmaziero
pip install -U qiskit==0.36.2 pip install pylatexenc import qiskit qiskit.__qiskit_version__ # Copie se API Token no IBMQ e cole aqui qiskit.IBMQ.save_account('ade2e1cd8926fee57b535ff0761ddac06ce27b6ea7ea0ecb60121d873ccf19578850d46431bbb002e5a64db18657e028fd17ae71b73ce25c57002e2ff579eeb6', overwrite = True) # Execute esse comando uma vez só qiskit.IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider.backends() from qiskit import * qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr,cr) qc.h(qr[0]) qc.cx(qr[0],qr[1]) qc.measure(qr[0],cr[0]) qc.measure(qr[1],cr[1]) qc.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') nshots = 8192 # número de "prepara-e-mede" job = execute(qc, backend = simulator, shots = nshots) from qiskit.tools.visualization import plot_histogram plot_histogram(job.result().get_counts(qc)) counts = job.result().get_counts(qc) counts counts['00'] # probabilidade p00 = 0; p01 = 0; p10 = 0; p11 = 0 for j in (0,2): for k in (0,2): if '00' in counts: p00 = counts['00']/nshots if '01' in counts: p01 = counts['01']/nshots if '10' in counts: p10 = counts['10']/nshots if '11' in counts: p11 = counts['11']/nshots p00, p01, p10, p11 device = provider.get_backend('ibm_nairobi') from qiskit.tools.monitor import job_monitor job = execute(qc, backend = device, shots = nshots) job_monitor(job) plot_histogram(job.result().get_counts(qc)) counts = job.result().get_counts(qc) counts counts['00'] # probabilidade p00 = 0; p01 = 0; p10 = 0; p11 = 0 for j in (0,2): for k in (0,2): if '00' in counts: p00 = counts['00']/nshots if '01' in counts: p01 = counts['01']/nshots if '10' in counts: p10 = counts['10']/nshots if '11' in counts: p11 = counts['11']/nshots p00, p01, p10, p11
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
jonasmaziero
from sympy import Matrix X = Matrix([[0,1],[1,0]]); X Y = Matrix([[0,-1j],[1j,0]]); Y Z = Matrix([[1,0],[0,-1]]); Z X.eigenvals() X.eigenvects() Y.eigenvects() Z.eigenvects() from sympy import Matrix X = Matrix([[0,1],[1,0]]) ket0 = Matrix([[1],[0]]); ket1 = Matrix([[0],[1]]); ket0, ket1 X*ket0, X*ket1 Y*ket0, Y*ket1, Z*ket0, Z*ket1 from sympy.physics.quantum import TensorProduct as tp ket00 = tp(ket0,ket0); ket01 = tp(ket0,ket1); ket10 = tp(ket1,ket0); ket11 = tp(ket1,ket1); ket00, ket01, ket10, ket11 tp(eye(2),X), tp(eye(2),eye(2))*ket00, tp(eye(2),X)*ket00, tp(X,eye(2))*ket00, tp(X,X)*ket00 from qiskit import QuantumCircuit import qiskit from qiskit.quantum_info import Statevector qc = QuantumCircuit(2) # prepara o estado |00> qc.draw('mpl') state = Statevector(qc) state qc = QuantumCircuit(2) qc.x(1) # estado |01> qc.draw('mpl') state = Statevector(qc); state from sympy.physics.quantum.dagger import Dagger P0 = ket0*Dagger(ket0); P1 = ket1*Dagger(ket1); P0,P1 CNOTab = tp(P0,eye(2)) + tp(P1,X); CNOTba = tp(eye(2),P0) + tp(X,P1); CNOTab,CNOTba H = Matrix([[1,1],[1,-1]])/sqrt(2); H Phip = CNOTab*tp(H,eye(2))*ket00; Phim = CNOTab*tp(H,eye(2))*ket10; Phip,Phim from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.draw('mpl') from qiskit.quantum_info import Statevector state = Statevector(qc); state # |Phi+> from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.x([0,1]) qc.h(0) qc.cx(0,1) qc.draw('mpl') from qiskit.quantum_info import Statevector state = Statevector(qc); state # |Psi-> from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0); qc.cx(0,1) # prepara |Phi+> qc.barrier() qc.cx(0,1) qc.h(0) qc.draw('mpl') from qiskit.quantum_info import Statevector state = Statevector(qc); state # estado |00> from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.x([0,1]); qc.h(0); qc.cx(0,1) # prepara |Psi-> qc.barrier() qc.cx(0,1) qc.h(0) qc.draw('mpl') from qiskit.quantum_info import Statevector state = Statevector(qc); state # estado |11> from sympy import Matrix X = Matrix([[0,1],[1,0]]); X init_printing(use_unicode=True) # pra visualização ficar melhor X.eigenvects() from qiskit import QuantumCircuit qc = QuantumCircuit(1,1) qc.h(0) from qiskit.quantum_info import Statevector state = Statevector(qc) state qc.measure(0,0) qc.draw('mpl') from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 # 8192 job = execute(qc, backend=simulator, shots=nshots) from qiskit.tools.visualization import plot_histogram plot_histogram(job.result().get_counts()) from qiskit import QuantumCircuit qc = QuantumCircuit(1,1) qc.h(0) qc.barrier() qc.h(0) qc.measure(0,0) qc.draw('mpl') from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 # 8192 job = execute(qc, backend=simulator, shots=nshots) from qiskit.tools.visualization import plot_histogram plot_histogram(job.result().get_counts()) from qiskit import QuantumCircuit qc = QuantumCircuit(1,1) qc.sdg(0) qc.h(0) qc.measure(0,0) qc.draw('mpl') from qiskit import execute, Aer simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 job = execute(qc, backend=simulator, shots=nshots) from qiskit.tools.visualization import plot_histogram plot_histogram(job.result().get_counts()) from sympy import symbols th, ph, lb = symbols('theta phi lambda'); th, ph, lb sn = Matrix([[cos(th),exp(-1j*ph)*sin(th)],[exp(1j*ph)*sin(th),-cos(th)]]); sn sn.eigenvects() import math math.cos(math.pi/8)**2 from qiskit import QuantumCircuit qc = QuantumCircuit(1,1) import math th = -math.pi/4 ph = 0 lb = math.pi - ph qc.u(th,ph,lb, 0) # porta parametrizada qc.measure(0,0) qc.draw('mpl') from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 job = execute(qc, backend = simulator, shots=nshots) from qiskit.tools.visualization import plot_histogram plot_histogram(job.result().get_counts()) # Cria o circuito quântico, sem usar medidas from qiskit import QuantumCircuit qc = QuantumCircuit(1) qc.h(0) qc.s(0) qc.draw(output='mpl') # estado |o+>=(|0>+i|1>)/sqrt(2) 2**13 from qiskit import Aer, execute; simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13 import qiskit; from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter qstc = state_tomography_circuits(qc, [0]); job = execute(qstc, backend=simulator, shots=nshots) qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq') qiskit.visualization.plot_state_city(rho) rho from sympy import Matrix, symbols, init_printing, eye init_printing(use_unicode=True) X = Matrix([[0,1],[1,0]]); Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]]) x,y,z = symbols('x y z') rho = (1/2)*(eye(2) + x*X + y*Y + z*Z); rho rho.eigenvals() from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector qc = QuantumCircuit(4) # não faz nada no 1º qubit qc.x(1) qc.h(2) qc.h(3); qc.s(3) state = Statevector(qc) plot_bloch_multivector(state)
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
jonasmaziero
from sympy import Matrix, sqrt, init_printing; init_printing(use_unicode=True) ket0 = Matrix([[1],[0]]); ket1 = Matrix([[0],[1]]); from sympy.physics.quantum import TensorProduct as tp ket00 = tp(ket0,ket0); ket01 = tp(ket0,ket1); ket10 = tp(ket1,ket0); ket11 = tp(ket1,ket1) Psim = (ket01-ket10)/sqrt(2); Psim.T X = Matrix([[0,1],[1,0]]); Z = Matrix([[1,0],[0,-1]]); (tp(Z,Z)*Psim).T, (tp(X,X)*Psim).T A1 = Z; A2 = X; B1 = (Z+X)/sqrt(2); B2 = (Z-X)/sqrt(2); O = tp(A1,B1)+tp(A1,B2)+tp(A2,B1)-tp(A2,B2) O, sqrt(2)*(tp(Z,Z)+tp(X,X)) from qiskit import QuantumCircuit def qc_Psim(): # função que cria o circuito quantico para preparar o estado de Bell |Psi-> qc = QuantumCircuit(2, name=r'$|\Psi_-\rangle$') qc.x([0,1]) qc.h(0) qc.cx(0,1) #qc.z(0) #qc.x(1) return qc qc_Psim_ = qc_Psim() qc_Psim_.draw('mpl') import qiskit from qiskit.quantum_info import Statevector qc_Psim_ = qc_Psim() state = Statevector(qc_Psim_) qiskit.visualization.plot_state_city(state) from sympy import Matrix Psim = Matrix([[0],[1],[-1],[0]])/sqrt(2) #Psim from sympy.physics.quantum.dagger import Dagger rho_Psim = Psim*Dagger(Psim) rho_Psim qc = QuantumCircuit(2,2) qc_Psim_ = qc_Psim() qc.append(qc_Psim_,[0,1]) qc.measure([0,1],[0,1]) qc.draw('mpl') from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 job = execute(qc, backend=simulator, shots=nshots) counts = job.result().get_counts() p00=0; p01=0; p10=0; p11=0 for j in (0,2): for k in (0,2): if '00' in counts: p00 = counts['00']/nshots if '01' in counts: p01 = counts['01']/nshots if '10' in counts: p10 = counts['10']/nshots if '11' in counts: p11 = counts['11']/nshots ZZ_avg = (p00+p11)-(p01+p10) ZZ_avg qc = QuantumCircuit(2,2) qc_Psim_ = qc_Psim() qc.append(qc_Psim_,[0,1]) qc.h([0,1]) qc.measure([0,1],[0,1]) qc.draw('mpl') from qiskit import Aer simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 job = execute(qc, backend=simulator, shots=nshots) counts = job.result().get_counts() p00=0; p01=0; p10=0; p11=0 for j in (0,2): for k in (0,2): if '00' in counts: p00 = counts['00']/nshots if '01' in counts: p01 = counts['01']/nshots if '10' in counts: p10 = counts['10']/nshots if '11' in counts: p11 = counts['11']/nshots XX_avg = (p00+p11)-(p01+p10) XX_avg O_avg = sqrt(2)*(ZZ_avg + XX_avg) O_avg, float(O_avg) import qiskit qiskit.IBMQ.save_account('5a0140fc106f9f8ae43104d5751baf65c726195f8b45b1f42e161f0182b5fe79ca6dbb1405159301e1e44d40d680223ea572d9b8737205bfa6f90485f1f88123', overwrite = True) qiskit.IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibm_nairobi') qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_,[0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend = device, shots = nshots); print(job.job_id()) device = provider.get_backend('ibm_nairobi'); job = device.retrieve_job('cmfbdw78vz2g008daj90') counts = job.result().get_counts() p00=0; p01=0; p10=0; p11=0 for j in (0,2): for k in (0,2): if '00' in counts: p00 = counts['00']/nshots if '01' in counts: p01 = counts['01']/nshots if '10' in counts: p10 = counts['10']/nshots if '11' in counts: p11 = counts['11']/nshots ZZ_avg_exp = (p00+p11)-(p01+p10); ZZ_avg_exp device = provider.get_backend('ibm_nairobi') qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_,[0,1]); qc.h([0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend = device, shots = nshots); jobid = job.job_id() print(jobid) device = provider.get_backend('ibm_nairobi'); job = device.retrieve_job('cmfbekafysfg008t2y4g') counts = job.result().get_counts() p00=0; p01=0; p10=0; p11=0 for j in (0,2): for k in (0,2): if '00' in counts: p00 = counts['00']/nshots if '01' in counts: p01 = counts['01']/nshots if '10' in counts: p10 = counts['10']/nshots if '11' in counts: p11 = counts['11']/nshots XX_avg_exp = (p00+p11)-(p01+p10); XX_avg_exp O_avg_exp = sqrt(2.)*(ZZ_avg_exp + XX_avg_exp) O_avg_exp import numpy as np import math th_max = math.pi/2; npt = 100; dth = th_max/npt; th = np.arange(0,th_max+dth,dth) Oteo = -math.sqrt(2)*(1+np.sin(th)) Odl = -2*np.ones(len(th)) from matplotlib import pyplot as plt plt.plot(th, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$') plt.plot(th, Odl, label = 'LHV limit') plt.xlabel(r'$\theta$') plt.legend(); plt.show() # circuito quântico para preparação do estado Psi def qc_Psi(th): qc = QuantumCircuit(2) qc.u(th,0,0, 0) qc.cx(0,1) qc.z(0) qc.x(1) return qc import math th = math.pi/4 qc_Psi_ = qc_Psi(th) qc_Psi_.draw('mpl') # função para calcular as médias tipo <A\otimes B>, com A,B=+1,-1, dadas as probabilidades def ABavg(result, nshots): avg = 0 if '00' in result: avg += result['00'] if '01' in result: avg -= result['01'] if '10' in result: avg -= result['10'] if '11' in result: avg += result['11'] return avg/nshots # = (N(00)-N(01)-N(10)+N(11))/nshots th_max = math.pi/2; npe = 5; dth = th_max/npe; th = np.arange(0,th_max+dth,dth) Osim = np.zeros(len(th)) from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 for j in range(0,len(th)): # mede ZZ qc = QuantumCircuit(2,2) qc_Psi_ = qc_Psi(th[j]); qc.append(qc_Psi_, [0,1]) qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots) result = job.result().get_counts() ZZavg = ABavg(result, nshots) # mede XX qc = QuantumCircuit(2,2) qc_Psi_ = qc_Psi(th[j]); qc.append(qc_Psi_, [0,1]) qc.h([0,1]) qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots) result = job.result().get_counts() XXavg = ABavg(result, nshots) # média de O Osim[j] = math.sqrt(2)*(ZZavg + XXavg) Osim import numpy as np; import math th_max = math.pi/2; dtht = th_max/npt; tht = np.arange(0,th_max+dtht,dtht) Oteo = -math.sqrt(2)*(1+np.sin(tht)); Odl = -2*np.ones(len(tht)) dth = th_max/npe; th = np.arange(0,th_max+dth,dth) from matplotlib import pyplot as plt plt.plot(tht, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$') plt.plot(tht, Odl, label = 'LHV limit') plt.plot(th, Osim, '*', label = r'$\langle O\rangle_{\Psi}^{sim}$') plt.xlabel(r'$\theta$') plt.legend(); plt.show() import qiskit qiskit.IBMQ.save_account('45b1db3a3c2ecae609e6c98184250919ccd31c9ea24100440abe0821fe6312c2b05a67239806c5b0020754eb3072f924547adb621e1e3931200aee13583a776f', overwrite = True) qiskit.IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') th_max = math.pi/2; dth = th_max/npe; th = np.arange(0,th_max+dth,dth) device = provider.get_backend('ibm_nairobi') nshots = 2**13 jobs_ids_ZZ = []; jobs_ids_XX = [] for j in range(0,len(th)): # mede ZZ qc = QuantumCircuit(2,2); qc_Psi_ = qc_Psi(th[j]); qc.append(qc_Psi_, [0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots) print('ZZ',job.job_id()); jobs_ids_ZZ.append(job.job_id()) # mede XX qc = QuantumCircuit(2,2); qc_Psi_ = qc_Psi(th[j]); qc.append(qc_Psi_, [0,1]); qc.h([0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots) print('XX',job.job_id()); jobs_ids_XX.append(job.job_id()) f = open("jobs_ids_ZZ.txt", "w"); f.write(str(jobs_ids_ZZ)); f.close() f = open("jobs_ids_XX.txt", "w"); f.write(str(jobs_ids_XX)); f.close() f = open("jobs_ids_ZZ.txt","r") list_ids_ZZ = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",") f.close() f = open("jobs_ids_XX.txt","r") list_ids_XX = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",") f.close() th_max = math.pi/2; dth = th_max/npe; th = np.arange(0,th_max+dth,dth) Oexp = np.zeros(len(th)) for j in range(0,len(th)): # média de ZZ job = device.retrieve_job(list_ids_ZZ[j]) result = job.result().get_counts() ZZavg = ABavg(result, nshots) # média de XX job = device.retrieve_job(list_ids_XX[j]) result = job.result().get_counts() XXavg = ABavg(result, nshots) # média de O Oexp[j] = math.sqrt(2)*(ZZavg + XXavg) Oexp import numpy as np; import math th_max = math.pi/2; dtht = th_max/npt; tht = np.arange(0,th_max+dtht,dtht) Oteo = -math.sqrt(2)*(1+np.sin(tht)); Odl = -2*np.ones(len(tht)) dth = th_max/npe; th = np.arange(0,th_max+dth,dth) from matplotlib import pyplot as plt plt.plot(tht, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$') plt.plot(tht, Odl, label = 'LHV limit') plt.plot(th, Osim, '*', label = r'$\langle O\rangle_{\Psi}^{sim}$') plt.plot(th, Oexp, '*', label = r'$\langle O\rangle_{\Psi}^{exp}$') plt.xlabel(r'$\theta$'); plt.legend(); plt.show() def f_Oavg(O,psi): from sympy.physics.quantum.dagger import Dagger return Dagger(psi)*O*psi from sympy import Matrix, symbols, cos, sin, sqrt, simplify from sympy.physics.quantum import TensorProduct as tp Psim = Matrix([[0],[1],[-1],[0]])/sqrt(2) X = Matrix([[0,1],[1,0]]) Z = Matrix([[1,0],[0,-1]]) th = symbols('theta') A1B1 = tp(Z,cos(th)*Z+sin(th)*X) A1B1avg = f_Oavg(A1B1,Psim) A1B2 = tp(Z,(Z-X)/sqrt(2)) A1B2avg = f_Oavg(A1B2,Psim) A2B1 = tp(X,cos(th)*Z+sin(th)*X) A2B1avg = f_Oavg(A2B1,Psim) A2B2 = tp(X,(Z-X)/sqrt(2)) A2B2avg = f_Oavg(A2B2,Psim) Oavg = A1B1avg + A1B2avg + A2B1avg - A2B2avg A1B1avg, A1B2avg, A2B1avg, A2B2avg, simplify(Oavg) import numpy as np; import math th_max = math.pi/4; npt = 100; dth = th_max/npt; tht = np.arange(-th_max,th_max+dth,dth) Oteo = -math.sqrt(2)*(1+np.sin(tht+math.pi/4)) Odl = -2*np.ones(len(tht)) from matplotlib import pyplot as plt plt.plot(tht, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$') plt.plot(tht, Odl, label = 'LHV limit') plt.xlabel(r'$\theta$') plt.legend(); plt.show() th_max = math.pi/4; npe = 4; dth = 2*th_max/npe; th = np.arange(-th_max,th_max+dth,dth); Osim = np.zeros(len(th)) from qiskit import *; simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13 for j in range(0,len(th)): # mede <A1B1> qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.u(th[j],0,math.pi, 1); qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots); result = job.result().get_counts(); A1B1avg = ABavg(result, nshots) # mede <A1B2> qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.u(-math.pi/4,0,math.pi, 1); qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots); result = job.result().get_counts(); A1B2avg = ABavg(result, nshots) # mede <A2B1> qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.h(0); qc.u(th[j],0,math.pi, 1); qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots); result = job.result().get_counts(); A2B1avg = ABavg(result, nshots) # mede <A2B2> qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.h(0); qc.u(-math.pi/4,0,math.pi, 1); qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots); result = job.result().get_counts(); A2B2avg = ABavg(result, nshots) # média de O Osim[j] = A1B1avg + A1B2avg + A2B1avg - A2B2avg Osim import numpy as np; import math th_max = math.pi/4; dtht = 2*th_max/npt; tht = np.arange(-th_max,th_max+dtht,dtht) Oteo = -math.sqrt(2)*(1+np.sin(tht+math.pi/4)); Odl = -2*np.ones(len(tht)) dth = 2*th_max/npe; th = np.arange(-th_max,th_max+dth,dth) from matplotlib import pyplot as plt plt.plot(tht, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$') plt.plot(tht, Odl, label = 'LHV limit') plt.plot(th, Osim, '*', label = r'$\langle O\rangle_{\Psi}^{sim}$') plt.xlabel(r'$\theta$') plt.legend(); plt.show() import qiskit qiskit.IBMQ.save_account('45b1db3a3c2ecae609e6c98184250919ccd31c9ea24100440abe0821fe6312c2b05a67239806c5b0020754eb3072f924547adb621e1e3931200aee13583a776f', overwrite = True) qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') th_max = math.pi/4; npe = 4; dth = 2*th_max/npe; th = np.arange(-th_max,th_max+dth,dth) from qiskit import *; device = provider.get_backend('ibm_nairobi'); nshots = 2**13 jobs_ids_A1B1 = []; jobs_ids_A1B2 = []; jobs_ids_A2B1 = []; jobs_ids_A2B2 = [] for j in range(0,len(th)): # mede <A1B1> qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.u(th[j],0,math.pi, 1) qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots); print('A1B1:',job.job_id()); jobs_ids_A1B1.append(job.job_id()) # mede <A1B2> qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.u(-math.pi/4,0,math.pi, 1) qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots); print('A1B2:',job.job_id()); jobs_ids_A1B2.append(job.job_id()) # mede <A2B1> qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.h(0); qc.u(th[j],0,math.pi, 1) qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots); print('A2B1:',job.job_id()); jobs_ids_A2B1.append(job.job_id()) # mede <A2B2> qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.h(0); qc.u(-math.pi/4,0,math.pi, 1) qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots); print('A2B2:',job.job_id()); jobs_ids_A2B2.append(job.job_id()) f = open("jobs_ids_A1B1.txt", "w"); f.write(str(jobs_ids_A1B1)); f.close() f = open("jobs_ids_A1B2.txt", "w"); f.write(str(jobs_ids_A1B2)); f.close() f = open("jobs_ids_A2B1.txt", "w"); f.write(str(jobs_ids_A2B1)); f.close() f = open("jobs_ids_A2B2.txt", "w"); f.write(str(jobs_ids_A2B2)); f.close() device = provider.get_backend('ibm_nairobi') f = open("jobs_ids_A1B1.txt","r") list_ids_A1B1 = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(","); f.close() f = open("jobs_ids_A1B2.txt","r") list_ids_A1B2 = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(","); f.close() f = open("jobs_ids_A2B1.txt","r") list_ids_A2B1 = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(","); f.close() f = open("jobs_ids_A2B2.txt","r") list_ids_A2B2 = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(","); f.close() th_max = math.pi/4; dth = 2*th_max/npe; th = np.arange(-th_max,th_max+dth,dth); Oexp = np.zeros(len(th)) for j in range(0,len(th)): # média de A1B1 job = device.retrieve_job(list_ids_A1B1[j]); result = job.result().get_counts(); A1B1avg = ABavg(result, nshots) # média de A1B2 job = device.retrieve_job(list_ids_A1B2[j]); result = job.result().get_counts(); A1B2avg = ABavg(result, nshots) # média de A2B1 job = device.retrieve_job(list_ids_A2B1[j]); result = job.result().get_counts(); A2B1avg = ABavg(result, nshots) # média de A2B2 job = device.retrieve_job(list_ids_A2B2[j]); result = job.result().get_counts(); A2B2avg = ABavg(result, nshots) # média de O Oexp[j] = A1B1avg + A1B2avg + A2B1avg - A2B2avg Oexp import numpy as np; import math th_max = math.pi/4; dtht = 2*th_max/npt; tht = np.arange(-th_max,th_max+dtht,dtht) Oteo = -math.sqrt(2)*(1+np.sin(tht+math.pi/4)); Odl = -2*np.ones(len(tht)) dth = 2*th_max/npe; th = np.arange(-th_max,th_max+dth,dth) from matplotlib import pyplot as plt plt.plot(tht, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$') plt.plot(tht, Odl, label = 'LHV limit') plt.plot(th, Osim, '*', label = r'$\langle O\rangle_{\Psi}^{sim}$') plt.plot(th, Oexp, '*', label = r'$\langle O\rangle_{\Psi}^{exp}$') plt.xlabel(r'$\theta$'); plt.legend(); plt.show()
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
jonasmaziero
from qiskit import QuantumCircuit; qc = QuantumCircuit(2,2) qc.barrier() qc.cx(0,1); qc.h(0) qc.barrier() qc.measure([0,1],[0,1]) qc.draw('mpl') from qiskit import QuantumCircuit, execute, Aer; from qiskit.tools.visualization import plot_histogram simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13 qc = QuantumCircuit(2,2) qc.h(0); qc.cx(0,1) # prepara |Phi+> qc.barrier() qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB qc.draw('mpl') job = execute(qc, backend=simulator, shots=nshots) plot_histogram(job.result().get_counts()) qc = QuantumCircuit(2,2) qc.x(1); qc.h(0); qc.cx(0,1) # prepara |Psi+> qc.barrier() qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB qc.draw('mpl') job = execute(qc, backend=simulator, shots=nshots) plot_histogram(job.result().get_counts()) qc = QuantumCircuit(2,2) qc.x(0); qc.h(0); qc.cx(0,1) # prepara |Phi-> qc.barrier() qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB qc.draw('mpl') job = execute(qc, backend=simulator, shots=nshots) plot_histogram(job.result().get_counts()) qc = QuantumCircuit(2,2) qc.x([0,1]); qc.h(0); qc.cx(0,1) # prepara |Psi-> qc.barrier() qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB qc.draw('mpl') job = execute(qc, backend=simulator, shots=nshots) plot_histogram(job.result().get_counts()) import qiskit qiskit.IBMQ.save_account('72f5d1e3769658b4908c384492eb3a9bd6d6ac4ab1fdf613d7fbe72884114d62728d6fd60a8bf8d0b6698f2f5463a605742658fee1ce3318181105c6acb8120e', overwrite = True) qiskit.IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibm_nairobi') nshots = 2**13 qc = QuantumCircuit(2,2) qc.h(0); qc.cx(0,1) # prepara |Phi+> qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB job = execute(qc, backend=device, shots=nshots) print(job.job_id()) job = device.retrieve_job('cmjn5w752bbg00825esg') from qiskit.tools.visualization import plot_histogram; plot_histogram(job.result().get_counts()) qc = QuantumCircuit(2,2) qc.x(1); qc.h(0); qc.cx(0,1) # prepara |Psi+> qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB job = execute(qc, backend=device, shots=nshots); print(job.job_id()) job = device.retrieve_job('cmjn66rffjhg0084we5g') plot_histogram(job.result().get_counts()) qc = QuantumCircuit(2,2) qc.x(0); qc.h(0); qc.cx(0,1) # prepara |Phi-> qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB job = execute(qc, backend=device, shots=nshots); print(job.job_id()) job = device.retrieve_job('cmjn6wk6n5g0008xpgg0') plot_histogram(job.result().get_counts()) provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') qc = QuantumCircuit(2,2) qc.x([0,1]); qc.h(0); qc.cx(0,1) # prepara |Psi-> qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB job = execute(qc, backend=device, shots=nshots); print(job.job_id()) job = device.retrieve_job('cmjnb9nz44x0008bwa3g'); plot_histogram(job.result().get_counts()) def qc_psi(th,ph,lb): # prepara o estado a ser teletransportado from qiskit import QuantumCircuit qc = QuantumCircuit(1, name=r'$|\psi\rangle$'); qc.x(0); qc.u(th,ph,lb, 0) return qc qc_psi_ = qc_psi(0.1,0.2,0.3); qc_psi_.draw('mpl') from qiskit.quantum_info import random_statevector for j in range(0,6): psi = random_statevector(2) print(psi) def angulos(psi): # psi = [c0,c1] c0_abs = math.sqrt(psi[0].real**2 + psi[0].imag**2); c1_abs = math.sqrt(psi[1].real**2 + psi[1].imag**2) ph0 = math.acos(psi[0].real/c0_abs); ph1 = math.acos(psi[1].real/c1_abs) th = 2*math.acos(c1_abs) lb = ph0 - math.pi; ph = ph1 - lb return th, ph, lb # existem erros de sinal! import math; import numpy as np for j in range(0,3): psi = random_statevector(2); print('rand = ',psi); th, ph, lb = angulos(psi) psin = np.array([(math.cos(math.pi+lb)+1j*math.sin(math.pi+lb))*math.sin(th/2), (math.cos(ph+lb)+1j*math.sin(ph+lb))*math.cos(th/2)]) print('new = ',psin) # existem erros de sinal! def acosm(x): # solução do chagpt não funciona angle = math.acos(x) if x >= 0: return angle else: return 2*math.pi - angle import math; import numpy as np thmax = 2*math.pi; npt = 10; dth = thmax/npt; th = np.arange(0,thmax+dth,dth) for j in range(0,len(th)): cs = math.cos(th[j]); acs = math.acos(cs); nacs = acosm(cs) print('th=',th[j],', acs=',acs,', nacs=',nacs) # não funcionam for j in range(0,len(th)): tg = math.tan(th[j]); atg = math.atan(tg); sn = math.sin(th[j]); asn = math.asin(sn) print('th=', th[j], ', atg=', atg,', asn=', asn) # também não funcionam # As funções anteriores não funcionam pois o mapa é 2 pra 1 # Essa função retorna o ângulo cert0, fornecidos os valores (seno,cosseno) def arc_fun(cs, sn): if sn >= 0: return math.acos(cs) if sn < 0: return 2*math.pi - math.acos(cs) for j in range(0,len(th)): cs = math.cos(th[j]); sn = math.sin(th[j]) print('th=', th[j], ', nth=', arc_fun(cs, sn)) def angulosn(psi): # psi = [c0,c1] c0_abs = math.sqrt(psi[0].real**2 + psi[0].imag**2); c1_abs = math.sqrt(psi[1].real**2 + psi[1].imag**2) ph0 = arc_fun(psi[0].real/c0_abs, psi[0].imag/c0_abs); ph1 = arc_fun(psi[1].real/c1_abs, psi[1].imag/c1_abs) th = 2*arc_fun(c1_abs,c0_abs) lb = ph0 - math.pi; ph = ph1 - lb return th, ph, lb import math; import numpy as np for j in range(0,5): psi = random_statevector(2); print('rand = ',psi); th, ph, lb = angulosn(psi) psin = np.array([(math.cos(math.pi+lb)+1j*math.sin(math.pi+lb))*math.sin(th/2), (math.cos(ph+lb)+1j*math.sin(ph+lb))*math.cos(th/2)]) print('new = ',psin) # Agora está certo ... from qiskit import * def qc_teleport(th,ph,lb): qc = QuantumCircuit(3,2, name='tel') qc_psi_ = qc_psi(th,ph,lb); qc.append(qc_psi_, [0]); qc.barrier() qc.h(2); qc.cx(2,1); qc.barrier() qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]); qc.barrier() qc.x(2).c_if(1, 1); qc.z(2).c_if(0, 1) # oprações condicionadas em info clássica return qc qc_teleport_ = qc_teleport(0.1,0.2,0.3); qc_teleport_.draw('mpl') import qiskit; import math; import numpy as np; from qiskit import Aer, QuantumCircuit, execute from qiskit.quantum_info import state_fidelity from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter simulator = Aer.get_backend('qasm_simulator') nshots = 2**13; qc = QuantumCircuit(3) psi = np.array([1/math.sqrt(2),1/math.sqrt(2)]); th,ph,lb=angulosn(psi) # estado a ser teletransportado qc_teleport_ = qc_teleport(th,ph,lb); qc.append(qc_teleport_, [0,1,2]) qstc = state_tomography_circuits(qc_teleport_, [2]) job = execute(qstc, backend = simulator, shots = nshots) qstf = StateTomographyFitter(job.result(), qstc) rho_sim = qstf.fit(method='lstsq') F = state_fidelity(rho_sim, psi); from sympy import Matrix rho_teo = Matrix([[1/2,1/2],[1/2,1/2]]); print('rho_teo = ',rho_teo); print('rho_sim =',rho_sim); print('F = ', F) import qiskit qiskit.IBMQ.save_account('7ec48a29167ab443c525564bd84b033895cf87b6c6da8d263be59ad00a2d9e70718cf1398362403ace62320d0044793f08dbaa2629bfde7f6ec339f90fe74e7b', overwrite = True) qiskit.IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibm_nairobi') qc = QuantumCircuit(3) psi = np.array([1/math.sqrt(2),1/math.sqrt(2)]) th,ph,lb=angulosn(psi) qc_teleport_ = qc_teleport(th,ph,lb) qc.append(qc_teleport_, [0,1,2]) qstc = state_tomography_circuits(qc_teleport_, [2]) job = execute(qstc, backend = device, shots = nshots) jobid = job.job_id() print(jobid) def qc_teleport_coe(th,ph,lb): from qiskit import QuantumCircuit qc = QuantumCircuit(3, name='tel') qc_psi_ = qc_psi(th,ph,lb); qc.append(qc_psi_, [0]); qc.barrier() qc.h(2); qc.cx(2,1); qc.barrier(); qc.cx(0,1); qc.h(0); qc.barrier() qc.cx(1,2); qc.cz(0,2) # oprações quânticas controladas return qc qc_teleport_coe_ = qc_teleport_coe(0.1,0.2,0.3); qc_teleport_coe_.draw('mpl') import qiskit; import math; import numpy as np from qiskit import Aer, QuantumCircuit, execute from qiskit.quantum_info import state_fidelity from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13; qc = QuantumCircuit(3) psi = np.array([1/math.sqrt(2),(1/math.sqrt(2))*1j]); th,ph,lb=angulosn(psi) qc_teleport_coe_ = qc_teleport_coe(th,ph,lb); qc.append(qc_teleport_coe_, [0,1,2]) qstc = state_tomography_circuits(qc_teleport_coe_, [2]) job = qiskit.execute(qstc, backend = simulator, shots = nshots) qstf = StateTomographyFitter(job.result(), qstc) rho_sim = qstf.fit(method='lstsq') F = state_fidelity(rho_sim, psi) from sympy import Matrix,sqrt; rho = Matrix([[1/2,-1j/2],[1j/2,1/2]]); print('rho_teo =',rho) print('rho_sim =',rho_sim); print('F = ', F) import qiskit qiskit.IBMQ.save_account('585d2242bad08223e0d894363adf8e4f76b1d426a84e85b2fbd51678adcb8e54e39cf0f33ff6c84c41e60a534a61ad4775091a01e338f0f9eff2265aa59a6a19', overwrite = True); qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') qc = QuantumCircuit(3) psi = np.array([1/math.sqrt(2),(1/math.sqrt(2))*1j]) th,ph,lb=angulosn(psi) qc_teleport_coe_ = qc_teleport_coe(th,ph,lb) qc.append(qc_teleport_coe_, [0,1,2]) qstc = state_tomography_circuits(qc_teleport_coe_, [2]) job = execute(qstc, backend = device, shots = nshots) jobid = job.job_id() print(jobid) provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibm_nairobi') job = device.retrieve_job('cmke9bn8tsq00080987g') qstf = StateTomographyFitter(job.result(), qstc) rho_exp = qstf.fit(method='lstsq') psi = np.array([1/math.sqrt(2),(1/math.sqrt(2))*1j]) from sympy import Matrix, sqrt rho = Matrix([[0.5,-0.5*1j],[0.5*1j,0.5]]) print('rho_teo =',rho) F = state_fidelity(psi, rho_exp) print('rho_exp = ',rho_exp,', F = ', F) import qiskit; import math; import numpy as np from qiskit import Aer, QuantumCircuit, execute from qiskit.quantum_info import state_fidelity from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13 for j in range(0,13): qc = QuantumCircuit(3) psi = random_statevector(2); th,ph,lb = angulosn(psi)#; print('psi=',psi) qc_teleport_coe_ = qc_teleport_coe(th,ph,lb); qc.append(qc_teleport_coe_, [0,1,2]) qstc = state_tomography_circuits(qc_teleport_coe_, [2]) job = qiskit.execute(qstc, backend=simulator, shots=nshots) qstf = StateTomographyFitter(job.result(), qstc); rho_sim = qstf.fit(method='lstsq') F = state_fidelity(rho_sim, psi); print('F=', F)
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
jonasmaziero
def qc_alice_encoding(cb): from qiskit import QuantumCircuit qc = QuantumCircuit(1, name='AE') if cb == '00': qc.id(0) elif cb == '01': qc.x(0) elif cb == '10': qc.z(0) elif cb == '11': qc.x(0); qc.z(0) return qc cb = '11' qcae = qc_alice_encoding(cb) qcae.draw('mpl') from qiskit import QuantumCircuit # só pra mostrar o circuito quântico qc = QuantumCircuit(2,2) qc.h(0) qc.cx(0,1) qc.barrier() qcae = qc_alice_encoding(cb) qc.append(qcae, [0]) qc.barrier() qc.cx(0,1) qc.h(0) qc.measure([0,1],[0,1]) qc.draw('mpl') def qc_dense_coding(cb): from qiskit import QuantumCircuit qc = QuantumCircuit(2, name='DC') qc.h(0); qc.cx(0,1) # compartilha o par emaranhado qcae = qc_alice_encoding(cb); qc.append(qcae, [0]) # codificação da Alice qc.cx(0,1); qc.h(0)#; qc.measure([0,1],[0,1]) # decodificação, medida na BB, do Bob # OBS. Não consegui incluir um subcircuito que contenha medidas return qc from qiskit import QuantumCircuit qc = QuantumCircuit(2,2) qcdc = qc_dense_coding('00') qc.append(qcdc, [0,1]) qc.draw('mpl') from qiskit import Aer, execute, QuantumCircuit; simulator = Aer.get_backend('qasm_simulator') nshots = 2**13; from qiskit import QuantumCircuit qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('00'); qc.append(qcdc, [0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots); counts = job.result().get_counts() from qiskit.tools.visualization import plot_histogram; plot_histogram(counts) from qiskit import Aer, execute, QuantumCircuit simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 from qiskit import QuantumCircuit qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('01'); qc.append(qcdc, [0,1]) qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots); counts = job.result().get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(counts) from qiskit import Aer, execute, QuantumCircuit simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 from qiskit import QuantumCircuit qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('10'); qc.append(qcdc, [0,1]) qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots); counts = job.result().get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(counts) from qiskit import Aer, execute, QuantumCircuit simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 from qiskit import QuantumCircuit qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('11'); qc.append(qcdc, [0,1]) qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots); counts = job.result().get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(counts) import qiskit qiskit.IBMQ.save_account('72f5d1e3769658b4908c384492eb3a9bd6d6ac4ab1fdf613d7fbe72884114d62728d6fd60a8bf8d0b6698f2f5463a605742658fee1ce3318181105c6acb8120e', overwrite = True) qiskit.IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') from qiskit import QuantumCircuit, execute device = provider.get_backend('ibm_nairobi') nshots = 2**13 qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('00'); qc.append(qcdc, [0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots); jobid = job.job_id(); print(jobid) job = device.retrieve_job('cmj6f1m0t6t00085y6r0') from qiskit.tools.visualization import plot_histogram; plot_histogram(job.result().get_counts()) from qiskit import QuantumCircuit, execute device = provider.get_backend('ibm_nairobi') nshots = 2**13 qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('01'); qc.append(qcdc, [0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots); jobid = job.job_id(); print(jobid) job = device.retrieve_job('cmj6f7c0t6t00085y6rg') plot_histogram(job.result().get_counts()) from qiskit import QuantumCircuit, execute device = provider.get_backend('ibm_nairobi') nshots = 2**13 qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('10'); qc.append(qcdc, [0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots); jobid = job.job_id(); print(jobid) job = device.retrieve_job('cmj6f9nstv5g008dwdb0') plot_histogram(job.result().get_counts()) #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') from qiskit import QuantumCircuit, execute; device = provider.get_backend('ibm_nairobi'); nshots = 2**13 qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('11'); qc.append(qcdc, [0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots); jobid = job.job_id(); print(jobid) job = device.retrieve_job('cmj6g3g0t6t00085y6sg') plot_histogram(job.result().get_counts()) import qiskit qiskit.IBMQ.save_account('e20d3045c7c23a3be753606794714e9b47d4331ec46a41b2281e2d601bae27b2b3c1baa0b5cb54f3282a8b5248e552b14c9c556699010660fb94b11d00ff1073', overwrite = True) qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') nshots = 2**13 from qiskit import QuantumRegister, execute from qiskit.ignis.mitigation.measurement import complete_meas_cal qr_ = QuantumRegister(2) qubit_list_ = [0, 1] # qubits para os quais aplicaremos calibracao de medidas meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list_, qr = qr_) meas_calibs # circuitos que serão executados para mitigação dos erros state_labels # estados que serão preparados/medidos/corrigidos job = execute(meas_calibs, backend=device, shots=nshots) print(job.job_id()) from qiskit.ignis.mitigation.measurement import CompleteMeasFitter job = device.retrieve_job('cmm4vmyrcq000080ceqg') cal_results = job.result() # função que usaremos para corrigir resultados experimentais meas_fitter = CompleteMeasFitter(cal_results, state_labels) # OBS. Uma vez feito isso para um chip e para uns certos qubits, depois é só usar job = device.retrieve_job('cmj6f1m0t6t00085y6r0') # dados do experimento da codificação densa para '00' unmitigated_counts = job.result().get_counts() mitigated_results = meas_fitter.filter.apply(job.result()) # corrige os resultados usando mitigação mitigated_counts = mitigated_results.get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram([unmitigated_counts, mitigated_counts], legend=['sem mit', 'com mit']) def prob_erro(counts, target, nshots): # Calcula a probabilidade de erro if target in counts: pacerto = counts[target]/nshots perro = 1 - pacerto return perro print('Probabilidade de erro SEM mitigação: ',prob_erro(unmitigated_counts, '00', nshots)) print('Probabilidade de erro COM mitigação: ',prob_erro(mitigated_counts, '00',nshots)) job = device.retrieve_job('cmj6f7c0t6t00085y6rg') # dados do experimento da codificação densa para '01' unmitigated_counts = job.result().get_counts() mitigated_results = meas_fitter.filter.apply(job.result()) # corrige os resultados usando mitigação mitigated_counts = mitigated_results.get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram([unmitigated_counts, mitigated_counts], legend=['sem mit', 'com mit']) print('Probabilidade de erro SEM mitigação: ',prob_erro(unmitigated_counts, '10', nshots)) print('Probabilidade de erro COM mitigação: ',prob_erro(mitigated_counts, '10',nshots)) job = device.retrieve_job('cmj6f9nstv5g008dwdb0'); unmitigated_counts = job.result().get_counts() mitigated_results = meas_fitter.filter.apply(job.result()) # corrige os resultados usando mitigação mitigated_counts = mitigated_results.get_counts(); from qiskit.tools.visualization import plot_histogram plot_histogram([unmitigated_counts, mitigated_counts], legend=['sem mit', 'com mit']) print('Probabilidade de erro SEM mitigação: ',prob_erro(unmitigated_counts, '01', nshots)) print('Probabilidade de erro COM mitigação: ',prob_erro(mitigated_counts, '01',nshots)) job = device.retrieve_job('cmj6g3g0t6t00085y6sg') # dados do experimento da codificação densa para '11' unmitigated_counts = job.result().get_counts(); mitigated_results = meas_fitter.filter.apply(job.result()) mitigated_counts = mitigated_results.get_counts(); from qiskit.tools.visualization import plot_histogram plot_histogram([unmitigated_counts, mitigated_counts], legend=['sem mit', 'com mit']) print('Probabilidade de erro SEM mitigação: ',prob_erro(unmitigated_counts, '11', nshots)) print('Probabilidade de erro COM mitigação: ',prob_erro(mitigated_counts, '11',nshots)) def qc_Eswap(): from qiskit import QuantumCircuit qc = QuantumCircuit(4, name='Eswap') qc.h([0,3]); qc.cx(0,1); qc.cx(3,2) # cria os pares emaranhados qc.barrier() qc.cx(1,2); qc.h(1) # muda da base computacional para a base de Bell qc.barrier() qc.cx(2,3); qc.cz(1,3) # envia a informação 'clássica' return qc qces = qc_Eswap(); qces.draw('mpl') from qiskit import Aer, QuantumCircuit; import qiskit from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.visualization import plot_state_city simulator = Aer.get_backend('qasm_simulator'); qc = QuantumCircuit(4); qces = qc_Eswap(); qc.append(qces, [0,1,2,3]) qstc = state_tomography_circuits(qc, [0,3]); job = execute(qstc, backend=simulator, shots=nshots) qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq'); plot_state_city(rho) from qiskit.quantum_info import state_fidelity F = state_fidelity(rho,Phip); print('F = ',F) import qiskit qiskit.IBMQ.save_account('72f5d1e3769658b4908c384492eb3a9bd6d6ac4ab1fdf613d7fbe72884114d62728d6fd60a8bf8d0b6698f2f5463a605742658fee1ce3318181105c6acb8120e', overwrite = True) qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') nshots = 2**13 from qiskit import QuantumCircuit, execute qc = QuantumCircuit(4); qces = qc_Eswap(); qc.append(qces, [0,1,2,3]) qstc = state_tomography_circuits(qc, [0,3]) job = execute(qstc, backend=device, shots=nshots) jobid = job.job_id(); print(jobid) job = device.retrieve_job('cmjp9zf5mym0008dvmzg') qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq') from qiskit.visualization import plot_state_city; plot_state_city(rho) rho import math; import numpy as np Phip = np.array([1/math.sqrt(2),0,0,1/math.sqrt(2)]); Phip from qiskit.quantum_info import state_fidelity F = state_fidelity(rho,Phip); print('F = ',F) import qiskit qiskit.IBMQ.save_account('dabd4674f7b3794f740813fec0c5478bfefdebb7d1dca9b7acd41e3f90ed2c8a8b80af26fb3236289fbfc70d0ea334829a836453ac46f96fee68abcb22495ef4', overwrite = True) qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') nshots = 2**13 from qiskit import QuantumRegister, execute from qiskit.ignis.mitigation.measurement import complete_meas_cal qr = QuantumRegister(4) qubit_list = [0, 3] meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr) job = execute(meas_calibs, backend=device, shots=nshots) print(job.job_id()) from qiskit.ignis.mitigation.measurement import CompleteMeasFitter job = device.retrieve_job('cmr2snercp70008sfsw0') cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels) from qiskit import QuantumCircuit, execute qc = QuantumCircuit(4); qces = qc_Eswap(); qc.append(qces, [0,1,2,3]) from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter qstc = state_tomography_circuits(qc, [0,3]) job = device.retrieve_job('cmjp9zf5mym0008dvmzg') mitigated_results = meas_fitter.filter.apply(job.result()) qstf = StateTomographyFitter(mitigated_results, qstc) rho = qstf.fit(method='lstsq') from qiskit.visualization import plot_state_city; plot_state_city(rho) import numpy as np import math from qiskit.quantum_info import state_fidelity Phip = np.array([1/math.sqrt(2),0,0,1/math.sqrt(2)]) F = state_fidelity(rho,Phip) print('F = ',F)
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
jonasmaziero
import math; import numpy as np; phmax = 4*math.pi; npt = 100; dth = phmax/npt; ph = np.arange(0,phmax+dth,dth) from matplotlib import pyplot as plt; PrD0 = 0.5*(1+np.cos(ph)); plt.plot(ph,PrD0, label=r'$Pr(D_0)$') PrD0 = 0.5*(1-np.cos(ph)); plt.plot(ph,PrD0, label=r'$Pr(D_1)$'); plt.legend(); plt.xlabel(r'$\phi$'); plt.show() from sympy import Matrix, sqrt S = Matrix([[1,0],[0,1j]]); H = (1/sqrt(2))*Matrix([[1,1],[1,-1]]) S*H*S Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]]); Y*Z from qiskit import QuantumCircuit def qc_df(): # divisor de feixes 50:50 qc = QuantumCircuit(1, name='DF') qc.s(0) qc.h(0) qc.s(0) return qc qcdf = qc_df(); qcdf.draw('mpl') def qc_espelhos(): qc = QuantumCircuit(1, name='E') qc.z(0) qc.y(0) return qc qce = qc_espelhos(); qce.draw('mpl') def qc_imz(ph): # retorna o circuito quântico para o IMZ (sem as medidas) qc = QuantumCircuit(1, name='IMZ') qcdf = qc_df(); qc.append(qcdf, [0]) qce = qc_espelhos(); qc.append(qce, [0]) qc.p(ph, [0]) qcdf = qc_df(); qc.append(qcdf, [0]) return qc qcimz = qc_imz(0); qcimz.draw('mpl') # Simulação clássica from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 import numpy as np; import math phmax = 2*math.pi npe = 6 dth = phmax/npe ph = np.arange(0,phmax+dth,dth) PD0sim = np.zeros(len(ph)) for j in range(0,len(ph)): qc = QuantumCircuit(1,1) qcimz = qc_imz(ph[j]) qc.append(qcimz,[0]) qc.measure(0,0) job = execute(qc, backend=simulator, shots=nshots) counts = job.result().get_counts() if '0' in counts: PD0sim[j] = counts['0']/nshots print(PD0sim) npt = 100 dtht = phmax/npt pht = np.arange(0,phmax+dtht,dtht) PD0teo = 0.5*(1+np.cos(pht)) from matplotlib import pyplot as plt plt.plot(pht,PD0teo, label=r'$Pr(D_0)_{teo}$') plt.plot(ph,PD0sim, 'o', label=r'$Pr(D_0)_{sim}$') plt.legend(); plt.xlabel(r'$\phi$') plt.show() import qiskit qiskit.IBMQ.save_account('a221013b3d88dd070a495178c3f732ac683a494e5af4e641383f16d361e9fa7fa22af7f09cad3f88988a3e6e5621c7fe951d8ca6ff0c0371422b211ec0ae9709', overwrite = True) qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') nshots = 2**13 import numpy as np; import math phmax = 2*math.pi npe = 6 dth = phmax/npe ph = np.arange(0,phmax+dth,dth) job_ids = [] for j in range(0,len(ph)): qc = QuantumCircuit(1,1) qcimz = qc_imz(ph[j]) qc.append(qcimz,[0]) qc.measure(0,0) job = execute(qc, backend=device, shots=nshots) jobid = job.job_id() job_ids.append(jobid) print(jobid) f = open("jobs_ids_IMZ.txt", "w") f.write(str(job_ids)) f.close() device = provider.get_backend('ibm_nairobi') f = open("jobs_ids_IMZ.txt","r") list_ids_IMZ = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",") f.close() PD0exp = np.zeros(len(ph)) for j in range(0,len(ph)): job = device.retrieve_job(list_ids_IMZ[j]) counts = job.result().get_counts() if '0' in counts: PD0exp[j] = counts['0']/nshots print(PD0exp) npt = 100; dtht = phmax/npt; pht = np.arange(0,phmax+dtht,dtht) PD0teo = 0.5*(1+np.cos(pht)) from matplotlib import pyplot as plt plt.plot(pht,PD0teo, label=r'$Pr(D_0)_{teo}$') plt.plot(ph,PD0sim, 'o', label=r'$Pr(D_0)_{sim}$') plt.plot(ph,PD0exp, '*', label=r'$Pr(D_0)_{exp}$') plt.legend() plt.xlabel(r'$\phi$') plt.show() Vsim = (np.max(PD0sim)-np.min(PD0sim))/(np.max(PD0sim)+np.min(PD0sim)); print('Vsim = ',Vsim) Vexp = (np.max(PD0exp)-np.min(PD0exp))/(np.max(PD0exp)+np.min(PD0exp)); print('Vexp = ',Vexp) from sympy import Matrix, eye; P0 = Matrix([[1,0],[0,0]]); P1 = Matrix([[0,0],[0,1]]); X = Matrix([[0,1],[1,0]]) from sympy.physics.quantum import TensorProduct as tp; tp(eye(2),P0) + tp(X,P1) def qc_bbo(): from qiskit import QuantumCircuit qc = QuantumCircuit(2, name='BBO') qc.x(1) qc.h(0) qc.cx(0,1) return qc qcbbo = qc_bbo(); qcbbo.draw('mpl') def qc_dfp(): from qiskit import QuantumCircuit qc = QuantumCircuit(2, name='DFP') qc.cz(0,1) qc.cy(0,1) return qc qcdfp = qc_dfp() qcdfp.draw('mpl') def qc_pmo(): from qiskit import QuantumCircuit qc = QuantumCircuit(2, name='PMO') qc.cx(1,0) return qc qcpmo = qc_pmo() qcpmo.draw('mpl') def qc_imz_ic(ph): # não consideramos o caminho do fóton A from qiskit import QuantumCircuit qc = QuantumCircuit(3, name='IMZIC') qcbbo = qc_bbo(); qc.append(qcbbo, [0,1]) qcdfp = qc_dfp(); qc.append(qcdfp, [1,2]) qcpmo = qc_pmo(); qc.append(qcpmo, [1,2]) qce = qc_espelhos(); qc.append(qce, [2]) qc.p(ph, [2]) qcdf = qc_df(); qc.append(qcdf, [2]) return qc qcimzic = qc_imz_ic(0); qcimzic.draw('mpl') qcimzic.decompose().draw('mpl') qcimzic.decompose().decompose().decompose().draw('mpl') # Simulação clássica from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 import numpy as np; import math phmax = 2*math.pi npe = 5 dth = phmax/npe ph = np.arange(0,phmax+dth,dth) PD0sim = np.zeros(len(ph)) for j in range(0,len(ph)): qc = QuantumCircuit(3,2) qcimzic = qc_imz_ic(ph[j]) qc.append(qcimzic,[0,1,2]) qc.measure([0,2],[0,1]) job = execute(qc, backend=simulator, shots=nshots) counts = job.result().get_counts() if '00' in counts: PD0sim[j] = counts['00']/nshots if '10' in counts: PD0sim[j] += counts['10']/nshots print(PD0sim) qc.draw('mpl') import numpy as np; import math phmax = 2*math.pi; npt = 100; dpht = phmax/npt pht = np.arange(0,phmax+dtht,dtht) PD0teo = 0.5*np.ones(len(pht)) from matplotlib import pyplot as plt plt.plot(pht,PD0teo, label=r'$Pr(D_0)_{teo}$') plt.plot(ph,PD0sim, 'o', label=r'$Pr(D_0)_{sim}$') plt.ylim(0,1); plt.legend() plt.xlabel(r'$\phi$') plt.show() import qiskit qiskit.IBMQ.save_account('e20d3045c7c23a3be753606794714e9b47d4331ec46a41b2281e2d601bae27b2b3c1baa0b5cb54f3282a8b5248e552b14c9c556699010660fb94b11d00ff1073', overwrite = True) qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') nshots = 2**13 import numpy as np; import math phmax=2*math.pi npe=5 dth=phmax/npe ph=np.arange(0,phmax+dth,dth) job_ids=[] for j in range(0,len(ph)): qc = QuantumCircuit(3,2) qcimzic = qc_imz_ic(ph[j]) qc.append(qcimzic,[0,1,2]) qc.measure([0,2],[0,1]) job = execute(qc, backend=device, shots=nshots) jobid = job.job_id() job_ids.append(jobid) f = open("jobs_ids_IMZIC.txt", "w") f.write(str(job_ids)) f.close() print(job_ids) f = open("jobs_ids_IMZIC.txt","r") list_ids_IMZIC = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",") f.close() phmax = 2*math.pi npe=5 dth = phmax/npe ph = np.arange(0,phmax+dth,dth) PD0exp = np.zeros(len(ph)) device = provider.get_backend('ibm_nairobi') for j in range(0,len(ph)): job = device.retrieve_job(list_ids_IMZIC[j]) counts = job.result().get_counts() if '00' in counts: PD0exp[j] = counts['00']/nshots if '10' in counts: PD0exp[j] += counts['10']/nshots print(PD0exp) import numpy as np; import math phmax = 2*math.pi; npt = 100; dpht = phmax/npt pht = np.arange(0,phmax+dtht,dtht) PD0teo = 0.5*np.ones(len(pht)) from matplotlib import pyplot as plt plt.plot(pht,PD0teo, label=r'$Pr(D_0)_{teo}$') plt.plot(ph,PD0sim, 'o', label=r'$Pr(D_0)_{sim}$') plt.plot(ph,PD0exp, '*', label=r'$Pr(D_0)_{exp}$') plt.ylim(0,1); plt.legend(); plt.xlabel(r'$\phi$'); plt.show() Vsim = (np.max(PD0sim)-np.min(PD0sim))/(np.max(PD0sim)+np.min(PD0sim)); print('Vsim = ',Vsim) Vexp = (np.max(PD0exp)-np.min(PD0exp))/(np.max(PD0exp)+np.min(PD0exp)); print('Vexp = ',Vexp) import numpy as np; import math; phmax = 2*math.pi; npt = 100; dpht = phmax/npt; pht = np.arange(0,phmax+dpht,dpht) PD0teoA0 = 0.5*(1+np.cos(pht)); PD0teoA1 = 0.5*(1-np.cos(pht)) from matplotlib import pyplot as plt plt.plot(pht,PD0teoA0, label=r'$Pr(D_0|A=0)_{teo}$'); plt.plot(pht,PD0teoA1, label=r'$Pr(D_0|A=1)_{teo}$') plt.xlim(0,2*math.pi); plt.xlim(-0.1,phmax+0.1); plt.ylim(-0.01,1.01); plt.legend(); plt.xlabel(r'$\phi$'); plt.show() def qc_pqo(): from qiskit import QuantumCircuit qc = QuantumCircuit(1, name='PQO') qc.h(0) qc.s(0) return qc qcpqo = qc_pqo() qcpqo.draw('mpl') def qc_apagadorQ(ph): from qiskit import QuantumCircuit qc = QuantumCircuit(3) qcimzic = qc_imz_ic(ph) qc.append(qcimzic, [0,1,2]) qcpqo = qc_pqo() qc.append(qcpqo, [0]) return qc qcaq = qc_apagadorQ(0) qcaq.decompose().draw('mpl') # Simulação clássica from qiskit import Aer, execute; simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13 import numpy as np; import math; phmax = 2*math.pi; npe = 6; dth = phmax/npe; ph = np.arange(0,phmax+dth,dth) PA0sim = np.zeros(len(ph)); PA1sim = np.zeros(len(ph)); PD0A0sim = np.zeros(len(ph)); PD0A1sim = np.zeros(len(ph)) for j in range(0,len(ph)): qc = QuantumCircuit(3,2) qcaq = qc_apagadorQ(ph[j]) qc.append(qcaq,[0,1,2]) qc.measure([0,2],[0,1]) job = execute(qc, backend=simulator, shots=nshots) counts = job.result().get_counts() if '00' in counts: PA0sim[j] = counts['00']/nshots if '01' in counts: PA0sim[j] += counts['01']/nshots if '10' in counts: PA1sim[j] = counts['10']/nshots if '11' in counts: PA1sim[j] += counts['11']/nshots if PA0sim[j] != 0 and '00' in counts: PD0A0sim[j] = (counts['00']/nshots)/PA0sim[j] if PA1sim[j] != 0 and '10' in counts: PD0A1sim[j] = (counts['10']/nshots)/PA1sim[j] print(PD0A0sim, PD0A1sim) import numpy as np; import math phmax = 2*math.pi; npt = 100; dpht = phmax/npt; pht = np.arange(0,phmax+dpht,dpht) PD0teoA0 = 0.5*(1+np.cos(pht)); PD0teoA1 = 0.5*(1-np.cos(pht)) from matplotlib import pyplot as plt plt.plot(pht,PD0teoA0, label=r'$Pr(D_0|A=0)_{teo}$') plt.plot(pht,PD0teoA1, label=r'$Pr(D_0|A=1)_{teo}$') plt.plot(ph,PD0A0sim, 'o', label=r'$Pr(D_0|A=0)_{sim}$') plt.plot(ph,PD0A1sim, 's', label=r'$Pr(D_0|A=1)_{sim}$') plt.xlim(-0.1,2*math.pi+0.1); plt.ylim(-0.01,1.02); plt.legend(); plt.xlabel(r'$\phi$'); plt.show() import qiskit qiskit.IBMQ.save_account('dabd4674f7b3794f740813fec0c5478bfefdebb7d1dca9b7acd41e3f90ed2c8a8b80af26fb3236289fbfc70d0ea334829a836453ac46f96fee68abcb22495ef4', overwrite = True) qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') nshots = 2**13 import numpy as np; import math phmax=2*math.pi npe=6 dth=phmax/npe ph=np.arange(0,phmax+dth,dth) job_ids=[] for j in range(0,len(ph)): qc = QuantumCircuit(3,2) qcaq = qc_apagadorQ(ph[j]) qc.append(qcaq,[0,1,2]) qc.measure([0,2],[0,1]) job = execute(qc, backend=device, shots=nshots) jobid = job.job_id() job_ids.append(jobid) print(jobid) f = open("jobs_ids_apagador.txt", "w") f.write(str(job_ids)) f.close() f = open("jobs_ids_apagador.txt","r") list_ids_apagador = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",") f.close() phmax = 2*math.pi; npe=6; dth = phmax/npe; ph = np.arange(0,phmax+dth,dth) PD0A0exp = np.zeros(len(ph)); PD0A1exp = np.zeros(len(ph)); PA0exp = np.zeros(len(ph)); PA1exp = np.zeros(len(ph)) device = provider.get_backend('ibm_nairobi') for j in range(0,len(ph)): job = device.retrieve_job(list_ids_apagador[j]) counts = job.result().get_counts() if '00' in counts: PA0exp[j] = counts['00']/nshots if '01' in counts: PA0exp[j] += counts['01']/nshots if '10' in counts: PA1exp[j] = counts['10']/nshots if '11' in counts: PA1exp[j] += counts['11']/nshots if PA0exp[j] != 0 and '00' in counts: PD0A0exp[j] = (counts['00']/nshots)/PA0exp[j] if PA1exp[j] != 0 and '10' in counts: PD0A1exp[j] = (counts['10']/nshots)/PA1exp[j] print(PD0A0exp,PD0A1exp) import numpy as np; import math phmax = 2*math.pi; npt = 100; dpht = phmax/npt pht = np.arange(0,phmax+dpht,dpht) PD0teoA0 = 0.5*(1+np.cos(pht)); PD0teoA1 = 0.5*(1-np.cos(pht)) from matplotlib import pyplot as plt plt.plot(pht,PD0teoA0, label=r'$Pr(D_0|A=0)_{teo}$'); plt.plot(pht,PD0teoA1, label=r'$Pr(D_0|A=1)_{teo}$') plt.plot(ph,PD0A0sim, 'o', label=r'$Pr(D_0|A=0)_{sim}$'); plt.plot(ph,PD0A1sim, 's', label=r'$Pr(D_0|A=1)_{sim}$') plt.plot(ph,PD0A0exp, '*', label=r'$Pr(D_0|A=0)_{exp}$'); plt.plot(ph,PD0A1exp, '+', label=r'$Pr(D_0|A=1)_{exp}$') plt.xlim(-0.1,2*math.pi+0.1); plt.ylim(-0.02,1.02); plt.legend(bbox_to_anchor=(1.4, 1.0),loc='upper right') plt.xlabel(r'$\phi$'); plt.show() VsimA0 = (np.max(PD0A0sim)-np.min(PD0A0sim))/(np.max(PD0A0sim)+np.min(PD0A0sim)) print('VsimA0 = ',VsimA0) VsimA1 = (np.max(PD0A1sim)-np.min(PD0A1sim))/(np.max(PD0A1sim)+np.min(PD0A1sim)) print('VsimA1 = ',VsimA1) VexpA0 = (np.max(PD0A0exp)-np.min(PD0A0exp))/(np.max(PD0A0exp)+np.min(PD0A0exp)) print('VexpA0 = ',VexpA0) VexpA1 = (np.max(PD0A1exp)-np.min(PD0A1exp))/(np.max(PD0A1exp)+np.min(PD0A1exp)) print('VexpA1 = ',VexpA1) import qiskit qiskit.IBMQ.save_account('e20d3045c7c23a3be753606794714e9b47d4331ec46a41b2281e2d601bae27b2b3c1baa0b5cb54f3282a8b5248e552b14c9c556699010660fb94b11d00ff1073', overwrite = True) qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') nshots = 2**13 from qiskit import QuantumRegister, execute from qiskit.ignis.mitigation.measurement import complete_meas_cal qr = QuantumRegister(3) qubit_list = [0, 2] meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr) job = execute(meas_calibs, backend=device, shots=nshots) print(job.job_id()) from qiskit.ignis.mitigation.measurement import CompleteMeasFitter job = device.retrieve_job('cmp2xzqyj8fg0080m0e0') cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels) f = open("jobs_ids_apagador.txt","r") list_ids_apagador = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",") f.close() phmax = 2*math.pi; npe=6; dth = phmax/npe; ph = np.arange(0,phmax+dth,dth) PD0A0exp_mit = np.zeros(len(ph)); PD0A1exp_mit = np.zeros(len(ph)); PA0exp_mit = np.zeros(len(ph)); PA1exp_mit = np.zeros(len(ph)) device = provider.get_backend('ibm_nairobi') for j in range(0,len(ph)): job = device.retrieve_job(list_ids_apagador[j]) mitigated_results = meas_fitter.filter.apply(job.result()) mitigated_counts = mitigated_results.get_counts() if '00' in counts: PA0exp_mit[j] = mitigated_counts['00']/nshots if '01' in counts: PA0exp_mit[j] += mitigated_counts['01']/nshots if '10' in counts: PA1exp_mit[j] = mitigated_counts['10']/nshots if '11' in counts: PA1exp_mit[j] += mitigated_counts['11']/nshots if PA0exp_mit[j] != 0 and '00' in mitigated_counts: PD0A0exp_mit[j] = (mitigated_counts['00']/nshots)/PA0exp[j] if PA1exp[j] != 0 and '10' in mitigated_counts: PD0A1exp_mit[j] = (mitigated_counts['10']/nshots)/PA1exp[j] print(PD0A0exp_mit, PD0A1exp_mit) import matplotlib; matplotlib.rcParams.update({'font.size':11}); plt.figure(figsize = (7,5), dpi = 100) import numpy as np; import math; phmax = 2*math.pi; npt = 100; dpht = phmax/npt; pht = np.arange(0,phmax+dpht,dpht) PD0teoA0 = 0.5*(1+np.cos(pht)); PD0teoA1 = 0.5*(1-np.cos(pht)); from matplotlib import pyplot as plt plt.plot(pht,PD0teoA0, label=r'$Pr(D_0|A=0)_{teo}$'); plt.plot(pht,PD0teoA1, label=r'$Pr(D_0|A=1)_{teo}$') plt.plot(ph,PD0A0sim, 'o', label=r'$Pr(D_0|A=0)_{sim}$'); plt.plot(ph,PD0A1sim, 's', label=r'$Pr(D_0|A=1)_{sim}$') plt.plot(ph,PD0A0exp, '*', label=r'$Pr(D_0|A=0)_{exp}$'); plt.plot(ph,PD0A1exp, 'v', label=r'$Pr(D_0|A=1)_{exp}$') plt.plot(ph,PD0A0exp_mit, '^', label=r'$Pr(D_0|A=0)_{expmit}$'); plt.plot(ph,PD0A1exp_mit, '+', label=r'$Pr(D_0|A=1)_{expmit}$') plt.xlim(-0.1,2*math.pi+0.1); plt.ylim(-0.03,1.03); plt.legend(bbox_to_anchor=(1.4, 1.0),loc='upper right') plt.xlabel(r'$\phi$'); plt.show() VsimA0 = (np.max(PD0A0sim)-np.min(PD0A0sim))/(np.max(PD0A0sim)+np.min(PD0A0sim)); print('VsimA0 = ',VsimA0) VsimA1 = (np.max(PD0A1sim)-np.min(PD0A1sim))/(np.max(PD0A1sim)+np.min(PD0A1sim)); print('VsimA1 = ',VsimA1) VexpA0 = (np.max(PD0A0exp)-np.min(PD0A0exp))/(np.max(PD0A0exp)+np.min(PD0A0exp)); print('VexpA0 = ',VexpA0) VexpA1 = (np.max(PD0A1exp)-np.min(PD0A1exp))/(np.max(PD0A1exp)+np.min(PD0A1exp)); print('VexpA1 = ',VexpA1) VexpA0_mit = (np.max(PD0A0exp_mit)-np.min(PD0A0exp_mit))/(np.max(PD0A0exp_mit)+np.min(PD0A0exp_mit)) print('VexpA0_mit = ',VexpA0_mit) VexpA1_mit = (np.max(PD0A1exp_mit)-np.min(PD0A1exp_mit))/(np.max(PD0A1exp_mit)+np.min(PD0A1exp_mit)) print('VexpA1_mit = ',VexpA1_mit) import math; import numpy as np al_max = math.pi/4; npt = 100; dalt = al_max/npt alt = np.arange(0,al_max+dalt,dalt) Vteo = np.sin(2*alt) from matplotlib import pyplot as plt plt.plot(alt,Vteo, label=r'$V_{teo}(A=0)$') plt.xlim(-0.01,al_max+0.01); plt.ylim(-0.01,1.01) plt.xlabel(r'$\alpha$'); plt.legend() plt.show() from qiskit import QuantumCircuit def qc_Psi(al): # prepara o estado parcialmente emaranhado qc = QuantumCircuit(2, name = r'$|\Psi\rangle$') qc.u(2*al,0,0, 0) qc.cx(0,1) qc.z(0) qc.x(1) return qc qcpsi = qc_Psi(0.1); qcpsi.draw('mpl') # simulação clássica from qiskit import Aer, execute; simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13 import math; import numpy as np almax = math.pi/4; npa=2; dal = almax/npa; al = np.arange(0,almax+dal,dal) phmax = 2*math.pi; npe=4; dph = phmax/npe; ph = np.arange(0,phmax+dph,dph); VA0sim = np.zeros(len(al)) for j in range(0,len(al)): PD0A0sim = np.zeros(len(ph)); PA0sim = np.zeros(len(ph)) for k in range(0,len(ph)): qc = QuantumCircuit(3,2) qcpsi = qc_Psi(al[j]); qc.append(qcpsi, [0,1]) qcdfp = qc_dfp(); qc.append(qcdfp, [1,2]); qcpmo = qc_pmo(); qc.append(qcpmo, [1,2]) qce = qc_espelhos(); qc.append(qce, [2]); qc.p(ph[k], [2]) qcdf = qc_df(); qc.append(qcdf, [2]); qcpqo = qc_pqo(); qc.append(qcpqo, [0]) qc.measure([0,2],[0,1]) job = execute(qc, backend=simulator, shots=nshots); counts = job.result().get_counts() if '00' in counts: PA0sim[k] = counts['00']/nshots if '01' in counts: PA0sim[k] += counts['01']/nshots if PA0sim[k] != 0: if '00' in counts: PD0A0sim[k] = (counts['00']/nshots)/PA0sim[k] VA0sim[j] = (np.max(PD0A0sim)-np.min(PD0A0sim))/(np.max(PD0A0sim)+np.min(PD0A0sim)) VA0sim PD0A0sim qc.draw('mpl') import math; import numpy as np al_max = math.pi/4; npt = 100; dalt = al_max/npt; alt = np.arange(0,al_max+dalt,dalt) Vteo = np.sin(2*alt) from matplotlib import pyplot as plt plt.plot(alt,Vteo, label=r'$V_{teo}(A=0)$') plt.plot(al,VA0sim, 'o', label=r'$V_{sim}(A=0)$') plt.xlim(-0.01,al_max+0.01); plt.ylim(-0.01,1.02); plt.xlabel(r'$\alpha$'); plt.legend() plt.show() # Experimento (simulação quântica) from qiskit import execute; import math; import numpy as np almax = math.pi/4; npa = 2; dal = almax/npa; al = np.arange(0,almax+dal,dal) phmax = 2*math.pi; npe=4; dph = phmax/npe; ph = np.arange(0,phmax+dph,dph) job_ids=[] for j in range(0,len(al)): for k in range(0,len(ph)): qc = QuantumCircuit(3,2); qcpsi = qc_Psi(al[j]); qc.append(qcpsi, [0,1]) qcdfp = qc_dfp(); qc.append(qcdfp, [1,2]); qcpmo = qc_pmo(); qc.append(qcpmo, [1,2]) qce = qc_espelhos(); qc.append(qce, [2]); qc.p(ph[k], [2]) qcdf = qc_df(); qc.append(qcdf, [2]); qcpqo = qc_pqo(); qc.append(qcpqo, [0]); qc.measure([0,2],[0,1]) job = execute(qc, backend=device, shots=nshots); jobid = job.job_id(); job_ids.append(jobid); print(jobid) f = open("jobs_ids_apagador_parcial.txt", "w"); f.write(str(job_ids)); f.close() f = open("jobs_ids_apagador_parcial.txt","r") list_ids_apagador_parcial = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",") f.close() import math; import numpy as np almax = math.pi/4; npa=2; dal = almax/npa; al = np.arange(0,almax+dal,dal) phmax = 2*math.pi; npe=4; dph = phmax/npe; ph = np.arange(0,phmax+dph,dph); VA0exp = np.zeros(len(al)) for j in range(0,len(al)): PD0A0exp = np.zeros(len(ph)); PA0exp = np.zeros(len(ph)) for k in range(0,len(ph)): job = device.retrieve_job(list_ids_apagador_parcial[(npe+1)*j+k]) counts = job.result().get_counts() if '00' in counts: PA0exp[k] = counts['00']/nshots if '01' in counts: PA0exp[k] += counts['01']/nshots if PA0exp[k] != 0: if '00' in counts: PD0A0exp[k] = (counts['00']/nshots)/PA0exp[k] VA0exp[j] = (np.max(PD0A0exp)-np.min(PD0A0exp))/(np.max(PD0A0exp)+np.min(PD0A0exp)) VA0exp import math; import numpy as np al_max = math.pi/4; npt = 100; dalt = al_max/npt; alt = np.arange(0,al_max+dalt,dalt); Vteo = np.sin(2*alt) from matplotlib import pyplot as plt plt.plot(alt,Vteo, label=r'$V_{teo}(A=0)$') plt.plot(al,VA0sim, 'o', label=r'$V_{sim}(A=0)$') plt.plot(al,VA0exp, '^', label=r'$V_{exp}(A=0)$') plt.xlim(-0.01,al_max+0.01); plt.ylim(-0.01,1.02); plt.xlabel(r'$\alpha$'); plt.legend() plt.show()
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
jonasmaziero
from qiskit import QuantumCircuit qc = QuantumCircuit(1,1) qc.x(0) qc.measure(0,0) qc.draw('mpl') from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 job = execute(qc, backend=simulator,shots=nshots) counts = job.result().get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(counts) from qiskit import QuantumCircuit def qc_df(): # divisor de feixes 50:50 qc = QuantumCircuit(1, name='DF') qc.s(0) qc.h(0) qc.s(0) return qc qcdf = qc_df(); qcdf.draw('mpl') def qc_espelhos(): qc = QuantumCircuit(1, name='E') qc.z(0) qc.y(0) return qc qce = qc_espelhos(); qce.draw('mpl') def qc_bomba(): qc = QuantumCircuit(2, name='B') qc.cx(0,1) return qc qcb = qc_bomba(); qcb.draw('mpl') def qc_detector_de_bomba(): qc = QuantumCircuit(2, name='DB') qcdf = qc_df(); qc.append(qcdf,[0]) qce = qc_espelhos(); qc.append(qce,[0]) qcb = qc_bomba(); qc.append(qcb,[0,1]) qcdf = qc_df(); qc.append(qcdf,[0]) return qc qcdb = qc_detector_de_bomba(); qcdb.draw('mpl') qc = QuantumCircuit(2,2) qcdb = qc_detector_de_bomba(); qc.append(qcdb,[0,1]) qc.measure([0,1],[0,1]) qc.draw('mpl') # Simulação clássica from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 job = execute(qc, backend=simulator,shots=nshots) counts = job.result().get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(counts) import qiskit qiskit.IBMQ.save_account('18d1a392e10ffca595cb87ad064ca04fb8f407e702274610ba421f54ac39fbef8e14b664d350f3e48cc9762e4b63aad22ecb2135f16468825ae37b14a85c1762', overwrite = True) qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') nshots = 2**13 # Experimento (simulação quântica) job = execute(qc, backend=device, shots=nshots) print(job.job_id()) job = device.retrieve_job('cmpt4asb9x9g0088t2c0') from qiskit.tools.visualization import plot_histogram plot_histogram(job.result().get_counts())
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
jonasmaziero
from IPython.display import IFrame; IFrame("https://www.ibm.com/quantum", 900,500) import csv with open('ibm_lagos_calibrations_2023-09-28T17_22_25Z.csv', newline='') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in spamreader: print(', '.join(row)) import qiskit qiskit.__qiskit_version__ # Copie se API Token no IBMQ e cole aqui qiskit.IBMQ.save_account('ee8631db565e87e97b066d08e02cafb9bfa745be07e573095b666daa608a37ce58ae6ef5c174aff56a935dadfe1fa9c82edfe37aec6b24774bc94613658cc7d8', overwrite = True) # Execute esse comando uma vez só qiskit.IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider.backends() from qiskit import * qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr,cr) qc.h(qr[0]) qc.cx(qr[0],qr[1]) qc.measure(qr[0],cr[0]) qc.measure(qr[1],cr[1]) qc.draw('mpl') simulator = Aer.get_backend('qasm_simulator') nshots = 8192 # número de "prepara-e-mede" job = execute(qc, backend = simulator, shots = nshots) from qiskit.tools.visualization import plot_histogram plot_histogram(job.result().get_counts(qc)) # Acessando as contagens com numpy counts = job.result().get_counts(qc) counts counts['00'] # probabilidade p00 = 0; p01 = 0; p10 = 0; p11 = 0 for j in (0,2): for k in (0,2): if '00' in counts: p00 = counts['00']/nshots if '01' in counts: p01 = counts['01']/nshots if '10' in counts: p10 = counts['10']/nshots if '11' in counts: p11 = counts['11']/nshots p00, p01, p10, p11 device = provider.get_backend('ibm_lagos') from qiskit.tools.monitor import job_monitor job = execute(qc, backend = device, shots = nshots) job_monitor(job) plot_histogram(job.result().get_counts(qc)) counts = job.result().get_counts(qc) counts counts['00'] # probabilidade p00 = 0; p01 = 0; p10 = 0; p11 = 0 for j in (0,2): for k in (0,2): if '00' in counts: p00 = counts['00']/nshots if '01' in counts: p01 = counts['01']/nshots if '10' in counts: p10 = counts['10']/nshots if '11' in counts: p11 = counts['11']/nshots p00, p01, p10, p11
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
jonasmaziero
from sympy import Matrix X = Matrix([[0,1],[1,0]]); X Y = Matrix([[0,-1j],[1j,0]]); Y Z = Matrix([[1,0],[0,-1]]); Z X.eigenvals() X.eigenvects() Y.eigenvects() Z.eigenvects() from sympy import Matrix X = Matrix([[0,1],[1,0]]) ket0 = Matrix([[1],[0]]); ket1 = Matrix([[0],[1]]); ket0, ket1 X*ket0, X*ket1 Y*ket0, Y*ket1, Z*ket0, Z*ket1 from sympy.physics.quantum import TensorProduct as tp ket00 = tp(ket0,ket0); ket01 = tp(ket0,ket1); ket10 = tp(ket1,ket0); ket11 = tp(ket1,ket1); ket00, ket01, ket10, ket11 tp(eye(2),X), tp(eye(2),eye(2))*ket00, tp(eye(2),X)*ket00, tp(X,eye(2))*ket00, tp(X,X)*ket00 from qiskit import QuantumCircuit import qiskit from qiskit.quantum_info import Statevector qc = QuantumCircuit(2) # prepara o estado |00> qc.draw('mpl') state = Statevector(qc) state qc = QuantumCircuit(2) qc.x(1) # estado |01> qc.draw('mpl') state = Statevector(qc); state from sympy.physics.quantum.dagger import Dagger P0 = ket0*Dagger(ket0); P1 = ket1*Dagger(ket1); P0,P1 CNOTab = tp(P0,eye(2)) + tp(P1,X); CNOTba = tp(eye(2),P0) + tp(X,P1); CNOTab,CNOTba H = Matrix([[1,1],[1,-1]])/sqrt(2); H Phip = CNOTab*tp(H,eye(2))*ket00; Phim = CNOTab*tp(H,eye(2))*ket10; Phip,Phim from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc.draw('mpl') from qiskit.quantum_info import Statevector state = Statevector(qc); state # |Phi+> from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.x([0,1]) qc.h(0) qc.cx(0,1) qc.draw('mpl') from qiskit.quantum_info import Statevector state = Statevector(qc); state # |Psi-> from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(0); qc.cx(0,1) # prepara |Phi+> qc.barrier() qc.cx(0,1) qc.h(0) qc.draw('mpl') from qiskit.quantum_info import Statevector state = Statevector(qc); state # estado |00> from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.x([0,1]); qc.h(0); qc.cx(0,1) # prepara |Psi-> qc.barrier() qc.cx(0,1) qc.h(0) qc.draw('mpl') from qiskit.quantum_info import Statevector state = Statevector(qc); state # estado |11> from sympy import Matrix X = Matrix([[0,1],[1,0]]); X init_printing(use_unicode=True) # pra visualização ficar melhor X.eigenvects() from qiskit import QuantumCircuit qc = QuantumCircuit(1,1) qc.h(0) from qiskit.quantum_info import Statevector state = Statevector(qc) state qc.measure(0,0) qc.draw('mpl') from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 # 8192 job = execute(qc, backend=simulator, shots=nshots) from qiskit.tools.visualization import plot_histogram plot_histogram(job.result().get_counts()) from qiskit import QuantumCircuit qc = QuantumCircuit(1,1) qc.h(0) qc.barrier() qc.h(0) qc.measure(0,0) qc.draw('mpl') from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 # 8192 job = execute(qc, backend=simulator, shots=nshots) from qiskit.tools.visualization import plot_histogram plot_histogram(job.result().get_counts()) from qiskit import QuantumCircuit qc = QuantumCircuit(1,1) qc.sdg(0) qc.h(0) qc.measure(0,0) qc.draw('mpl') from qiskit import execute, Aer simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 job = execute(qc, backend=simulator, shots=nshots) from qiskit.tools.visualization import plot_histogram plot_histogram(job.result().get_counts()) from sympy import symbols th, ph, lb = symbols('theta phi lambda'); th, ph, lb sn = Matrix([[cos(th),exp(-1j*ph)*sin(th)],[exp(1j*ph)*sin(th),-cos(th)]]); sn sn.eigenvects() import math math.cos(math.pi/8)**2 from qiskit import QuantumCircuit qc = QuantumCircuit(1,1) import math th = -math.pi/4 ph = 0 lb = math.pi - ph qc.u(th,ph,lb, 0) # porta parametrizada qc.measure(0,0) qc.draw('mpl') from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 job = execute(qc, backend = simulator, shots=nshots) from qiskit.tools.visualization import plot_histogram plot_histogram(job.result().get_counts()) # Cria o circuito quântico, sem usar medidas from qiskit import QuantumCircuit qc = QuantumCircuit(1) qc.h(0) qc.s(0) qc.draw(output='mpl') # estado |o+>=(|0>+i|1>)/sqrt(2) 2**13 from qiskit import Aer, execute; simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13 import qiskit; from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter qstc = state_tomography_circuits(qc, [0]); job = execute(qstc, backend=simulator, shots=nshots) qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq') qiskit.visualization.plot_state_city(rho) rho from sympy import Matrix, symbols, init_printing, eye init_printing(use_unicode=True) X = Matrix([[0,1],[1,0]]); Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]]) x,y,z = symbols('x y z') rho = (1/2)*(eye(2) + x*X + y*Y + z*Z); rho rho.eigenvals() from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector qc = QuantumCircuit(4) # não faz nada no 1º qubit qc.x(1) qc.h(2) qc.h(3); qc.s(3) state = Statevector(qc) plot_bloch_multivector(state)
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
jonasmaziero
from sympy import Matrix, sqrt, init_printing; init_printing(use_unicode=True) ket0 = Matrix([[1],[0]]); ket1 = Matrix([[0],[1]]); from sympy.physics.quantum import TensorProduct as tp ket00 = tp(ket0,ket0); ket01 = tp(ket0,ket1); ket10 = tp(ket1,ket0); ket11 = tp(ket1,ket1) Psim = (ket01-ket10)/sqrt(2); Psim.T X = Matrix([[0,1],[1,0]]); Z = Matrix([[1,0],[0,-1]]); (tp(Z,Z)*Psim).T, (tp(X,X)*Psim).T A1 = Z; A2 = X; B1 = (Z+X)/sqrt(2); B2 = (Z-X)/sqrt(2); O = tp(A1,B1)+tp(A1,B2)+tp(A2,B1)-tp(A2,B2) O, sqrt(2)*(tp(Z,Z)+tp(X,X)) from qiskit import QuantumCircuit def qc_Psim(): # função que cria o circuito quantico para preparar o estado de Bell |Psi-> qc = QuantumCircuit(2, name=r'$|\Psi_-\rangle$') qc.x([0,1]) qc.h(0) qc.cx(0,1) #qc.z(0) #qc.x(1) return qc qc_Psim_ = qc_Psim() qc_Psim_.draw('mpl') import qiskit from qiskit.quantum_info import Statevector qc_Psim_ = qc_Psim() state = Statevector(qc_Psim_) qiskit.visualization.plot_state_city(state) from sympy import Matrix Psim = Matrix([[0],[1],[-1],[0]])/sqrt(2) #Psim from sympy.physics.quantum.dagger import Dagger rho_Psim = Psim*Dagger(Psim) rho_Psim qc = QuantumCircuit(2,2) qc_Psim_ = qc_Psim() qc.append(qc_Psim_,[0,1]) qc.measure([0,1],[0,1]) qc.draw('mpl') from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 job = execute(qc, backend=simulator, shots=nshots) counts = job.result().get_counts() p00=0; p01=0; p10=0; p11=0 for j in (0,2): for k in (0,2): if '00' in counts: p00 = counts['00']/nshots if '01' in counts: p01 = counts['01']/nshots if '10' in counts: p10 = counts['10']/nshots if '11' in counts: p11 = counts['11']/nshots ZZ_avg = (p00+p11)-(p01+p10) ZZ_avg qc = QuantumCircuit(2,2) qc_Psim_ = qc_Psim() qc.append(qc_Psim_,[0,1]) qc.h([0,1]) qc.measure([0,1],[0,1]) qc.draw('mpl') from qiskit import Aer simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 job = execute(qc, backend=simulator, shots=nshots) counts = job.result().get_counts() p00=0; p01=0; p10=0; p11=0 for j in (0,2): for k in (0,2): if '00' in counts: p00 = counts['00']/nshots if '01' in counts: p01 = counts['01']/nshots if '10' in counts: p10 = counts['10']/nshots if '11' in counts: p11 = counts['11']/nshots XX_avg = (p00+p11)-(p01+p10) XX_avg O_avg = sqrt(2)*(ZZ_avg + XX_avg) O_avg, float(O_avg) import qiskit qiskit.IBMQ.save_account('5a0140fc106f9f8ae43104d5751baf65c726195f8b45b1f42e161f0182b5fe79ca6dbb1405159301e1e44d40d680223ea572d9b8737205bfa6f90485f1f88123', overwrite = True) qiskit.IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibm_nairobi') qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_,[0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend = device, shots = nshots); print(job.job_id()) device = provider.get_backend('ibm_nairobi'); job = device.retrieve_job('cmfbdw78vz2g008daj90') counts = job.result().get_counts() p00=0; p01=0; p10=0; p11=0 for j in (0,2): for k in (0,2): if '00' in counts: p00 = counts['00']/nshots if '01' in counts: p01 = counts['01']/nshots if '10' in counts: p10 = counts['10']/nshots if '11' in counts: p11 = counts['11']/nshots ZZ_avg_exp = (p00+p11)-(p01+p10); ZZ_avg_exp device = provider.get_backend('ibm_nairobi') qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_,[0,1]); qc.h([0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend = device, shots = nshots); jobid = job.job_id() print(jobid) device = provider.get_backend('ibm_nairobi'); job = device.retrieve_job('cmfbekafysfg008t2y4g') counts = job.result().get_counts() p00=0; p01=0; p10=0; p11=0 for j in (0,2): for k in (0,2): if '00' in counts: p00 = counts['00']/nshots if '01' in counts: p01 = counts['01']/nshots if '10' in counts: p10 = counts['10']/nshots if '11' in counts: p11 = counts['11']/nshots XX_avg_exp = (p00+p11)-(p01+p10); XX_avg_exp O_avg_exp = sqrt(2.)*(ZZ_avg_exp + XX_avg_exp) O_avg_exp import numpy as np import math th_max = math.pi/2; npt = 100; dth = th_max/npt; th = np.arange(0,th_max+dth,dth) Oteo = -math.sqrt(2)*(1+np.sin(th)) Odl = -2*np.ones(len(th)) from matplotlib import pyplot as plt plt.plot(th, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$') plt.plot(th, Odl, label = 'LHV limit') plt.xlabel(r'$\theta$') plt.legend(); plt.show() # circuito quântico para preparação do estado Psi def qc_Psi(th): qc = QuantumCircuit(2) qc.u(th,0,0, 0) qc.cx(0,1) qc.z(0) qc.x(1) return qc import math th = math.pi/4 qc_Psi_ = qc_Psi(th) qc_Psi_.draw('mpl') # função para calcular as médias tipo <A\otimes B>, com A,B=+1,-1, dadas as probabilidades def ABavg(result, nshots): avg = 0 if '00' in result: avg += result['00'] if '01' in result: avg -= result['01'] if '10' in result: avg -= result['10'] if '11' in result: avg += result['11'] return avg/nshots # = (N(00)-N(01)-N(10)+N(11))/nshots th_max = math.pi/2; npe = 5; dth = th_max/npe; th = np.arange(0,th_max+dth,dth) Osim = np.zeros(len(th)) from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 for j in range(0,len(th)): # mede ZZ qc = QuantumCircuit(2,2) qc_Psi_ = qc_Psi(th[j]); qc.append(qc_Psi_, [0,1]) qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots) result = job.result().get_counts() ZZavg = ABavg(result, nshots) # mede XX qc = QuantumCircuit(2,2) qc_Psi_ = qc_Psi(th[j]); qc.append(qc_Psi_, [0,1]) qc.h([0,1]) qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots) result = job.result().get_counts() XXavg = ABavg(result, nshots) # média de O Osim[j] = math.sqrt(2)*(ZZavg + XXavg) Osim import numpy as np; import math th_max = math.pi/2; dtht = th_max/npt; tht = np.arange(0,th_max+dtht,dtht) Oteo = -math.sqrt(2)*(1+np.sin(tht)); Odl = -2*np.ones(len(tht)) dth = th_max/npe; th = np.arange(0,th_max+dth,dth) from matplotlib import pyplot as plt plt.plot(tht, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$') plt.plot(tht, Odl, label = 'LHV limit') plt.plot(th, Osim, '*', label = r'$\langle O\rangle_{\Psi}^{sim}$') plt.xlabel(r'$\theta$') plt.legend(); plt.show() import qiskit qiskit.IBMQ.save_account('45b1db3a3c2ecae609e6c98184250919ccd31c9ea24100440abe0821fe6312c2b05a67239806c5b0020754eb3072f924547adb621e1e3931200aee13583a776f', overwrite = True) qiskit.IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') th_max = math.pi/2; dth = th_max/npe; th = np.arange(0,th_max+dth,dth) device = provider.get_backend('ibm_nairobi') nshots = 2**13 jobs_ids_ZZ = []; jobs_ids_XX = [] for j in range(0,len(th)): # mede ZZ qc = QuantumCircuit(2,2); qc_Psi_ = qc_Psi(th[j]); qc.append(qc_Psi_, [0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots) print('ZZ',job.job_id()); jobs_ids_ZZ.append(job.job_id()) # mede XX qc = QuantumCircuit(2,2); qc_Psi_ = qc_Psi(th[j]); qc.append(qc_Psi_, [0,1]); qc.h([0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots) print('XX',job.job_id()); jobs_ids_XX.append(job.job_id()) f = open("jobs_ids_ZZ.txt", "w"); f.write(str(jobs_ids_ZZ)); f.close() f = open("jobs_ids_XX.txt", "w"); f.write(str(jobs_ids_XX)); f.close() f = open("jobs_ids_ZZ.txt","r") list_ids_ZZ = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",") f.close() f = open("jobs_ids_XX.txt","r") list_ids_XX = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",") f.close() th_max = math.pi/2; dth = th_max/npe; th = np.arange(0,th_max+dth,dth) Oexp = np.zeros(len(th)) for j in range(0,len(th)): # média de ZZ job = device.retrieve_job(list_ids_ZZ[j]) result = job.result().get_counts() ZZavg = ABavg(result, nshots) # média de XX job = device.retrieve_job(list_ids_XX[j]) result = job.result().get_counts() XXavg = ABavg(result, nshots) # média de O Oexp[j] = math.sqrt(2)*(ZZavg + XXavg) Oexp import numpy as np; import math th_max = math.pi/2; dtht = th_max/npt; tht = np.arange(0,th_max+dtht,dtht) Oteo = -math.sqrt(2)*(1+np.sin(tht)); Odl = -2*np.ones(len(tht)) dth = th_max/npe; th = np.arange(0,th_max+dth,dth) from matplotlib import pyplot as plt plt.plot(tht, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$') plt.plot(tht, Odl, label = 'LHV limit') plt.plot(th, Osim, '*', label = r'$\langle O\rangle_{\Psi}^{sim}$') plt.plot(th, Oexp, '*', label = r'$\langle O\rangle_{\Psi}^{exp}$') plt.xlabel(r'$\theta$'); plt.legend(); plt.show() def f_Oavg(O,psi): from sympy.physics.quantum.dagger import Dagger return Dagger(psi)*O*psi from sympy import Matrix, symbols, cos, sin, sqrt, simplify from sympy.physics.quantum import TensorProduct as tp Psim = Matrix([[0],[1],[-1],[0]])/sqrt(2) X = Matrix([[0,1],[1,0]]) Z = Matrix([[1,0],[0,-1]]) th = symbols('theta') A1B1 = tp(Z,cos(th)*Z+sin(th)*X) A1B1avg = f_Oavg(A1B1,Psim) A1B2 = tp(Z,(Z-X)/sqrt(2)) A1B2avg = f_Oavg(A1B2,Psim) A2B1 = tp(X,cos(th)*Z+sin(th)*X) A2B1avg = f_Oavg(A2B1,Psim) A2B2 = tp(X,(Z-X)/sqrt(2)) A2B2avg = f_Oavg(A2B2,Psim) Oavg = A1B1avg + A1B2avg + A2B1avg - A2B2avg A1B1avg, A1B2avg, A2B1avg, A2B2avg, simplify(Oavg) import numpy as np; import math th_max = math.pi/4; npt = 100; dth = th_max/npt; tht = np.arange(-th_max,th_max+dth,dth) Oteo = -math.sqrt(2)*(1+np.sin(tht+math.pi/4)) Odl = -2*np.ones(len(tht)) from matplotlib import pyplot as plt plt.plot(tht, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$') plt.plot(tht, Odl, label = 'LHV limit') plt.xlabel(r'$\theta$') plt.legend(); plt.show() th_max = math.pi/4; npe = 4; dth = 2*th_max/npe; th = np.arange(-th_max,th_max+dth,dth); Osim = np.zeros(len(th)) from qiskit import *; simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13 for j in range(0,len(th)): # mede <A1B1> qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.u(th[j],0,math.pi, 1); qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots); result = job.result().get_counts(); A1B1avg = ABavg(result, nshots) # mede <A1B2> qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.u(-math.pi/4,0,math.pi, 1); qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots); result = job.result().get_counts(); A1B2avg = ABavg(result, nshots) # mede <A2B1> qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.h(0); qc.u(th[j],0,math.pi, 1); qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots); result = job.result().get_counts(); A2B1avg = ABavg(result, nshots) # mede <A2B2> qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.h(0); qc.u(-math.pi/4,0,math.pi, 1); qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots); result = job.result().get_counts(); A2B2avg = ABavg(result, nshots) # média de O Osim[j] = A1B1avg + A1B2avg + A2B1avg - A2B2avg Osim import numpy as np; import math th_max = math.pi/4; dtht = 2*th_max/npt; tht = np.arange(-th_max,th_max+dtht,dtht) Oteo = -math.sqrt(2)*(1+np.sin(tht+math.pi/4)); Odl = -2*np.ones(len(tht)) dth = 2*th_max/npe; th = np.arange(-th_max,th_max+dth,dth) from matplotlib import pyplot as plt plt.plot(tht, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$') plt.plot(tht, Odl, label = 'LHV limit') plt.plot(th, Osim, '*', label = r'$\langle O\rangle_{\Psi}^{sim}$') plt.xlabel(r'$\theta$') plt.legend(); plt.show() import qiskit qiskit.IBMQ.save_account('45b1db3a3c2ecae609e6c98184250919ccd31c9ea24100440abe0821fe6312c2b05a67239806c5b0020754eb3072f924547adb621e1e3931200aee13583a776f', overwrite = True) qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') th_max = math.pi/4; npe = 4; dth = 2*th_max/npe; th = np.arange(-th_max,th_max+dth,dth) from qiskit import *; device = provider.get_backend('ibm_nairobi'); nshots = 2**13 jobs_ids_A1B1 = []; jobs_ids_A1B2 = []; jobs_ids_A2B1 = []; jobs_ids_A2B2 = [] for j in range(0,len(th)): # mede <A1B1> qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.u(th[j],0,math.pi, 1) qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots); print('A1B1:',job.job_id()); jobs_ids_A1B1.append(job.job_id()) # mede <A1B2> qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.u(-math.pi/4,0,math.pi, 1) qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots); print('A1B2:',job.job_id()); jobs_ids_A1B2.append(job.job_id()) # mede <A2B1> qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.h(0); qc.u(th[j],0,math.pi, 1) qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots); print('A2B1:',job.job_id()); jobs_ids_A2B1.append(job.job_id()) # mede <A2B2> qc = QuantumCircuit(2,2); qc_Psim_ = qc_Psim(); qc.append(qc_Psim_, [0,1]); qc.h(0); qc.u(-math.pi/4,0,math.pi, 1) qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots); print('A2B2:',job.job_id()); jobs_ids_A2B2.append(job.job_id()) f = open("jobs_ids_A1B1.txt", "w"); f.write(str(jobs_ids_A1B1)); f.close() f = open("jobs_ids_A1B2.txt", "w"); f.write(str(jobs_ids_A1B2)); f.close() f = open("jobs_ids_A2B1.txt", "w"); f.write(str(jobs_ids_A2B1)); f.close() f = open("jobs_ids_A2B2.txt", "w"); f.write(str(jobs_ids_A2B2)); f.close() device = provider.get_backend('ibm_nairobi') f = open("jobs_ids_A1B1.txt","r") list_ids_A1B1 = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(","); f.close() f = open("jobs_ids_A1B2.txt","r") list_ids_A1B2 = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(","); f.close() f = open("jobs_ids_A2B1.txt","r") list_ids_A2B1 = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(","); f.close() f = open("jobs_ids_A2B2.txt","r") list_ids_A2B2 = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(","); f.close() th_max = math.pi/4; dth = 2*th_max/npe; th = np.arange(-th_max,th_max+dth,dth); Oexp = np.zeros(len(th)) for j in range(0,len(th)): # média de A1B1 job = device.retrieve_job(list_ids_A1B1[j]); result = job.result().get_counts(); A1B1avg = ABavg(result, nshots) # média de A1B2 job = device.retrieve_job(list_ids_A1B2[j]); result = job.result().get_counts(); A1B2avg = ABavg(result, nshots) # média de A2B1 job = device.retrieve_job(list_ids_A2B1[j]); result = job.result().get_counts(); A2B1avg = ABavg(result, nshots) # média de A2B2 job = device.retrieve_job(list_ids_A2B2[j]); result = job.result().get_counts(); A2B2avg = ABavg(result, nshots) # média de O Oexp[j] = A1B1avg + A1B2avg + A2B1avg - A2B2avg Oexp import numpy as np; import math th_max = math.pi/4; dtht = 2*th_max/npt; tht = np.arange(-th_max,th_max+dtht,dtht) Oteo = -math.sqrt(2)*(1+np.sin(tht+math.pi/4)); Odl = -2*np.ones(len(tht)) dth = 2*th_max/npe; th = np.arange(-th_max,th_max+dth,dth) from matplotlib import pyplot as plt plt.plot(tht, Oteo, label = r'$\langle O\rangle_{\Psi}^{teo}$') plt.plot(tht, Odl, label = 'LHV limit') plt.plot(th, Osim, '*', label = r'$\langle O\rangle_{\Psi}^{sim}$') plt.plot(th, Oexp, '*', label = r'$\langle O\rangle_{\Psi}^{exp}$') plt.xlabel(r'$\theta$'); plt.legend(); plt.show()
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
jonasmaziero
from qiskit import QuantumCircuit; qc = QuantumCircuit(2,2) qc.barrier() qc.cx(0,1); qc.h(0) qc.barrier() qc.measure([0,1],[0,1]) qc.draw('mpl') from qiskit import QuantumCircuit, execute, Aer; from qiskit.tools.visualization import plot_histogram simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13 qc = QuantumCircuit(2,2) qc.h(0); qc.cx(0,1) # prepara |Phi+> qc.barrier() qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB qc.draw('mpl') job = execute(qc, backend=simulator, shots=nshots) plot_histogram(job.result().get_counts()) qc = QuantumCircuit(2,2) qc.x(1); qc.h(0); qc.cx(0,1) # prepara |Psi+> qc.barrier() qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB qc.draw('mpl') job = execute(qc, backend=simulator, shots=nshots) plot_histogram(job.result().get_counts()) qc = QuantumCircuit(2,2) qc.x(0); qc.h(0); qc.cx(0,1) # prepara |Phi-> qc.barrier() qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB qc.draw('mpl') job = execute(qc, backend=simulator, shots=nshots) plot_histogram(job.result().get_counts()) qc = QuantumCircuit(2,2) qc.x([0,1]); qc.h(0); qc.cx(0,1) # prepara |Psi-> qc.barrier() qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB qc.draw('mpl') job = execute(qc, backend=simulator, shots=nshots) plot_histogram(job.result().get_counts()) import qiskit qiskit.IBMQ.save_account('72f5d1e3769658b4908c384492eb3a9bd6d6ac4ab1fdf613d7fbe72884114d62728d6fd60a8bf8d0b6698f2f5463a605742658fee1ce3318181105c6acb8120e', overwrite = True) qiskit.IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibm_nairobi') nshots = 2**13 qc = QuantumCircuit(2,2) qc.h(0); qc.cx(0,1) # prepara |Phi+> qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB job = execute(qc, backend=device, shots=nshots) print(job.job_id()) job = device.retrieve_job('cmjn5w752bbg00825esg') from qiskit.tools.visualization import plot_histogram; plot_histogram(job.result().get_counts()) qc = QuantumCircuit(2,2) qc.x(1); qc.h(0); qc.cx(0,1) # prepara |Psi+> qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB job = execute(qc, backend=device, shots=nshots); print(job.job_id()) job = device.retrieve_job('cmjn66rffjhg0084we5g') plot_histogram(job.result().get_counts()) qc = QuantumCircuit(2,2) qc.x(0); qc.h(0); qc.cx(0,1) # prepara |Phi-> qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB job = execute(qc, backend=device, shots=nshots); print(job.job_id()) job = device.retrieve_job('cmjn6wk6n5g0008xpgg0') plot_histogram(job.result().get_counts()) provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') qc = QuantumCircuit(2,2) qc.x([0,1]); qc.h(0); qc.cx(0,1) # prepara |Psi-> qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB job = execute(qc, backend=device, shots=nshots); print(job.job_id()) job = device.retrieve_job('cmjnb9nz44x0008bwa3g'); plot_histogram(job.result().get_counts()) def qc_psi(th,ph,lb): # prepara o estado a ser teletransportado from qiskit import QuantumCircuit qc = QuantumCircuit(1, name=r'$|\psi\rangle$'); qc.x(0); qc.u(th,ph,lb, 0) return qc qc_psi_ = qc_psi(0.1,0.2,0.3); qc_psi_.draw('mpl') from qiskit.quantum_info import random_statevector for j in range(0,6): psi = random_statevector(2) print(psi) def angulos(psi): # psi = [c0,c1] c0_abs = math.sqrt(psi[0].real**2 + psi[0].imag**2); c1_abs = math.sqrt(psi[1].real**2 + psi[1].imag**2) ph0 = math.acos(psi[0].real/c0_abs); ph1 = math.acos(psi[1].real/c1_abs) th = 2*math.acos(c1_abs) lb = ph0 - math.pi; ph = ph1 - lb return th, ph, lb # existem erros de sinal! import math; import numpy as np for j in range(0,3): psi = random_statevector(2); print('rand = ',psi); th, ph, lb = angulos(psi) psin = np.array([(math.cos(math.pi+lb)+1j*math.sin(math.pi+lb))*math.sin(th/2), (math.cos(ph+lb)+1j*math.sin(ph+lb))*math.cos(th/2)]) print('new = ',psin) # existem erros de sinal! def acosm(x): # solução do chagpt não funciona angle = math.acos(x) if x >= 0: return angle else: return 2*math.pi - angle import math; import numpy as np thmax = 2*math.pi; npt = 10; dth = thmax/npt; th = np.arange(0,thmax+dth,dth) for j in range(0,len(th)): cs = math.cos(th[j]); acs = math.acos(cs); nacs = acosm(cs) print('th=',th[j],', acs=',acs,', nacs=',nacs) # não funcionam for j in range(0,len(th)): tg = math.tan(th[j]); atg = math.atan(tg); sn = math.sin(th[j]); asn = math.asin(sn) print('th=', th[j], ', atg=', atg,', asn=', asn) # também não funcionam # As funções anteriores não funcionam pois o mapa é 2 pra 1 # Essa função retorna o ângulo cert0, fornecidos os valores (seno,cosseno) def arc_fun(cs, sn): if sn >= 0: return math.acos(cs) if sn < 0: return 2*math.pi - math.acos(cs) for j in range(0,len(th)): cs = math.cos(th[j]); sn = math.sin(th[j]) print('th=', th[j], ', nth=', arc_fun(cs, sn)) def angulosn(psi): # psi = [c0,c1] c0_abs = math.sqrt(psi[0].real**2 + psi[0].imag**2); c1_abs = math.sqrt(psi[1].real**2 + psi[1].imag**2) ph0 = arc_fun(psi[0].real/c0_abs, psi[0].imag/c0_abs); ph1 = arc_fun(psi[1].real/c1_abs, psi[1].imag/c1_abs) th = 2*arc_fun(c1_abs,c0_abs) lb = ph0 - math.pi; ph = ph1 - lb return th, ph, lb import math; import numpy as np for j in range(0,5): psi = random_statevector(2); print('rand = ',psi); th, ph, lb = angulosn(psi) psin = np.array([(math.cos(math.pi+lb)+1j*math.sin(math.pi+lb))*math.sin(th/2), (math.cos(ph+lb)+1j*math.sin(ph+lb))*math.cos(th/2)]) print('new = ',psin) # Agora está certo ... from qiskit import * def qc_teleport(th,ph,lb): qc = QuantumCircuit(3,2, name='tel') qc_psi_ = qc_psi(th,ph,lb); qc.append(qc_psi_, [0]); qc.barrier() qc.h(2); qc.cx(2,1); qc.barrier() qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]); qc.barrier() qc.x(2).c_if(1, 1); qc.z(2).c_if(0, 1) # oprações condicionadas em info clássica return qc qc_teleport_ = qc_teleport(0.1,0.2,0.3); qc_teleport_.draw('mpl') import qiskit; import math; import numpy as np; from qiskit import Aer, QuantumCircuit, execute from qiskit.quantum_info import state_fidelity from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter simulator = Aer.get_backend('qasm_simulator') nshots = 2**13; qc = QuantumCircuit(3) psi = np.array([1/math.sqrt(2),1/math.sqrt(2)]); th,ph,lb=angulosn(psi) # estado a ser teletransportado qc_teleport_ = qc_teleport(th,ph,lb); qc.append(qc_teleport_, [0,1,2]) qstc = state_tomography_circuits(qc_teleport_, [2]) job = execute(qstc, backend = simulator, shots = nshots) qstf = StateTomographyFitter(job.result(), qstc) rho_sim = qstf.fit(method='lstsq') F = state_fidelity(rho_sim, psi); from sympy import Matrix rho_teo = Matrix([[1/2,1/2],[1/2,1/2]]); print('rho_teo = ',rho_teo); print('rho_sim =',rho_sim); print('F = ', F) import qiskit qiskit.IBMQ.save_account('7ec48a29167ab443c525564bd84b033895cf87b6c6da8d263be59ad00a2d9e70718cf1398362403ace62320d0044793f08dbaa2629bfde7f6ec339f90fe74e7b', overwrite = True) qiskit.IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibm_nairobi') qc = QuantumCircuit(3) psi = np.array([1/math.sqrt(2),1/math.sqrt(2)]) th,ph,lb=angulosn(psi) qc_teleport_ = qc_teleport(th,ph,lb) qc.append(qc_teleport_, [0,1,2]) qstc = state_tomography_circuits(qc_teleport_, [2]) job = execute(qstc, backend = device, shots = nshots) jobid = job.job_id() print(jobid) def qc_teleport_coe(th,ph,lb): from qiskit import QuantumCircuit qc = QuantumCircuit(3, name='tel') qc_psi_ = qc_psi(th,ph,lb); qc.append(qc_psi_, [0]); qc.barrier() qc.h(2); qc.cx(2,1); qc.barrier(); qc.cx(0,1); qc.h(0); qc.barrier() qc.cx(1,2); qc.cz(0,2) # oprações quânticas controladas return qc qc_teleport_coe_ = qc_teleport_coe(0.1,0.2,0.3); qc_teleport_coe_.draw('mpl') import qiskit; import math; import numpy as np from qiskit import Aer, QuantumCircuit, execute from qiskit.quantum_info import state_fidelity from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13; qc = QuantumCircuit(3) psi = np.array([1/math.sqrt(2),(1/math.sqrt(2))*1j]); th,ph,lb=angulosn(psi) qc_teleport_coe_ = qc_teleport_coe(th,ph,lb); qc.append(qc_teleport_coe_, [0,1,2]) qstc = state_tomography_circuits(qc_teleport_coe_, [2]) job = qiskit.execute(qstc, backend = simulator, shots = nshots) qstf = StateTomographyFitter(job.result(), qstc) rho_sim = qstf.fit(method='lstsq') F = state_fidelity(rho_sim, psi) from sympy import Matrix,sqrt; rho = Matrix([[1/2,-1j/2],[1j/2,1/2]]); print('rho_teo =',rho) print('rho_sim =',rho_sim); print('F = ', F) import qiskit qiskit.IBMQ.save_account('585d2242bad08223e0d894363adf8e4f76b1d426a84e85b2fbd51678adcb8e54e39cf0f33ff6c84c41e60a534a61ad4775091a01e338f0f9eff2265aa59a6a19', overwrite = True); qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') qc = QuantumCircuit(3) psi = np.array([1/math.sqrt(2),(1/math.sqrt(2))*1j]) th,ph,lb=angulosn(psi) qc_teleport_coe_ = qc_teleport_coe(th,ph,lb) qc.append(qc_teleport_coe_, [0,1,2]) qstc = state_tomography_circuits(qc_teleport_coe_, [2]) job = execute(qstc, backend = device, shots = nshots) jobid = job.job_id() print(jobid) provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibm_nairobi') job = device.retrieve_job('cmke9bn8tsq00080987g') qstf = StateTomographyFitter(job.result(), qstc) rho_exp = qstf.fit(method='lstsq') psi = np.array([1/math.sqrt(2),(1/math.sqrt(2))*1j]) from sympy import Matrix, sqrt rho = Matrix([[0.5,-0.5*1j],[0.5*1j,0.5]]) print('rho_teo =',rho) F = state_fidelity(psi, rho_exp) print('rho_exp = ',rho_exp,', F = ', F) import qiskit; import math; import numpy as np from qiskit import Aer, QuantumCircuit, execute from qiskit.quantum_info import state_fidelity from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13 for j in range(0,13): qc = QuantumCircuit(3) psi = random_statevector(2); th,ph,lb = angulosn(psi)#; print('psi=',psi) qc_teleport_coe_ = qc_teleport_coe(th,ph,lb); qc.append(qc_teleport_coe_, [0,1,2]) qstc = state_tomography_circuits(qc_teleport_coe_, [2]) job = qiskit.execute(qstc, backend=simulator, shots=nshots) qstf = StateTomographyFitter(job.result(), qstc); rho_sim = qstf.fit(method='lstsq') F = state_fidelity(rho_sim, psi); print('F=', F)
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
jonasmaziero
def qc_alice_encoding(cb): from qiskit import QuantumCircuit qc = QuantumCircuit(1, name='AE') if cb == '00': qc.id(0) elif cb == '01': qc.x(0) elif cb == '10': qc.z(0) elif cb == '11': qc.x(0); qc.z(0) return qc cb = '11' qcae = qc_alice_encoding(cb) qcae.draw('mpl') from qiskit import QuantumCircuit # só pra mostrar o circuito quântico qc = QuantumCircuit(2,2) qc.h(0) qc.cx(0,1) qc.barrier() qcae = qc_alice_encoding(cb) qc.append(qcae, [0]) qc.barrier() qc.cx(0,1) qc.h(0) qc.measure([0,1],[0,1]) qc.draw('mpl') def qc_dense_coding(cb): from qiskit import QuantumCircuit qc = QuantumCircuit(2, name='DC') qc.h(0); qc.cx(0,1) # compartilha o par emaranhado qcae = qc_alice_encoding(cb); qc.append(qcae, [0]) # codificação da Alice qc.cx(0,1); qc.h(0)#; qc.measure([0,1],[0,1]) # decodificação, medida na BB, do Bob # OBS. Não consegui incluir um subcircuito que contenha medidas return qc from qiskit import QuantumCircuit qc = QuantumCircuit(2,2) qcdc = qc_dense_coding('00') qc.append(qcdc, [0,1]) qc.draw('mpl') from qiskit import Aer, execute, QuantumCircuit; simulator = Aer.get_backend('qasm_simulator') nshots = 2**13; from qiskit import QuantumCircuit qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('00'); qc.append(qcdc, [0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots); counts = job.result().get_counts() from qiskit.tools.visualization import plot_histogram; plot_histogram(counts) from qiskit import Aer, execute, QuantumCircuit simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 from qiskit import QuantumCircuit qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('01'); qc.append(qcdc, [0,1]) qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots); counts = job.result().get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(counts) from qiskit import Aer, execute, QuantumCircuit simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 from qiskit import QuantumCircuit qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('10'); qc.append(qcdc, [0,1]) qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots); counts = job.result().get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(counts) from qiskit import Aer, execute, QuantumCircuit simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 from qiskit import QuantumCircuit qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('11'); qc.append(qcdc, [0,1]) qc.measure([0,1],[0,1]) job = execute(qc, backend=simulator, shots=nshots); counts = job.result().get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(counts) import qiskit qiskit.IBMQ.save_account('72f5d1e3769658b4908c384492eb3a9bd6d6ac4ab1fdf613d7fbe72884114d62728d6fd60a8bf8d0b6698f2f5463a605742658fee1ce3318181105c6acb8120e', overwrite = True) qiskit.IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') from qiskit import QuantumCircuit, execute device = provider.get_backend('ibm_nairobi') nshots = 2**13 qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('00'); qc.append(qcdc, [0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots); jobid = job.job_id(); print(jobid) job = device.retrieve_job('cmj6f1m0t6t00085y6r0') from qiskit.tools.visualization import plot_histogram; plot_histogram(job.result().get_counts()) from qiskit import QuantumCircuit, execute device = provider.get_backend('ibm_nairobi') nshots = 2**13 qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('01'); qc.append(qcdc, [0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots); jobid = job.job_id(); print(jobid) job = device.retrieve_job('cmj6f7c0t6t00085y6rg') plot_histogram(job.result().get_counts()) from qiskit import QuantumCircuit, execute device = provider.get_backend('ibm_nairobi') nshots = 2**13 qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('10'); qc.append(qcdc, [0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots); jobid = job.job_id(); print(jobid) job = device.retrieve_job('cmj6f9nstv5g008dwdb0') plot_histogram(job.result().get_counts()) #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') from qiskit import QuantumCircuit, execute; device = provider.get_backend('ibm_nairobi'); nshots = 2**13 qc = QuantumCircuit(2,2); qcdc = qc_dense_coding('11'); qc.append(qcdc, [0,1]); qc.measure([0,1],[0,1]) job = execute(qc, backend=device, shots=nshots); jobid = job.job_id(); print(jobid) job = device.retrieve_job('cmj6g3g0t6t00085y6sg') plot_histogram(job.result().get_counts()) import qiskit qiskit.IBMQ.save_account('e20d3045c7c23a3be753606794714e9b47d4331ec46a41b2281e2d601bae27b2b3c1baa0b5cb54f3282a8b5248e552b14c9c556699010660fb94b11d00ff1073', overwrite = True) qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') nshots = 2**13 from qiskit import QuantumRegister, execute from qiskit.ignis.mitigation.measurement import complete_meas_cal qr_ = QuantumRegister(2) qubit_list_ = [0, 1] # qubits para os quais aplicaremos calibracao de medidas meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list_, qr = qr_) meas_calibs # circuitos que serão executados para mitigação dos erros state_labels # estados que serão preparados/medidos/corrigidos job = execute(meas_calibs, backend=device, shots=nshots) print(job.job_id()) from qiskit.ignis.mitigation.measurement import CompleteMeasFitter job = device.retrieve_job('cmm4vmyrcq000080ceqg') cal_results = job.result() # função que usaremos para corrigir resultados experimentais meas_fitter = CompleteMeasFitter(cal_results, state_labels) # OBS. Uma vez feito isso para um chip e para uns certos qubits, depois é só usar job = device.retrieve_job('cmj6f1m0t6t00085y6r0') # dados do experimento da codificação densa para '00' unmitigated_counts = job.result().get_counts() mitigated_results = meas_fitter.filter.apply(job.result()) # corrige os resultados usando mitigação mitigated_counts = mitigated_results.get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram([unmitigated_counts, mitigated_counts], legend=['sem mit', 'com mit']) def prob_erro(counts, target, nshots): # Calcula a probabilidade de erro if target in counts: pacerto = counts[target]/nshots perro = 1 - pacerto return perro print('Probabilidade de erro SEM mitigação: ',prob_erro(unmitigated_counts, '00', nshots)) print('Probabilidade de erro COM mitigação: ',prob_erro(mitigated_counts, '00',nshots)) job = device.retrieve_job('cmj6f7c0t6t00085y6rg') # dados do experimento da codificação densa para '01' unmitigated_counts = job.result().get_counts() mitigated_results = meas_fitter.filter.apply(job.result()) # corrige os resultados usando mitigação mitigated_counts = mitigated_results.get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram([unmitigated_counts, mitigated_counts], legend=['sem mit', 'com mit']) print('Probabilidade de erro SEM mitigação: ',prob_erro(unmitigated_counts, '10', nshots)) print('Probabilidade de erro COM mitigação: ',prob_erro(mitigated_counts, '10',nshots)) job = device.retrieve_job('cmj6f9nstv5g008dwdb0'); unmitigated_counts = job.result().get_counts() mitigated_results = meas_fitter.filter.apply(job.result()) # corrige os resultados usando mitigação mitigated_counts = mitigated_results.get_counts(); from qiskit.tools.visualization import plot_histogram plot_histogram([unmitigated_counts, mitigated_counts], legend=['sem mit', 'com mit']) print('Probabilidade de erro SEM mitigação: ',prob_erro(unmitigated_counts, '01', nshots)) print('Probabilidade de erro COM mitigação: ',prob_erro(mitigated_counts, '01',nshots)) job = device.retrieve_job('cmj6g3g0t6t00085y6sg') # dados do experimento da codificação densa para '11' unmitigated_counts = job.result().get_counts(); mitigated_results = meas_fitter.filter.apply(job.result()) mitigated_counts = mitigated_results.get_counts(); from qiskit.tools.visualization import plot_histogram plot_histogram([unmitigated_counts, mitigated_counts], legend=['sem mit', 'com mit']) print('Probabilidade de erro SEM mitigação: ',prob_erro(unmitigated_counts, '11', nshots)) print('Probabilidade de erro COM mitigação: ',prob_erro(mitigated_counts, '11',nshots)) def qc_Eswap(): from qiskit import QuantumCircuit qc = QuantumCircuit(4, name='Eswap') qc.h([0,3]); qc.cx(0,1); qc.cx(3,2) # cria os pares emaranhados qc.barrier() qc.cx(1,2); qc.h(1) # muda da base computacional para a base de Bell qc.barrier() qc.cx(2,3); qc.cz(1,3) # envia a informação 'clássica' return qc qces = qc_Eswap(); qces.draw('mpl') from qiskit import Aer, QuantumCircuit; import qiskit from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.visualization import plot_state_city simulator = Aer.get_backend('qasm_simulator'); qc = QuantumCircuit(4); qces = qc_Eswap(); qc.append(qces, [0,1,2,3]) qstc = state_tomography_circuits(qc, [0,3]); job = execute(qstc, backend=simulator, shots=nshots) qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq'); plot_state_city(rho) from qiskit.quantum_info import state_fidelity F = state_fidelity(rho,Phip); print('F = ',F) import qiskit qiskit.IBMQ.save_account('72f5d1e3769658b4908c384492eb3a9bd6d6ac4ab1fdf613d7fbe72884114d62728d6fd60a8bf8d0b6698f2f5463a605742658fee1ce3318181105c6acb8120e', overwrite = True) qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') nshots = 2**13 from qiskit import QuantumCircuit, execute qc = QuantumCircuit(4); qces = qc_Eswap(); qc.append(qces, [0,1,2,3]) qstc = state_tomography_circuits(qc, [0,3]) job = execute(qstc, backend=device, shots=nshots) jobid = job.job_id(); print(jobid) job = device.retrieve_job('cmjp9zf5mym0008dvmzg') qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq') from qiskit.visualization import plot_state_city; plot_state_city(rho) rho import math; import numpy as np Phip = np.array([1/math.sqrt(2),0,0,1/math.sqrt(2)]); Phip from qiskit.quantum_info import state_fidelity F = state_fidelity(rho,Phip); print('F = ',F) import qiskit qiskit.IBMQ.save_account('dabd4674f7b3794f740813fec0c5478bfefdebb7d1dca9b7acd41e3f90ed2c8a8b80af26fb3236289fbfc70d0ea334829a836453ac46f96fee68abcb22495ef4', overwrite = True) qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') nshots = 2**13 from qiskit import QuantumRegister, execute from qiskit.ignis.mitigation.measurement import complete_meas_cal qr = QuantumRegister(4) qubit_list = [0, 3] meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr) job = execute(meas_calibs, backend=device, shots=nshots) print(job.job_id()) from qiskit.ignis.mitigation.measurement import CompleteMeasFitter job = device.retrieve_job('cmr2snercp70008sfsw0') cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels) from qiskit import QuantumCircuit, execute qc = QuantumCircuit(4); qces = qc_Eswap(); qc.append(qces, [0,1,2,3]) from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter qstc = state_tomography_circuits(qc, [0,3]) job = device.retrieve_job('cmjp9zf5mym0008dvmzg') mitigated_results = meas_fitter.filter.apply(job.result()) qstf = StateTomographyFitter(mitigated_results, qstc) rho = qstf.fit(method='lstsq') from qiskit.visualization import plot_state_city; plot_state_city(rho) import numpy as np import math from qiskit.quantum_info import state_fidelity Phip = np.array([1/math.sqrt(2),0,0,1/math.sqrt(2)]) F = state_fidelity(rho,Phip) print('F = ',F)
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
jonasmaziero
import math; import numpy as np; phmax = 4*math.pi; npt = 100; dth = phmax/npt; ph = np.arange(0,phmax+dth,dth) from matplotlib import pyplot as plt; PrD0 = 0.5*(1+np.cos(ph)); plt.plot(ph,PrD0, label=r'$Pr(D_0)$') PrD0 = 0.5*(1-np.cos(ph)); plt.plot(ph,PrD0, label=r'$Pr(D_1)$'); plt.legend(); plt.xlabel(r'$\phi$'); plt.show() from sympy import Matrix, sqrt S = Matrix([[1,0],[0,1j]]); H = (1/sqrt(2))*Matrix([[1,1],[1,-1]]) S*H*S Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]]); Y*Z from qiskit import QuantumCircuit def qc_df(): # divisor de feixes 50:50 qc = QuantumCircuit(1, name='DF') qc.s(0) qc.h(0) qc.s(0) return qc qcdf = qc_df(); qcdf.draw('mpl') def qc_espelhos(): qc = QuantumCircuit(1, name='E') qc.z(0) qc.y(0) return qc qce = qc_espelhos(); qce.draw('mpl') def qc_imz(ph): # retorna o circuito quântico para o IMZ (sem as medidas) qc = QuantumCircuit(1, name='IMZ') qcdf = qc_df(); qc.append(qcdf, [0]) qce = qc_espelhos(); qc.append(qce, [0]) qc.p(ph, [0]) qcdf = qc_df(); qc.append(qcdf, [0]) return qc qcimz = qc_imz(0); qcimz.draw('mpl') # Simulação clássica from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 import numpy as np; import math phmax = 2*math.pi npe = 6 dth = phmax/npe ph = np.arange(0,phmax+dth,dth) PD0sim = np.zeros(len(ph)) for j in range(0,len(ph)): qc = QuantumCircuit(1,1) qcimz = qc_imz(ph[j]) qc.append(qcimz,[0]) qc.measure(0,0) job = execute(qc, backend=simulator, shots=nshots) counts = job.result().get_counts() if '0' in counts: PD0sim[j] = counts['0']/nshots print(PD0sim) npt = 100 dtht = phmax/npt pht = np.arange(0,phmax+dtht,dtht) PD0teo = 0.5*(1+np.cos(pht)) from matplotlib import pyplot as plt plt.plot(pht,PD0teo, label=r'$Pr(D_0)_{teo}$') plt.plot(ph,PD0sim, 'o', label=r'$Pr(D_0)_{sim}$') plt.legend(); plt.xlabel(r'$\phi$') plt.show() import qiskit qiskit.IBMQ.save_account('a221013b3d88dd070a495178c3f732ac683a494e5af4e641383f16d361e9fa7fa22af7f09cad3f88988a3e6e5621c7fe951d8ca6ff0c0371422b211ec0ae9709', overwrite = True) qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') nshots = 2**13 import numpy as np; import math phmax = 2*math.pi npe = 6 dth = phmax/npe ph = np.arange(0,phmax+dth,dth) job_ids = [] for j in range(0,len(ph)): qc = QuantumCircuit(1,1) qcimz = qc_imz(ph[j]) qc.append(qcimz,[0]) qc.measure(0,0) job = execute(qc, backend=device, shots=nshots) jobid = job.job_id() job_ids.append(jobid) print(jobid) f = open("jobs_ids_IMZ.txt", "w") f.write(str(job_ids)) f.close() device = provider.get_backend('ibm_nairobi') f = open("jobs_ids_IMZ.txt","r") list_ids_IMZ = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",") f.close() PD0exp = np.zeros(len(ph)) for j in range(0,len(ph)): job = device.retrieve_job(list_ids_IMZ[j]) counts = job.result().get_counts() if '0' in counts: PD0exp[j] = counts['0']/nshots print(PD0exp) npt = 100; dtht = phmax/npt; pht = np.arange(0,phmax+dtht,dtht) PD0teo = 0.5*(1+np.cos(pht)) from matplotlib import pyplot as plt plt.plot(pht,PD0teo, label=r'$Pr(D_0)_{teo}$') plt.plot(ph,PD0sim, 'o', label=r'$Pr(D_0)_{sim}$') plt.plot(ph,PD0exp, '*', label=r'$Pr(D_0)_{exp}$') plt.legend() plt.xlabel(r'$\phi$') plt.show() Vsim = (np.max(PD0sim)-np.min(PD0sim))/(np.max(PD0sim)+np.min(PD0sim)); print('Vsim = ',Vsim) Vexp = (np.max(PD0exp)-np.min(PD0exp))/(np.max(PD0exp)+np.min(PD0exp)); print('Vexp = ',Vexp) from sympy import Matrix, eye; P0 = Matrix([[1,0],[0,0]]); P1 = Matrix([[0,0],[0,1]]); X = Matrix([[0,1],[1,0]]) from sympy.physics.quantum import TensorProduct as tp; tp(eye(2),P0) + tp(X,P1) def qc_bbo(): from qiskit import QuantumCircuit qc = QuantumCircuit(2, name='BBO') qc.x(1) qc.h(0) qc.cx(0,1) return qc qcbbo = qc_bbo(); qcbbo.draw('mpl') def qc_dfp(): from qiskit import QuantumCircuit qc = QuantumCircuit(2, name='DFP') qc.cz(0,1) qc.cy(0,1) return qc qcdfp = qc_dfp() qcdfp.draw('mpl') def qc_pmo(): from qiskit import QuantumCircuit qc = QuantumCircuit(2, name='PMO') qc.cx(1,0) return qc qcpmo = qc_pmo() qcpmo.draw('mpl') def qc_imz_ic(ph): # não consideramos o caminho do fóton A from qiskit import QuantumCircuit qc = QuantumCircuit(3, name='IMZIC') qcbbo = qc_bbo(); qc.append(qcbbo, [0,1]) qcdfp = qc_dfp(); qc.append(qcdfp, [1,2]) qcpmo = qc_pmo(); qc.append(qcpmo, [1,2]) qce = qc_espelhos(); qc.append(qce, [2]) qc.p(ph, [2]) qcdf = qc_df(); qc.append(qcdf, [2]) return qc qcimzic = qc_imz_ic(0); qcimzic.draw('mpl') qcimzic.decompose().draw('mpl') qcimzic.decompose().decompose().decompose().draw('mpl') # Simulação clássica from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 import numpy as np; import math phmax = 2*math.pi npe = 5 dth = phmax/npe ph = np.arange(0,phmax+dth,dth) PD0sim = np.zeros(len(ph)) for j in range(0,len(ph)): qc = QuantumCircuit(3,2) qcimzic = qc_imz_ic(ph[j]) qc.append(qcimzic,[0,1,2]) qc.measure([0,2],[0,1]) job = execute(qc, backend=simulator, shots=nshots) counts = job.result().get_counts() if '00' in counts: PD0sim[j] = counts['00']/nshots if '10' in counts: PD0sim[j] += counts['10']/nshots print(PD0sim) qc.draw('mpl') import numpy as np; import math phmax = 2*math.pi; npt = 100; dpht = phmax/npt pht = np.arange(0,phmax+dtht,dtht) PD0teo = 0.5*np.ones(len(pht)) from matplotlib import pyplot as plt plt.plot(pht,PD0teo, label=r'$Pr(D_0)_{teo}$') plt.plot(ph,PD0sim, 'o', label=r'$Pr(D_0)_{sim}$') plt.ylim(0,1); plt.legend() plt.xlabel(r'$\phi$') plt.show() import qiskit qiskit.IBMQ.save_account('e20d3045c7c23a3be753606794714e9b47d4331ec46a41b2281e2d601bae27b2b3c1baa0b5cb54f3282a8b5248e552b14c9c556699010660fb94b11d00ff1073', overwrite = True) qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') nshots = 2**13 import numpy as np; import math phmax=2*math.pi npe=5 dth=phmax/npe ph=np.arange(0,phmax+dth,dth) job_ids=[] for j in range(0,len(ph)): qc = QuantumCircuit(3,2) qcimzic = qc_imz_ic(ph[j]) qc.append(qcimzic,[0,1,2]) qc.measure([0,2],[0,1]) job = execute(qc, backend=device, shots=nshots) jobid = job.job_id() job_ids.append(jobid) f = open("jobs_ids_IMZIC.txt", "w") f.write(str(job_ids)) f.close() print(job_ids) f = open("jobs_ids_IMZIC.txt","r") list_ids_IMZIC = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",") f.close() phmax = 2*math.pi npe=5 dth = phmax/npe ph = np.arange(0,phmax+dth,dth) PD0exp = np.zeros(len(ph)) device = provider.get_backend('ibm_nairobi') for j in range(0,len(ph)): job = device.retrieve_job(list_ids_IMZIC[j]) counts = job.result().get_counts() if '00' in counts: PD0exp[j] = counts['00']/nshots if '10' in counts: PD0exp[j] += counts['10']/nshots print(PD0exp) import numpy as np; import math phmax = 2*math.pi; npt = 100; dpht = phmax/npt pht = np.arange(0,phmax+dtht,dtht) PD0teo = 0.5*np.ones(len(pht)) from matplotlib import pyplot as plt plt.plot(pht,PD0teo, label=r'$Pr(D_0)_{teo}$') plt.plot(ph,PD0sim, 'o', label=r'$Pr(D_0)_{sim}$') plt.plot(ph,PD0exp, '*', label=r'$Pr(D_0)_{exp}$') plt.ylim(0,1); plt.legend(); plt.xlabel(r'$\phi$'); plt.show() Vsim = (np.max(PD0sim)-np.min(PD0sim))/(np.max(PD0sim)+np.min(PD0sim)); print('Vsim = ',Vsim) Vexp = (np.max(PD0exp)-np.min(PD0exp))/(np.max(PD0exp)+np.min(PD0exp)); print('Vexp = ',Vexp) import numpy as np; import math; phmax = 2*math.pi; npt = 100; dpht = phmax/npt; pht = np.arange(0,phmax+dpht,dpht) PD0teoA0 = 0.5*(1+np.cos(pht)); PD0teoA1 = 0.5*(1-np.cos(pht)) from matplotlib import pyplot as plt plt.plot(pht,PD0teoA0, label=r'$Pr(D_0|A=0)_{teo}$'); plt.plot(pht,PD0teoA1, label=r'$Pr(D_0|A=1)_{teo}$') plt.xlim(0,2*math.pi); plt.xlim(-0.1,phmax+0.1); plt.ylim(-0.01,1.01); plt.legend(); plt.xlabel(r'$\phi$'); plt.show() def qc_pqo(): from qiskit import QuantumCircuit qc = QuantumCircuit(1, name='PQO') qc.h(0) qc.s(0) return qc qcpqo = qc_pqo() qcpqo.draw('mpl') def qc_apagadorQ(ph): from qiskit import QuantumCircuit qc = QuantumCircuit(3) qcimzic = qc_imz_ic(ph) qc.append(qcimzic, [0,1,2]) qcpqo = qc_pqo() qc.append(qcpqo, [0]) return qc qcaq = qc_apagadorQ(0) qcaq.decompose().draw('mpl') # Simulação clássica from qiskit import Aer, execute; simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13 import numpy as np; import math; phmax = 2*math.pi; npe = 6; dth = phmax/npe; ph = np.arange(0,phmax+dth,dth) PA0sim = np.zeros(len(ph)); PA1sim = np.zeros(len(ph)); PD0A0sim = np.zeros(len(ph)); PD0A1sim = np.zeros(len(ph)) for j in range(0,len(ph)): qc = QuantumCircuit(3,2) qcaq = qc_apagadorQ(ph[j]) qc.append(qcaq,[0,1,2]) qc.measure([0,2],[0,1]) job = execute(qc, backend=simulator, shots=nshots) counts = job.result().get_counts() if '00' in counts: PA0sim[j] = counts['00']/nshots if '01' in counts: PA0sim[j] += counts['01']/nshots if '10' in counts: PA1sim[j] = counts['10']/nshots if '11' in counts: PA1sim[j] += counts['11']/nshots if PA0sim[j] != 0 and '00' in counts: PD0A0sim[j] = (counts['00']/nshots)/PA0sim[j] if PA1sim[j] != 0 and '10' in counts: PD0A1sim[j] = (counts['10']/nshots)/PA1sim[j] print(PD0A0sim, PD0A1sim) import numpy as np; import math phmax = 2*math.pi; npt = 100; dpht = phmax/npt; pht = np.arange(0,phmax+dpht,dpht) PD0teoA0 = 0.5*(1+np.cos(pht)); PD0teoA1 = 0.5*(1-np.cos(pht)) from matplotlib import pyplot as plt plt.plot(pht,PD0teoA0, label=r'$Pr(D_0|A=0)_{teo}$') plt.plot(pht,PD0teoA1, label=r'$Pr(D_0|A=1)_{teo}$') plt.plot(ph,PD0A0sim, 'o', label=r'$Pr(D_0|A=0)_{sim}$') plt.plot(ph,PD0A1sim, 's', label=r'$Pr(D_0|A=1)_{sim}$') plt.xlim(-0.1,2*math.pi+0.1); plt.ylim(-0.01,1.02); plt.legend(); plt.xlabel(r'$\phi$'); plt.show() import qiskit qiskit.IBMQ.save_account('dabd4674f7b3794f740813fec0c5478bfefdebb7d1dca9b7acd41e3f90ed2c8a8b80af26fb3236289fbfc70d0ea334829a836453ac46f96fee68abcb22495ef4', overwrite = True) qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') nshots = 2**13 import numpy as np; import math phmax=2*math.pi npe=6 dth=phmax/npe ph=np.arange(0,phmax+dth,dth) job_ids=[] for j in range(0,len(ph)): qc = QuantumCircuit(3,2) qcaq = qc_apagadorQ(ph[j]) qc.append(qcaq,[0,1,2]) qc.measure([0,2],[0,1]) job = execute(qc, backend=device, shots=nshots) jobid = job.job_id() job_ids.append(jobid) print(jobid) f = open("jobs_ids_apagador.txt", "w") f.write(str(job_ids)) f.close() f = open("jobs_ids_apagador.txt","r") list_ids_apagador = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",") f.close() phmax = 2*math.pi; npe=6; dth = phmax/npe; ph = np.arange(0,phmax+dth,dth) PD0A0exp = np.zeros(len(ph)); PD0A1exp = np.zeros(len(ph)); PA0exp = np.zeros(len(ph)); PA1exp = np.zeros(len(ph)) device = provider.get_backend('ibm_nairobi') for j in range(0,len(ph)): job = device.retrieve_job(list_ids_apagador[j]) counts = job.result().get_counts() if '00' in counts: PA0exp[j] = counts['00']/nshots if '01' in counts: PA0exp[j] += counts['01']/nshots if '10' in counts: PA1exp[j] = counts['10']/nshots if '11' in counts: PA1exp[j] += counts['11']/nshots if PA0exp[j] != 0 and '00' in counts: PD0A0exp[j] = (counts['00']/nshots)/PA0exp[j] if PA1exp[j] != 0 and '10' in counts: PD0A1exp[j] = (counts['10']/nshots)/PA1exp[j] print(PD0A0exp,PD0A1exp) import numpy as np; import math phmax = 2*math.pi; npt = 100; dpht = phmax/npt pht = np.arange(0,phmax+dpht,dpht) PD0teoA0 = 0.5*(1+np.cos(pht)); PD0teoA1 = 0.5*(1-np.cos(pht)) from matplotlib import pyplot as plt plt.plot(pht,PD0teoA0, label=r'$Pr(D_0|A=0)_{teo}$'); plt.plot(pht,PD0teoA1, label=r'$Pr(D_0|A=1)_{teo}$') plt.plot(ph,PD0A0sim, 'o', label=r'$Pr(D_0|A=0)_{sim}$'); plt.plot(ph,PD0A1sim, 's', label=r'$Pr(D_0|A=1)_{sim}$') plt.plot(ph,PD0A0exp, '*', label=r'$Pr(D_0|A=0)_{exp}$'); plt.plot(ph,PD0A1exp, '+', label=r'$Pr(D_0|A=1)_{exp}$') plt.xlim(-0.1,2*math.pi+0.1); plt.ylim(-0.02,1.02); plt.legend(bbox_to_anchor=(1.4, 1.0),loc='upper right') plt.xlabel(r'$\phi$'); plt.show() VsimA0 = (np.max(PD0A0sim)-np.min(PD0A0sim))/(np.max(PD0A0sim)+np.min(PD0A0sim)) print('VsimA0 = ',VsimA0) VsimA1 = (np.max(PD0A1sim)-np.min(PD0A1sim))/(np.max(PD0A1sim)+np.min(PD0A1sim)) print('VsimA1 = ',VsimA1) VexpA0 = (np.max(PD0A0exp)-np.min(PD0A0exp))/(np.max(PD0A0exp)+np.min(PD0A0exp)) print('VexpA0 = ',VexpA0) VexpA1 = (np.max(PD0A1exp)-np.min(PD0A1exp))/(np.max(PD0A1exp)+np.min(PD0A1exp)) print('VexpA1 = ',VexpA1) import qiskit qiskit.IBMQ.save_account('e20d3045c7c23a3be753606794714e9b47d4331ec46a41b2281e2d601bae27b2b3c1baa0b5cb54f3282a8b5248e552b14c9c556699010660fb94b11d00ff1073', overwrite = True) qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') nshots = 2**13 from qiskit import QuantumRegister, execute from qiskit.ignis.mitigation.measurement import complete_meas_cal qr = QuantumRegister(3) qubit_list = [0, 2] meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr) job = execute(meas_calibs, backend=device, shots=nshots) print(job.job_id()) from qiskit.ignis.mitigation.measurement import CompleteMeasFitter job = device.retrieve_job('cmp2xzqyj8fg0080m0e0') cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels) f = open("jobs_ids_apagador.txt","r") list_ids_apagador = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",") f.close() phmax = 2*math.pi; npe=6; dth = phmax/npe; ph = np.arange(0,phmax+dth,dth) PD0A0exp_mit = np.zeros(len(ph)); PD0A1exp_mit = np.zeros(len(ph)); PA0exp_mit = np.zeros(len(ph)); PA1exp_mit = np.zeros(len(ph)) device = provider.get_backend('ibm_nairobi') for j in range(0,len(ph)): job = device.retrieve_job(list_ids_apagador[j]) mitigated_results = meas_fitter.filter.apply(job.result()) mitigated_counts = mitigated_results.get_counts() if '00' in counts: PA0exp_mit[j] = mitigated_counts['00']/nshots if '01' in counts: PA0exp_mit[j] += mitigated_counts['01']/nshots if '10' in counts: PA1exp_mit[j] = mitigated_counts['10']/nshots if '11' in counts: PA1exp_mit[j] += mitigated_counts['11']/nshots if PA0exp_mit[j] != 0 and '00' in mitigated_counts: PD0A0exp_mit[j] = (mitigated_counts['00']/nshots)/PA0exp[j] if PA1exp[j] != 0 and '10' in mitigated_counts: PD0A1exp_mit[j] = (mitigated_counts['10']/nshots)/PA1exp[j] print(PD0A0exp_mit, PD0A1exp_mit) import matplotlib; matplotlib.rcParams.update({'font.size':11}); plt.figure(figsize = (7,5), dpi = 100) import numpy as np; import math; phmax = 2*math.pi; npt = 100; dpht = phmax/npt; pht = np.arange(0,phmax+dpht,dpht) PD0teoA0 = 0.5*(1+np.cos(pht)); PD0teoA1 = 0.5*(1-np.cos(pht)); from matplotlib import pyplot as plt plt.plot(pht,PD0teoA0, label=r'$Pr(D_0|A=0)_{teo}$'); plt.plot(pht,PD0teoA1, label=r'$Pr(D_0|A=1)_{teo}$') plt.plot(ph,PD0A0sim, 'o', label=r'$Pr(D_0|A=0)_{sim}$'); plt.plot(ph,PD0A1sim, 's', label=r'$Pr(D_0|A=1)_{sim}$') plt.plot(ph,PD0A0exp, '*', label=r'$Pr(D_0|A=0)_{exp}$'); plt.plot(ph,PD0A1exp, 'v', label=r'$Pr(D_0|A=1)_{exp}$') plt.plot(ph,PD0A0exp_mit, '^', label=r'$Pr(D_0|A=0)_{expmit}$'); plt.plot(ph,PD0A1exp_mit, '+', label=r'$Pr(D_0|A=1)_{expmit}$') plt.xlim(-0.1,2*math.pi+0.1); plt.ylim(-0.03,1.03); plt.legend(bbox_to_anchor=(1.4, 1.0),loc='upper right') plt.xlabel(r'$\phi$'); plt.show() VsimA0 = (np.max(PD0A0sim)-np.min(PD0A0sim))/(np.max(PD0A0sim)+np.min(PD0A0sim)); print('VsimA0 = ',VsimA0) VsimA1 = (np.max(PD0A1sim)-np.min(PD0A1sim))/(np.max(PD0A1sim)+np.min(PD0A1sim)); print('VsimA1 = ',VsimA1) VexpA0 = (np.max(PD0A0exp)-np.min(PD0A0exp))/(np.max(PD0A0exp)+np.min(PD0A0exp)); print('VexpA0 = ',VexpA0) VexpA1 = (np.max(PD0A1exp)-np.min(PD0A1exp))/(np.max(PD0A1exp)+np.min(PD0A1exp)); print('VexpA1 = ',VexpA1) VexpA0_mit = (np.max(PD0A0exp_mit)-np.min(PD0A0exp_mit))/(np.max(PD0A0exp_mit)+np.min(PD0A0exp_mit)) print('VexpA0_mit = ',VexpA0_mit) VexpA1_mit = (np.max(PD0A1exp_mit)-np.min(PD0A1exp_mit))/(np.max(PD0A1exp_mit)+np.min(PD0A1exp_mit)) print('VexpA1_mit = ',VexpA1_mit) import math; import numpy as np al_max = math.pi/4; npt = 100; dalt = al_max/npt alt = np.arange(0,al_max+dalt,dalt) Vteo = np.sin(2*alt) from matplotlib import pyplot as plt plt.plot(alt,Vteo, label=r'$V_{teo}(A=0)$') plt.xlim(-0.01,al_max+0.01); plt.ylim(-0.01,1.01) plt.xlabel(r'$\alpha$'); plt.legend() plt.show() from qiskit import QuantumCircuit def qc_Psi(al): # prepara o estado parcialmente emaranhado qc = QuantumCircuit(2, name = r'$|\Psi\rangle$') qc.u(2*al,0,0, 0) qc.cx(0,1) qc.z(0) qc.x(1) return qc qcpsi = qc_Psi(0.1); qcpsi.draw('mpl') # simulação clássica from qiskit import Aer, execute; simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13 import math; import numpy as np almax = math.pi/4; npa=2; dal = almax/npa; al = np.arange(0,almax+dal,dal) phmax = 2*math.pi; npe=4; dph = phmax/npe; ph = np.arange(0,phmax+dph,dph); VA0sim = np.zeros(len(al)) for j in range(0,len(al)): PD0A0sim = np.zeros(len(ph)); PA0sim = np.zeros(len(ph)) for k in range(0,len(ph)): qc = QuantumCircuit(3,2) qcpsi = qc_Psi(al[j]); qc.append(qcpsi, [0,1]) qcdfp = qc_dfp(); qc.append(qcdfp, [1,2]); qcpmo = qc_pmo(); qc.append(qcpmo, [1,2]) qce = qc_espelhos(); qc.append(qce, [2]); qc.p(ph[k], [2]) qcdf = qc_df(); qc.append(qcdf, [2]); qcpqo = qc_pqo(); qc.append(qcpqo, [0]) qc.measure([0,2],[0,1]) job = execute(qc, backend=simulator, shots=nshots); counts = job.result().get_counts() if '00' in counts: PA0sim[k] = counts['00']/nshots if '01' in counts: PA0sim[k] += counts['01']/nshots if PA0sim[k] != 0: if '00' in counts: PD0A0sim[k] = (counts['00']/nshots)/PA0sim[k] VA0sim[j] = (np.max(PD0A0sim)-np.min(PD0A0sim))/(np.max(PD0A0sim)+np.min(PD0A0sim)) VA0sim PD0A0sim qc.draw('mpl') import math; import numpy as np al_max = math.pi/4; npt = 100; dalt = al_max/npt; alt = np.arange(0,al_max+dalt,dalt) Vteo = np.sin(2*alt) from matplotlib import pyplot as plt plt.plot(alt,Vteo, label=r'$V_{teo}(A=0)$') plt.plot(al,VA0sim, 'o', label=r'$V_{sim}(A=0)$') plt.xlim(-0.01,al_max+0.01); plt.ylim(-0.01,1.02); plt.xlabel(r'$\alpha$'); plt.legend() plt.show() # Experimento (simulação quântica) from qiskit import execute; import math; import numpy as np almax = math.pi/4; npa = 2; dal = almax/npa; al = np.arange(0,almax+dal,dal) phmax = 2*math.pi; npe=4; dph = phmax/npe; ph = np.arange(0,phmax+dph,dph) job_ids=[] for j in range(0,len(al)): for k in range(0,len(ph)): qc = QuantumCircuit(3,2); qcpsi = qc_Psi(al[j]); qc.append(qcpsi, [0,1]) qcdfp = qc_dfp(); qc.append(qcdfp, [1,2]); qcpmo = qc_pmo(); qc.append(qcpmo, [1,2]) qce = qc_espelhos(); qc.append(qce, [2]); qc.p(ph[k], [2]) qcdf = qc_df(); qc.append(qcdf, [2]); qcpqo = qc_pqo(); qc.append(qcpqo, [0]); qc.measure([0,2],[0,1]) job = execute(qc, backend=device, shots=nshots); jobid = job.job_id(); job_ids.append(jobid); print(jobid) f = open("jobs_ids_apagador_parcial.txt", "w"); f.write(str(job_ids)); f.close() f = open("jobs_ids_apagador_parcial.txt","r") list_ids_apagador_parcial = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",") f.close() import math; import numpy as np almax = math.pi/4; npa=2; dal = almax/npa; al = np.arange(0,almax+dal,dal) phmax = 2*math.pi; npe=4; dph = phmax/npe; ph = np.arange(0,phmax+dph,dph); VA0exp = np.zeros(len(al)) for j in range(0,len(al)): PD0A0exp = np.zeros(len(ph)); PA0exp = np.zeros(len(ph)) for k in range(0,len(ph)): job = device.retrieve_job(list_ids_apagador_parcial[(npe+1)*j+k]) counts = job.result().get_counts() if '00' in counts: PA0exp[k] = counts['00']/nshots if '01' in counts: PA0exp[k] += counts['01']/nshots if PA0exp[k] != 0: if '00' in counts: PD0A0exp[k] = (counts['00']/nshots)/PA0exp[k] VA0exp[j] = (np.max(PD0A0exp)-np.min(PD0A0exp))/(np.max(PD0A0exp)+np.min(PD0A0exp)) VA0exp import math; import numpy as np al_max = math.pi/4; npt = 100; dalt = al_max/npt; alt = np.arange(0,al_max+dalt,dalt); Vteo = np.sin(2*alt) from matplotlib import pyplot as plt plt.plot(alt,Vteo, label=r'$V_{teo}(A=0)$') plt.plot(al,VA0sim, 'o', label=r'$V_{sim}(A=0)$') plt.plot(al,VA0exp, '^', label=r'$V_{exp}(A=0)$') plt.xlim(-0.01,al_max+0.01); plt.ylim(-0.01,1.02); plt.xlabel(r'$\alpha$'); plt.legend() plt.show()
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
jonasmaziero
from qiskit import QuantumCircuit qc = QuantumCircuit(1,1) qc.x(0) qc.measure(0,0) qc.draw('mpl') from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 job = execute(qc, backend=simulator,shots=nshots) counts = job.result().get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(counts) from qiskit import QuantumCircuit def qc_df(): # divisor de feixes 50:50 qc = QuantumCircuit(1, name='DF') qc.s(0) qc.h(0) qc.s(0) return qc qcdf = qc_df(); qcdf.draw('mpl') def qc_espelhos(): qc = QuantumCircuit(1, name='E') qc.z(0) qc.y(0) return qc qce = qc_espelhos(); qce.draw('mpl') def qc_bomba(): qc = QuantumCircuit(2, name='B') qc.cx(0,1) return qc qcb = qc_bomba(); qcb.draw('mpl') def qc_detector_de_bomba(): qc = QuantumCircuit(2, name='DB') qcdf = qc_df(); qc.append(qcdf,[0]) qce = qc_espelhos(); qc.append(qce,[0]) qcb = qc_bomba(); qc.append(qcb,[0,1]) qcdf = qc_df(); qc.append(qcdf,[0]) return qc qcdb = qc_detector_de_bomba(); qcdb.draw('mpl') qc = QuantumCircuit(2,2) qcdb = qc_detector_de_bomba(); qc.append(qcdb,[0,1]) qc.measure([0,1],[0,1]) qc.draw('mpl') # Simulação clássica from qiskit import Aer, execute simulator = Aer.get_backend('qasm_simulator') nshots = 2**13 job = execute(qc, backend=simulator,shots=nshots) counts = job.result().get_counts() from qiskit.tools.visualization import plot_histogram plot_histogram(counts) import qiskit qiskit.IBMQ.save_account('18d1a392e10ffca595cb87ad064ca04fb8f407e702274610ba421f54ac39fbef8e14b664d350f3e48cc9762e4b63aad22ecb2135f16468825ae37b14a85c1762', overwrite = True) qiskit.IBMQ.load_account() #provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main') device = provider.get_backend('ibm_nairobi') nshots = 2**13 # Experimento (simulação quântica) job = execute(qc, backend=device, shots=nshots) print(job.job_id()) job = device.retrieve_job('cmpt4asb9x9g0088t2c0') from qiskit.tools.visualization import plot_histogram plot_histogram(job.result().get_counts())
https://github.com/GyeonghunKim/2022-Feb-Qiskit-Metal-Study
GyeonghunKim
%load_ext autoreload %autoreload 2 import numpy as np import qiskit_metal as metal from qiskit_metal import designs, draw from qiskit_metal import MetalGUI, Dict, open_docs %metal_heading Welcome to Qiskit Metal Study! # To start qiskit-metal, you have to create instance of below two. # After runing this cell, metal gui will appear. design = designs.DesignPlanar() gui = MetalGUI(design) # If you delete all components in the current design, you can use delete_all_components method. design.delete_all_components() # To apply changes in design instance to your gui, you can use rebuild method in gui. gui.rebuild() # You can import templated qubit class from qiskit_metal.qlibrary.qubits. # For transmon pocket, from qiskit_metal.qlibrary.qubits.transmon_pocket import TransmonPocket # For most simplest case, you can create TransmonPocket instance with default options as below. # Methods for creating QComponent with options will be explained in the section 2.4 # Please ignore warnings here. These are caused by Shapely's future update, and would not make any troubles now. q1 = TransmonPocket(design, 'Q1') gui.rebuild() # If you call TransmonPocket instance, you can see the parameters of it. q1 # Above options are same with TransmonPocket's default option TransmonPocket.default_options # If you want to change parameters of Transmon qubit, # you can simply change the parameters in the q1.options as below q1.options.pos_x = '2.0 mm' # Note that if you don't input the unit here, default length unit is mm not um. q1.options.pos_y = '2.0 mm' q1.options.pad_height = '250 um' q1.options.pad_width = '300 um' # By rebuilding gui, you can check the parameters are changed. gui.rebuild() # In many cases, copying QComponents is very useful. # To copy single QComponent, you can use copy_qcomponent method for design instance. q2 = design.copy_qcomponent(q1, 'Q2') # If you want to change parameters for copyed object, you can do it with two different way. # First method is same with above explained changing parameters. q2.options.pos_x = '-2.0mm' gui.rebuild() # By runing below, you can automatly scale the gui. gui.autoscale() # Second method is giving options to the copy_qcomponent as below. q3 = design.copy_qcomponent(q1, 'Q3', dict(pos_x='-4.0mm')) # If you want to copy multiple qcomponent, you can use below method. newcopies = design.copy_multiple_qcomponents([q1, q2], ['Q3', 'Q4'], [dict(pos_y='-2.0mm'), dict(pos_y='-2.0mm')]) gui.rebuild() gui.autoscale() design.delete_all_components() gui.rebuild() # To create Transmon Qubit with option, the only thing you have to do is # creating dictionary of options and give it as a input when you create TransmonPocket instance. # You can give options directly, without create dictionary as variable, like below, # Adding connection pads also can be done by add "connection_pads" in your option dictionary as below. q1 = TransmonPocket(design, 'Q1', options = dict( pos_x='-1.5mm', pos_y='+0.0mm', pad_width = '425 um', pocket_height = '650um', connection_pads = dict( a = dict(loc_W=+1,loc_H=+1), # (low_W, low_H) = (1, 1) => First Quadrant b = dict(loc_W=-1,loc_H=+1, pad_height='30um'), # (low_W, low_H) = (-1, 1) => Second Quadrant c = dict(loc_W=+1,loc_H=-1, pad_width='200um'), # (low_W, low_H) = (1, -1) => Fourth Quadrant d = dict(loc_W=-1,loc_H=-1, pad_height='50um') # (low_W, low_H) = (-1, -1) => Third Quadrant ) # Note that connection_pads have two geometrical options pad_height and pad_weight. # You can modify those values from default, by add them in option as above. ) ) gui.rebuild() design.delete_all_components() gui.rebuild() # I prefer below method, which is very convenient for reusing the parameters. optionsQ = dict( pad_width = '425 um', pocket_height = '650um', connection_pads = dict( # Qbits defined to have 4 pins a = dict(loc_W=+1,loc_H=+1), b = dict(loc_W=-1,loc_H=+1, pad_height='30um'), c = dict(loc_W=+1,loc_H=-1, pad_width='200um'), d = dict(loc_W=-1,loc_H=-1, pad_height='50um') ) ) q1 = TransmonPocket(design, 'Q1', options = dict(pos_x='-1.5mm', pos_y='+0.0mm', **optionsQ)) q2 = TransmonPocket(design, 'Q2', options = dict(pos_x='+0.35mm', pos_y='+1.0mm', orientation = '90',**optionsQ)) q3 = TransmonPocket(design, 'Q3', options = dict(pos_x='2.0mm', pos_y='+0.0mm', **optionsQ)) gui.rebuild() gui.autoscale() gui.highlight_components(['Q1', 'Q2', 'Q3']) # This is to show the pins, so we can choose what to connect gui.rebuild() gui.autoscale() # You can import RouteMeander class as below from qiskit_metal.qlibrary.tlines.meandered import RouteMeander # Same with TransmonPocket, it also have its default options RouteMeander.get_template_options(design) # Connecting two TransmonPocket with RouteMinder is very easy. # It can be done by setting start_pin and end_pin in option as below ops=dict(fillet='90um') options = Dict( total_length= '8mm', # This parameter is key parameter for changing resonant frequency hfss_wire_bonds = True, pin_inputs=Dict( start_pin=Dict( component= 'Q1', # Start component Name pin= 'a'), # Start Pin in component end_pin=Dict( component= 'Q2', pin= 'b')), lead=Dict( start_straight='0mm', # How long go straight from the starting point end_straight='0.5mm'), # How long go straight to the end point meander=Dict( asymmetry='-1mm'), **ops # Remark that this syntax usually used for reusing options. ) cpw = RouteMeander(design, options=options) gui.rebuild() gui.autoscale() cpw.options.lead.start_straight='100um' gui.rebuild() gui.autoscale() cpw.options['fillet']='30um' gui.rebuild() gui.autoscale() from collections import OrderedDict jogs = OrderedDict() jogs[0] = ["L", '800um'] jogs[1] = ["L", '500um'] jogs[2] = ["R", '200um'] jogs[3] = ["R", '500um'] options = Dict( total_length= '14mm', pin_inputs=Dict( start_pin=Dict( component= 'Q1', pin= 'd'), end_pin=Dict( component= 'Q3', pin= 'd')), lead=Dict( start_straight='0.1mm', end_straight='0.1mm', start_jogged_extension=jogs, end_jogged_extension=jogs), meander=Dict( asymmetry='-1.2mm'), **ops ) try: cpw5.delete() except NameError: pass cpw5 = RouteMeander(design,options=options) gui.rebuild() gui.autoscale() # Before showing examples of anchors, I will reset design and add some new transmon pockets. design.delete_all_components() gui.rebuild() options = dict( pad_width = '425 um', pocket_height = '650um', connection_pads=dict( # pin connectors a = dict(loc_W=+1,loc_H=+1), b = dict(loc_W=-1,loc_H=+1, pad_height='30um'), c = dict(loc_W=+1,loc_H=-1, pad_width='200um'), d = dict(loc_W=-1,loc_H=-1, pad_height='50um') ) ) q0 = TransmonPocket(design, 'Q0', options = dict(pos_x='-1.0mm', pos_y='-1.0mm', **options)) q1 = TransmonPocket(design, 'Q1', options = dict(pos_x='1.0mm', pos_y='+0.0mm', **options)) gui.rebuild() gui.autoscale() # You can import RoutePathfinder as below from qiskit_metal.qlibrary.tlines.pathfinder import RoutePathfinder from collections import OrderedDict # You should add anchors in OrderedDict because the order in anchors are very important. anchors = OrderedDict() anchors[0] = np.array([-0.452, -0.555]) anchors[1] = np.array([-0.452, -1.5]) anchors[2] = np.array([0.048, -1.5]) options = {'pin_inputs': {'start_pin': {'component': 'Q0', 'pin': 'b'}, 'end_pin': {'component': 'Q1', 'pin': 'b'}}, 'lead': {'start_straight': '91um', 'end_straight': '95um'}, 'step_size': '0.25mm', 'anchors': anchors, **ops } qa = RoutePathfinder(design, 'line', options) gui.rebuild() gui.autoscale()
https://github.com/alejomonbar/Qiskit_Fall_Fest_Mexico_2022
alejomonbar
%pip install yfinance %pip install cplex %pip qiskit_optimization %matplotlib inline import numpy as np import matplotlib.pyplot as plt import pandas as pd from docplex.mp.model import Model colors = plt.cm.tab20(range(20)) label_size = 22 plt.rcParams['xtick.labelsize'] = label_size plt.rcParams['ytick.labelsize'] = label_size plt.rcParams['axes.labelsize'] = label_size plt.rcParams['legend.fontsize'] = label_size plt.rcParams['axes.titlesize'] = label_size stocks_info = {"Stocks":["MSFT", "AAPL", "GOOG", "PFE", "MRNA", "JPM", "C", "XOM", "HAL", "HON"], "Name":["Microsoft", "Apple Inc.", "Alphabet", "Pfizer", "Moderna","JPMorgan Chase", "Citigroup", "ExxonMobil","Halliburton", "Honeywell"], "Sector":3*["Information Technology"] + 2 * ["Health Care"] + 2* ["Financial"] + 2 * ["Energy"]+ ["Industrial"]} pd.DataFrame(stocks_info) import yfinance as yf stocks = stocks_info["Stocks"] tickers = yf.Tickers(stocks) tickers.tickers["AAPL"].history(period="12mo") fig, ax = plt.subplots(2,2, figsize=(24,17)) colors_case = {"Open":colors[0], "High":colors[5], "Low":colors[10], "Close":colors[19]} linestyle = {"Open":"-", "High":"--", "Low":":", "Close":"-."} for case in ["Open", "High","Low", "Close"]: ax[0,0].plot(tickers.tickers["AAPL"].history(period="12mo")[case], color = colors_case[case], linestyle=linestyle[case], label=case) ax[0,0].legend() ax[0,1].plot(tickers.tickers["AAPL"].history(period="12mo")["Volume"], label=case) ax[1,0].plot(tickers.tickers["AAPL"].history(period="12mo")["Dividends"], label=case) ax[1,1].plot(tickers.tickers["AAPL"].history(period="12mo")["Stock Splits"], label=case) names = [["Stock Price", "Volume"], ["Dividends", "Stock Splits"]] for i in range(2): for j in range(2): ax[i,j].set_xlabel("date") ax[i,j].set_ylabel(names[i][j]) ax[i,j].set_title("Apple Inc.") # Price of all the stocks of this example Pt = np.array([tickers.tickers[stock].history(period="12mo")["Close"] for stock in stocks]) mu = (Pt[:,1:] - Pt[:,:-1]) / Pt[:,:-1] plt.figure() plt.plot(mu[0]) plt.xlabel("Days") plt.ylabel(r"$\mu_t$") plt.title("Apple Inc.") N_stocks, N_days = mu.shape sigma = np.zeros((N_stocks, N_stocks)) for i in range(N_stocks-1): for j in range(i, N_stocks): sigma[i,j] = ((mu[i] - mu[i].mean()) * (mu[j] - mu[j].mean())).sum()/(N_time - 1) sigma += sigma.T # sigma = np.cov(mu, varcol=True) fig, ax = plt.subplots(1, 2, figsize=(22,9)) for i in range(N_stocks): ax[0].plot(range(N_days+1), Pt[i], color=colors[i], label=stocks[i]) ax[0].set_xlabel("day") ax[0].set_ylabel("Stock Price [$]") ax[0].legend(loc='upper center', bbox_to_anchor=(0.5, 1.2), ncol=5, fancybox=True, shadow=True) im = ax[1].imshow(sigma, cmap="coolwarm", vmin=-0.0002, vmax=0.0006) fig.colorbar(im) ax[1].set_yticks(range(N_stocks)) ax[1].set_xticks(range(N_stocks)) ax[1].set_xticklabels(stocks, rotation=45) ax[1].set_yticklabels(stocks, rotation=45) ax[1].set_title(r"Covariance Matrix $\Sigma$ associated to the risk") q = 0.1 # Risk aversion Budget = 7 # I can invest in 7 stocks c = N_stocks * [1] # Minimum we can invest in the different assets c_i mdl = Model('Portfolio Optimization') # Binary set of variables that represent the stocks x = np.array(mdl.binary_var_list(N_stocks, name=stocks)) # x vector in numpy array for matrix multiplication # Portfolio optimization function objective_function = mu.mean(axis=1) @ x - q * x.T @ sigma @ x mdl.maximize(objective_function) # Budget constraint mdl.add_constraint(c @ x == Budget, ctname='budget') # Printing the docplex model mdl.prettyprint() sol_docplex = mdl.solve() sol_docplex = {st: int(sol_docplex.get_value(st)) for st in stocks} sol_docplex from qiskit_optimization.translators import from_docplex_mp from qiskit_optimization.runtime import QAOAClient, VQEClient from qiskit.algorithms import VQE, QAOA from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit import Aer # local simulator from qiskit.algorithms.optimizers import SPSA, COBYLA backend = Aer.get_backend("qasm_simulator") qubo = from_docplex_mp(mdl) def optimization_QAOA(qubo, reps=1, optimizer=SPSA(maxiter=50), backend=None, shots=1024, provider=None): intermediate_info = {'nfev': [], 'parameters': [], 'stddev': [], 'mean': [] } def callback(nfev, parameters, mean, stddev): intermediate_info['nfev'].append(nfev) intermediate_info['parameters'].append(parameters) intermediate_info['mean'].append(mean) intermediate_info['stddev'].append(stddev) qaoa_mes = QAOA(optimizer=optimizer, reps=reps, quantum_instance=backend, callback=callback) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(qubo) return result, intermediate_info sol_spsa, info_spsa = optimization_QAOA(qubo, backend=backend) sol_cobyla, info_cobyla = optimization_QAOA(qubo, backend=backend, optimizer=COBYLA()) solutions = {"Stocks":stocks_info["Stocks"], "CPLEX":sol_docplex.values(), "COBYLA":sol_cobyla.x, "SPSA":sol_spsa.x} pd.DataFrame(solutions) plt.figure() plt.plot(info_spsa["nfev"], info_spsa["mean"], label="SPSA", color=colors[5]) plt.plot(info["nfev"], info["mean"], label = "COBYLA", color=colors[10]) plt.legend() plt.xlabel("num func evals") plt.ylabel("Cost func.") from qiskit.circuit.library import TwoLocal ansatz = TwoLocal(N_stocks, rotation_blocks='ry', entanglement_blocks='cz') def Optimization_VQE(qubo, ansatz, optimizer=SPSA(maxiter=50), backend=None, shots=1024): intermediate_info = {'nfev': [], 'parameters': [], 'stddev': [], 'mean': [] } def callback(nfev, parameters, mean, stddev): intermediate_info['nfev'].append(nfev) intermediate_info['parameters'].append(parameters) intermediate_info['mean'].append(mean) intermediate_info['stddev'].append(stddev) vqe_mes = VQE(ansatz=ansatz, quantum_instance=backend, callback=callback, optimizer=optimizer) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(qubo) return result, intermediate_info import qiskit.tools.jupyter %qiskit_version_table
https://github.com/mahabubul-alam/QAOA-Compiler
mahabubul-alam
!python run.py -device_json examples/QC.json -circuit_json examples/QAOA_circ.json -config_json examples/Config.json -policy_compilation VIC -initial_layout_method vqp !cat VIC_QAOA.qasm
https://github.com/mahabubul-alam/QAOA-Compiler
mahabubul-alam
""" ################################################################################ ############## This library has been created by ###################### ############## Md Mahabubul Alam ###################### ############## https://mahabubul-alam.github.io/Personal/ ###################### ############## Graduate Student (Ph.D.) ###################### ############## Department of Electrical Engineering ###################### ############## Pennsylvania State University ###################### ############## University Park, PA, USA ###################### ############## mxa890@psu.edu ###################### ################################################################################ """ import math import re import os from . initial_layout_qaoa import create_initial_layout from random import shuffle from qiskit.circuit import Parameter from qiskit import QuantumCircuit, transpile, Aer, execute import commentjson as json import networkx as nx from qiskit.quantum_info.analysis import hellinger_fidelity from qiskit.converters import circuit_to_dag class CompileQAOAQiskit: """ This class implements the QAOA-specific compilation policies described in the following articles https://ieeexplore.ieee.org/document/9251960 https://ieeexplore.ieee.org/document/9218558 https://ieeexplore.ieee.org/document/9256490 After crating the object, compilation can be performed with the chosen compilation policies using the following public methods: run_ip run_iter_c run_incr_c The current implementation only supports compilation with qiskit compiler backend. Necessary instrcutions are given under __compile_with_backend method docstring to add support for other compilers (e.g. tket). """ def __init__(self, circuit_json = None, qc_json = None, config_json = None, out_circuit_file_name = 'QAOA.qasm'): """ This method initializes necessary config variables. """ self.supported_backends = ['qiskit'] self.supported_initial_layout_strategies = ['qaim','vqp','random'] self.__load_config(config_json) self.output_file_name = out_circuit_file_name self.__extract_qc_data(qc_json) self.layer_zz_assignments = {} self.zz_graph = self.qaoa_zz_graph(circuit_json) with open(circuit_json) as f: self.zz_dict = json.loads(f.read()) self.initial_layout = list(range(len(self.zz_graph.nodes()))) self.circuit = None self.sorted_ops = None self.cost = 10e10 self.final_map = [] [self.uncompiled_ckt, self.naive_ckt] = self.__naive_compilation() def __naive_compilation(self): """ This method constructs performs a naive compilation with the qiskit backend. (gates are randomly ordered). """ n = len(self.zz_graph.nodes()) qc = QuantumCircuit(n, n) for node in self.zz_graph.nodes(): qc.h(node) for p in range(1,self.Target_p+1): for zz in self.zz_graph.edges(): n1 = zz[0] n2 = zz[1] gamma = Parameter('g{}_{}_{}'.format(p, n1, n2)) qc.cx(n1, n2) qc.rz(gamma, n2) qc.cx(n1, n2) beta = Parameter('b{}'.format(p)) for node in self.zz_graph.nodes(): qc.rx(beta,node) qc.barrier() qc.measure(range(n), range(n)) trans_ckt = self.__compile_with_backend(ckt_qiskit = qc) filename = 'uncompiled_' + self.output_file_name qc.qasm(filename = filename) self.__fix_param_names(filename) filename = 'naive_compiled_' + self.output_file_name trans_ckt.qasm(filename = filename) self.__fix_param_names(filename) return [qc, trans_ckt] def __load_config(self, config_json = None): """ This method loads the variables in the config json file. """ with open(config_json) as f: self.config = json.load(f) if 'Target_p' in self.config.keys(): self.Target_p = int(self.config['Target_p']) else: self.Target_p = 1 if 'Packing_Limit' in self.config.keys(): self.Packing_Limit = float(self.config['Packing_Limit']) else: self.Packing_Limit = 10e10 if 'Route_Method' in self.config.keys(): self.Route_Method = self.config['Route_Method'] else: self.Route_Method = 'sabre' if 'Trans_Seed' in self.config.keys(): self.Trans_Seed = int(self.config['Trans_Seed']) else: self.Trans_Seed = 0 if 'Opt_Level' in self.config.keys(): self.Opt_Level = int(self.config['Opt_Level']) else: self.Opt_Level = 1 if 'Backend' in self.config.keys(): self.Backend = str(self.config['Backend']) assert self.Backend in self.supported_backends else: self.Backend = 'qiskit' assert self.Backend in self.supported_backends def __extract_qc_data(self, qc_file = None): """ This method extracts hardware information from the QC json file. """ with open(qc_file) as f: self.qc_data = json.load(f) try: self.native_2q = eval(self.qc_data['2Q'].strip('"')) except: self.native_2q = self.qc_data['2Q'] try: self.native_1q = eval(self.qc_data['1Q'].strip('"')) except: self.native_1q = self.qc_data['1Q'] self.basis_gates = self.native_2q + self.native_1q self.coupling_map = [] for key in self.qc_data[str(self.native_2q[0])].keys(): n1, n2 = eval(key)[0], eval(key)[1] if [n1, n2] not in self.coupling_map: self.coupling_map.append([n1, n2]) if [n2, n1] not in self.coupling_map: self.coupling_map.append([n2, n1]) self.__calc_qq_distances() def __calc_qq_distances(self): """ This method calculates pairwise qubit-qubit distances using the floyd_warshall algorithm. """ self.unweighted_undirected_coupling_graph = nx.Graph() self.weighted_undirected_coupling_graph = nx.Graph() for key, value in self.qc_data[str(self.native_2q[0])].items(): n1, n2, sp = eval(key)[0], eval(key)[1], float(value) self.unweighted_undirected_coupling_graph.add_edge(n1, n2) self.weighted_undirected_coupling_graph.add_edge(n1, n2, weight=1/sp) self.qq_distances = nx.floyd_warshall(self.unweighted_undirected_coupling_graph) self.noise_aware_qq_distances = nx.floyd_warshall(self.weighted_undirected_coupling_graph) def __set_iter_c_target(self, target = 'GC_2Q'): """ This method can be used to set the target of iterative compilation. """ self.iter_c_target = target def __set_incrc_var_awareness(self, variation_aware = False): """ This method can be used to set variation awareness in incremental compilation. """ self.incr_c_var_awareness = variation_aware @staticmethod def qaoa_zz_graph(circ_json = None): """ This method is used to create the MaxCut graph from the json file. """ with open(circ_json) as f: data = json.loads(f.read()) zz_graph = nx.Graph() for key, val in data.items(): nodes = eval(key) zz_graph.add_edge(nodes[0], nodes[1]) return zz_graph def __final_mapping_ic(self, qiskit_ckt_object): """ This method finds the output logical-to-physical qubit mapping in a compiled circuit block. """ qiskit_ckt_object.qasm(filename='tempfile') os.system('grep measure tempfile | awk \'{print $2, $4}\' > temp') qreg_creg_map = open('temp','r').readlines() fmap = {} for line in qreg_creg_map: elements = line.split(' ') physical_qs = elements[0] logical_qs = str(elements[1]).split(';')[0] physical_q = re.search('\[.*\]',physical_qs).group() physical_q = re.sub('\[|\]','',physical_q) logical_q = re.search('\[.*\]',logical_qs).group() logical_q = re.sub('\[|\]','',logical_q) fmap[logical_q[0:]] = int(physical_q[0:]) final_map = [] for i in range(qiskit_ckt_object.width() - qiskit_ckt_object.num_qubits): final_map.append(fmap[str(i)]) os.system('rm temp') os.system('rm tempfile') self.final_map = final_map def __set_initial_layout(self, target_layout = None, initial_layout_method = None): """ This method is used to set initial layout before starting compilation of any circuit block. """ if target_layout: self.initial_layout = target_layout elif initial_layout_method: if initial_layout_method == 'qaim': self.initial_layout = create_initial_layout(self.weighted_undirected_coupling_graph, self.zz_graph, method = 'qaim') elif initial_layout_method == 'vqp': self.initial_layout = create_initial_layout(self.weighted_undirected_coupling_graph, self.zz_graph, method = 'vqp') elif initial_layout_method == 'random': self.initial_layout = list(range(len(self.zz_graph.nodes()))) shuffle(self.initial_layout) #default: random else: raise ValueError def __sort_zz_by_qq_distances(self, unsorted_ops = None): """ This method sorts the ZZ operations based on the control-target distances for the current mapping. """ sorted_ops = [] swap_distances_ops = {} for op in unsorted_ops: _physical_q1 = self.initial_layout[op[0]] _physical_q2 = self.initial_layout[op[1]] if not self.incr_c_var_awareness: swap_dist = self.qq_distances[_physical_q1][_physical_q2] else: swap_dist = self.noise_aware_qq_distances[_physical_q1][_physical_q2] swap_distances_ops[op] = swap_dist for op in unsorted_ops: if not sorted_ops: sorted_ops.append(op) continue i = 0 for sop in sorted_ops: if swap_distances_ops[op] < swap_distances_ops[sop]: sorted_ops.insert(i, op) break i = i + 1 if i == len(sorted_ops): sorted_ops.append(op) self.sorted_ops = sorted_ops def __construct_single_layer_ckt_ic(self, p): """ This method constructs a single layer of the circuit in incremental compilation. """ n = len(self.zz_graph.nodes()) qc = QuantumCircuit(n, n) for zz in self.layer_zz_assignments['L0']: n1 = zz[0] n2 = zz[1] gamma = Parameter('g{}_{}_{}'.format(p, n1, n2)) qc.cx(n1, n2) qc.rz(gamma, n2) qc.cx(n1, n2) qc.measure(range(n), range(n)) trans_ckt = self.__compile_with_backend(ckt_qiskit = qc) self.circuit = trans_ckt def __compile_with_backend(self, ckt_qiskit = None): """ This method performs full/partial circuit compilation using the chosen backend. This method can be extended to support other compilers (e.g. tket). 1) The target backend should support parametric circuit compilation from a given qiskit QuantumCircuit object with the target basis gates, given initial layout, and target hardware coupling map. initial layout format: [1 2 0 ...] (means q0 --> p1, q1 --> p2, q2 --> p0 ...) qX: logical qubit, pX: physical qubit coupling map format: [[0,1],[1,0]...] (means the native 2q gate supported between 0 and 1, 1 and 0, ....) basis gates format: ['x', 'cx' ...] 2) It should be able to recognize CX, RZ(theta), RX(theta), and H operations. 3) It should return the compiled circuit as a qiskit QuantumCircuit object. If it does not do so, please convert the compiled circuit to a qiskit QuantumCircuit object. 4) If you are adding a new backend, please update the supported_backends variable under __init__ as well. 5) Use/add config variables in the Config.json (see under examples) file based on the supported features of the new backend. 6) Update the __load_config method as well if you are adding new variables in Config.json. """ assert isinstance(ckt_qiskit, QuantumCircuit) if self.Backend == 'qiskit': return transpile(ckt_qiskit, coupling_map = self.coupling_map, basis_gates = self.basis_gates, initial_layout = self.initial_layout, optimization_level = self.Opt_Level, seed_transpiler = self.Trans_Seed, routing_method = self.Route_Method) def __incremental_compilation(self): """ This method is used for incremental compilation. """ logical_n = len(self.zz_graph.nodes()) physical_n = len(self.unweighted_undirected_coupling_graph.nodes()) incr_c_qc = QuantumCircuit(physical_n, logical_n) for i in range(logical_n): incr_c_qc.h(self.initial_layout[i]) for p in range(1,self.Target_p+1): remaining_ops = self.zz_graph.edges() while remaining_ops: self.__sort_zz_by_qq_distances(unsorted_ops = remaining_ops) sorted_ops = self.sorted_ops self.__instruction_parallelization(sorted_ops, single_layer = True) remaining_ops = self.layer_zz_assignments['R'] self.__construct_single_layer_ckt_ic(p) new_ckt_segment = self.circuit self.__final_mapping_ic(qiskit_ckt_object = new_ckt_segment) final_map = self.final_map self.__set_initial_layout(final_map) new_ckt_segment.remove_final_measurements(inplace=True) incr_c_qc = incr_c_qc + new_ckt_segment beta = Parameter('b{}'.format(p)) for node in range(logical_n): incr_c_qc.rx(beta,self.initial_layout[node]) incr_c_qc.barrier() for i in range(logical_n): incr_c_qc.measure(self.initial_layout[i], i) self.circuit = incr_c_qc def __instruction_parallelization(self, sorted_edges = None, single_layer = False): """ This method is used for instruction parallelization. """ logical_qubits = self.zz_graph.nodes() if sorted_edges: remaining_edges = sorted_edges.copy() else: remaining_edges = list(self.zz_graph.edges()) current_layer = 'L0' layer_occupancy = {current_layer: list()} for qubit in logical_qubits: layer_occupancy[current_layer].insert(len(layer_occupancy[current_layer]), [qubit,'FREE']) self.layer_zz_assignments[current_layer] = list() while True: unallocated_edges = list() allocated_op_count_in_this_layer = 0 for edge in remaining_edges: if allocated_op_count_in_this_layer >= self.Packing_Limit: unallocated_edges.insert(len(unallocated_edges), edge) continue n1, n2 = edge[0], edge[1] free_among_the_two = 0 for occupancy_info_list in layer_occupancy[current_layer]: if occupancy_info_list[0] in edge: if occupancy_info_list[1] == 'OCCUPIED': unallocated_edges.insert(len(unallocated_edges), edge) break free_among_the_two = free_among_the_two + 1 if free_among_the_two == 2: n1_indx = layer_occupancy[current_layer].index([n1, 'FREE']) n2_indx = layer_occupancy[current_layer].index([n2, 'FREE']) layer_occupancy[current_layer][n1_indx] = [n1, 'OCCUPIED'] layer_occupancy[current_layer][n2_indx] = [n2, 'OCCUPIED'] self.layer_zz_assignments[current_layer].insert(len(layer_occupancy[current_layer]), edge) allocated_op_count_in_this_layer = allocated_op_count_in_this_layer + 1 break remaining_edges = unallocated_edges if single_layer: #print('Single layer formed!') self.layer_zz_assignments['R'] = list() for edge in remaining_edges: self.layer_zz_assignments['R'].insert(0, edge) break elif len(remaining_edges) != 0: next_layer = int(current_layer[1:]) + 1 current_layer = 'L' + str(next_layer) layer_occupancy[current_layer] = list() self.layer_zz_assignments[current_layer] = list() for qubit in logical_qubits: layer_occupancy[current_layer].insert(len(layer_occupancy[current_layer]), [qubit,'FREE']) else: #print('All layers formed!') break def __iterative_compilation(self): """ This method is used for iterative compilation. """ interchange = [] layer_order = [] for l in self.layer_zz_assignments.keys(): layer_order.append(l) opt_target = 10e10 opt_ckt = QuantumCircuit() while True: for layer_1 in range(len(layer_order)): for layer_2 in range(layer_1+1, len(layer_order)): temp = layer_order.copy() temp[layer_1], temp[layer_2] = temp[layer_2], temp[layer_1] self.__construct_circuit_iterc(layer_order = temp) trial_ckt = self.circuit self.__calc_cost(circ = trial_ckt, target = self.iter_c_target) trial_target = self.cost if trial_target < opt_target: interchange = [layer_1, layer_2] opt_target = trial_target opt_ckt = self.circuit if not interchange: self.circuit = opt_ckt break layer_1 = interchange[0] layer_2 = interchange[1] layer_order[layer_1], layer_order[layer_2] = layer_order[layer_2], layer_order[layer_1] #print('Interchanged: %s, %s, Cost: %s\n' % (layer_1, layer_2, opt_target)) interchange = [] def __calc_cost(self, circ = None, target = 'GC_2Q'): """ This method is used to calculate cost of the compiled circuit in terms of depth/2-qubit gate-count/estimated success probability. """ if target == 'GC_2Q': self.cost = circ.count_ops()[self.native_2q[0]] elif target == 'D': self.cost = circ.depth() elif target == 'ESP': self.circuit = circ self.__estimate_sp() def __estimate_sp(self): """ This method estimates the success probability of a compiled circuit. """ cir = self.circuit.copy() ESP = 1 while True: if cir._data: k = cir._data.pop() gate = k[0].__dict__['name'] if gate not in self.basis_gates: continue qub = [] for i in range(len(k[1])): qub.append(k[1][i].index) if len(qub) == 1: ESP = ESP*float(self.qc_data[gate][str(qub[0])]) else: if '({},{})'.format(qub[0],qub[1]) in self.qc_data[gate].keys(): ESP = ESP*float(self.qc_data[gate]['({},{})'.format(qub[0], qub[1])]) elif '({},{})'.format(qub[1],qub[0]) in self.qc_data[gate].keys(): ESP = ESP*float(self.qc_data[gate]['({},{})'.format(qub[1], qub[0])]) else: print('Please check the device configuration' + 'file for the following qubit-pair data: {}, {}'.format(qub[0], qub[1])) else: break self.cost = -math.log(ESP) def __construct_circuit_iterc(self, layer_order = None): """ This method constructs the circuit for iterative compilation. """ n = len(self.zz_graph.nodes()) qc = QuantumCircuit(n, n) # superposition state applying hadamard to all the qubits for node in self.zz_graph.nodes(): qc.h(node) # change based on the mixing and phase separation layer architectures for p in range(1, self.Target_p+1): for l in layer_order: # phase seperation depends on the number of edges for edge in self.layer_zz_assignments[l]: n1 = edge[0] n2 = edge[1] gamma = Parameter('g{}_{}_{}'.format(p, n1, n2)) qc.cx(n1, n2) qc.rz(gamma, n2) qc.cx(n1, n2) # mixing depends on the number of nodes rx gates beta = Parameter('b{}'.format(p)) for node in self.zz_graph.nodes(): qc.rx(beta, node) qc.barrier() qc.measure(range(n), range(n)) trans_ckt = self.__compile_with_backend(ckt_qiskit = qc) self.circuit = trans_ckt def __approximate_equivalence(self, ckt = None): """ This method checks (approximate) equivalence of the compiled circuit with the original one by comparing the output measurements (at a fixed value of all the parameters). """ bind_dic1 = {} bind_dic2 = {} val = 1 for param in ckt.parameters: bind_dic1[param] = val for param in self.uncompiled_ckt.parameters: bind_dic2[param] = val ckt1 = ckt.bind_parameters(bind_dic1) ckt2 = self.uncompiled_ckt.bind_parameters(bind_dic2) backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute([ckt1, ckt2], backend_sim, shots=1000000) result_sim = job_sim.result() counts1 = result_sim.get_counts(ckt1) counts2 = result_sim.get_counts(ckt2) return hellinger_fidelity(counts1, counts2) > 0.9 def __qasm_note(self, ckt = None, pol = None): """ This method prints notes on the compilation. """ #optional, will not work for larger circuits due to finite sampling errors assert self.__approximate_equivalence(ckt) print('##################### Notes on the Output File #############################') if ckt: self.circuit = self.naive_ckt self.__estimate_sp() print('(naive) Depth: {}, gate-count(2Q): {}, ESP: {}'.format(self.naive_ckt.depth(), self.naive_ckt.count_ops()[self.native_2q[0]], math.exp(-self.cost))) self.circuit = ckt self.__estimate_sp() print('({}) Depth: {}, gate-count(2Q): {}, ESP: {}'.format(pol, ckt.depth(), ckt.count_ops()[self.native_2q[0]], math.exp(-self.cost))) print('The circuit is written with beta/gamma parameters ' + 'at different p-lavels (https://arxiv.org/pdf/1411.4028.pdf)') print('bX --> beta parameter at p=X') print('gX --> gamma parameter at p=X (https://arxiv.org/pdf/1411.4028.pdf)') else: print('Compilation Error! Please check the input files.') print('############################################################################') def run_ip(self, initial_layout_method = 'qaim'): """ This public method runs instruction parallelization and writes the output circuits in qasm format. args: No arguments required. """ self.__set_initial_layout(initial_layout_method = initial_layout_method) self.__instruction_parallelization() layer_order = self.layer_zz_assignments.keys() self.__construct_circuit_iterc(layer_order) ckt = self.circuit filename = 'IP_' + self.output_file_name ckt.qasm(filename = filename) self.__fix_param_names(filename) print('############################################################################') print('Instruction Parallelization-only Compilation (IP) completed (initial layout: {})!'.format(initial_layout_method) + '\nQASM File Written: {}'.format('IP_' + self.output_file_name)) self.__qasm_note(ckt, 'IP') def run_iter_c(self, target = 'D', initial_layout_method = 'qaim'): """ This public method runs iterative compilation and writes the output circuits in qasm format. Args: Target minimization objective: D (depth), GC-2Q (two-qubit gate-count), ESP (estimated success probability) """ self.__set_initial_layout(initial_layout_method = initial_layout_method) self.__set_iter_c_target(target) self.__instruction_parallelization() self.__iterative_compilation() ckt = self.circuit filename = 'IterC_' + self.output_file_name ckt.qasm(filename = filename) self.__fix_param_names(filename) print('############################################################################') print('Iterative Compilation (IterC) completed (initial layout: {})!'.format(initial_layout_method) + '\nQASM File Written: {}'.format('IterC_' + self.output_file_name)) self.__qasm_note(ckt, 'IterC_' + target) def run_incr_c(self, variation_aware = False, initial_layout_method = 'qaim'): """ This public method runs incremental compilation and writes the output circuits in qasm format. Args: variation_aware (boolean) - False to perform IC and True to perform VIC """ self.__set_initial_layout(initial_layout_method = initial_layout_method) self.__set_incrc_var_awareness(variation_aware) self.__incremental_compilation() ckt = self.circuit print('############################################################################') if variation_aware: filename = 'VIC_' + self.output_file_name ckt.qasm(filename = filename) self.__fix_param_names(filename) print('Variation-aware Incremental Compilation (VIC) completed (initial layout: {})!'.format(initial_layout_method) + '\nQASM File Written: {}'.format('VIC_' + self.output_file_name)) self.__qasm_note(ckt, 'VIC') else: filename = 'IC_' + self.output_file_name ckt.qasm(filename = filename) self.__fix_param_names(filename) print('Incremental Compilation (IC) completed (initial layout: {})!'.format(initial_layout_method) + '\nQASM File Written: {}'.format('IC_' + self.output_file_name)) self.__qasm_note(ckt, 'IC') def __fix_param_names(self, filename): all_keys = self.zz_dict.keys() f = open(filename, 'r').readlines() out = open('{}_fixed'.format(filename), 'w') for line in f: captures = re.search('(g\d+)_(\d+)_(\d+)', line) if captures: captures = captures.groups() g = captures[0] n1 = captures[1] n2 = captures[2] if '({}, {})'.format(n1, n2) in all_keys: coeff = 2*float(self.zz_dict['({}, {})'.format(n1, n2)]) else: coeff = 2*float(self.zz_dict['({}, {})'.format(n2, n1)]) line = line.replace('{}_{}_{}'.format(g, n1, n2), str(coeff) + '*' + g) out.write(line) out.close() os.remove(filename) os.rename(filename + '_fixed', filename)
https://github.com/OccumRazor/implement-quantum-algotirhms-with-qiskit
OccumRazor
from qiskit import QuantumRegister,ClassicalRegister,QuantumCircuit,execute,Aer from qiskit.providers.aer import QasmSimulator from qiskit.quantum_info.operators import Operator from math import log,cos,sin,sqrt,pi,exp import matplotlib.pyplot as plt from numpy import kron,matmul,transpose,conjugate,zeros,trace,complex128,array,inf,linspace,abs from time import time from scipy.linalg import expm from random import random from scipy.fft import fft from scipy import integrate import xlsxwriter from tqdm import tqdm H=[[1/sqrt(2),1/sqrt(2)],[1/sqrt(2),-1/sqrt(2)]] X=[[0,1],[1,0]] ID=[[1,0],[0,1]] DM0=[[1,0],[0,0]] DM1=[[0,0],[0,1]] Y=[[0,-1j],[1j,0]] Z=[[1,0],[0,-1]] CX=[[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]] ket=[[[1],[0]],[[0],[1]],ID] CH=[[1,0,0,0],[0,1/sqrt(2),0,1/sqrt(2)],[0,0,1,0],[0,1/sqrt(2),0,-1/sqrt(2)]] def RX(t): return [[cos(t),-1j*sin(t)],[-1j*sin(t),cos(t)]] def twoQubitState(t):# Parametrized two qubit state # twoQubitState(t)|00>=cost|00>-isint|11> #CH=kron(DM0,ID)+kron(DM1,H) #return [[cos(t)],[0],[0],[-1j*sin(t)]] #return matmul(CH,kron(RX(t),ID)) return matmul(CX,kron(RX(t),ID)) def WState(t):# Parametrized three qubit W State # cos(theta)|100>+sin(theta)/sqrt(2)|010>+sin(theta)/sqrt(2)|001> XNCNC=kron(ID,kron(DM1,DM1))+kron(ID,kron(DM0,DM1))+kron(ID,kron(DM1,DM0))+kron(X,kron(DM0,DM0)) U=matmul(kron(kron(DM0,ID)+kron(DM1,Y),ID),kron(RX(t),kron(ID,ID))) U=matmul(kron(ID,kron(DM0,ID)+kron(DM1,H)),U) U=matmul(kron(kron(ID,DM0)+kron(X,DM1),ID),U) U=matmul(kron(ID,kron(ID,DM0)+kron(X,DM1)),U) U=matmul(XNCNC,U) return U def M(p,q):# function for nQubitWState return [[sqrt(p)/sqrt(p+q),sqrt(q)/sqrt(p+q)],[-sqrt(q)/sqrt(p+q),sqrt(p)/sqrt(p+q)]] def spaceExpansion(mat,n,idx):# function for nQubitWState if idx[0]>0: for _ in range(idx[0]): mat=kron(ID,mat) if idx[-1]<n-1: for _ in range(idx[-1]+1,n): mat=kron(mat,ID) return mat def nQubitWState(n): m=M(1,n-1) m=spaceExpansion(m,n,[0]) for i in range(1,n-1): mat=kron(DM0,ID)+kron(DM1,M(1,n-1-i)) mat=spaceExpansion(mat,n,[i-1,i]) m=matmul(mat,m) for i in range(n-1,0,-1): mat=spaceExpansion(CX,n,[i-1,i]) m=matmul(mat,m) m=matmul(spaceExpansion(X,n,[0]),m) return m def nQubitGHZState(n):# of course n must be at least 2, otherwise what do you want? U=matmul(CX,kron(H,ID)) newCX=kron(ID,CX) while n>2: U=kron(U,ID) U=matmul(newCX,U) newCX=kron(ID,newCX) n-=1 return U def D2B(n,N): # n current number # N maximum # to make sure the output have the same length l=int(log(N,2)) opt=[] for i in range(l): if n <2**(l-i-1):opt.append(0) else: opt.append(1) n-=2**(l-i-1) return opt def B2D(li): l=len(li) res=0 for i in range(l):res+=li[i]*2**(l-i-1) return res def D2Q(num,length):# convert decimal number to quaternary number res=[0 for _ in range(length)] for i in range(length-1,-1,-1): if num>=4**i: res[length-i-1]=int((num-num%(4**i))/4**i) num=num%(4**i) return res def mulKron(ops): res=ops[0] for i in range(1,len(ops)):res=kron(res,ops[i]) return res def listStringSum(li): text=li[0] for i in range(1,len(li)):text+=li[i] return text def PauliDecomposition(Ham): n=int(log(len(Ham),2)) set=[ID,X,Y,Z] dic={0:'I',1:'X',2:'Y',3:'Z'} nQubitPauli=[] remaindOps=[] coes=[] for i in range(4**n): idx=D2Q(i,n) ops=mulKron([set[idx[i]] for i in range(n)]) temp=trace(matmul(ops,Ham))/(2**n) if temp!=0: coes.append(temp) nQubitPauli.append([dic[idx[i]] for i in range(n)]) remaindOps.append(ops) print(f'number of nonzero term(s): {len(coes)}') for i in range(len(coes)):print(f'operator: {listStringSum(nQubitPauli[i])}, coefficient: {coes[i]}') def quad(li):# hamiltonian companian function to avoid shallow copy res=[]# there are specific deep copy, from copy import deepcopy for j in range(len(li)): for _ in range(4):res.append([li[j][0],li[j][1]]) return res def hamiltonian(num_qubit,idle): # this Hamiltonian calculates Tr(rho^2_gamma) # the variable num_qubit is actually half the number of qubit required loc=idle if isinstance(idle,int):loc=[idle] dim=2**(2*num_qubit) Har=[[0 for _ in range(dim)] for _ in range(dim)] # the list jk denotes the jk part of |ijk ijk> initially, # and finally it turns to |ijk i'jk> jk=[[D2B(i,2**(num_qubit-len(loc)))*2,D2B(j,2**(num_qubit-len(loc)))*2] for i in range(2**(num_qubit-1)) for j in range(2**(num_qubit-1))] for i in range(len(loc)): jk=quad(jk) for j in range(len(jk)): c=j%4 jk[j][0]=jk[j][0][:loc[i]]+[int(c/2)]+jk[j][0][loc[i]:loc[i]+num_qubit-1]+[c%2]+jk[j][0][loc[i]+num_qubit-1:] jk[j][1]=jk[j][1][:loc[i]]+[int(c/2)]+jk[j][1][loc[i]:loc[i]+num_qubit-1]+[c%2]+jk[j][1][loc[i]+num_qubit-1:] for i in range(len(jk)):Har[B2D(jk[i][0])][B2D(jk[i][1])]=1 return Har def densityMatrix(state): dm=[] for i in range(len(state)): dm.append([]) for j in range(len(state)): dm[i].append(complex(state[i]*conjugate(state[j]))) return dm def partialTrace(state,idle): # idle here refers to those traced qubits. n=int(log(len(state),2)) traceList=[i for i in range(n) if i not in idle] li=[] for i in range(n): if i in traceList:li.append(0) else:li.append(1) N=2**sum(li) # number of basis rho=densityMatrix(state) res=complex128(zeros([2**len(traceList),2**len(traceList)])) for i in range(N): li=D2B(i,N) for j in traceList: li.insert(j,2) basis=ket[li[-1]] for k in range(n-2,-1,-1): basis=kron(ket[li[k]],basis) res+=matmul(transpose(basis),matmul(rho,basis)) return res def swapTestRes(ipt,rep): trrho2=2*ipt['0']/rep-1 # the try sentence isn't required here, p0>=0.5 return sqrt(2*(1-trrho2)) def swapTest(u0,idle,rep=10**6): n=int(log(len(u0),2)) u0=Operator(u0) ctrl=QuantumRegister(1) d0Reg=QuantumRegister(n) d1Reg=QuantumRegister(n) c2Reg=ClassicalRegister(1) qc=QuantumCircuit(ctrl,d0Reg,d1Reg,c2Reg) qc.append(u0,[d0Reg[i] for i in range(n)]) qc.append(u0,[d1Reg[i] for i in range(n)]) qc.h(ctrl) for i in range(n): if i not in idle: qc.cswap(ctrl,d0Reg[i],d1Reg[i]) qc.h(ctrl) qc.barrier() qc.measure(ctrl,c2Reg) simulator=Aer.get_backend('qasm_simulator') res=execute(qc,simulator,shots=rep).result().get_counts() return swapTestRes(res,rep) def WStateConcurrence(N,k): # the GME concurrence has a simple formula, # it only depends on the number of qubits N # and the number of idle qubits k return sqrt(2*(1-(N**2-2*N*k+2*k**2)/N/N)) def completes(ele,otherPart,N):# to check whether a term should be added to idle for i in range(len(otherPart)): if len(ele)+len(otherPart[i])==N: temp=ele+otherPart[i] count=0 for j in range(N): if j in temp:count+=1 if count>=N:return False if len(ele)==len(otherPart[i]): count1=0 for j in range(len(ele)): if ele[j] in otherPart[i]:count1+=1 if count1==len(ele):return False return True def genPartition(N):# for n qubits, 2^(n-1)-1 terms for n>2 n=int(N/2) li=[[i] for i in range(N)] idles=[[i] for i in range(N)] for i in range(1,n+1): temp=[[j] for j in range(N)] for j in range(i-1): for k in range(len(temp)): if len(temp[k])==j+1: for l in range(N): if li[l][0] not in temp[k]:temp.append(temp[k]+li[l]) for j in range(N,len(temp)): if completes(temp[j],idles,N) and temp[j] not in idles: idles.append(temp[j]) return idles def expectation(state,ham,time,rep): eiht=expm(time*1j*array(ham)) dm=densityMatrix(kron(state,state)) return trace(matmul(eiht,dm))*(1+(1-2*random())/sqrt(rep)) def h(x): if x**2>=1:return 0 else:return exp(-1/(1-x**2)) def window(x): if x>=0 and x<1:return 1 else:return 0 def fUnint(xp): return 5*h(2*xp-point)*window(xp)#/4.05 def F(x,num_sample): coes=[] xs=[x-2*(num_sample-m)/num_sample for m in range(num_sample)]+[x+2*m/num_sample for m in range(num_sample)] #xs=[-x/2+x*i/num_sample for i in range(len(num_sample))] #print(f'xs:{xs}') global point for i in range(len(xs)): point=xs[i] coes.append(integrate.quad(fUnint,-inf,inf)[0]) coes=fft(coes) return coes def timeSeries(theta,num_qubit=3,num_sample=50,rep=10**5): exp_TS=[] coes=F(0.75,num_sample) for i in range(len(theta)): if num_qubit==3:unitary=WState(theta[i]) else:unitary=twoQubitState(theta[i]) state=matmul(unitary,[[1]]+[[0] for _ in range(2**num_qubit-1)]) exp=[] for j in range(-num_sample,num_sample): exp.append(coes[j]*expectation(state,array(hamiltonian(num_qubit,0)),j,rep)) exp_TS.append(sum(exp)) #norm=exp_TS[0] norm=max(exp_TS) for i in range(len(exp_TS)):exp_TS[i]/=norm#sqrt(2*(1-exp_TS[i]/norm)) return exp_TS def varyingTheta(num_points=100,num_qubit=3,rep=10**4): #theta=[i*pi/(num_points-1) for i in range(num_points-1)]+[pi] theta=linspace(0,pi/2,num_points) idle=genPartition(num_qubit) GME_Classical=[] GME_Quantum=[] for i in range(num_points): if num_qubit==3:unitary=WState(theta[i]) else:unitary=twoQubitState(theta[i]) state=matmul(unitary,[[1]]+[[0] for _ in range(2**num_qubit-1)]) #print(state) iGME=[] qGME=[] for j in range(len(idle)): pdm=partialTrace(state,idle[j]) #print(pdm) temp=2*(1-trace(matmul(pdm,pdm))) #print(temp) #temp=trace(matmul(pdm,pdm)) if abs(temp.imag)>1e-7:print('imaginary part might exist') iGME.append(sqrt(abs(temp))) swap_test_res=swapTest(unitary,idle[j],rep) qGME.append(swap_test_res) GME_Classical.append(min(iGME)) GME_Quantum.append(min(qGME)) #GME_Har.append(min(hGME)) x=[theta[i]/pi for i in range(num_points)] plt.plot(x,GME_Classical,'r',label='partial trace') plt.plot(x,GME_Quantum,'b-.',label='swap test') GME_TS=timeSeries(theta,num_qubit,10**2,rep) for i in range(len(GME_TS)):GME_TS[i]=sqrt(2*(1-GME_TS[i])) plt.plot(x,GME_TS,'g*',label='time series') plt.xlabel(r'$\theta/\pi$') plt.ylabel('GME Concurrence') #plt.ylabel('purity') plt.legend(loc='best') plt.savefig('with time series.png') plt.savefig('with time series.eps',format='eps') plt.show() varyingTheta(101,2,10**4) def varyingQubit(rep=10**4): start=2 end=5 GME_Classical=[] GME_Quantum=[] for num_qubit in range(start,end): print(f'{num_qubit}-qubit GME concurrence') idle=genPartition(num_qubit) unitary=nQubitWState(num_qubit) state=matmul(unitary,[[1]]+[[0] for _ in range(2**num_qubit-1)]) iGME=[] qGME=[] t0=0 print(len(idle)) for j in tqdm(range(len(idle))): pdm=partialTrace(state,idle[j]) temp=2*(1-trace(matmul(pdm,pdm))) if abs(temp.imag)>1e-5: print('imag part goes high') iGME.append(sqrt(temp.real)) t1=time() qGME.append(swapTest(unitary,idle[j],rep)) t2=time() t0+=t2-t1 print(f'{num_qubit}-qubit GME concurrence requires time: {t0}') GME_Classical.append(min(iGME)) GME_Quantum.append(min(qGME)) x=[i for i in range(start,end)] plt.plot(x,GME_Classical,'r',label='partial trace') plt.plot(x,GME_Quantum,'b-.',label='swap test') plt.xlabel('number of qubits') plt.ylabel('GME Concurrence') plt.legend(loc='best') plt.show() #plt.savefig('n qubit w state.png') #plt.savefig('n qubit w state.eps',format='eps') #varyingQubit(10**4) def unnecessaryBipartitions(rep=10**4): # for W state and GHZ state, they are highly symmetrical, it is reasonable to # assume that a lot of bipartitions give the same result. start=2 end=13 y1=[] y2=[] for num_qubit in range(start,end): idle=genPartition(num_qubit) unitary=nQubitWState(num_qubit) state=matmul(unitary,[[1]]+[[0] for _ in range(2**num_qubit-1)]) for j in range(len(idle)-1): if len(idle[j])!=len(idle[j+1]): print(f'idle qubits:{idle[j]}') pdm=partialTrace(state,idle[j]) temp=2*(1-trace(matmul(pdm,pdm))) y1.append(temp) if abs(temp.imag)>1e-5: print('imag part goes high') print(f'partial trace result: {sqrt(temp.real)}') print(f'formula result: {WStateConcurrence(num_qubit,len(idle[j]))}') y2.append(WStateConcurrence(num_qubit,len(idle[j]))) x=[i for i in range(len(y1))] plt.plot(x,y1,'r') plt.plot(x,y2,'bo') plt.show() #unnecessaryBipartitions() def varyingQubitWithFewerBipartition(rep=10**4): start=2 end=16 GME_Classical=[] GME_Quantum=[] idle=[0] t0=time() for num_qubit in range(start,end): unitary=nQubitWState(num_qubit) state=matmul(unitary,[[1]]+[[0] for _ in range(2**num_qubit-1)]) pdm=partialTrace(state,idle) temp=2*(1-trace(matmul(pdm,pdm))) if abs(temp.imag)>1e-5: print('imag part goes high') GME_Classical.append(sqrt(temp.real)) print(f'current precise result: {GME_Classical[-1]}') t2=time() GME_Quantum.append(swapTest(unitary,idle,rep)) t3=time() print(f'current C-Swap result: {GME_Quantum[-1]}') print(f'time spent for {2*num_qubit} swap test: {t3-t2}s') t1=time() print(f'time spent: {t1-t0}s') print(f'current precise result: {GME_Classical}') print(f'current approximate result: {GME_Quantum}') x=[i for i in range(start,end)] plt.plot(x,GME_Classical,'r',label='partial trace') plt.plot(x,GME_Quantum,'b-.',label='swap test') plt.xlabel('number of qubits') plt.ylabel('GME Concurrence') plt.legend(loc='best') plt.savefig('n qubit w state with one bipartition.png') plt.savefig('n qubit w state with one bipartition.eps',format='eps') plt.show() #varyingQubitWithFewerBipartition(10**5)
https://github.com/OccumRazor/implement-quantum-algotirhms-with-qiskit
OccumRazor
from qiskit import QuantumRegister,ClassicalRegister,QuantumCircuit,Aer,execute from qiskit.providers.aer import QasmSimulator from qiskit.circuit.library.standard_gates import CU1Gate from numpy import pi from qiskit_code.classicalMethod import printCounts,Dec2Bi,modifyExpValue from qiskit_code.quantumMethod import ini from qiskit.aqua.operators import StateFn,I from numpy import real def physicalQubits(ipt): qr=QuantumRegister(5) circ=QuantumCircuit(qr) if ipt==1: circ.x(qr[0]) # controlled phase flip - if the input state is |1>, # then flip the global phase by pi CU1=CU1Gate(pi) circ.append(CU1,[qr[0],qr[1]]) circ.cx(qr[0],qr[1]) circ.append(CU1,[qr[0],qr[1]]) circ.cx(qr[0],qr[1]) circ.h(qr[4]) circ.s(qr[4]) # g1 circ.cz(qr[4],qr[3]) circ.cz(qr[4],qr[1]) circ.cy(qr[4],qr[0]) circ.h(qr[3]) #g2 circ.cz(qr[3],qr[2]) circ.cz(qr[3],qr[1]) circ.cx(qr[3],qr[0]) circ.h(qr[2]) #g3 circ.cz(qr[2],qr[4]) circ.cz(qr[2],qr[3]) circ.cx(qr[2],qr[0]) circ.h(qr[1]) circ.s(qr[1]) #g4 circ.cz(qr[1],qr[4]) circ.cz(qr[1],qr[2]) circ.cy(qr[1],qr[0]) return circ.to_gate() def checkPhases(): operator=I.tensorpower(5) for i in range(32): qr=QuantumRegister(5) circ=QuantumCircuit(qr) ini(circ,qr,Dec2Bi(i)) # generate the state vector of the test state psi=StateFn(circ) # generate the state vector of the 0L state phi1=StateFn(physicalQubits(0)) thisNumber=bin(i)[2:] if len(thisNumber)<5: thisNumber=(5-len(thisNumber))*'0'+thisNumber print('expectation value for state '+thisNumber) print(' and the physical qubits of 0:') exp01=(~phi1@operator@psi).eval() exp1=modifyExpValue(real(exp01)) print(exp1) # generate the state vector of the 1L state phi2=StateFn(physicalQubits(1)) print(' and the physical qubits of 1:') exp02=(~phi2@operator@psi).eval() exp2=modifyExpValue(real(exp02)) print(exp2) def stabilized(ipt): operator=I.tensorpower(5) qr=QuantumRegister(5) circ=QuantumCircuit(qr) circ.append(physicalQubits(ipt),qr) # stabilized: phi=StateFn(circ) # g1 check circ.cz(qr[4],qr[3]) circ.cz(qr[4],qr[1]) circ.cy(qr[4],qr[0]) psi=StateFn(circ) print((~phi@operator@psi).eval()) #g2 check circ.cz(qr[3],qr[2]) circ.cz(qr[3],qr[1]) circ.cx(qr[3],qr[0]) psi=StateFn(circ) print((~phi@operator@psi).eval()) #g3 check circ.cz(qr[2],qr[4]) circ.cz(qr[2],qr[3]) circ.cx(qr[2],qr[0]) psi=StateFn(circ) print((~phi@operator@psi).eval()) #g4 check circ.cz(qr[1],qr[4]) circ.cz(qr[1],qr[2]) circ.cy(qr[1],qr[0]) psi=StateFn(circ) print((~phi@operator@psi).eval()) #checkPhase() stabilized(0) stabilized(1)
https://github.com/OccumRazor/implement-quantum-algotirhms-with-qiskit
OccumRazor
from qiskit import QuantumRegister,QuantumCircuit from qiskit.aqua.operators import StateFn from qiskit.aqua.operators import I from qiskit_code.quantumMethod import add,ini from qiskit_code.classicalMethod import Dec2Bi def DeutschJozsa(l,method): # Deutsch, D. and Jozsa, R., 1992. Rapid solution of problems by quantum computation. # Proceedings of the Royal Society of London. Series A: Mathematical and Physical Sciences, # 439(1907), pp.553-558. # The input 'l' is the equivalent to the 'N' in the original paper of # David Deutsch and Richard Jozsa, and 'method' denotes the 'unknown' # function, if you input 'balanced' then it will be balanced and otherwise # it will be constant. qr0=QuantumRegister(l) qr1=QuantumRegister(l+1) # One qubit larger to carry. ac=QuantumRegister(l) # Ancilla. t0=QuantumRegister(1) circ=QuantumCircuit(qr0,qr1,ac,t0) circ.h(qr0) if method=='balanced': print('balanced oracle') ini(circ,qr1,Dec2Bi(2**(l-1))) else: print('constant oracle') ini(circ,qr1,Dec2Bi(0)) lst=range(l) QIN1=[qr0[i] for i in lst]+[qr1[i] for i in range(l+1)]+[ac[i] for i in lst] ADD=add(qr0,qr1,ac,l) circ.append(ADD,QIN1)# Role of the U unitary circ.cx(qr1[l],t0)# Role of the U unitary circ.z(t0)# The S unitary. circ.cx(qr1[l],t0)# Role of the U unitary circ.append(ADD.inverse(),QIN1)# Role of the U unitary psi=StateFn(circ) phiReg0=QuantumRegister(l) phiReg1=QuantumRegister(l+1) phiReg2=QuantumRegister(l) t1=QuantumRegister(1) phiCirc=QuantumCircuit(phiReg0,phiReg1,phiReg2,t1) phiCirc.h(phiReg0) if method=='balanced': ini(circ,qr1,Dec2Bi(2**(l-1))) else: ini(circ,qr1,Dec2Bi(0)) phi=StateFn(phiCirc) operator=I.tensorpower(3*l+2) expectation_value=(~psi@operator@phi).eval() print(expectation_value) #DeutschJozsa('constant') #DeutschJozsa('balanced')
https://github.com/OccumRazor/implement-quantum-algotirhms-with-qiskit
OccumRazor
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>) out of four possible values.""" #import numpy and plot library import matplotlib.pyplot as plt import numpy as np # importing Qiskit from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.quantum_info import Statevector # import basic plot tools from qiskit.visualization import plot_histogram # define variables, 1) initialize qubits to zero n = 2 grover_circuit = QuantumCircuit(n) #define initialization function def initialize_s(qc, qubits): '''Apply a H-gate to 'qubits' in qc''' for q in qubits: qc.h(q) return qc ### begin grovers circuit ### #2) Put qubits in equal state of superposition grover_circuit = initialize_s(grover_circuit, [0,1]) # 3) Apply oracle reflection to marked instance x_0 = 3, (|11>) grover_circuit.cz(0,1) statevec = job_sim.result().get_statevector() from qiskit_textbook.tools import vector2latex vector2latex(statevec, pretext="|\\psi\\rangle =") # 4) apply additional reflection (diffusion operator) grover_circuit.h([0,1]) grover_circuit.z([0,1]) grover_circuit.cz(0,1) grover_circuit.h([0,1]) # 5) measure the qubits grover_circuit.measure_all() # Load IBM Q account and get the least busy backend device provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) from qiskit.tools.monitor import job_monitor job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(grover_circuit) plot_histogram(answer) #highest amplitude should correspond with marked value x_0 (|11>)
https://github.com/OccumRazor/implement-quantum-algotirhms-with-qiskit
OccumRazor
from qiskit import * from qiskit.circuit.library.standard_gates import SwapGate,CU1Gate,XGate,U1Gate from math import pi,sqrt from qiskit.quantum_info.operators import Operator import numpy as np def ini(circ,qr,ipt): # Input binary form, and append [0] ahead for qr1 block. for i in range(len(ipt)): if ipt[len(ipt)-i-1]: circ.x(qr[i]) return 0 def diffusion(n): # Matrix representation of the diffusion transformation. N=2**n# for Grover search. return [N*[2/N] for i in range(N)]-np.identity(N) def phaseFlip(reg,theta): # reg is a one qubit register (input a qubit is also OK). if reg.__len__()!=1: raise TypeError('The input quantum register contains more than one qubit.') phaseCirc=QuantumCircuit(reg,name='p\nh\na\ns\ne\n') phaseCirc.append(U1Gate(theta),reg) phaseCirc.append(XGate(),reg) phaseCirc.append(U1Gate(theta),reg) phaseCirc.append(XGate(),reg) return phaseCirc.to_instruction() def CPhaseFlip(qReg,reg,theta):# If all ancilla qubits equal one, flip the phase of querry REG. # In this place, reg is a one qubit quantum register, and qReg is a n qubits quantum register. phaseCirc=QuantumCircuit(qReg,reg,name='p\nh\na\ns\ne\n') num=qReg.__len__() IN=[qReg[i] for i in range(num)]+[reg[0]] CU1Gate=U1Gate(theta).control(num) CXGate=XGate().control(num) phaseCirc.append(CU1Gate,IN) phaseCirc.append(CXGate,IN) phaseCirc.append(CU1Gate,IN) phaseCirc.append(CXGate,IN) return phaseCirc.to_instruction() def amulitpdeAmplification(query,criteria,ancilla,n):# for Grover search. AACirc=QuantumCircuit(query,criteria,ancilla,name='A\nA\n') AACirc.h(query) from qiskit_code.Grover import check CHECK=check(query,criteria,ancilla,n) lst=range(n)# This looks rather awkward, I may (but not likely) try to change this later. AC=[ancilla[i] for i in lst] QUERY=[query[i] for i in lst] CHECKIN=QUERY+[criteria[i] for i in lst]+AC nCP=CPhaseFlip(ancilla,QuantumRegister(1),pi) nCX=XGate().control(n)# Generate a controlled-X gate with n controls. D=Operator(diffusion(n)) for i in range(int(pi*sqrt(2**n)/8+1)):#[1] Iteration times. AACirc.append(CHECK,CHECKIN) AACirc.append(nCP,AC+[query[0]]) AACirc.append(CHECK,CHECKIN) AACirc.append(D,query) # [1]M. Boyer, G. Brassard, P. Hoyer & A. Tapp, Tight bounds on quantum searching, #Proceedings, PhysComp 1996 return AACirc.to_instruction() def bigCSwap(c,t0,t1,l):# Controlled Swap of two qubit blocks. BCSC=QuantumCircuit(c,t0,t1,name='b\ni\ng\nC\nS\nw\na\np\n') for i in range(l): BCSC.cswap(c,t0[i],t1[i]) return BCSC.to_instruction() def bigSwap(t0,t1,l):# Swap of two qubit blocks. BSC=QuantumCircuit(t0,t1,name='b\ni\ng\nS\nw\na\np\n') for i in range(l): BSC.swap(t0[i],t1[i]) return BSC.to_instruction() def c_cx(c0,c1,target,n):# CCX where the second control and the target are two blocks c_cxC=QuantumCircuit(c0,c1,target,name='C\no\nn\nt\nr\no\nl\nl\ne\nd\n-\nC\nX\n') for i in range(n): c_cxC.ccx(c0,c1[i],target[i]) return c_cxC.to_instruction() def bigCCSwap(c0,c1,reg1,reg2,l):# Controlled-Controlled Swap of two qubit blocks. bigCCSwapC=QuantumCircuit(c0,c1,reg1,reg2,name='C\nC\nS\nw\na\np\n') ccswap=SwapGate().control(2) for i in range(l): bigCCSwapC.append(ccswap,[c0[0],c1[0],reg1[i],reg2[i]]) return bigCCSwapC.to_instruction() carry_q=QuantumRegister(4) carryC=QuantumCircuit(carry_q,name='c\na\nr\nr\ny\n') carryC.ccx(carry_q[1],carry_q[2],carry_q[3]) carryC.cx(carry_q[1],carry_q[2]) carryC.ccx(carry_q[0],carry_q[2],carry_q[3]) CARRY=carryC.to_instruction() sum_q=QuantumRegister(3) sumC=QuantumCircuit(sum_q,name='s\nu\nm') sumC.cx(sum_q[1],sum_q[2]) sumC.cx(sum_q[0],sum_q[2]) SUM=sumC.to_instruction() def add(q0,q1,q2,l): # A quantum plain adder, as the main part of the oracle. # Vedral, V., Barenco, A. and Ekert, A., 1996. # Quantum networks for elementary arithmetic operations. Physical Review A, 54(1), p.147. add_circ=QuantumCircuit(q0,q1,q2,name='a\nd\nd') for i in range(l-1): add_circ.append(CARRY,[q2[i],q0[i],q1[i],q2[i+1]]) add_circ.append(CARRY,[q2[l-1],q0[l-1],q1[l-1],q1[l]]) add_circ.cx(q0[l-1],q1[l-1]) add_circ.append(SUM,[q2[l-1],q0[l-1],q1[l-1]]) RCARRY=CARRY.reverse_ops()#inverse() for i in range(l-2,-1,-1): add_circ.append(RCARRY,[q2[i],q0[i],q1[i],q2[i+1]]) add_circ.append(SUM,[q2[i],q0[i],q1[i]]) return add_circ.to_instruction() def sub(q0,q1,q2,l): RCARRY=CARRY.reverse_ops() sub_circ=QuantumCircuit(q0,q1,q2,name='s\nu\nb') for i in range(l): sub_circ.append(SUM,[q2[i],q1[i],q0[i]]) if i==l-1: sub_circ.cx(q0[i],q1[i]) sub_circ.append(CARRY,[q2[i],q1[i],q0[i],q2[i+1]]) for i in range(l-2,-1,-1): sub_circ.append(RCARRY,[q2[i],q1[i],q0[i],q2[i+1]]) sub_circ.x(q2[l]) sub_circ.swap(q0,q1) return sub_circ.to_instruction() def adderMod(qr0,qr1,ac,Nr,swap_ac,t,l,ADD,SUB): # 0<=a,b<N AMC=QuantumCircuit(qr0,qr1,ac,Nr,swap_ac,t,name='a\nd\nd\ne\nr\nM\no\nd\n') BigCSwap=bigCSwap(t,qr0,swap_ac,l) BigSwap=bigSwap(qr0,Nr,l) lst=range(l) ADDIN=[qr0[i] for i in lst]+[qr1[i] for i in lst]+[ac[i] for i in lst] BigSwapIN=[qr0[i] for i in lst]+[Nr[i] for i in lst] BigCSwapIN=[t[0]]+[qr0[i] for i in lst]+[swap_ac[i] for i in lst] AMC.append(ADD,ADDIN) AMC.append(BigSwap,BigSwapIN) AMC.append(SUB,ADDIN) AMC.x(qr1[l-1]) AMC.cx(qr1[l-1],t) AMC.x(qr1[l-1]) AMC.append(BigCSwap,BigCSwapIN) AMC.append(ADD,ADDIN) AMC.append(BigCSwap,BigCSwapIN) AMC.append(BigSwap,BigSwapIN) AMC.append(SUB,ADDIN) AMC.cx(qr1[l-1],t) AMC.append(ADD,ADDIN) return AMC.to_instruction() def c_mtpMOD(circ,qr0,qr1,qr2,ac,Nr,swap_ac,t,cReg,xReg,l,n): ADD=add(qr0,qr1,ac,l) SUB=sub(qr0,qr1,ac,l) AddMOD=adderMod(qr0,qr1,ac,Nr,swap_ac,t,l,ADD,SUB) iAddMOD=AddMOD.reverse_ops() BigCCSwap=bigCCSwap(cReg,t,qr0,swap_ac,l) CCX=c_cx(cReg,xReg,qr1,n) lst=range(l) AddMODIN=[qr0[i] for i in lst]+[qr1[i] for i in lst]+[ac[i] for i in lst] AddMODIN+=[Nr[i] for i in lst]+[swap_ac[i] for i in lst]+[t[0]] for i in range(n): BigCCSwapIN=[cReg,xReg[i]]+[qr0[i] for i in lst]+[qr2[i] for i in lst] circ.append(BigCCSwap,BigCCSwapIN) circ.append(AddMOD,AddMODIN) circ.append(BigCCSwap,BigCCSwapIN) circ.x(cReg) CCXIN=[cReg[0]]+[xReg[i] for i in range(n)]+[qr1[i] for i in range(l)] circ.append(CCX,CCXIN) circ.x(cReg) return 0 def expMod(qr0,qr1,ac,circ,N,l): BigSwap=bigSwap(xReg,qr1,l) lst=range(l) BigSwapIN=[xReg[i] for i in lst]+[qr1[i] for i in lst] C_MtpMOD=c_mtpMOD(qr0,qr1,qr2,ac,Nr,swap_ac,t,cReg,xReg,l,n) iC_MtpMOD=C_MtpMOD.reverse_ops() for i in range(m): MtpMODIN circ.append(C_MtpMOD,MtpMODIN) circ.append(BigSwap,BigSwapIN) circ.append(C_MtpMOD,MtpMODIN) return None def qft(qReg): # Michael Nielsen and Isaac Chuang (2000). Quantum Computation and Quantum # Information. Cambridge: Cambridge University Press. ISBN 0-521-63503-9. # OCLC 174527496. P219, section 5.1 The quantum Fourier transform # https://qiskit.org/documentation/stubs/qiskit.circuit.library.QFT.html qft_circ=QuantumCircuit(qReg,name='Q\nF\nT\n') num=qReg.__len__() for i in range(num-1,-1,-1): qft_circ.h(qReg[i]) for j in range(i): qft_circ.append(CU1Gate(pi/2**(i-j)),[qReg[i],qReg[j]]) # Reverse the qubit order for i in range(int(num/2)):# int(0.5)=0, so odd/even does not matters qft_circ.swap(qReg[i],qReg[num-1-i]) return qft_circ.to_instruction()
https://github.com/sanori/qiskit-tips
sanori
from qiskit import QuantumCircuit qc = QuantumCircuit(1) qc.x(0) qc.draw('mpl') from qiskit.visualization import visualize_transition visualize_transition(qc) qc = QuantumCircuit(1) qc.x(0) qc.y(0) qc.h(0) qc.draw('mpl') visualize_transition(qc)
https://github.com/dwarkeshsp/quantum-bomb-tester
dwarkeshsp
import numpy as np import matplotlib.pyplot as plt from qiskit import( QuantumCircuit, QuantumRegister, execute, Aer) from qiskit.quantum_info.operators import Operator e = np.pi / 100 rotations = int(np.pi / (2*e)) shots = 10000 def elitzur_vaidman(bomb): measurements = rotations + 1 if bomb else 1 circuit = QuantumCircuit(1, measurements) rotate = Operator([ [np.cos(e), -np.sin(e)], [np.sin(e), np.cos(e)]]) for i in range(rotations): circuit.unitary(rotate, [0], label='Re') if bomb: circuit.measure(0, i) circuit.measure(0, measurements - 1) simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, simulator, shots=shots) result = job.result() counts = result.get_counts(circuit) predict_bomb = predict_no_bomb = blown_up = 0 if bomb: predict_bomb = counts['0' * measurements] zeros_one = '0' * (predict_no_bomb - 1) + '1' predict_no_bomb = counts[zeros_one] if zeros_one in counts else 0 blown_up = shots - predict_bomb - predict_no_bomb else: predict_bomb = counts['0'] if '0' in counts else 0 predict_no_bomb = counts['1'] blown_up = 0 y_pos = np.arange(3) plt.bar(y_pos, [predict_bomb, predict_no_bomb, blown_up]) plt.xticks(y_pos, ['Predicts bomb', 'Predicts no bomb', 'Blown up']) plt.ylabel('Trials') plt.title('Elitzur-Vaidman results with' + (' ' if bomb else ' no ') + 'bomb') plt.show() elitzur_vaidman(bomb=True) elitzur_vaidman(bomb=False)
https://github.com/alvinli04/Quantum-Steganography
alvinli04
import qiskit from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute from qiskit import Aer from qiskit import IBMQ from qiskit.circuit.quantumregister import AncillaRegister def comparator(regX, regY): qc = QuantumCircuit(regX, regY) # regX and regY should have the same size regLength = regX.size ancilla = AncillaRegister(2*regLength) qc.add_register(ancilla) qc.x(ancilla) for index in range(regLength): qc.x(regX[index]) qc.mcx([regY[index], regX[index]]+[ancilla[i] for i in range(2*index)], [ancilla[index*2]]) if index < regLength-1: qc.mcx([regY[index], regX[index]]+[ancilla[i] for i in range(2*index)], [ancilla[2*regLength-2]]) qc.x(regX[index]) qc.x(regY[index]) qc.mcx([regY[index], regX[index]]+[ancilla[i] for i in range(2*index)], [ancilla[index*2+1]]) if index < regLength-1: qc.mcx([regY[index], regX[index]]+[ancilla[i] for i in range(2*index)], [ancilla[2*regLength-1]]) qc.x(regY[index]) qc.x(ancilla) return qc if __name__ == '__main__': regX = QuantumRegister(2, "x") regY = QuantumRegister(2, "y") cResult = comparator(regX, regY) print("Comparator Register Output") print(comparator(regX, regY))
https://github.com/alvinli04/Quantum-Steganography
alvinli04
import qiskit from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute from qiskit import Aer from qiskit import IBMQ from qiskit.compiler import transpile from time import perf_counter from qiskit.tools.visualization import plot_histogram import numpy as np import math ''' params --------------- picture: square 2d array of integers representing grayscale values assume the length (n) is some power of 2 return --------------- a flattened representation of picture using bitstrings (boolean arrays) ''' def convert_to_bits (picture): n = len(picture) ret = [] for i in range(n): for j in range(n): value = picture[i][j] bitstring = bin(value)[2:] ret.append([0 for i in range(8 - len(bitstring))] + [1 if c=='1' else 0 for c in bitstring]) return ret ''' params ---------------- bitStr: a representation of an image using bitstrings to represent grayscale values return ---------------- A quantum circuit containing the NEQR representation of the image ''' def neqr(bitStr, quantumImage, idx, intensity): newBitStr = bitStr numOfQubits = quantumImage.num_qubits quantumImage.draw() print("Number of Qubits:", numOfQubits) # ----------------------------------- # Drawing the Quantum Circuit # ----------------------------------- lengthIntensity = intensity.size lengthIdx = idx.size quantumImage.i([intensity[lengthIntensity-1-i] for i in range(lengthIntensity)]) quantumImage.h([idx[lengthIdx-1-i] for i in range(lengthIdx)]) numOfPixels = len(newBitStr) for i in range(numOfPixels): bin_ind = bin(i)[2:] bin_ind = (lengthIdx - len(bin_ind)) * '0' + bin_ind bin_ind = bin_ind[::-1] # X-gate (enabling zero-controlled nature) for j in range(len(bin_ind)): if bin_ind[j] == '0': quantumImage.x(idx[j]) # Configuring CCNOT (ccx) gates with control and target qubits for j in range(len(newBitStr[i])): if newBitStr[i][j] == 1: quantumImage.mcx(idx, intensity[lengthIntensity-1-j]) # X-gate (enabling zero-controlled nature) for j in range(len(bin_ind)): if bin_ind[j] == '0': quantumImage.x(idx[j]) quantumImage.barrier()
https://github.com/alvinli04/Quantum-Steganography
alvinli04
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * # Loading your IBM Quantum account(s) provider = IBMQ.load_account() import qiskit from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute from qiskit import Aer from qiskit import IBMQ from qiskit.compiler import transpile from time import perf_counter from qiskit.tools.visualization import plot_histogram import numpy as np import math ''' params --------------- picture: square 2d array of integers representing grayscale values assume the length (n) is some power of 2 return --------------- a flattened representation of picture using bitstrings (boolean arrays) ''' def convert_to_bits (picture): n = len(picture) ret = [] for i in range(n): for j in range(n): value = picture[i][j] bitstring = bin(value)[2:] ret.append([0 for i in range(8 - len(bitstring))] + [1 if c=='1' else 0 for c in bitstring]) return ret ''' params ---------------- bitStr: a representation of an image using bitstrings to represent grayscale values return ---------------- A quantum circuit containing the NEQR representation of the image ''' def neqr(bitStr): newBitStr = bitStr #print(newBitStr) #print("\n") # Pixel position idx = QuantumRegister(math.ceil(math.log2(len(newBitStr))), 'idx') # Pixel intensity values intensity = QuantumRegister(8, 'intensity') # Classical Register creg = ClassicalRegister(10, 'creg') # Quantum Image Representation as a quantum circuit # with Pixel Position and Intensity registers quantumImage = QuantumCircuit(intensity, idx, creg) numOfQubits = quantumImage.num_qubits print("\n>> Initial Number of Qubits:", numOfQubits) # ----------------------------------- # Drawing the Quantum Circuit # ----------------------------------- lengthIntensity = intensity.size lengthIdx = idx.size start = perf_counter() quantumImage.i([intensity[lengthIntensity-1-i] for i in range(lengthIntensity)]) quantumImage.h([idx[lengthIdx-1-i] for i in range(lengthIdx)]) numOfPixels = len(newBitStr) for i in range(numOfPixels): bin_ind = bin(i)[2:] bin_ind = (lengthIdx - len(bin_ind)) * '0' + bin_ind bin_ind = bin_ind[::-1] # X-gate (enabling zero-controlled nature) for j in range(len(bin_ind)): if bin_ind[j] == '0': quantumImage.x(idx[j]) # Configuring Multi-Qubit Controlled-NOT (mcx) gates with control and target qubits for j in range(len(newBitStr[i])): if newBitStr[i][j] == 1: quantumImage.mcx(idx, intensity[lengthIntensity-1-j]) # X-gate (reversing the Negated state of the qubits) for j in range(len(bin_ind)): if bin_ind[j] == '0': quantumImage.x(idx[j]) quantumImage.barrier() quantumImage.measure(range(10), range(10)) end = perf_counter() print(f">> Circuit construction took {(end-start)} seconds.") return (quantumImage, intensity) if __name__ == '__main__': test_picture_2x2 = [[0, 100], [200, 255]] test_picture_3x3 = [[25, 50, 75], [100, 125, 150], [175, 200, 225]] test_picture_4x4 = [[0, 100, 143, 83], [200, 255, 43, 22], [12, 234, 23, 5], [112, 113, 117, 125]] test_picture_5x5 = [[0, 100, 212, 12, 32], [0, 100, 212, 12, 32], [0, 100, 212, 12, 32], [0, 100, 212, 12, 32], [0, 100, 212, 12, 32]] arr = convert_to_bits(test_picture_2x2) arr1 = convert_to_bits(test_picture_3x3) arr2 = convert_to_bits(test_picture_4x4) arr3 = convert_to_bits(test_picture_5x5) print("2x2: ", arr, "\n") #print("3x3: ", arr1, "\n") #print("4x4: ", arr2, "\n") #print("5x5: ", arr3, "\n") qc_image, _ = neqr(arr) qc_image.draw() # Circuit Dimensions print('>> Circuit dimensions') print('>> Circuit depth (length of critical path): ', qc_image.depth()) print('>> Total Number of Gate Operations: ', qc_image.size()) # Get the number of qubits needed to run the circuit active_qubits = {} for op in qc_image.data: if op[0].name != "barrier" and op[0].name != "snapshot": for qubit in op[1]: active_qubits[qubit.index] = True print(f">> Width: {len(active_qubits)} qubits") print(f">> Width (total number of qubits and clbits): {qc_image.width()} qubits") print(f">> Gates used: {qc_image.count_ops()}") print(f">> Fundamental Gates: {qc_image.decompose().count_ops()}") # Testing qc_image circuit using Fake Simulator # to simulate the error in a real quantum computer from qiskit.providers.aer import AerSimulator from qiskit.test.mock import FakeMontreal device_backend = FakeMontreal() sim_montreal = AerSimulator.from_backend(device_backend) #### TRANSPILING start_transpile = perf_counter() tcirc = transpile(qc_image, sim_montreal, optimization_level=1) # Optimization Level = 1 (default) end_transpile = perf_counter() print(f"\n>> Circuit transpilation took {(end_transpile-start_transpile)} seconds.") #### SIMULATING start_sim = perf_counter() # Run transpiled circuit on FakeMontreal result_noise = sim_montreal.run(tcirc).result() # Get counts for each possible result counts_noise = result_noise.get_counts() end_sim = perf_counter() print(f"\n>> Circuit simulation took {(end_sim-start_sim)} seconds.") #plot_histogram(counts_noise, figsize=(30, 15)) #print(counts_noise) from qiskit.compiler import assemble aer_sim = Aer.get_backend('aer_simulator') t_qc_image = transpile(qc_image, aer_sim) shots = 1024 qobj = assemble(t_qc_image, shots=shots) job_neqr = aer_sim.run(qobj) result_neqr = job_neqr.result() counts_neqr = result_neqr.get_counts() print('Encoded: 00 = ', arr[0]) print('Encoded: 01 = ', arr[1]) print('Encoded: 10 = ', arr[2]) print('Encoded: 11 = ', arr[3]) print("\nExpected Counts per pixel = ", shots/len(arr)) print("Experimental Counts", counts_neqr) print("\nExpected probability for each pixel = ", 1.0/(len(arr))) plot_histogram(counts_neqr) machine = "ibmq_santiago" backend = provider.get_backend(machine) santiago_sim = AerSimulator.from_backend(backend) start_sim = perf_counter() result = santiago_sim.run(qc_image).result() counts = result.get_counts(qc_image) end_sim = perf_counter() print("\n", end_sim-start_sim) print("\nExpected Counts per pixel = ", shots/len(arr), "\n") for(measured_state, count) in counts.items(): big_endian_state = measured_state[::-1] print(f"Measured {big_endian_state} {count} times.") machine = "ibmq_belem" backend = provider.get_backend(machine) santiago_sim = AerSimulator.from_backend(backend) start_sim = perf_counter() result = santiago_sim.run(qc_image).result() counts = result.get_counts(qc_image) end_sim = perf_counter() print(end_sim-start_sim) print("\nExpected Counts per pixel = ", shots/len(arr), "\n") for(measured_state, count) in counts.items(): big_endian_state = measured_state[::-1] print(f"Measured {big_endian_state} {count} times.") # Testing qc_image circuit using Fake Simulator # to simulate the error in a real quantum computer from qiskit.providers.aer import AerSimulator from qiskit.test.mock import FakeMumbai device_backend = FakeMumbai() sim_brooklyn = AerSimulator.from_backend(device_backend) #### TRANSPILING start_transpile = perf_counter() tcirc = transpile(qc_image, sim_brooklyn, optimization_level=1) # Optimization Level = 1 (default) end_transpile = perf_counter() print(f"\n>> Circuit transpilation took {(end_transpile-start_transpile)} seconds.") #### SIMULATING start_sim = perf_counter() # Run transpiled circuit on FakeMontreal result_noise = sim_brooklyn.run(tcirc).result() # Get counts for each possible result counts_noise = result_noise.get_counts() end_sim = perf_counter() print(f"\n>> Circuit simulation took {(end_sim-start_sim)} seconds.") from qiskit.test.mock import FakeMontreal fake_athens = FakeMontreal() t_qc = transpile(qc_image, fake_athens, optimization_level=3) qobj = assemble(t_qc, shots=4096) result = fake_athens.run(qobj).result() counts = result.get_counts(qc_image) print(counts) plot_histogram(counts) plot_histogram(counts, figsize=(30, 15))
https://github.com/alvinli04/Quantum-Steganography
alvinli04
import qiskit from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, AncillaRegister from qiskit import execute from qiskit import Aer from qiskit import IBMQ from qiskit.compiler import transpile from time import perf_counter from qiskit.tools.visualization import plot_histogram from qiskit.circuit.library import SXdgGate import numpy as np import neqr import random import math ''' params --------------- regY: a quantum register regX: a quantum register circuit: the circuit that contains all the register result: an empty register that will hold results return --------------- a size 2 register, c0 c1: If c1c0 = 00, then Y = X. If c1c0 = 01, then Y < X. If c1c0 = 10, then Y > X ''' def comparator(regY, regX, circuit, result): # regX and regY should have the same size regLength = regX.size ancilla = AncillaRegister(2*regLength) circuit.add_register(ancilla) circuit.x(ancilla) for index in range(regLength): circuit.x(regX[index]) circuit.mcx([regY[index], regX[index]]+[ancilla[i] for i in range(2*index)], [ancilla[index*2]]) if index < regLength-1: circuit.mcx([regY[index], regX[index]]+[ancilla[i] for i in range(2*index)], [ancilla[2*regLength-2]]) circuit.x(regX[index]) circuit.x(regY[index]) circuit.mcx([regY[index], regX[index]]+[ancilla[i] for i in range(2*index)], [ancilla[index*2+1]]) if index < regLength-1: circuit.mcx([regY[index], regX[index]]+[ancilla[i] for i in range(2*index)], [ancilla[2*regLength-1]]) circuit.x(regY[index]) circuit.x(ancilla) circuit.cx(ancilla[2*regLength-2], result[0]) circuit.cx(ancilla[2*regLength-1], result[1]) ''' params --------------- YX: a quantum register containing two coordinates, |Y>|X> AB: a quantum register containing two coordinates, |A>|B> return --------------- A single qubit |r> which is |1> when YX = AB and |0> otherwise ''' def coordinate_comparator(circuit, result, YX, AB): assert len(YX) == len(AB) n = YX.size for i in range(n): circuit.x(YX[i]) circuit.cx(YX[i], AB[i]) circuit.x(YX[i]) circuit.mcx(AB, result) for i in range(n): circuit.x(YX[i]) circuit.cx(YX[i], AB[i]) circuit.x(YX[i]) ''' params --------------- Y: a quantum register X: a quantum register difference: an empty quantum register the same size as X and Y return --------------- A quantum register |D> which holds the positive difference of Y and X. ''' def difference(circuit, Y, X, difference): assert len(Y) == len(X) # PART 1: # reversible parallel subtractor # initialize registers to store sign, difference, and junk qubits regLength = X.size sign = QuantumRegister(1) ancilla = QuantumRegister(regLength - 1) circuit.add_register(ancilla) circuit.add_register(sign) # perform half subtractor for last qubit rev_half_subtractor(circuit, X[-1], Y[-1], difference[-1], ancilla[-1]) # perform full subtrator for rest of qubits for i in range(regLength - 2, 0, -1): rev_full_subtractor(circuit, X[i], Y[i], ancilla[i], difference[i], ancilla[i-1]) rev_full_subtractor(circuit, X[0], Y[0], ancilla[0], difference[0], sign[0]) # swap X and difference registers to fix result # this is just sort of a thing you have to do for i in range(regLength - 1, -1, -1): circuit.swap(difference[i], X[i]) # PART 2: # complementary operation # flip the difference based on the sign (pt 1) for i in range(regLength): circuit.cx(sign[0], difference[i]) # flip the difference again, but based on sign and remaining bits (pt 2) #for i in range(regLength-1, -1, -1): for i in range(regLength): circuit.mcx([sign[0]] + difference[i+1:], difference[i]) ''' params --------------- regA: a quantum register, one of the numbers being subtracted regB: a quantum register, one of the numbers being subtracted Q: Updated depending on result Borrow: Digit to be carried over return --------------- Performs A - B, and updates results into Q and Borrow ''' def rev_half_subtractor(circuit, A, B, Q, Borrow): csxdg_gate = SXdgGate().control() circuit.append(csxdg_gate, [A, Borrow]) circuit.cx(A, Q) circuit.cx(B, A) circuit.csx(B, Borrow) circuit.csx(A, Borrow) circuit.barrier() ''' params --------------- regA: a quantum register, one of the numbers being subtracted regB: a quantum register, one of the numbers subtracting regC: a quantum register, one of the numbers subtracting Q: Updated depending on result Borrow: Digit to be carried over return --------------- Performs A - B - C, updates results into Q and Borrow ''' def rev_full_subtractor(circuit, A, B, C, Q, Borrow): csxdg_gate = SXdgGate().control() circuit.append(csxdg_gate, [A, Borrow]) circuit.cx(A, Q) circuit.cx(B, A) circuit.csx(B, Borrow) circuit.cx(C, A) circuit.csx(C, Borrow) circuit.csx(A, Borrow) circuit.barrier() def controlled_difference(controlled_qubit, circuit, Y, X, difference): # PART 1: # reversible parallel subtractor # initialize registers to store sign, difference, and junk qubits regLength = X.size sign = QuantumRegister(1, 'sign') ancilla = QuantumRegister(regLength - 1, 'junk') circuit.add_register(ancilla) circuit.add_register(sign) # perform half subtractor for last qubit controlled_rhs(controlled_qubit, circuit, X[-1], Y[-1], difference[-1], ancilla[-1]) # perform full subtrator for rest of qubits for i in range(regLength - 2, 0, -1): controlled_rfs(controlled_qubit, circuit, X[i], Y[i], ancilla[i], difference[i], ancilla[i-1]) controlled_rfs(controlled_qubit, circuit, X[0], Y[0], ancilla[0], difference[0], sign[0]) # swap X and difference registers to fix result # this is just sort of a thing you have to do for i in range(regLength - 1, -1, -1): circuit.cswap(controlled_qubit, difference[i], X[i]) # PART 2: # complementary operation # flip the difference based on the sign (pt 1) for i in range(regLength): circuit.ccx(controlled_qubit, sign[0], difference[i]) # flip the difference again, but based on sign and remaining bits (pt 2) #for i in range(regLength-1, -1, -1): for i in range(regLength): circuit.mcx([controlled_qubit] + [sign[0]] + difference[i+1:], difference[i]) # controlled reversible half subtractor def controlled_rhs(controlled_qubit, circuit, A, B, Q, Borrow): # allocate ancilla qubits anc1 = QuantumRegister(3) circuit.add_register(anc1) # rewritten code to control for given qubit csxdg_gate = SXdgGate().control() circuit.ccx(controlled_qubit, A, anc1[0]) circuit.append(csxdg_gate, [anc1[0], Borrow]) circuit.ccx(controlled_qubit, A, Q) circuit.ccx(controlled_qubit, B, A) circuit.ccx(controlled_qubit, B, anc1[1]) circuit.ccx(controlled_qubit, A, anc1[2]) circuit.csx(anc1[1], Borrow) circuit.csx(anc1[2], Borrow) circuit.barrier() # controlled reversible full subtractor def controlled_rfs(controlled_qubit, circuit, A, B, C, Q, Borrow): # allocate ancilla qubits anc2 = QuantumRegister(4) circuit.add_register(anc2) # rewritten code to control for given qubit csxdg_gate = SXdgGate().control() circuit.ccx(controlled_qubit, A, anc2[0]) circuit.append(csxdg_gate, [anc2[0], Borrow]) circuit.cx(A, Q) circuit.cx(B, A) circuit.ccx(controlled_qubit, B, anc2[1]) circuit.csx(anc2[1], Borrow) circuit.cx(C, A) circuit.ccx(controlled_qubit, C, anc2[2]) circuit.csx(anc2[2], Borrow) circuit.ccx(controlled_qubit, A, anc2[3]) circuit.csx(anc2[3], Borrow) circuit.barrier() ''' Embedding Procedure ''' ''' params ------------------ k: the number of binary images binary_images: a list of 2^n by 2^n binary images to construct the secret image assume they are all the same size return ------------------- the secret image ''' def get_secret_image(k, binary_images): n = len(binary_images[0][0]) secret_image = [['' for i in range(n)] for j in range(n)] for i in range(k): for j in range(n): for l in range(n): secret_image[j][l] += str(binary_images[i][j][l]) return secret_image ''' params -------------------- secret_image: a quantum circuit containing the secret image intensity: a quantum register in secret_image that contains the intensity returns -------------------- nothing ''' def invert(secret_image, intensity, inverse): secret_image.x(intensity) for i in range(len(intensity)): secret_image.cx(intensity[i], inverse[i]) secret_image.x(intensity) ''' params ------------------ circuit: the quantum circuit containing all the images key: an empty key register, to be modified cover: the quantum cover image secret: the quantum secret image inv_secret: the inverse secret image image_size: total size of the image diff1: holds difference between cover and secret diff2: holds difference between cover and inverse secret image_size: number of pixels ''' def get_key(circuit, key_idx, key_result, cover_intensity, secret_intensity, inv_secret_intensity, diff1, diff2, comp_result, image_size): circuit.h(key_idx) difference(circuit, cover_intensity, secret_intensity, diff1) difference(circuit, cover_intensity, inv_secret_intensity, diff2) comparator(diff1, diff2, circuit, comp_result) circuit.x(comp_result[1]) for i in range(image_size): bin_ind = bin(i)[2:] bin_ind = (len(key_idx) - len(bin_ind)) * '0' + bin_ind bin_ind = bin_ind[::-1] # X-gate (enabling zero-controlled nature) for j in range(len(bin_ind)): if bin_ind[j] == '0': circuit.x(key_idx[j]) circuit.mcx(comp_result[:] + key_idx[:], key_result) # X-gate (enabling zero-controlled nature) for j in range(len(bin_ind)): if bin_ind[j] == '0': circuit.x(key_idx[j]) circuit.x(comp_result[1]) def embed(circuit, C, S, Key, cover_image_values, secret_image_values, key_i): # removed code. can be used for unit test ''' #preperation array = [[random.randint(0, 255), random.randint(0, 255)], [random.randint(0, 255), random.randint(0, 255)]] print(array) bits_array = neqr.convert_to_bits(array) print(bits_array) #setting up the images, difference registers, and circuiit _, cover_image_values = neqr.neqr(bits_array) _, secret_image_values = neqr.neqr(bits_array) circuit = QuantumCircuit(cover_image_values, secret_image_values, difference_1, difference_2) ''' #part 1: #carrying out the coordinate comparators coord_result = QuantumRegister(2, 'coord_result') circuit.add_register(coord_result) coordinate_comparator(circuit, coord_result, C, S) #getting the key through getKey (once its done) coordinate_comparator(circuit, coord_result, C, Key) #adding outputs to the circuit circuit.add_register(coord_result[0]) circuit.add_register(coord_result[1]) #part 2: #need to make a controlled difference method :( diff1_result = QuantumRegister(C.size, 'diff1_result') circuit.add_register(diff1_result) controlled_difference(coord_result[0], circuit, cover_image_values, secret_image_values, diff1_result) #after this, secret_image_values are inverted invert(circuit, secret_image_values) #computing difference again diff2_result = QuantumRegister(C.size, 'diff2_result') circuit.add_register(diff2_result) difference(circuit,cover_image_values, secret_image_values, diff2_result) #comparing the differences comparator_result = QuantumRegister(2, "compare_result") circuit.add_register(comparator_result) comparator(circuit, diff2_result, diff1_result, comparator_result) # flip for zero-controlled ccnots circuit.x(comparator_result[1]) circuit.ccx(coord_result[0], comparator_result[1], cover_image_values) circuit.ccx(coord_result[0], comparator_result[1], secret_image_values) circuit.x(comparator_result[1]) # flip back # do a cute little toffoli cascade for the cccswap and cccx anc = QuantumRegister(2) # allocate ancilla qubits circuit.add_register(anc) circuit.ccx(coord_result[0], coord_result[1], anc[0]) circuit.ccx(anc[0], comparator_result[1], anc[1]) circuit.cswap(anc[2], cover_image_values, secret_image_values) # cccswap circuit.cx(comparator_result[1], key_i) # cccnot def extract(circuit, key_idx, key_val, cs_idx, cs_val, extracted, comp_result, k): for i in range(k): circuit.cx(cs_val[len(cs_val) - k - 1 + i], extracted[i]) coordinate_comparator(circuit, comp_result, key_idx, cs_idx) for i in range(image_size): bin_ind = bin(i)[2:] bin_ind = (len(key_idx) - len(bin_ind)) * '0' + bin_ind bin_ind = bin_ind[::-1] # X-gate (enabling zero-controlled nature) for j in range(len(bin_ind)): if bin_ind[j] == '0': circuit.x(cs_idx[j]) circuit.mcx(comp_result[:] + cs_idx[:], extracted) # X-gate (enabling zero-controlled nature) for j in range(len(bin_ind)): if bin_ind[j] == '0': circuit.x(cs_idx[j])