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): result = self.backend.run(qobj, noise_model=noise_model_wrapper()).result() if result.status != 'COMPLETED': raise QiskitError("Simulation failed. Status: " + result.status)
def custom_gate(): print("\ncustom gate") # Use Aer's qasm_simulator simulator = QasmSimulator() # Create a Quantum Circuit acting on the q register qr = QuantumRegister(1) cr = ClassicalRegister(1) circuit = QuantumCircuit(qr, cr) # Add a H gate on qubit 0 # circuit.h(0) # hadamard gate from a matrix v = (1 / np.sqrt(2)) u = np.array([[v, v], [v, -v]]) # qu = qiskit.extensions.UnitaryGate(u) myh = Operator(u) circuit.unitary(myh, qr[0], label='mygate') cx = Operator([ [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0] ]) print(cx) h = Operator(qiskit.circuit.library.HGate()) print(h) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1 #circuit.cx(0, 1) # Map the quantum measurement to the classical bits circuit.measure(qr, cr) # compile the circuit down to low-level QASM instructions # supported by the backend (not needed for simple circuits) compiled_circuit = transpile(circuit, simulator) # Execute the circuit on the qasm simulator job = simulator.run(compiled_circuit, shots=100) # Grab results from the job result = job.result() # Draw the circuit # circuit.draw() print(circuit) circuit.draw(output='mpl', filename='E:\_Ricks\Python\Qiskit1\circuit1.png') # Returns counts counts = result.get_counts(circuit) print("\nTotal count for 00 and 11 are:", counts)
def HalfAdder(): print("\nAdder") # Use Aer's qasm_simulator simulator = QasmSimulator() circuit = QuantumCircuit(4, 2) # circuit.x(0) circuit.h(0) # circuit.x(1) circuit.h(1) circuit.barrier() circuit.cx(0, 2) circuit.cx(1, 2) circuit.ccx(0, 1, 3) circuit.barrier() # circuit.measure(2, 0) # circuit.measure(3, 1) circuit.measure([2, 3], [0, 1]) circuit.barrier() print(circuit) # compile the circuit down to low-level QASM instructions # supported by the backend (not needed for simple circuits) compiled_circuit = transpile(circuit, simulator) # Execute the circuit on the qasm simulator job = simulator.run(compiled_circuit, shots=1000) # Grab results from the job result = job.result() counts = result.get_counts(circuit) print("\nTotal counts are:", counts)
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)
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)
def Adder1(): print("\nAdder 1") # Use Aer's qasm_simulator simulator = QasmSimulator() qc_cnot = QuantumCircuit(2, 2) qc_cnot.x(0) qc_cnot.x(1) qc_cnot.cx(0, 1) # qc_cnot.measure([0,1], [0,1]) qc_cnot.measure(0, 0) qc_cnot.measure(1, 1) print(qc_cnot) # compile the circuit down to low-level QASM instructions # supported by the backend (not needed for simple circuits) compiled_circuit = transpile(qc_cnot, simulator) # Execute the circuit on the qasm simulator job = simulator.run(compiled_circuit, shots=100) # Grab results from the job result = job.result() counts = result.get_counts(qc_cnot) print("\nTotal counts are:", counts)
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, backend_options={ 'fusion_enable': fusion_enable }).result() if result.status != 'COMPLETED': raise QiskitError("Simulation failed. Status: " + result.status)
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)], backend_options={ 'fusion_enable': fusion_enable }).result() if result.status != 'COMPLETED': raise QiskitError("Simulation failed. Status: " + result.status)
class QuantumFourierTransformTimeSuite: """ Benchmarking times for Quantum Fourier Transform 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.qft_circuits = [] self.backend = QasmSimulator() for num_qubits in (5, 10, 15): circ = quantum_fourier_transform_circuit(num_qubits) circ = transpile(circ) qobj = assemble(circ, self.backend, shots=1) self.qft_circuits.append(qobj) self.param_names = ["Quantum Fourier Transform", "Noise Model"] # This will run every benchmark for one of the combinations we have here: # 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() ]) def setup(self, qobj, noise_model_wrapper): pass def time_quantum_fourier_transform(self, qobj, 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)
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( Terra.compile(circuit, self.backend, shots=1) ) self.param_names = [ "Simple u3 circuits (5/16/20/30 qubits)", "Noise model" ] self.params = ( self.circuits, [ None, mixed_unitary_noise_model(), reset_noise_model(), kraus_noise_model() ] ) def time_simple_u3(self, qobj, noise_model): result = self.backend.run( qobj, noise_model=noise_model ).result() if result.status != 'COMPLETED': raise QiskitError("Simulation failed. Status: " + result.status)
def circuit2(): print("\nCircuit 2") # Use Aer's qasm_simulator simulator = QasmSimulator() # Create a Quantum Circuit acting on the q register circuit = QuantumCircuit(3, 3, name="Circuit2") # Add a H gate on qubit 0 circuit.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1 circuit.cx(0, 1) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1 circuit.cx(0, 2) # Map the quantum measurement to the classical bits circuit.measure([0,1,2], [0,1,2]) # # compile the circuit down to low-level QASM instructions # supported by the backend (not needed for simple circuits) compiled_circuit = transpile(circuit, simulator) # Execute the circuit on the qasm simulator job = simulator.run(compiled_circuit, shots=100) # Grab results from the job result = job.result() # Draw the circuit #circuit.draw() print(circuit) circuit.draw(output='mpl', filename='E:\_Ricks\Python\Qiskit1\circuit2.png') # Returns counts counts = result.get_counts(circuit) print("\nTotal counts are:",counts)
# The Qiskit circuit object supports composition. # Here the meas has to be first and front=True (putting it before) # as compose must put a smaller circuit into a larger one. qc = meas.compose(circ, range(3), front=True) #drawing the circuit qc.draw('mpl') # Adding the transpiler to reduce the circuit to QASM instructions # supported by the backend from qiskit import transpile # Use Aer's qasm_simulator from qiskit.providers.aer import QasmSimulator from qiskit.providers.models import BackendConfiguration backend = QasmSimulator() # First we have to transpile the quantum circuit # to the low-level QASM instructions used by the # backend qc_compiled = transpile(qc, backend) # Execute the circuit on the qasm simulator. # We've set the number of repeats of the circuit # to be 1024, which is the default. job_sim = backend.run(qc, shots=1024) # Grab the results from the job. result_sim = job_sim.result()
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 16 ,: for depth in 10 ,: # We want always the same seed, as we want always the same circuits # for the same value pairs of qubits,depth circ = quantum_volume_circuit(num_qubits, depth, seed=1) self.qv_circuits.append( Terra.compile(circ, self.backend, shots=1) ) self.param_names = [ "Quantum Volume (16qubits 10depth)", "Noise Model" ] # This will run every benchmark for one of the combinations we have here: # bench(qv_circuits, None) => bench(qv_circuits, mixed()) => # bench(qv_circuits, reset) => bench(qv_circuits, kraus()) self.params = ( self.qv_circuits, [ None, mixed_unitary_noise_model(), reset_noise_model(), kraus_noise_model() ] ) def setup(self, qobj): pass def time_quantum_volume(self, qobj, noise_model): result = self.backend.run( qobj, noise_model=noise_model ).result() if result.status != 'COMPLETED': raise QiskitError("Simulation failed. Status: " + result.status)
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)
return model, schedule if __name__ == '__main__': # Run qasm simulator shots = 2000 circuits = grovers_circuit(final_measure=True, allow_sampling=True) targets = [{ '0x0': 5 * shots / 8, '0x1': shots / 8, '0x2': shots / 8, '0x3': shots / 8 }] simulator = QasmSimulator() qobj = assemble(transpile(circuits, simulator), simulator, shots=shots) result = simulator.run(qobj).result() assert result.status == 'COMPLETED' compare_counts(result, circuits, targets, delta=0.05 * shots) assert result.success is True # Run statevector simulator circuits = cx_gate_circuits_deterministic(final_measure=False) targets = cx_gate_statevector_deterministic() job = execute(circuits, StatevectorSimulator(), shots=1) result = job.result() assert result.status == 'COMPLETED' assert result.success is True compare_statevector(result, circuits, targets) # Run unitary simulator circuits = cx_gate_circuits_deterministic(final_measure=False)
# Add a H gate on qubit 0 circuit.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1 circuit.cx(0, 1) # Map the quantum measurement to the classical bits circuit.measure([0, 1], [0, 1]) # compile the circuit down to low-level QASM instructions # supported by the backend (not needed for simple circuits) compiled_circuit = transpile(circuit, simulator) # Execute the circuit on the qasm simulator job = simulator.run(compiled_circuit, shots=1000) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(compiled_circuit) print("\nTotal count for 00 and 11 are:", counts) # Draw the circuit #circuit.draw() print(circuit) circuit.draw(output='mpl', filename='my_circuit.png') qiskit.visualization.circuit_drawer(circuit)
import timeit import matplotlib.pyplot as plt import math from quantumvolume import quantum_volume_circuit qubit = 10 depth = 10 measure = True seed = 0 shots = 1024 simulator = QasmSimulator() parallel_shots_list = {1, 5, 10, 20, 30, 40, 50, 60, 70, 80} circuit = quantum_volume_circuit(qubit, depth, measure, seed) qobj = assemble(circuit, simulator, shots=shots) for parallel_shots in parallel_shots_list: backend_opts = { 'max_parallel_threads': 80, 'max_parallel_shots': parallel_shots, 'parallel_state_update': 80 / parallel_shots } result = simulator.run(qobj, backend_options=backend_opts).result() print(80, parallel_shots, 80 / parallel_shots, result.metadata['time_taken'])