repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/thyung/qiskit_factorization
thyung
import numpy as np from numpy import pi # importing Qiskit from qiskit import QuantumCircuit, transpile, assemble, Aer from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(3) qc.h(2) qc.cp(pi/2, 1, 2) qc.cp(pi/4, 0, 2) qc.h(1) qc.cp(pi/2, 0, 1) qc.h(0) qc.swap(0, 2) qc.draw() def qft_rotations(circuit, n): if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) qft_rotations(circuit, n) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft(circuit, n): qft_rotations(circuit, n) swap_registers(circuit, n) return circuit qc = QuantumCircuit(4) qft(qc,4) qc.draw() # Create the circuit qc = QuantumCircuit(3) # Encode the state 5 (101 in binary) qc.x(0) qc.x(2) qc.draw() sim = Aer.get_backend("aer_simulator") qc_init = qc.copy() qc_init.save_statevector() statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) qft(qc, 3) qc.draw() qc.save_statevector() statevector = sim.run(qc).result().get_statevector() plot_bloch_multivector(statevector)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.quantumcircuitdata import CircuitInstruction from qiskit.circuit import Measure from qiskit.circuit.library import HGate, CXGate qr = QuantumRegister(2) cr = ClassicalRegister(2) instructions = [ CircuitInstruction(HGate(), [qr[0]], []), CircuitInstruction(CXGate(), [qr[0], qr[1]], []), CircuitInstruction(Measure(), [qr[0]], [cr[0]]), CircuitInstruction(Measure(), [qr[1]], [cr[1]]), ] circuit = QuantumCircuit.from_instructions(instructions) circuit.draw("mpl")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import HGate qr = QuantumRegister(3) qc = QuantumCircuit(qr) c3h_gate = HGate().control(2) qc.append(c3h_gate, qr) qc.draw('mpl')
https://github.com/dcavar/q
dcavar
!pip install -U qiskit !pip install -U qiskit_ibm_provider from qiskit import transpile from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_ibm_runtime.fake_provider import FakeManilaV2 q = QuantumRegister(2,'q') c = ClassicalRegister(2,'c') circuit = QuantumCircuit(q,c) circuit.h(q) circuit.cx(q[0], q[1]) circuit.measure(q,c) fake_manila = FakeManilaV2() pm = generate_preset_pass_manager(backend=fake_manila, optimization_level=1) isa_qc = pm.run(circuit) print(isa_qc) new_circuit = transpile(circuit, fake_manila) job = fake_manila.run(new_circuit, shots=100) res = job.result() print('Result:', res)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 100 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(qr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / num_steps}) print("created qc") # Generate state tomography circuits to evaluate fidelity of simulation st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === print("created st_qcs (length:", len(st_qcs), ")") # remove barriers st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] print("removed barriers from st_qcs") # optimize circuit t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling print("created zne_qcs (length:", len(zne_qcs), ")") # optimization_level must be 0 # feed initial_layout here to see the picture of the circuits before casting the job t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")") t3_zne_qcs[-3].draw("mpl") from qiskit.test.mock import FakeJakarta backend = FakeJakarta() # backend = Aer.get_backend("qasm_simulator") # IBMQ.load_account() # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") print(str(backend)) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): #! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) # QREM qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') # we have to feed initial_layout to calibration matrix cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) meas_calibs[0].draw("mpl") dt_now = datetime.datetime.now() print(dt_now) filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl" print(filename) # with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump({"jobs": jobs, "cal_job": cal_job}, f) # with open(filename, "wb") as f: # pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f) # with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: # pickle.dump(backend.properties(), f) retrieved_jobs = jobs retrieved_cal_job = cal_job cal_results = retrieved_cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! fids = [] for job in retrieved_jobs: mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors) rho = expvals_to_valid_rho(num_qubits, zne_expvals) fid = state_fidelity(rho, target_state) fids.append(fid) print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
https://github.com/quantumyatra/quantum_computing
quantumyatra
from qiskit import IBMQ #token = open('/Users/gshyam/projects/work_projects/machine_learning/ANPA_dataScience/Python2020/TOKEN_BMQ','r') #print (token) #IBMQ.save_account(token) #IBMQ.save_account('dbf31c5ec55e2b7914fe280fe04980f4edd8efa6063471bd9bc4e3617e7cc8348819917b6a01a4e106d8ef02c33f9abbf2920ceb9bbe44056eaec59eb1e910d3') from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute, BasicAer from qiskit.visualization import plot_bloch_multivector import numpy as np import matplotlib.pyplot as plt %matplotlib inline import qiskit print (qiskit.__version__) print (qiskit.__qiskit_version__) IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() for backend in provider.backends(): print(backend.status()) real_device = provider.get_backend('ibmq_16_melbourne') properties = real_device.properties() coupling_map = real_device.configuration().coupling_map from qiskit.providers.aer.noise import NoiseModel noise_model = NoiseModel.from_backend(properties) qc = QuantumCircuit(2,2) qc.x(1) # CNOT gate converts (00) qc.measure(0,0) qc.measure(1,1) simulator = Aer.get_backend('qasm_simulator') job = execute(qc, simulator, shots=1024, noise_model=noise_model, coupling_map=coupling_map, basis_gates=noise_model.basis_gates) job.result().get_counts() n=8 qc_encode = QuantumCircuit(n) qc_encode.x(7) qc_encode.draw(output='mpl') qc_output = QuantumCircuit(n, n) for j in range(n): qc_output.measure(j,j) qc_output.draw(output='mpl') job = execute(qc_output, Aer.get_backend('quasm_simulator'))#.result().get_counts()
https://github.com/DaisukeIto-ynu/KosakaQ
DaisukeIto-ynu
# 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 """ Simulator command to snapshot internal simulator representation. """ from warnings import warn from qiskit import QuantumCircuit from .snapshot import Snapshot class SnapshotProbabilities(Snapshot): """Snapshot instruction for all methods of Qasm simulator.""" def __init__(self, label, num_qubits, variance=False): """Create a probability snapshot instruction. Args: label (str): the snapshot label. num_qubits (int): the number of qubits to snapshot. variance (bool): compute variance of probabilities [Default: False] Raises: ExtensionError: if snapshot is invalid. .. deprecated:: 0.9.0 This instruction has been deprecated and will be removed no earlier than 3 months from the 0.9.0 release date. It has been superseded by the :class:`qiskit.providers.aer.library.SaveProbabilities` and :class:`qiskit.providers.aer.library.SaveProbabilitiesDict` instructions. """ warn('The `SnapshotProbabilities` instruction has been deprecated as of' ' qiskit-aer 0.9. It has been superseded by the `SaveProbabilities` and' ' `SaveProbabilitiesDict` instructions.', DeprecationWarning, stacklevel=2) snapshot_type = 'probabilities_with_variance' if variance else 'probabilities' super().__init__(label, snapshot_type=snapshot_type, num_qubits=num_qubits) def snapshot_probabilities(self, label, qubits, variance=False): """Take a probability snapshot of the simulator state. Args: label (str): a snapshot label to report the result qubits (list): the qubits to snapshot. variance (bool): compute variance of probabilities [Default: False] Returns: QuantumCircuit: with attached instruction. Raises: ExtensionError: if snapshot is invalid. .. deprecated:: 0.9.0 This instruction has been deprecated and will be removed no earlier than 3 months from the 0.9.0 release date. It has been superseded by the :func:`qiskit.providers.aer.library.save_probabilities` and :func:`qiskit.providers.aer.library.save_probabilities_dict` circuit methods. """ warn('The `snapshot_probabilities` circuit method has been deprecated as of' ' qiskit-aer 0.9. It has been superseded by the `save_probabilities`' ' and `save_probabilities_dict` circuit methods.', DeprecationWarning) snapshot_register = Snapshot.define_snapshot_register(self, qubits=qubits) return self.append( SnapshotProbabilities(label, num_qubits=len(snapshot_register), variance=variance), snapshot_register) QuantumCircuit.snapshot_probabilities = snapshot_probabilities
https://github.com/rohitgit1/Quantum-Computing-Summer-School
rohitgit1
!pip install -U -r grading_tools/requirements.txt from IPython.display import clear_output clear_output() import numpy as np; pi = np.pi from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram from copy import deepcopy as make_copy def prepare_hets_circuit(depth, angle1, angle2): hets_circ = QuantumCircuit(depth) hets_circ.ry(angle1, 0) hets_circ.rz(angle1, 0) hets_circ.ry(angle1, 1) hets_circ.rz(angle1, 1) for ii in range(depth): hets_circ.cx(0,1) hets_circ.ry(angle2,0) hets_circ.rz(angle2,0) hets_circ.ry(angle2,1) hets_circ.rz(angle2,1) return hets_circ hets_circuit = prepare_hets_circuit(2, pi/2, pi/2) hets_circuit.draw() def measure_zz_circuit(given_circuit): zz_meas = make_copy(given_circuit) zz_meas.measure_all() return zz_meas zz_meas = measure_zz_circuit(hets_circuit) zz_meas.draw() simulator = Aer.get_backend('qasm_simulator') result = execute(zz_meas, backend = simulator, shots=10000).result() counts = result.get_counts(zz_meas) plot_histogram(counts) def measure_zz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zz = counts['00'] + counts['11'] - counts['01'] - counts['10'] zz = zz / total_counts return zz zz = measure_zz(hets_circuit) print("<ZZ> =", str(zz)) def measure_zi(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] zi = counts['00'] - counts['11'] + counts['01'] - counts['10'] zi = zi / total_counts return zi def measure_iz(given_circuit, num_shots = 10000): zz_meas = measure_zz_circuit(given_circuit) result = execute(zz_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(zz_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] iz = counts['00'] - counts['11'] - counts['01'] + counts['10'] iz = iz / total_counts return iz zi = measure_zi(hets_circuit) print("<ZI> =", str(zi)) iz = measure_iz(hets_circuit) print("<IZ> =", str(iz)) def measure_xx_circuit(given_circuit): xx_meas = make_copy(given_circuit) ### WRITE YOUR CODE BETWEEN THESE LINES - START xx_meas.h(0) xx_meas.h(1) xx_meas.measure_all() ### WRITE YOUR CODE BETWEEN THESE LINES - END return xx_meas xx_meas = measure_xx_circuit(hets_circuit) xx_meas.draw() def measure_xx(given_circuit, num_shots = 10000): xx_meas = measure_xx_circuit(given_circuit) result = execute(xx_meas, backend = simulator, shots = num_shots).result() counts = result.get_counts(xx_meas) if '00' not in counts: counts['00'] = 0 if '01' not in counts: counts['01'] = 0 if '10' not in counts: counts['10'] = 0 if '11' not in counts: counts['11'] = 0 total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10'] xx = counts['00'] + counts['11'] - counts['01'] - counts['10'] xx = xx / total_counts return xx xx = measure_xx(hets_circuit) print("<XX> =", str(xx)) def get_energy(given_circuit, num_shots = 10000): zz = measure_zz(given_circuit, num_shots = num_shots) iz = measure_iz(given_circuit, num_shots = num_shots) zi = measure_zi(given_circuit, num_shots = num_shots) xx = measure_xx(given_circuit, num_shots = num_shots) energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx return energy energy = get_energy(hets_circuit) print("The energy of the trial state is", str(energy)) hets_circuit_plus = None hets_circuit_minus = None ### WRITE YOUR CODE BETWEEN THESE LINES - START hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2) hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2) ### WRITE YOUR CODE BETWEEN THESE LINES - END energy_plus = get_energy(hets_circuit_plus, num_shots=100000) energy_minus = get_energy(hets_circuit_minus, num_shots=100000) print(energy_plus, energy_minus) name = 'Pon Rahul M' email = 'ponrahul.21it@licet.ac.in' ### Do not change the lines below from grading_tools import grade grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1') grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2') grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3') energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0 energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0 ### WRITE YOUR CODE BETWEEN THESE LINES - START energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100) energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100) energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000) energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000) energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000) energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000) ### WRITE YOUR CODE BETWEEN THESE LINES - END print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100) print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000) print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000) ### WRITE YOUR CODE BETWEEN THESE LINES - START I = np.array([ [1, 0], [0, 1] ]) X = np.array([ [0, 1], [1, 0] ]) Z = np.array([ [1, 0], [0, -1] ]) h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \ (0.39793742) * np.kron(I, Z) + \ (-0.3979374) * np.kron(Z, I) + \ (-0.0112801) * np.kron(Z, Z) + \ (0.18093119) * np.kron(X, X) from numpy import linalg as LA eigenvalues, eigenvectors = LA.eig(h2_hamiltonian) for ii, eigenvalue in enumerate(eigenvalues): print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}") exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)] exact_eigenvalue = np.min(eigenvalues) print() print("Minimum energy is", exact_eigenvalue) ### WRITE YOUR CODE BETWEEN THESE LINES - END
https://github.com/kosakhro/QAOA-for-exact-cover
kosakhro
from qiskit import * from qiskit.visualization import plot_bloch_multivector from qiskit.visualization import plot_histogram import numpy as np import matplotlib.pyplot as plt import seaborn as sns IBMQ.load_account() matplotlib inline my_provider = IBMQ.get_provider() my_provider.backends() simulator = my_provider.get_backend('ibmq_5_yorktown') # Making the quantum circuit def circuitI(gamma, beta, J, h1, h2): qc = QuantumCircuit(2, 2) qc.h([0, 1]) qc.h(1) qc.cz(0,1) qc.rx(2*gamma*J, 1) qc.cz(0,1) qc.h(1) qc.i(0) qc.rz(2*gamma*h1, 0) qc.rz(2*gamma*h2, 1) qc.rx(2*beta, 0) qc.rx(2*beta, 1) qc.measure([0,1], [0,1]) return qc # Initializing the variables for B. J = 0 h1 = -1 h2 = 0 #Setting the dimesions of the pasephase. The amount of simulated points = n**2 n = 61 p = np.pi/(n-1) res = np.zeros([n, n, 4]) # Running a simulation for each point for i in range(n): qc_list = [] gamma = i*p for j in range(n): beta = j*p qc = circuitI(gamma, beta, J, h1, h2) qc_list.append(qc) transpiled_circs = transpile(qc_list, backend=simulator) job = execute(transpiled_circs, backend = simulator, shots=1000 ) for circ_index in range(len(transpiled_circs)): counts = job.result().get_counts(qc_list[circ_index]) res[i][circ_index][:] = np.array([int(counts.get('00', 0)), int(counts.get('01', 0)), int(counts.get('10', 0)), int(counts.get('11', 0))]) print(res) #Draw the current circuit qc.draw(output='mpl') transpiled_circs[0].draw(output='mpl') # Making a heatmap plot sns.heatmap(res[:, :, 1]+res[:, :, 3])
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, assemble, Aer from qiskit.tools.visualization import plot_histogram from math import pi import matplotlib.pyplot as plt q = QuantumRegister(1,'q') c = ClassicalRegister(1,'c') qc = QuantumCircuit(q, c) qc.h(0) qc.measure(0,0) qc.x(0).c_if(c, 0) qc.draw(output='mpl') q = QuantumRegister(3,'q') c = ClassicalRegister(3,'c') qc = QuantumCircuit(q, c) qc.h(q[0]) qc.h(q[1]) qc.h(q[2]) qc.barrier() qc.measure(q,c) qc.draw('mpl') print(bin(3)) print(bin(7)) q = QuantumRegister(3,'q') c = ClassicalRegister(3,'c') qc = QuantumCircuit(q, c) qc.h(0) qc.h(1) qc.h(2) qc.barrier() qc.measure(q,c) qc.x(2).c_if(c, 3) # for the 011 case qc.x(2).c_if(c, 7) # for the 111 case qc.draw(output='mpl') nq = 2 m = 2 q = QuantumRegister(nq,'q') c = ClassicalRegister(m,'c') qc_S = QuantumCircuit(q,c) qc_S.h(0) qc_S.x(1) qc_S.draw('mpl') cu_circ = QuantumCircuit(2) cu_circ.cp(pi/2,0,1) cu_circ.draw('mpl') for _ in range(2**(m-1)): qc_S.cp(pi/2,0,1) qc_S.draw('mpl') def x_measurement(qc, qubit, cbit): """Measure 'qubit' in the X-basis, and store the result in 'cbit'""" qc.h(qubit) qc.measure(qubit, cbit) x_measurement(qc_S, q[0], c[0]) qc_S.draw('mpl') qc_S.reset(0) qc_S.h(0) qc_S.draw('mpl') qc_S.p(-pi/2,0).c_if(c,1) qc_S.draw('mpl') ## 2^t c-U operations (with t=m-2) for _ in range(2**(m-2)): qc_S.cp(pi/2,0,1) x_measurement(qc_S, q[0], c[1]) qc_S.draw('mpl') sim = Aer.get_backend('qasm_simulator') count0 = execute(qc_S, sim).result().get_counts() key_new = [str(int(key,2)/2**m) for key in list(count0.keys())] count1 = dict(zip(key_new, count0.values())) fig, ax = plt.subplots(1,2) plot_histogram(count0, ax=ax[0]) plot_histogram(count1, ax=ax[1]) plt.tight_layout() nq = 3 # number of qubits m = 3 # number of classical bits q = QuantumRegister(nq,'q') c = ClassicalRegister(m,'c') qc = QuantumCircuit(q,c) qc.h(0) qc.x([1,2]) qc.draw('mpl') cu_circ = QuantumCircuit(nq) cu_circ.mcp(pi/4,[0,1],2) cu_circ.draw('mpl') for _ in range(2**(m-1)): qc.mcp(pi/4,[0,1],2) qc.draw('mpl') x_measurement(qc, q[0], c[0]) qc.draw('mpl') qc.reset(0) qc.h(0) qc.draw('mpl') qc.p(-pi/2,0).c_if(c,1) qc.draw('mpl') for _ in range(2**(m-2)): qc.mcp(pi/4,[0,1],2) x_measurement(qc, q[0], c[1]) qc.draw('mpl') # initialization of qubit q0 qc.reset(0) qc.h(0) # phase correction qc.p(-pi/4,0).c_if(c,1) qc.p(-pi/2,0).c_if(c,2) qc.p(-3*pi/4,0).c_if(c,3) # c-U operations for _ in range(2**(m-3)): qc.mcp(pi/4,[0,1],2) # X measurement qc.h(0) qc.measure(0,2) qc.draw('mpl') count0 = execute(qc, sim).result().get_counts() key_new = [str(int(key,2)/2**m) for key in list(count0.keys())] count1 = dict(zip(key_new, count0.values())) fig, ax = plt.subplots(1,2) plot_histogram(count0, ax=ax[0]) plot_histogram(count1, ax=ax[1]) fig.tight_layout() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.library.standard_gates import HGate qc1 = QuantumCircuit(2) qc1.x(0) qc1.h(1) custom = qc1.to_gate().control(2) qc2 = QuantumCircuit(4) qc2.append(custom, [0, 3, 1, 2]) qc2.draw('mpl')
https://github.com/1chooo/Quantum-Oracle
1chooo
#Program 4.1 Apply CX-gate to qubit from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.cx(0,1) qc.draw('mpl') #Program 4.2 Show unitary matrix of CX-gate (MSB as target bit) from qiskit import QuantumCircuit, Aer from qiskit.visualization import array_to_latex qc = QuantumCircuit(2) qc.cx(0,1) display(qc.draw('mpl')) sim = Aer.get_backend('aer_simulator') qc.save_unitary() unitary = sim.run(qc).result().get_unitary() display(array_to_latex(unitary, prefix="\\text{CNOT (MSB as target bit) = }")) #Program 4.3 Show unitary matrix of CX-gate (LSB as target bit) from qiskit import QuantumCircuit, Aer from qiskit.visualization import array_to_latex sim = Aer.get_backend('aer_simulator') qc = QuantumCircuit(2) qc.cx(1,0) display(qc.draw('mpl')) qc.save_unitary() unitary = sim.run(qc).result().get_unitary() display(array_to_latex(unitary, prefix="\\text{CNOT (LSB as target bit) = }")) #Program 4.4a Appliy CX-gate to qubit from qiskit import QuantumCircuit,execute from qiskit.quantum_info import Statevector qc = QuantumCircuit(8,8) sv = Statevector.from_label('11011000') qc.initialize(sv,range(8)) qc.cx(0,1) qc.cx(2,3) qc.cx(4,5) qc.cx(6,7) qc.measure(range(8),range(8)) qc.draw('mpl') #Program 4.4b Measure state of qubit w/ CX-gate from qiskit import execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram sim=AerSimulator() job=execute(qc, backend=sim, shots=1000) result=job.result() counts=result.get_counts(qc) print("Counts:",counts) plot_histogram(counts) #Program 4.5 Build Bell state via H- and CX-gate from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.h(1) qc.cx(1,0) print("Below is the Bell state (top: q0 for target; bottom: q1 for control):") display(qc.draw('mpl')) print("Below is the Bell state (top: q1 for control; bottom: q0 for traget):") display(qc.draw('mpl',reverse_bits=True)) #Program 4.6a Build Bell state via H- and CX-gate from qiskit import QuantumCircuit qc = QuantumCircuit(2,2) qc.h(0) qc.cx(0,1) qc.measure(range(2),range(2)) qc.draw('mpl') #Program 4.6b Measure state of qubit in Bell state from qiskit import execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram sim=AerSimulator() job=execute(qc, backend=sim, shots=1000) result=job.result() counts=result.get_counts(qc) print("Counts:",counts) plot_histogram(counts) #Program 4.7a Iinitialize qubit and build Bell state via H- and CX-gate from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector qc = QuantumCircuit(2,2) sv = Statevector.from_label('10') qc.initialize(sv,range(2)) qc.h(0) qc.cx(0,1) qc.measure(range(2),range(2)) qc.draw('mpl') #Program 4.7b Measure state of qubit in Bell state from qiskit import execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram sim=AerSimulator() job=execute(qc, backend=sim, shots=1000) result=job.result() counts=result.get_counts(qc) print("Counts:",counts) plot_histogram(counts) #Program 4.8 Show quantum circuit for quantum teleportation from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qs = QuantumRegister(1,'qs') qa = QuantumRegister(1,'qa') qb = QuantumRegister(1,'qb') cr = ClassicalRegister(2,'c') qc = QuantumCircuit(qs,qa,qb,cr) qc.h(qa) qc.cx(qa,qb) qc.barrier() qc.cx(qs,qa) qc.h(qs) qc.measure(qs,0) qc.measure(qa,1) qc.barrier() qc.x(qb) qc.z(qb) qc.draw('mpl') #Program 4.9 Apply CX-, CY-, CZ-, CH-, and SWAP-gate to qubit from qiskit import QuantumCircuit qc = QuantumCircuit(12) qc.cx(0,1) qc.cy(2,3) qc.cz(4,5) qc.ch(6,7) qc.swap(8,9) qc.cx(10,11) qc.cx(11,10) qc.cx(10,11) qc.draw('mpl') #Program 4.10 Apply CCX-gate to qubit from qiskit import QuantumCircuit qc = QuantumCircuit(3) qc.ccx(0,1,2) qc.draw('mpl') #Program 4.11 Show unitary matrix of CCX-gate from qiskit import QuantumCircuit, Aer from qiskit.visualization import array_to_latex sim = Aer.get_backend('aer_simulator') qc1 = QuantumCircuit(3) qc1.ccx(0,1,2) print("="*70,"\nBelow is quantum circuit of CCNOT gate (MSB as target bit):") display(qc1.draw('mpl')) qc1.save_unitary() unitary = sim.run(qc1).result().get_unitary() display(array_to_latex(unitary, prefix="\\text{CCNOT (MSB as target bit) = }\n")) qc2 = QuantumCircuit(3) qc2.ccx(2,1,0) print("="*70,"\nBelow is quantum circuit of CCNOT gate (LSB as target bit):") display(qc2.draw('mpl')) qc2.save_unitary() unitary = sim.run(qc2).result().get_unitary() display(array_to_latex(unitary, prefix="\\text{CCNOT (LSB as target bit) = }\n")) #Program 4.12 Apply CCCCX-gate to qubit from qiskit import QuantumCircuit qc = QuantumCircuit(7) qc.ccx(0,1,4) qc.ccx(2,3,5) qc.ccx(4,5,6) qc.draw('mpl')
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # # your solution is here # from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer # Quantum Circuit with 4 qbits qreg = QuantumRegister(4) # quantum register with 4 qubits creg = ClassicalRegister(4) # classical register with 4 bits mycircuit = QuantumCircuit(qreg,creg) # quantum circuit with quantum and classical registers # Apply Hadamard to each one of the q-bits for i in range(4): mycircuit.h(qreg[i]) # perform measurement mycircuit.measure(qreg,creg) # Execute circuit 16000 times job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1600) counts = job.result().get_counts(mycircuit) # reverse q-bits to have a readable format for outcome in counts: reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print(reverse_outcome,"is observed",counts[outcome],"times") # include our predefined functions %run qlatvia.py # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import acos, pi # after Hadamard operators u = [(13/16)**0.5,(3/16)**0.5] def angle_between_two_states(u1,u2): dot_product = u1[0]*u2[0]+u1[1]*u2[1] return acos(dot_product) theta = angle_between_two_states(u,[1,0]) all_visited_quantum_states =[] qreg2 = QuantumRegister(1) # quantum register with 1 qubit creg2 = ClassicalRegister(1) # classical register with 1 bit mycircuit2 = QuantumCircuit(qreg2,creg2) # quantum circuit with quantum and classical registers # set the qubit to |u> by rotating it by theta mycircuit2.ry(2*theta,qreg2[0]) # read and store the current quantum state current_state = execute(mycircuit2,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit2) [x,y] = [current_state[0].real,current_state[1].real] all_visited_quantum_states.append([x,y,'u']) # the first reflection theta = angle_between_two_states([x,y],[1,0]) mycircuit2.ry(2*(-2*theta),qreg2[0]) # read and store the current quantum state current_state = execute(mycircuit2,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit2) [x,y] = [current_state[0].real,current_state[1].real] all_visited_quantum_states.append([x,y,'r']) # the second reflection theta = angle_between_two_states(u,[x,y]) mycircuit2.ry(2*(2*theta),qreg2[0]) # read and store the current quantum state current_state = execute(mycircuit2,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit2) [x,y] = [current_state[0].real,current_state[1].real] all_visited_quantum_states.append([x,y,'n']) # measure the qubit mycircuit2.measure(qreg2,creg2) # execute the circuit 100 times, and print the outcomes job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=100) counts2 = job.result().get_counts(mycircuit2) print(counts2) # visualization draw_qubit() for quantum_state in all_visited_quantum_states: draw_quantum_state(quantum_state[0],quantum_state[1],quantum_state[2]) # include our predefined functions %run qlatvia.py # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import acos, pi # after Hadamard operators u = [(63/64)**0.5,(1/64)**0.5] def angle_between_two_states(u1,u2): dot_product = u1[0]*u2[0]+u1[1]*u2[1] return acos(dot_product) theta = angle_between_two_states(u,[1,0]) all_visited_quantum_states =[] qreg3 = QuantumRegister(1) # quantum register with 1 qubit creg3 = ClassicalRegister(1) # classical register with 1 bit mycircuit3 = QuantumCircuit(qreg3,creg3) # quantum circuit with quantum and classical registers # set the qubit to |u> by rotating it by theta mycircuit3.ry(2*theta,qreg3[0]) # read and store the current quantum state current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3) [x,y] = [current_state[0].real,current_state[1].real] all_visited_quantum_states.append([x,y,'u']) # three iterations for i in range(3): # 4,5,6,7,8,9,10 # the first reflection theta = angle_between_two_states([x,y],[1,0]) mycircuit3.ry(2*(-2*theta),qreg3[0]) # read and store the current quantum state current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3) [x,y] = [current_state[0].real,current_state[1].real] all_visited_quantum_states.append([x,y,'r'+str(i+1)]) # the second reflection theta = angle_between_two_states(u,[x,y]) mycircuit3.ry(2*(2*theta),qreg3[0]) # read and store the current quantum state current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3) [x,y] = [current_state[0].real,current_state[1].real] all_visited_quantum_states.append([x,y,'n'+str(i+1)]) # measure the qubit mycircuit3.measure(qreg3,creg3) # execute the circuit 100 times, and print the outcomes job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=100) counts3 = job.result().get_counts(mycircuit3) print(counts3) # visualization draw_qubit() for quantum_state in all_visited_quantum_states: draw_quantum_state(quantum_state[0],quantum_state[1],quantum_state[2]) # include our predefined functions %run qlatvia.py # import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from math import acos, pi # after Hadamard operators u = [(4/16)**0.5,(12/16)**0.5] def angle_between_two_states(u1,u2): dot_product = u1[0]*u2[0]+u1[1]*u2[1] return acos(dot_product) theta = angle_between_two_states(u,[1,0]) all_visited_quantum_states = [] qreg3 = QuantumRegister(1) # quantum register with 1 qubit creg3 = ClassicalRegister(1) # classical register with 1 bit mycircuit3 = QuantumCircuit(qreg3,creg3) # quantum circuit with quantum and classical registers # set the qubit to |u> by rotating it by theta mycircuit3.ry(2*theta,qreg3[0]) # read and store the current quantum state current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3) [x,y] = [current_state[0].real,current_state[1].real] all_visited_quantum_states.append([x,y,'u']) # three iterations number_of_iterations = 1 # 2, 3, and 4 for i in range(number_of_iterations): # the first reflection theta = angle_between_two_states([x,y],[1,0]) mycircuit3.ry(2*(-2*theta),qreg3[0]) # read and store the current quantum state current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3) [x,y] = [current_state[0].real,current_state[1].real] if i == number_of_iterations -1: all_visited_quantum_states.append([x,y,'r'+str(i+1)]) # the second reflection theta = angle_between_two_states(u,[x,y]) mycircuit3.ry(2*(2*theta),qreg3[0]) # read and store the current quantum state current_state = execute(mycircuit3,Aer.get_backend('statevector_simulator')).result().get_statevector(mycircuit3) [x,y] = [current_state[0].real,current_state[1].real] if i == number_of_iterations -1: all_visited_quantum_states.append([x,y,'n'+str(i+1)]) # measure the qubit mycircuit3.measure(qreg3,creg3) # execute the circuit 100 times, and print the outcomes job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=100) counts3 = job.result().get_counts(mycircuit3) print(counts3) # visualization draw_qubit() for quantum_state in all_visited_quantum_states: draw_quantum_state(quantum_state[0],quantum_state[1],quantum_state[2])
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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. """A collection of backend information formatted to generate drawing data. This instance will be provided to generator functions. The module provides an abstract class :py:class:``DrawerBackendInfo`` with necessary methods to generate drawing objects. Because the data structure of backend class may depend on providers, this abstract class has an abstract factory method `create_from_backend`. Each subclass should provide the factory method which conforms to the associated provider. By default we provide :py:class:``OpenPulseBackendInfo`` class that has the factory method taking backends satisfying OpenPulse specification [1]. This class can be also initialized without the factory method by manually specifying required information. This may be convenient for visualizing a pulse program for simulator backend that only has a device Hamiltonian information. This requires two mapping objects for channel/qubit and channel/frequency along with the system cycle time. If those information are not provided, this class will be initialized with a set of empty data and the drawer illustrates a pulse program without any specific information. Reference: - [1] Qiskit Backend Specifications for OpenQASM and OpenPulse Experiments, https://arxiv.org/abs/1809.03452 """ from abc import ABC, abstractmethod from collections import defaultdict from typing import Dict, List, Union, Optional from qiskit import pulse from qiskit.providers import BackendConfigurationError from qiskit.providers.backend import Backend class DrawerBackendInfo(ABC): """Backend information to be used for the drawing data generation.""" def __init__( self, name: Optional[str] = None, dt: Optional[float] = None, channel_frequency_map: Optional[Dict[pulse.channels.Channel, float]] = None, qubit_channel_map: Optional[Dict[int, List[pulse.channels.Channel]]] = None, ): """Create new backend information. Args: name: Name of the backend. dt: System cycle time. channel_frequency_map: Mapping of channel and associated frequency. qubit_channel_map: Mapping of qubit and associated channels. """ self.backend_name = name or "no-backend" self._dt = dt self._chan_freq_map = channel_frequency_map or {} self._qubit_channel_map = qubit_channel_map or {} @classmethod @abstractmethod def create_from_backend(cls, backend: Backend): """Initialize a class with backend information provided by provider. Args: backend: Backend object. """ raise NotImplementedError @property def dt(self): """Return cycle time.""" return self._dt def get_qubit_index(self, chan: pulse.channels.Channel) -> Union[int, None]: """Get associated qubit index of given channel object.""" for qind, chans in self._qubit_channel_map.items(): if chan in chans: return qind return chan.index def get_channel_frequency(self, chan: pulse.channels.Channel) -> Union[float, None]: """Get frequency of given channel object.""" return self._chan_freq_map.get(chan, None) class OpenPulseBackendInfo(DrawerBackendInfo): """Drawing information of backend that conforms to OpenPulse specification.""" @classmethod def create_from_backend(cls, backend: Backend): """Initialize a class with backend information provided by provider. Args: backend: Backend object. Returns: OpenPulseBackendInfo: New configured instance. """ configuration = backend.configuration() defaults = backend.defaults() # load name name = backend.name() # load cycle time dt = configuration.dt # load frequencies chan_freqs = {} chan_freqs.update( {pulse.DriveChannel(qind): freq for qind, freq in enumerate(defaults.qubit_freq_est)} ) chan_freqs.update( {pulse.MeasureChannel(qind): freq for qind, freq in enumerate(defaults.meas_freq_est)} ) for qind, u_lo_mappers in enumerate(configuration.u_channel_lo): temp_val = 0.0 + 0.0j for u_lo_mapper in u_lo_mappers: temp_val += defaults.qubit_freq_est[u_lo_mapper.q] * u_lo_mapper.scale chan_freqs[pulse.ControlChannel(qind)] = temp_val.real # load qubit channel mapping qubit_channel_map = defaultdict(list) for qind in range(configuration.n_qubits): qubit_channel_map[qind].append(configuration.drive(qubit=qind)) qubit_channel_map[qind].append(configuration.measure(qubit=qind)) for tind in range(configuration.n_qubits): try: qubit_channel_map[qind].extend(configuration.control(qubits=(qind, tind))) except BackendConfigurationError: pass return OpenPulseBackendInfo( name=name, dt=dt, channel_frequency_map=chan_freqs, qubit_channel_map=qubit_channel_map )
https://github.com/maryrbarros2/QuantumAlgorithms_Qiskit
maryrbarros2
from qiskit import QuantumCircuit, Aer, assemble from math import pi import numpy as np from qiskit.visualization import plot_bloch_multivector, plot_histogram, array_to_latex qc = QuantumCircuit(2) qc.h(0) qc.h(1) qc.cx(0,1) qc.draw() qc = QuantumCircuit(2) qc.h(0) qc.h(1) qc.cx(0,1) display(qc.draw()) # `display` is a command for Jupyter notebooks # similar to `print`, but for rich content # Let's see the result svsim = Aer.get_backend('aer_simulator') qc.save_statevector() qobj = assemble(qc) final_state = svsim.run(qobj).result().get_statevector() display(array_to_latex(final_state, prefix="\\text{Statevector} = ")) plot_bloch_multivector(final_state) qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.h(1) qc.draw() qc = QuantumCircuit(2) qc.h(0) qc.x(1) qc.h(1) display(qc.draw()) # See the result qc1 = qc.copy() qc1.save_statevector() final_state = svsim.run(qc1).result().get_statevector() display(array_to_latex(final_state, prefix="\\text{Statevector} = ")) plot_bloch_multivector(final_state) qc.cx(0,1) display(qc.draw()) qc.save_statevector() qobj = assemble(qc) final_state = svsim.run(qobj).result().get_statevector() display(array_to_latex(final_state, prefix="\\text{Statevector} = ")) plot_bloch_multivector(final_state) qc = QuantumCircuit(2) qc.h(0) qc.h(1) qc.cx(0,1) qc.h(0) qc.h(1) display(qc.draw()) qc.save_unitary() usim = Aer.get_backend('aer_simulator') qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() array_to_latex(unitary, prefix="\\text{Circuit = }\n") qc = QuantumCircuit(2) qc.cx(1,0) display(qc.draw()) qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() array_to_latex(unitary, prefix="\\text{Circuit = }\n") qc = QuantumCircuit(2) qc.cp(pi/4, 0, 1) qc.draw() qc = QuantumCircuit(2) qc.cp(pi/4, 0, 1) display(qc.draw()) # See Results: qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() array_to_latex(unitary, prefix="\\text{Controlled-T} = \n") qc = QuantumCircuit(2) qc.h(0) qc.x(1) display(qc.draw()) # See Results: qc.save_statevector() qobj = assemble(qc) final_state = svsim.run(qobj).result().get_statevector() plot_bloch_multivector(final_state) qc = QuantumCircuit(2) qc.h(0) qc.x(1) # Add Controlled-T qc.cp(pi/4, 0, 1) display(qc.draw()) # See Results: qc.save_statevector() qobj = assemble(qc) final_state = svsim.run(qobj).result().get_statevector() plot_bloch_multivector(final_state)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw, IQXDebugging from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial') draw(qc, style=IQXDebugging())
https://github.com/xtophe388/QISKIT
xtophe388
import numpy as np # These column vectors can be stored in numpy arrays so that we can operate # on them with the circuit diagram's corresponding matrix (which is to be evaluated) # as follows: zero_zero = np.array([[1],[0],[0],[0]]) zero_one = np.array([[0],[1],[0],[0]]) one_zero = np.array([[0],[0],[1],[0]]) one_one = np.array([[0],[0],[0],[1]]) Psi = {'zero_zero': zero_zero, 'zero_one': zero_one, 'one_zero': one_zero, 'one_one': one_one} # ^We can conveniently store all possible input states in a dictionary and then print to check the representations: for key, val in Psi.items(): print(key, ':', '\n', val) # storing CNOT as a numpy array: CNOT_1 = np.matrix([[1, 0, 0, 0],[0, 1, 0, 0],[0, 0, 0, 1],[0, 0, 1, 0]]) print(CNOT_1) print('FINAL STATE OF i):') #Apply CNOT to each possible state for |Psi> to find --> |Psi'> for key, val in Psi.items(): print(key, 'becomes..\n', CNOT_1*val) # storing this in a numpy array: H_2 = .5*np.matrix([[1, 1, 1, 1],[1, -1, 1, -1],[1, 1, -1, -1],[1, -1, -1, 1]]) print('H_2:') print(H_2) # storing this in a numpy array: CNOT_2 = np.matrix([[1, 0, 0, 0],[0, 0, 0, 1],[0, 0, 1, 0],[0, 1, 0, 0]]) A = H_2*CNOT_2*H_2 print(A) print(CNOT_1) for key, val in Psi.items(): print(key, 'becomes...\n', A*val)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) ghz.draw(output='mpl')
https://github.com/Qiskit/feedback
Qiskit
import matplotlib.pyplot as plt from qiskit import Aer from qiskit.algorithms.state_fidelities import ComputeUncompute from qiskit.circuit.library import ZZFeatureMap from qiskit.primitives import Sampler from qiskit.utils import algorithm_globals, QuantumInstance from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from qiskit_machine_learning.algorithms import QSVC from qiskit_machine_learning.kernels import QuantumKernel, FidelityQuantumKernel algorithm_globals.random_seed = 123456 features, labels = make_classification( n_samples=20, n_features=2, n_redundant=0, random_state=algorithm_globals.random_seed ) features = MinMaxScaler().fit_transform(features) plt.scatter(features[:, 0], features[:, 1], c=labels) train_features, test_feature, train_labels, test_labels = train_test_split( features, labels, train_size=15, random_state=algorithm_globals.random_seed ) qi_sv = QuantumInstance( Aer.get_backend("statevector_simulator"), seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, ) qk_old = QuantumKernel(feature_map=ZZFeatureMap(2), quantum_instance=qi_sv) qsvc = QSVC(quantum_kernel=qk_old) qsvc.fit(train_features, train_labels) qsvc.score(test_feature, test_labels) # these are optional sampler = Sampler() fidelity = ComputeUncompute(sampler) qk_new = FidelityQuantumKernel(feature_map=ZZFeatureMap(2), fidelity=fidelity) qsvc = QSVC(quantum_kernel=qk_new) qsvc.fit(train_features, train_labels) qsvc.score(test_feature, test_labels) import qiskit.tools.jupyter %qiskit_copyright
https://github.com/derwind/qiskit_applications
derwind
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 * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() from qiskit.circuit.library.standard_gates import XGate, HGate from operator import * n = 3 N = 8 #2**n index_colour_table = {} colour_hash_map = {} index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"} colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'} def database_oracle(index_colour_table, colour_hash_map): circ_database = QuantumCircuit(n + n) for i in range(N): circ_data = QuantumCircuit(n) idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) # qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0 # we therefore reverse the index string -> q0, ..., qn data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour) circ_database.append(data_gate, list(range(n+n))) return circ_database # drawing the database oracle circuit print("Database Encoding") database_oracle(index_colour_table, colour_hash_map).draw() circ_data = QuantumCircuit(n) m = 4 idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion colour = index_colour_table[idx] colour_hash = colour_hash_map[colour][::-1] for j in range(n): if colour_hash[j] == '1': circ_data.x(j) print("Internal colour encoding for the colour green (as an example)"); circ_data.draw() def oracle_grover(database, data_entry): circ_grover = QuantumCircuit(n + n + 1) circ_grover.append(database, list(range(n+n))) target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target") # control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()' # The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class. circ_grover.append(target_reflection_gate, list(range(n, n+n+1))) circ_grover.append(database, list(range(n+n))) return circ_grover print("Grover Oracle (target example: orange)") oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw() def mcz_gate(num_qubits): num_controls = num_qubits - 1 mcz_gate = QuantumCircuit(num_qubits) target_mcz = QuantumCircuit(1) target_mcz.z(0) target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ") mcz_gate.append(target_mcz, list(range(num_qubits))) return mcz_gate.reverse_bits() print("Multi-controlled Z (MCZ) Gate") mcz_gate(n).decompose().draw() def diffusion_operator(num_qubits): circ_diffusion = QuantumCircuit(num_qubits) qubits_list = list(range(num_qubits)) # Layer of H^n gates circ_diffusion.h(qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of Multi-controlled Z (MCZ) Gate circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list) # Layer of X^n gates circ_diffusion.x(qubits_list) # Layer of H^n gates circ_diffusion.h(qubits_list) return circ_diffusion print("Diffusion Circuit") diffusion_operator(n).draw() # Putting it all together ... !!! item = "green" print("Searching for the index of the colour", item) circuit = QuantumCircuit(n + n + 1, n) circuit.x(n + n) circuit.barrier() circuit.h(list(range(n))) circuit.h(n+n) circuit.barrier() unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator") unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator") M = countOf(index_colour_table.values(), item) Q = int(np.pi * np.sqrt(N/M) / 4) for i in range(Q): circuit.append(unitary_oracle, list(range(n + n + 1))) circuit.append(unitary_diffuser, list(range(n))) circuit.barrier() circuit.measure(list(range(n)), list(range(n))) circuit.draw() backend_sim = Aer.get_backend('qasm_simulator') job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024) result_sim = job_sim.result() counts = result_sim.get_counts(circuit) if M==1: print("Index of the colour", item, "is the index with most probable outcome") else: print("Indices of the colour", item, "are the indices the most probable outcomes") from qiskit.visualization import plot_histogram plot_histogram(counts)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Import requisite modules import math import datetime import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Import Qiskit packages from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit_aer.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer # The data providers of stock-market data from qiskit_finance.data_providers import RandomDataProvider from qiskit_finance.applications.optimization import PortfolioDiversification # Generate a pairwise time-series similarity matrix seed = 123 stocks = ["TICKER1", "TICKER2"] n = len(stocks) data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() rho = data.get_similarity_matrix() q = 1 # q less or equal than n class ClassicalOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n # number of inner variables self.q = q # number of required selection def compute_allowed_combinations(self): f = math.factorial return int(f(self.n) / f(self.q) / f(self.n - self.q)) def cplex_solution(self): # refactoring rho = self.rho n = self.n q = self.q my_obj = list(rho.reshape(1, n**2)[0]) + [0.0 for x in range(0, n)] my_ub = [1 for x in range(0, n**2 + n)] my_lb = [0 for x in range(0, n**2 + n)] my_ctype = "".join(["I" for x in range(0, n**2 + n)]) my_rhs = ( [q] + [1 for x in range(0, n)] + [0 for x in range(0, n)] + [0.1 for x in range(0, n**2)] ) my_sense = ( "".join(["E" for x in range(0, 1 + n)]) + "".join(["E" for x in range(0, n)]) + "".join(["L" for x in range(0, n**2)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] col = [x for x in range(n**2, n**2 + n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [ii * n + ii, n**2 + ii] coef = [1, -1] rows.append([col, coef]) for ii in range(0, n): for jj in range(0, n): col = [ii * n + jj, n**2 + jj] coef = [1, -1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(rho, n, q) # Compute the number of feasible solutions: print("Number of feasible combinations= " + str(classical_optimizer.compute_allowed_combinations())) # Compute the total number of possible combinations (feasible + unfeasible) print("Total number of combinations= " + str(2 ** (n * (n + 1)))) # Visualize the solution def visualize_solution(xc, yc, x, C, n, K, title_str): plt.figure() plt.scatter(xc, yc, s=200) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.015, yc[i]), size=16, color="r") plt.grid() for ii in range(n**2, n**2 + n): if x[ii] > 0: plt.plot(xc[ii - n**2], yc[ii - n**2], "r*", ms=20) for ii in range(0, n**2): if x[ii] > 0: iy = ii // n ix = ii % n plt.plot([xc[ix], xc[iy]], [yc[ix], yc[iy]], "C2") plt.title(title_str + " cost = " + str(int(C * 100) / 100.0)) plt.show() from qiskit.utils import algorithm_globals class QuantumOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n self.q = q self.pdf = PortfolioDiversification(similarity_matrix=rho, num_assets=n, num_clusters=q) self.qp = self.pdf.to_quadratic_program() # Obtains the least eigenvalue of the Hamiltonian classically def exact_solution(self): exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(self.qp) return self.decode_result(result) def vqe_solution(self): algorithm_globals.random_seed = 100 cobyla = COBYLA() cobyla.set_options(maxiter=250) ry = TwoLocal(n, "ry", "cz", reps=5, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(self.qp) return self.decode_result(result) def qaoa_solution(self): algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(self.qp) return self.decode_result(result) def decode_result(self, result, offset=0): quantum_solution = 1 - (result.x) ground_level = self.qp.objective.evaluate(result.x) return quantum_solution, ground_level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(rho, n, q) # Check if the binary representation is correct. This requires CPLEX try: import cplex # warnings.filterwarnings('ignore') quantum_solution, quantum_cost = quantum_optimizer.exact_solution() print(quantum_solution, quantum_cost) classical_solution, classical_cost = classical_optimizer.cplex_solution() print(classical_solution, classical_cost) if np.abs(quantum_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the formulation of the Hamiltonian") except Exception as ex: print(ex) ground_state, ground_level = quantum_optimizer.exact_solution() print(ground_state) classical_cost = 1.000779571614484 # obtained from the CPLEX solution try: if np.abs(ground_level - classical_cost) < 0.01: print("Ising Hamiltonian in Z basis is correct") else: print("Error in the Ising Hamiltonian formulation") except Exception as ex: print(ex) vqe_state, vqe_level = quantum_optimizer.vqe_solution() print(vqe_state, vqe_level) try: if np.linalg.norm(ground_state - vqe_state) < 0.01: print("SamplingVQE produces the same solution as the exact eigensolver.") else: print( "SamplingVQE does not produce the same solution as the exact eigensolver, but that is to be expected." ) except Exception as ex: print(ex) xc, yc = data.get_coordinates() visualize_solution(xc, yc, ground_state, ground_level, n, q, "Classical") visualize_solution(xc, yc, vqe_state, vqe_level, n, q, "VQE") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/lynnlangit/learning-quantum
lynnlangit
# This cell is added by sphinx-gallery # It can be customized to whatever you like %matplotlib inline import pennylane as qml from pennylane import numpy as np dev1 = qml.device("default.qubit", wires=1) def circuit(params): qml.RX(params[0], wires=0) qml.RY(params[1], wires=0) return qml.expval(qml.PauliZ(0)) @qml.qnode(dev1) def circuit(params): qml.RX(params[0], wires=0) qml.RY(params[1], wires=0) return qml.expval(qml.PauliZ(0)) print(circuit([0.54, 0.12])) dcircuit = qml.grad(circuit, argnum=0) print(dcircuit([0.54, 0.12])) @qml.qnode(dev1) def circuit2(phi1, phi2): qml.RX(phi1, wires=0) qml.RY(phi2, wires=0) return qml.expval(qml.PauliZ(0)) dcircuit = qml.grad(circuit2, argnum=[0, 1]) print(dcircuit(0.54, 0.12)) def cost(x): return circuit(x) init_params = np.array([0.011, 0.012]) print(cost(init_params)) # initialise the optimizer opt = qml.GradientDescentOptimizer(stepsize=0.4) # set the number of steps steps = 100 # set the initial parameter values params = init_params for i in range(steps): # update the circuit parameters params = opt.step(cost, params) if (i + 1) % 5 == 0: print("Cost after step {:5d}: {: .7f}".format(i + 1, cost(params))) print("Optimized rotation angles: {}".format(params))
https://github.com/helionagamachi/QISKit
helionagamachi
from qiskit import QuantumProgram import Qconfig import sys qp = QuantumProgram() qp.set_api(Qconfig.APItoken, Qconfig.config['url']) # set the APIToken and API url # set up registers and program qr = qp.create_quantum_register('qr', 16) cr = qp.create_classical_register('cr', 16) qc = qp.create_circuit('smiley_writer', [qr], [cr]) # rightmost eight (qu)bits have ')' = 00101001 qc.x(qr[0]) qc.x(qr[3]) qc.x(qr[5]) # second eight (qu)bits have superposition of # '8' = 00111000 # ';' = 00111011 # these differ only on the rightmost two bits qc.h(qr[9]) # create superposition on 9 qc.cx(qr[9],qr[8]) # spread it to 8 with a cnot qc.x(qr[11]) qc.x(qr[12]) qc.x(qr[13]) # measure for j in range(16): qc.measure(qr[j], cr[j]) backend = 'ibmqx_qasm_simulator' if len(sys.argv) > 1: backend = sys.argv[1] # run and get results print('Executing..') results = qp.execute(['smiley_writer'], backend, shots=1024) print('waiting for results') stats = results.get_counts('smiley_writer') print(stats)
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
from qiskit import * import numpy as np import math from matplotlib import pyplot as plt import qiskit nshots = 8192 IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibmq_belem') simulator = Aer.get_backend('qasm_simulator') from qiskit.tools.monitor import job_monitor from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter #from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.visualization import plot_histogram qr = QuantumRegister(4) cr = ClassicalRegister(3) qc = QuantumCircuit(qr, cr) qc.x(3) qc.h([0,1,2]) qc.draw('mpl') import numpy as np import matplotlib.pyplot as plt x = np.linspace(-np.pi/2, np.pi/2, 1000) # generate 1000 evenly spaced points between -pi and pi y_sin = np.abs(np.sin(x/2)) # compute sin(x) for each x y_x = np.abs(x/2) # set y=x for each x plt.plot(x, y_sin, label='sin(x)') # plot sin(x) as a blue line plt.plot(x, y_x, label='x', color='orange') # plot x as an orange line plt.legend() # display the legend plt.show() # show the plot
https://github.com/qiskit-community/qiskit-jku-provider
qiskit-community
# -*- 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. import random import unittest import numpy from scipy.stats import chi2_contingency from qiskit import execute from qiskit import QuantumCircuit from qiskit import QuantumRegister from qiskit import ClassicalRegister from qiskit import BasicAer from qiskit_jku_provider import QasmSimulator try: global_pq_simulator = QasmSimulator(silent=True) except ImportError: _skip_class = True else: _skip_class = False from ._random_circuit_generator import RandomCircuitGenerator from .common import QiskitTestCase @unittest.skipIf(_skip_class, 'JKU C++ simulator unavailable') class TestQasmSimulatorJKU(QiskitTestCase): """ Test JKU simulator. """ # noinspection PyPep8Naming @classmethod def setUpClass(cls): super().setUpClass() # Set up random circuits n_circuits = 20 min_depth = 1 max_depth = 50 min_qubits = 1 max_qubits = 4 random_circuits = RandomCircuitGenerator(min_qubits=min_qubits, max_qubits=max_qubits, min_depth=min_depth, max_depth=max_depth, seed=None) for _ in range(n_circuits): basis = list(random.sample(random_circuits.op_signature.keys(), random.randint(2, 7))) if 'reset' in basis: basis.remove('reset') if 'u0' in basis: basis.remove('u0') if 'measure' in basis: basis.remove('measure') random_circuits.add_circuits(1, basis=basis) cls.rqg = random_circuits def run_on_simulators(self, qc, pq_simulator, qk_simulator, shots, seed): job_pq = execute(qc, pq_simulator, shots=shots, seed_simulator=seed) job_qk = execute(qc, qk_simulator, shots=shots, seed_simulator=seed) counts_pq = job_pq.result().get_counts() counts_qk = job_qk.result().get_counts() states = counts_qk.keys() | counts_pq.keys() # contingency table ctable = numpy.array([[counts_pq.get(key, 0) for key in states], [counts_qk.get(key, 0) for key in states]]) result = chi2_contingency(ctable) return counts_pq, counts_qk, result def test_gate_x(self): shots = 100 qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr, name='test_gate_x') qc.x(qr[0]) qc.measure(qr, cr) job = execute(qc, global_pq_simulator, shots=shots) result_pq = job.result(timeout=30) self.assertEqual(result_pq.get_counts(), {'1': shots}) def test_entangle(self): shots = 100 N = 5 qr = QuantumRegister(N) cr = ClassicalRegister(N) qc = QuantumCircuit(qr, cr, name='test_entangle') qc.h(qr[0]) for i in range(1, N): qc.cx(qr[0], qr[i]) qc.measure(qr, cr) timeout = 30 job = execute(qc, global_pq_simulator, shots=shots) result = job.result(timeout=timeout) counts = result.get_counts() self.log.info(counts) for key, _ in counts.items(): with self.subTest(key=key): self.assertTrue(key in ['0' * N, '1' * N]) def test_output_style(self): qk_simulator = BasicAer.get_backend('qasm_simulator', ) qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr, name='test_output_order') qc.h(qr[0]) qc.measure(qr[0], cr[0]) qc.measure(qr[1], cr[1]) shots = 100 counts_pq, counts_qk, result = self.run_on_simulators(qc, global_pq_simulator, qk_simulator, shots=shots, seed=1) self.assertGreater(result[1], 0.01) cr1 = ClassicalRegister(1) cr2 = ClassicalRegister(1) qc = QuantumCircuit(qr, cr1, cr2, name='test_output_separation') qc.h(qr[0]) qc.measure(qr[0], cr1[0]) qc.measure(qr[1], cr2[0]) counts_pq, counts_qk, result = self.run_on_simulators(qc, global_pq_simulator, qk_simulator, shots=shots, seed=1) self.log.info('chi2_contingency: %s', str(result)) self.assertGreater(result[1], 0.01) def test_random_circuits(self): qk_simulator = BasicAer.get_backend('qasm_simulator', ) for circuit in self.rqg.get_circuits(format_='QuantumCircuit'): self.log.info(circuit.qasm()) shots = 100 job_pq = execute(circuit, global_pq_simulator, shots=shots, seed_simulator=1) job_qk = execute(circuit, qk_simulator, shots=shots, seed_simulator=1) result_pq = job_pq.result() result_qk = job_qk.result() counts_pq = result_pq.get_counts() counts_qk = result_qk.get_counts() self.log.info('local_qasm_simulator_jku: %s', str(counts_pq)) self.log.info('local_qasm_simulator: %s', str(counts_qk)) states = counts_qk.keys() | counts_pq.keys() # contingency table ctable = numpy.array([[counts_pq.get(key, 0) for key in states], [counts_qk.get(key, 0) for key in states]]) result = chi2_contingency(ctable) self.log.info('chi2_contingency: %s', str(result)) with self.subTest(circuit=circuit): self.assertGreater(result[1], 0.01) if __name__ == '__main__': unittest.main(verbosity=2)
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # 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 QASM3 exporter.""" # We can't really help how long the lines output by the exporter are in some cases. # pylint: disable=line-too-long from io import StringIO from math import pi import re import unittest from ddt import ddt, data from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile from qiskit.circuit import Parameter, Qubit, Clbit, Instruction, Gate, Delay, Barrier from qiskit.circuit.classical import expr from qiskit.circuit.controlflow import CASE_DEFAULT from qiskit.test import QiskitTestCase from qiskit.qasm3 import Exporter, dumps, dump, QASM3ExporterError, ExperimentalFeatures from qiskit.qasm3.exporter import QASM3Builder from qiskit.qasm3.printer import BasicPrinter # Tests marked with this decorator should be restored after gate definition with parameters is fixed # properly, and the dummy tests after them should be deleted. See gh-7335. requires_fixed_parameterisation = unittest.expectedFailure class TestQASM3Functions(QiskitTestCase): """QASM3 module - high level functions""" def setUp(self): self.circuit = QuantumCircuit(2) self.circuit.u(2 * pi, 3 * pi, -5 * pi, 0) self.expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "qubit[2] q;", "U(2*pi, 3*pi, -5*pi) q[0];", "", ] ) super().setUp() def test_dumps(self): """Test dumps.""" result = dumps(self.circuit) self.assertEqual(result, self.expected_qasm) def test_dump(self): """Test dump into an IO stream.""" io = StringIO() dump(self.circuit, io) result = io.getvalue() self.assertEqual(result, self.expected_qasm) @ddt class TestCircuitQASM3(QiskitTestCase): """QASM3 exporter.""" maxDiff = 1_000_000 @classmethod def setUpClass(cls): # These regexes are not perfect by any means, but sufficient for simple tests on controlled # input circuits. They can allow false negatives (in which case, update the regex), but to # be useful for the tests must _never_ have false positive matches. We use an explicit # space (`\s`) or semicolon rather than the end-of-word `\b` because we want to ensure that # the exporter isn't putting out invalid characters as part of the identifiers. cls.register_regex = re.compile( r"^\s*(let|(qu)?bit(\[\d+\])?)\s+(?P<name>\w+)[\s;]", re.U | re.M ) scalar_type_names = { "angle", "duration", "float", "int", "stretch", "uint", } cls.scalar_parameter_regex = re.compile( r"^\s*((input|output|const)\s+)?" # Modifier rf"({'|'.join(scalar_type_names)})\s*(\[[^\]]+\])?\s+" # Type name and designator r"(?P<name>\w+)[\s;]", # Parameter name re.U | re.M, ) super().setUpClass() def test_regs_conds_qasm(self): """Test with registers and conditionals.""" qr1 = QuantumRegister(1, "qr1") qr2 = QuantumRegister(2, "qr2") cr = ClassicalRegister(3, "cr") qc = QuantumCircuit(qr1, qr2, cr) qc.measure(qr1[0], cr[0]) qc.measure(qr2[0], cr[1]) qc.measure(qr2[1], cr[2]) qc.x(qr2[1]).c_if(cr, 0) qc.y(qr1[0]).c_if(cr, 1) qc.z(qr1[0]).c_if(cr, 2) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[3] cr;", "qubit[1] qr1;", "qubit[2] qr2;", "cr[0] = measure qr1[0];", "cr[1] = measure qr2[0];", "cr[2] = measure qr2[1];", "if (cr == 0) {", " x qr2[1];", "}", "if (cr == 1) {", " y qr1[0];", "}", "if (cr == 2) {", " z qr1[0];", "}", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_registers_as_aliases(self): """Test that different types of alias creation and concatenation work.""" qubits = [Qubit() for _ in [None] * 10] first_four = QuantumRegister(name="first_four", bits=qubits[:4]) last_five = QuantumRegister(name="last_five", bits=qubits[5:]) alternate = QuantumRegister(name="alternate", bits=qubits[::2]) sporadic = QuantumRegister(name="sporadic", bits=[qubits[4], qubits[2], qubits[9]]) qc = QuantumCircuit(qubits, first_four, last_five, alternate, sporadic) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "qubit _qubit0;", "qubit _qubit1;", "qubit _qubit2;", "qubit _qubit3;", "qubit _qubit4;", "qubit _qubit5;", "qubit _qubit6;", "qubit _qubit7;", "qubit _qubit8;", "qubit _qubit9;", "let first_four = {_qubit0, _qubit1, _qubit2, _qubit3};", "let last_five = {_qubit5, _qubit6, _qubit7, _qubit8, _qubit9};", "let alternate = {first_four[0], first_four[2], _qubit4, last_five[1], last_five[3]};", "let sporadic = {alternate[2], alternate[1], last_five[4]};", "", ] ) self.assertEqual(Exporter(allow_aliasing=True).dumps(qc), expected_qasm) def test_composite_circuit(self): """Test with a composite circuit instruction and barriers""" composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_gate() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate composite_circ _gate_q_0, _gate_q_1 {", " h _gate_q_0;", " x _gate_q_1;", " cx _gate_q_0, _gate_q_1;", "}", "bit[2] cr;", "qubit[2] qr;", "h qr[0];", "cx qr[0], qr[1];", "barrier qr[0], qr[1];", "composite_circ qr[0], qr[1];", "cr[0] = measure qr[0];", "cr[1] = measure qr[1];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_custom_gate(self): """Test custom gates (via to_gate).""" composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_gate() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate composite_circ _gate_q_0, _gate_q_1 {", " h _gate_q_0;", " x _gate_q_1;", " cx _gate_q_0, _gate_q_1;", "}", "bit[2] cr;", "qubit[2] qr;", "h qr[0];", "cx qr[0], qr[1];", "barrier qr[0], qr[1];", "composite_circ qr[0], qr[1];", "cr[0] = measure qr[0];", "cr[1] = measure qr[1];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_same_composite_circuits(self): """Test when a composite circuit is added to the circuit multiple times.""" composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_gate() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate composite_circ _gate_q_0, _gate_q_1 {", " h _gate_q_0;", " x _gate_q_1;", " cx _gate_q_0, _gate_q_1;", "}", "bit[2] cr;", "qubit[2] qr;", "h qr[0];", "cx qr[0], qr[1];", "barrier qr[0], qr[1];", "composite_circ qr[0], qr[1];", "composite_circ qr[0], qr[1];", "cr[0] = measure qr[0];", "cr[1] = measure qr[1];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_composite_circuits_with_same_name(self): """Test when multiple composite circuit instructions same name and different implementation.""" my_gate = QuantumCircuit(1, name="my_gate") my_gate.h(0) my_gate_inst1 = my_gate.to_gate() my_gate = QuantumCircuit(1, name="my_gate") my_gate.x(0) my_gate_inst2 = my_gate.to_gate() my_gate = QuantumCircuit(1, name="my_gate") my_gate.x(0) my_gate_inst3 = my_gate.to_gate() qr = QuantumRegister(1, name="qr") circuit = QuantumCircuit(qr, name="circuit") circuit.append(my_gate_inst1, [qr[0]]) circuit.append(my_gate_inst2, [qr[0]]) my_gate_inst2_id = id(circuit.data[-1].operation) circuit.append(my_gate_inst3, [qr[0]]) my_gate_inst3_id = id(circuit.data[-1].operation) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate my_gate _gate_q_0 {", " h _gate_q_0;", "}", f"gate my_gate_{my_gate_inst2_id} _gate_q_0 {{", " x _gate_q_0;", "}", f"gate my_gate_{my_gate_inst3_id} _gate_q_0 {{", " x _gate_q_0;", "}", "qubit[1] qr;", "my_gate qr[0];", f"my_gate_{my_gate_inst2_id} qr[0];", f"my_gate_{my_gate_inst3_id} qr[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) def test_pi_disable_constants_false(self): """Test pi constant (disable_constants=False)""" circuit = QuantumCircuit(2) circuit.u(2 * pi, 3 * pi, -5 * pi, 0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "qubit[2] q;", "U(2*pi, 3*pi, -5*pi) q[0];", "", ] ) self.assertEqual(Exporter(disable_constants=False).dumps(circuit), expected_qasm) def test_pi_disable_constants_true(self): """Test pi constant (disable_constants=True)""" circuit = QuantumCircuit(2) circuit.u(2 * pi, 3 * pi, -5 * pi, 0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "qubit[2] q;", "U(6.283185307179586, 9.42477796076938, -15.707963267948966) q[0];", "", ] ) self.assertEqual(Exporter(disable_constants=True).dumps(circuit), expected_qasm) def test_custom_gate_with_unbound_parameter(self): """Test custom gate with unbound parameter.""" parameter_a = Parameter("a") custom = QuantumCircuit(1, name="custom") custom.rx(parameter_a, 0) circuit = QuantumCircuit(1) circuit.append(custom.to_gate(), [0]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "input float[64] a;", "gate custom(a) _gate_q_0 {", " rx(a) _gate_q_0;", "}", "qubit[1] q;", "custom(a) q[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) def test_custom_gate_with_bound_parameter(self): """Test custom gate with bound parameter.""" parameter_a = Parameter("a") custom = QuantumCircuit(1) custom.rx(parameter_a, 0) custom_gate = custom.bind_parameters({parameter_a: 0.5}).to_gate() custom_gate.name = "custom" circuit = QuantumCircuit(1) circuit.append(custom_gate, [0]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate custom _gate_q_0 {", " rx(0.5) _gate_q_0;", "}", "qubit[1] q;", "custom q[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) @requires_fixed_parameterisation def test_custom_gate_with_params_bound_main_call(self): """Custom gate with unbound parameters that are bound in the main circuit""" parameter0 = Parameter("p0") parameter1 = Parameter("p1") custom = QuantumCircuit(2, name="custom") custom.rz(parameter0, 0) custom.rz(parameter1 / 2, 1) qr_all_qubits = QuantumRegister(3, "q") qr_r = QuantumRegister(3, "r") circuit = QuantumCircuit(qr_all_qubits, qr_r) circuit.append(custom.to_gate(), [qr_all_qubits[0], qr_r[0]]) circuit.assign_parameters({parameter0: pi, parameter1: pi / 2}, inplace=True) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate custom(_gate_p_0, _gate_p_0) _gate_q_0, _gate_q_1 {", " rz(pi) _gate_q_0;", " rz(pi/4) _gate_q_1;", "}", "qubit[3] q;", "qubit[3] r;", "custom(pi, pi/2) q[0], r[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) def test_reused_custom_parameter(self): """Test reused custom gate with parameter.""" parameter_a = Parameter("a") custom = QuantumCircuit(1) custom.rx(parameter_a, 0) circuit = QuantumCircuit(1) circuit.append(custom.bind_parameters({parameter_a: 0.5}).to_gate(), [0]) circuit.append(custom.bind_parameters({parameter_a: 1}).to_gate(), [0]) circuit_name_0 = circuit.data[0].operation.definition.name circuit_name_1 = circuit.data[1].operation.definition.name expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"gate {circuit_name_0} _gate_q_0 {{", " rx(0.5) _gate_q_0;", "}", f"gate {circuit_name_1} _gate_q_0 {{", " rx(1.0) _gate_q_0;", "}", "qubit[1] q;", f"{circuit_name_0} q[0];", f"{circuit_name_1} q[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) def test_unbound_circuit(self): """Test with unbound parameters (turning them into inputs).""" qc = QuantumCircuit(1) theta = Parameter("θ") qc.rz(theta, 0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "input float[64] θ;", "qubit[1] q;", "rz(θ) q[0];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_unknown_parameterized_gate_called_multiple_times(self): """Test that a parameterised gate is called correctly if the first instance of it is generic.""" x, y = Parameter("x"), Parameter("y") qc = QuantumCircuit(2) qc.rzx(x, 0, 1) qc.rzx(y, 0, 1) qc.rzx(0.5, 0, 1) expected_qasm = "\n".join( [ "OPENQASM 3;", "input float[64] x;", "input float[64] y;", "gate rzx(x) _gate_q_0, _gate_q_1 {", " h _gate_q_1;", " cx _gate_q_0, _gate_q_1;", " rz(x) _gate_q_1;", " cx _gate_q_0, _gate_q_1;", " h _gate_q_1;", "}", "qubit[2] q;", "rzx(x) q[0], q[1];", "rzx(y) q[0], q[1];", "rzx(0.5) q[0], q[1];", "", ] ) # Set the includes and basis gates to ensure that this gate is unknown. exporter = Exporter(includes=[], basis_gates=("rz", "h", "cx")) self.assertEqual(exporter.dumps(qc), expected_qasm) def test_gate_qasm_with_ctrl_state(self): """Test with open controlled gate that has ctrl_state""" qc = QuantumCircuit(2) qc.ch(0, 1, ctrl_state=0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate ch_o0 _gate_q_0, _gate_q_1 {", " x _gate_q_0;", " ch _gate_q_0, _gate_q_1;", " x _gate_q_0;", "}", "qubit[2] q;", "ch_o0 q[0], q[1];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) def test_custom_gate_collision_with_stdlib(self): """Test a custom gate with name collision with the standard library.""" custom = QuantumCircuit(2, name="cx") custom.cx(0, 1) custom_gate = custom.to_gate() qc = QuantumCircuit(2) qc.append(custom_gate, [0, 1]) custom_gate_id = id(qc.data[-1].operation) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"gate cx_{custom_gate_id} _gate_q_0, _gate_q_1 {{", " cx _gate_q_0, _gate_q_1;", "}", "qubit[2] q;", f"cx_{custom_gate_id} q[0], q[1];", "", ] ) self.assertEqual(Exporter().dumps(qc), expected_qasm) @requires_fixed_parameterisation def test_no_include(self): """Test explicit gate declaration (no include)""" q = QuantumRegister(2, "q") circuit = QuantumCircuit(q) circuit.rz(pi / 2, 0) circuit.sx(0) circuit.cx(0, 1) expected_qasm = "\n".join( [ "OPENQASM 3;", "gate u3(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {", " U(0, 0, pi/2) _gate_q_0;", "}", "gate u1(_gate_p_0) _gate_q_0 {", " u3(0, 0, pi/2) _gate_q_0;", "}", "gate rz(_gate_p_0) _gate_q_0 {", " u1(pi/2) _gate_q_0;", "}", "gate sdg _gate_q_0 {", " u1(-pi/2) _gate_q_0;", "}", "gate u2(_gate_p_0, _gate_p_1) _gate_q_0 {", " u3(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", " u2(0, pi) _gate_q_0;", "}", "gate sx _gate_q_0 {", " sdg _gate_q_0;", " h _gate_q_0;", " sdg _gate_q_0;", "}", "gate cx c, t {", " ctrl @ U(pi, 0, pi) c, t;", "}", "qubit[2] q;", "rz(pi/2) q[0];", "sx q[0];", "cx q[0], q[1];", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(circuit), expected_qasm) @requires_fixed_parameterisation def test_teleportation(self): """Teleportation with physical qubits""" qc = QuantumCircuit(3, 2) qc.h(1) qc.cx(1, 2) qc.barrier() qc.cx(0, 1) qc.h(0) qc.barrier() qc.measure([0, 1], [0, 1]) qc.barrier() qc.x(2).c_if(qc.clbits[1], 1) qc.z(2).c_if(qc.clbits[0], 1) transpiled = transpile(qc, initial_layout=[0, 1, 2]) expected_qasm = "\n".join( [ "OPENQASM 3;", "gate u3(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {", " U(pi/2, 0, pi) _gate_q_0;", "}", "gate u2(_gate_p_0, _gate_p_1) _gate_q_0 {", " u3(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", " u2(0, pi) _gate_q_0;", "}", "gate cx c, t {", " ctrl @ U(pi, 0, pi) c, t;", "}", "gate x _gate_q_0 {", " u3(pi, 0, pi) _gate_q_0;", "}", "gate u1(_gate_p_0) _gate_q_0 {", " u3(0, 0, pi) _gate_q_0;", "}", "gate z _gate_q_0 {", " u1(pi) _gate_q_0;", "}", "bit[2] c;", "h $1;", "cx $1, $2;", "barrier $0, $1, $2;", "cx $0, $1;", "h $0;", "barrier $0, $1, $2;", "c[0] = measure $0;", "c[1] = measure $1;", "barrier $0, $1, $2;", "if (c[1]) {", " x $2;", "}", "if (c[0]) {", " z $2;", "}", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(transpiled), expected_qasm) @requires_fixed_parameterisation def test_basis_gates(self): """Teleportation with physical qubits""" qc = QuantumCircuit(3, 2) qc.h(1) qc.cx(1, 2) qc.barrier() qc.cx(0, 1) qc.h(0) qc.barrier() qc.measure([0, 1], [0, 1]) qc.barrier() qc.x(2).c_if(qc.clbits[1], 1) qc.z(2).c_if(qc.clbits[0], 1) transpiled = transpile(qc, initial_layout=[0, 1, 2]) expected_qasm = "\n".join( [ "OPENQASM 3;", "gate u3(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {", " U(pi/2, 0, pi) _gate_q_0;", "}", "gate u2(_gate_p_0, _gate_p_1) _gate_q_0 {", " u3(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", " u2(0, pi) _gate_q_0;", "}", "gate x _gate_q_0 {", " u3(pi, 0, pi) _gate_q_0;", "}", "bit[2] c;", "h $1;", "cx $1, $2;", "barrier $0, $1, $2;", "cx $0, $1;", "h $0;", "barrier $0, $1, $2;", "c[0] = measure $0;", "c[1] = measure $1;", "barrier $0, $1, $2;", "if (c[1]) {", " x $2;", "}", "if (c[0]) {", " z $2;", "}", "", ] ) self.assertEqual( Exporter(includes=[], basis_gates=["cx", "z", "U"]).dumps(transpiled), expected_qasm, ) def test_opaque_instruction_in_basis_gates(self): """Test that an instruction that is set in the basis gates is output verbatim with no definition.""" qc = QuantumCircuit(1) qc.x(0) qc.append(Gate("my_gate", 1, []), [0], []) basis_gates = ["my_gate", "x"] transpiled = transpile(qc, initial_layout=[0]) expected_qasm = "\n".join( [ "OPENQASM 3;", "x $0;", "my_gate $0;", "", ] ) self.assertEqual( Exporter(includes=[], basis_gates=basis_gates).dumps(transpiled), expected_qasm ) def test_reset_statement(self): """Test that a reset statement gets output into valid QASM 3. This includes tests of reset operations on single qubits and in nested scopes.""" qreg = QuantumRegister(2, "qr") qc = QuantumCircuit(qreg) qc.reset(0) qc.reset([0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", "qubit[2] qr;", "reset qr[0];", "reset qr[0];", "reset qr[1];", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(qc), expected_qasm) def test_delay_statement(self): """Test that delay operations get output into valid QASM 3.""" qreg = QuantumRegister(2, "qr") qc = QuantumCircuit(qreg) qc.delay(100, qreg[0], unit="ms") qc.delay(2, qreg[1], unit="ps") # "ps" is not a valid unit in OQ3, so we need to convert. expected_qasm = "\n".join( [ "OPENQASM 3;", "qubit[2] qr;", "delay[100ms] qr[0];", "delay[2000ns] qr[1];", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(qc), expected_qasm) def test_loose_qubits(self): """Test that qubits that are not in any register can be used without issue.""" bits = [Qubit(), Qubit()] qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(bits, qr, cr) qc.h(0) qc.h(1) qc.h(2) qc.h(3) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit _qubit0;", "qubit _qubit1;", "qubit[2] qr;", "h _qubit0;", "h _qubit1;", "h qr[0];", "h qr[1];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_loose_clbits(self): """Test that clbits that are not in any register can be used without issue.""" qreg = QuantumRegister(1, name="qr") bits = [Clbit() for _ in [None] * 7] cr1 = ClassicalRegister(name="cr1", bits=bits[1:3]) cr2 = ClassicalRegister(name="cr2", bits=bits[4:6]) qc = QuantumCircuit(bits, qreg, cr1, cr2) qc.measure(0, 0) qc.measure(0, 1) qc.measure(0, 2) qc.measure(0, 3) qc.measure(0, 4) qc.measure(0, 5) qc.measure(0, 6) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit _bit0;", "bit _bit3;", "bit _bit6;", "bit[2] cr1;", "bit[2] cr2;", "qubit[1] qr;", "_bit0 = measure qr[0];", "cr1[0] = measure qr[0];", "cr1[1] = measure qr[0];", "_bit3 = measure qr[0];", "cr2[0] = measure qr[0];", "cr2[1] = measure qr[0];", "_bit6 = measure qr[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_classical_register_aliasing(self): """Test that clbits that are not in any register can be used without issue.""" qreg = QuantumRegister(1, name="qr") bits = [Clbit() for _ in [None] * 7] cr1 = ClassicalRegister(name="cr1", bits=bits[1:3]) cr2 = ClassicalRegister(name="cr2", bits=bits[4:6]) # cr3 overlaps cr2, but this should be allowed in this alias form. cr3 = ClassicalRegister(name="cr3", bits=bits[5:]) qc = QuantumCircuit(bits, qreg, cr1, cr2, cr3) qc.measure(0, 0) qc.measure(0, 1) qc.measure(0, 2) qc.measure(0, 3) qc.measure(0, 4) qc.measure(0, 5) qc.measure(0, 6) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit _bit0;", "bit _bit1;", "bit _bit2;", "bit _bit3;", "bit _bit4;", "bit _bit5;", "bit _bit6;", "let cr1 = {_bit1, _bit2};", "let cr2 = {_bit4, _bit5};", "let cr3 = {cr2[1], _bit6};", "qubit[1] qr;", "_bit0 = measure qr[0];", "cr1[0] = measure qr[0];", "cr1[1] = measure qr[0];", "_bit3 = measure qr[0];", "cr2[0] = measure qr[0];", "cr3[0] = measure qr[0];", "cr3[1] = measure qr[0];", "", ] ) self.assertEqual(dumps(qc, allow_aliasing=True), expected_qasm) def test_old_alias_classical_registers_option(self): """Test that the ``alias_classical_registers`` option still functions during its changeover period.""" qreg = QuantumRegister(1, name="qr") bits = [Clbit() for _ in [None] * 7] cr1 = ClassicalRegister(name="cr1", bits=bits[1:3]) cr2 = ClassicalRegister(name="cr2", bits=bits[4:6]) # cr3 overlaps cr2, but this should be allowed in this alias form. cr3 = ClassicalRegister(name="cr3", bits=bits[5:]) qc = QuantumCircuit(bits, qreg, cr1, cr2, cr3) qc.measure(0, 0) qc.measure(0, 1) qc.measure(0, 2) qc.measure(0, 3) qc.measure(0, 4) qc.measure(0, 5) qc.measure(0, 6) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit _bit0;", "bit _bit1;", "bit _bit2;", "bit _bit3;", "bit _bit4;", "bit _bit5;", "bit _bit6;", "let cr1 = {_bit1, _bit2};", "let cr2 = {_bit4, _bit5};", "let cr3 = {cr2[1], _bit6};", "qubit[1] qr;", "_bit0 = measure qr[0];", "cr1[0] = measure qr[0];", "cr1[1] = measure qr[0];", "_bit3 = measure qr[0];", "cr2[0] = measure qr[0];", "cr3[0] = measure qr[0];", "cr3[1] = measure qr[0];", "", ] ) self.assertEqual(dumps(qc, alias_classical_registers=True), expected_qasm) def test_simple_for_loop(self): """Test that a simple for loop outputs the expected result.""" parameter = Parameter("x") loop_body = QuantumCircuit(1) loop_body.rx(parameter, 0) loop_body.break_loop() loop_body.continue_loop() qc = QuantumCircuit(2) qc.for_loop([0, 3, 4], parameter, loop_body, [1], []) qc.x(0) qr_name = qc.qregs[0].name expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"qubit[2] {qr_name};", f"for {parameter.name} in {{0, 3, 4}} {{", f" rx({parameter.name}) {qr_name}[1];", " break;", " continue;", "}", f"x {qr_name}[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_nested_for_loop(self): """Test that a for loop nested inside another outputs the expected result.""" inner_parameter = Parameter("x") outer_parameter = Parameter("y") inner_body = QuantumCircuit(2) inner_body.rz(inner_parameter, 0) inner_body.rz(outer_parameter, 1) inner_body.break_loop() outer_body = QuantumCircuit(2) outer_body.h(0) outer_body.rz(outer_parameter, 1) # Note we reverse the order of the bits here to test that this is traced. outer_body.for_loop(range(1, 5, 2), inner_parameter, inner_body, [1, 0], []) outer_body.continue_loop() qc = QuantumCircuit(2) qc.for_loop(range(4), outer_parameter, outer_body, [0, 1], []) qc.x(0) qr_name = qc.qregs[0].name expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"qubit[2] {qr_name};", f"for {outer_parameter.name} in [0:3] {{", f" h {qr_name}[0];", f" rz({outer_parameter.name}) {qr_name}[1];", f" for {inner_parameter.name} in [1:2:4] {{", # Note the reversed bit order. f" rz({inner_parameter.name}) {qr_name}[1];", f" rz({outer_parameter.name}) {qr_name}[0];", " break;", " }", " continue;", "}", f"x {qr_name}[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_regular_parameter_in_nested_for_loop(self): """Test that a for loop nested inside another outputs the expected result, including defining parameters that are used in nested loop scopes.""" inner_parameter = Parameter("x") outer_parameter = Parameter("y") regular_parameter = Parameter("t") inner_body = QuantumCircuit(2) inner_body.h(0) inner_body.rx(regular_parameter, 1) inner_body.break_loop() outer_body = QuantumCircuit(2) outer_body.h(0) outer_body.h(1) # Note we reverse the order of the bits here to test that this is traced. outer_body.for_loop(range(1, 5, 2), inner_parameter, inner_body, [1, 0], []) outer_body.continue_loop() qc = QuantumCircuit(2) qc.for_loop(range(4), outer_parameter, outer_body, [0, 1], []) qc.x(0) qr_name = qc.qregs[0].name expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', # This next line will be missing until gh-7280 is fixed. f"input float[64] {regular_parameter.name};", f"qubit[2] {qr_name};", f"for {outer_parameter.name} in [0:3] {{", f" h {qr_name}[0];", f" h {qr_name}[1];", f" for {inner_parameter.name} in [1:2:4] {{", # Note the reversed bit order. f" h {qr_name}[1];", f" rx({regular_parameter.name}) {qr_name}[0];", " break;", " }", " continue;", "}", f"x {qr_name}[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_for_loop_with_no_parameter(self): """Test that a for loop with the parameter set to ``None`` outputs the expected result.""" loop_body = QuantumCircuit(1) loop_body.h(0) qc = QuantumCircuit(2) qc.for_loop([0, 3, 4], None, loop_body, [1], []) qr_name = qc.qregs[0].name expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"qubit[2] {qr_name};", "for _ in {0, 3, 4} {", f" h {qr_name}[1];", "}", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_simple_while_loop(self): """Test that a simple while loop works correctly.""" loop_body = QuantumCircuit(1) loop_body.h(0) loop_body.break_loop() loop_body.continue_loop() qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.while_loop((cr, 0), loop_body, [1], []) qc.x(0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "while (cr == 0) {", " h qr[1];", " break;", " continue;", "}", "x qr[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_nested_while_loop(self): """Test that a while loop nested inside another outputs the expected result.""" inner_body = QuantumCircuit(2, 2) inner_body.measure(0, 0) inner_body.measure(1, 1) inner_body.break_loop() outer_body = QuantumCircuit(2, 2) outer_body.measure(0, 0) outer_body.measure(1, 1) # We reverse the order of the bits here to test this works, and test a single-bit condition. outer_body.while_loop((outer_body.clbits[0], 0), inner_body, [1, 0], [1, 0]) outer_body.continue_loop() qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.while_loop((cr, 0), outer_body, [0, 1], [0, 1]) qc.x(0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "while (cr == 0) {", " cr[0] = measure qr[0];", " cr[1] = measure qr[1];", # Note the reversed bits in the body. " while (!cr[0]) {", " cr[1] = measure qr[1];", " cr[0] = measure qr[0];", " break;", " }", " continue;", "}", "x qr[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_simple_if_statement(self): """Test that a simple if statement with no else works correctly.""" true_body = QuantumCircuit(1) true_body.h(0) qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.if_test((cr, 0), true_body, [1], []) qc.x(0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "if (cr == 0) {", " h qr[1];", "}", "x qr[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_simple_if_else_statement(self): """Test that a simple if statement with an else branch works correctly.""" true_body = QuantumCircuit(1) true_body.h(0) false_body = QuantumCircuit(1) false_body.z(0) qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.if_else((cr, 0), true_body, false_body, [1], []) qc.x(0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "if (cr == 0) {", " h qr[1];", "} else {", " z qr[1];", "}", "x qr[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_nested_if_else_statement(self): """Test that a nested if/else statement works correctly.""" inner_true_body = QuantumCircuit(2, 2) inner_true_body.measure(0, 0) inner_false_body = QuantumCircuit(2, 2) inner_false_body.measure(1, 1) outer_true_body = QuantumCircuit(2, 2) outer_true_body.if_else( (outer_true_body.clbits[0], 0), inner_true_body, inner_false_body, [0, 1], [0, 1] ) outer_false_body = QuantumCircuit(2, 2) # Note the flipped bits here. outer_false_body.if_else( (outer_false_body.clbits[0], 1), inner_true_body, inner_false_body, [1, 0], [1, 0] ) qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.if_else((cr, 0), outer_true_body, outer_false_body, [0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "if (cr == 0) {", " if (!cr[0]) {", " cr[0] = measure qr[0];", " } else {", " cr[1] = measure qr[1];", " }", "} else {", " if (cr[0]) {", " cr[1] = measure qr[1];", " } else {", " cr[0] = measure qr[0];", " }", "}", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_chain_else_if(self): """Test the basic 'else/if' chaining logic for flattening the else scope if its content is a single if/else statement.""" inner_true_body = QuantumCircuit(2, 2) inner_true_body.measure(0, 0) inner_false_body = QuantumCircuit(2, 2) inner_false_body.measure(1, 1) outer_true_body = QuantumCircuit(2, 2) outer_true_body.if_else( (outer_true_body.clbits[0], 0), inner_true_body, inner_false_body, [0, 1], [0, 1] ) outer_false_body = QuantumCircuit(2, 2) # Note the flipped bits here. outer_false_body.if_else( (outer_false_body.clbits[0], 1), inner_true_body, inner_false_body, [1, 0], [1, 0] ) qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.if_else((cr, 0), outer_true_body, outer_false_body, [0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "if (cr == 0) {", " if (!cr[0]) {", " cr[0] = measure qr[0];", " } else {", " cr[1] = measure qr[1];", " }", "} else if (cr[0]) {", " cr[1] = measure qr[1];", "} else {", " cr[0] = measure qr[0];", "}", "", ] ) # This is not the default behaviour, and it's pretty buried how you'd access it. builder = QASM3Builder( qc, includeslist=("stdgates.inc",), basis_gates=("U",), disable_constants=False, allow_aliasing=False, ) stream = StringIO() BasicPrinter(stream, indent=" ", chain_else_if=True).visit(builder.build_program()) self.assertEqual(stream.getvalue(), expected_qasm) def test_chain_else_if_does_not_chain_if_extra_instructions(self): """Test the basic 'else/if' chaining logic for flattening the else scope if its content is a single if/else statement does not cause a flattening if the 'else' block is not a single if/else.""" inner_true_body = QuantumCircuit(2, 2) inner_true_body.measure(0, 0) inner_false_body = QuantumCircuit(2, 2) inner_false_body.measure(1, 1) outer_true_body = QuantumCircuit(2, 2) outer_true_body.if_else( (outer_true_body.clbits[0], 0), inner_true_body, inner_false_body, [0, 1], [0, 1] ) outer_false_body = QuantumCircuit(2, 2) # Note the flipped bits here. outer_false_body.if_else( (outer_false_body.clbits[0], 1), inner_true_body, inner_false_body, [1, 0], [1, 0] ) outer_false_body.h(0) qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="cr") qc = QuantumCircuit(qr, cr) qc.if_else((cr, 0), outer_true_body, outer_false_body, [0, 1], [0, 1]) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "bit[2] cr;", "qubit[2] qr;", "if (cr == 0) {", " if (!cr[0]) {", " cr[0] = measure qr[0];", " } else {", " cr[1] = measure qr[1];", " }", "} else {", " if (cr[0]) {", " cr[1] = measure qr[1];", " } else {", " cr[0] = measure qr[0];", " }", " h qr[0];", "}", "", ] ) # This is not the default behaviour, and it's pretty buried how you'd access it. builder = QASM3Builder( qc, includeslist=("stdgates.inc",), basis_gates=("U",), disable_constants=False, allow_aliasing=False, ) stream = StringIO() BasicPrinter(stream, indent=" ", chain_else_if=True).visit(builder.build_program()) self.assertEqual(stream.getvalue(), expected_qasm) def test_custom_gate_used_in_loop_scope(self): """Test that a custom gate only used within a loop scope still gets a definition at the top level.""" parameter_a = Parameter("a") parameter_b = Parameter("b") custom = QuantumCircuit(1) custom.rx(parameter_a, 0) custom_gate = custom.bind_parameters({parameter_a: 0.5}).to_gate() custom_gate.name = "custom" loop_body = QuantumCircuit(1) loop_body.append(custom_gate, [0]) qc = QuantumCircuit(1) qc.for_loop(range(2), parameter_b, loop_body, [0], []) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "gate custom _gate_q_0 {", " rx(0.5) _gate_q_0;", "}", "qubit[1] q;", "for b in [0:1] {", " custom q[0];", "}", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_registers_have_escaped_names(self): """Test that both types of register are emitted with safely escaped names if they begin with invalid names. Regression test of gh-9658.""" qc = QuantumCircuit( QuantumRegister(2, name="q_{reg}"), ClassicalRegister(2, name="c_{reg}") ) qc.measure([0, 1], [0, 1]) out_qasm = dumps(qc) matches = {match_["name"] for match_ in self.register_regex.finditer(out_qasm)} self.assertEqual(len(matches), 2, msg=f"Observed OQ3 output:\n{out_qasm}") def test_parameters_have_escaped_names(self): """Test that parameters are emitted with safely escaped names if they begin with invalid names. Regression test of gh-9658.""" qc = QuantumCircuit(1) qc.u(Parameter("p_{0}"), 2 * Parameter("p_?0!"), 0, 0) out_qasm = dumps(qc) matches = {match_["name"] for match_ in self.scalar_parameter_regex.finditer(out_qasm)} self.assertEqual(len(matches), 2, msg=f"Observed OQ3 output:\n{out_qasm}") def test_parameter_expression_after_naming_escape(self): """Test that :class:`.Parameter` instances are correctly renamed when they are used with :class:`.ParameterExpression` blocks, even if they have names that needed to be escaped.""" param = Parameter("measure") # an invalid name qc = QuantumCircuit(1) qc.u(2 * param, 0, 0, 0) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', "input float[64] _measure;", "qubit[1] q;", "U(2*_measure, 0, 0) q[0];", "", ] ) self.assertEqual(dumps(qc), expected_qasm) def test_parameters_and_registers_cannot_have_naming_clashes(self): """Test that parameters and registers are considered part of the same symbol table for the purposes of avoiding clashes.""" qreg = QuantumRegister(1, "clash") param = Parameter("clash") qc = QuantumCircuit(qreg) qc.u(param, 0, 0, 0) out_qasm = dumps(qc) register_name = self.register_regex.search(out_qasm) parameter_name = self.scalar_parameter_regex.search(out_qasm) self.assertTrue(register_name) self.assertTrue(parameter_name) self.assertIn("clash", register_name["name"]) self.assertIn("clash", parameter_name["name"]) self.assertNotEqual(register_name["name"], parameter_name["name"]) # Not necessarily all the reserved keywords, just a sensibly-sized subset. @data("bit", "const", "def", "defcal", "float", "gate", "include", "int", "let", "measure") def test_reserved_keywords_as_names_are_escaped(self, keyword): """Test that reserved keywords used to name registers and parameters are escaped into another form when output, and the escaping cannot introduce new conflicts.""" with self.subTest("register"): qreg = QuantumRegister(1, keyword) qc = QuantumCircuit(qreg) out_qasm = dumps(qc) register_name = self.register_regex.search(out_qasm) self.assertTrue(register_name, msg=f"Observed OQ3:\n{out_qasm}") self.assertNotEqual(keyword, register_name["name"]) with self.subTest("parameter"): qc = QuantumCircuit(1) param = Parameter(keyword) qc.u(param, 0, 0, 0) out_qasm = dumps(qc) parameter_name = self.scalar_parameter_regex.search(out_qasm) self.assertTrue(parameter_name, msg=f"Observed OQ3:\n{out_qasm}") self.assertNotEqual(keyword, parameter_name["name"]) def test_expr_condition(self): """Simple test that the conditions of `if`s and `while`s can be `Expr` nodes.""" bits = [Qubit(), Clbit()] cr = ClassicalRegister(2, "cr") if_body = QuantumCircuit(1) if_body.x(0) while_body = QuantumCircuit(1) while_body.x(0) qc = QuantumCircuit(bits, cr) qc.if_test(expr.logic_not(qc.clbits[0]), if_body, [0], []) qc.while_loop(expr.equal(cr, 3), while_body, [0], []) expected = """\ OPENQASM 3; include "stdgates.inc"; bit _bit0; bit[2] cr; qubit _qubit0; if (!_bit0) { x _qubit0; } while (cr == 3) { x _qubit0; } """ self.assertEqual(dumps(qc), expected) def test_expr_nested_condition(self): """Simple test that the conditions of `if`s and `while`s can be `Expr` nodes when nested, and the mapping of inner bits to outer bits is correct.""" bits = [Qubit(), Clbit(), Clbit()] cr = ClassicalRegister(2, "cr") inner_if_body = QuantumCircuit(1) inner_if_body.x(0) outer_if_body = QuantumCircuit(1, 1) outer_if_body.if_test(expr.lift(outer_if_body.clbits[0]), inner_if_body, [0], []) inner_while_body = QuantumCircuit(1) inner_while_body.x(0) outer_while_body = QuantumCircuit([Qubit()], cr) outer_while_body.while_loop(expr.equal(expr.bit_and(cr, 3), 3), inner_while_body, [0], []) qc = QuantumCircuit(bits, cr) qc.if_test(expr.logic_not(qc.clbits[0]), outer_if_body, [0], [1]) qc.while_loop(expr.equal(cr, 3), outer_while_body, [0], cr) expected = """\ OPENQASM 3; include "stdgates.inc"; bit _bit0; bit _bit1; bit[2] cr; qubit _qubit0; if (!_bit0) { if (_bit1) { x _qubit0; } } while (cr == 3) { while ((cr & 3) == 3) { x _qubit0; } } """ self.assertEqual(dumps(qc), expected) def test_expr_associativity_left(self): """Test that operations that are in the expression tree in a left-associative form are output to OQ3 correctly.""" body = QuantumCircuit() cr1 = ClassicalRegister(3, "cr1") cr2 = ClassicalRegister(3, "cr2") cr3 = ClassicalRegister(3, "cr3") qc = QuantumCircuit(cr1, cr2, cr3) qc.if_test(expr.equal(expr.bit_and(expr.bit_and(cr1, cr2), cr3), 7), body.copy(), [], []) qc.if_test(expr.equal(expr.bit_or(expr.bit_or(cr1, cr2), cr3), 7), body.copy(), [], []) qc.if_test(expr.equal(expr.bit_xor(expr.bit_xor(cr1, cr2), cr3), 7), body.copy(), [], []) qc.if_test(expr.logic_and(expr.logic_and(cr1[0], cr1[1]), cr1[2]), body.copy(), [], []) qc.if_test(expr.logic_or(expr.logic_or(cr1[0], cr1[1]), cr1[2]), body.copy(), [], []) # Note that bitwise operations have lower priority than `==` so there's extra parentheses. # All these operators are left-associative in OQ3. expected = """\ OPENQASM 3; include "stdgates.inc"; bit[3] cr1; bit[3] cr2; bit[3] cr3; if ((cr1 & cr2 & cr3) == 7) { } if ((cr1 | cr2 | cr3) == 7) { } if ((cr1 ^ cr2 ^ cr3) == 7) { } if (cr1[0] && cr1[1] && cr1[2]) { } if (cr1[0] || cr1[1] || cr1[2]) { } """ self.assertEqual(dumps(qc), expected) def test_expr_associativity_right(self): """Test that operations that are in the expression tree in a right-associative form are output to OQ3 correctly.""" body = QuantumCircuit() cr1 = ClassicalRegister(3, "cr1") cr2 = ClassicalRegister(3, "cr2") cr3 = ClassicalRegister(3, "cr3") qc = QuantumCircuit(cr1, cr2, cr3) qc.if_test(expr.equal(expr.bit_and(cr1, expr.bit_and(cr2, cr3)), 7), body.copy(), [], []) qc.if_test(expr.equal(expr.bit_or(cr1, expr.bit_or(cr2, cr3)), 7), body.copy(), [], []) qc.if_test(expr.equal(expr.bit_xor(cr1, expr.bit_xor(cr2, cr3)), 7), body.copy(), [], []) qc.if_test(expr.logic_and(cr1[0], expr.logic_and(cr1[1], cr1[2])), body.copy(), [], []) qc.if_test(expr.logic_or(cr1[0], expr.logic_or(cr1[1], cr1[2])), body.copy(), [], []) # Note that bitwise operations have lower priority than `==` so there's extra parentheses. # All these operators are left-associative in OQ3, so we need parentheses for them to be # parsed correctly. Mathematically, they're all actually associative in general, so the # order doesn't _technically_ matter. expected = """\ OPENQASM 3; include "stdgates.inc"; bit[3] cr1; bit[3] cr2; bit[3] cr3; if ((cr1 & (cr2 & cr3)) == 7) { } if ((cr1 | (cr2 | cr3)) == 7) { } if ((cr1 ^ (cr2 ^ cr3)) == 7) { } if (cr1[0] && (cr1[1] && cr1[2])) { } if (cr1[0] || (cr1[1] || cr1[2])) { } """ self.assertEqual(dumps(qc), expected) def test_expr_binding_unary(self): """Test that nested unary operators don't insert unnecessary brackets.""" body = QuantumCircuit() cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(cr) qc.if_test(expr.equal(expr.bit_not(expr.bit_not(cr)), 3), body.copy(), [], []) qc.if_test(expr.logic_not(expr.logic_not(cr[0])), body.copy(), [], []) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] cr; if (~~cr == 3) { } if (!!cr[0]) { } """ self.assertEqual(dumps(qc), expected) def test_expr_precedence(self): """Test that the precedence properties of operators are correctly output.""" body = QuantumCircuit() cr = ClassicalRegister(2, "cr") # This tree is _completely_ inside out, so there's brackets needed round every operand. inside_out = expr.logic_not( expr.less( expr.bit_and( expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)), expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)), ), expr.bit_and( expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)), expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)), ), ) ) # This one is the other way round - the tightest-binding operations are on the inside, so no # brackets should be needed at all except to put in a comparison to a bitwise binary # operation, since those bind less tightly than anything that can cast them to a bool. outside_in = expr.logic_or( expr.logic_and( expr.equal(expr.bit_or(cr, cr), expr.bit_and(cr, cr)), expr.equal(expr.bit_and(cr, cr), expr.bit_or(cr, cr)), ), expr.logic_and( expr.greater(expr.bit_or(cr, cr), expr.bit_xor(cr, cr)), expr.less_equal(expr.bit_xor(cr, cr), expr.bit_or(cr, cr)), ), ) # And an extra test of the logical operator order. logics = expr.logic_or( expr.logic_and( expr.logic_or(expr.logic_not(cr[0]), expr.logic_not(cr[0])), expr.logic_not(expr.logic_and(cr[0], cr[0])), ), expr.logic_and( expr.logic_not(expr.logic_and(cr[0], cr[0])), expr.logic_or(expr.logic_not(cr[0]), expr.logic_not(cr[0])), ), ) qc = QuantumCircuit(cr) qc.if_test(inside_out, body.copy(), [], []) qc.if_test(outside_in, body.copy(), [], []) qc.if_test(logics, body.copy(), [], []) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] cr; if (!((((cr | cr) ^ (cr | cr)) & ((cr | cr) ^ (cr | cr)))\ < (((cr | cr) ^ (cr | cr)) & ((cr | cr) ^ (cr | cr))))) { } if ((cr | cr) == (cr & cr) && (cr & cr) == (cr | cr)\ || (cr | cr) > (cr ^ cr) && (cr ^ cr) <= (cr | cr)) { } if ((!cr[0] || !cr[0]) && !(cr[0] && cr[0]) || !(cr[0] && cr[0]) && (!cr[0] || !cr[0])) { } """ self.assertEqual(dumps(qc), expected) def test_no_unnecessary_cast(self): """This is a bit of a cross `Expr`-constructor / OQ3-exporter test. It doesn't really matter whether or not the `Expr` constructor functions insert cast nodes into their output for the literals (at the time of writing [commit 2616602], they don't because they do some type inference) but the OQ3 export definitely shouldn't have them.""" cr = ClassicalRegister(8, "cr") qc = QuantumCircuit(cr) # Note that the integer '1' has a minimum bit-width of 1, whereas the register has a width # of 8. We're testing to make sure that there's no spurious cast up from `bit[1]` to # `bit[8]`, or anything like that, _whether or not_ the `Expr` node includes one. qc.if_test(expr.equal(cr, 1), QuantumCircuit(), [], []) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[8] cr; if (cr == 1) { } """ self.assertEqual(dumps(qc), expected) class TestCircuitQASM3ExporterTemporaryCasesWithBadParameterisation(QiskitTestCase): """Test functionality that is not what we _want_, but is what we need to do while the definition of custom gates with parameterisation does not work correctly. These tests are modified versions of those marked with the `requires_fixed_parameterisation` decorator, and this whole class can be deleted once those are fixed. See gh-7335. """ maxDiff = 1_000_000 def test_basis_gates(self): """Teleportation with physical qubits""" qc = QuantumCircuit(3, 2) first_h = qc.h(1)[0].operation qc.cx(1, 2) qc.barrier() qc.cx(0, 1) qc.h(0) qc.barrier() qc.measure([0, 1], [0, 1]) qc.barrier() first_x = qc.x(2).c_if(qc.clbits[1], 1)[0].operation qc.z(2).c_if(qc.clbits[0], 1) u2 = first_h.definition.data[0].operation u3_1 = u2.definition.data[0].operation u3_2 = first_x.definition.data[0].operation expected_qasm = "\n".join( [ "OPENQASM 3;", f"gate u3_{id(u3_1)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(pi/2, 0, pi) _gate_q_0;", "}", f"gate u2_{id(u2)}(_gate_p_0, _gate_p_1) _gate_q_0 {{", f" u3_{id(u3_1)}(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", f" u2_{id(u2)}(0, pi) _gate_q_0;", "}", f"gate u3_{id(u3_2)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(pi, 0, pi) _gate_q_0;", "}", "gate x _gate_q_0 {", f" u3_{id(u3_2)}(pi, 0, pi) _gate_q_0;", "}", "bit[2] c;", "qubit[3] q;", "h q[1];", "cx q[1], q[2];", "barrier q[0], q[1], q[2];", "cx q[0], q[1];", "h q[0];", "barrier q[0], q[1], q[2];", "c[0] = measure q[0];", "c[1] = measure q[1];", "barrier q[0], q[1], q[2];", "if (c[1]) {", " x q[2];", "}", "if (c[0]) {", " z q[2];", "}", "", ] ) self.assertEqual( Exporter(includes=[], basis_gates=["cx", "z", "U"]).dumps(qc), expected_qasm, ) def test_teleportation(self): """Teleportation with physical qubits""" qc = QuantumCircuit(3, 2) qc.h(1) qc.cx(1, 2) qc.barrier() qc.cx(0, 1) qc.h(0) qc.barrier() qc.measure([0, 1], [0, 1]) qc.barrier() qc.x(2).c_if(qc.clbits[1], 1) qc.z(2).c_if(qc.clbits[0], 1) transpiled = transpile(qc, initial_layout=[0, 1, 2]) first_h = transpiled.data[0].operation u2 = first_h.definition.data[0].operation u3_1 = u2.definition.data[0].operation first_x = transpiled.data[-2].operation u3_2 = first_x.definition.data[0].operation first_z = transpiled.data[-1].operation u1 = first_z.definition.data[0].operation u3_3 = u1.definition.data[0].operation expected_qasm = "\n".join( [ "OPENQASM 3;", f"gate u3_{id(u3_1)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(pi/2, 0, pi) _gate_q_0;", "}", f"gate u2_{id(u2)}(_gate_p_0, _gate_p_1) _gate_q_0 {{", f" u3_{id(u3_1)}(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", f" u2_{id(u2)}(0, pi) _gate_q_0;", "}", "gate cx c, t {", " ctrl @ U(pi, 0, pi) c, t;", "}", f"gate u3_{id(u3_2)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(pi, 0, pi) _gate_q_0;", "}", "gate x _gate_q_0 {", f" u3_{id(u3_2)}(pi, 0, pi) _gate_q_0;", "}", f"gate u3_{id(u3_3)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(0, 0, pi) _gate_q_0;", "}", f"gate u1_{id(u1)}(_gate_p_0) _gate_q_0 {{", f" u3_{id(u3_3)}(0, 0, pi) _gate_q_0;", "}", "gate z _gate_q_0 {", f" u1_{id(u1)}(pi) _gate_q_0;", "}", "bit[2] c;", "h $1;", "cx $1, $2;", "barrier $0, $1, $2;", "cx $0, $1;", "h $0;", "barrier $0, $1, $2;", "c[0] = measure $0;", "c[1] = measure $1;", "barrier $0, $1, $2;", "if (c[1]) {", " x $2;", "}", "if (c[0]) {", " z $2;", "}", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(transpiled), expected_qasm) def test_custom_gate_with_params_bound_main_call(self): """Custom gate with unbound parameters that are bound in the main circuit""" parameter0 = Parameter("p0") parameter1 = Parameter("p1") custom = QuantumCircuit(2, name="custom") custom.rz(parameter0, 0) custom.rz(parameter1 / 2, 1) qr_all_qubits = QuantumRegister(3, "q") qr_r = QuantumRegister(3, "r") circuit = QuantumCircuit(qr_all_qubits, qr_r) circuit.append(custom.to_gate(), [qr_all_qubits[0], qr_r[0]]) circuit.assign_parameters({parameter0: pi, parameter1: pi / 2}, inplace=True) custom_id = id(circuit.data[0].operation) expected_qasm = "\n".join( [ "OPENQASM 3;", 'include "stdgates.inc";', f"gate custom_{custom_id}(_gate_p_0, _gate_p_1) _gate_q_0, _gate_q_1 {{", " rz(pi) _gate_q_0;", " rz(pi/4) _gate_q_1;", "}", "qubit[3] q;", "qubit[3] r;", f"custom_{custom_id}(pi, pi/2) q[0], r[0];", "", ] ) self.assertEqual(Exporter().dumps(circuit), expected_qasm) def test_no_include(self): """Test explicit gate declaration (no include)""" q = QuantumRegister(2, "q") circuit = QuantumCircuit(q) circuit.rz(pi / 2, 0) circuit.sx(0) circuit.cx(0, 1) rz = circuit.data[0].operation u1_1 = rz.definition.data[0].operation u3_1 = u1_1.definition.data[0].operation sx = circuit.data[1].operation sdg = sx.definition.data[0].operation u1_2 = sdg.definition.data[0].operation u3_2 = u1_2.definition.data[0].operation h_ = sx.definition.data[1].operation u2_1 = h_.definition.data[0].operation u3_3 = u2_1.definition.data[0].operation expected_qasm = "\n".join( [ "OPENQASM 3;", f"gate u3_{id(u3_1)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(0, 0, pi/2) _gate_q_0;", "}", f"gate u1_{id(u1_1)}(_gate_p_0) _gate_q_0 {{", f" u3_{id(u3_1)}(0, 0, pi/2) _gate_q_0;", "}", f"gate rz_{id(rz)}(_gate_p_0) _gate_q_0 {{", f" u1_{id(u1_1)}(pi/2) _gate_q_0;", "}", f"gate u3_{id(u3_2)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(0, 0, -pi/2) _gate_q_0;", "}", f"gate u1_{id(u1_2)}(_gate_p_0) _gate_q_0 {{", f" u3_{id(u3_2)}(0, 0, -pi/2) _gate_q_0;", "}", "gate sdg _gate_q_0 {", f" u1_{id(u1_2)}(-pi/2) _gate_q_0;", "}", f"gate u3_{id(u3_3)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{", " U(pi/2, 0, pi) _gate_q_0;", "}", f"gate u2_{id(u2_1)}(_gate_p_0, _gate_p_1) _gate_q_0 {{", f" u3_{id(u3_3)}(pi/2, 0, pi) _gate_q_0;", "}", "gate h _gate_q_0 {", f" u2_{id(u2_1)}(0, pi) _gate_q_0;", "}", "gate sx _gate_q_0 {", " sdg _gate_q_0;", " h _gate_q_0;", " sdg _gate_q_0;", "}", "gate cx c, t {", " ctrl @ U(pi, 0, pi) c, t;", "}", "qubit[2] q;", f"rz_{id(rz)}(pi/2) q[0];", "sx q[0];", "cx q[0], q[1];", "", ] ) self.assertEqual(Exporter(includes=[]).dumps(circuit), expected_qasm) def test_unusual_conditions(self): """Test that special QASM constructs such as ``measure`` are correctly handled when the Terra instructions have old-style conditions.""" qc = QuantumCircuit(3, 2) qc.h(0) qc.measure(0, 0) qc.measure(1, 1).c_if(0, True) qc.reset([0, 1]).c_if(0, True) with qc.while_loop((qc.clbits[0], True)): qc.break_loop().c_if(0, True) qc.continue_loop().c_if(0, True) # Terra forbids delay and barrier from being conditioned through `c_if`, but in theory they # should work fine in a dynamic-circuits sense (although what a conditional barrier _means_ # is a whole other kettle of fish). delay = Delay(16, "dt") delay.condition = (qc.clbits[0], True) qc.append(delay, [0], []) barrier = Barrier(2) barrier.condition = (qc.clbits[0], True) qc.append(barrier, [0, 1], []) expected = """ OPENQASM 3; include "stdgates.inc"; bit[2] c; qubit[3] q; h q[0]; c[0] = measure q[0]; if (c[0]) { c[1] = measure q[1]; } if (c[0]) { reset q[0]; } if (c[0]) { reset q[1]; } while (c[0]) { if (c[0]) { break; } if (c[0]) { continue; } } if (c[0]) { delay[16dt] q[0]; } if (c[0]) { barrier q[0], q[1]; }""" self.assertEqual(dumps(qc).strip(), expected.strip()) class TestExperimentalFeatures(QiskitTestCase): """Tests of features that are hidden behind experimental flags.""" maxDiff = None def test_switch_forbidden_without_flag(self): """Omitting the feature flag should raise an error.""" case = QuantumCircuit(1) circuit = QuantumCircuit(1, 1) circuit.switch(circuit.clbits[0], [((True, False), case)], [0], []) with self.assertRaisesRegex(QASM3ExporterError, "'switch' statements are not stabilized"): dumps(circuit) def test_switch_clbit(self): """Test that a switch statement can be constructed with a bit as a condition.""" qubit = Qubit() clbit = Clbit() case1 = QuantumCircuit([qubit, clbit]) case1.x(0) case2 = QuantumCircuit([qubit, clbit]) case2.z(0) circuit = QuantumCircuit([qubit, clbit]) circuit.switch(clbit, [(True, case1), (False, case2)], [0], [0]) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit _bit0; int switch_dummy; qubit _qubit0; switch_dummy = _bit0; switch (switch_dummy) { case 1: { x _qubit0; } break; case 0: { z _qubit0; } break; } """ self.assertEqual(test, expected) def test_switch_register(self): """Test that a switch statement can be constructed with a register as a condition.""" qubit = Qubit() creg = ClassicalRegister(2, "c") case1 = QuantumCircuit([qubit], creg) case1.x(0) case2 = QuantumCircuit([qubit], creg) case2.y(0) case3 = QuantumCircuit([qubit], creg) case3.z(0) circuit = QuantumCircuit([qubit], creg) circuit.switch(creg, [(0, case1), (1, case2), (2, case3)], [0], circuit.clbits) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] c; int switch_dummy; qubit _qubit0; switch_dummy = c; switch (switch_dummy) { case 0: { x _qubit0; } break; case 1: { y _qubit0; } break; case 2: { z _qubit0; } break; } """ self.assertEqual(test, expected) def test_switch_with_default(self): """Test that a switch statement can be constructed with a default case at the end.""" qubit = Qubit() creg = ClassicalRegister(2, "c") case1 = QuantumCircuit([qubit], creg) case1.x(0) case2 = QuantumCircuit([qubit], creg) case2.y(0) case3 = QuantumCircuit([qubit], creg) case3.z(0) circuit = QuantumCircuit([qubit], creg) circuit.switch(creg, [(0, case1), (1, case2), (CASE_DEFAULT, case3)], [0], circuit.clbits) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] c; int switch_dummy; qubit _qubit0; switch_dummy = c; switch (switch_dummy) { case 0: { x _qubit0; } break; case 1: { y _qubit0; } break; default: { z _qubit0; } break; } """ self.assertEqual(test, expected) def test_switch_multiple_cases_to_same_block(self): """Test that it is possible to add multiple cases that apply to the same block, if they are given as a compound value. This is an allowed special case of block fall-through.""" qubit = Qubit() creg = ClassicalRegister(2, "c") case1 = QuantumCircuit([qubit], creg) case1.x(0) case2 = QuantumCircuit([qubit], creg) case2.y(0) circuit = QuantumCircuit([qubit], creg) circuit.switch(creg, [(0, case1), ((1, 2), case2)], [0], circuit.clbits) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] c; int switch_dummy; qubit _qubit0; switch_dummy = c; switch (switch_dummy) { case 0: { x _qubit0; } break; case 1: case 2: { y _qubit0; } break; } """ self.assertEqual(test, expected) def test_multiple_switches_dont_clash_on_dummy(self): """Test that having more than one switch statement in the circuit doesn't cause naming clashes in the dummy integer value used.""" qubit = Qubit() creg = ClassicalRegister(2, "switch_dummy") case1 = QuantumCircuit([qubit], creg) case1.x(0) case2 = QuantumCircuit([qubit], creg) case2.y(0) circuit = QuantumCircuit([qubit], creg) circuit.switch(creg, [(0, case1), ((1, 2), case2)], [0], circuit.clbits) circuit.switch(creg, [(0, case1), ((1, 2), case2)], [0], circuit.clbits) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] switch_dummy; int switch_dummy__generated0; int switch_dummy__generated1; qubit _qubit0; switch_dummy__generated0 = switch_dummy; switch (switch_dummy__generated0) { case 0: { x _qubit0; } break; case 1: case 2: { y _qubit0; } break; } switch_dummy__generated1 = switch_dummy; switch (switch_dummy__generated1) { case 0: { x _qubit0; } break; case 1: case 2: { y _qubit0; } break; } """ self.assertEqual(test, expected) def test_switch_nested_in_if(self): """Test that the switch statement works when in a nested scope, including the dummy classical variable being declared globally. This isn't necessary in the OQ3 language, but it is universally valid and the IBM QSS stack prefers that. They're our primary consumers of OQ3 strings, so it's best to play nicely with them.""" qubit = Qubit() creg = ClassicalRegister(2, "c") case1 = QuantumCircuit([qubit], creg) case1.x(0) case2 = QuantumCircuit([qubit], creg) case2.y(0) body = QuantumCircuit([qubit], creg) body.switch(creg, [(0, case1), ((1, 2), case2)], [0], body.clbits) circuit = QuantumCircuit([qubit], creg) circuit.if_else((creg, 1), body.copy(), body, [0], body.clbits) test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1) expected = """\ OPENQASM 3; include "stdgates.inc"; bit[2] c; int switch_dummy; int switch_dummy__generated0; qubit _qubit0; if (c == 1) { switch_dummy = c; switch (switch_dummy) { case 0: { x _qubit0; } break; case 1: case 2: { y _qubit0; } break; } } else { switch_dummy__generated0 = c; switch (switch_dummy__generated0) { case 0: { x _qubit0; } break; case 1: case 2: { y _qubit0; } break; } } """ self.assertEqual(test, expected) def test_expr_target(self): """Simple test that the target of `switch` can be `Expr` nodes.""" bits = [Qubit(), Clbit()] cr = ClassicalRegister(2, "cr") case0 = QuantumCircuit(1) case0.x(0) case1 = QuantumCircuit(1) case1.x(0) qc = QuantumCircuit(bits, cr) qc.switch(expr.logic_not(bits[1]), [(False, case0)], [0], []) qc.switch(expr.bit_and(cr, 3), [(3, case1)], [0], []) expected = """\ OPENQASM 3; include "stdgates.inc"; bit _bit0; bit[2] cr; int switch_dummy; int switch_dummy__generated0; qubit _qubit0; switch_dummy = !_bit0; switch (switch_dummy) { case 0: { x _qubit0; } break; } switch_dummy__generated0 = cr & 3; switch (switch_dummy__generated0) { case 3: { x _qubit0; } break; } """ test = dumps(qc, experimental=ExperimentalFeatures.SWITCH_CASE_V1) self.assertEqual(test, expected) @ddt class TestQASM3ExporterFailurePaths(QiskitTestCase): """Tests of the failure paths for the exporter.""" def test_disallow_overlapping_classical_registers_if_no_aliasing(self): """Test that the exporter rejects circuits with a classical bit in more than one register if the ``alias_classical_registers`` option is set false.""" qubits = [Qubit() for _ in [None] * 3] clbits = [Clbit() for _ in [None] * 5] registers = [ClassicalRegister(bits=clbits[:4]), ClassicalRegister(bits=clbits[1:])] qc = QuantumCircuit(qubits, *registers) exporter = Exporter(alias_classical_registers=False) with self.assertRaisesRegex(QASM3ExporterError, r"classical registers .* overlap"): exporter.dumps(qc) @data([1, 2, 1.1], [1j, 2]) def test_disallow_for_loops_with_non_integers(self, indices): """Test that the exporter rejects ``for`` loops that include non-integer values in their index sets.""" loop_body = QuantumCircuit() qc = QuantumCircuit(2, 2) qc.for_loop(indices, None, loop_body, [], []) exporter = Exporter() with self.assertRaisesRegex( QASM3ExporterError, r"The values in QASM 3 'for' loops must all be integers.*" ): exporter.dumps(qc) def test_disallow_custom_subroutine_with_parameters(self): """Test that the exporter throws an error instead of trying to export a subroutine with parameters, while this is not supported.""" subroutine = QuantumCircuit(1) subroutine.rx(Parameter("x"), 0) qc = QuantumCircuit(1) qc.append(subroutine.to_instruction(), [0], []) exporter = Exporter() with self.assertRaisesRegex( QASM3ExporterError, "Exporting non-unitary instructions is not yet supported" ): exporter.dumps(qc) def test_disallow_opaque_instruction(self): """Test that the exporter throws an error instead of trying to export something into a ``defcal`` block, while this is not supported.""" qc = QuantumCircuit(1) qc.append(Instruction("opaque", 1, 0, []), [0], []) exporter = Exporter() with self.assertRaisesRegex( QASM3ExporterError, "Exporting opaque instructions .* is not yet supported" ): exporter.dumps(qc)
https://github.com/deveshq/QC-with-qiskit
deveshq
import numpy as np from numpy import pi # importing Qiskit from qiskit import QuantumCircuit, transpile, assemble, Aer from qiskit.visualization import plot_histogram, plot_bloch_multivector qc = QuantumCircuit(3) qc.h(2) qc.cp(pi/2, 1, 2) qc.cp(pi/4, 0, 2) qc.h(1) qc.cp(pi/2, 0, 1) qc.h(0) qc.swap(0, 2) qc.draw() def qft_rotations(circuit, n): if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(pi/2**(n-qubit), qubit, n) qft_rotations(circuit, n) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft(circuit, n): qft_rotations(circuit, n) swap_registers(circuit, n) return circuit qc = QuantumCircuit(4) qft(qc,4) qc.draw() # Create the circuit qc = QuantumCircuit(3) # Encode the state 5 (101 in binary) qc.x(0) qc.x(2) qc.draw() sim = Aer.get_backend("aer_simulator") qc_init = qc.copy() qc_init.save_statevector() statevector = sim.run(qc_init).result().get_statevector() plot_bloch_multivector(statevector) qft(qc, 3) qc.draw() qc.save_statevector() statevector = sim.run(qc).result().get_statevector() plot_bloch_multivector(statevector)
https://github.com/Anastasia-Sim/PoW-QCSA-fa22
Anastasia-Sim
#Importing all the necessary libraries !pip install qiskit matplotlib import qiskit import matplotlib from qiskit import QuantumCircuit, assemble, Aer, circuit, QuantumRegister, ClassicalRegister from qiskit.visualization import plot_histogram from qiskit.quantum_info.operators import Operator from qiskit.extensions import UnitaryGate hash_gate = Operator([ [0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0], [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,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0], [0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,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,0,0,0], [0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0], [0,0,0,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,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,0,0,0,0,0,0,0] ]) hash_gate.name = "Hash Gate" hash_dagger = hash_gate.conjugate().transpose() hash_gate.name = "Hash Dagger" #Testing input 0110 -> should get 1000 n_qubits = 4 controls = QuantumRegister(n_qubits) outputs = ClassicalRegister(n_qubits) circuit = QuantumCircuit(controls, outputs) circuit.x(controls[1:3]) circuit.draw() circuit.append(hash_gate, [0,1,2,3]) circuit.barrier(controls) circuit.measure(controls, outputs) circuit.draw() sim = Aer.get_backend('aer_simulator') result = sim.run(circuit).result() counts = result.get_counts() plot_histogram(counts) n_qubits = 4 controls = QuantumRegister(n_qubits) outputs = ClassicalRegister(n_qubits) circuit = QuantumCircuit(controls, outputs) circuit.x(controls[1:3]) circuit.draw() circuit.append(hash_gate, [0,1,2,3]) circuit.append(hash_dagger, [0,1,2,3]) circuit.barrier(controls) circuit.measure(controls, outputs) circuit.draw() # We begin by declaring a simulator for our circuit to run on sim = Aer.get_backend('aer_simulator') # We run the simulator with sim.run(QUANTUM CIRCUIT), # And we get the resulting values with .result() result = sim.run(circuit).result() # We then collect the results using .get_counts() counts = result.get_counts() # Visualization plot_histogram(counts)
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) ### replaced x gate ### qc.x(1) return qc
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.visualization import dag_drawer q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) dag_drawer(dag)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- 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/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# import all necessary objects and methods for quantum circuits from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer all_pairs = ['00','01','10','11'] for pair in all_pairs: # create a quantum curcuit with two qubits: Asja's and Balvis' qubits. # both are initially set to |0>. qreg = QuantumRegister(2) # quantum register with 2 qubits creg = ClassicalRegister(2) # classical register with 2 bits mycircuit = QuantumCircuit(qreg,creg) # quantum circuit with quantum and classical registers # apply h-gate (Hadamard) to the first qubit. mycircuit.h(qreg[0]) # apply cx-gate (CNOT) with parameters first-qubit and second-qubit. mycircuit.cx(qreg[0],qreg[1]) # they are separated now. # if a is 1, then apply z-gate to the first qubit. if pair[0]=='1': mycircuit.z(qreg[0]) # if b is 1, then apply x-gate (NOT) to the first qubit. if pair[1]=='1': mycircuit.x(qreg[0]) # Asja sends her qubit to Balvis. # apply cx-gate (CNOT) with parameters first-qubit and second-qubit. mycircuit.cx(qreg[0],qreg[1]) # apply h-gate (Hadamard) to the first qubit. mycircuit.h(qreg[0]) # measure both qubits mycircuit.measure(qreg,creg) # compare the results with pair (a,b) job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=100) counts = job.result().get_counts(mycircuit) for outcome in counts: reverse_outcome = '' for i in outcome: reverse_outcome = i + reverse_outcome print("(a,b) is",pair,": ",reverse_outcome,"is observed",counts[outcome],"times")
https://github.com/ColibrITD-SAS/mpqp
ColibrITD-SAS
from mpqp import QCircuit, Language from mpqp.gates import * from mpqp.noise import Depolarizing from mpqp.measures import BasisMeasure from mpqp.execution import * Depolarizing(0.5, [0, 1, 2]) Depolarizing(0.1, [0, 1, 2], dimension=2) Depolarizing(0.23, [2, 3], gates=[H, Rx, U]) d = Depolarizing(0.45, [1, 3, 4], dimension=2, gates=[CNOT, CZ]) d.to_other_language(Language.BRAKET) print(d.to_other_language(Language.MY_QLM)) circuit_1 = QCircuit([H(0), CNOT(0,1), Y(1), BasisMeasure([0,1], shots=100), Depolarizing(0.3, [0], gates=[H])]) print(circuit_1) circuit_2 = QCircuit([H(0), CNOT(0,1), Y(1), BasisMeasure([0,1], shots=100)]) circuit_2.add([Depolarizing(0.08, [0]), Depolarizing(0.13, [1])]) circuit_2.pretty_print() print(circuit_2.noises) circuit_2.without_noises() noisy_braket_circuit = circuit_2.to_other_language(Language.BRAKET) print(noisy_braket_circuit) for device in AWSDevice: print(device.name, "|", device.is_noisy_simulator()) result = run(circuit_2, AWSDevice.BRAKET_LOCAL_SIMULATOR) # this line is valid for both noisy and non noisy cases print(result)
https://github.com/pedroripper/qiskit_tutoriais
pedroripper
from qiskit import * %matplotlib inline import numpy as np qc = QuantumCircuit(2,2) qc.h(0) qc.cx(0,1) qc.measure([0,1],[0,1]) qc.draw(output='mpl') backend = Aer.get_backend('qasm_simulator') result = execute(qc,backend).result() from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(qc)) counts = result.get_counts(qc) legenda = ['Meu resultado'] plot_histogram(counts,color='red' ,legend=legenda) IBMQ.load_account() provedor = IBMQ.get_provider('ibm-q') backend = provedor.get_backend('ibmq_valencia') job = execute(qc,backend) from qiskit.tools.monitor import job_monitor job_monitor(job) result2 = job.result() counts2 = result2.get_counts(qc) legenda = ['Simulador','CQ Real'] plot_histogram([counts,counts2],color=['red','green'] ,legend=legenda) qc2 = QuantumCircuit(2,2) qc2.h(0) qc2.cx(0,1) backend_st = Aer.get_backend('statevector_simulator') result3 = execute(qc2, backend_st).result() statevector = result3.get_statevector() from qiskit.tools.visualization import plot_state_city plot_state_city(statevector) from qiskit.tools.visualization import plot_state_paulivec plot_state_paulivec(statevector) from qiskit.tools.visualization import plot_state_hinton plot_state_hinton(statevector) from qiskit.tools.visualization import plot_bloch_multivector plot_bloch_multivector(statevector) %matplotlib notebook # Repare que não está escrito inline como geralmente plot_bloch_multivector(statevector) # Para voltar ao normal é necessário apenas rodar o comando original %matplotlib inline from qiskit.tools.visualization import plot_bloch_vector plot_bloch_vector([1,0,0])
https://github.com/jeevesh2002/QuantumKatasQiskit
jeevesh2002
# Run this cell using Ctrl+Enter (⌘+Enter on Mac). from testing import exercise from typing import Tuple import math Complex = Tuple[float, float] Polar = Tuple[float, float] @exercise def imaginary_power(n : int) -> int: # If n is divisible by 4 if n % 4 == 0: return ... else: return ... @exercise def complex_add(x : Complex, y : Complex) -> Complex: # You can extract elements from a tuple like this a = x[0] b = x[1] c = y[0] d = y[1] # This creates a new variable and stores the real component into it real = a + c # Replace the ... with code to calculate the imaginary component imaginary = ... # You can create a tuple like this ans = (real, imaginary) return ans @exercise def complex_mult(x : Complex, y : Complex) -> Complex: # Fill in your own code return ... @exercise def conjugate(x : Complex) -> Complex: return ... @exercise def complex_div(x : Complex, y : Complex) -> Complex: return ... @exercise def modulus(x : Complex) -> float: return ... @exercise def complex_exp(x : Complex) -> Complex: return ... @exercise def complex_exp_real(r : float, x : Complex) -> Complex: return ... @exercise def polar_convert(x : Complex) -> Polar: r = ... theta = ... return (r, theta) @exercise def cartesian_convert(x : Polar) -> Complex: return ... @exercise def polar_mult(x : Polar, y : Polar) -> Polar: return ... @exercise def complex_exp_arbitrary(x : Complex, y : Complex) -> Complex: return ...
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
# Classical HF computation from qiskit_nature.drivers import PySCFDriver molecule = "H .0 .0 .0; H .0 .0 0.739" driver = PySCFDriver(atom=molecule) qmolecule = driver.run() n_el = qmolecule.num_alpha + qmolecule.num_beta n_mo = qmolecule.num_molecular_orbitals n_so = 2 * qmolecule.num_molecular_orbitals n_q = n_so e_nn = qmolecule.nuclear_repulsion_energy print("1. Number of electrons: {}".format(n_el)) print("2. Number of molecular orbitals: {}".format(n_mo)) print("3. Number of spin-orbitals: {}".format(n_so)) print("4. Number of qubits: {}".format(n_q)) print("5. Nuclear repulsion energy: {}".format(e_nn)) # Generate the second-quantized operators from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem problem = ElectronicStructureProblem(driver) second_q_ops = problem.second_q_ops() main_op = second_q_ops[0] from qiskit_nature.mappers.second_quantization import ParityMapper, BravyiKitaevMapper, JordanWignerMapper from qiskit_nature.converters.second_quantization.qubit_converter import QubitConverter # Setup the qubit converter mapper_type = 'JordanWignerMapper' if mapper_type == 'ParityMapper': mapper = ParityMapper() elif mapper_type == 'JordanWignerMapper': mapper = JordanWignerMapper() elif mapper_type == 'BravyiKitaevMapper': mapper = BravyiKitaevMapper() converter = QubitConverter(mapper=mapper, two_qubit_reduction=False) # Exact solution from qiskit_nature.algorithms.ground_state_solvers.minimum_eigensolver_factories import NumPyMinimumEigensolverFactory from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver import numpy as np def exact_diagonalizer(problem, converter): solver = NumPyMinimumEigensolverFactory() calc = GroundStateEigensolver(converter, solver) result = calc.solve(problem) return result result_exact = exact_diagonalizer(problem, converter) exact_energy = np.real(result_exact.eigenenergies[0]) print("Exact electronic energy", exact_energy) print(result_exact) # The fermionic operators are mapped to qubit operators num_particles = (problem.molecule_data_transformed.num_alpha, problem.molecule_data_transformed.num_beta) qubit_op = converter.convert(main_op, num_particles=num_particles) from qiskit_nature.circuit.library import HartreeFock num_particles = (problem.molecule_data_transformed.num_alpha, problem.molecule_data_transformed.num_beta) num_spin_orbitals = 2 * problem.molecule_data_transformed.num_molecular_orbitals init_state = HartreeFock(num_spin_orbitals, num_particles, converter) print(init_state) from qiskit.circuit.library import TwoLocal from qiskit_nature.circuit.library import UCCSD, PUCCD, SUCCD from qiskit.circuit import Parameter, QuantumCircuit # Choose the ansatz ansatz_type = "TwoLocal" # Parameters for q-UCC antatze num_particles = (problem.molecule_data_transformed.num_alpha, problem.molecule_data_transformed.num_beta) num_spin_orbitals = 2 * problem.molecule_data_transformed.num_molecular_orbitals # Put arguments for twolocal if ansatz_type == "TwoLocal": # Single qubit rotations that are placed on all qubits with independent parameters rotation_blocks = ['ry'] # Entangling gates entanglement_blocks = 'cx' # How the qubits are entangled entanglement = 'linear' # Repetitions of rotation_blocks + entanglement_blocks with independent parameters repetitions = 1 # Skip the final rotation_blocks layer skip_final_rotation_layer = False ansatz = TwoLocal(qubit_op.num_qubits, rotation_blocks, entanglement_blocks, reps=repetitions, entanglement=entanglement, skip_final_rotation_layer=skip_final_rotation_layer) # Add the initial state ansatz.compose(init_state, front=True, inplace=True) elif ansatz_type == "UCCSD": ansatz = UCCSD(converter,num_particles,num_spin_orbitals,initial_state = init_state) elif ansatz_type == "PUCCD": ansatz = PUCCD(converter,num_particles,num_spin_orbitals,initial_state = init_state) elif ansatz_type == "SUCCD": ansatz = SUCCD(converter,num_particles,num_spin_orbitals,initial_state = init_state) elif ansatz_type == "Custom": num_qubits = qubit_op.num_qubits qc = QuantumCircuit(num_qubits) param_count = 1 for i in range(num_qubits): theta = Parameter(f"ry_angle{param_count}" ) qc.ry(theta, i) param_count += 1 qc.cx(0,1) qc.cx(1,2) qc.cx(2,3) for i in range(num_qubits): theta = Parameter(f"ry_angle{param_count}") qc.ry(theta, i) param_count += 1 ansatz = qc ansatz.compose(init_state, front=True, inplace=True) print(ansatz) # Backend from qiskit import Aer backend = Aer.get_backend('statevector_simulator') # Classical optimizer from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA, SLSQP optimizer_type = 'COBYLA' # You may want to tune the parameters # of each optimizer, here the defaults are used if optimizer_type == 'COBYLA': optimizer = COBYLA(maxiter=500) elif optimizer_type == 'L_BFGS_B': optimizer = L_BFGS_B(maxfun=500) elif optimizer_type == 'SPSA': optimizer = SPSA(maxiter=500) elif optimizer_type == 'SLSQP': optimizer = SLSQP(maxiter=500) # Run VQE from qiskit.algorithms import VQE from IPython.display import display, clear_output # Print and save the data in lists def callback(eval_count, parameters, mean, std): # Overwrites the same line when printing display("Evaluation: {}, Energy: {}, Std: {}".format(eval_count, mean, std)) clear_output(wait=True) counts.append(eval_count) values.append(mean) params.append(parameters) deviation.append(std) counts = [] values = [] params = [] deviation = [] # Set initial parameters of the ansatz # We choose a fixed small displacement # So all participants start from similar starting point try: initial_point = [0.01] * len(ansatz.ordered_parameters) except: initial_point = [0.01] * ansatz.num_parameters algorithm = VQE(ansatz, optimizer=optimizer, quantum_instance=backend, callback=callback, initial_point=initial_point) result = algorithm.compute_minimum_eigenvalue(qubit_op) print(result) # Store results in a dictionary from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller # Unroller transpile your circuit into CNOTs and U gates pass_ = Unroller(['u', 'cx']) pm = PassManager(pass_) ansatz_tp = pm.run(ansatz) cnots = ansatz_tp.count_ops()['cx'] score = cnots accuracy_threshold = 4.0 # in mHa energy = result.optimal_value if ansatz_type == "TwoLocal": result_dict = { 'optimizer': optimizer.__class__.__name__, 'mapping': converter.mapper.__class__.__name__, 'ansatz': ansatz.__class__.__name__, 'rotation blocks': rotation_blocks, 'entanglement_blocks': entanglement_blocks, 'entanglement': entanglement, 'repetitions': repetitions, 'skip_final_rotation_layer': skip_final_rotation_layer, 'energy (Ha)': energy, 'error (mHa)': (energy-exact_energy)*1000, 'pass': (energy-exact_energy)*1000 <= accuracy_threshold, '# of parameters': len(result.optimal_point), 'final parameters': result.optimal_point, '# of evaluations': result.optimizer_evals, 'optimizer time': result.optimizer_time, '# of qubits': int(qubit_op.num_qubits), '# of CNOTs': cnots, 'score': score} else: result_dict = { 'optimizer': optimizer.__class__.__name__, 'mapping': converter.mapper.__class__.__name__, 'ansatz': ansatz.__class__.__name__, 'rotation blocks': None, 'entanglement_blocks': None, 'entanglement': None, 'repetitions': None, 'skip_final_rotation_layer': None, 'energy (Ha)': energy, 'error (mHa)': (energy-exact_energy)*1000, 'pass': (energy-exact_energy)*1000 <= accuracy_threshold, '# of parameters': len(result.optimal_point), 'final parameters': result.optimal_point, '# of evaluations': result.optimizer_evals, 'optimizer time': result.optimizer_time, '# of qubits': int(qubit_op.num_qubits), '# of CNOTs': cnots, 'score': score} # Plot the results import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) ax.set_xlabel('Iterations') ax.set_ylabel('Energy') ax.grid() fig.text(0.7, 0.75, f'Energy: {result.optimal_value:.3f}\nScore: {score:.0f}') plt.title(f"{result_dict['optimizer']}-{result_dict['mapping']}\n{result_dict['ansatz']}") ax.plot(counts, values) ax.axhline(exact_energy, linestyle='--') fig_title = f"\ {result_dict['optimizer']}-\ {result_dict['mapping']}-\ {result_dict['ansatz']}-\ Energy({result_dict['energy (Ha)']:.3f})-\ Score({result_dict['score']:.0f})\ .png" fig.savefig(fig_title, dpi=300) # Display and save the data import pandas as pd import os.path filename = 'results_h2.csv' if os.path.isfile(filename): result_df = pd.read_csv(filename) result_df = result_df.append([result_dict]) else: result_df = pd.DataFrame.from_dict([result_dict]) result_df.to_csv(filename) result_df[['optimizer','ansatz', '# of qubits', '# of parameters','rotation blocks', 'entanglement_blocks', 'entanglement', 'repetitions', 'error (mHa)', 'pass', 'score']] from qiskit_nature.drivers import PySCFDriver molecule = 'Li 0.0 0.0 0.0; H 0.0 0.0 1.5474' driver = PySCFDriver(atom=molecule) qmolecule = driver.run() n_el = qmolecule.num_alpha + qmolecule.num_beta n_mo = qmolecule.num_molecular_orbitals n_so = 2 * qmolecule.num_molecular_orbitals n_q = n_so e_nn = qmolecule.nuclear_repulsion_energy print("Number of electrons: {}".format(n_el)) print("Number of molecular orbitals: {}".format(n_mo)) print("Number of spin-orbitals: {}".format(n_so)) print("Number of qubits: {}".format(n_q)) print("Nuclear repulsion energy: {}".format(e_nn)) # Generate the second-quantized operators from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem problem = ElectronicStructureProblem(driver) second_q_ops = problem.second_q_ops() main_op = second_q_ops[0] from qiskit_nature.mappers.second_quantization import ParityMapper, BravyiKitaevMapper, JordanWignerMapper from qiskit_nature.converters.second_quantization.qubit_converter import QubitConverter # Setup the qubit converter mapper_type = 'JordanWignerMapper' if mapper_type == 'ParityMapper': mapper = ParityMapper() elif mapper_type == 'JordanWignerMapper': mapper = JordanWignerMapper() elif mapper_type == 'BravyiKitaevMapper': mapper = BravyiKitaevMapper() converter = QubitConverter(mapper=mapper, two_qubit_reduction=False) # Exact solution from qiskit_nature.algorithms.ground_state_solvers.minimum_eigensolver_factories import NumPyMinimumEigensolverFactory from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver import numpy as np def exact_diagonalizer(problem, converter): solver = NumPyMinimumEigensolverFactory() calc = GroundStateEigensolver(converter, solver) result = calc.solve(problem) return result result_exact = exact_diagonalizer(problem, converter) exact_energy = np.real(result_exact.eigenenergies[0]) print("Exact electronic energy", exact_energy) print(result_exact) from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem from qiskit_nature.transformers import FreezeCoreTransformer freezeCoreTransformer = FreezeCoreTransformer(True) problem = ElectronicStructureProblem(driver, q_molecule_transformers=[freezeCoreTransformer]) # Generate the second-quantized operators second_q_ops = problem.second_q_ops() # Hamiltonian main_op = second_q_ops[0] from qiskit_nature.mappers.second_quantization import ParityMapper from qiskit_nature.converters.second_quantization.qubit_converter import QubitConverter # Setup the mapper and qubit converter mapper_type = 'ParityMapper' mapper = ParityMapper() converter = QubitConverter(mapper=mapper, two_qubit_reduction=True) # The fermionic operators are mapped to qubit operators num_particles = (problem.molecule_data_transformed.num_alpha, problem.molecule_data_transformed.num_beta) symmetries = True if symmetries: num_particles = (problem.molecule_data_transformed.num_alpha, problem.molecule_data_transformed.num_beta) converter = QubitConverter(mapper, two_qubit_reduction=True, z2symmetry_reduction="auto") qubit_op = converter.convert( main_op, num_particles, sector_locator=problem.symmetry_sector_locator, ) else: converter = QubitConverter(mapper=mapper, two_qubit_reduction=True) qubit_op = converter.convert(main_op, num_particles=num_particles) print("Number of qubits: ", qubit_op.num_qubits) result_exact = exact_diagonalizer(problem, converter) exact_energy = np.real(result_exact.eigenenergies[0]) print("Exact electronic energy", exact_energy) print(result_exact) from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem from qiskit_nature.transformers import FreezeCoreTransformer # Eliminate the MOs 3 and 4 that correspond to 2px and 2py in addition to freezen the core electrons freezeCoreTransformer = FreezeCoreTransformer(True,[3,4]) problem = ElectronicStructureProblem(driver, q_molecule_transformers=[freezeCoreTransformer]) # Generate the second-quantized operators second_q_ops = problem.second_q_ops() # Hamiltonian main_op = second_q_ops[0] from qiskit_nature.mappers.second_quantization import ParityMapper from qiskit_nature.converters.second_quantization.qubit_converter import QubitConverter # Setup the mapper and qubit converter mapper_type = 'ParityMapper' mapper = ParityMapper() converter = QubitConverter(mapper=mapper, two_qubit_reduction=True) # The fermionic operators are mapped to qubit operators num_particles = (problem.molecule_data_transformed.num_alpha, problem.molecule_data_transformed.num_beta) symmetries = False if symmetries: num_particles = (problem.molecule_data_transformed.num_alpha, problem.molecule_data_transformed.num_beta) converter = QubitConverter(mapper, two_qubit_reduction=True, z2symmetry_reduction="auto") qubit_op = converter.convert( main_op, num_particles, sector_locator=problem.symmetry_sector_locator, ) else: converter = QubitConverter(mapper=mapper, two_qubit_reduction=True) qubit_op = converter.convert(main_op, num_particles=num_particles) print("Number of qubits: ", qubit_op.num_qubits) result_exact = exact_diagonalizer(problem, converter) exact_energy = np.real(result_exact.eigenenergies[0]) print("Exact electronic energy", exact_energy) from qiskit_nature.circuit.library import HartreeFock num_particles = (problem.molecule_data_transformed.num_alpha, problem.molecule_data_transformed.num_beta) num_spin_orbitals = 2 * problem.molecule_data_transformed.num_molecular_orbitals init_state = HartreeFock(num_spin_orbitals, num_particles, converter) init_state.draw() # ansatz 1 num_qubits = qubit_op.num_qubits qc = QuantumCircuit(num_qubits) param_count = 1 for i in range(num_qubits): theta = Parameter(f"ry_angle{param_count}" ) qc.ry(theta, i) param_count += 1 qc.cx(0,1) qc.cx(1,2) qc.cx(2,3) for i in range(num_qubits): theta = Parameter(f"ry_angle{param_count}") qc.ry(theta, i) param_count += 1 ansatz = qc ansatz.compose(init_state, front=True, inplace=True) ansatz.draw() # ansatz 2 # num_qubits = qubit_op.num_qubits # qc = QuantumCircuit(num_qubits) # param_count = 1 # for i in range(num_qubits): # theta = Parameter(f"ry_angle{param_count}" ) # theta2 = Parameter(f"rz_angle{param_count}" ) # qc.ry(theta, i) # qc.rz(theta2, i) # param_count += 1 # qc.cx(2,3) # qc.cx(0,2) # qc.cx(1,3) # for i in range(num_qubits): # theta = Parameter(f"ry_angle{param_count}") # theta2 = Parameter(f"rz_angle{param_count}" ) # qc.ry(theta, i) # qc.rz(theta2, i) # param_count += 1 # ansatz = qc # ansatz.compose(init_state, front=True, inplace=True) # ansatz.draw() from qiskit import Aer backend = Aer.get_backend('statevector_simulator') from qiskit.algorithms.optimizers import SLSQP optimizer_type = 'SLSQP' optimizer = SLSQP(maxiter=1000) from qiskit.algorithms import VQE from IPython.display import display, clear_output # Print and save the data in lists def callback(eval_count, parameters, mean, std): # Overwrites the same line when printing display("Evaluation: {}, Energy: {}, Std: {}".format(eval_count, mean, std)) clear_output(wait=True) counts.append(eval_count) values.append(mean) params.append(parameters) deviation.append(std) counts = [] values = [] params = [] deviation = [] # Set initial parameters of the ansatz # We choose a fixed small displacement # So all participants start from similar starting point try: initial_point = [0.01] * len(ansatz.ordered_parameters) except: initial_point = [0.01] * ansatz.num_parameters algorithm = VQE(ansatz, optimizer=optimizer, quantum_instance=backend, callback=callback, initial_point=initial_point) result = algorithm.compute_minimum_eigenvalue(qubit_op) print(result) # Store results in a dictionary from qiskit.transpiler import PassManager from qiskit.transpiler.passes import Unroller # Unroller transpile your circuit into CNOTs and U gates pass_ = Unroller(['u', 'cx']) pm = PassManager(pass_) ansatz_tp = pm.run(ansatz) cnots = ansatz_tp.count_ops()['cx'] score = cnots accuracy_threshold = 4.0 # in mHa energy = result.optimal_value if ansatz_type == "TwoLocal": result_dict = { 'optimizer': optimizer.__class__.__name__, 'mapping': converter.mapper.__class__.__name__, 'ansatz': ansatz.__class__.__name__, 'rotation blocks': rotation_blocks, 'entanglement_blocks': entanglement_blocks, 'entanglement': entanglement, 'repetitions': repetitions, 'skip_final_rotation_layer': skip_final_rotation_layer, 'energy (Ha)': energy, 'error (mHa)': (energy-exact_energy)*1000, 'pass': (energy-exact_energy)*1000 <= accuracy_threshold, '# of parameters': len(result.optimal_point), 'final parameters': result.optimal_point, '# of evaluations': result.optimizer_evals, 'optimizer time': result.optimizer_time, '# of qubits': int(qubit_op.num_qubits), '# of CNOTs': cnots, 'score': score} else: result_dict = { 'optimizer': optimizer.__class__.__name__, 'mapping': converter.mapper.__class__.__name__, 'ansatz': ansatz.__class__.__name__, 'rotation blocks': None, 'entanglement_blocks': None, 'entanglement': None, 'repetitions': None, 'skip_final_rotation_layer': None, 'energy (Ha)': energy, 'error (mHa)': (energy-exact_energy)*1000, 'pass': (energy-exact_energy)*1000 <= accuracy_threshold, '# of parameters': len(result.optimal_point), 'final parameters': result.optimal_point, '# of evaluations': result.optimizer_evals, 'optimizer time': result.optimizer_time, '# of qubits': int(qubit_op.num_qubits), '# of CNOTs': cnots, 'score': score} # Plot the results import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) ax.set_xlabel('Iterations') ax.set_ylabel('Energy') ax.grid() fig.text(0.7, 0.75, f'Energy: {result.optimal_value:.3f}\nScore: {score:.0f}') plt.title(f"{result_dict['optimizer']}-{result_dict['mapping']}\n{result_dict['ansatz']}") ax.plot(counts, values) ax.axhline(exact_energy, linestyle='--') fig_title = f"\ {result_dict['optimizer']}-\ {result_dict['mapping']}-\ {result_dict['ansatz']}-\ Energy({result_dict['energy (Ha)']:.3f})-\ Score({result_dict['score']:.0f})\ .png" fig.savefig(fig_title, dpi=300) # Display and save the data import pandas as pd import os.path filename = 'results_lih.csv' if os.path.isfile(filename): result_df = pd.read_csv(filename) result_df = result_df.append([result_dict]) else: result_df = pd.DataFrame.from_dict([result_dict]) result_df.to_csv(filename) result_df[['optimizer','ansatz', '# of qubits', 'error (mHa)', 'pass', 'score']]
https://github.com/IvanIsCoding/Quantum
IvanIsCoding
# initialization import numpy as np # importing Qiskit from qiskit import IBMQ, Aer from qiskit import QuantumCircuit, transpile # import basic plot tools from qiskit.visualization import plot_histogram # set the length of the n-bit input string. n = 3 # Constant Oracle const_oracle = QuantumCircuit(n+1) # Random output output = np.random.randint(2) if output == 1: const_oracle.x(n) const_oracle.draw() # Balanced Oracle balanced_oracle = QuantumCircuit(n+1) # Binary string length b_str = "101" # For each qubit in our circuit # we place an X-gate if the corresponding digit in b_str is 1 # or do nothing if the digit is 0 balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) balanced_oracle.draw() # Creating the controlled-NOT gates # using each input qubit as a control # and the output as a target balanced_oracle = QuantumCircuit(n+1) b_str = "101" # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Use barrier as divider balanced_oracle.barrier() # Controlled-NOT gates for qubit in range(n): balanced_oracle.cx(qubit, n) balanced_oracle.barrier() # Wrapping the controls in X-gates # Place X-gates for qubit in range(len(b_str)): if b_str[qubit] == '1': balanced_oracle.x(qubit) # Show oracle balanced_oracle.draw() dj_circuit = QuantumCircuit(n+1, n) # Apply H-gates for qubit in range(n): dj_circuit.h(qubit) # Put qubit in state |-> dj_circuit.x(n) dj_circuit.h(n) # Add oracle dj_circuit = dj_circuit.compose(balanced_oracle) # Repeat H-gates for qubit in range(n): dj_circuit.h(qubit) dj_circuit.barrier() # Measure for i in range(n): dj_circuit.measure(i, i) # Display circuit dj_circuit.draw() # Viewing the output # use local simulator aer_sim = Aer.get_backend('aer_simulator') results = aer_sim.run(dj_circuit).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/Innanov/Qiskit-Global-Summer-School-2022
Innanov
# General Imports import numpy as np # Visualisation Imports import matplotlib.pyplot as plt # Scikit Imports from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler, MinMaxScaler # Qiskit Imports from qiskit import Aer, execute from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2 from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate from qiskit_machine_learning.kernels import QuantumKernel # Load digits dataset digits = datasets.load_digits(n_class=2) # Plot example '0' and '1' fig, axs = plt.subplots(1, 2, figsize=(6,3)) axs[0].set_axis_off() axs[0].imshow(digits.images[0], cmap=plt.cm.gray_r, interpolation='nearest') axs[1].set_axis_off() axs[1].imshow(digits.images[1], cmap=plt.cm.gray_r, interpolation='nearest') plt.show() # Split dataset sample_train, sample_test, label_train, label_test = train_test_split( digits.data, digits.target, test_size=0.2, random_state=22) # Reduce dimensions n_dim = 4 pca = PCA(n_components=n_dim).fit(sample_train) sample_train = pca.transform(sample_train) sample_test = pca.transform(sample_test) # Normalise std_scale = StandardScaler().fit(sample_train) sample_train = std_scale.transform(sample_train) sample_test = std_scale.transform(sample_test) # Scale samples = np.append(sample_train, sample_test, axis=0) minmax_scale = MinMaxScaler((-1, 1)).fit(samples) sample_train = minmax_scale.transform(sample_train) sample_test = minmax_scale.transform(sample_test) # Select train_size = 100 sample_train = sample_train[:train_size] label_train = label_train[:train_size] test_size = 20 sample_test = sample_test[:test_size] label_test = label_test[:test_size] print(sample_train[0], label_train[0]) print(sample_test[0], label_test[0]) # 3 features, depth 2 map_z = ZFeatureMap(feature_dimension=3, reps=2) map_z.draw('mpl') # 3 features, depth 1 map_zz = ZZFeatureMap(feature_dimension=3, reps=1) map_zz.draw('mpl') # 3 features, depth 1, linear entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear') map_zz.draw('mpl') # 3 features, depth 1, circular entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular') map_zz.draw('mpl') # 3 features, depth 1 map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ']) map_pauli.draw('mpl') def custom_data_map_func(x): coeff = x[0] if len(x) == 1 else reduce(lambda m, n: m * n, np.sin(np.pi - x)) return coeff map_customdatamap = PauliFeatureMap(feature_dimension=3, reps=1, paulis=['Z','ZZ'], data_map_func=custom_data_map_func) #map_customdatamap.draw() # qiskit isn't able to draw the circuit with np.sin in the custom data map twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'], entanglement_blocks='cx', entanglement='circular', insert_barriers=True) twolocal.draw('mpl') twolocaln = NLocal(num_qubits=3, reps=2, rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))], entanglement_blocks=CXGate(), entanglement='circular', insert_barriers=True) twolocaln.draw('mpl') # rotation block: rot = QuantumCircuit(2) params = ParameterVector('r', 2) rot.ry(params[0], 0) rot.rz(params[1], 1) # entanglement block: ent = QuantumCircuit(4) params = ParameterVector('e', 3) ent.crx(params[0], 0, 1) ent.crx(params[1], 1, 2) ent.crx(params[2], 2, 3) nlocal = NLocal(num_qubits=6, rotation_blocks=rot, entanglement_blocks=ent, entanglement='linear', insert_barriers=True) nlocal.draw('mpl') qubits = 3 repeats = 2 x = ParameterVector('x', length=qubits) var_custom = QuantumCircuit(qubits) for _ in range(repeats): for i in range(qubits): var_custom.rx(x[i], i) for i in range(qubits): for j in range(i + 1, qubits): var_custom.cx(i, j) var_custom.p(x[i] * x[j], j) var_custom.cx(i, j) var_custom.barrier() var_custom.draw('mpl') print(sample_train[0]) encode_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True) encode_circuit = encode_map.bind_parameters(sample_train[0]) encode_circuit.draw(output='mpl') x = [-0.1,0.2] # YOUR CODE HERE encode_map_x =ZZFeatureMap(feature_dimension=2, reps=4) ex1_circuit =encode_map_x.bind_parameters(x) ex1_circuit.draw(output='mpl') from qc_grader import grade_lab3_ex1 # Note that the grading function is expecting a quantum circuit grade_lab3_ex1(ex1_circuit) zz_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True) zz_kernel = QuantumKernel(feature_map=zz_map, quantum_instance=Aer.get_backend('statevector_simulator')) print(sample_train[0]) print(sample_train[1]) zz_circuit = zz_kernel.construct_circuit(sample_train[0], sample_train[1]) zz_circuit.decompose().decompose().draw(output='mpl') backend = Aer.get_backend('qasm_simulator') job = execute(zz_circuit, backend, shots=8192, seed_simulator=1024, seed_transpiler=1024) counts = job.result().get_counts(zz_circuit) counts['0000']/sum(counts.values()) matrix_train = zz_kernel.evaluate(x_vec=sample_train) matrix_test = zz_kernel.evaluate(x_vec=sample_test, y_vec=sample_train) fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].imshow(np.asmatrix(matrix_train), interpolation='nearest', origin='upper', cmap='Blues') axs[0].set_title("training kernel matrix") axs[1].imshow(np.asmatrix(matrix_test), interpolation='nearest', origin='upper', cmap='Reds') axs[1].set_title("testing kernel matrix") plt.show() x = [-0.1,0.2] y = [0.4,-0.6] # YOUR CODE HERE encode_map_x2 = ZZFeatureMap(feature_dimension=2, reps=4) zz_kernel_x2 =QuantumKernel(feature_map=encode_map_x2,quantum_instance=Aer.get_backend('statevector_simulator')) zz_circuit_x2 =zz_kernel_x2.construct_circuit(x,y) backend =Aer.get_backend('qasm_simulator') job = execute(zz_circuit_x2,backend,shots=8192, seed_simulator=1024, seed_transpiler=1024) counts_x2 = job.result().get_counts(zz_circuit_x2) amplitude= counts_x2['00']/sum(counts_x2.values()) from qc_grader import grade_lab3_ex2 # Note that the grading function is expecting a floating point number grade_lab3_ex2(amplitude) zzpc_svc = SVC(kernel='precomputed') zzpc_svc.fit(matrix_train, label_train) zzpc_score = zzpc_svc.score(matrix_test, label_test) print(f'Precomputed kernel classification test score: {zzpc_score}') zzcb_svc = SVC(kernel=zz_kernel.evaluate) zzcb_svc.fit(sample_train, label_train) zzcb_score = zzcb_svc.score(sample_test, label_test) print(f'Callable kernel classification test score: {zzcb_score}') classical_kernels = ['linear', 'poly', 'rbf', 'sigmoid'] for kernel in classical_kernels: classical_svc = SVC(kernel=kernel) classical_svc.fit(sample_train, label_train) classical_score = classical_svc.score(sample_test, label_test) print('%s kernel classification test score: %0.2f' % (kernel, classical_score))
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# let's start with a zero matrix A = [ [0,0,0], [0,0,0], [0,0,0] ] # we will randomly pick the entries and then make normalization for each column # it will be easier to iteratively construct the columns # you may notice that each column is a probabilistic state from random import randrange normalization_factor = [0,0,0] # the normalization factor of each column may be different for j in range(3): # each column is iteratively constructed normalization_factor[j] = 0 while normalization_factor[j]==0: # the normalization factor cannot be zero for i in range(3): A[i][j] = randrange(101) # pick a random value between 0 and 100 normalization_factor[j] += A[i][j] # let's print matrix A before the normalization # the entries are between 0 and 100 print("matrix A before normalization:") for i in range(3): print(A[i]) # let's normalize each column for j in range(3): for i in range(3): A[i][j] /= normalization_factor[j] # shorter form of A[i][j] = A[i][j] / normalization_factor[j] # let's print matrix A after the normalization print() # print an empty line print("matrix A after normalization:") for i in range(3): print(A[i]) print() print("the column summations must be 1") sum = [0,0,0] for j in range(3): for i in range(3): sum[j] += A[i][j] print(sum) # Asja's probabilistic operator (coin flip protocol) A = [ [0.6,0.3], [0.4,0.7] ] # one-step evolution of Asja's probabilistic operator on a given probabilistic state def asja(prelist): newlist=[0,0] for i in range(2): # for each row for j in range(2): # for each column newlist[i] = newlist[i] + prelist[j] * A[i][j] # summation of pairwise multiplication return newlist # return the new state # initial state state = [1,0] # after one step state = asja(state) print("after one step, the state is",state) # the new state is correct # let's check one more step state = asja(state) print("after two steps, the state is",state) # this is also correct # # then, let's evolve the system for more steps for i in [3,6,9,12,24,48,96]: # start from the initial state state = [1,0] for t in range(i): # apply asja t times state = asja(state) # print the result print(state,"after",(t+1),"steps") def evolve(Op,state): newstate=[] for i in range(len(Op)): # for each row # we calculate the corresponding entry of the new state newstate.append(0) # we set this value to 0 for the initialization for j in range(len(state)): # for each element in state newstate[i] = newstate[i] + Op[i][j] * state[j] # summation of pairwise multiplications return newstate # return the new probabilistic state # test the function # operator for the test A = [ [0.4,0.6,0], [0.2,0.1,0.7], [0.4,0.3,0.3] ] # state for test v = [0.1,0.3,0.6] newstate = evolve(A,v) print(newstate) for step in [5,10,20,40]: new_state = [0.1,0.3,0.6] # initial state for i in range(step): new_state = evolve(A,new_state) print(new_state) # change the initial state for step in [5,10,20,40]: new_state = [1,0,0] # initial state for i in range(step): new_state = evolve(A,new_state) print(new_state) # for random number generation from random import randrange # we will use evolve function def evolve(Op,state): newstate=[] for i in range(len(Op)): # for each row newstate.append(0) for j in range(len(state)): # for each element in state newstate[i] = newstate[i] + Op[i][j] * state[j] # summation of pairwise multiplications return newstate # return the new probabilistic state # the initial state state = [0.5, 0, 0.5, 0] # probabilistic operator for symbol a A = [ [0.5, 0, 0, 0], [0.25, 1, 0, 0], [0, 0, 1, 0], [0.25, 0, 0, 1] ] # probabilistic operator for symbol b B = [ [1, 0, 0, 0], [0, 1, 0.25, 0], [0, 0, 0.5, 0], [0, 0, 0.25, 1] ] # # your solution is here # length = 40 total = 50 # total = 1000 # we will also test our code for 1000 strings # we will check 5 cases # let's use a list cases = [0,0,0,0,0] for i in range(total): # total number of strings Na = 0 Nb = 0 string = "" state = [0.5, 0, 0.5, 0] for j in range(length): # generate random string if randrange(2) == 0: Na = Na + 1 # new symbol is a string = string + "a" state = evolve(A,state) # update the probabilistic state by A else: Nb = Nb + 1 # new symbol is b string = string + "b" state = evolve(B,state) # update the probabilistic state by B # now we have the final state p0 = state[0] + state[1] # the probabilities of being in 00 and 01 p1 = state[2] + state[3] # the probabilities of being in 10 and 11 #print() # print an empty line print("(Na-Nb) is",Na-Nb,"and","(p0-p1) is",p0-p1) # let's check possible different cases # start with the case in which both are nonzero # then their multiplication is nonzero # let's check the sign of their multiplication if (Na-Nb) * (p0-p1) < 0: print("they have opposite sign") cases[0] = cases[0] + 1 elif (Na-Nb) * (p0-p1) > 0: print("they have the same sign") cases[1] = cases[1] + 1 # one of them should be zero elif (Na-Nb) == 0: if (p0-p1) == 0: print("both are zero") cases[2] = cases[2] + 1 else: print("(Na-Nb) is zero, but (p0-p1) is nonzero") cases[3] = cases[3] + 1 elif (p0-p1) == 0: print("(Na-Nb) is nonzero, while (p0-p1) is zero") cases[4] = cases[4] + 1 # check the case(s) that are observed and the case(s) that are not observed print() # print an empty line print(cases)
https://github.com/jcylim/QiskitProject
jcylim
import getpass, time from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit import available_backends, execute, register, least_busy, get_backend import Qconfig # import basic plot tools from qiskit.tools.visualization import plot_histogram, circuit_drawer q = QuantumRegister(2) c = ClassicalRegister(2) qc = QuantumCircuit(q, c) qc.h(q[0]) qc.cx(q[0], q[1]) qc.measure(q, c) register(Qconfig.APItoken) backend = get_backend('ibmqx4') job_exp = execute(qc, backend=backend, shots=1024, max_credits=3) lapse = 0 interval = 30 while not job_exp.done: print('Status @ {} seconds'.format(interval * lapse)) print(job_exp.status) time.sleep(interval) lapse += 1 print(job_exp.status) plot_histogram(job_exp.result().get_counts(qc)) print('You have made entanglement!')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import transpile, QuantumCircuit import qiskit.quantum_info as qi from qiskit_aer import AerSimulator from qiskit_aer.noise import NoiseModel, amplitude_damping_error from qiskit.tools.visualization import plot_histogram # CNOT matrix operator with qubit-0 as control and qubit-1 as target cx_op = qi.Operator([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]]) # iSWAP matrix operator iswap_op = qi.Operator([[1, 0, 0, 0], [0, 0, 1j, 0], [0, 1j, 0, 0], [0, 0, 0, 1]]) # CNOT in terms of iSWAP and single-qubit gates cx_circ = QuantumCircuit(2, name='cx<iSWAP>') # Add gates cx_circ.sdg(1) cx_circ.h(1) cx_circ.sdg(0) cx_circ.unitary(iswap_op, [0, 1], label='iswap') cx_circ.sdg(0) cx_circ.h(0) cx_circ.sdg(0) cx_circ.unitary(iswap_op, [0, 1], label='iswap') cx_circ.s(1) print(cx_circ) # Simulate the unitary for the circuit using Operator: unitary = qi.Operator(cx_circ) print(unitary) f_ave = qi.average_gate_fidelity(cx_op, unitary) print("Average Gate Fidelity: F = {:f}".format(f_ave)) 'unitary' in AerSimulator().configuration().basis_gates # Error parameters param_q0 = 0.05 # damping parameter for qubit-0 param_q1 = 0.1 # damping parameter for qubit-1 # Construct the error qerror_q0 = amplitude_damping_error(param_q0) qerror_q1 = amplitude_damping_error(param_q1) iswap_error = qerror_q1.tensor(qerror_q0) # Build the noise model by adding the error to the "iswap" gate noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(iswap_error, 'iswap') noise_model.add_basis_gates(['unitary']) print(noise_model.basis_gates) # Bell state circuit where iSWAPS should be inserted at barrier locations bell_circ = QuantumCircuit(2, 2, name='bell') bell_circ.h(0) bell_circ.append(cx_circ, [0, 1]) bell_circ.measure([0,1], [0,1]) print(bell_circ) # Create ideal simulator backend and transpile circuit sim_ideal = AerSimulator() tbell_circ = transpile(bell_circ, sim_ideal) ideal_result = sim_ideal.run(tbell_circ).result() ideal_counts = ideal_result.get_counts(0) plot_histogram(ideal_counts, title='Ideal output for iSWAP bell-state preparation') # Create noisy simulator and transpile circuit sim_noise = AerSimulator(noise_model=noise_model) tbell_circ_noise = transpile(bell_circ, sim_noise) # Run on the simulator without noise noise_result = sim_noise.run(tbell_circ_noise).result() noise_counts = noise_result.get_counts(bell_circ) plot_histogram(noise_counts, title='Noisy output for iSWAP bell-state preparation') import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/alejomonbar/Quantum-Supply-Chain-Manager
alejomonbar
%load_ext autoreload %autoreload 2 #pip install pennyane #improt pennylane dependnecies import pennylane as qml from pennylane import numpy as np from pennylane.optimize import NesterovMomentumOptimizer # load the csv files import pandas as pd # plot the historical acc and cost import matplotlib.pyplot as plt import seaborn as sns from IPython.display import clear_output clear_output(wait=False) import os data_train = pd.read_csv("dataset/fair_train.csv") X_train,y_train = data_train[data_train.columns[:16]].values, data_train[data_train.columns[16]].values data_test = pd.read_csv("dataset/classic_test.csv") X_test,y_test = data_test[data_test.columns[:16]].values, data_test[data_test.columns[16]].values (X_train.shape, y_train.shape),(X_test.shape, y_test.shape) n_wires = 4 dev = qml.device("default.qubit", wires=n_wires) def block(weights, wires): qml.CNOT(wires=[wires[0],wires[1]]) qml.RY(weights[0], wires=wires[0]) qml.RY(weights[1], wires=wires[1]) n_block_wires = 2 n_params_block = 2 n_blocks = qml.MERA.get_n_blocks(range(n_wires),n_block_wires) n_blocks @qml.qnode(dev) def circuit(weights, x): qml.AmplitudeEmbedding(x, wires=[0,1,2,3],normalize=True,pad_with=True) for w in weights: qml.MERA(range(n_wires),n_block_wires,block, n_params_block, w) #print(w) #print(x) return qml.expval(qml.PauliZ(1)) def variational_classifier(weights, bias, x): return circuit(weights, x) + bias def square_loss(labels, predictions): loss = 0 for l, p in zip(labels, predictions): loss = loss + (l - p) ** 2 loss = loss / len(labels) return loss def accuracy(labels, predictions): loss = 0 for l, p in zip(labels, predictions): if abs(l - p) < 1e-5: loss = loss + 1 loss = loss / len(labels) return loss def cost(weights, bias, X, Y): #print(1) predictions = [variational_classifier(weights, bias, x) for x in X] return square_loss(Y, predictions) np.random.seed(0) num_layers = 1 weights_init = 2*np.pi * np.random.randn(num_layers,n_blocks, n_params_block, requires_grad=True) bias_init = np.array(0.0, requires_grad=True) print(weights_init, bias_init) print(qml.draw(circuit,expansion_strategy='device',wire_order=[0,1,2,3])(weights_init,np.asarray(X_train[0]))) for i in weights_init: print(i[0]) y_train = np.where(y_train < 1, -1, y_train) y_test = np.where(y_test < 1, -1, y_test) from sklearn.utils import shuffle X,y = shuffle(X_train, y_train, random_state=0) from sklearn.model_selection import train_test_split opt = NesterovMomentumOptimizer(0.4) batch_size = 32 num_data = len(y_train) num_train = 0.9 # train the variational classifier weights = weights_init bias = bias_init print() cost_g = [] acc_train = [] acc_test = [] plt.show() for it in range(50): X_train_70, X_test_30, y_train_70, y_test_30 =train_test_split(np.asarray(X), np.asarray(y), train_size=num_train, test_size=1.0-num_train, shuffle=True) # Update the weights by one optimizer step batch_index = np.random.randint(0, len(X_train_70), (batch_size,)) feats_train_batch = X_train_70[batch_index] Y_train_batch = y_train_70[batch_index] weights, bias, _, _ = opt.step(cost, weights, bias, feats_train_batch, Y_train_batch) # Compute predictions on train and validation set predictions_train = [np.sign(variational_classifier(weights, bias, f)) for f in X_train_70] predictions_val = [np.sign(variational_classifier(weights, bias, f)) for f in X_test_30] # Compute accuracy on train and validation set acc_tra = accuracy(y_train_70, predictions_train) acc_val = accuracy(y_test_30, predictions_val) cost_train = cost(weights, bias,X_train, y_train) cost_g.append(cost_train) acc_train.append(acc_tra) acc_test.append(acc_val) clear_output(wait=True) plt.plot(cost_g,label='cost') plt.plot(acc_train,label='acc_train') plt.plot(acc_test,label='acc_test') plt.legend(['cost','acc_train','acc_test']) plt.show() print( "Iter: {:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} " "".format(it + 1, cost_train, acc_tra, acc_val) ) print(weights) x_test = [] for x in X_test.tolist(): if sum(x) == 0: x[0]=1 x_test.append( x/ np.linalg.norm(x)) x_test[0] y_test y_test_pred = [np.sign(variational_classifier(weights, bias, f)) for f in x_test] y_test_pred = [] for i in y_pred: if i < 0: y_test_pred.append(-1) else: y_test_pred.append(1) from sklearn.metrics import confusion_matrix, roc_curve, auc from sklearn.preprocessing import StandardScaler # demonstration of calculating metrics for a neural network model using sklearn from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score from sklearn.metrics import cohen_kappa_score from sklearn.metrics import roc_auc_score accuracy = accuracy_score(y_test, y_test_pred) print('Accuracy: %f' % accuracy) # precision tp / (tp + fp) precision = precision_score(y_test, y_test_pred) print('Precision: %f' % precision) # recall: tp / (tp + fn) recall = recall_score(y_test, y_test_pred) print('Recall: %f' % recall) # f1: 2 tp / (2 tp + fp + fn) f1 = f1_score(y_test, y_test_pred) print('F1 score: %f' % f1) # kappa kappa = cohen_kappa_score(y_test, y_test_pred) print('Cohens kappa: %f' % kappa) # ROC AUC auc = roc_auc_score(y_test, y_test_pred) print('ROC AUC: %f' % auc) # confusion matrix test_matrix = confusion_matrix(y_test, y_test_pred) print(test_matrix) ax = sns.heatmap(test_matrix, annot=True, cmap='Blues', fmt='g') ax.set_title('Seaborn Confusion Matrix with labels\n\n'); ax.set_xlabel('\nPredicted Values') ax.set_ylabel('Actual Values '); ax.xaxis.set_ticklabels(['0','1']) ax.yaxis.set_ticklabels(['0','1']) ## Display the visualization of the Confusion Matrix. plt.show() y_pred_1 = [int(i) for i in y_test_pred ] y_pred_1 = ["{}\n".format(i) for i in y_pred_1] with open(r'mera_1_layers.csv', 'w') as fp: fp.writelines(y_pred_1)
https://github.com/rickapocalypse/final_paper_qiskit_sat
rickapocalypse
from qiskit.providers.aer import QasmSimulator from multiprocessing import Barrier from qiskit import* from qiskit import circuit import matplotlib.pyplot as plt from qiskit.tools.visualization import plot_histogram from qiskit.tools.monitor import job_monitor circuit = QuantumCircuit(2) circuit.cx(0,1) circuit.draw(output='mpl') plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit circ = QuantumCircuit(2, 2) circ.h(0) circ.cx(0, 1) circ.measure([0, 1], [0, 1]) circ.draw("mpl") from qiskit import transpile, schedule as build_schedule from qiskit.providers.fake_provider import FakeHanoi backend = FakeHanoi() transpiled_circ = transpile(circ, backend) # Undefined Hadamard is replaced by U1 schedule = build_schedule(transpiled_circ, backend) schedule.draw() from qiskit import pulse with pulse.build() as h_q0: pulse.play(pulse.library.Gaussian(duration=256, amp=0.2, sigma=50, name='custom'), pulse.DriveChannel(0)) circ.add_calibration('h', [0], h_q0) schedule = build_schedule(circ, backend) schedule.draw() circ = QuantumCircuit(2, 2) circ.x(0) circ.x(0) circ.x(1) circ.measure([0, 1], [0, 1]) circ.draw("mpl") schedule = build_schedule(circ, backend, method="as_late_as_possible") schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1)]).draw() schedule = build_schedule(circ, backend, method="as_soon_as_possible") schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1)]).draw() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
# Import general libraries (needed for functions) import numpy as np import time # Import Qiskit classes import qiskit from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer from qiskit.providers.aer import noise from qiskit.tools.visualization import plot_histogram # Import measurement calibration functions from qiskit.ignis.mitigation.measurement import (complete_meas_cal, CompleteMeasFitter, MeasurementFilter) # Generate the calibration circuits qr = qiskit.QuantumRegister(5) meas_calibs, state_labels = complete_meas_cal(qubit_list=[2,3,4], qr=qr, circlabel='mcal') state_labels # Execute the calibration circuits without noise backend = qiskit.Aer.get_backend('qasm_simulator') job = qiskit.execute(meas_calibs, backend=backend, shots=1000) cal_results = job.result() # The calibration matrix without noise is the identity matrix meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') print(meas_fitter.cal_matrix) # Generate a noise model for the 5 qubits noise_model = noise.NoiseModel() for qi in range(5): read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1],[0.25,0.75]]) noise_model.add_readout_error(read_err, [qi]) # Execute the calibration circuits backend = qiskit.Aer.get_backend('qasm_simulator') job = qiskit.execute(meas_calibs, backend=backend, shots=1000, noise_model=noise_model) cal_results = job.result() # Calculate the calibration matrix with the noise model meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') print(meas_fitter.cal_matrix) # Plot the calibration matrix meas_fitter.plot_calibration() # What is the measurement fidelity? print("Average Measurement Fidelity: %f" % meas_fitter.readout_fidelity()) # What is the measurement fidelity of Q0? print("Average Measurement Fidelity of Q0: %f" % meas_fitter.readout_fidelity( label_list = [['000','001','010','011'],['100','101','110','111']])) # Make a 3Q GHZ state cr = ClassicalRegister(3) ghz = QuantumCircuit(qr, cr) ghz.h(qr[2]) ghz.cx(qr[2], qr[3]) ghz.cx(qr[3], qr[4]) ghz.measure(qr[2],cr[0]) ghz.measure(qr[3],cr[1]) ghz.measure(qr[4],cr[2]) job = qiskit.execute([ghz], backend=backend, shots=5000, noise_model=noise_model) results = job.result() # Results without mitigation raw_counts = results.get_counts() # Get the filter object meas_filter = meas_fitter.filter # Results with mitigation mitigated_results = meas_filter.apply(results) mitigated_counts = mitigated_results.get_counts(0) from qiskit.tools.visualization import * plot_histogram([raw_counts, mitigated_counts], legend=['raw', 'mitigated'])
https://github.com/brhn-4/CMSC457
brhn-4
# Do the necessary imports import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer from qiskit.extensions import Initialize from qiskit.quantum_info import random_statevector, Statevector,partial_trace def trace01(out_vector): return Statevector([sum([out_vector[i] for i in range(0,4)]), sum([out_vector[i] for i in range(4,8)])]) def teleportation(): # Create random 1-qubit state psi = random_statevector(2) print(psi) init_gate = Initialize(psi) init_gate.label = "init" ## SETUP qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical registers crx = ClassicalRegister(1, name="crx") qc = QuantumCircuit(qr, crz, crx) # Don't modify the code above ## Put your code below # ---------------------------- qc.initialize(psi, qr[0]) qc.h(qr[1]) qc.cx(qr[1],qr[2]) qc.cx(qr[0],qr[1]) qc.h(qr[0]) qc.measure(qr[0],crz[0]) qc.measure(qr[1],crx[0]) qc.x(qr[2]).c_if(crx[0], 1) qc.z(qr[2]).c_if(crz[0], 1) # ---------------------------- # Don't modify the code below sim = Aer.get_backend('aer_simulator') qc.save_statevector() out_vector = sim.run(qc).result().get_statevector() result = trace01(out_vector) return psi, result # (psi,res) = teleportation() # print(psi) # print(res) # if psi == res: # print('1') # else: # print('0')
https://github.com/zapatacomputing/qe-qiskit
zapatacomputing
from qiskit import QuantumCircuit, Aer, execute from qiskit.visualization import plot_histogram # simulate in statevector_simulator def simulateStatevector(circuit): backend = Aer.get_backend('statevector_simulator') result = execute(circuit.remove_final_measurements(inplace=False), backend, shots=1).result() counts = result.get_counts() return result.get_statevector(circuit) # return plot_histogram(counts, color='midnightblue', title="StateVector Histogram") # simulate in qasm_simulator def simulateQasm(circuit, count=1024): backend = Aer.get_backend('qasm_simulator') result = execute(circuit, backend, shots=count).result() counts = result.get_counts() return plot_histogram(counts, color='midnightblue', title="Qasm Histogram")
https://github.com/MonitSharma/qiskit-projects
MonitSharma
# -*- 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. """ Created on Wed Mar 11 18:03:12 2020 Functional interface to Qasm2 source loading and exporting Supersede QuantumCircuit member functions Provide for pluggable qasm translator Based on conversation with Dr. Luciano Bello @author: jax """ from importlib import import_module from os import linesep from typing import List, BinaryIO, TextIO from qiskit import QuantumCircuit, QiskitError from qiskit_openqasm2 import Qasm from .funhelp import qasm_load, qasm_export def _load_from_string(qasm_src: str or List[str], loader: str = None, include_path: str = '') -> QuantumCircuit: """ Parameters ---------- qasm_src : str or List[str] Qasm program source as string or list of string. loader : str, optional Name of module with functional attribute load(filename: str = None, data: str = None, include_path: str = None) -> QuantumCircuit: ... to use for qasm translation. None means "use Qiskit qasm" The default is None. include_path : str, optional Loader-specific include path for qasm include directives. The default is ''. Raises ------ QiskitError If unknown loader. Returns ------- QuantumCircuit Circuit factoried from Qasm src. """ circ = None if not loader: if isinstance(qasm_src, list): qasm_src = ''.join(s + linesep for s in qasm_src) qasm = Qasm(data=qasm_src) circ = qasm_load(qasm) else: m_m = import_module(loader) circ = getattr(m_m, 'load')(data=qasm_src, include_path=include_path) return circ def _load_from_file(filename: str, loader: str = None, include_path: str = '') -> QuantumCircuit: """ Parameters ---------- filename : str Filepath to qasm program source. loader : str, optional Name of module with functional attribute load(filename: str = None, data: str = None, include_path: str = None) -> QuantumCircuit: ... to use for qasm translation. None means "use Qiskit qasm" The default is None. include_path : str, optional Loader-specific include path for qasm include directives. The default is ''. Returns ------- QuantumCircuit Circuit factoried from Qasm src. """ circ = None if not loader: qasm = Qasm(filename=filename) circ = qasm_load(qasm) else: m_m = import_module(loader) circ = getattr(m_m, 'load')(filename=filename, include_path=include_path) return circ def load(data: str or List[str] = None, filename: str = None, loader: str = None, include_path: str = None) -> QuantumCircuit: """ Parameters ---------- data : str or List[str], optional Qasm program source as string or list of string. The default is None. filename : str, optional Filepath to qasm program source. The default is None. loader : str, optional Name of module with functional attribute load(filename: str = None, data: str = None, include_path: str = None) -> QuantumCircuit: ... to use for qasm translation. None means "use Qiskit qasm" The default is None. include_path : str, optional Loader-specific include path for qasm include directives. The default is None. Raises ------ QiskitError If both filename and data or neither filename nor data. Returns ------- QuantumCircuit The factoried circuit. """ if (not data and not filename) or (data and filename): raise QiskitError("To load, either filename or data (and not both) must be provided.") circ = None if data: circ = _load_from_string(data, loader=loader, include_path=include_path) elif filename: circ = _load_from_file(filename, loader=loader, include_path=include_path) return circ def export(qc: QuantumCircuit, exporter: str = None, file: BinaryIO or TextIO = None, filename: str = None, include_path: str = None,) -> str: """ Decompile a QuantumCircuit into Return OpenQASM string Parameters ---------- qc : QuantumCircuit Circuit to decompile ("export") exporter : str, optional Name of module with functional attribute export(qc: QuantumCircuit, include_path: str = None) -> QuantumCircuit: ... to use for qasm translation. None means "use Qiskit qasm" The default is None. file : BinaryIO or TextIO, optional File object to write to as well as return str Written in UTF-8 Caller must close file. Mutually exclusive with filename= The default is None. filename : str, optional Name of file to write export to as well as return str Mutually exclusive with file= The default is None. include_path: str, optional Unloader-specific include path for qasm include directives Raises ------ QiskitError If both filename and file Returns ------- str OpenQASM source for circuit. """ if filename and file: raise QiskitError("export: file= and filename= are mutually exclusive") qasm_src = None if not exporter: qasm_src = qasm_export(qc) else: m_m = import_module(exporter) qasm_src = getattr(m_m, 'export')(qc, include_path=include_path) if filename: f_f = open(filename, 'w') f_f.write(qasm_src) f_f.close() elif file: if 'b' in file.mode: file.write(bytes(qasm_src, 'utf-8')) else: file.write(qasm_src) return qasm_src
https://github.com/hephaex/Quantum-Computing-Awesome-List
hephaex
from qiskit import QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram, plot_bloch_vector from math import sqrt, pi %config InlineBackend.figure_format = 'svg' qc = QuantumCircuit(1) initialize_state = [1,0] qc.initialize(initialize_state, 0) qc.draw() backend = Aer.get_backend('statevector_simulator') result = execute(qc, backend).result() out_state = result.get_statevector() print(out_state) qc.measure_all() qc.draw() counts = execute(qc, backend).result().get_counts() plot_histogram(counts) initial_state = [1/sqrt(3), complex(0, sqrt(2)/sqrt(3))] qc = QuantumCircuit(1) qc.initialize(initial_state, 0) state = execute(qc, backend).result().get_statevector() print(state) count = execute(qc, backend).result().get_counts() plot_histogram(count) qc = QuantumCircuit(1) # Redefine qc initial_state = [0.+1.j/sqrt(2),1/sqrt(2)+0.j] qc.initialize(initial_state, [0]) qc.draw() qc.measure_all() qc.draw() state = execute(qc,backend).result().get_statevector() print("State of Measured Qubit = " + str(state)) from qiskit_textbook.widgets import plot_bloch_vector_spherical coords = [pi/2,0,1] # [Theta, Phi, Radius] plot_bloch_vector_spherical(coords)
https://github.com/qiskit-community/prototype-entanglement-forging
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # 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. """ pauli common functions """ import logging import numpy as np from qiskit import QuantumCircuit, QuantumRegister from qiskit.algorithms import AlgorithmError from qiskit.circuit import Parameter, ParameterExpression from qiskit.qasm import pi from qiskit.quantum_info import Pauli # pylint: disable=unused-import logger = logging.getLogger(__name__) # pylint: disable=too-many-arguments,too-many-branches,too-many-locals def pauli_measurement(circuit, pauli, qreg, creg, barrier=False): """ Add the proper post-rotation gate on the circuit. Args: circuit (QuantumCircuit): the circuit to be modified. pauli (Pauli): the pauli will be added. qreg (QuantumRegister): the quantum register associated with the circuit. creg (ClassicalRegister): the classical register associated with the circuit. barrier (bool, optional): whether or not add barrier before measurement. Returns: QuantumCircuit: the original circuit object with post-rotation gate """ num_qubits = pauli.num_qubits for qubit_idx in range(num_qubits): if pauli.x[qubit_idx]: if pauli.z[qubit_idx]: # Measure Y circuit.sdg(qreg[qubit_idx]) # sdg circuit.h(qreg[qubit_idx]) # h else: # Measure X circuit.h(qreg[qubit_idx]) # h if barrier: circuit.barrier(qreg[qubit_idx]) circuit.measure(qreg[qubit_idx], creg[qubit_idx]) return circuit def measure_pauli_z(data, pauli): """ Appropriate post-rotations on the state are assumed. Args: data (dict): a dictionary of the form data = {'00000': 10} ({str: int}) pauli (Pauli): a Pauli object Returns: float: Expected value of paulis given data """ observable = 0.0 num_shots = sum(data.values()) p_z_or_x = np.logical_or(pauli.z, pauli.x) for key, value in data.items(): bitstr = np.asarray(list(key))[::-1].astype(int).astype(bool) # pylint: disable=no-member sign = -1.0 if np.logical_xor.reduce(np.logical_and(bitstr, p_z_or_x)) else 1.0 observable += sign * value observable /= num_shots return observable def covariance(data, pauli_1, pauli_2, avg_1, avg_2): """ Compute the covariance matrix element between two Paulis, given the measurement outcome. Appropriate post-rotations on the state are assumed. Args: data (dict): a dictionary of the form data = {'00000': 10} ({str:int}) pauli_1 (Pauli): a Pauli class member pauli_2 (Pauli): a Pauli class member avg_1 (float): expectation value of pauli_1 on `data` avg_2 (float): expectation value of pauli_2 on `data` Returns: float: the element of the covariance matrix between two Paulis """ cov = 0.0 num_shots = sum(data.values()) if num_shots == 1: return cov p1_z_or_x = np.logical_or(pauli_1.z, pauli_1.x) p2_z_or_x = np.logical_or(pauli_2.z, pauli_2.x) for key, value in data.items(): bitstr = np.asarray(list(key))[::-1].astype(int).astype(bool) # pylint: disable=no-member sign_1 = ( -1.0 if np.logical_xor.reduce(np.logical_and(bitstr, p1_z_or_x)) else 1.0 ) sign_2 = ( -1.0 if np.logical_xor.reduce(np.logical_and(bitstr, p2_z_or_x)) else 1.0 ) cov += (sign_1 - avg_1) * (sign_2 - avg_2) * value cov /= num_shots - 1 return cov # pylint: disable=invalid-name def suzuki_expansion_slice_pauli_list(pauli_list, lam_coef, expansion_order): """ Compute the list of pauli terms for a single slice of the suzuki expansion following the paper https://arxiv.org/pdf/quant-ph/0508139.pdf. Args: pauli_list (list[list[complex, Pauli]]): The slice's weighted Pauli list for the suzuki expansion lam_coef (float): The parameter lambda as defined in said paper, adjusted for the evolution time and the number of time slices expansion_order (int): The order for suzuki expansion Returns: list: slice pauli list """ if expansion_order == 1: half = [[lam_coef / 2 * c, p] for c, p in pauli_list] res = half + list(reversed(half)) else: p_k = (4 - 4 ** (1 / (2 * expansion_order - 1))) ** -1 side_base = suzuki_expansion_slice_pauli_list( pauli_list, lam_coef * p_k, expansion_order - 1 ) side = side_base * 2 middle = suzuki_expansion_slice_pauli_list( pauli_list, lam_coef * (1 - 4 * p_k), expansion_order - 1 ) res = side + middle + side return res def check_commutativity(op_1, op_2, anti=False): """ Check the (anti-)commutativity between two operators. Args: op_1 (WeightedPauliOperator): operator op_2 (WeightedPauliOperator): operator anti (bool): if True, check anti-commutativity, otherwise check commutativity. Returns: bool: whether or not two operators are commuted or anti-commuted. """ com = op_1 * op_2 - op_2 * op_1 if not anti else op_1 * op_2 + op_2 * op_1 com.simplify() return bool(com.is_empty()) # pylint: disable=too-many-statements def evolution_instruction( pauli_list, evo_time, num_time_slices, controlled=False, power=1, use_basis_gates=True, shallow_slicing=False, barrier=False, ): """ Construct the evolution circuit according to the supplied specification. Args: pauli_list (list([[complex, Pauli]])): The list of pauli terms corresponding to a single time slice to be evolved evo_time (Union(complex, float, Parameter, ParameterExpression)): The evolution time num_time_slices (int): The number of time slices for the expansion controlled (bool, optional): Controlled circuit or not power (int, optional): The power to which the unitary operator is to be raised use_basis_gates (bool, optional): boolean flag for indicating only using basis gates when building circuit. shallow_slicing (bool, optional): boolean flag for indicating using shallow qc.data reference repetition for slicing barrier (bool, optional): whether or not add barrier for every slice Returns: Instruction: The Instruction corresponding to specified evolution. Raises: AlgorithmError: power must be an integer and greater or equal to 1 ValueError: Unrecognized pauli """ if not isinstance(power, int) or power < 1: raise AlgorithmError("power must be an integer and greater or equal to 1.") state_registers = QuantumRegister(pauli_list[0][1].num_qubits) if controlled: inst_name = f"Controlled-Evolution^{power}" ancillary_registers = QuantumRegister(1) qc_slice = QuantumCircuit(state_registers, ancillary_registers, name=inst_name) else: inst_name = f"Evolution^{power}" qc_slice = QuantumCircuit(state_registers, name=inst_name) # for each pauli [IXYZ]+, record the list of qubit pairs needing CX's cnot_qubit_pairs = [None] * len(pauli_list) # for each pauli [IXYZ]+, record the highest index of the nontrivial pauli gate (X,Y, or Z) top_xyz_pauli_indices = [-1] * len(pauli_list) for pauli_idx, pauli in enumerate(reversed(pauli_list)): n_qubits = pauli[1].num_qubits # changes bases if necessary nontrivial_pauli_indices = [] for qubit_idx in range(n_qubits): # pauli I if not pauli[1].z[qubit_idx] and not pauli[1].x[qubit_idx]: continue if cnot_qubit_pairs[pauli_idx] is None: nontrivial_pauli_indices.append(qubit_idx) if pauli[1].x[qubit_idx]: # pauli X if not pauli[1].z[qubit_idx]: if use_basis_gates: qc_slice.h(state_registers[qubit_idx]) else: qc_slice.h(state_registers[qubit_idx]) # pauli Y elif pauli[1].z[qubit_idx]: if use_basis_gates: qc_slice.u(pi / 2, -pi / 2, pi / 2, state_registers[qubit_idx]) else: qc_slice.rx(pi / 2, state_registers[qubit_idx]) # pauli Z elif pauli[1].z[qubit_idx] and not pauli[1].x[qubit_idx]: pass else: raise ValueError(f"Unrecognized pauli: {pauli[1]}") if nontrivial_pauli_indices: top_xyz_pauli_indices[pauli_idx] = nontrivial_pauli_indices[-1] # insert lhs cnot gates if cnot_qubit_pairs[pauli_idx] is None: cnot_qubit_pairs[pauli_idx] = list( zip( sorted(nontrivial_pauli_indices)[:-1], sorted(nontrivial_pauli_indices)[1:], ) ) for pair in cnot_qubit_pairs[pauli_idx]: qc_slice.cx(state_registers[pair[0]], state_registers[pair[1]]) # insert Rz gate if top_xyz_pauli_indices[pauli_idx] >= 0: # Because Parameter does not support complexity number operation; thus, we do # the following tricks to generate parameterized instruction. # We assume the coefficient in the pauli is always real. and can not do imaginary time # evolution if isinstance(evo_time, (Parameter, ParameterExpression)): lam = 2.0 * pauli[0] / num_time_slices lam = lam.real if lam.imag == 0 else lam lam = lam * evo_time else: lam = (2.0 * pauli[0] * evo_time / num_time_slices).real if not controlled: if use_basis_gates: qc_slice.p(lam, state_registers[top_xyz_pauli_indices[pauli_idx]]) else: qc_slice.rz(lam, state_registers[top_xyz_pauli_indices[pauli_idx]]) else: if use_basis_gates: qc_slice.p( lam / 2, state_registers[top_xyz_pauli_indices[pauli_idx]] ) qc_slice.cx( ancillary_registers[0], state_registers[top_xyz_pauli_indices[pauli_idx]], ) qc_slice.p( -lam / 2, state_registers[top_xyz_pauli_indices[pauli_idx]] ) qc_slice.cx( ancillary_registers[0], state_registers[top_xyz_pauli_indices[pauli_idx]], ) else: qc_slice.crz( lam, ancillary_registers[0], state_registers[top_xyz_pauli_indices[pauli_idx]], ) # insert rhs cnot gates for pair in reversed(cnot_qubit_pairs[pauli_idx]): qc_slice.cx(state_registers[pair[0]], state_registers[pair[1]]) # revert bases if necessary for qubit_idx in range(n_qubits): if pauli[1].x[qubit_idx]: # pauli X if not pauli[1].z[qubit_idx]: if use_basis_gates: qc_slice.h(state_registers[qubit_idx]) else: qc_slice.h(state_registers[qubit_idx]) # pauli Y elif pauli[1].z[qubit_idx]: if use_basis_gates: qc_slice.u(-pi / 2, -pi / 2, pi / 2, state_registers[qubit_idx]) else: qc_slice.rx(-pi / 2, state_registers[qubit_idx]) # repeat the slice if shallow_slicing: logger.info( "Under shallow slicing mode, the qc.data reference is repeated shallowly. " "Thus, changing gates of one slice of the output circuit might affect " "other slices." ) if barrier: qc_slice.barrier(state_registers) qc_slice.data *= num_time_slices * power qc = qc_slice else: qc = QuantumCircuit(*qc_slice.qregs, name=inst_name) for _ in range(num_time_slices * power): qc.append(qc_slice, qc.qubits) if barrier: qc.barrier(state_registers) return qc.to_instruction()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2024 # # 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=missing-docstring,invalid-name,no-member # pylint: disable=attribute-defined-outside-init # pylint: disable=unused-argument import numpy as np from qiskit import QuantumRegister, QuantumCircuit from qiskit.compiler import transpile from qiskit.circuit.library.data_preparation import StatePreparation class StatePreparationTranspileBench: params = [4, 5, 6, 7, 8] param_names = ["number of qubits in state"] def setup(self, n): q = QuantumRegister(n) qc = QuantumCircuit(q) state = np.random.rand(2**n) + np.random.rand(2**n) * 1j state = state / np.linalg.norm(state) state_gate = StatePreparation(state) qc.append(state_gate, q) self.circuit = qc def track_cnot_counts_after_mapping_to_ibmq_16_melbourne(self, *unused): coupling = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] circuit = transpile( self.circuit, basis_gates=["u1", "u3", "u2", "cx"], coupling_map=coupling, seed_transpiler=0, ) counts = circuit.count_ops() cnot_count = counts.get("cx", 0) return cnot_count
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
import numpy as np from qiskit_aqua import Operator, run_algorithm from qiskit_aqua.input import EnergyInput from qiskit_aqua.translators.ising import partition from qiskit import Aer from qiskit_aqua.algorithms.classical.cplex.cplex_ising import CPLEX_Ising number_list = partition.read_numbers_from_file('sample.partition') qubitOp, offset = partition.get_partition_qubitops(number_list) algo_input = EnergyInput(qubitOp) print(number_list) if True: np.random.seed(8123179) number_list = partition.random_number_list(5, weight_range=25) qubitOp, offset = partition.get_partition_qubitops(number_list) algo_input.qubit_op = qubitOp print(number_list) to_be_tested_algos = ['ExactEigensolver', 'CPLEX.Ising', 'VQE'] print(to_be_tested_algos) algorithm_cfg = { 'name': 'ExactEigensolver', } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params,algo_input) x = partition.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('partition objective:', result['energy'] + offset) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list)) cplex_installed = True try: CPLEX_Ising.check_pluggable_valid() except Exception as e: cplex_installed = False if cplex_installed: algorithm_cfg = { 'name': 'CPLEX.Ising', 'display': 0 } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg } result = run_algorithm(params, algo_input) x_dict = result['x_sol'] print('energy:', result['energy']) print('time:', result['eval_time']) print('partition objective:', result['energy'] + offset) x = np.array([x_dict[i] for i in sorted(x_dict.keys())]) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list)) algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix' } optimizer_cfg = { 'name': 'L_BFGS_B', 'maxfun': 6000 } var_form_cfg = { 'name': 'RYRZ', 'depth': 3, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising'}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = Aer.get_backend('statevector_simulator') result = run_algorithm(params, algo_input, backend=backend) x = partition.sample_most_likely(result['eigvecs'][0]) print('energy:', result['energy']) print('time:', result['eval_time']) print('partition objective:', result['energy'] + offset) print('solution:', x) print('solution objective:', partition.partition_value(x, number_list))
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# include our predefined functions %run qlatvia.py # draw the axes draw_qubit() # # your solution is here # draw_quantum_state(3/5,4/5,"main") draw_quantum_state(-4/5,3/5,"ort1") draw_quantum_state(4/5,-3/5,"ort2") # include our predefined functions %run qlatvia.py # draw the axes draw_qubit() # # your solution is here # draw_quantum_state(3/5,-4/5,"main") draw_quantum_state(-4/5,-3/5,"ort1") draw_quantum_state(4/5,3/5,"ort2") # include our predefined functions %run qlatvia.py # draw the axes draw_qubit() # # your solution is here # draw_quantum_state(-5/13,12/13,"main") draw_quantum_state(-12/13,-5/13,"ort1") draw_quantum_state(12/13,5/13,"ort2") # include our predefined functions %run qlatvia.py # draw the axes draw_qubit() # # your solution is here # sqrttwo=2**0.5 draw_quantum_state(-1/sqrttwo,-1/sqrttwo,"main") draw_quantum_state(1/sqrttwo,-1/sqrttwo,"ort1") draw_quantum_state(-1/sqrttwo,1/sqrttwo,"ort2") # randomly create a 2-dimensional quantum state from math import cos, sin, pi from random import randrange def random_quantum_state2(): angle_degree = randrange(360) angle_radian = 2*pi*angle_degree/360 return [cos(angle_radian),sin(angle_radian)] # finding the angle of a 2-dimensional quantum state from math import acos, pi def angle_quantum_state(x,y): angle_radian = acos(x) # radian of the angle with state |0> angle_degree = 360*angle_radian/(2*pi) # degree of the angle with state |0> # if the second amplitude is negative, # then angle is (-angle_degree) # or equivalently 360 + (-angle_degree) if y<0: angle_degree = 360-angle_degree # degree of the angle # else degree of the angle is the same as degree of the angle with state |0> return angle_degree %run qlatvia.py draw_qubit() from math import acos, pi [x1,y1]=random_quantum_state2() # randomly pick a quantum state first_angle = angle_quantum_state(x1,y1) print("the angle of |u> is",first_angle) [x2,y2]=random_quantum_state2() # randomly pick a quantum state second_angle = angle_quantum_state(x2,y2) print("the angle of |c> is",second_angle) angle_between_1 = first_angle - second_angle if angle_between_1 < 0: angle_between_1 *= -1 dot_product = x1*x2+y1*y2 print("their dot prouct is",dot_product) angle_between_radian = acos(dot_product) angle_between_2 = 360 * angle_between_radian/(2*pi) print("the angle in between is calculated as",angle_between_1,"and",angle_between_2) draw_quantum_state(x1,y1,"|u>") draw_quantum_state(x2,y2,"|v>") %run qlatvia.py draw_qubit() from math import acos, pi [x1,y1]=random_quantum_state() # randomly pick a quantum state first_angle = angle_quantum_state(x1,y1) print("the angle of |u> is",first_angle) [x2,y2]=random_quantum_state() # randomly pick a quantum state second_angle = angle_quantum_state(x2,y2) print("the angle of |c> is",second_angle) angle_between_1 = first_angle - second_angle if angle_between_1 < 0: angle_between_1 *= -1 if angle_between_1 >180: angle_between_1 = 360 - angle_between_1 dot_product = x1*x2+y1*y2 print("their dot prouct is",dot_product) angle_between_radian = acos(dot_product) angle_between_2 = 360 * angle_between_radian/(2*pi) print("the angle in between is calculated as",angle_between_1,"and",angle_between_2) draw_quantum_state(x1,y1,"|u>") draw_quantum_state(x2,y2,"|v>")
https://github.com/sergiogh/qpirates-qiskit-notebooks
sergiogh
from sklearn.datasets import make_blobs # example dataset features, labels = make_blobs(n_samples=20, n_features=2, centers=2, random_state=3, shuffle=True) import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler features = MinMaxScaler(feature_range=(0, np.pi)).fit_transform(features) train_features, test_features, train_labels, test_labels = train_test_split( features, labels, train_size=15, shuffle=False ) # number of qubits is equal to the number of features num_qubits = 2 # number of steps performed during the training procedure tau = 100 # regularization parameter C = 1000 from qiskit import BasicAer from qiskit.circuit.library import ZFeatureMap from qiskit.utils import QuantumInstance, algorithm_globals from qiskit_machine_learning.kernels import QuantumKernel algorithm_globals.random_seed = 12345 pegasos_backend = QuantumInstance( BasicAer.get_backend("statevector_simulator"), seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, ) feature_map = ZFeatureMap(feature_dimension=num_qubits, reps=1) qkernel = QuantumKernel(feature_map=feature_map, quantum_instance=pegasos_backend) from qiskit_machine_learning.algorithms import PegasosQSVC pegasos_qsvc = PegasosQSVC(quantum_kernel=qkernel, C=C, num_steps=tau) # training pegasos_qsvc.fit(train_features, train_labels) # testing pegasos_score = pegasos_qsvc.score(test_features, test_labels) print(f"PegasosQSVC classification test score: {pegasos_score}") grid_step = 0.2 margin = 0.2 grid_x, grid_y = np.meshgrid( np.arange(-margin, np.pi + margin, grid_step), np.arange(-margin, np.pi + margin, grid_step) ) meshgrid_features = np.column_stack((grid_x.ravel(), grid_y.ravel())) meshgrid_colors = pegasos_qsvc.predict(meshgrid_features) import matplotlib.pyplot as plt plt.figure(figsize=(5, 5)) meshgrid_colors = meshgrid_colors.reshape(grid_x.shape) plt.pcolormesh(grid_x, grid_y, meshgrid_colors, cmap="RdBu", shading="auto") plt.scatter( train_features[:, 0][train_labels == 0], train_features[:, 1][train_labels == 0], marker="s", facecolors="w", edgecolors="r", label="A train", ) plt.scatter( train_features[:, 0][train_labels == 1], train_features[:, 1][train_labels == 1], marker="o", facecolors="w", edgecolors="b", label="B train", ) plt.scatter( test_features[:, 0][test_labels == 0], test_features[:, 1][test_labels == 0], marker="s", facecolors="r", edgecolors="r", label="A test", ) plt.scatter( test_features[:, 0][test_labels == 1], test_features[:, 1][test_labels == 1], marker="o", facecolors="b", edgecolors="b", label="B test", ) plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0) plt.title("Pegasos Classification") plt.show()
https://github.com/qiskit-community/qiskit-tket-passes
qiskit-community
import re from collections import OrderedDict from qiskit import QuantumCircuit from qiskit.transpiler import TransformationPass from qiskit.transpiler.target import Target, target_to_backend_properties from pytket.architecture import Architecture from pytket.circuit import OpType from pytket.passes import BasePass from pytket.passes._decompositions import _TK1_to_X_SX_Rz, _TK1_to_U from pytket.transform import CXConfigType, PauliSynthStrat from pytket.extensions.qiskit import qiskit_to_tk from pytket.placement import GraphPlacement, LinePlacement, NoiseAwarePlacement from .utils import get_arguments_from_doc, qiskit_dag_to_tk, tk_to_qiskit_dag def ToQiskitPass(tket_pass, target: Target = None, **kwargs): class TketPassClass(TransformationPass): def __init__(self, target: Target = None, **kwargs): if isinstance(tket_pass, BasePass): self._pass = tket_pass _dict = tket_pass.to_dict() class_name = _dict[_dict['pass_class']]['name'] self.requires = [] self.preserves = [] else: self.target = target super().__init__() class_name = tket_pass.__name__ self._args_dict = OrderedDict() parsed_args = get_arguments_from_doc(tket_pass) for parsed_arg in parsed_args: arg_name = parsed_arg[0] arg_type = parsed_arg[1] if arg_type.endswith('architecture.Architecture'): if arg_name in kwargs: arc = kwargs.pop(arg_name) if type(arc) == list: connections = [] for edge in arc: connections.append(tuple(edge)) arc = Architecture(connections) self._args_dict[arg_name] = arc elif self.target: arc = self._arch_from_target() self._args_dict[arg_name] = arc elif arg_type.endswith('placement.Placement'): if arg_name in kwargs: placer_str = kwargs.pop(arg_name) else: placer_str = 'NoiseAware' if placer_str == 'Graph': placer = GraphPlacement(self._arch_from_target()) self._args_dict[arg_name] = placer elif placer_str == 'Line': placer = LinePlacement(self._arch_from_target()) self._args_dict[arg_name] = placer elif placer_str == 'NoiseAware': if self.target: placer = self._noise_aware_placer_from_target() self._args_dict[arg_name] = placer else: raise ValueError('Unsupported placer type:', placer_str) elif arg_type.endswith('circuit.Circuit'): if arg_name in kwargs: circ = kwargs.pop(arg_name) tkcirc = qiskit_to_tk(circ) self._args_dict[arg_name] = tkcirc elif self.target: if class_name == 'DecomposeSwapsToCircuit' and arg_name == 'replacement_circuit': # Construct SWAP replacement circuit based on target's gate set. circ = self._swap_decomposition_from_target() tkcirc = qiskit_to_tk(circ) self._args_dict[arg_name] = tkcirc elif class_name == 'RebaseCustom' and arg_name == 'cx_replacement': # Construct CNOT replacement circuit based on target's gate set. circ = self._cnot_decomposition_from_target() tkcirc = qiskit_to_tk(circ) self._args_dict[arg_name] = tkcirc elif arg_type.endswith('circuit.OpType'): if arg_name in kwargs: op_str = kwargs.pop(arg_name) op_type = self._optype_from_str(op_str) self._args_dict[arg_name] = op_type elif re.match("Set\[.+\.circuit\.OpType\]", arg_type) is not None: if arg_name in kwargs: _value = kwargs.pop(arg_name) if all(isinstance(elem, str) for elem in _value): op_types = set() for op_str in _value: op_types.add(self._optype_from_str(op_str)) self._args_dict[arg_name] = op_types elif isinstance(_value, set) and all(isinstance(elem, OpType) for elem in _value): self._args_dict[arg_name] = _value elif self.target and class_name == 'RebaseCustom' and arg_name == 'gateset': # Get the target's gate set. self._args_dict[arg_name] = self._gateset_from_target() elif arg_type.endswith('transform.PauliSynthStrat'): if arg_name in kwargs: strategy = kwargs.pop(arg_name) strategies_map = { 'Individual': PauliSynthStrat.Individual, 'Pairwise': PauliSynthStrat.Pairwise, 'Sets': PauliSynthStrat.Sets, } value = strategies_map[strategy] self._args_dict[arg_name] = value elif arg_type.endswith('transform.CXConfigType'): if arg_name in kwargs: cx_config = kwargs.pop(arg_name) cx_config_map = { 'Snake': CXConfigType.Snake, 'Star': CXConfigType.Star, 'Tree': CXConfigType.Tree, 'MultiQGate': CXConfigType.MultiQGate } value = cx_config_map[cx_config] self._args_dict[arg_name] = value elif arg_name == 'tk1_replacement': if self.target: self._args_dict[arg_name] = self._tk1_replacement_from_target() else: self._args_dict[arg_name] = _TK1_to_U else: if arg_name in kwargs: value = kwargs.pop(arg_name) self._args_dict[arg_name] = value args = self._args_dict.values() self._pass = tket_pass(*args, **kwargs) __class__.__name__ = 'TketPass_' + class_name def run(self, dag): tkcirc = qiskit_dag_to_tk(dag) self._pass.apply(tkcirc) return tk_to_qiskit_dag(tkcirc) def tket_argument(self, arg_name): if arg_name in self._args_dict: return self._args_dict[arg_name] else: raise ValueError(f"{__class__.__name__} has no argument with the name {arg_name}.") #TODO: May be we should move the following methods to utils file instead of having them as class methods def _optype_from_str(self, op_str): for op_type in dir(OpType): if op_str.upper() == op_type.upper(): return OpType.from_name(op_type) ops_map = { 'id': 'noop', 'u': 'U3', 'cu': 'CU3', 'iswap': 'ISWAPMax', 'rxx': 'XXPhase', 'ryy': 'YYPhase', 'rzz': 'ZZPhase', 'p': 'U1', 'cp': 'CU1', 'r': 'PhasedX', } return OpType.from_name(ops_map[op_str]) def _gateset_from_target(self): operation_names = list(self.target.operation_names) for op in ['delay', 'if_else', 'rzx']: if op in operation_names: operation_names.remove(op) return { self._optype_from_str(op_str) for op_str in operation_names } def _arch_from_target(self): _coupling_map = self.target.build_coupling_map() if _coupling_map is None: return Architecture([]) else: return Architecture(_coupling_map.get_edges()) def _cnot_decomposition_from_target(self): circ = QuantumCircuit(2) circ.cx(0, 1) if 'cx' not in self.target.operation_names: from qiskit import transpile circ = transpile(circ, basis_gates=list(self.target.operation_names)) return circ def _swap_decomposition_from_target(self): from qiskit import transpile circ = QuantumCircuit(2) circ.swap(0, 1) return transpile(circ, basis_gates=list(self.target.operation_names)) def _tk1_replacement_from_target(self): if {'x', 'sx', 'rz'}.issubset(self.target.operation_names): return _TK1_to_X_SX_Rz else: return _TK1_to_U def _noise_aware_placer_from_target(self): """ Get noise data from target. This code is a modified copy from `process_characterisation` & `get_avg_characterisation` functions in pytket-qiskit module. """ from collections import defaultdict from pytket.circuit import Node node_errors = defaultdict(dict) edge_errors = defaultdict(dict) readout_errors = {} coupling_map = target.build_coupling_map() arc = self._arch_from_target() properties = target_to_backend_properties(target) if properties is None: return None else: for gate in properties.gates: for param in gate.parameters: if param.name == 'gate_error': optype = self._optype_from_str(gate.gate) gate_error = param.value if len(gate.qubits) == 1: node_errors[Node(gate.qubits[0])].update({optype: gate_error}) else: edge_errors[(Node(gate.qubits[0]), Node(gate.qubits[1]))].update({optype: gate_error}) if gate.qubits[::-1] not in coupling_map: edge_errors[(Node(gate.qubits[1]), Node(gate.qubits[0]))].update({optype: 2 * gate_error}) props_dict = properties.to_dict() for n in range(target.num_qubits): if len(props_dict['qubits']) > n: readout_error = properties.readout_error(n) else: readout_error = 0 readout_errors[Node(n)] = [ [1.0 - readout_error, readout_error], [readout_error, 1.0 - readout_error], ] avg = lambda xs: sum(xs.values()) / len(xs) avg_mat = (lambda xs: (xs[0][1] + xs[1][0]) / 2.0) map_values = lambda f, d: { k: f(v) for k, v in d.items() } avg_node_errors = map_values(avg, node_errors) avg_edge_errors = map_values(avg, edge_errors) avg_readout_errors = map_values(avg_mat, readout_errors) return NoiseAwarePlacement( arc, avg_node_errors, avg_edge_errors, avg_readout_errors ) return TketPassClass(target, **kwargs)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) with pulse.build() as hahn_echo: with pulse.align_equispaced(duration=100): pulse.play(x90, d0) pulse.play(x180, d0) pulse.play(x90, d0) hahn_echo.draw()
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
from qiskit import * import numpy as np import math from matplotlib import pyplot as plt import qiskit nshots = 8192 IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibmq_belem') simulator = Aer.get_backend('qasm_simulator') from qiskit.tools.monitor import job_monitor from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter #from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.visualization import plot_histogram def qc_dqc1(ph): qr = QuantumRegister(3) qc = QuantumCircuit(qr, name='DQC1') qc.h(0) qc.h(1) # cria o estado de Bell dos qubits 1 e 2, que equivale ao estado de 1 sendo maximamente misto qc.cx(1,2) #qc.barrier() qc.cp(ph, 0, 1) return qc ph = math.pi/2 qc_dqc1_ = qc_dqc1(ph) qc_dqc1_.draw('mpl') qc_dqc1_.decompose().draw('mpl') def pTraceL_num(dl, dr, rhoLR): # Retorna traco parcial sobre L de rhoLR rhoR = np.zeros((dr, dr), dtype=complex) for j in range(0, dr): for k in range(j, dr): for l in range(0, dl): rhoR[j,k] += rhoLR[l*dr+j,l*dr+k] if j != k: rhoR[k,j] = np.conj(rhoR[j,k]) return rhoR def pTraceR_num(dl, dr, rhoLR): # Retorna traco parcial sobre R de rhoLR rhoL = np.zeros((dl, dl), dtype=complex) for j in range(0, dl): for k in range(j, dl): for l in range(0, dr): rhoL[j,k] += rhoLR[j*dr+l,k*dr+l] if j != k: rhoL[k,j] = np.conj(rhoL[j,k]) return rhoL # simulation phmax = 2*math.pi dph = phmax/20 ph = np.arange(0,phmax+dph,dph) d = len(ph); xm = np.zeros(d) ym = np.zeros(d) for j in range(0,d): qr = QuantumRegister(3) qc = QuantumCircuit(qr) qc_dqc1_ = qc_dqc1(ph[j]) qc.append(qc_dqc1_, [0,1,2]) qstc = state_tomography_circuits(qc, [1,0]) job = execute(qstc, backend=simulator, shots=nshots) qstf = StateTomographyFitter(job.result(), qstc) rho_01 = qstf.fit(method='lstsq') rho_0 = pTraceR_num(2, 2, rho_01) xm[j] = 2*rho_0[1,0].real ym[j] = 2*rho_0[1,0].imag qc.draw('mpl') # experiment phmax = 2*math.pi dph = phmax/10 ph_exp = np.arange(0,phmax+dph,dph) d = len(ph_exp); xm_exp = np.zeros(d) ym_exp = np.zeros(d) for j in range(0,d): qr = QuantumRegister(3) qc = QuantumCircuit(qr) qc_dqc1_ = qc_dqc1(ph_exp[j]) qc.append(qc_dqc1_, [0,1,2]) qstc = state_tomography_circuits(qc, [1,0]) job = execute(qstc, backend=device, shots=nshots) print(job.job_id()) job_monitor(job) qstf = StateTomographyFitter(job.result(), qstc) rho_01 = qstf.fit(method='lstsq') rho_0 = pTraceR_num(2, 2, rho_01) xm_exp[j] = 2*rho_0[1,0].real ym_exp[j] = 2*rho_0[1,0].imag plt.plot(ph, xm, label = r'$\langle X\rangle_{sim}$')#, marker='*') plt.plot(ph, ym, label = r'$\langle Y\rangle_{sim}$')#, marker='o') plt.scatter(ph_exp, xm_exp, label = r'$\langle X\rangle_{exp}$', marker='*', color='r') plt.scatter(ph_exp, ym_exp, label = r'$\langle Y\rangle_{exp}$', marker='o', color='g') plt.legend(bbox_to_anchor=(1, 1))#,loc='center right') #plt.xlim(0,2*math.pi) #plt.ylim(-1,1) plt.xlabel(r'$\phi$') plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_aer.utils import approximate_quantum_error, approximate_noise_model import numpy as np # Import Aer QuantumError functions that will be used from qiskit_aer.noise import amplitude_damping_error, reset_error, pauli_error from qiskit.quantum_info import Kraus gamma = 0.23 error = amplitude_damping_error(gamma) results = approximate_quantum_error(error, operator_string="reset") print(results) p = (1 + gamma - np.sqrt(1 - gamma)) / 2 q = 0 print("") print("Expected results:") print("P(0) = {}".format(1-(p+q))) print("P(1) = {}".format(p)) print("P(2) = {}".format(q)) gamma = 0.23 K0 = np.array([[1,0],[0,np.sqrt(1-gamma)]]) K1 = np.array([[0,np.sqrt(gamma)],[0,0]]) results = approximate_quantum_error(Kraus([K0, K1]), operator_string="reset") print(results) reset_to_0 = Kraus([np.array([[1,0],[0,0]]), np.array([[0,1],[0,0]])]) reset_to_1 = Kraus([np.array([[0,0],[1,0]]), np.array([[0,0],[0,1]])]) reset_kraus = [reset_to_0, reset_to_1] gamma = 0.23 error = amplitude_damping_error(gamma) results = approximate_quantum_error(error, operator_list=reset_kraus) print(results) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/we-taper/qiskit-pyzx
we-taper
import qiskit import pyzx from qiskit.converters import circuit_to_dag, dag_to_circuit from circuit_translate_main import dag_to_pyzx_circuit, pyzx_circ_to_dag def optimize(c): pyzx_graph = c.to_graph() # Phase 1 pyzx.simplify.full_reduce(pyzx_graph) # Phase 2 pyzx_circuit = pyzx.extract.streaming_extract(pyzx_graph) # Phase 3 pyzx_circuit = pyzx_circuit.to_basic_gates() # Phase 4 try: # First try including the phase polynomial optimizer pyzx_circuit = pyzx.optimize.full_optimize(pyzx_circuit) except TypeError: # The phase polynomial optimizer only works on Clifford+T circuits. # Fall back to the basic optimizer pyzx_circuit = pyzx.optimize.basic_optimization(pyzx_circuit) # Phase 5 pyzx_circuit = pyzx_circuit.to_basic_gates() # Phase 6 pyzx_circuit = pyzx_circuit.split_phase_gates() return pyzx_circuit def pyzx_optimize(circuit: qiskit.QuantumCircuit) -> qiskit.QuantumCircuit: ret = dag_to_pyzx_circuit(circuit_to_dag(circuit)) pyzx_circuit = ret.circuit reduced = optimize(ret.circuit) dag = pyzx_circ_to_dag(reduced, ret) result = dag_to_circuit(dag) result.name = "{}_zx_optimized".format(circuit.name) return result
https://github.com/qonwaygameoflife/qonwaygameoflife
qonwaygameoflife
#!/usr/bin/env python3 import math from neighbours import neighbours3 from qiskit import QuantumCircuit from qiskit import Aer, execute from qiskit.aqua.components.oracles import TruthTableOracle from qiskit.circuit.reset import reset from qiskit.extensions.standard import barrier, h, swap, x def make_init_circuit(register, init_cells): init_circuit = QuantumCircuit(register) for i, v in enumerate(init_cells[::-1]): if v == '0': continue if v == '1': init_circuit.x(register[i]) else: init_circuit.h(register[i]) return init_circuit def make_barrier_circuit(regs): circuit = QuantumCircuit(*regs) for r in regs: circuit.barrier(r) return circuit def make_swap_circuit(reg01, reg02): circuit = QuantumCircuit(reg01, reg02) circuit.swap(reg01, reg02) return circuit def make_reset_circuit(regs): circuit = QuantumCircuit(*regs) for r in regs: circuit.reset(r) return circuit def make_oracle(qcount): bitmaps = [''] * qcount for raw_value in range(2**qcount): value = format(raw_value, '0{}b'.format(qcount))[::-1] for index in range(qcount): n = neighbours3(index, value) alive_count = 1 if n[0] == '1' else 0 alive_count += 1 if n[2] == '1' else 0 if n[1] == '0' and alive_count == 2: bitmaps[index] += '1' elif n[1] == '1' and alive_count == 1: bitmaps[index] += '1' else: bitmaps[index] += '0' return TruthTableOracle(bitmaps) def vector_state_to_summary(state, extract_cells): summary = {} circuit_size = int(math.log(len(state), 2)) for index, value in enumerate(state): if value == complex(0,0): continue f_index = format(index, '0{}b'.format(circuit_size)) cells = extract_cells(f_index) if cells in summary: summary[cells] += value else: summary[cells] = value return summary def print_summary(summary, min_prob): for cells, value in summary.items(): prob = abs(value) if prob >= min_prob: print('{} <{}>'.format(format_cells(cells), prob)) def print_cells(cells): print(format_cells(cells)) def format_cells(cells): output = '' for c in cells: if c == '0': output += '□' elif c == '1': output += '■' else: output += '☒' return ' '.join(output) init_cells = 'XXX' print('Input:') print_cells(init_cells) qcount = len(init_cells) oracle = make_oracle(qcount) oracle_circuit = oracle.construct_circuit() init_circuit = make_init_circuit(oracle.variable_register, init_cells) circuit = init_circuit + oracle_circuit backend_sim = Aer.get_backend('statevector_simulator') result = execute(circuit, backend_sim).result() state = result.get_statevector(circuit) cell_range_start = oracle.ancillary_register.size cell_range_end = cell_range_start + oracle.output_register.size extract_cells = lambda index: index[cell_range_start:cell_range_end] summary = vector_state_to_summary(state, extract_cells) print('Output:') min_prob = 0 #(1 / len(summary)) - 0.00001 print_summary(summary, min_prob) oracle2 = make_oracle(qcount) oracle2_circuit = oracle2.construct_circuit() barrier_circuit = make_barrier_circuit(oracle2_circuit.qregs) swap_circuit = make_swap_circuit(oracle.output_register, oracle2.variable_register) reset_circuit = make_reset_circuit([oracle2.output_register, oracle2.ancillary_register]) circuit2 = (init_circuit + oracle_circuit + barrier_circuit + swap_circuit + reset_circuit + oracle2_circuit) ##print(circuit2) result = execute(circuit2, backend_sim).result() state = result.get_statevector(circuit2) cell_range_start = oracle2.ancillary_register.size cell_range_end = cell_range_start + oracle2.output_register.size extract_cells = lambda index: index[cell_range_start:cell_range_end] summary = vector_state_to_summary(state, extract_cells) print('Output:') min_prob = 0 #(1 / len(summary)) - 0.00001 print_summary(summary, min_prob)
https://github.com/parton-quark/RLSB-CongX-Qiskit
parton-quark
def tfc_to_qiskit(tfc_path): tfc_file = open(tfc_path, "r", encoding = "utf_8") # convert tfc_file into list of lines tfc_lines = tfc.readlines() # prepare .py file py_file_name = "RLSBQC" + str(tfc_path) + ".py" py_file = open(py_file_name, "w", encoding = "utf_8") # py_file.write(text)で書き込める _write_head(py_file) tfc_line_number = 0 for tfc_line in tfc_lines: tfc_line_number += 1 if tfc_lines.startswith('t'): _gt(py_file, tfc_line, valiable_list) elif tfc_lines.startswith('f'): _gf(py_file, tfc_line, valiable_list) elif tfc_lines.startswith('#'): _write_comment(py_file, tfc_line) elif tfc_lines.startswith('.v'): # get list of valiables _valiables(py_file, tfc_line) elif tfc_lines.startswith('.i'): # get inputs _inputs(py_file, tfc_line) elif tfc_lines.startswith('.o'): # get outputs outputs elif tfc_lines.startswith('.ol'): # get outputs list elif tfc_lines.startswith('.c'): # get constants elif tfc_lines.startswith('BEGIN'): py_file.write('# BEGIN') elif tfc_lines.startswith('END'): py_file.write('# END') py_file.close() else: print("The first letter of the" + tfc_line_number + "line of the input is strange.") #終わり tfc_file.close() def _write_head(py_file): lisences = _license_info() # import SDKs import_qiskit = 'from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister' import_CongX = 'from CongX.extensions.standard import cnx' # Comments from RLSB-CongX-Qiskit comments_from_RLSB_CongX_Qiskit = '""\n' + 'なんかコメントするよん qiskit, congxをインポートしてね!' + '"""' py_file.write(lisences) py_file.write(import_qiskit) py_file.write(import_CongX) py_file.write(comments_from_RLSB_CongX_Qiskit) def _license_info: original_lisence = '' congx_lisence = 'This file is converted by RLSB-CongX-Qiskit. RLSB-CongX-Qiskit はpartonによって書かれたソフトウェアです。→bib fileのアドレス' # (c) Copyright 2020 Shin Nishio, parton@sfc.wide.ad.jp 入れるか考える def _prepare_register(line_qubit): line_qubit = line_qubit.replace(' ', '') line_qubit = line_qubit.replace(' ', '') # line_qubit = line_qubit.replace('.', '') if line_qubit[0:2] == '.v': line_qubit = line_qubit.lstrip('.v') num_qubit = _count_num_qubits(line_qubit) + 1 return num_qubit else: print('error, prepare_register() have some problem') print(line_qubit) def _input_qubits(line_qubit): line_qubit = line_qubit.replace(' ', '') line_qubit = line_qubit.replace(' ', '') # line_qubit = line_qubit.replace('.', '') if line_qubit[0:2] == '.i': line_qubit = line_qubit.lstrip('.i') i_qubits = abcを数字のリストに直したやつ return num_qubits else: print('error, input_qubits() have some problem') print(line_qubit) def _output_qubits(line_qubit): line_qubit = line_qubit.replace(' ', '') line_qubit = line_qubit.replace(' ', '') # line_qubit = line_qubit.replace('.', '') if line_qubit[0:2] == '.o': line_qubit = line_qubit.lstrip('.o') o_qubits = abcを数字のリストにしたやつ return o_qubits else: print('error, output_qubits() have some problem') print(line_qubit) def _count_num_qubits(qubit_str): alphabets = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,'k':10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25} if qubit_str[0] == 'a': num = alphabets[qubit_str[-1]] return num else: print('error, count_num_qubits() have some problem') print(qubit_str) def _write_comment(py_file): コメント来た時の対処 コメントとして書き込む
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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. """Tests for visualization tools.""" import unittest import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Qubit, Clbit from qiskit.visualization.circuit import _utils from qiskit.visualization import array_to_latex from qiskit.test import QiskitTestCase from qiskit.utils import optionals class TestVisualizationUtils(QiskitTestCase): """Tests for circuit drawer utilities.""" def setUp(self): super().setUp() self.qr1 = QuantumRegister(2, "qr1") self.qr2 = QuantumRegister(2, "qr2") self.cr1 = ClassicalRegister(2, "cr1") self.cr2 = ClassicalRegister(2, "cr2") self.circuit = QuantumCircuit(self.qr1, self.qr2, self.cr1, self.cr2) self.circuit.cx(self.qr2[0], self.qr2[1]) self.circuit.measure(self.qr2[0], self.cr2[0]) self.circuit.cx(self.qr2[1], self.qr2[0]) self.circuit.measure(self.qr2[1], self.cr2[1]) self.circuit.cx(self.qr1[0], self.qr1[1]) self.circuit.measure(self.qr1[0], self.cr1[0]) self.circuit.cx(self.qr1[1], self.qr1[0]) self.circuit.measure(self.qr1[1], self.cr1[1]) def test_get_layered_instructions(self): """_get_layered_instructions without reverse_bits""" (qregs, cregs, layered_ops) = _utils._get_layered_instructions(self.circuit) exp = [ [("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())], [("measure", (self.qr2[0],), (self.cr2[0],))], [("measure", (self.qr1[0],), (self.cr1[0],))], [("cx", (self.qr2[1], self.qr2[0]), ()), ("cx", (self.qr1[1], self.qr1[0]), ())], [("measure", (self.qr2[1],), (self.cr2[1],))], [("measure", (self.qr1[1],), (self.cr1[1],))], ] self.assertEqual([self.qr1[0], self.qr1[1], self.qr2[0], self.qr2[1]], qregs) self.assertEqual([self.cr1[0], self.cr1[1], self.cr2[0], self.cr2[1]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_reverse_bits(self): """_get_layered_instructions with reverse_bits=True""" (qregs, cregs, layered_ops) = _utils._get_layered_instructions( self.circuit, reverse_bits=True ) exp = [ [("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())], [("measure", (self.qr2[0],), (self.cr2[0],))], [("measure", (self.qr1[0],), (self.cr1[0],)), ("cx", (self.qr2[1], self.qr2[0]), ())], [("cx", (self.qr1[1], self.qr1[0]), ())], [("measure", (self.qr2[1],), (self.cr2[1],))], [("measure", (self.qr1[1],), (self.cr1[1],))], ] self.assertEqual([self.qr2[1], self.qr2[0], self.qr1[1], self.qr1[0]], qregs) self.assertEqual([self.cr2[1], self.cr2[0], self.cr1[1], self.cr1[0]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_remove_idle_wires(self): """_get_layered_instructions with idle_wires=False""" qr1 = QuantumRegister(3, "qr1") qr2 = QuantumRegister(3, "qr2") cr1 = ClassicalRegister(3, "cr1") cr2 = ClassicalRegister(3, "cr2") circuit = QuantumCircuit(qr1, qr2, cr1, cr2) circuit.cx(qr2[0], qr2[1]) circuit.measure(qr2[0], cr2[0]) circuit.cx(qr2[1], qr2[0]) circuit.measure(qr2[1], cr2[1]) circuit.cx(qr1[0], qr1[1]) circuit.measure(qr1[0], cr1[0]) circuit.cx(qr1[1], qr1[0]) circuit.measure(qr1[1], cr1[1]) (qregs, cregs, layered_ops) = _utils._get_layered_instructions(circuit, idle_wires=False) exp = [ [("cx", (qr2[0], qr2[1]), ()), ("cx", (qr1[0], qr1[1]), ())], [("measure", (qr2[0],), (cr2[0],))], [("measure", (qr1[0],), (cr1[0],))], [("cx", (qr2[1], qr2[0]), ()), ("cx", (qr1[1], qr1[0]), ())], [("measure", (qr2[1],), (cr2[1],))], [("measure", (qr1[1],), (cr1[1],))], ] self.assertEqual([qr1[0], qr1[1], qr2[0], qr2[1]], qregs) self.assertEqual([cr1[0], cr1[1], cr2[0], cr2[1]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_left_justification_simple(self): """Test _get_layered_instructions left justification simple since #2802 q_0: |0>───────■── ┌───┐ │ q_1: |0>┤ H ├──┼── ├───┤ │ q_2: |0>┤ H ├──┼── └───┘┌─┴─┐ q_3: |0>─────┤ X ├ └───┘ """ qc = QuantumCircuit(4) qc.h(1) qc.h(2) qc.cx(0, 3) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left") l_exp = [ [ ("h", (Qubit(QuantumRegister(4, "q"), 1),), ()), ("h", (Qubit(QuantumRegister(4, "q"), 2),), ()), ], [("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())], ] self.assertEqual( l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_right_justification_simple(self): """Test _get_layered_instructions right justification simple since #2802 q_0: |0>──■─────── │ ┌───┐ q_1: |0>──┼──┤ H ├ │ ├───┤ q_2: |0>──┼──┤ H ├ ┌─┴─┐└───┘ q_3: |0>┤ X ├───── └───┘ """ qc = QuantumCircuit(4) qc.h(1) qc.h(2) qc.cx(0, 3) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right") r_exp = [ [("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())], [ ("h", (Qubit(QuantumRegister(4, "q"), 1),), ()), ("h", (Qubit(QuantumRegister(4, "q"), 2),), ()), ], ] self.assertEqual( r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_left_justification_less_simple(self): """Test _get_layered_instructions left justification less simple example since #2802 ┌────────────┐┌───┐┌────────────┐ ┌─┐┌────────────┐┌───┐┌────────────┐ q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├──────────────┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├ ├────────────┤└─┬─┘├────────────┤┌────────────┐└╥┘└────────────┘└─┬─┘├────────────┤ q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├┤ U2(0,pi/1) ├─╫─────────────────■──┤ U2(0,pi/1) ├ └────────────┘ └────────────┘└────────────┘ ║ └────────────┘ q_2: |0>────────────────────────────────────────────────╫────────────────────────────────── ║ q_3: |0>────────────────────────────────────────────────╫────────────────────────────────── ║ q_4: |0>────────────────────────────────────────────────╫────────────────────────────────── ║ c1_0: 0 ════════════════════════════════════════════════╩══════════════════════════════════ """ qasm = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[5]; creg c1[1]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; u2(0,3.14159265358979) q[1]; measure q[0] -> c1[0]; u2(0,3.14159265358979) q[0]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; """ qc = QuantumCircuit.from_qasm_str(qasm) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left") l_exp = [ [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("u2", (Qubit(QuantumRegister(5, "q"), 1),), ())], [ ( "measure", (Qubit(QuantumRegister(5, "q"), 0),), (Clbit(ClassicalRegister(1, "c1"), 0),), ) ], [("u2", (Qubit(QuantumRegister(5, "q"), 0),), ())], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], ] self.assertEqual( l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_right_justification_less_simple(self): """Test _get_layered_instructions right justification less simple example since #2802 ┌────────────┐┌───┐┌────────────┐┌─┐┌────────────┐┌───┐┌────────────┐ q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├ ├────────────┤└─┬─┘├────────────┤└╥┘├────────────┤└─┬─┘├────────────┤ q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├─╫─┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├ └────────────┘ └────────────┘ ║ └────────────┘ └────────────┘ q_2: |0>──────────────────────────────────╫────────────────────────────────── ║ q_3: |0>──────────────────────────────────╫────────────────────────────────── ║ q_4: |0>──────────────────────────────────╫────────────────────────────────── ║ c1_0: 0 ══════════════════════════════════╩══════════════════════════════════ """ qasm = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[5]; creg c1[1]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; u2(0,3.14159265358979) q[1]; measure q[0] -> c1[0]; u2(0,3.14159265358979) q[0]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; """ qc = QuantumCircuit.from_qasm_str(qasm) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right") r_exp = [ [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [ ( "measure", (Qubit(QuantumRegister(5, "q"), 0),), (Clbit(ClassicalRegister(1, "c1"), 0),), ) ], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], ] self.assertEqual( r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_op_with_cargs(self): """Test _get_layered_instructions op with cargs right of measure ┌───┐┌─┐ q_0: |0>┤ H ├┤M├───────────── └───┘└╥┘┌───────────┐ q_1: |0>──────╫─┤0 ├ ║ │ add_circ │ c_0: 0 ══════╩═╡0 ╞ └───────────┘ c_1: 0 ═════════════════════ """ qc = QuantumCircuit(2, 2) qc.h(0) qc.measure(0, 0) qc_2 = QuantumCircuit(1, 1, name="add_circ") qc_2.h(0).c_if(qc_2.cregs[0], 1) qc_2.measure(0, 0) qc.append(qc_2, [1], [0]) (_, _, layered_ops) = _utils._get_layered_instructions(qc) expected = [ [("h", (Qubit(QuantumRegister(2, "q"), 0),), ())], [ ( "measure", (Qubit(QuantumRegister(2, "q"), 0),), (Clbit(ClassicalRegister(2, "c"), 0),), ) ], [ ( "add_circ", (Qubit(QuantumRegister(2, "q"), 1),), (Clbit(ClassicalRegister(2, "c"), 0),), ) ], ] self.assertEqual( expected, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_nomathmode(self): """Test generate latex label default.""" self.assertEqual("abc", _utils.generate_latex_label("abc")) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_nomathmode_utf8char(self): """Test generate latex label utf8 characters.""" self.assertEqual( "{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("∭X∀Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_mathmode_utf8char(self): """Test generate latex label mathtext with utf8.""" self.assertEqual( "abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("$abc_$∭X∀Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_mathmode_underscore_outside(self): """Test generate latex label with underscore outside mathmode.""" self.assertEqual( "abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("$abc$_∭X∀Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_escaped_dollar_signs(self): """Test generate latex label with escaped dollarsign.""" self.assertEqual("${\\ensuremath{\\forall}}$", _utils.generate_latex_label(r"\$∀\$")) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_escaped_dollar_sign_in_mathmode(self): """Test generate latex label with escaped dollar sign in mathmode.""" self.assertEqual( "a$bc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label(r"$a$bc$_∭X∀Y"), ) def test_array_to_latex(self): """Test array_to_latex produces correct latex string""" matrix = [ [np.sqrt(1 / 2), 1 / 16, 1 / np.sqrt(8) + 3j, -0.5 + 0.5j], [1 / 3 - 1 / 3j, np.sqrt(1 / 2) * 1j, 34.3210, -9 / 2], ] matrix = np.array(matrix) exp_str = ( "\\begin{bmatrix}\\frac{\\sqrt{2}}{2}&\\frac{1}{16}&" "\\frac{\\sqrt{2}}{4}+3i&-\\frac{1}{2}+\\frac{i}{2}\\\\" "\\frac{1}{3}+\\frac{i}{3}&\\frac{\\sqrt{2}i}{2}&34.321&-" "\\frac{9}{2}\\\\\\end{bmatrix}" ) result = array_to_latex(matrix, source=True).replace(" ", "").replace("\n", "") self.assertEqual(exp_str, result) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister # If the name is not given, default name is taken q=QuantumRegister(2) q # We can also give the name to the quantum register q=QuantumRegister(2,'qr') q c=ClassicalRegister(2) c=ClassicalRegister(2,'cr') q=QuantumRegister(2,'qr') c=ClassicalRegister(2,'cr') qc=QuantumCircuit(q,c) qc=QuantumCircuit(QuantumRegister(2,'qr'),ClassicalRegister(2,'cr')) qc=QuantumCircuit(QuantumRegister(2,'qr')) qc=QuantumCircuit(QuantumRegister(2)) qc=QuantumCircuit(QuantumRegister(2),ClassicalRegister(2)) qc=QuantumCircuit(2) qc=QuantumCircuit(2,2) qc # In this example, we have given registers name qc=QuantumCircuit(QuantumRegister(2,'qr'),ClassicalRegister(2,'cr')) qc.draw(output="mpl") print(qc.qubits) print(qc.clbits) # In this example, we have NOT given registers name qc=QuantumCircuit(2,2) qc.draw(output="mpl") print(qc.qubits) print(qc.clbits) qc.qregs qc.cregs qc.num_qubits qc.num_clbits qc.clbits qc.qubits qc.width() #total number of qubits and classical bits
https://github.com/GabrielPontolillo/QiskitPBT
GabrielPontolillo
from qiskit import QuantumCircuit, transpile, assemble from qiskit.circuit.library import QFT class CtrlMultCircuit(QuantumCircuit): def __init__(self, a, binary_power, N): super().__init__(N.bit_length()) self.a = a self.power = 2 ** binary_power # Convert binary to decimal self.N = N self.name = f'{self.a}^{self.power} mod {self.N}' self._create_circuit() def _create_circuit(self): for dec_power in range(self.power): a_exp = self.a ** dec_power % self.N for i in range(self.num_qubits): if a_exp >> i & 1: self.x(i) for j in range(i + 1, self.num_qubits): if a_exp >> j & 1: self.swap(i, j) class QPECircuit(QuantumCircuit): def __init__(self, a, N): super().__init__(2 * N.bit_length(), N.bit_length()) self.a = a self.N = N self._create_circuit() def _modular_exponentiation(self): for qbit_idx in range(self.num_qubits // 2): self.append( CtrlMultCircuit(self.a, qbit_idx, self.N).to_gate().control(), [qbit_idx] + list(range(self.num_qubits // 2, 2 * self.num_qubits // 2)) ) def _create_circuit(self): self.h(range(self.num_qubits // 2)) # Apply Hadamard gates to the first n qubits self.x(self.num_qubits - 1) self.barrier() self._modular_exponentiation() # Apply controlled modular exponentiation self.barrier() self.append( QFT(self.num_qubits // 2, inverse=True), range(self.num_qubits // 2) # Apply inverse QFT to the first n qubits ) def collapse(self, simulator): self.measure(range(self.num_qubits // 2), range(self.num_qubits // 2)) transpiled_circuit = transpile(self, simulator) self.collapse_result = simulator.run(transpiled_circuit, memory=True).result() return self.collapse_result
https://github.com/qiskit-community/qiskit-tket-passes
qiskit-community
import pydoc import re import pytket.passes as tkps def get_arguments_from_doc(tket_pass): arguments = [] _doc = pydoc.getdoc(tket_pass) if 'Overloaded function.' in _doc: #Return the first signature #TODO: We should return all possible signatures. This would requires changes in ToQiskitPass also. matches = re.findall("[1-9]\. (" + tket_pass.__name__ + '[^\n]+)', _doc) synopsis_line = matches[0] else: synopsis_line = pydoc.splitdoc(_doc)[0] # To avoid issue caused by callable parentheses: synopsis_line = re.sub('Callable\[\[[^\[]+\][^\[]+\]', 'Callable', synopsis_line) match = re.search("\(([^(]+)\)", synopsis_line) if match is not None: splitted_args = match.group(1).split(', ') for arg_str in splitted_args: if arg_str == '**kwargs': continue else: argument = arg_str.split(': ') eq_index = argument[1].find('=') if eq_index > 0: (_type, _default) = argument[1].split(' = ') arguments.append((argument[0], _type, _default)) else: arguments.append(tuple(argument)) return arguments # This is **temp**. Conversion should be done in a better way # https://github.com/CQCL/pytket-qiskit/blob/develop/pytket/extensions/qiskit/qiskit_convert.py from pytket.extensions.qiskit import qiskit_to_tk, tk_to_qiskit from qiskit.converters import dag_to_circuit, circuit_to_dag from pytket.circuit import Circuit from qiskit.dagcircuit import DAGCircuit def qiskit_dag_to_tk(dag: DAGCircuit): # Replace any gate that is not known to pyket by its definition from pytket.extensions.qiskit.qiskit_convert import _known_qiskit_gate for node in dag.op_nodes(): if not type(node.op) in _known_qiskit_gate: dag.substitute_node_with_dag(node, circuit_to_dag(node.op.definition)) return qiskit_to_tk(dag_to_circuit(dag)) def tk_to_qiskit_dag(tkcirc: Circuit): return circuit_to_dag(tk_to_qiskit(tkcirc))
https://github.com/hkhetawat/QArithmetic
hkhetawat
# Import the Qiskit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, Aer from QArithmetic import div # Input n n = 2 p = QuantumRegister(2*n) d = QuantumRegister(2*n) q = QuantumRegister(n) cp = ClassicalRegister(2*n) cd = ClassicalRegister(2*n) cq = ClassicalRegister(n) qc = QuantumCircuit(p,d,q,cp,cd,cq) # Input Superposition # p = 0011 qc.x(p[0]) qc.x(p[1]) # d = 1000 qc.x(d[3]) div(qc, p, d, q, n) qc.measure(p, cp) qc.measure(d, cd) qc.measure(q, cq) backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(qc, backend_sim) result_sim = job_sim.result() print(result_sim.get_counts(qc))
https://github.com/crabster/qiskit-learning
crabster
from qiskit import QuantumCircuit from QCLG_lvl3.oracles.secret_number_oracle import SecretNUmberOracle class BernsteinVazirani: @classmethod def bernstein_vazirani(cls, random_binary, eval_mode: bool) -> QuantumCircuit: # Construct secret number oracle secret_number_oracle = SecretNUmberOracle.create_secret_number_oracle(random_binary=random_binary, eval_mode=eval_mode) num_of_qubits = secret_number_oracle.num_qubits # Construct circuit according to the length of the number dj_circuit = QuantumCircuit(num_of_qubits, num_of_qubits - 1) dj_circuit_before_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1) # Apply H-gates for qubit in range(num_of_qubits - 1): dj_circuit_before_oracle.h(qubit) # Put output qubit in state |-> dj_circuit_before_oracle.x(num_of_qubits - 1) dj_circuit_before_oracle.h(num_of_qubits - 1) dj_circuit += dj_circuit_before_oracle # Add oracle dj_circuit += secret_number_oracle dj_circuit_after_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1) # Repeat H-gates for qubit in range(num_of_qubits - 1): dj_circuit_after_oracle.h(qubit) dj_circuit_after_oracle.barrier() # Measure for i in range(num_of_qubits - 1): dj_circuit_after_oracle.measure(i, i) dj_circuit += dj_circuit_after_oracle if not eval_mode: print("Circuit before the oracle\n") print(QuantumCircuit.draw(dj_circuit_before_oracle)) print("Circuit after the oracle\n") print(QuantumCircuit.draw(dj_circuit_after_oracle)) print(dj_circuit) return dj_circuit
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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. """ Example use of the initialize gate to prepare arbitrary pure states. """ import math from qiskit import QuantumCircuit, execute, BasicAer ############################################################### # Make a quantum circuit for state initialization. ############################################################### circuit = QuantumCircuit(4, 4, name="initializer_circ") desired_vector = [ 1 / math.sqrt(4) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(8) * complex(0, 1), 0, 0, 0, 0, 1 / math.sqrt(4) * complex(1, 0), 1 / math.sqrt(8) * complex(1, 0), ] circuit.initialize(desired_vector, [0, 1, 2, 3]) circuit.measure([0, 1, 2, 3], [0, 1, 2, 3]) print(circuit) ############################################################### # Execute on a simulator backend. ############################################################### shots = 10000 # Desired vector print("Desired probabilities: ") print([format(abs(x * x), ".3f") for x in desired_vector]) # Initialize on local simulator sim_backend = BasicAer.get_backend("qasm_simulator") job = execute(circuit, sim_backend, shots=shots) result = job.result() counts = result.get_counts(circuit) qubit_strings = [format(i, "04b") for i in range(2**4)] print("Probabilities from simulator: ") print([format(counts.get(s, 0) / shots, ".3f") for s in qubit_strings])
https://github.com/DRA-chaos/Quantum-Classical-Hyrid-Neural-Network-for-binary-image-classification-using-PyTorch-Qiskit-pipeline
DRA-chaos
!pip install qiskit import numpy as np import matplotlib.pyplot as plt import torch from torch.autograd import Function from torchvision import datasets, transforms import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import qiskit from qiskit import transpile, assemble from qiskit.visualization import * def to_numbers(tensor_list): num_list = [] for tensor in tensor_list: num_list += [tensor.item()] return num_list import numpy as np import torch from torch.autograd import Function import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import torchvision from torchvision import datasets, transforms from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, execute from qiskit.circuit import Parameter from qiskit import Aer from tqdm import tqdm from matplotlib import pyplot as plt %matplotlib inline class QuantumCircuit: """ This class provides a simple interface for interaction with the quantum circuit """ def __init__(self, n_qubits, backend, shots): # --- Circuit definition --- self._circuit = qiskit.QuantumCircuit(n_qubits) all_qubits = [i for i in range(n_qubits)] self.theta = qiskit.circuit.Parameter('theta') self._circuit.h(all_qubits) self._circuit.barrier() self._circuit.ry(self.theta, all_qubits) self._circuit.measure_all() # --------------------------- self.backend = backend self.shots = shots def run(self, thetas): t_qc = transpile(self._circuit, self.backend) qobj = assemble(t_qc, shots=self.shots, parameter_binds = [{self.theta: theta} for theta in thetas]) job = self.backend.run(qobj) result = job.result().get_counts() counts = np.array(list(result.values())) states = np.array(list(result.keys())).astype(float) # Compute probabilities for each state probabilities = counts / self.shots # Get state expectation expectation = np.sum(states * probabilities) return np.array([expectation]) simulator = qiskit.Aer.get_backend('qasm_simulator') circuit = QuantumCircuit(1, simulator, 100) print('Expected value for rotation pi {}'.format(circuit.run([np.pi])[0])) circuit._circuit.draw() class HybridFunction(Function): """ Hybrid quantum - classical function definition """ @staticmethod def forward(ctx, input, quantum_circuit, shift): """ Forward pass computation """ ctx.shift = shift ctx.quantum_circuit = quantum_circuit expectation_z = ctx.quantum_circuit.run(input[0].tolist()) result = torch.tensor([expectation_z]) ctx.save_for_backward(input, result) return result @staticmethod def backward(ctx, grad_output): """ Backward pass computation """ input, expectation_z = ctx.saved_tensors input_list = np.array(input.tolist()) shift_right = input_list + np.ones(input_list.shape) * ctx.shift shift_left = input_list - np.ones(input_list.shape) * ctx.shift gradients = [] for i in range(len(input_list)): expectation_right = ctx.quantum_circuit.run(shift_right[i]) expectation_left = ctx.quantum_circuit.run(shift_left[i]) gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left]) gradients.append(gradient) gradients = np.array([gradients]).T return torch.tensor([gradients]).float() * grad_output.float(), None, None class Hybrid(nn.Module): """ Hybrid quantum - classical layer definition """ def __init__(self, backend, shots, shift): super(Hybrid, self).__init__() self.quantum_circuit = QuantumCircuit(1, backend, shots) self.shift = shift def forward(self, input): return HybridFunction.apply(input, self.quantum_circuit, self.shift) import torchvision transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform) labels = cifar_trainset.targets # get the labels for the data labels = np.array(labels) idx1 = np.where(labels == 0) # filter on aeroplanes idx2 = np.where(labels == 1) # filter on automobiles # Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set) n=100 # concatenate the data indices idx = np.concatenate((idx1[0][0:n],idx2[0][0:n])) # create the filtered dataset for our training set cifar_trainset.targets = labels[idx] cifar_trainset.data = cifar_trainset.data[idx] train_loader = torch.utils.data.DataLoader(cifar_trainset, batch_size=1, shuffle=True) import numpy as np import matplotlib.pyplot as plt n_samples_show = 8 data_iter = iter(train_loader) fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 2)) while n_samples_show > 0: images, targets = data_iter.__next__() images=images.squeeze() #axes[n_samples_show - 1].imshow( tf.shape( tf.squeeze(images[0]) ),cmap='gray' ) #plt.imshow((tf.squeeze(images[0]))) #plt.imshow( tf.shape( tf.squeeze(x_train) ) ) #axes[n_samples_show - 1].imshow(images[0].numpy().squeeze(), cmap='gray') axes[n_samples_show - 1].imshow(images[0].numpy(), cmap='gray') axes[n_samples_show - 1].set_xticks([]) axes[n_samples_show - 1].set_yticks([]) axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item())) n_samples_show -= 1 import torchvision transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors cifar_testset = datasets.CIFAR10(root='./data1', train=False, download=True, transform=transform) labels = cifar_testset.targets # get the labels for the data labels = np.array(labels) idx1 = np.where(labels == 0) # filter on aeroplanes idx2 = np.where(labels == 1) # filter on automobiles # Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set) n=100 # concatenate the data indices idx = np.concatenate((idx1[0][0:n],idx2[0][0:n])) # create the filtered dataset for our training set cifar_testset.targets = labels[idx] cifar_testset.data = cifar_testset.data[idx] test_loader = torch.utils.data.DataLoader(cifar_testset, batch_size=1, shuffle=True) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.dropout = nn.Dropout2d() self.fc1 = nn.Linear(500, 500) self.fc2 = nn.Linear(500, 1) self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2) def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2) x = self.dropout(x) x = x.view(1, -1) x = F.relu(self.fc1(x)) x = self.fc2(x) x = self.hybrid(x) return torch.cat((x, 1 - x), -1) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 5 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Now plotting the training graph plt.plot(loss_list) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 10 loss_listA = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listA.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listA[-1])) #Now plotting the training graph plt.plot(loss_listA) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 15 loss_listb = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listb.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listb[-1])) #Now plotting the training graph plt.plot(loss_listb) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.01) loss_func = nn.NLLLoss() epochs = 5 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Now plotting the training graph plt.plot(loss_list) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.01) loss_func = nn.NLLLoss() epochs = 10 loss_listc = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listc.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listc[-1])) #Now plotting the training graph plt.plot(loss_listc) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.01) loss_func = nn.NLLLoss() epochs = 15 loss_listd = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listd.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listd[-1])) #Now plotting the training graph plt.plot(loss_listd) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 5 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Now plotting the training graph plt.plot(loss_list) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.SGD(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 5 loss_listF = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listF.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listF[-1])) #Now plotting the training graph plt.plot(loss_listF) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.SGD(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 15 loss_listF = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listF.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listF[-1])) #Now plotting the training graph plt.plot(loss_listF) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adadelta(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 10 loss_listF = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listF.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listF[-1])) #Now plotting the training graph plt.plot(loss_listF) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adadelta(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 15 loss_listF = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listF.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listF[-1])) #Now plotting the training graph plt.plot(loss_listF) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) ##Adagrad model = Net() optimizer = optim.Adagrad(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 5 loss_listG = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listG.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listG[-1])) #Now plotting the training graph plt.plot(loss_listG) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100)) #RMSprop model = Net() optimizer = optim.RMSprop(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 5 loss_listG = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listG.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listG[-1])) #Now plotting the training graph plt.plot(loss_listG) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model = Net() optimizer = optim.RMSprop(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 10 loss_listH = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listH.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listH[-1])) #Now plotting the training graph plt.plot(loss_listH) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100)) model = Net() optimizer = optim.RMSprop(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 15 loss_listH = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listH.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listH[-1])) #Now plotting the training graph plt.plot(loss_listH) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100)) model = Net() optimizer = optim.RMSprop(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 20 loss_listH = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listH.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listH[-1])) #Now plotting the training graph plt.plot(loss_listH) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100)) #ADAM 20 epochs model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 20 loss_listH = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listH.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listH[-1])) #Now plotting the training graph plt.plot(loss_listH) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100)) loss.item() model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100)) model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100)) model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.RMSprop(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 10 loss_listD = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listD.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listD[-1])) #Now plotting the training graph plt.plot(loss_listD) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 10 loss_listD = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listD.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listD[-1])) #Now plotting the training graph plt.plot(loss_listD) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 15 loss_listE = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listE.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listE[-1])) #Now plotting the training graph plt.plot(loss_listE) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 10 loss_list1 = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list1.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list1[-1])) #Alongside, let's also plot the data plt.plot(loss_list1) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 15 loss_list2 = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list2.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list2[-1])) #Alongside, let's also plot the data plt.plot(loss_list2) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 20 loss_list3 = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list3.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list3[-1])) #Alongside, let's also plot the data plt.plot(loss_list3) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.NLLLoss() epochs = 30 loss_list4 = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list4.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list4[-1])) #Alongside, let's also plot the data plt.plot(loss_list4) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adamax(model.parameters(), lr=0.0001) loss_func = nn.NLLLoss() epochs = 5 loss_list4 = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list4.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format( 100. * (epoch + 1) / epochs, loss_list4[-1])) #Alongside, let's also plot the data plt.plot(loss_list4) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Neg Log Likelihood Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.CrossEntropyLoss() epochs = 5 loss_list = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1])) #Now plotting the training graph plt.plot(loss_list) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Cross Entropy loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.CrossEntropyLoss() epochs = 10 loss_listK = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listK.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listK[-1])) #Now plotting the training graph plt.plot(loss_listK) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Cross Entropy loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.CrossEntropyLoss() epochs = 15 loss_listL = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listL.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listL[-1])) #Now plotting the training graph plt.plot(loss_listL) plt.title('Hybrid NN Training Convergence') plt.xlabel('Training Iterations') plt.ylabel('Cross Entropy loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) loss_func = nn.PoissonNLLLoss() epochs = 5 loss_listK = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listK.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listK[-1])) #Now plotting the training graph plt.plot(loss_listK) plt.title('Negative log likelihood with Poisson') plt.xlabel('Training Iterations') plt.ylabel('NLL with Poisson distribution.') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 5 loss_listM = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listM.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listM[-1])) #Now plotting the training graph plt.plot(loss_listM) plt.title('Hybrid NN training convergence') plt.xlabel('Training Iterations') plt.ylabel('Negative log Likelihood loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 10 loss_listM = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listM.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listM[-1])) #Now plotting the training graph plt.plot(loss_listM) plt.title('Hybrid NN training convergence') plt.xlabel('Training Iterations') plt.ylabel('Negative log Likelihood loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 15 loss_listM = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listM.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listM[-1])) #Now plotting the training graph plt.plot(loss_listM) plt.title('Hybrid NN training convergence') plt.xlabel('Training Iterations') plt.ylabel('Negative log Likelihood loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.NLLLoss() epochs = 20 loss_listM = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listM.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listM[-1])) #Now plotting the training graph plt.plot(loss_listM) plt.title('Hybrid NN training convergence') plt.xlabel('Training Iterations') plt.ylabel('Negative log Likelihood loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.CrossEntropyLoss() epochs = 5 loss_listN = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listN.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listN[-1])) #Now plotting the training graph plt.plot(loss_listN) plt.title('Hybrid NN training convergence') plt.xlabel('Training Iterations') plt.ylabel('Cross Entropy Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) #changing epochs model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.CrossEntropyLoss() epochs = 10 loss_listN = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listN.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listN[-1])) #Now plotting the training graph plt.plot(loss_listN) plt.title('Hybrid NN training convergence') plt.xlabel('Training Iterations') plt.ylabel('Cross Entropy Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) ) #epochs to 15 model = Net() optimizer = optim.Adam(model.parameters(), lr=0.0005) loss_func = nn.CrossEntropyLoss() epochs = 15 loss_listN = [] model.train() for epoch in range(epochs): total_loss = [] for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() # Forward pass output = model(data) # Calculating loss loss = loss_func(output, target) # Backward pass loss.backward() # Optimize the weights optimizer.step() total_loss.append(loss.item()) loss_listN.append(sum(total_loss)/len(total_loss)) print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_listN[-1])) #Now plotting the training graph plt.plot(loss_listN) plt.title('Hybrid NN training convergence') plt.xlabel('Training Iterations') plt.ylabel('Cross Entropy Loss') model.eval() with torch.no_grad(): correct = 0 for batch_idx, (data, target) in enumerate(test_loader): output = model(data) pred = output.argmax(dim=1, keepdim=True) correct += pred.eq(target.view_as(pred)).sum().item() loss = loss_func(output, target) total_loss.append(loss.item()) print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format( sum(total_loss) / len(total_loss), correct / len(test_loader) * 100) )
https://github.com/avkhadiev/schwinger-vqe
avkhadiev
from qiskit import * import qiskit.tools.jupyter import numpy as np IBMQ.load_account() class SchwingerAnsatz(qiskit.aqua.components.variational_forms.VariationalForm): """ Variational Layer from Martin's Paper """ CONFIGURATION = { 'name': 'Schwinger Ansatz', 'description': 'Variational Form for Schwinger VQE', 'input_schema': { '$schema': 'http://json-schema.org/draft-07/schema#', 'id': 'schwinger_schema', 'type': 'object', 'properties': { 'depth': { 'type': 'integer', 'default': 3, 'minimum': 1 }, 'entangler_map': { 'type': ['array', 'null'], 'default': None }, 'entanglement_gate': { 'type': 'string', 'default': 'cx', 'enum': ['cx'] }, }, 'additionalProperties': False }, 'depends': [ { 'pluggable_type': 'initial_state', 'default': { 'name': 'ZERO', } }, ], } def __init__(self, depth=3, entangler_map=None, initial_state=None): """ Constructor. Args: depth (int) : number of rotation layers entangler_map (list[list]): describe the connectivity of qubits, each list describes [source, target], or None for full entanglement. Note that the order is the list is the order of applying the two-qubit gate. initial_state (InitialState): an initial state object """ self.validate(locals()) super().__init__() # hard-coded, first pass through FIXME num_qubits = 2 num_parameters = 3 entanglement='full' entanglement_gate='cx' skip_unentangled_qubits = False self._num_qubits = num_qubits self._depth = depth if entangler_map is None: self._entangler_map = qiskit.aqua.components.variational_forms.VariationalForm.get_entangler_map(entanglement, num_qubits) else: self._entangler_map = qiskit.aqua.components.variational_forms.VariationalForm.validate_entangler_map(entangler_map, num_qubits) # determine the entangled qubits all_qubits = [] for src, targ in self._entangler_map: all_qubits.extend([src, targ]) self._entangled_qubits = sorted(list(set(all_qubits))) self._initial_state = initial_state self._entanglement_gate = entanglement_gate self._skip_unentangled_qubits = skip_unentangled_qubits # for the first layer self._num_parameters = num_parameters # for repeated block self._num_parameters += num_parameters * (depth-1) self._bounds = [(-np.pi, np.pi)] * self._num_parameters def construct_circuit(self, parameters, q=None): """ Construct the variational form, given its parameters. Args: parameters (numpy.ndarray): circuit parameters q (QuantumRegister): Quantum Register for the circuit. Returns: QuantumCircuit: a quantum circuit with given `parameters` Raises: ValueError: the number of parameters is incorrect. """ if len(parameters) != self._num_parameters: raise ValueError('The number of parameters has to be {}'.format(self._num_parameters)) if q is None: q = QuantumRegister(self._num_qubits, name='q') if self._initial_state is not None: circuit = self._initial_state.construct_circuit('circuit', q) else: circuit = QuantumCircuit(q) # param_idx = 0 def angle(theta=0., phi=0., lam=0.): return [theta, phi, lam] for _ in range(self._depth): # get variational parameters for this layer t0 = parameters[param_idx] # theta-angle values t1 = parameters[param_idx+1] t2 = parameters[param_idx+2] t = [angle(t_i) for t_i in [t0, t1, t2]] # Construct circuit circuit.u3(*(t[1]), 0) # u3(*angles, q) circuit.u3(*(t[0]), 1) circuit.cx(0, 1) # entangling qubit cx(ctrl, tgt) circuit.u3(*(t[0]), 1) circuit.cx(0, 1) # entangling qubit cx(ctrl, tgt) circuit.u3(*(t[2]), 1) circuit.barrier(q) return circuit test = SchwingerAnsatz(1) vqs_circ = test.construct_circuit([-0.386244, 0.317799, -0.416888]) vqs_circ.draw(output='latex', scale=0.5)
https://github.com/ashishpatel26/IBM-Quantum-Challenge-Fall-2021
ashishpatel26
# General imports import os import gzip import numpy as np import matplotlib.pyplot as plt from pylab import cm import warnings warnings.filterwarnings("ignore") # scikit-learn imports from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.decomposition import PCA from sklearn.svm import SVC from sklearn.metrics import accuracy_score # Qiskit imports from qiskit import Aer, execute from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2 from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate from qiskit_machine_learning.kernels import QuantumKernel # Load MNIST dataset DATA_PATH = './resources/ch3_part1.npz' data = np.load(DATA_PATH) sample_train = data['sample_train'] labels_train = data['labels_train'] sample_test = data['sample_test'] # Split train data sample_train, sample_val, labels_train, labels_val = train_test_split( sample_train, labels_train, test_size=0.2, random_state=42) # Visualize samples fig = plt.figure() LABELS = [4, 9] num_labels = len(LABELS) for i in range(num_labels): ax = fig.add_subplot(1, num_labels, i+1) img = sample_train[labels_train==LABELS[i]][0].reshape((28, 28)) ax.imshow(img, cmap="Greys") # Standardize ss = StandardScaler() sample_train = ss.fit_transform(sample_train) sample_val = ss.transform(sample_val) sample_test = ss.transform(sample_test) # Reduce dimensions N_DIM = 5 pca = PCA(n_components=N_DIM) sample_train = pca.fit_transform(sample_train) sample_val = pca.transform(sample_val) sample_test = pca.transform(sample_test) # Normalize mms = MinMaxScaler((-1, 1)) sample_train = mms.fit_transform(sample_train) sample_val = mms.transform(sample_val) sample_test = mms.transform(sample_test) # 3 features, depth 2 map_z = ZFeatureMap(feature_dimension=3, reps=2) map_z.decompose().draw('mpl') # 3 features, depth 1, linear entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear') map_zz.decompose().draw('mpl') # 3 features, depth 1, circular entanglement map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular') map_zz.decompose().draw('mpl') # 3 features, depth 1 map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ']) map_pauli.decompose().draw('mpl') twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'], entanglement_blocks='cx', entanglement='circular', insert_barriers=True) twolocal.decompose().draw('mpl') twolocaln = NLocal(num_qubits=3, reps=2, rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))], entanglement_blocks=CXGate(), entanglement='circular', insert_barriers=True) twolocaln.decompose().draw('mpl') print(f'First training data: {sample_train[0]}') encode_map = PauliFeatureMap(feature_dimension=N_DIM, reps=1, paulis = ['X', 'Y', 'ZZ']) encode_circuit = encode_map.bind_parameters(sample_train[0]) encode_circuit.decompose().draw(output='mpl') ############################## # Provide your code here ex3a_fmap = ZZFeatureMap(feature_dimension=5, reps=3, entanglement='circular') ############################## # Check your answer and submit using the following code from qc_grader import grade_ex3a grade_ex3a(ex3a_fmap) pauli_map = PauliFeatureMap(feature_dimension=N_DIM, reps=1, paulis = ['X', 'Y', 'ZZ']) pauli_kernel = QuantumKernel(feature_map=pauli_map, quantum_instance=Aer.get_backend('statevector_simulator')) print(f'First training data : {sample_train[0]}') print(f'Second training data: {sample_train[1]}') pauli_circuit = pauli_kernel.construct_circuit(sample_train[0], sample_train[1]) pauli_circuit.decompose().decompose().draw(output='mpl') backend = Aer.get_backend('qasm_simulator') job = execute(pauli_circuit, backend, shots=8192, seed_simulator=1024, seed_transpiler=1024) counts = job.result().get_counts(pauli_circuit) print(f"Transition amplitude: {counts['0'*N_DIM]/sum(counts.values())}") matrix_train = pauli_kernel.evaluate(x_vec=sample_train) matrix_val = pauli_kernel.evaluate(x_vec=sample_val, y_vec=sample_train) fig, axs = plt.subplots(1, 2, figsize=(10, 5)) axs[0].imshow(np.asmatrix(matrix_train), interpolation='nearest', origin='upper', cmap='Blues') axs[0].set_title("training kernel matrix") axs[1].imshow(np.asmatrix(matrix_val), interpolation='nearest', origin='upper', cmap='Reds') axs[1].set_title("validation kernel matrix") plt.show() x = [-0.5, -0.4, 0.3, 0, -0.9] y = [0, -0.7, -0.3, 0, -0.4] ############################## # Provide your code here zz = ZZFeatureMap(feature_dimension=N_DIM, reps=3, entanglement='circular') zz_kernel = QuantumKernel(feature_map=zz, quantum_instance=Aer.get_backend('statevector_simulator')) zz_circuit = zz_kernel.construct_circuit(x, y) backend = Aer.get_backend('qasm_simulator') job = execute(zz_circuit, backend, shots=8192, seed_simulator=1024, seed_transpiler=1024) counts = job.result().get_counts(zz_circuit) ex3b_amp = counts['0'*N_DIM]/sum(counts.values()) ############################## # Check your answer and submit using the following code from qc_grader import grade_ex3b grade_ex3b(ex3b_amp) pauli_svc = SVC(kernel='precomputed') pauli_svc.fit(matrix_train, labels_train) pauli_score = pauli_svc.score(matrix_val, labels_val) print(f'Precomputed kernel classification test score: {pauli_score*100}%') # Load MNIST dataset DATA_PATH = './resources/ch3_part2.npz' data = np.load(DATA_PATH) sample_train = data['sample_train'] labels_train = data['labels_train'] sample_test = data['sample_test'] # Split train data sample_train, sample_val, labels_train, labels_val = train_test_split( sample_train, labels_train, test_size=0.2, random_state=42) # Visualize samples fig = plt.figure() LABELS = [0, 2, 3] num_labels = len(LABELS) for i in range(num_labels): ax = fig.add_subplot(1, num_labels, i+1) img = sample_train[labels_train==LABELS[i]][0].reshape((28, 28)) ax.imshow(img, cmap="Greys") # Standardize standard_scaler = StandardScaler() sample_train = standard_scaler.fit_transform(sample_train) sample_val = standard_scaler.transform(sample_val) sample_test = standard_scaler.transform(sample_test) # Reduce dimensions N_DIM = 5 pca = PCA(n_components=N_DIM) sample_train = pca.fit_transform(sample_train) sample_val = pca.transform(sample_val) sample_test = pca.transform(sample_test) # Normalize min_max_scaler = MinMaxScaler((-1, 1)) sample_train = min_max_scaler.fit_transform(sample_train) sample_val = min_max_scaler.transform(sample_val) sample_test = min_max_scaler.transform(sample_test) labels_train_0 = np.where(labels_train==0, 1, 0) labels_val_0 = np.where(labels_val==0, 1, 0) print(f'Original validation labels: {labels_val}') print(f'Validation labels for 0 vs Rest: {labels_val_0}') labels_train_2 = np.where(labels_train==2, 1, 0) labels_val_2 = np.where(labels_val==2, 1, 0) print(f'Original validation labels: {labels_val}') print(f'Validation labels for 2 vs Rest: {labels_val_2}') labels_train_3 = np.where(labels_train==3, 1, 0) labels_val_3 = np.where(labels_val==3, 1, 0) print(f'Original validation labels: {labels_val}') print(f'Validation labels for 2 vs Rest: {labels_val_3}') pauli_map_0 = ZZFeatureMap(feature_dimension=N_DIM, reps=1, entanglement = 'linear') pauli_kernel_0 = QuantumKernel(feature_map=pauli_map_0, quantum_instance=Aer.get_backend('statevector_simulator')) pauli_svc_0 = SVC(kernel='precomputed', probability=True) matrix_train_0 = pauli_kernel_0.evaluate(x_vec=sample_train) pauli_svc_0.fit(matrix_train_0, labels_train_0) matrix_val_0 = pauli_kernel_0.evaluate(x_vec=sample_val, y_vec=sample_train) pauli_score_0 = pauli_svc_0.score(matrix_val_0, labels_val_0) print(f'Accuracy of discriminating between label 0 and others: {pauli_score_0*100}%') pauli_map_2 = ZZFeatureMap(feature_dimension=N_DIM, reps=1, entanglement='linear') pauli_kernel_2 = QuantumKernel(feature_map=pauli_map_2, quantum_instance=Aer.get_backend('statevector_simulator')) pauli_svc_2 = SVC(kernel='precomputed', probability=True) matrix_train_2 = pauli_kernel_2.evaluate(x_vec=sample_train) pauli_svc_2.fit(matrix_train_2, labels_train_2) matrix_val_2 = pauli_kernel_2.evaluate(x_vec=sample_val, y_vec=sample_train) pauli_score_2 = pauli_svc_2.score(matrix_val_2, labels_val_2) print(f'Accuracy of discriminating between label 2 and others: {pauli_score_2*100}%') pauli_map_3 = ZZFeatureMap(feature_dimension=N_DIM, reps=1, entanglement = 'linear') pauli_kernel_3 = QuantumKernel(feature_map=pauli_map_3, quantum_instance=Aer.get_backend('statevector_simulator')) pauli_svc_3 = SVC(kernel='precomputed', probability=True) matrix_train_3 = pauli_kernel_3.evaluate(x_vec=sample_train) pauli_svc_3.fit(matrix_train_3, labels_train_3) matrix_val_3 = pauli_kernel_3.evaluate(x_vec=sample_val, y_vec=sample_train) pauli_score_3 = pauli_svc_3.score(matrix_val_3, labels_val_3) print(f'Accuracy of discriminating between label 3 and others: {pauli_score_3*100}%') matrix_test_0 = pauli_kernel_0.evaluate(x_vec=sample_test, y_vec=sample_train) pred_0 = pauli_svc_0.predict_proba(matrix_test_0)[:, 1] print(f'Probability of label 0: {np.round(pred_0, 2)}') matrix_test_2 = pauli_kernel_2.evaluate(x_vec=sample_test, y_vec=sample_train) pred_2 = pauli_svc_2.predict_proba(matrix_test_2)[:, 1] print(f'Probability of label 2: {np.round(pred_2, 2)}') matrix_test_3 = pauli_kernel_3.evaluate(x_vec=sample_test, y_vec=sample_train) pred_3 = pauli_svc_3.predict_proba(matrix_test_3)[:, 1] print(f'Probability of label 3: {np.round(pred_3, 2)}') ############################## # Provide your code here pred_2 = pauli_svc_2.predict_proba(matrix_test_2)[:, 1] ############################## ############################## # Provide your code here pred_3 = pauli_svc_3.predict_proba(matrix_test_3)[:, 1] ############################## sample_pred = np.load('./resources/ch3_part2_sub.npy') print(f'Sample prediction: {sample_pred}') pred_2_ex = np.array([0.7]) pred_3_ex = np.array([0.2]) pred_test_ex = np.where((pred_2_ex > pred_3_ex), 2, 3) print(f'Prediction: {pred_test_ex}') pred_2_ex = np.array([0.7, 0.1]) pred_3_ex = np.array([0.2, 0.6]) pred_test_ex = np.where((pred_2_ex > pred_3_ex), 2, 3) print(f'Prediction: {pred_test_ex}') ############################## # Provide your code here prob_0 = np.array(np.round(pred_0,2)) prob_2 = np.array(np.round(pred_2,2)) prob_3 = np.array(np.round(pred_3,2)) def pred(pred_0, pred_2, pred_3): prediction=[] for i in range(len(pred_0)): if pred_0[i]>pred_2[i] and pred_0[i]>pred_3[i]: prediction.append(0) elif pred_2[i]>pred_0[i] and pred_2[i]>pred_3[i]: prediction.append(2) else: prediction.append(3) return np.array(prediction) test = pred(prob_0, prob_2, prob_3) pred_test = np.array(test) print(pred_test) ############################## print(f'Sample prediction: {sample_pred}') # Check your answer and submit using the following code from qc_grader import grade_ex3c grade_ex3c(pred_test, sample_train, standard_scaler, pca, min_max_scaler, pauli_kernel_0, pauli_kernel_2, pauli_kernel_3, pauli_svc_0, pauli_svc_2, pauli_svc_3)
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- 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. """ TomographyBasis class """ from qiskit import QuantumRegister from qiskit import ClassicalRegister from qiskit import QiskitError class TomographyBasis: """ Tomography basis class. """ def __init__(self, name, measurement=None, preparation=None): # TODO: check that measurement and preparation are both tuples # (labels, circuit_fn, matrix_fn) # Also check functions have correct signature and are return valid # outputs for all specified labels self._name = name self._measurement = False self._preparation = False if measurement is not None and len(measurement) == 3: self._measurement = True self._measurement_labels = measurement[0] self._measurement_circuit = measurement[1] self._measurement_matrix = measurement[2] if preparation is not None and len(preparation) == 3: self._preparation = True self._preparation_labels = preparation[0] self._preparation_circuit = preparation[1] self._preparation_matrix = preparation[2] @property def name(self): """The name of the tomography basis.""" return self._name @property def measurement(self): """The measurement of the tomography basis.""" return self._measurement @property def preparation(self): """The preparation of the tomography basis.""" return self._preparation @property def measurement_labels(self): """The measurement labels of the tomography basis.""" if self.measurement is True: return self._measurement_labels return None @property def preparation_labels(self): """The preparation labels of the tomography basis.""" if self.preparation is True: return self._preparation_labels return None def measurement_circuit(self, op, qubit, clbit): """Return the measurement circuits.""" # Error Checking if self.measurement is False: raise QiskitError( "{} is not a measurement basis".format(self._name)) if not (isinstance(qubit, tuple) and isinstance(qubit[0], QuantumRegister)): raise QiskitError('Input must be a qubit in a QuantumRegister') if not (isinstance(clbit, tuple) and isinstance(clbit[0], ClassicalRegister)): raise QiskitError('Input must be a bit in a ClassicalRegister') if op not in self._measurement_labels: msg = "Invalid {0} measurement operator label".format(self._name) error = "'{0}' != {1}".format(op, self._measurement_labels) raise ValueError("{0}: {1}".format(msg, error)) # Return QuantumCircuit function output return self._measurement_circuit(op, qubit, clbit) def preparation_circuit(self, op, qubit): """Return the preparation circuits.""" # Error Checking if self.preparation is False: raise QiskitError("{} is not a preparation basis".format( self._name)) if not (isinstance(qubit, tuple) and isinstance(qubit[0], QuantumRegister)): raise QiskitError('Input must be a qubit in a QuantumRegister') if op not in self._preparation_labels: msg = "Invalid {0} preparation operator label".format(self._name) error = "'{}' not in {}".format(op, self._preparation_labels) raise ValueError("{0}: {1}".format(msg, error)) return self._preparation_circuit(op, qubit) def measurement_matrix(self, label, outcome): """Return the measurement matrix.""" if self.measurement is False: raise QiskitError("{} is not a measurement basis".format( self._name)) # Check input is valid for this basis if label not in self._measurement_labels: msg = "Invalid {0} measurement operator label".format(self._name) error = "'{}' not in {}".format(label, self._measurement_labels) raise ValueError("{0}: {1}".format(msg, error)) # Check outcome is valid for this measurement allowed_outcomes = [0, 1, '0', '1'] if outcome not in allowed_outcomes: error = "'{}' not in {}".format(outcome, allowed_outcomes) raise ValueError('Invalid measurement outcome: {}'.format(error)) return self._measurement_matrix(label, outcome) def preparation_matrix(self, label): """Return the preparation matrix.""" if self.preparation is False: raise QiskitError("{} is not a preparation basis".format( self._name)) # Check input is valid for this basis if label not in self._preparation_labels: msg = "Invalid {0} preparation operator label".format(self._name) error = "'{}' not in {}".format(label, self._preparation_labels) raise ValueError("{0}: {1}".format(msg, error)) return self._preparation_matrix(label)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Clifford, random_clifford qc = QuantumCircuit(3) cliff = random_clifford(2) qc.append(cliff, [0, 1]) qc.ccx(0, 1, 2) qc.draw('mpl')
https://github.com/qiskit-community/qgss-2024
qiskit-community
from qiskit import QuantumCircuit, Aer, execute import numpy as np from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt from math import gcd #QFT Circuit def qft(n): """Creates an n-qubit QFT circuit""" circuit = QuantumCircuit(n) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft_rotations(circuit, n): """Performs qft on the first n qubits in circuit (without swaps)""" if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(np.pi/2**(n-qubit), qubit, n) qft_rotations(circuit, n) qft_rotations(circuit, n) swap_registers(circuit, n) return circuit #Inverse Quantum Fourier Transform def qft_dagger(qc, n): """n-qubit QFTdagger the first n qubits in circ""" # Don't forget the Swaps! 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) qc.h(j) return qc phase_register_size = 4 qpe4 = QuantumCircuit(phase_register_size+1, phase_register_size) ### Insert your code here ## Run this cell to simulate 'qpe4' and to plot the histogram of the result sim = Aer.get_backend('aer_simulator') shots = 2000 count_qpe4 = execute(qpe4, sim, shots=shots).result().get_counts() plot_histogram(count_qpe4, figsize=(9,5)) from qc_grader.challenges.qgss_2023 import grade_lab3_ex1 grade_lab3_ex1(count_qpe4) #Grab the highest probability measurement max_binary_counts = 0 max_binary_val = '' for key, item in count_qpe4.items(): if item > max_binary_counts: max_binary_counts = item max_binary_val = key ## Your function to convert a binary string to decimal goes here estimated_phase = # calculate the estimated phase phase_accuracy_window = # highest power of 2 (i.e. smallest decimal) this circuit can estimate from qc_grader.challenges.qgss_2023 import grade_lab3_ex2 grade_lab3_ex2([estimated_phase, phase_accuracy_window]) from qiskit_ibm_provider import IBMProvider from qiskit.compiler import transpile provider = IBMProvider() hub = "YOUR_HUB" group = "YOUR_GROUP" project = "YOUR_PROJECT" backend_name = "YOUR_BACKEND" backend = provider.get_backend(backend_name, instance=f"{hub}/{group}/{project}") # your code goes here from qc_grader.challenges.qgss_2023 import grade_lab3_ex3 grade_lab3_ex3([max_depth_qpe, min_depth_qpe]) shots = 2000 #OPTIONAL: Run the minimum depth qpe circuit job_min_qpe4 = backend.run(min_depth_qpe, sim, shots=shots) print(job_min_qpe4.job_id()) #Gather the count data count_min_qpe4 = job_min_qpe4.result().get_counts() plot_histogram(count_min_qpe4, figsize=(9,5)) #OPTIONAL: Run the maximum depth qpe circuit job_max_qpe4 = backend.run(max_depth_qpe, sim, shots=shots) print(job_max_qpe4.job_id()) #Gather the count data count_max_qpe4 = job_max_qpe4.result().get_counts() plot_histogram(count_max_qpe4, figsize=(9,5)) def qpe_circuit(register_size): # Your code goes here return qpe ## Run this cell to simulate 'qpe4' and to plot the histogram of the result reg_size = # Vary the register sizes qpe_check = qpe_circuit(reg_size) sim = Aer.get_backend('aer_simulator') shots = 10000 count_qpe4 = execute(qpe_check, sim, shots=shots).result().get_counts() plot_histogram(count_qpe4, figsize=(9,5)) # Process the count data to determine accuracy of the estimated phase required_register_size = #your answer here from qc_grader.challenges.qgss_2023 import grade_lab3_ex4 grade_lab3_ex4(required_register_size) ## Create 7mod15 gate N = 15 m = int(np.ceil(np.log2(N))) U_qc = QuantumCircuit(m) U_qc.x(range(m)) U_qc.swap(1, 2) U_qc.swap(2, 3) U_qc.swap(0, 3) U = U_qc.to_gate() U.name ='{}Mod{}'.format(7, N) ### your code goes here qcirc = QuantumCircuit(m) ## Run this cell to simulate 'qpe4' and to plot the histogram of the result sim = Aer.get_backend('aer_simulator') shots = 20000 input_1 = execute(qcirc, sim, shots=shots).result().get_counts() # save the count data for input 1 input_2 = # save the count data for input 2 input_5 = # save the count data for input 5 from qc_grader.challenges.qgss_2023 import grade_lab3_ex5 grade_lab3_ex5([input_1, input_2, input_5]) unitary_circ = QuantumCircuit(m) # Your code goes here sim = Aer.get_backend('unitary_simulator') unitary = execute(unitary_circ, sim).result().get_unitary() from qc_grader.challenges.qgss_2023 import grade_lab3_ex6 grade_lab3_ex6(unitary, unitary_circ) #This function will return a ControlledGate object which repeats the action # of U, 2^k times def cU_multi(k): sys_register_size = 4 circ = QuantumCircuit(sys_register_size) for _ in range(2**k): circ.append(U, range(sys_register_size)) U_multi = circ.to_gate() U_multi.name = '7Mod15_[2^{}]'.format(k) cU_multi = U_multi.control() return cU_multi # your code goes here shor_qpe = #Create the QuantumCircuit needed to run with 8 phase register qubits ## Run this cell to simulate 'shor_qpe' and to plot the histogram of the results sim = Aer.get_backend('aer_simulator') shots = 20000 shor_qpe_counts = execute(shor_qpe, sim, shots=shots).result().get_counts() plot_histogram(shor_qpe_counts, figsize=(9,5)) from qc_grader.challenges.qgss_2023 import grade_lab3_ex7 grade_lab3_ex7(shor_qpe_counts) from fractions import Fraction print(Fraction(0.666), '\n') print(Fraction(0.666).limit_denominator(15)) shor_qpe_fractions = # create a list of Fraction objects for each measurement outcome from qc_grader.challenges.qgss_2023 import grade_lab3_ex8 grade_lab3_ex8(shor_qpe_fractions) def shor_qpe(k): a = 7 #Step 1. Begin a while loop until a nontrivial guess is found ### Your code goes here ### #Step 2a. Construct a QPE circuit with m phase count qubits # to guess the phase phi = s/r using the function cU_multi() ### Your code goes here ### #Step 2b. Run the QPE circuit with a single shot, record the results # and convert the estimated phase bitstring to decimal ### Your code goes here ### #Step 3. Use the Fraction object to find the guess for r ### Your code goes here ### #Step 4. Now that r has been found, use the builtin greatest common deonominator # function to determine the guesses for a factor of N guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)] #Step 5. For each guess in guesses, check if at least one is a non-trivial factor # i.e. (guess != 1 or N) and (N % guess == 0) ### Your code goes here ### #Step 6. If a nontrivial factor is found return the list 'guesses', otherwise # continue the while loop ### Your code goes here ### return guesses from qc_grader.challenges.qgss_2023 import grade_lab3_ex9 grade_lab3_ex9(shor_qpe)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# 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 Qiskit's gates in QASM2.""" import unittest from math import pi import re from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.circuit import Parameter, Qubit, Clbit, Gate from qiskit.circuit.library import C3SXGate, CCZGate, CSGate, CSdgGate, PermutationGate from qiskit.qasm.exceptions import QasmError # Regex pattern to match valid OpenQASM identifiers VALID_QASM2_IDENTIFIER = re.compile("[a-z][a-zA-Z_0-9]*") class TestCircuitQasm(QiskitTestCase): """QuantumCircuit QASM2 tests.""" def test_circuit_qasm(self): """Test circuit qasm() method.""" qr1 = QuantumRegister(1, "qr1") qr2 = QuantumRegister(2, "qr2") cr = ClassicalRegister(3, "cr") qc = QuantumCircuit(qr1, qr2, cr) qc.p(0.3, qr1[0]) qc.u(0.3, 0.2, 0.1, qr2[1]) qc.s(qr2[1]) qc.sdg(qr2[1]) qc.cx(qr1[0], qr2[1]) qc.barrier(qr2) qc.cx(qr2[1], qr1[0]) qc.h(qr2[1]) qc.x(qr2[1]).c_if(cr, 0) qc.y(qr1[0]).c_if(cr, 1) qc.z(qr1[0]).c_if(cr, 2) qc.barrier(qr1, qr2) qc.measure(qr1[0], cr[0]) qc.measure(qr2[0], cr[1]) qc.measure(qr2[1], cr[2]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg qr1[1]; qreg qr2[2]; creg cr[3]; p(0.3) qr1[0]; u(0.3,0.2,0.1) qr2[1]; s qr2[1]; sdg qr2[1]; cx qr1[0],qr2[1]; barrier qr2[0],qr2[1]; cx qr2[1],qr1[0]; h qr2[1]; if(cr==0) x qr2[1]; if(cr==1) y qr1[0]; if(cr==2) z qr1[0]; barrier qr1[0],qr2[0],qr2[1]; measure qr1[0] -> cr[0]; measure qr2[0] -> cr[1]; measure qr2[1] -> cr[2];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_composite_circuit(self): """Test circuit qasm() method when a composite circuit instruction is included within circuit. """ composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_instruction() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate composite_circ q0,q1 { h q0; x q1; cx q0,q1; } qreg qr[2]; creg cr[2]; h qr[0]; cx qr[0],qr[1]; barrier qr[0],qr[1]; composite_circ qr[0],qr[1]; measure qr[0] -> cr[0]; measure qr[1] -> cr[1];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_multiple_same_composite_circuits(self): """Test circuit qasm() method when a composite circuit is added to the circuit multiple times """ composite_circ_qreg = QuantumRegister(2) composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ") composite_circ.h(0) composite_circ.x(1) composite_circ.cx(0, 1) composite_circ_instr = composite_circ.to_instruction() qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") qc = QuantumCircuit(qr, cr) qc.h(0) qc.cx(0, 1) qc.barrier() qc.append(composite_circ_instr, [0, 1]) qc.append(composite_circ_instr, [0, 1]) qc.measure([0, 1], [0, 1]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate composite_circ q0,q1 { h q0; x q1; cx q0,q1; } qreg qr[2]; creg cr[2]; h qr[0]; cx qr[0],qr[1]; barrier qr[0],qr[1]; composite_circ qr[0],qr[1]; composite_circ qr[0],qr[1]; measure qr[0] -> cr[0]; measure qr[1] -> cr[1];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_multiple_composite_circuits_with_same_name(self): """Test circuit qasm() method when multiple composite circuit instructions with the same circuit name are added to the circuit """ my_gate = QuantumCircuit(1, name="my_gate") my_gate.h(0) my_gate_inst1 = my_gate.to_instruction() my_gate = QuantumCircuit(1, name="my_gate") my_gate.x(0) my_gate_inst2 = my_gate.to_instruction() my_gate = QuantumCircuit(1, name="my_gate") my_gate.x(0) my_gate_inst3 = my_gate.to_instruction() qr = QuantumRegister(1, name="qr") circuit = QuantumCircuit(qr, name="circuit") circuit.append(my_gate_inst1, [qr[0]]) circuit.append(my_gate_inst2, [qr[0]]) my_gate_inst2_id = id(circuit.data[-1].operation) circuit.append(my_gate_inst3, [qr[0]]) my_gate_inst3_id = id(circuit.data[-1].operation) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate my_gate q0 {{ h q0; }} gate my_gate_{1} q0 {{ x q0; }} gate my_gate_{0} q0 {{ x q0; }} qreg qr[1]; my_gate qr[0]; my_gate_{1} qr[0]; my_gate_{0} qr[0];\n""".format( my_gate_inst3_id, my_gate_inst2_id ) self.assertEqual(circuit.qasm(), expected_qasm) def test_circuit_qasm_with_composite_circuit_with_children_composite_circuit(self): """Test circuit qasm() method when composite circuits with children composite circuits in the definitions are added to the circuit""" child_circ = QuantumCircuit(2, name="child_circ") child_circ.h(0) child_circ.cx(0, 1) parent_circ = QuantumCircuit(3, name="parent_circ") parent_circ.append(child_circ, range(2)) parent_circ.h(2) grandparent_circ = QuantumCircuit(4, name="grandparent_circ") grandparent_circ.append(parent_circ, range(3)) grandparent_circ.x(3) qc = QuantumCircuit(4) qc.append(grandparent_circ, range(4)) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate child_circ q0,q1 { h q0; cx q0,q1; } gate parent_circ q0,q1,q2 { child_circ q0,q1; h q2; } gate grandparent_circ q0,q1,q2,q3 { parent_circ q0,q1,q2; x q3; } qreg q[4]; grandparent_circ q[0],q[1],q[2],q[3];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_pi(self): """Test circuit qasm() method with pi params.""" circuit = QuantumCircuit(2) circuit.cz(0, 1) circuit.u(2 * pi, 3 * pi, -5 * pi, 0) qasm_str = circuit.qasm() circuit2 = QuantumCircuit.from_qasm_str(qasm_str) self.assertEqual(circuit, circuit2) def test_circuit_qasm_with_composite_circuit_with_one_param(self): """Test circuit qasm() method when a composite circuit instruction has one param """ original_str = """OPENQASM 2.0; include "qelib1.inc"; gate nG0(param0) q0 { h q0; } qreg q[3]; creg c[3]; nG0(pi) q[0];\n""" qc = QuantumCircuit.from_qasm_str(original_str) self.assertEqual(original_str, qc.qasm()) def test_circuit_qasm_with_composite_circuit_with_many_params_and_qubits(self): """Test circuit qasm() method when a composite circuit instruction has many params and qubits """ original_str = """OPENQASM 2.0; include "qelib1.inc"; gate nG0(param0,param1) q0,q1 { h q0; h q1; } qreg q[3]; qreg r[3]; creg c[3]; creg d[3]; nG0(pi,pi/2) q[0],r[0];\n""" qc = QuantumCircuit.from_qasm_str(original_str) self.assertEqual(original_str, qc.qasm()) def test_c3sxgate_roundtrips(self): """Test that C3SXGate correctly round trips. Qiskit gives this gate a different name ('c3sx') to the name in Qiskit's version of qelib1.inc ('c3sqrtx') gate, which can lead to resolution issues.""" qc = QuantumCircuit(4) qc.append(C3SXGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; qreg q[4]; c3sqrtx q[0],q[1],q[2],q[3]; """ self.assertEqual(qasm, expected) parsed = QuantumCircuit.from_qasm_str(qasm) self.assertIsInstance(parsed.data[0].operation, C3SXGate) def test_c3sxgate_qasm_deprecation_warning(self): """Test deprecation warning for C3SXGate.""" with self.assertWarnsRegex(DeprecationWarning, r"Correct exporting to OpenQASM 2"): C3SXGate().qasm() def test_cczgate_qasm(self): """Test that CCZ dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(3) qc.append(CCZGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate ccz q0,q1,q2 { h q2; ccx q0,q1,q2; h q2; } qreg q[3]; ccz q[0],q[1],q[2]; """ self.assertEqual(qasm, expected) def test_csgate_qasm(self): """Test that CS dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.append(CSGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate cs q0,q1 { p(pi/4) q0; cx q0,q1; p(-pi/4) q1; cx q0,q1; p(pi/4) q1; } qreg q[2]; cs q[0],q[1]; """ self.assertEqual(qasm, expected) def test_csdggate_qasm(self): """Test that CSdg dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.append(CSdgGate(), qc.qubits, []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate csdg q0,q1 { p(-pi/4) q0; cx q0,q1; p(pi/4) q1; cx q0,q1; p(-pi/4) q1; } qreg q[2]; csdg q[0],q[1]; """ self.assertEqual(qasm, expected) def test_rzxgate_qasm(self): """Test that RZX dumps definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.rzx(0, 0, 1) qc.rzx(pi / 2, 1, 0) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate rzx(param0) q0,q1 { h q1; cx q0,q1; rz(param0) q1; cx q0,q1; h q1; } qreg q[2]; rzx(0) q[0],q[1]; rzx(pi/2) q[1],q[0]; """ self.assertEqual(qasm, expected) def test_ecrgate_qasm(self): """Test that ECR dumps its definition as a non-qelib1 gate.""" qc = QuantumCircuit(2) qc.ecr(0, 1) qc.ecr(1, 0) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate rzx(param0) q0,q1 { h q1; cx q0,q1; rz(param0) q1; cx q0,q1; h q1; } gate ecr q0,q1 { rzx(pi/4) q0,q1; x q0; rzx(-pi/4) q0,q1; } qreg q[2]; ecr q[0],q[1]; ecr q[1],q[0]; """ self.assertEqual(qasm, expected) def test_unitary_qasm(self): """Test that UnitaryGate can be dumped to OQ2 correctly.""" qc = QuantumCircuit(1) qc.unitary([[1, 0], [0, 1]], 0) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate unitary q0 { u(0,0,0) q0; } qreg q[1]; unitary q[0]; """ self.assertEqual(qasm, expected) def test_multiple_unitary_qasm(self): """Test that multiple UnitaryGate instances can all dump successfully.""" custom = QuantumCircuit(1, name="custom") custom.unitary([[1, 0], [0, -1]], 0) qc = QuantumCircuit(2) qc.unitary([[1, 0], [0, 1]], 0) qc.unitary([[0, 1], [1, 0]], 1) qc.append(custom.to_gate(), [0], []) qasm = qc.qasm() expected = re.compile( r"""OPENQASM 2.0; include "qelib1.inc"; gate unitary q0 { u\(0,0,0\) q0; } gate (?P<u1>unitary_[0-9]*) q0 { u\(pi,-pi/2,pi/2\) q0; } gate (?P<u2>unitary_[0-9]*) q0 { u\(0,pi/2,pi/2\) q0; } gate custom q0 { (?P=u2) q0; } qreg q\[2\]; unitary q\[0\]; (?P=u1) q\[1\]; custom q\[0\]; """, re.MULTILINE, ) self.assertRegex(qasm, expected) def test_unbound_circuit_raises(self): """Test circuits with unbound parameters raises.""" qc = QuantumCircuit(1) theta = Parameter("θ") qc.rz(theta, 0) with self.assertRaises(QasmError): qc.qasm() def test_gate_qasm_with_ctrl_state(self): """Test gate qasm() with controlled gate that has ctrl_state setting.""" from qiskit.quantum_info import Operator qc = QuantumCircuit(2) qc.ch(0, 1, ctrl_state=0) qasm_str = qc.qasm() self.assertEqual(Operator(qc), Operator(QuantumCircuit.from_qasm_str(qasm_str))) def test_circuit_qasm_with_mcx_gate(self): """Test circuit qasm() method with MCXGate See https://github.com/Qiskit/qiskit-terra/issues/4943 """ qc = QuantumCircuit(4) qc.mcx([0, 1, 2], 3) # qasm output doesn't support parameterized gate yet. # param0 for "gate mcuq(param0) is not used inside the definition expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate mcx q0,q1,q2,q3 { h q3; p(pi/8) q0; p(pi/8) q1; p(pi/8) q2; p(pi/8) q3; cx q0,q1; p(-pi/8) q1; cx q0,q1; cx q1,q2; p(-pi/8) q2; cx q0,q2; p(pi/8) q2; cx q1,q2; p(-pi/8) q2; cx q0,q2; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; h q3; } qreg q[4]; mcx q[0],q[1],q[2],q[3];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_mcx_gate_variants(self): """Test circuit qasm() method with MCXGrayCode, MCXRecursive, MCXVChain""" import qiskit.circuit.library as cl n = 5 qc = QuantumCircuit(2 * n - 1) qc.append(cl.MCXGrayCode(n), range(n + 1)) qc.append(cl.MCXRecursive(n), range(n + 2)) qc.append(cl.MCXVChain(n), range(2 * n - 1)) # qasm output doesn't support parameterized gate yet. # param0 for "gate mcuq(param0) is not used inside the definition expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate mcu1(param0) q0,q1,q2,q3,q4,q5 { cu1(pi/16) q4,q5; cx q4,q3; cu1(-pi/16) q3,q5; cx q4,q3; cu1(pi/16) q3,q5; cx q3,q2; cu1(-pi/16) q2,q5; cx q4,q2; cu1(pi/16) q2,q5; cx q3,q2; cu1(-pi/16) q2,q5; cx q4,q2; cu1(pi/16) q2,q5; cx q2,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q3,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q2,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q3,q1; cu1(-pi/16) q1,q5; cx q4,q1; cu1(pi/16) q1,q5; cx q1,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q2,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q1,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q2,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; cx q3,q0; cu1(-pi/16) q0,q5; cx q4,q0; cu1(pi/16) q0,q5; } gate mcx_gray q0,q1,q2,q3,q4,q5 { h q5; mcu1(pi) q0,q1,q2,q3,q4,q5; h q5; } gate mcx q0,q1,q2,q3 { h q3; p(pi/8) q0; p(pi/8) q1; p(pi/8) q2; p(pi/8) q3; cx q0,q1; p(-pi/8) q1; cx q0,q1; cx q1,q2; p(-pi/8) q2; cx q0,q2; p(pi/8) q2; cx q1,q2; p(-pi/8) q2; cx q0,q2; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q1,q3; p(pi/8) q3; cx q2,q3; p(-pi/8) q3; cx q0,q3; h q3; } gate mcx_recursive q0,q1,q2,q3,q4,q5,q6 { mcx q0,q1,q2,q6; mcx q3,q4,q6,q5; mcx q0,q1,q2,q6; mcx q3,q4,q6,q5; } gate mcx_vchain q0,q1,q2,q3,q4,q5,q6,q7,q8 { rccx q0,q1,q6; rccx q2,q6,q7; rccx q3,q7,q8; ccx q4,q8,q5; rccx q3,q7,q8; rccx q2,q6,q7; rccx q0,q1,q6; } qreg q[9]; mcx_gray q[0],q[1],q[2],q[3],q[4],q[5]; mcx_recursive q[0],q[1],q[2],q[3],q[4],q[5],q[6]; mcx_vchain q[0],q[1],q[2],q[3],q[4],q[5],q[6],q[7],q[8];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_registerless_bits(self): """Test that registerless bits do not have naming collisions in their registers.""" initial_registers = [QuantumRegister(2), ClassicalRegister(2)] qc = QuantumCircuit(*initial_registers, [Qubit(), Clbit()]) # Match a 'qreg identifier[3];'-like QASM register declaration. register_regex = re.compile(r"\s*[cq]reg\s+(\w+)\s*\[\d+\]\s*", re.M) qasm_register_names = set() for statement in qc.qasm().split(";"): match = register_regex.match(statement) if match: qasm_register_names.add(match.group(1)) self.assertEqual(len(qasm_register_names), 4) # Check that no additional registers were added to the circuit. self.assertEqual(len(qc.qregs), 1) self.assertEqual(len(qc.cregs), 1) # Check that the registerless-register names are recalculated after adding more registers, # to avoid naming clashes in this case. generated_names = qasm_register_names - {register.name for register in initial_registers} for generated_name in generated_names: qc.add_register(QuantumRegister(1, name=generated_name)) qasm_register_names = set() for statement in qc.qasm().split(";"): match = register_regex.match(statement) if match: qasm_register_names.add(match.group(1)) self.assertEqual(len(qasm_register_names), 6) def test_circuit_qasm_with_repeated_instruction_names(self): """Test that qasm() doesn't change the name of the instructions that live in circuit.data, but a copy of them when there are repeated names.""" qc = QuantumCircuit(2) qc.h(0) qc.x(1) # Create some random custom gate and name it "custom" custom = QuantumCircuit(1) custom.h(0) custom.y(0) gate = custom.to_gate() gate.name = "custom" # Another random custom gate named "custom" as well custom2 = QuantumCircuit(2) custom2.x(0) custom2.z(1) gate2 = custom2.to_gate() gate2.name = "custom" # Append custom gates with same name to original circuit qc.append(gate, [0]) qc.append(gate2, [1, 0]) # Expected qasm string will append the id to the second gate with repeated name expected_qasm = f"""OPENQASM 2.0; include "qelib1.inc"; gate custom q0 {{ h q0; y q0; }} gate custom_{id(gate2)} q0,q1 {{ x q0; z q1; }} qreg q[2]; h q[0]; x q[1]; custom q[0]; custom_{id(gate2)} q[1],q[0];\n""" # Check qasm() produced the correct string self.assertEqual(expected_qasm, qc.qasm()) # Check instruction names were not changed by qasm() names = ["h", "x", "custom", "custom"] for idx, instruction in enumerate(qc._data): self.assertEqual(instruction.operation.name, names[idx]) def test_circuit_qasm_with_invalid_identifiers(self): """Test that qasm() detects and corrects invalid OpenQASM gate identifiers, while not changing the instructions on the original circuit""" qc = QuantumCircuit(2) # Create some gate and give it an invalid name custom = QuantumCircuit(1) custom.x(0) custom.u(0, 0, pi, 0) gate = custom.to_gate() gate.name = "A[$]" # Another gate also with invalid name custom2 = QuantumCircuit(2) custom2.x(0) custom2.append(gate, [1]) gate2 = custom2.to_gate() gate2.name = "invalid[name]" # Append gates qc.append(gate, [0]) qc.append(gate2, [1, 0]) # Expected qasm with valid identifiers expected_qasm = "\n".join( [ "OPENQASM 2.0;", 'include "qelib1.inc";', "gate gate_A___ q0 { x q0; u(0,0,pi) q0; }", "gate invalid_name_ q0,q1 { x q0; gate_A___ q1; }", "qreg q[2];", "gate_A___ q[0];", "invalid_name_ q[1],q[0];", "", ] ) # Check qasm() produces the correct string self.assertEqual(expected_qasm, qc.qasm()) # Check instruction names were not changed by qasm() names = ["A[$]", "invalid[name]"] for idx, instruction in enumerate(qc._data): self.assertEqual(instruction.operation.name, names[idx]) def test_circuit_qasm_with_duplicate_invalid_identifiers(self): """Test that qasm() corrects invalid identifiers and the de-duplication code runs correctly, without altering original instructions""" base = QuantumCircuit(1) # First gate with invalid name, escapes to "invalid__" clash1 = QuantumCircuit(1, name="invalid??") clash1.x(0) base.append(clash1, [0]) # Second gate with invalid name that also escapes to "invalid__" clash2 = QuantumCircuit(1, name="invalid[]") clash2.z(0) base.append(clash2, [0]) # Check qasm is correctly produced names = set() for match in re.findall(r"gate (\S+)", base.qasm()): self.assertTrue(VALID_QASM2_IDENTIFIER.fullmatch(match)) names.add(match) self.assertEqual(len(names), 2) # Check instruction names were not changed by qasm() names = ["invalid??", "invalid[]"] for idx, instruction in enumerate(base._data): self.assertEqual(instruction.operation.name, names[idx]) def test_circuit_qasm_escapes_register_names(self): """Test that registers that have invalid OpenQASM 2 names get correctly escaped, even when they would escape to the same value.""" qc = QuantumCircuit(QuantumRegister(2, "?invalid"), QuantumRegister(2, "!invalid")) qc.cx(0, 1) qc.cx(2, 3) qasm = qc.qasm() match = re.fullmatch( rf"""OPENQASM 2.0; include "qelib1.inc"; qreg ({VALID_QASM2_IDENTIFIER.pattern})\[2\]; qreg ({VALID_QASM2_IDENTIFIER.pattern})\[2\]; cx \1\[0\],\1\[1\]; cx \2\[0\],\2\[1\]; """, qasm, ) self.assertTrue(match) self.assertNotEqual(match.group(1), match.group(2)) def test_circuit_qasm_escapes_reserved(self): """Test that the OpenQASM 2 exporter won't export reserved names.""" qc = QuantumCircuit(QuantumRegister(1, "qreg")) gate = Gate("gate", 1, []) gate.definition = QuantumCircuit(1) qc.append(gate, [qc.qubits[0]]) qasm = qc.qasm() match = re.fullmatch( rf"""OPENQASM 2.0; include "qelib1.inc"; gate ({VALID_QASM2_IDENTIFIER.pattern}) q0 {{ }} qreg ({VALID_QASM2_IDENTIFIER.pattern})\[1\]; \1 \2\[0\]; """, qasm, ) self.assertTrue(match) self.assertNotEqual(match.group(1), "gate") self.assertNotEqual(match.group(1), "qreg") def test_circuit_qasm_with_double_precision_rotation_angle(self): """Test that qasm() emits high precision rotation angles per default.""" from qiskit.circuit.tools.pi_check import MAX_FRAC qc = QuantumCircuit(1) qc.p(0.123456789, 0) qc.p(pi * pi, 0) qc.p(MAX_FRAC * pi + 1, 0) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; p(0.123456789) q[0]; p(9.869604401089358) q[0]; p(51.26548245743669) q[0];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_qasm_with_rotation_angles_close_to_pi(self): """Test that qasm() properly rounds values closer than 1e-12 to pi.""" qc = QuantumCircuit(1) qc.p(pi + 1e-11, 0) qc.p(pi + 1e-12, 0) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; p(3.141592653599793) q[0]; p(pi) q[0];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_circuit_raises_on_single_bit_condition(self): """OpenQASM 2 can't represent single-bit conditions, so test that a suitable error is printed if this is attempted.""" qc = QuantumCircuit(1, 1) qc.x(0).c_if(0, True) with self.assertRaisesRegex(QasmError, "OpenQASM 2 can only condition on registers"): qc.qasm() def test_circuit_raises_invalid_custom_gate_no_qubits(self): """OpenQASM 2 exporter of custom gates with no qubits. See: https://github.com/Qiskit/qiskit-terra/issues/10435""" legit_circuit = QuantumCircuit(5, name="legit_circuit") empty_circuit = QuantumCircuit(name="empty_circuit") legit_circuit.append(empty_circuit) with self.assertRaisesRegex(QasmError, "acts on zero qubits"): legit_circuit.qasm() def test_circuit_raises_invalid_custom_gate_clbits(self): """OpenQASM 2 exporter of custom instruction. See: https://github.com/Qiskit/qiskit-terra/issues/7351""" instruction = QuantumCircuit(2, 2, name="inst") instruction.cx(0, 1) instruction.measure([0, 1], [0, 1]) custom_instruction = instruction.to_instruction() qc = QuantumCircuit(2, 2) qc.append(custom_instruction, [0, 1], [0, 1]) with self.assertRaisesRegex(QasmError, "acts on 2 classical bits"): qc.qasm() def test_circuit_qasm_with_permutations(self): """Test circuit qasm() method with Permutation gates.""" qc = QuantumCircuit(4) qc.append(PermutationGate([2, 1, 0]), [0, 1, 2]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate permutation__2_1_0_ q0,q1,q2 { swap q0,q2; } qreg q[4]; permutation__2_1_0_ q[0],q[1],q[2];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_multiple_permutation(self): """Test that multiple PermutationGates can be added to a circuit.""" custom = QuantumCircuit(3, name="custom") custom.append(PermutationGate([2, 1, 0]), [0, 1, 2]) custom.append(PermutationGate([0, 1, 2]), [0, 1, 2]) qc = QuantumCircuit(4) qc.append(PermutationGate([2, 1, 0]), [0, 1, 2], []) qc.append(PermutationGate([1, 2, 0]), [0, 1, 2], []) qc.append(custom.to_gate(), [1, 3, 2], []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; gate permutation__2_1_0_ q0,q1,q2 { swap q0,q2; } gate permutation__1_2_0_ q0,q1,q2 { swap q1,q2; swap q0,q2; } gate permutation__0_1_2_ q0,q1,q2 { } gate custom q0,q1,q2 { permutation__2_1_0_ q0,q1,q2; permutation__0_1_2_ q0,q1,q2; } qreg q[4]; permutation__2_1_0_ q[0],q[1],q[2]; permutation__1_2_0_ q[0],q[1],q[2]; custom q[1],q[3],q[2]; """ self.assertEqual(qasm, expected) def test_circuit_qasm_with_reset(self): """Test circuit qasm() method with Reset.""" qc = QuantumCircuit(2) qc.reset([0, 1]) expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; reset q[0]; reset q[1];\n""" self.assertEqual(qc.qasm(), expected_qasm) def test_nested_gate_naming_clashes(self): """Test that gates that have naming clashes but only appear in the body of another gate still get exported correctly.""" # pylint: disable=missing-class-docstring class Inner(Gate): def __init__(self, param): super().__init__("inner", 1, [param]) def _define(self): self._definition = QuantumCircuit(1) self._definition.rx(self.params[0], 0) class Outer(Gate): def __init__(self, param): super().__init__("outer", 1, [param]) def _define(self): self._definition = QuantumCircuit(1) self._definition.append(Inner(self.params[0]), [0], []) qc = QuantumCircuit(1) qc.append(Outer(1.0), [0], []) qc.append(Outer(2.0), [0], []) qasm = qc.qasm() expected = re.compile( r"""OPENQASM 2\.0; include "qelib1\.inc"; gate inner\(param0\) q0 { rx\(1\.0\) q0; } gate outer\(param0\) q0 { inner\(1\.0\) q0; } gate (?P<inner1>inner_[0-9]*)\(param0\) q0 { rx\(2\.0\) q0; } gate (?P<outer1>outer_[0-9]*)\(param0\) q0 { (?P=inner1)\(2\.0\) q0; } qreg q\[1\]; outer\(1\.0\) q\[0\]; (?P=outer1)\(2\.0\) q\[0\]; """, re.MULTILINE, ) self.assertRegex(qasm, expected) def test_opaque_output(self): """Test that gates with no definition are exported as `opaque`.""" custom = QuantumCircuit(1, name="custom") custom.append(Gate("my_c", 1, []), [0]) qc = QuantumCircuit(2) qc.append(Gate("my_a", 1, []), [0]) qc.append(Gate("my_a", 1, []), [1]) qc.append(Gate("my_b", 2, [1.0]), [1, 0]) qc.append(custom.to_gate(), [0], []) qasm = qc.qasm() expected = """OPENQASM 2.0; include "qelib1.inc"; opaque my_a q0; opaque my_b(param0) q0,q1; opaque my_c q0; gate custom q0 { my_c q0; } qreg q[2]; my_a q[0]; my_a q[1]; my_b(1.0) q[1],q[0]; custom q[0]; """ self.assertEqual(qasm, expected) def test_sequencial_inner_gates_with_same_name(self): """Test if inner gates sequentially added with the same name result in the correct qasm""" qubits_range = range(3) gate_a = QuantumCircuit(3, name="a") gate_a.h(qubits_range) gate_a = gate_a.to_instruction() gate_b = QuantumCircuit(3, name="a") gate_b.append(gate_a, qubits_range) gate_b.x(qubits_range) gate_b = gate_b.to_instruction() qc = QuantumCircuit(3) qc.append(gate_b, qubits_range) qc.z(qubits_range) gate_a_id = id(qc.data[0].operation) expected_output = f"""OPENQASM 2.0; include "qelib1.inc"; gate a q0,q1,q2 {{ h q0; h q1; h q2; }} gate a_{gate_a_id} q0,q1,q2 {{ a q0,q1,q2; x q0; x q1; x q2; }} qreg q[3]; a_{gate_a_id} q[0],q[1],q[2]; z q[0]; z q[1]; z q[2]; """ self.assertEqual(qc.qasm(), expected_output) def test_empty_barrier(self): """Test that a blank barrier statement in _Qiskit_ acts over all qubits, while an explicitly no-op barrier (assuming Qiskit continues to allow this) is not output to OQ2 at all, since the statement requires an argument in the spec.""" qc = QuantumCircuit(QuantumRegister(2, "qr1"), QuantumRegister(3, "qr2")) qc.barrier() # In Qiskit land, this affects _all_ qubits. qc.barrier([]) # This explicitly affects _no_ qubits (so is totally meaningless). expected = """\ OPENQASM 2.0; include "qelib1.inc"; qreg qr1[2]; qreg qr2[3]; barrier qr1[0],qr1[1],qr2[0],qr2[1],qr2[2]; """ self.assertEqual(qc.qasm(), expected) def test_small_angle_valid(self): """Test that small angles do not get converted to invalid OQ2 floating-point values.""" # OQ2 _technically_ requires a decimal point in all floating-point values, even ones that # are followed by an exponent. qc = QuantumCircuit(1) qc.rx(0.000001, 0) expected = """\ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; rx(1.e-06) q[0]; """ self.assertEqual(qc.qasm(), expected) if __name__ == "__main__": unittest.main()
https://github.com/Cryoris/surfer
Cryoris
import numpy as np from time import time from qiskit import IBMQ from qiskit.circuit import QuantumCircuit, ParameterVector from qiskit.circuit.library import EfficientSU2 from qiskit.opflow import QFI, StateFn from surfer.qfi import OverlapQFI num_qubits = [10] reps = 1 runs = 1 backend = provider.get_backend(backend_name) coupling_map = backend.configuration().coupling_map num_qubits = backend.configuration().num_qubits ansatz = EfficientSU2(hamiltonian.num_qubits, reps=1, entanglement=coupling_map) return hamiltonian, ansatz def run_single(num_qubits, reps): circuit = EfficientSU2(num_qubits, reps=reps, entanglement="pairwise") values = np.zeros(circuit.num_parameters) start = time() qfi = OverlapQFI(clifford=True).compute(circuit, values) return time() - start times = [] times_std = [] for n in num_qubits: results = [run_single(n, reps) for _ in range(runs)] times.append(np.mean(results)) times_std.append(np.std(results)) print(f"{n} qubits took {times[-1]}s +- {times_std[-1]}") # np.save("cliffsimv2_su2r4.npy", np.vstack((num_qubits, times, times_std)))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) qc.h(q) qc.measure(q, c) qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
PabloMartinezAngerosa
import numpy as np import networkx as nx import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble from qiskit.quantum_info import Statevector from qiskit.aqua.algorithms import NumPyEigensolver from qiskit.quantum_info import Pauli from qiskit.aqua.operators import op_converter from qiskit.aqua.operators import WeightedPauliOperator from qiskit.visualization import plot_histogram from qiskit.providers.aer.extensions.snapshot_statevector import * from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost from utils import mapeo_grafo from collections import defaultdict from operator import itemgetter from scipy.optimize import minimize import matplotlib.pyplot as plt LAMBDA = 10 SEED = 10 SHOTS = 10000 # returns the bit index for an alpha and j def bit(i_city, l_time, num_cities): return i_city * num_cities + l_time # e^(cZZ) def append_zz_term(qc, q_i, q_j, gamma, constant_term): qc.cx(q_i, q_j) qc.rz(2*gamma*constant_term,q_j) qc.cx(q_i, q_j) # e^(cZ) def append_z_term(qc, q_i, gamma, constant_term): qc.rz(2*gamma*constant_term, q_i) # e^(cX) def append_x_term(qc,qi,beta): qc.rx(-2*beta, qi) def get_not_edge_in(G): N = G.number_of_nodes() not_edge = [] for i in range(N): for j in range(N): if i != j: buffer_tupla = (i,j) in_edges = False for edge_i, edge_j in G.edges(): if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)): in_edges = True if in_edges == False: not_edge.append((i, j)) return not_edge def get_classical_simplified_z_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # z term # z_classic_term = [0] * N**2 # first term for l in range(N): for i in range(N): z_il_index = bit(i, l, N) z_classic_term[z_il_index] += -1 * _lambda # second term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_jl z_jl_index = bit(j, l, N) z_classic_term[z_jl_index] += _lambda / 2 # third term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 2 # z_ij z_ij_index = bit(i, j, N) z_classic_term[z_ij_index] += _lambda / 2 # fourth term not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) z_classic_term[z_il_index] += _lambda / 4 # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) z_classic_term[z_jlplus_index] += _lambda / 4 # fifthy term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) z_classic_term[z_il_index] += weight_ij / 4 # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) z_classic_term[z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) z_classic_term[z_il_index] += weight_ji / 4 # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) z_classic_term[z_jlplus_index] += weight_ji / 4 return z_classic_term def tsp_obj_2(x, G,_lambda): # obtenemos el valor evaluado en f(x_1, x_2,... x_n) not_edge = get_not_edge_in(G) N = G.number_of_nodes() tsp_cost=0 #Distancia weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # x_il x_il_index = bit(edge_i, l, N) # x_jlplus l_plus = (l+1) % N x_jlplus_index = bit(edge_j, l_plus, N) tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij # add order term because G.edges() do not include order tuples # # x_i'l x_il_index = bit(edge_j, l, N) # x_j'lplus x_jlplus_index = bit(edge_i, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji #Constraint 1 for l in range(N): penal1 = 1 for i in range(N): x_il_index = bit(i, l, N) penal1 -= int(x[x_il_index]) tsp_cost += _lambda * penal1**2 #Contstraint 2 for i in range(N): penal2 = 1 for l in range(N): x_il_index = bit(i, l, N) penal2 -= int(x[x_il_index]) tsp_cost += _lambda*penal2**2 #Constraint 3 for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # x_il x_il_index = bit(i, l, N) # x_j(l+1) l_plus = (l+1) % N x_jlplus_index = bit(j, l_plus, N) tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda return tsp_cost def get_classical_simplified_zz_term(G, _lambda): # recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos N = G.number_of_nodes() E = G.edges() # zz term # zz_classic_term = [[0] * N**2 for i in range(N**2) ] # first term for l in range(N): for j in range(N): for i in range(N): if i < j: # z_il z_il_index = bit(i, l, N) # z_jl z_jl_index = bit(j, l, N) zz_classic_term[z_il_index][z_jl_index] += _lambda / 2 # second term for i in range(N): for l in range(N): for j in range(N): if l < j: # z_il z_il_index = bit(i, l, N) # z_ij z_ij_index = bit(i, j, N) zz_classic_term[z_il_index][z_ij_index] += _lambda / 2 # third term not_edge = get_not_edge_in(G) for edge in not_edge: for l in range(N): i = edge[0] j = edge[1] # z_il z_il_index = bit(i, l, N) # z_j(l+1) l_plus = (l+1) % N z_jlplus_index = bit(j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4 # fourth term weights = nx.get_edge_attributes(G,'weight') for edge_i, edge_j in G.edges(): weight_ij = weights.get((edge_i,edge_j)) weight_ji = weight_ij for l in range(N): # z_il z_il_index = bit(edge_i, l, N) # z_jlplus l_plus = (l+1) % N z_jlplus_index = bit(edge_j, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4 # add order term because G.edges() do not include order tuples # # z_i'l z_il_index = bit(edge_j, l, N) # z_j'lplus l_plus = (l+1) % N z_jlplus_index = bit(edge_i, l_plus, N) zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4 return zz_classic_term def get_classical_simplified_hamiltonian(G, _lambda): # z term # z_classic_term = get_classical_simplified_z_term(G, _lambda) # zz term # zz_classic_term = get_classical_simplified_zz_term(G, _lambda) return z_classic_term, zz_classic_term def get_cost_circuit(G, gamma, _lambda): N = G.number_of_nodes() N_square = N**2 qc = QuantumCircuit(N_square,N_square) z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda) # z term for i in range(N_square): if z_classic_term[i] != 0: append_z_term(qc, i, gamma, z_classic_term[i]) # zz term for i in range(N_square): for j in range(N_square): if zz_classic_term[i][j] != 0: append_zz_term(qc, i, j, gamma, zz_classic_term[i][j]) return qc def get_mixer_operator(G,beta): N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) for n in range(N**2): append_x_term(qc, n, beta) return qc def get_QAOA_circuit(G, beta, gamma, _lambda): assert(len(beta)==len(gamma)) N = G.number_of_nodes() qc = QuantumCircuit(N**2,N**2) # init min mix state qc.h(range(N**2)) p = len(beta) for i in range(p): qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda)) qc = qc.compose(get_mixer_operator(G, beta[i])) qc.barrier(range(N**2)) qc.snapshot_statevector("final_state") qc.measure(range(N**2),range(N**2)) return qc def invert_counts(counts): return {k[::-1] :v for k,v in counts.items()} # Sample expectation value def compute_tsp_energy_2(counts, G): energy = 0 get_counts = 0 total_counts = 0 for meas, meas_count in counts.items(): obj_for_meas = tsp_obj_2(meas, G, LAMBDA) energy += obj_for_meas*meas_count total_counts += meas_count mean = energy/total_counts return mean def get_black_box_objective_2(G,p): backend = Aer.get_backend('qasm_simulator') sim = Aer.get_backend('aer_simulator') # function f costo def f(theta): beta = theta[:p] gamma = theta[p:] # Anzats qc = get_QAOA_circuit(G, beta, gamma, LAMBDA) result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result() final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0] state_vector = Statevector(final_state_vector) probabilities = state_vector.probabilities() probabilities_states = invert_counts(state_vector.probabilities_dict()) expected_value = 0 for state,probability in probabilities_states.items(): cost = tsp_obj_2(state, G, LAMBDA) expected_value += cost*probability counts = result.get_counts() mean = compute_tsp_energy_2(invert_counts(counts),G) return mean return f def crear_grafo(cantidad_ciudades): pesos, conexiones = None, None mejor_camino = None while not mejor_camino: pesos, conexiones = rand_graph(cantidad_ciudades) mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False) G = mapeo_grafo(conexiones, pesos) return G, mejor_costo, mejor_camino def run_QAOA(p,ciudades, grafo): if grafo == None: G, mejor_costo, mejor_camino = crear_grafo(ciudades) print("Mejor Costo") print(mejor_costo) print("Mejor Camino") print(mejor_camino) print("Bordes del grafo") print(G.edges()) print("Nodos") print(G.nodes()) print("Pesos") labels = nx.get_edge_attributes(G,'weight') print(labels) else: G = grafo intial_random = [] # beta, mixer Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,np.pi)) # gamma, cost Hammiltonian for i in range(p): intial_random.append(np.random.uniform(0,2*np.pi)) init_point = np.array(intial_random) obj = get_black_box_objective_2(G,p) res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True}) print(res_sample) if __name__ == '__main__': # Run QAOA parametros: profundidad p, numero d ciudades, run_QAOA(5, 3, None)
https://github.com/acfilok96/Quantum-Computation
acfilok96
import qiskit from qiskit import * print(qiskit.__version__) %matplotlib inline from qiskit.tools.visualization import plot_histogram circuit = QuantumCircuit(3,3) circuit # qiskit.__dir__() circuit.draw(output='mpl') circuit.x(0) circuit.barrier() circuit.draw(output='mpl') circuit.h(1) circuit.cx(1,2) circuit.draw(output='mpl') circuit.barrier() circuit.cx(0,1) circuit.h(0) circuit.draw(output='mpl') circuit.barrier() circuit.measure([0,1],[0,1]) circuit.draw(output='mpl') circuit.barrier() circuit.cx(1,2) circuit.cx(0,2) circuit.draw(output='mpl') simulator = Aer.get_backend('qasm_simulator') job = execute(circuit, backend=simulator,shots=1024) result = job.result() counts=result.get_counts() print(counts) plot_histogram(counts)
https://github.com/khaledalam/QuantumComputingAndPrimesAndOthers
khaledalam
# Author: Khaled Alam(khaledalam.net@gmail.com) ''' Guess binary string (secret) of length N in 1 shot only using quantum computing circuit! ~ by using clasical computers we need at least N shots to guess string (secret) of length N ~ by using quantum computer we need 1 shot to guess string (secret) of ANY length ( cool isn't it! ^^ ) ''' secret = '01000001' # `01000001` = `A` from qiskit import * n = len(secret) qCircuit = QuantumCircuit(n+1, n) # n+1 qubits and n classical bits qCircuit.x(n) qCircuit.barrier() qCircuit.h(range(n+1)) qCircuit.barrier() for ii, OZ in enumerate(reversed(secret)): if OZ == '1': qCircuit.cx(ii, n) qCircuit.barrier() qCircuit.h(range(n+1)) qCircuit.barrier() qCircuit.measure(range(n), range(n)) %matplotlib inline qCircuit.draw(output='mpl') # run on simulator simulator = Aer.get_backend('qasm_simulator') result = execute(qCircuit, backend=simulator, shots=1).result() # only 1 shot from qiskit.visualization import plot_histogram plot_histogram( result.get_counts(qCircuit) )
https://github.com/Manish-Sudhir/QiskitCheck
Manish-Sudhir
from qiskit import Aer, IBMQ, transpile from qiskit.providers.ibmq import least_busy import numpy as np import pandas as pd """ INPUTS: a string that specifies the backend to select, and a QuantumCircuit, used for checking requirements for IBMQ OUTPUTS: a backend to run QuantumCircuits with """ def select_backend(backend, qc): if backend.lower() == "ibmq": if IBMQ.active_account() == None: IBMQ.load_account() provider = IBMQ.get_provider(hub="ibm-q") available_backends = provider.backends(filters=lambda x: x.configuration().n_qubits >= len(qc.qubits) and \ not x.configuration().selectedBackendulator and x.status().operational==True) if len(available_backends) == 0: raise Exception("No suitable quantum backend found") return least_busy(available_backends) else: return Aer.get_backend(backend) def measureX(qc, qubit, classicalBit): qc.h(qubit) qc.measure(qubit, classicalBit) return qc def measureY(qc, qubit, classicalBit): qc.sdg(qubit) qc.h(qubit) qc.measure(qubit, classicalBit) return qc class TestExecutor: """ INPUTS: - qc: QuantumCircuit to run the tests - noOfExperiments: number of times the the qc will be run - noOfMeasurements: number of times the qc will be measured after each run - qubit0: the first qubit to compare - qubit1: the second qubit to comapre - classicalBit0: the bit where the first qubit will be measured in - classicalBit1: the bit where the second qubit will be measured in - basis: the basis of the measurement - backend: the backend used to run the tests OUTPUT: the data of the execution of the tests, meaning a tuple of two numpy arrays, one for each qubit. Each numpy array contains a list of probabilities (float between 0 and 1) that the qubit was measured in state |0> during one trial Each trial is measured as many times as noOfMeasurements specifies """ def runTestAssertEqual(self, qc, noOfExperiments, noOfMeasurements, qubit0, qubit1, classicalBit0, classicalBit1, basis, backend): selectedBackend = select_backend(backend, qc) if basis.lower() == "x": measureX(qc, qubit0, classicalBit0) measureX(qc, qubit1, classicalBit1) elif basis.lower() == "y": measureY(qc, qubit0, classicalBit0) measureY(qc, qubit1, classicalBit1) else: qc.measure(qubit0, classicalBit0) qc.measure(qubit1, classicalBit1) qc_trans = transpile(qc, backend=selectedBackend) trialProbas0 = np.empty(noOfExperiments) trialProbas1 = np.empty(noOfExperiments) for trialIndex in range(noOfExperiments): result = selectedBackend.run(qc_trans, shots=noOfMeasurements).result() counts = result.get_counts() nb0s_qubit0 = 0 nb0s_qubit1 = 0 for elem in counts: if elem[::-1][classicalBit0] == '0': nb0s_qubit0 += counts[elem] if elem[::-1][classicalBit1] == '0': nb0s_qubit1 += counts[elem] trialProbas0[trialIndex] = nb0s_qubit0 / noOfMeasurements trialProbas1[trialIndex] = nb0s_qubit1 / noOfMeasurements return (trialProbas0, trialProbas1) """ INPUTS: same as runTestAssertEqual except the first one, which is a list of QuantumCircuit instead of just one OUTPUT: a list of the results of runTestsAssertEqual for each test """ def runTestsAssertEqual(self, initialisedTests, noOfExperiments, noOfMeasurements, qubit0, qubit1, classicalBit0, classicalBit1, basis, backend): return [self.runTestAssertEqual(qc, noOfExperiments, noOfMeasurements, qubit0, qubit1, classicalBit0, classicalBit1, basis, backend) for qc in initialisedTests] """ INPUTS: - qc: QuantumCircuit to run the tests - noOfExperiments: number of times the the qc will be run - noOfMeasurements: number of times the qc will be measured after each run - qubit0: the first qubit to compare - qubit1: the second qubit to comapre - classicalBit0: the bit where the first qubit will be measured in - classicalBit1: the bit where the second qubit will be measured in - basis: the basis of the measurement - backend: the backend used to run the tests OUTPUT: - the data of the execution of the tests, which is a list of statevectors (aka lists) """ #Return for each test the recreated "statevector" of 2 bits def runTestAssertEntangled(self, qc, noOfExperiments, noOfMeasurements, qubit0, qubit1, classicalBit0, classicalBit1, basis, backend): selectedBackend = select_backend(backend, qc) if basis.lower() == "x": measureX(qc, qubit0, classicalBit0) measureX(qc, qubit1, classicalBit1) elif basis.lower() == "y": measureY(qc, qubit0, classicalBit0) measureY(qc, qubit1, classicalBit1) else: qc.measure(qubit0, classicalBit0) qc.measure(qubit1, classicalBit1) q1=[] q2=[] job = execute(qc, selectedBackend, shots=noOfMeasurements, memory=True) memory = job.result().get_memory() qubitDict = dict.fromkeys(['qubit0','qubit1']) qubitDict = {'qubit0': qubit0,'qubit1':qubit1} # print("new dict", qubitDict) classicalQubitIndex = 1 for i in range (noOfExperiments): for qubit in qubitDict.keys(): # print("this qubit:",qubit) for measurement in memory: # print("this measurement", measurement) if (measurement[2-classicalQubitIndex] == '0'): # print("measure: ",measurement[2-classicalQubitIndex],"also: qubittoassert0",qubitList[0],"and qubittoassert1: ",qubitList[1]) if(qubit=='qubit0'): q1.append(measurement[2-classicalQubitIndex]) # print("Added to q1 for measure0:", measurement[2-classicalQubitIndex]) else: q2.append(measurement[2-classicalQubitIndex]) # print("Added to q2 for measure0:", measurement[2-classicalQubitIndex]) else: # print("measureOTHER: ",measurement[2-classicalQubitIndex], "also: qubittoassert0",qubitList[0],"and qubittoassert1: ",qubitList[1]) if(qubit=='qubit0'): q1.append(measurement[2-classicalQubitIndex]) # print("Added to q1 for measure1:", measurement[2-classicalQubitIndex]) else: q2.append(measurement[2-classicalQubitIndex]) # print("Added to q2 for measure1:", measurement[2-classicalQubitIndex]) classicalQubitIndex+=1 measDict = dict.fromkeys(['qubit1','qubit2']) measDict = {'qubit1': q1,'qubit2':q2} measDf1 = pd.DataFrame.from_dict(measDict,orient='index') measDf12=measDf1.transpose() print(measDf12) # print(measDf12) ct = pd.crosstab(measDf12.qubit1,measDf12.qubit2) return ct """ INPUTS: - qc: QuantumCircuit to run the tests - noOfExperiments: number of times the the qc will be run - noOfMeasurements: number of times the qc will be measured after each run - qubit0: the first qubit to compare - qubit1: the second qubit to comapre - classicalBit0: the bit where the first qubit will be measured in - classicalBit1: the bit where the second qubit will be measured in - basis: the basis of the measurement - backend: the backend used to run the tests OUTPUT: - the data of the execution of the tests, which is a list of lists of statevectors (aka lists) """ def runTestsAssertEntangled(self, initialisedTests, noOfExperiments, noOfMeasurements, qubit0, qubit1, classicalBit0, classicalBit1, basis, backend): return [self.runTestAssertEntangled(qc, noOfExperiments, noOfMeasurements, qubit0, qubit1, classicalBit0, classicalBit1, basis, backend) for qc in initialisedTests] """ INPUTS: - qc: QuantumCircuit to run the tests - noOfExperiments: number of times the the qc will be run - noOfMeasurements: number of times the qc will be measured after each run - qubit0: the first qubit to compare - measuredBit: the bit where the qubit will be measured in - basis: the basis of the measurement - backend: the backend used to run the tests OUTPUT: - the data of the execution of the tests, which is like runTestAssertEqual but without but for only one qubit instead of two """ def runTestAssertProbability(self, qc, noOfExperiments, noOfMeasurements, qubit0, measuredBit, basis, backend): selectedBackend = select_backend(backend, qc) if basis.lower() == "x": measureX(qc, qubit0, measuredBit) elif basis.lower() == "y": measureY(qc, qubit0, measuredBit) else: qc.measure(qubit0, measuredBit) qc_trans = transpile(qc, backend=selectedBackend) trialProbas = np.empty(noOfExperiments) for trialIndex in range(noOfExperiments): result = selectedBackend.run(qc_trans, shots = noOfMeasurements).result() counts = result.get_counts() nb0s = 0 for elem in counts: #Bit oredering is in the reverse order for get_count #(if we measure the last bit, it will get its value in index 0 of the string for some reason) if elem[::-1][measuredBit] == '0': nb0s += counts[elem] trialProba = nb0s / noOfMeasurements trialProbas[trialIndex] = trialProba return trialProbas """ INPUTS: - initialisedTests: list of QuantumCircuits to run the tests - noOfExperiments: number of times the the qc will be run - noOfMeasurements: number of times the qc will be measured after each run - qubit0: the first qubit to compare - measuredBit: the bit where the qubit will be measured in - basis: the basis of the measurement - backend: the backend used to run the tests OUTPUT: - the data of the execution of the tests, which is like runTestsAssertEqual but without but for only one qubit instead of two """ def runTestsAssertProbability(self, initialisedTests, noOfExperiments, noOfMeasurements, qubit0, measuredBit, basis, backend): return [self.runTestAssertProbability(qc, noOfExperiments, noOfMeasurements, qubit0, measuredBit, basis, backend) for qc in initialisedTests] """ INPUTS: - initialisedTests: list of QuantumCircuits to run the tests - noOfExperiments: number of times the the qc will be run - noOfMeasurements: number of times the qc will be measured after each run - qubit0: the first qubit to compare - measuredBit: the bit where the qubit will be measured in - backend: the backend used to run the tests OUTPUT: - the data of the execution of the tests, which is like runTestsAssertEqual but for 3 bases """ def runTestsAssertState(self, initialisedTests, noOfExperiments, noOfMeasurements, qubit0, measuredBit, backend): tests_Y = [qc.copy() for qc in initialisedTests] tests_X = [qc.copy() for qc in initialisedTests] return (self.runTestsAssertProbability(initialisedTests, noOfExperiments, noOfMeasurements, qubit0, measuredBit, "z", backend), self.runTestsAssertProbability(tests_Y, noOfExperiments, noOfMeasurements, qubit0, measuredBit, "y", backend), self.runTestsAssertProbability(tests_X, noOfExperiments, noOfMeasurements, qubit0, measuredBit, "x", backend)) """ INPUTS: - qc: QuantumCircuit to run the tests - noOfMeasurements: number of measurements - backend: the backend used to run the tests OUTPUT: - the data of the execution of the tests """ def runTestAssertMostProbable(self, qc, noOfMeasurements, backend): selectedBackend = select_backend(backend, qc) nbBits = len(qc.clbits) qc.measure_all() qc_trans = transpile(qc, backend=selectedBackend) result = selectedBackend.run(qc_trans, shots=noOfMeasurements).result() counts = result.get_counts() cut_counts = {} for key, value in counts.items(): if key[:-(nbBits+1)] in counts: cut_counts[key[:-(nbBits+1)]] += value else: cut_counts[key[:-(nbBits+1)]] = value return sorted(cut_counts.items(), key=lambda x:x[1]) """ INPUTS: - initialisedTests: list of QuantumCircuits to run the tests - noOfMeasurements: number of measurements - backend: the backend used to run the tests OUTPUT: - the data of the execution of the tests """ def runTestsAssertMostProbable(self, initialisedTests, noOfMeasurements, backend): return [self.runTestAssertMostProbable(qc, noOfMeasurements, backend) for qc in initialisedTests] # def runTestsAssertPhase(self,qc,noOfMeasurements,qubit0,qubit1,expectedPhases,classicalbit0,classicalbit1,noOfExperiments): # selectedBackend = select_backend(backend, qc) # qubitList = [qubit0,qubit1] # for trialIndex in range(noOfExperiments): # (x,y) = getDf(qc,qubitList,noOfMeasurements,selectedBackend) # ## make a dataframe that contains p values of chi square tests to analyse results # ## if x and y counts are both 25/25/25/25, it means that we cannot calculate a phase # ## we assume that a qubit that is in |0> or |1> position to have 50% chance to fall # ## either way, like a coin toss: We treat X and Y results like coin tosses # pValues = pd.DataFrame(columns=['X','Y']) # pValues['X'] = resDf.apply(lambda row: applyChiSquareX(row, measurements_to_make/2), axis=1) # pValues['Y'] = resDf.apply(lambda row: applyChiSquareY(row, measurements_to_make/2), axis=1) # def getDf(qc,qubitList,noOfMeasurements,selectedBackend): # ## divide measurements to make by 3 as we need to run measurements twice, one for x and one for y # ## divide measurements to make by 2 as we need to run measurements twice, one for x and one for y # noOfMeasurements = noOfMeasurements // 2 # ## copy the circit and set measurement to y axis # yQuantumCircuit = measureY(qc.copy(), qubitList) # ## measure the x axis # xQuantumCircuit = measureX(qc.copy(), qubitList) # ## get y axis results # yJob = execute(yQuantumCircuit, selectedBackend, shots=noOfMeasurements, memory=True) # yCounts = yJob.result().get_counts() # ## get x axis results # xJob = execute(xQuantumCircuit, selectedBackend, shots=noOfMeasurements, memory=True) # xCounts = xJob.result().get_counts() # ## make a df to keep track of the predicted angles # resDf = pd.DataFrame(columns=['+','i','-','-i']) # ## fill the df with the x and y results of each qubit that is being asserted # classicalQubitIndex = 1 # for qubit in qubitList: # plus_amount, i_amount, minus_amount, minus_i_amount = 0,0,0,0 # for experiment in xCounts: # if (experiment[len(qubitList)-classicalQubitIndex] == '0'): # plus_amount += xCounts[experiment] # else: # minus_amount += xCounts[experiment] # for experiment in yCounts: # if (experiment[len(qubitList)-classicalQubitIndex] == '0'): # i_amount += yCounts[experiment] # else: # minus_i_amount += yCounts[experiment] # df = {'+':plus_amount, 'i':i_amount, # '-':minus_amount, '-i':minus_i_amount} # resDf = resDf.append(df, ignore_index = True) # classicalQubitIndex+=1 # ## convert the columns to a strict numerical type # resDf['+'] = resDf['+'].astype(int) # resDf['i'] = resDf['i'].astype(int) # resDf['-'] = resDf['-'].astype(int) # resDf['-i'] = resDf['-i'].astype(int) # xAmount = resDf['-'].tolist() # yAmount = resDf['-i'].tolist() # return (xAmount,yAmount)
https://github.com/Pitt-JonesLab/mirror-gates
Pitt-JonesLab
%matplotlib widget from monodromy.depthPass import MonodromyDepth from qiskit.circuit.library import XXPlusYYGate import numpy as np from qiskit import QuantumCircuit from qiskit.quantum_info import Operator from qiskit.extensions import UnitaryGate from weylchamber import canonical_gate gate = XXPlusYYGate(np.pi / 2, np.pi / 6) qc = QuantumCircuit(2) qc.append(gate, [0, 1]) qc.swap(0, 1) gate = UnitaryGate(Operator(qc)) gate = UnitaryGate(canonical_gate(0.5, 0.25, 0.25).full()) MonodromyDepth(basis_gate=gate).coverage_set from slam.utils.polytopes.coverage_plot import plot_coverage_set plot_coverage_set(MonodromyDepth(basis_gate=gate).coverage_set) from qiskit import QuantumCircuit from weylchamber import c1c2c3, WeylChamber from qiskit.quantum_info import Operator import numpy as np from qiskit import transpile # observable = SparsePauliOp("XZ") # qubits = observable.num_qubits # ansatz = RealAmplitudes(observable.num_qubits, reps=3) # display(ansatz.decompose().draw('mpl')) # backend = service.get_backend('ibm_lagos') # transpiled_ansatz = transpile(ansatz, backend=backend, # basis_gates=['u1', 'u2', 'u3', 'rx', 'ry', 'rz', 'cx', 'cz'], # seed_transpiler=42, # optimization_level=3) # display(transpiled_ansatz.decompose().draw('mpl')) # from qiskit.circuit.random import random_circuit # from qiskit.quantum_info import SparsePauliOp # from qiskit.circuit.library import RealAmplitudes # from qiskit_ibm_runtime import QiskitRuntimeService, Session, Estimator, Options # observable = SparsePauliOp("XZ") # qubits = observable.num_qubits # ansatz = RealAmplitudes(observable.num_qubits, reps=3) # display(ansatz.decompose().draw('mpl')) # backend = service.get_backend('simulator_statevector') # transpiled_ansatz = transpile(ansatz, backend=backend, # basis_gates=['u1', 'u2', 'u3', 'rx', 'ry', 'rz', 'cx', 'cz'], # seed_transpiler=42, # optimization_level=3) # service = QiskitRuntimeService() # with Session(service=service, backend="ibmq_qasm_simulator") as session: # estimator = Estimator(session=session, options=options) # job = estimator.run(circuit, observable) # result = job.result() # # Close the session only if all jobs are finished, and you don't need to run more in the session # session.close() # Closes the session # display(circuit.draw("mpl")) # print(f" > Observable: {observable.paulis}") # print(f" > Expectation value: {result.values[0]}") # print(f" > Metadata: {result.metadata[0]}") # from qiskit import QuantumCircuit # qc = QuantumCircuit(2) # qc.cx(0, 1) # qc.swap(0,1) # qc.draw('mpl', filename='cns.svg') # # print(qc.draw("latex_source")) # write circuit for CX decomposed into sqiswaps from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.cx(0, 1) from slam.utils.transpiler_pass.weyl_decompose import ( RootiSwapWeylDecomposition, SiSwapGate, ) # decomposer = RootiSwapWeylDecomposition() # from qiskit.converters import circuit_to_dag, dag_to_circuit # dag = decomposer.run(circuit_to_dag(qc)) # qc2 = dag_to_circuit(dag) from qiskit.transpiler.passmanager import PassManager from qiskit.transpiler.passes import Optimize1qGates pm = PassManager() pm.append(RootiSwapWeylDecomposition()) pm.append(Optimize1qGates()) qc2 = pm.run(qc) qc2.draw("mpl") qc3 = QuantumCircuit(2) from qiskit.circuit.library import iSwapGate import numpy as np # qc3.u(np.pi/2, -np.pi/2, 0, 0) qc3.ry(np.pi / 2, 0) qc3.rz(-np.pi / 2, 0) # qc3.u(np.pi/2, np.pi, -np.pi/2, 1) qc3.rz(np.pi / 2, 1) qc3.ry(-np.pi / 2, 1) qc3.append(SiSwapGate(), [0, 1]) # qc3.u(np.pi, -np.pi/2, np.pi/2, 0) qc3.rx(np.pi, 0) # qc3.u(0, 0, np.pi, 1) qc3.rz(-np.pi, 1) qc3.append(SiSwapGate(), [0, 1]) # qc3.u(np.pi/2, -np.pi/2, -3*np.pi/2, 0) qc3.rx(np.pi / 2, 0) # qc3.u(0, -np.pi/2, -np.pi, 1) qc3.rz(np.pi / 2, 1) qc3.draw("mpl", filename="cx-sqiswap.svg") # from qiskit.quantum_info import Operator # Operator(qc4).equiv(qc) qc3 = QuantumCircuit(2) qc3.u(np.pi / 2, -np.pi / 2, 0, 0) # qc3.ry(np.pi/2, 0) # qc3.rz(-np.pi/2, 0) qc3.u(np.pi / 2, np.pi, -np.pi / 2, 1) # qc3.rz(np.pi/2, 1) # qc3.ry(-np.pi/2, 1) # qc3.append(SiSwapGate(), [0,1]) qc3.barrier() qc3.u(np.pi, -np.pi / 2, np.pi / 2, 0) qc3.u(0, 0, np.pi, 1) # qc3.append(SiSwapGate(), [0,1]) qc3.barrier() qc3.u(np.pi / 2, -np.pi / 2, -3 * np.pi / 2, 0) qc3.u(0, -np.pi / 2, -np.pi, 1) # pm = PassManager() # # pm.append(RootiSwapWeylDecomposition()) # pm.append(Optimize1qGates(basis=['u'])) # qc4 = pm.run(qc3) qc4 = transpile( qc3, basis_gates=["x", "y", "z", "h", "t", "s", "sx", "sy", "sz", "rz", "ry"] ) qc4.draw("mpl", filename="cx_decomp") from virtual_swap.cns_transform import cx_replace from qiskit.transpiler.passes import ( Collect1qRuns, ConsolidateBlocks, Unroller, Optimize1qGates, ) pm = PassManager() # pm.append(Collect1qRuns()) # pm.append(ConsolidateBlocks()) # pm.append(Unroller(['u'])) pm.append(Optimize1qGates(basis=["u"])) # cx_replace.swap(0, 1) cx_replace2 = pm.run(cx_replace) cx_replace2.draw("mpl", filename="cx_decomp.svg") qc = QuantumCircuit(2) qc.crz(np.pi / 2, 0, 1) qc = transpile(qc, basis_gates=["u", "cx"]) qc.draw() # replace the last cx gate with iswap+virtual_swap from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.circuit.library import CXGate dag = circuit_to_dag(qc) cx_node = dag.op_nodes(CXGate)[1] from virtual_swap.cns_transform import cns_transform qc2 = dag_to_circuit(cns_transform(dag, cx_node)) qc2.decompose().draw() Operator(qc2).equiv(qc) from slam.utils.transpiler_pass.weyl_decompose import RootiSwapWeylDecomposition from qiskit.transpiler import PassManager from qiskit.transpiler.passes import ConsolidateBlocks, Collect2qBlocks, Unroller pm = PassManager() pm.append(Unroller(["u", "cx", "iswap"])) pm.append(Collect2qBlocks()) pm.append(ConsolidateBlocks(force_consolidate=True)) pm.append(RootiSwapWeylDecomposition()) pm.run(qc2).draw() qc3 = QuantumCircuit(2) qc3.cx(1, 0) qc3.cx(0, 1) qc3.draw() Operator(qc3).equiv(cx_replace) qc = QuantumCircuit(2) qc.cx(0, 1) qc.swap(0, 1) # transpile into CR gates transpile(qc, basis_gates=["rzx", "u"], optimization_level=3).draw("mpl") qc = QuantumCircuit(2) qc.cx(0, 1) qc.draw("mpl") from slam.utils.transpiler_pass.weyl_decompose import RootiSwapWeylDecomposition from qiskit.transpiler import PassManager pm = PassManager() pm.append(RootiSwapWeylDecomposition()) qc = pm.run(qc) qc.draw("mpl") qc1 = QuantumCircuit(2) qc1.rx(np.pi / 2, 1) qc1.rz(-np.pi / 2, 0) qc1.rz(np.pi / 2, 1) qc1.iswap(0, 1) qc1.rx(np.pi / 2, 0) qc1.iswap(0, 1) qc1.rz(np.pi / 2, 1) qc1.draw("mpl") from qiskit import QuantumCircuit qc = QuantumCircuit(2) qc.cx(1, 0) qc.h(1) qc.cx(0, 1) qc.tdg(1) qc2 = QuantumCircuit(2) qc2.s(0) qc2.cx(1, 0) qc2.sx(1) qc2.sdg(0) qc2.t(1) qc3 = QuantumCircuit(2) qc3.cx(1, 0) qc3.cx(0, 1) qc4 = QuantumCircuit(2) qc4.cx(0, 1) qc4.swap(0, 1) c1 = c1c2c3(Operator(qc).data) c2 = c1c2c3(Operator(qc2).data) c3 = c1c2c3(Operator(qc3).data) c4 = c1c2c3(Operator(qc4).data) print(c1, c2, c3, c4) qc3.draw("mpl") qc4.draw("mpl") Operator(qc4).equiv(cx_replace) from virtual_swap.cns_transform import cx_replace, iswap_replace cx_replace.draw("mpl") iswap_replace.draw("mpl") Operator(qc3).equiv(qc4) # visualize weyl chamber coordinates from weylchamber import WeylChamber w = WeylChamber() N = 1000 for _ in range(N): qc = QuantumCircuit(2) # random 1q qc.u( 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 0, ) qc.u( 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 1, ) # qc.crz(2 * np.pi * np.random.rand(), 0, 1) qc.cx(0, 1) # random 1q qc.u( 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 0, ) qc.u( 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 1, ) # qc.swap(0, 1) # qc.cx(0, 1) qc.iswap(0, 1) # random 1q qc.u( 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 0, ) qc.u( 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 1, ) qc.swap(0, 1) op = Operator(qc).data w.add_point(*c1c2c3(op)) w.plot() qc.draw("mpl") # visualize weyl chamber coordinates from qiskit import QuantumCircuit from weylchamber import c1c2c3, WeylChamber from qiskit.quantum_info import Operator import numpy as np w = WeylChamber() N = 1000 for _ in range(N): qc = QuantumCircuit(2) # random 1q qc.u( 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 0, ) qc.u( 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 1, ) qc.cx(0, 1) # random 1q qc.u( 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 0, ) qc.u( 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 1, ) qc.iswap(0, 1) # random 1q qc.u( 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 0, ) qc.u( 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 1, ) qc.swap(0, 1) # random 1q qc.u( 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 0, ) qc.u( 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand(), 1, ) op = Operator(qc).data w.add_point(*c1c2c3(op)) w.plot() import matplotlib.pyplot as plt w = WeylChamber() # generate a color gradient N = 9 color_gradient = [ plt.cm.tab10(i / (N + 1)) for i in range(N + 1) ] # using 'plasma' colormap here w = WeylChamber() # create two lists for the two types of operations op1_list = [] op2_list = [] # iterate from I to CX (theta = 0 to np.pi) for i in range(N + 1): qc = QuantumCircuit(2) qc.cp(np.pi * i / N, 0, 1) op1 = Operator(qc).data t = c1c2c3(op1) # force to use x < 1/2 if t[0] > 0.5: t = (1 - t[0], t[1], t[2]) op1_list.append((t, color_gradient[i])) qc.swap(0, 1) op2 = Operator(qc).data op2_list.append((c1c2c3(op2), color_gradient[i])) # add the operations to the Weyl chamber for coords, color in op1_list: w.scatter(*coords, color=color) for coords, color in op2_list: w.scatter(*coords, color=color) # define a region using line segments between the following points # (0,0,0), (1/2, 1/2, 0); (0,0,0), (1,0,0); (1/2, 1/2, 0), (1,0,0); (0,0,0), (1/2, 1/4, 1/4) lines = [ [(0, 0, 0), (0.5, 0.5, 0)], [(0, 0, 0), (1, 0, 0)], [(0.5, 0.5, 0), (1, 0, 0)], [(0, 0, 0), (0.5, 0.25, 0.25)], [(0.5, 0.5, 0), (0.5, 0.25, 0.25)], [(0.5, 0.25, 0.25), (1, 0, 0)], ] # draw the lines w.labels = {} w.plot() for i in range(len(lines)): w._draw_line( w.ax, origin=lines[i][0], end=lines[i][1], color="blue", linestyle="--" ) w.fig.savefig("cphase_swap.svg", dpi=300) # fig.savefig("cphase_swap.svg", dpi=300) w = WeylChamber() # generate Haar random unitary from qiskit.quantum_info import random_unitary op = random_unitary(4).data qc = QuantumCircuit(2) qc.unitary(op, [0, 1]) op = Operator(qc).data w.scatter(*c1c2c3(op), color="blue") qc.swap(0, 1) op2 = Operator(qc).data w.scatter(*c1c2c3(op2), color="red") w.plot() import numpy as np from qiskit.quantum_info import random_unitary from qiskit.quantum_info import Operator from qiskit import QuantumCircuit from weylchamber import WeylChamber, c1c2c3 import matplotlib.pyplot as plt from matplotlib import cm w = WeylChamber() # Generate many random unitaries N = 1000 coords_initial = [] coords_final = [] for _ in range(N): # Generate Haar random unitary op = random_unitary(4).data qc = QuantumCircuit(2) qc.unitary(op, [0, 1]) op = Operator(qc).data coords_initial.append(c1c2c3(op)) # Apply SWAP qc.swap(0, 1) op2 = Operator(qc).data coords_final.append(c1c2c3(op2)) # Convert to numpy arrays for easier handling coords_initial = np.array(coords_initial) coords_final = np.array(coords_final) # Plot initial points with blue color w.scatter( coords_initial[:, 0], coords_initial[:, 1], coords_initial[:, 2], color="blue" ) # Plot final points with red color w.scatter(coords_final[:, 0], coords_final[:, 1], coords_final[:, 2], color="red") import matplotlib as mpl # Create a color map with 256 colors color_map = mpl.cm.get_cmap("viridis", 256) # Generate colors from the color map colors = color_map(np.linspace(0, 1, N)) # # Plot trajectories # for i in range(N): # w._draw_line( # (coords_initial[i, 0], coords_initial[i, 1], coords_initial[i, 2]), # (coords_final[i, 0], coords_final[i, 1], coords_final[i, 2]), # color=colors[i], # ) w.plot()
https://github.com/e-eight/vqe
e-eight
# -*- coding: utf-8 -*- # 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. """ The Variational Quantum Eigensolver algorithm. See https://arxiv.org/abs/1304.3061 """ import logging import functools import numpy as np from qiskit import ClassicalRegister, QuantumCircuit from qiskit.aqua.algorithms.adaptive.vq_algorithm import VQAlgorithm from qiskit.aqua import AquaError, Pluggable, PluggableType, get_pluggable_class from qiskit.aqua.utils.backend_utils import is_aer_statevector_backend from qiskit.aqua.utils import find_regs_by_name logger = logging.getLogger(__name__) class VQE(VQAlgorithm): """ The Variational Quantum Eigensolver algorithm. See https://arxiv.org/abs/1304.3061 """ CONFIGURATION = { 'name': 'VQE', 'description': 'VQE Algorithm', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'vqe_schema', 'type': 'object', 'properties': { 'operator_mode': { 'type': 'string', 'default': 'matrix', 'oneOf': [ {'enum': ['matrix', 'paulis', 'grouped_paulis']} ] }, 'initial_point': { 'type': ['array', 'null'], "items": { "type": "number" }, 'default': None }, 'max_evals_grouped': { 'type': 'integer', 'default': 1 } }, 'additionalProperties': False }, 'problems': ['energy', 'ising'], 'depends': [ {'pluggable_type': 'optimizer', 'default': { 'name': 'L_BFGS_B' } }, {'pluggable_type': 'variational_form', 'default': { 'name': 'RYRZ' } }, ], } def __init__(self, operator, var_form, optimizer, operator_mode='matrix', initial_point=None, max_evals_grouped=1, aux_operators=None, callback=None): """Constructor. Args: operator (Operator): Qubit operator operator_mode (str): operator mode, used for eval of operator var_form (VariationalForm): parametrized variational form. optimizer (Optimizer): the classical optimization algorithm. initial_point (numpy.ndarray): optimizer initial point. max_evals_grouped (int): max number of evaluations performed simultaneously aux_operators (list of Operator): Auxiliary operators to be evaluated at each eigenvalue callback (Callable): a callback that can access the intermediate data during the optimization. Internally, four arguments are provided as follows the index of evaluation, parameters of variational form, evaluated mean, evaluated standard devation. """ self.validate(locals()) super().__init__(var_form=var_form, optimizer=optimizer, cost_fn=self._energy_evaluation, initial_point=initial_point) self._optimizer.set_max_evals_grouped(max_evals_grouped) self._callback = callback if initial_point is None: self._initial_point = var_form.preferred_init_points self._operator = operator self._operator_mode = operator_mode self._eval_count = 0 if aux_operators is None: self._aux_operators = [] else: self._aux_operators = [aux_operators] if not isinstance(aux_operators, list) else aux_operators logger.info(self.print_settings()) @classmethod def init_params(cls, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance. Args: params (dict): parameters dictionary algo_input (EnergyInput): EnergyInput instance Returns: VQE: vqe object """ if algo_input is None: raise AquaError("EnergyInput instance is required.") operator = algo_input.qubit_op vqe_params = params.get(Pluggable.SECTION_KEY_ALGORITHM) operator_mode = vqe_params.get('operator_mode') initial_point = vqe_params.get('initial_point') max_evals_grouped = vqe_params.get('max_evals_grouped') # Set up variational form, we need to add computed num qubits # Pass all parameters so that Variational Form can create its dependents var_form_params = params.get(Pluggable.SECTION_KEY_VAR_FORM) var_form_params['num_qubits'] = operator.num_qubits var_form = get_pluggable_class(PluggableType.VARIATIONAL_FORM, var_form_params['name']).init_params(params) # Set up optimizer opt_params = params.get(Pluggable.SECTION_KEY_OPTIMIZER) optimizer = get_pluggable_class(PluggableType.OPTIMIZER, opt_params['name']).init_params(params) return cls(operator, var_form, optimizer, operator_mode=operator_mode, initial_point=initial_point, max_evals_grouped=max_evals_grouped, aux_operators=algo_input.aux_ops) @property def setting(self): """Prepare the setting of VQE as a string.""" ret = "Algorithm: {}\n".format(self._configuration['name']) params = "" for key, value in self.__dict__.items(): if key != "_configuration" and key[0] == "_": if "initial_point" in key and value is None: params += "-- {}: {}\n".format(key[1:], "Random seed") else: params += "-- {}: {}\n".format(key[1:], value) ret += "{}".format(params) return ret def print_settings(self): """ Preparing the setting of VQE into a string. Returns: str: the formatted setting of VQE """ ret = "\n" ret += "==================== Setting of {} ============================\n".format(self.configuration['name']) ret += "{}".format(self.setting) ret += "===============================================================\n" ret += "{}".format(self._var_form.setting) ret += "===============================================================\n" ret += "{}".format(self._optimizer.setting) ret += "===============================================================\n" return ret def construct_circuit(self, parameter, backend=None, use_simulator_operator_mode=False): """Generate the circuits. Args: parameters (numpy.ndarray): parameters for variational form. backend (qiskit.BaseBackend): backend object. use_simulator_operator_mode (bool): is backend from AerProvider, if True and mode is paulis, single circuit is generated. Returns: [QuantumCircuit]: the generated circuits with Hamiltonian. """ input_circuit = self._var_form.construct_circuit(parameter) if backend is None: warning_msg = "Circuits used in VQE depends on the backend type, " from qiskit import BasicAer if self._operator_mode == 'matrix': temp_backend_name = 'statevector_simulator' else: temp_backend_name = 'qasm_simulator' backend = BasicAer.get_backend(temp_backend_name) warning_msg += "since operator_mode is '{}', '{}' backend is used.".format( self._operator_mode, temp_backend_name) logger.warning(warning_msg) circuit = self._operator.construct_evaluation_circuit(self._operator_mode, input_circuit, backend, use_simulator_operator_mode) return circuit def _eval_aux_ops(self, threshold=1e-12, params=None): if params is None: params = self.optimal_params wavefn_circuit = self._var_form.construct_circuit(params) circuits = [] values = [] params = [] for operator in self._aux_operators: if not operator.is_empty(): temp_circuit = QuantumCircuit() + wavefn_circuit circuit = operator.construct_evaluation_circuit(self._operator_mode, temp_circuit, self._quantum_instance.backend, self._use_simulator_operator_mode) params.append(operator.aer_paulis) else: circuit = None circuits.append(circuit) if len(circuits) > 0: to_be_simulated_circuits = functools.reduce(lambda x, y: x + y, [c for c in circuits if c is not None]) if self._use_simulator_operator_mode: extra_args = {'expectation': { 'params': params, 'num_qubits': self._operator.num_qubits} } else: extra_args = {} result = self._quantum_instance.execute(to_be_simulated_circuits, **extra_args) for operator, circuit in zip(self._aux_operators, circuits): if circuit is None: mean, std = 0.0, 0.0 else: mean, std = operator.evaluate_with_result(self._operator_mode, circuit, self._quantum_instance.backend, result, self._use_simulator_operator_mode) mean = mean.real if abs(mean.real) > threshold else 0.0 std = std.real if abs(std.real) > threshold else 0.0 values.append((mean, std)) if len(values) > 0: aux_op_vals = np.empty([1, len(self._aux_operators), 2]) aux_op_vals[0, :] = np.asarray(values) self._ret['aux_ops'] = aux_op_vals def _run(self): """ Run the algorithm to compute the minimum eigenvalue. Returns: Dictionary of results """ if not self._quantum_instance.is_statevector and self._operator_mode == 'matrix': logger.warning('Qasm simulation does not work on {} mode, changing ' 'the operator_mode to "paulis"'.format(self._operator_mode)) self._operator_mode = 'paulis' self._use_simulator_operator_mode = \ is_aer_statevector_backend(self._quantum_instance.backend) \ and self._operator_mode != 'matrix' self._quantum_instance.circuit_summary = True self._eval_count = 0 self._ret = self.find_minimum(initial_point=self.initial_point, var_form=self.var_form, cost_fn=self._energy_evaluation, optimizer=self.optimizer) if self._ret['num_optimizer_evals'] is not None and self._eval_count >= self._ret['num_optimizer_evals']: self._eval_count = self._ret['num_optimizer_evals'] self._eval_time = self._ret['eval_time'] logger.info('Optimization complete in {} seconds.\nFound opt_params {} in {} evals'.format( self._eval_time, self._ret['opt_params'], self._eval_count)) self._ret['eval_count'] = self._eval_count self._ret['energy'] = self.get_optimal_cost() self._ret['eigvals'] = np.asarray([self.get_optimal_cost()]) self._ret['eigvecs'] = np.asarray([self.get_optimal_vector()]) self._eval_aux_ops() return self._ret # This is the objective function to be passed to the optimizer that is uses for evaluation def _energy_evaluation(self, parameters): """ Evaluate energy at given parameters for the variational form. Args: parameters (numpy.ndarray): parameters for variational form. Returns: float or list of float: energy of the hamiltonian of each parameter. """ num_parameter_sets = len(parameters) // self._var_form.num_parameters circuits = [] parameter_sets = np.split(parameters, num_parameter_sets) mean_energy = [] std_energy = [] for idx in range(len(parameter_sets)): parameter = parameter_sets[idx] circuit = self.construct_circuit(parameter, self._quantum_instance.backend, self._use_simulator_operator_mode) circuits.append(circuit) to_be_simulated_circuits = functools.reduce(lambda x, y: x + y, circuits) if self._use_simulator_operator_mode: extra_args = {'expectation': { 'params': [self._operator.aer_paulis], 'num_qubits': self._operator.num_qubits} } else: extra_args = {} result = self._quantum_instance.execute(to_be_simulated_circuits, **extra_args) for idx in range(len(parameter_sets)): mean, std = self._operator.evaluate_with_result( self._operator_mode, circuits[idx], self._quantum_instance.backend, result, self._use_simulator_operator_mode) mean_energy.append(np.real(mean)) std_energy.append(np.real(std)) self._eval_count += 1 if self._callback is not None: self._callback(self._eval_count, parameter_sets[idx], np.real(mean), np.real(std)) logger.info('Energy evaluation {} returned {}'.format(self._eval_count, np.real(mean))) return mean_energy if len(mean_energy) > 1 else mean_energy[0] def get_optimal_cost(self): if 'opt_params' not in self._ret: raise AquaError("Cannot return optimal cost before running the algorithm to find optimal params.") return self._ret['min_val'] def get_optimal_circuit(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal circuit before running the algorithm to find optimal params.") return self._var_form.construct_circuit(self._ret['opt_params']) def get_optimal_vector(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal vector before running the algorithm to find optimal params.") qc = self.get_optimal_circuit() if self._quantum_instance.is_statevector: ret = self._quantum_instance.execute(qc) self._ret['min_vector'] = ret.get_statevector(qc, decimals=16) else: c = ClassicalRegister(qc.width(), name='c') q = find_regs_by_name(qc, 'q') qc.add_register(c) qc.barrier(q) qc.measure(q, c) ret = self._quantum_instance.execute(qc) self._ret['min_vector'] = ret.get_counts(qc) return self._ret['min_vector'] @property def optimal_params(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal params before running the algorithm.") return self._ret['opt_params']
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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=invalid-name """Randomized tests of transpiler circuit equivalence. This test can be optionally configured (e.g. by CI) via the following env vars: QISKIT_RANDOMIZED_TEST_LAYOUT_METHODS A space-delimited list of layout method names from which the randomizer should pick the layout method. Defaults to all available built-in methods if unspecified. QISKIT_RANDOMIZED_TEST_ROUTING_METHODS A space-delimited list of routing method names from which the randomizer should pick the routing method. Defaults to all available built-in methods if unspecified. QISKIT_RANDOMIZED_TEST_SCHEDULING_METHODS A space-delimited list of scheduling method names from which the randomizer should pick the scheduling method. Defaults to all available built-in methods if unspecified. QISKIT_RANDOMIZED_TEST_BACKEND_NEEDS_DURATIONS A boolean value (e.g. "true", "Y", etc.) which, when true, forces the randomizer to pick a backend which fully supports scheduling (i.e. has fully specified duration info). Defaults to False. QISKIT_RANDOMIZED_TEST_ALLOW_BARRIERS A boolean value (e.g. "true", "Y", etc.) which, when false, prevents the randomizer from emitting barrier instructions. Defaults to True. """ import os from math import pi from hypothesis import assume, settings, HealthCheck from hypothesis.stateful import multiple, rule, precondition, invariant from hypothesis.stateful import Bundle, RuleBasedStateMachine import hypothesis.strategies as st from qiskit import transpile, Aer from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit import Measure, Reset, Gate, Barrier from qiskit.providers.fake_provider import ( FakeProvider, FakeOpenPulse2Q, FakeOpenPulse3Q, FakeYorktown, FakeTenerife, FakeOurense, FakeVigo, FakeMelbourne, FakeRueschlikon, FakeTokyo, FakePoughkeepsie, FakeAlmaden, FakeSingapore, FakeJohannesburg, FakeBoeblingen, FakeRochester, FakeBurlington, FakeCambridge, FakeCambridgeAlternativeBasis, FakeEssex, FakeLondon, FakeQasmSimulator, FakeArmonk, FakeRome, FakeSantiago, FakeSydney, FakeToronto, FakeValencia, ) from qiskit.test.base import dicts_almost_equal # pylint: disable=wildcard-import,unused-wildcard-import from qiskit.circuit.library.standard_gates import * default_profile = "transpiler_equivalence" settings.register_profile( default_profile, report_multiple_bugs=False, max_examples=200, deadline=None, suppress_health_check=[HealthCheck.filter_too_much], ) settings.load_profile(os.getenv("HYPOTHESIS_PROFILE", default_profile)) BASE_INSTRUCTIONS = { # Key is (n_qubits, n_clbits, n_params). All gates here should be directly known by Aer so they # can be simulated without an initial transpile (whether that's via `execute` or not). (1, 0, 0): [HGate, IGate, SGate, SdgGate, TGate, TdgGate, XGate, YGate, ZGate, Reset], (2, 0, 0): [CXGate, CYGate, CZGate, SwapGate], (3, 0, 0): [CCXGate, CSwapGate], (1, 0, 1): [PhaseGate, RXGate, RYGate, RZGate], (1, 0, 3): [UGate], (2, 0, 1): [RZZGate, CPhaseGate], (2, 0, 4): [CUGate], (1, 1, 0): [Measure], } variadic_gates = [Barrier] def _strtobool(s): return s.lower() in ("y", "yes", "t", "true", "on", "1") if not _strtobool(os.getenv("QISKIT_RANDOMIZED_TEST_ALLOW_BARRIERS", "True")): variadic_gates.remove(Barrier) def _getenv_list(var_name): value = os.getenv(var_name) return None if value is None else value.split() # Note: a value of `None` for any of the following methods means that # the selected pass manager gets to choose. However, to avoid complexity, # its not possible to specify `None` when overriding these with environment # variables. Really, `None` is useful only for testing Terra's pass managers, # and if you're overriding these, your goal is probably to test a specific # pass or set of passes instead. layout_methods = _getenv_list("QISKIT_RANDOMIZED_TEST_LAYOUT_METHODS") or [ None, "trivial", "dense", "noise_adaptive", "sabre", ] routing_methods = _getenv_list("QISKIT_RANDOMIZED_TEST_ROUTING_METHODS") or [ None, "basic", "stochastic", "lookahead", "sabre", ] scheduling_methods = _getenv_list("QISKIT_RANDOMIZED_TEST_SCHEDULING_METHODS") or [ None, "alap", "asap", ] backend_needs_durations = _strtobool( os.getenv("QISKIT_RANDOMIZED_TEST_BACKEND_NEEDS_DURATIONS", "False") ) def _fully_supports_scheduling(backend): """Checks if backend is not in the set of backends known not to have specified gate durations.""" return not isinstance( backend, ( # no coupling map FakeArmonk, # no measure durations FakeAlmaden, FakeBurlington, FakeCambridge, FakeCambridgeAlternativeBasis, FakeEssex, FakeJohannesburg, FakeLondon, FakeOpenPulse2Q, FakeOpenPulse3Q, FakePoughkeepsie, FakeQasmSimulator, FakeRochester, FakeRueschlikon, FakeSingapore, FakeTenerife, FakeTokyo, # No reset duration FakeAlmaden, FakeArmonk, FakeBoeblingen, FakeBurlington, FakeCambridge, FakeCambridgeAlternativeBasis, FakeEssex, FakeJohannesburg, FakeLondon, FakeMelbourne, FakeOpenPulse2Q, FakeOpenPulse3Q, FakeOurense, FakePoughkeepsie, FakeQasmSimulator, FakeRochester, FakeRome, FakeRueschlikon, FakeSantiago, FakeSingapore, FakeSydney, FakeTenerife, FakeTokyo, FakeToronto, FakeValencia, FakeVigo, FakeYorktown, ), ) fake_provider = FakeProvider() mock_backends = fake_provider.backends() mock_backends_with_scheduling = [b for b in mock_backends if _fully_supports_scheduling(b)] @st.composite def transpiler_conf(draw): """Composite search strategy to pick a valid transpiler config.""" all_backends = st.one_of(st.none(), st.sampled_from(mock_backends)) scheduling_backends = st.sampled_from(mock_backends_with_scheduling) scheduling_method = draw(st.sampled_from(scheduling_methods)) backend = ( draw(scheduling_backends) if scheduling_method or backend_needs_durations else draw(all_backends) ) return { "backend": backend, "optimization_level": draw(st.integers(min_value=0, max_value=3)), "layout_method": draw(st.sampled_from(layout_methods)), "routing_method": draw(st.sampled_from(routing_methods)), "scheduling_method": scheduling_method, "seed_transpiler": draw(st.integers(min_value=0, max_value=1_000_000)), } class QCircuitMachine(RuleBasedStateMachine): """Build a Hypothesis rule based state machine for constructing, transpiling and simulating a series of random QuantumCircuits. Build circuits with up to QISKIT_RANDOM_QUBITS qubits, apply a random selection of gates from qiskit.circuit.library with randomly selected qargs, cargs, and parameters. At random intervals, transpile the circuit for a random backend with a random optimization level and simulate both the initial and the transpiled circuits to verify that their counts are the same. """ qubits = Bundle("qubits") clbits = Bundle("clbits") backend = Aer.get_backend("aer_simulator") max_qubits = int(backend.configuration().n_qubits / 2) # Limit reg generation for more interesting circuits max_qregs = 3 max_cregs = 3 def __init__(self): super().__init__() self.qc = QuantumCircuit() self.enable_variadic = bool(variadic_gates) @precondition(lambda self: len(self.qc.qubits) < self.max_qubits) @precondition(lambda self: len(self.qc.qregs) < self.max_qregs) @rule(target=qubits, n=st.integers(min_value=1, max_value=max_qubits)) def add_qreg(self, n): """Adds a new variable sized qreg to the circuit, up to max_qubits.""" n = min(n, self.max_qubits - len(self.qc.qubits)) qreg = QuantumRegister(n) self.qc.add_register(qreg) return multiple(*list(qreg)) @precondition(lambda self: len(self.qc.cregs) < self.max_cregs) @rule(target=clbits, n=st.integers(1, 5)) def add_creg(self, n): """Add a new variable sized creg to the circuit.""" creg = ClassicalRegister(n) self.qc.add_register(creg) return multiple(*list(creg)) # Gates of various shapes @precondition(lambda self: self.qc.num_qubits > 0 and self.qc.num_clbits > 0) @rule(n_arguments=st.sampled_from(sorted(BASE_INSTRUCTIONS.keys())), data=st.data()) def add_gate(self, n_arguments, data): """Append a random fixed gate to the circuit.""" n_qubits, n_clbits, n_params = n_arguments gate_class = data.draw(st.sampled_from(BASE_INSTRUCTIONS[n_qubits, n_clbits, n_params])) qubits = data.draw(st.lists(self.qubits, min_size=n_qubits, max_size=n_qubits, unique=True)) clbits = data.draw(st.lists(self.clbits, min_size=n_clbits, max_size=n_clbits, unique=True)) params = data.draw( st.lists( st.floats( allow_nan=False, allow_infinity=False, min_value=-10 * pi, max_value=10 * pi ), min_size=n_params, max_size=n_params, ) ) self.qc.append(gate_class(*params), qubits, clbits) @precondition(lambda self: self.enable_variadic) @rule(gate=st.sampled_from(variadic_gates), qargs=st.lists(qubits, min_size=1, unique=True)) def add_variQ_gate(self, gate, qargs): """Append a gate with a variable number of qargs.""" self.qc.append(gate(len(qargs)), qargs) @precondition(lambda self: len(self.qc.data) > 0) @rule(carg=clbits, data=st.data()) def add_c_if_last_gate(self, carg, data): """Modify the last gate to be conditional on a classical register.""" creg = self.qc.find_bit(carg).registers[0][0] val = data.draw(st.integers(min_value=0, max_value=2 ** len(creg) - 1)) last_gate = self.qc.data[-1] # Conditional instructions are not supported assume(isinstance(last_gate[0], Gate)) last_gate[0].c_if(creg, val) # Properties to check @invariant() def qasm(self): """After each circuit operation, it should be possible to build QASM.""" self.qc.qasm() @precondition(lambda self: any(isinstance(d[0], Measure) for d in self.qc.data)) @rule(kwargs=transpiler_conf()) def equivalent_transpile(self, kwargs): """Simulate, transpile and simulate the present circuit. Verify that the counts are not significantly different before and after transpilation. """ assume( kwargs["backend"] is None or kwargs["backend"].configuration().n_qubits >= len(self.qc.qubits) ) call = ( "transpile(qc, " + ", ".join(f"{key:s}={value!r}" for key, value in kwargs.items() if value is not None) + ")" ) print(f"Evaluating {call} for:\n{self.qc.qasm()}") shots = 4096 # Note that there's no transpilation here, which is why the gates are limited to only ones # that Aer supports natively. aer_counts = self.backend.run(self.qc, shots=shots).result().get_counts() try: xpiled_qc = transpile(self.qc, **kwargs) except Exception as e: failed_qasm = f"Exception caught during transpilation of circuit: \n{self.qc.qasm()}" raise RuntimeError(failed_qasm) from e xpiled_aer_counts = self.backend.run(xpiled_qc, shots=shots).result().get_counts() count_differences = dicts_almost_equal(aer_counts, xpiled_aer_counts, 0.05 * shots) assert ( count_differences == "" ), "Counts not equivalent: {}\nFailing QASM Input:\n{}\n\nFailing QASM Output:\n{}".format( count_differences, self.qc.qasm(), xpiled_qc.qasm() ) TestQuantumCircuit = QCircuitMachine.TestCase
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import pulse d0 = pulse.DriveChannel(0) x90 = pulse.Gaussian(10, 0.1, 3) x180 = pulse.Gaussian(10, 0.2, 3) def udd10_pos(j): return np.sin(np.pi*j/(2*10 + 2))**2 with pulse.build() as udd_sched: pulse.play(x90, d0) with pulse.align_func(duration=300, func=udd10_pos): for _ in range(10): pulse.play(x180, d0) pulse.play(x90, d0) udd_sched.draw()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) ghz.draw(output='mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.735", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) problem = driver.run() print(problem) hamiltonian = problem.hamiltonian coefficients = hamiltonian.electronic_integrals print(coefficients.alpha) second_q_op = hamiltonian.second_q_op() print(second_q_op) hamiltonian.nuclear_repulsion_energy # NOT included in the second_q_op above problem.molecule problem.reference_energy problem.num_particles problem.num_spatial_orbitals problem.basis problem.properties problem.properties.particle_number problem.properties.angular_momentum problem.properties.magnetization problem.properties.electronic_dipole_moment from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms import GroundStateEigensolver from qiskit_nature.second_q.mappers import JordanWignerMapper solver = GroundStateEigensolver( JordanWignerMapper(), NumPyMinimumEigensolver(), ) result = solver.solve(problem) print(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/mareksubocz/QRBM-qiskit
mareksubocz
from qiskit import IBMQ # IBMQ.save_account(MY_API_TOKEN) import qiskit qiskit.__version__ import scipy import numpy as np import random from sklearn import preprocessing from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.quantum_info.operators import Operator from qiskit import(QuantumCircuit, execute, Aer) from qiskit.visualization import plot_histogram from qiskit.extensions import Initialize # Import the Inititialize function from qiskit.aqua.circuits.gates import multi_control_toffoli_gate from qiskit.aqua.circuits.gates import multi_control_multi_target_gate #definicja rozmiaru sieci visible = 1 hidden = 1 ancilla = visible-1 #definicja wejścia (x) oraz inicjalizacja macierzy wag x = np.array([random.uniform(0, 1) for n in range(visible)]) weight_matrix = np.random.rand(visible, hidden) * np.pi # definicja obwodu (linii qubitów) # qc = QuantumCircuit(visible + hidden, visible) qr = QuantumRegister(visible + hidden + ancilla, 'q') cr = ClassicalRegister(visible + hidden, 'c') qc = QuantumCircuit(qr, cr) # inicjalizacja wartości qubitów wejściowych (x) na razie randomowa initial_state = [[np.sqrt(x[i]), np.sqrt(1-x[i])] for i in range(len(x))] # inicjalizacja wartości qubitów wejściowych i bramka Hadamarda for i in range(visible): initialize_qubit = Initialize(initial_state[i]) qc.append(initialize_qubit, [i]) qc.h(i) # ciąg bramek CNOT i bramek rotacji R (zależnych od parametrów) for i in range(hidden): for j in range(visible): qc.rz(weight_matrix[j][i], j) multi_control_toffoli_gate.mct(qc, [qr[k] for k in range(visible)], qr[visible + i], [qr[i] for i in range(visible + hidden, visible + hidden + ancilla)], mode='basic') # bramki Hadamarda na warstwie ukrytej for i in range(hidden): qc.h(visible + i) # pomiar linii visible qc.measure(list(range(visible, visible+hidden)), list(range(visible, visible+hidden))) ### OBWÓD DRUGĄ STRONĘ # wyzerowanie wartości qubitów visible for i in range(visible): initialize_qubit = Initialize([1, 0]) qc.append(initialize_qubit, [i]) # bramka Hadamarda na qubitach hidden for i in range(visible, hidden + visible): qc.h(i) #odwrócone rotacje i CNOTy for i in range(hidden): for j in range(visible): multi_control_toffoli_gate.mct(qc, [qr[k] for k in range(visible, visible + hidden)], qr[j], [qr[k] for k in range(visible + hidden, visible + hidden + ancilla)], mode='basic') qc.rz(-weight_matrix[j][hidden - 1 - i], j) # bramka Hadamarda i pomiar na qubitach visible for i in range(visible): qc.h(i) qc.measure(list(range(visible)), list(range(visible))) # Use Aer's qasm_simulator simulator = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator job = execute(qc, simulator, shots=1000) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(qc) print("\nTotal count for 0 and 1 are:",counts) # qc.draw(output='mpl') qc.draw() # komórka do testowania wieloqubitowej bramki CNOT # NIE ZALEŻNA OD WŁAŚCIWEJ SIECI # work = ancilla def n_control_gate(qc, target, control: list, work: list, gate_type): if len(control) - len(work) != 1: raise Exception("Wrong number of control or work qubits!") qc.toffoli(control[0], control[1], work[0]) control_left = control[2:] for i, c_bit in enumerate(control_left): qc.toffoli(c_bit, work[i], work[i+1]) qc.gate_type(work[-1], target) for i, c_bit in reversed(list(enumerate(control_left))): qc.toffoli(c_bit, work[i], work[i+1]) qc.toffoli(control[0], control[1], work[0]) visible = 2 hidden = 2 ancilla = visible - 1 # qr_visible = QuantumRegister(visible, 'visible') # qr_hidden = QuantumRegister(hidden, 'hidden') # cr = ClassicalRegister(3, 'c') # if visible > 2: # anc = QuantumRegister(visible - 2, 'ancilla') # qc = QuantumCircuit(qr_visible, qr_hidden, anc, cr) # else: # qc = QuantumCircuit(qr_visible, qr_hidden, cr) # qr_visible = QuantumRegister(visible, 'visible') qr = QuantumRegister(visible + hidden + ancilla, 'q') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qr, cr) for i in range(visible + hidden): initialize_qubit = Initialize([0, 1]) qc.append(initialize_qubit, [i]) # initialize_qubit = Initialize([1, 0]) # qc.append(initialize_qubit, [2]) # for i in range(hidden): # for j in range(visible): # qc.rz(weight_matrix[j][i], j) print(list(range(visible)) + [visible + 0]) print(list(range(visible+hidden, visible+hidden+ancilla))) # multi_control_multi_target_gate.mcmt(qc, list(range(visible)), [], QuantumCircuit.cx, [visible]) # print([qr_visible[i] for i in range(visible)]) # print([anc[i] for i in range(ancilla)]) # print([qr_hidden[i] for i in range(hidden)]) for j in range(hidden): multi_control_multi_target_gate.mcmt(qc, [qr[i] for i in range(visible)], [qr[i] for i in range(visible + hidden, visible + hidden + ancilla)], QuantumCircuit.cx, [qr[visible + j]]) # multi_control_multi_target_gate.mcmt(qc, [qr_visible[i] for i in range(visible)], [anc[i] for i in range(ancilla)], QuantumCircuit.cx, [qr_hidden[0]]) # qc.measure(list(range(visible+hidden)), list(range(visible + hidden))) # (qc, list(range(visible)) + [visible + 0], qancilla = 6) # Use Aer's qasm_simulator simulator = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator job = execute(qc, simulator, shots=1000) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(qc) print("\nTotal count for 0 and 1 are:",counts) qc.draw() print(weight_matrix, '\n') sinus_matrix = np.sin(weight_matrix + np.pi/4) print(sinus_matrix, '\n') print(sinus_matrix.prod(axis = 0), '\n') phi = np.arcsin(sinus_matrix.prod(axis = 0)) print(phi, '\n') psi = phi + np.pi/4 print(psi, '\n') ph = np.sin(psi)**2 print(ph, '\n') # ph_normalized = preprocessing.normalize([ph], norm = 'l1')[0] # print(ph_normalized) def exctract_single_qubit_measurment(dict_of_counts, qubit_range): num_qubits = int(np.log2(len(counts))) # result = np.zeros(len(qubit_range)) result = np.zeros(num_qubits) for el in dict_of_counts: for i in range(num_qubits): # print("i", i) # print("el[i]", el[i]) if i in qubit_range and el[i] == '1': result[i] += dict_of_counts[el] # print(result) # print(result[qubit_range]) return result[qubit_range] # template do uczenia def update(exp_ph): global weight_matrix #obliczanie prawdopodobieństwa p(|h>) ze wzoru sinus_matrix = np.sin(weight_matrix + np.pi/4) phi = np.arcsin(sinus_matrix.prod(axis = 0)) # print('phi', phi) psi = phi + np.pi/4 # print('psi', psi) ph = np.sin(psi)**2 # print('ph', ph) #obliczanie gradientu i,k S = 1/(np.sqrt(1-(np.sin(phi))**2)) # print("S", S) T = np.sin(phi) * np.sum(1/np.tan(weight_matrix + np.pi/4), axis = 0) # print("T", T) # print("sum products", (exp_ph - ph) * ph * np.cos(2*psi) * S * T) gradient = np.zeros(hidden) for k in range(hidden): gradient[k] = np.sum( (exp_ph - ph) * ph * np.cos(2*psi) * S * T[k]) # print("gradient = ", gradient) # print([gradient] * len(weight_matrix)) weight_matrix = weight_matrix + ([gradient] * len(weight_matrix)) #definicja rozmiaru sieci visible = 3 hidden = 2 ancilla = visible-1 #definicja wejścia (x)oraz inicjalizacja macierzy wag # x = np.array([random.uniform(0, 1) for n in range(visible)]) x = np.array([0.25 for n in range(visible)]) weight_matrix = np.random.rand(visible, hidden) * np.pi #definicja parametrów uczenia num_shots = 1000 num_epochs = 100 for epoch in range(num_epochs): ########################## # definicja obwodu (linii qubitów) # qc = QuantumCircuit(visible + hidden, visible) qr = QuantumRegister(visible + hidden + ancilla, 'q') cr = ClassicalRegister(visible + hidden, 'c') qc = QuantumCircuit(qr, cr) # inicjalizacja wartości qubitów wejściowych (x) na razie randomowa initial_state = [[np.sqrt(x[i]), np.sqrt(1-x[i])] for i in range(len(x))] # inicjalizacja wartości qubitów wejściowych i bramka Hadamarda for i in range(visible): initialize_qubit = Initialize(initial_state[i]) qc.append(initialize_qubit, [i]) qc.h(i) # ciąg bramek CNOT i bramek rotacji R (zależnych od parametrów) for i in range(hidden): for j in range(visible): qc.rz(weight_matrix[j][i], j) multi_control_toffoli_gate.mct(qc, [qr[k] for k in range(visible)], qr[visible + i], [qr[i] for i in range(visible + hidden, visible + hidden + ancilla)], mode='basic') # bramki Hadamarda na warstwie ukrytej for i in range(hidden): qc.h(visible + i) # pomiar linii visible qc.measure(list(range(visible, visible+hidden)), list(range(visible, visible+hidden))) ### OBWÓD DRUGĄ STRONĘ # wyzerowanie wartości qubitów visible for i in range(visible): initialize_qubit = Initialize([1, 0]) qc.append(initialize_qubit, [i]) # bramka Hadamarda na qubitach hidden for i in range(visible, hidden + visible): qc.h(i) #odwrócone rotacje i CNOTy for i in range(hidden): for j in range(visible): multi_control_toffoli_gate.mct(qc, [qr[k] for k in range(visible, visible + hidden)], qr[j], [qr[k] for k in range(visible + hidden, visible + hidden + ancilla)], mode='basic') qc.rz(-weight_matrix[j][hidden - 1 - i], j) # bramka Hadamarda i pomiar na qubitach visible for i in range(visible): qc.h(i) qc.measure(list(range(visible)), list(range(visible))) ################################# #eksperyment: #symylator simulator = Aer.get_backend('qasm_simulator') # Execute the circuit on the qasm simulator job = execute(qc, simulator, shots=num_shots) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(qc) exp_ph = exctract_single_qubit_measurment(counts, list(range(visible, visible + hidden))) / num_shots # print("\nTotal count for hidden qubits '1' measurments are:",exctract_single_qubit_measurment(counts)) print("\nProbabilities are:",exp_ph) # print("\nTotal count for 0 and 1 are:",counts) print(weight_matrix) qc.draw() update(exp_ph)
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
mathelatics
import numpy as np import pylab from qiskit import BasicAer from qiskit.aqua.operators import WeightedPauliOperator from qiskit.aqua import QuantumInstance, aqua_globals from qiskit.aqua.algorithms import VQE, NumPyMinimumEigensolver from qiskit.aqua.components.initial_states import Zero from qiskit.aqua.components.optimizers import COBYLA, L_BFGS_B, SLSQP from qiskit.circuit.library import TwoLocal pauli_dict = { 'paulis': [{"coeff": {"imag": 0.0, "real": -1.052373245772859}, "label": "II"}, {"coeff": {"imag": 0.0, "real": 0.39793742484318045}, "label": "ZI"}, {"coeff": {"imag": 0.0, "real": -0.39793742484318045}, "label": "IZ"}, {"coeff": {"imag": 0.0, "real": -0.01128010425623538}, "label": "ZZ"}, {"coeff": {"imag": 0.0, "real": 0.18093119978423156}, "label": "XX"} ] } qubit_op = WeightedPauliOperator.from_dict(pauli_dict) optimizers = [COBYLA, L_BFGS_B, SLSQP] converge_cnts = np.empty([len(optimizers)], dtype=object) converge_vals = np.empty([len(optimizers)], dtype=object) num_qubits = qubit_op.num_qubits for i in range(len(optimizers)): aqua_globals.random_seed = 250 optimizer = optimizers[i]() print('\rOptimizer: {} '.format(type(optimizer).__name__), end='') init_state = Zero(num_qubits) var_form = TwoLocal(num_qubits, 'ry', 'cz', initial_state=init_state) counts = [] values = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) algo = VQE(qubit_op, var_form, optimizer, callback=store_intermediate_result) backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend=backend) algo_result = algo.run(quantum_instance) converge_cnts[i] = np.asarray(counts) converge_vals[i] = np.asarray(values) print('\rOptimization complete '); pylab.rcParams['figure.figsize'] = (12, 8) for i in range(len(optimizers)): pylab.plot(converge_cnts[i], converge_vals[i], label=optimizers[i].__name__) pylab.xlabel('Eval count') pylab.ylabel('Energy') pylab.title('Energy convergence for various optimizers') pylab.legend(loc='upper right') ee = NumPyMinimumEigensolver(qubit_op) result = ee.run() ref = result.eigenvalue.real print('Reference value: {}'.format(ref)) pylab.rcParams['figure.figsize'] = (12, 8) for i in range(len(optimizers)): pylab.plot(converge_cnts[i], abs(ref - converge_vals[i]), label=optimizers[i].__name__) pylab.xlabel('Eval count') pylab.ylabel('Energy difference from solution reference value') pylab.title('Energy convergence for various optimizers') pylab.yscale('log') pylab.legend(loc='upper right')
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) ### replaced x gate ### qc.x(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) ### replaced x gate ### qc.x(1) return qc
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# 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. """`_text_circuit_drawer` draws a circuit in ascii art""" import pathlib import os import tempfile import unittest.mock from codecs import encode from math import pi import numpy from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile from qiskit.circuit import Gate, Parameter, Qubit, Clbit, Instruction from qiskit.quantum_info.operators import SuperOp from qiskit.quantum_info.random import random_unitary from qiskit.test import QiskitTestCase from qiskit.transpiler.layout import Layout, TranspileLayout from qiskit.visualization import circuit_drawer from qiskit.visualization.circuit import text as elements from qiskit.visualization.circuit.circuit_visualization import _text_circuit_drawer from qiskit.extensions import UnitaryGate, HamiltonianGate from qiskit.extensions.quantum_initializer import UCGate from qiskit.circuit.library import ( HGate, U2Gate, U3Gate, XGate, CZGate, ZGate, YGate, U1Gate, SwapGate, RZZGate, CU3Gate, CU1Gate, CPhaseGate, ) from qiskit.transpiler.passes import ApplyLayout from qiskit.utils.optionals import HAS_TWEEDLEDUM from .visualization import path_to_diagram_reference, QiskitVisualizationTestCase if HAS_TWEEDLEDUM: from qiskit.circuit.classicalfunction import classical_function from qiskit.circuit.classicalfunction.types import Int1 class TestTextDrawerElement(QiskitTestCase): """Draw each element""" def assertEqualElement(self, expected, element): """ Asserts the top,mid,bot trio Args: expected (list[top,mid,bot]): What is expected. element (DrawElement): The element to check. """ try: encode("\n".join(expected), encoding="cp437") except UnicodeEncodeError: self.fail("_text_circuit_drawer() should only use extended ascii (aka code page 437).") self.assertEqual(expected[0], element.top) self.assertEqual(expected[1], element.mid) self.assertEqual(expected[2], element.bot) def test_measure_to(self): """MeasureTo element.""" element = elements.MeasureTo() # fmt: off expected = [" ║ ", "═╩═", " "] # fmt: on self.assertEqualElement(expected, element) def test_measure_to_label(self): """MeasureTo element with cregbundle""" element = elements.MeasureTo("1") # fmt: off expected = [" ║ ", "═╩═", " 1 "] # fmt: on self.assertEqualElement(expected, element) def test_measure_from(self): """MeasureFrom element.""" element = elements.MeasureFrom() # fmt: off expected = ["┌─┐", "┤M├", "└╥┘"] # fmt: on self.assertEqualElement(expected, element) def test_text_empty(self): """The empty circuit.""" expected = "" circuit = QuantumCircuit() self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_pager(self): """The pager breaks the circuit when the drawing does not fit in the console.""" expected = "\n".join( [ " ┌───┐ »", "q_0: |0>┤ X ├──■──»", " └─┬─┘┌─┴─┐»", "q_1: |0>──■──┤ X ├»", " └───┘»", " c: 0 1/══════════»", " »", "« ┌─┐┌───┐ »", "«q_0: ┤M├┤ X ├──■──»", "« └╥┘└─┬─┘┌─┴─┐»", "«q_1: ─╫───■──┤ X ├»", "« ║ └───┘»", "«c: 1/═╩═══════════»", "« 0 »", "« ┌─┐┌───┐ ", "«q_0: ┤M├┤ X ├──■──", "« └╥┘└─┬─┘┌─┴─┐", "«q_1: ─╫───■──┤ X ├", "« ║ └───┘", "«c: 1/═╩═══════════", "« 0 ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) circuit.cx(qr[1], qr[0]) circuit.cx(qr[0], qr[1]) circuit.measure(qr[0], cr[0]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[0], qr[1]) circuit.measure(qr[0], cr[0]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[0], qr[1]) self.assertEqual(str(_text_circuit_drawer(circuit, fold=20)), expected) def test_text_no_pager(self): """The pager can be disable.""" qr = QuantumRegister(1, "q") circuit = QuantumCircuit(qr) for _ in range(100): circuit.h(qr[0]) amount_of_lines = str(_text_circuit_drawer(circuit, fold=-1)).count("\n") self.assertEqual(amount_of_lines, 2) class TestTextDrawerGatesInCircuit(QiskitTestCase): """Gate by gate checks in different settings.""" def test_text_measure_cregbundle(self): """The measure operator, using 3-bit-length registers with cregbundle=True.""" expected = "\n".join( [ " ┌─┐ ", "q_0: |0>┤M├──────", " └╥┘┌─┐ ", "q_1: |0>─╫─┤M├───", " ║ └╥┘┌─┐", "q_2: |0>─╫──╫─┤M├", " ║ ║ └╥┘", " c: 0 3/═╩══╩══╩═", " 0 1 2 ", ] ) qr = QuantumRegister(3, "q") cr = ClassicalRegister(3, "c") circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_measure_cregbundle_2(self): """The measure operator, using 2 classical registers with cregbundle=True.""" expected = "\n".join( [ " ┌─┐ ", "q_0: |0>┤M├───", " └╥┘┌─┐", "q_1: |0>─╫─┤M├", " ║ └╥┘", "cA: 0 1/═╩══╬═", " 0 ║ ", "cB: 0 1/════╩═", " 0 ", ] ) qr = QuantumRegister(2, "q") cr_a = ClassicalRegister(1, "cA") cr_b = ClassicalRegister(1, "cB") circuit = QuantumCircuit(qr, cr_a, cr_b) circuit.measure(qr[0], cr_a[0]) circuit.measure(qr[1], cr_b[0]) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_measure_1(self): """The measure operator, using 3-bit-length registers.""" expected = "\n".join( [ " ┌─┐ ", "q_0: |0>┤M├──────", " └╥┘┌─┐ ", "q_1: |0>─╫─┤M├───", " ║ └╥┘┌─┐", "q_2: |0>─╫──╫─┤M├", " ║ ║ └╥┘", " c_0: 0 ═╩══╬══╬═", " ║ ║ ", " c_1: 0 ════╩══╬═", " ║ ", " c_2: 0 ═══════╩═", " ", ] ) qr = QuantumRegister(3, "q") cr = ClassicalRegister(3, "c") circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_measure_1_reverse_bits(self): """The measure operator, using 3-bit-length registers, with reverse_bits""" expected = "\n".join( [ " ┌─┐", "q_2: |0>──────┤M├", " ┌─┐└╥┘", "q_1: |0>───┤M├─╫─", " ┌─┐└╥┘ ║ ", "q_0: |0>┤M├─╫──╫─", " └╥┘ ║ ║ ", " c: 0 3/═╩══╩══╩═", " 0 1 2 ", ] ) qr = QuantumRegister(3, "q") cr = ClassicalRegister(3, "c") circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_text_measure_2(self): """The measure operator, using some registers.""" expected = "\n".join( [ " ", "q1_0: |0>──────", " ", "q1_1: |0>──────", " ┌─┐ ", "q2_0: |0>┤M├───", " └╥┘┌─┐", "q2_1: |0>─╫─┤M├", " ║ └╥┘", " c1: 0 2/═╬══╬═", " ║ ║ ", " c2: 0 2/═╩══╩═", " 0 1 ", ] ) qr1 = QuantumRegister(2, "q1") cr1 = ClassicalRegister(2, "c1") qr2 = QuantumRegister(2, "q2") cr2 = ClassicalRegister(2, "c2") circuit = QuantumCircuit(qr1, qr2, cr1, cr2) circuit.measure(qr2, cr2) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_measure_2_reverse_bits(self): """The measure operator, using some registers, with reverse_bits""" expected = "\n".join( [ " ┌─┐", "q2_1: |0>───┤M├", " ┌─┐└╥┘", "q2_0: |0>┤M├─╫─", " └╥┘ ║ ", "q1_1: |0>─╫──╫─", " ║ ║ ", "q1_0: |0>─╫──╫─", " ║ ║ ", " c2: 0 2/═╩══╩═", " 0 1 ", " c1: 0 2/══════", " ", ] ) qr1 = QuantumRegister(2, "q1") cr1 = ClassicalRegister(2, "c1") qr2 = QuantumRegister(2, "q2") cr2 = ClassicalRegister(2, "c2") circuit = QuantumCircuit(qr1, qr2, cr1, cr2) circuit.measure(qr2, cr2) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_wire_order(self): """Test the wire_order option""" expected = "\n".join( [ " ", "q_2: |0>────────────", " ┌───┐ ", "q_1: |0>┤ X ├───────", " ├───┤ ┌───┐ ", "q_3: |0>┤ H ├─┤ X ├─", " ├───┤ └─╥─┘ ", "q_0: |0>┤ H ├───╫───", " └───┘┌──╨──┐", " c: 0 4/═════╡ 0xa ╞", " └─────┘", "ca: 0 2/════════════", " ", ] ) qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") cr2 = ClassicalRegister(2, "ca") circuit = QuantumCircuit(qr, cr, cr2) circuit.h(0) circuit.h(3) circuit.x(1) circuit.x(3).c_if(cr, 10) self.assertEqual( str(_text_circuit_drawer(circuit, wire_order=[2, 1, 3, 0, 6, 8, 9, 5, 4, 7])), expected ) def test_text_swap(self): """Swap drawing.""" expected = "\n".join( [ " ", "q1_0: |0>─X────", " │ ", "q1_1: |0>─┼──X─", " │ │ ", "q2_0: |0>─X──┼─", " │ ", "q2_1: |0>────X─", " ", ] ) qr1 = QuantumRegister(2, "q1") qr2 = QuantumRegister(2, "q2") circuit = QuantumCircuit(qr1, qr2) circuit.swap(qr1, qr2) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_swap_reverse_bits(self): """Swap drawing with reverse_bits.""" expected = "\n".join( [ " ", "q2_1: |0>────X─", " │ ", "q2_0: |0>─X──┼─", " │ │ ", "q1_1: |0>─┼──X─", " │ ", "q1_0: |0>─X────", " ", ] ) qr1 = QuantumRegister(2, "q1") qr2 = QuantumRegister(2, "q2") circuit = QuantumCircuit(qr1, qr2) circuit.swap(qr1, qr2) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_text_reverse_bits_read_from_config(self): """Swap drawing with reverse_bits set in the configuration file.""" expected_forward = "\n".join( [ " ", "q1_0: ─X────", " │ ", "q1_1: ─┼──X─", " │ │ ", "q2_0: ─X──┼─", " │ ", "q2_1: ────X─", " ", ] ) expected_reverse = "\n".join( [ " ", "q2_1: ────X─", " │ ", "q2_0: ─X──┼─", " │ │ ", "q1_1: ─┼──X─", " │ ", "q1_0: ─X────", " ", ] ) qr1 = QuantumRegister(2, "q1") qr2 = QuantumRegister(2, "q2") circuit = QuantumCircuit(qr1, qr2) circuit.swap(qr1, qr2) self.assertEqual(str(circuit_drawer(circuit, output="text")), expected_forward) config_content = """ [default] circuit_reverse_bits = true """ with tempfile.TemporaryDirectory() as dir_path: file_path = pathlib.Path(dir_path) / "qiskit.conf" with open(file_path, "w") as fptr: fptr.write(config_content) with unittest.mock.patch.dict(os.environ, {"QISKIT_SETTINGS": str(file_path)}): test_reverse = str(circuit_drawer(circuit, output="text")) self.assertEqual(test_reverse, expected_reverse) def test_text_cswap(self): """CSwap drawing.""" expected = "\n".join( [ " ", "q_0: |0>─■──X──X─", " │ │ │ ", "q_1: |0>─X──■──X─", " │ │ │ ", "q_2: |0>─X──X──■─", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cswap(qr[0], qr[1], qr[2]) circuit.cswap(qr[1], qr[0], qr[2]) circuit.cswap(qr[2], qr[1], qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_cswap_reverse_bits(self): """CSwap drawing with reverse_bits.""" expected = "\n".join( [ " ", "q_2: |0>─X──X──■─", " │ │ │ ", "q_1: |0>─X──■──X─", " │ │ │ ", "q_0: |0>─■──X──X─", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cswap(qr[0], qr[1], qr[2]) circuit.cswap(qr[1], qr[0], qr[2]) circuit.cswap(qr[2], qr[1], qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_text_cu3(self): """cu3 drawing.""" expected = "\n".join( [ " ┌─────────────────┐", "q_0: |0>─────────■─────────┤ U3(π/2,π/2,π/2) ├", " ┌────────┴────────┐└────────┬────────┘", "q_1: |0>┤ U3(π/2,π/2,π/2) ├─────────┼─────────", " └─────────────────┘ │ ", "q_2: |0>────────────────────────────■─────────", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[0], qr[1]]) circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[2], qr[0]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_cu3_reverse_bits(self): """cu3 drawing with reverse_bits""" expected = "\n".join( [ " ", "q_2: |0>────────────────────────────■─────────", " ┌─────────────────┐ │ ", "q_1: |0>┤ U3(π/2,π/2,π/2) ├─────────┼─────────", " └────────┬────────┘┌────────┴────────┐", "q_0: |0>─────────■─────────┤ U3(π/2,π/2,π/2) ├", " └─────────────────┘", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[0], qr[1]]) circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[2], qr[0]]) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_text_crz(self): """crz drawing.""" expected = "\n".join( [ " ┌─────────┐", "q_0: |0>─────■─────┤ Rz(π/2) ├", " ┌────┴────┐└────┬────┘", "q_1: |0>┤ Rz(π/2) ├─────┼─────", " └─────────┘ │ ", "q_2: |0>────────────────■─────", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.crz(pi / 2, qr[0], qr[1]) circuit.crz(pi / 2, qr[2], qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_cry(self): """cry drawing.""" expected = "\n".join( [ " ┌─────────┐", "q_0: |0>─────■─────┤ Ry(π/2) ├", " ┌────┴────┐└────┬────┘", "q_1: |0>┤ Ry(π/2) ├─────┼─────", " └─────────┘ │ ", "q_2: |0>────────────────■─────", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cry(pi / 2, qr[0], qr[1]) circuit.cry(pi / 2, qr[2], qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_crx(self): """crx drawing.""" expected = "\n".join( [ " ┌─────────┐", "q_0: |0>─────■─────┤ Rx(π/2) ├", " ┌────┴────┐└────┬────┘", "q_1: |0>┤ Rx(π/2) ├─────┼─────", " └─────────┘ │ ", "q_2: |0>────────────────■─────", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.crx(pi / 2, qr[0], qr[1]) circuit.crx(pi / 2, qr[2], qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_cx(self): """cx drawing.""" expected = "\n".join( [ " ┌───┐", "q_0: |0>──■──┤ X ├", " ┌─┴─┐└─┬─┘", "q_1: |0>┤ X ├──┼──", " └───┘ │ ", "q_2: |0>───────■──", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[2], qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_cy(self): """cy drawing.""" expected = "\n".join( [ " ┌───┐", "q_0: |0>──■──┤ Y ├", " ┌─┴─┐└─┬─┘", "q_1: |0>┤ Y ├──┼──", " └───┘ │ ", "q_2: |0>───────■──", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cy(qr[0], qr[1]) circuit.cy(qr[2], qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_cz(self): """cz drawing.""" expected = "\n".join( [ " ", "q_0: |0>─■──■─", " │ │ ", "q_1: |0>─■──┼─", " │ ", "q_2: |0>────■─", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cz(qr[0], qr[1]) circuit.cz(qr[2], qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_ch(self): """ch drawing.""" expected = "\n".join( [ " ┌───┐", "q_0: |0>──■──┤ H ├", " ┌─┴─┐└─┬─┘", "q_1: |0>┤ H ├──┼──", " └───┘ │ ", "q_2: |0>───────■──", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.ch(qr[0], qr[1]) circuit.ch(qr[2], qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_rzz(self): """rzz drawing. See #1957""" expected = "\n".join( [ " ", "q_0: |0>─■────────────────", " │ZZ(0) ", "q_1: |0>─■───────■────────", " │ZZ(π/2) ", "q_2: |0>─────────■────────", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.rzz(0, qr[0], qr[1]) circuit.rzz(pi / 2, qr[2], qr[1]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_cu1(self): """cu1 drawing.""" expected = "\n".join( [ " ", "q_0: |0>─■─────────■────────", " │U1(π/2) │ ", "q_1: |0>─■─────────┼────────", " │U1(π/2) ", "q_2: |0>───────────■────────", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(CU1Gate(pi / 2), [qr[0], qr[1]]) circuit.append(CU1Gate(pi / 2), [qr[2], qr[0]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_cp(self): """cp drawing.""" expected = "\n".join( [ " ", "q_0: |0>─■────────■───────", " │P(π/2) │ ", "q_1: |0>─■────────┼───────", " │P(π/2) ", "q_2: |0>──────────■───────", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]]) circuit.append(CPhaseGate(pi / 2), [qr[2], qr[0]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_cu1_condition(self): """Test cu1 with condition""" expected = "\n".join( [ " ", "q_0: ────────■────────", " │U1(π/2) ", "q_1: ────────■────────", " ║ ", "q_2: ────────╫────────", " ┌────╨────┐ ", "c: 3/═══╡ c_1=0x1 ╞═══", " └─────────┘ ", ] ) qr = QuantumRegister(3, "q") cr = ClassicalRegister(3, "c") circuit = QuantumCircuit(qr, cr) circuit.append(CU1Gate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1) self.assertEqual(str(_text_circuit_drawer(circuit, initial_state=False)), expected) def test_text_rzz_condition(self): """Test rzz with condition""" expected = "\n".join( [ " ", "q_0: ────────■────────", " │ZZ(π/2) ", "q_1: ────────■────────", " ║ ", "q_2: ────────╫────────", " ┌────╨────┐ ", "c: 3/═══╡ c_1=0x1 ╞═══", " └─────────┘ ", ] ) qr = QuantumRegister(3, "q") cr = ClassicalRegister(3, "c") circuit = QuantumCircuit(qr, cr) circuit.append(RZZGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1) self.assertEqual(str(_text_circuit_drawer(circuit, initial_state=False)), expected) def test_text_cp_condition(self): """Test cp with condition""" expected = "\n".join( [ " ", "q_0: ───────■───────", " │P(π/2) ", "q_1: ───────■───────", " ║ ", "q_2: ───────╫───────", " ┌────╨────┐ ", "c: 3/══╡ c_1=0x1 ╞══", " └─────────┘ ", ] ) qr = QuantumRegister(3, "q") cr = ClassicalRegister(3, "c") circuit = QuantumCircuit(qr, cr) circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1) self.assertEqual(str(_text_circuit_drawer(circuit, initial_state=False)), expected) def test_text_cu1_reverse_bits(self): """cu1 drawing with reverse_bits""" expected = "\n".join( [ " ", "q_2: |0>───────────■────────", " │ ", "q_1: |0>─■─────────┼────────", " │U1(π/2) │U1(π/2) ", "q_0: |0>─■─────────■────────", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(CU1Gate(pi / 2), [qr[0], qr[1]]) circuit.append(CU1Gate(pi / 2), [qr[2], qr[0]]) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_text_ccx(self): """cx drawing.""" expected = "\n".join( [ " ┌───┐", "q_0: |0>──■────■──┤ X ├", " │ ┌─┴─┐└─┬─┘", "q_1: |0>──■──┤ X ├──■──", " ┌─┴─┐└─┬─┘ │ ", "q_2: |0>┤ X ├──■────■──", " └───┘ ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.ccx(qr[0], qr[1], qr[2]) circuit.ccx(qr[2], qr[0], qr[1]) circuit.ccx(qr[2], qr[1], qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_reset(self): """Reset drawing.""" expected = "\n".join( [ " ", "q1_0: |0>─|0>─", " ", "q1_1: |0>─|0>─", " ", "q2_0: |0>─────", " ", "q2_1: |0>─|0>─", " ", ] ) qr1 = QuantumRegister(2, "q1") qr2 = QuantumRegister(2, "q2") circuit = QuantumCircuit(qr1, qr2) circuit.reset(qr1) circuit.reset(qr2[1]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_single_gate(self): """Single Qbit gate drawing.""" expected = "\n".join( [ " ┌───┐", "q1_0: |0>┤ H ├", " ├───┤", "q1_1: |0>┤ H ├", " └───┘", "q2_0: |0>─────", " ┌───┐", "q2_1: |0>┤ H ├", " └───┘", ] ) qr1 = QuantumRegister(2, "q1") qr2 = QuantumRegister(2, "q2") circuit = QuantumCircuit(qr1, qr2) circuit.h(qr1) circuit.h(qr2[1]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_id(self): """Id drawing.""" expected = "\n".join( [ " ┌───┐", "q1_0: |0>┤ I ├", " ├───┤", "q1_1: |0>┤ I ├", " └───┘", "q2_0: |0>─────", " ┌───┐", "q2_1: |0>┤ I ├", " └───┘", ] ) qr1 = QuantumRegister(2, "q1") qr2 = QuantumRegister(2, "q2") circuit = QuantumCircuit(qr1, qr2) circuit.id(qr1) circuit.id(qr2[1]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_barrier(self): """Barrier drawing.""" expected = "\n".join( [ " ░ ", "q1_0: |0>─░─", " ░ ", "q1_1: |0>─░─", " ░ ", "q2_0: |0>───", " ░ ", "q2_1: |0>─░─", " ░ ", ] ) qr1 = QuantumRegister(2, "q1") qr2 = QuantumRegister(2, "q2") circuit = QuantumCircuit(qr1, qr2) circuit.barrier(qr1) circuit.barrier(qr2[1]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_no_barriers(self): """Drawing without plotbarriers.""" expected = "\n".join( [ " ┌───┐ ", "q1_0: |0>┤ H ├─────", " ├───┤ ", "q1_1: |0>┤ H ├─────", " ├───┤ ", "q2_0: |0>┤ H ├─────", " └───┘┌───┐", "q2_1: |0>─────┤ H ├", " └───┘", ] ) qr1 = QuantumRegister(2, "q1") qr2 = QuantumRegister(2, "q2") circuit = QuantumCircuit(qr1, qr2) circuit.h(qr1) circuit.barrier(qr1) circuit.barrier(qr2[1]) circuit.h(qr2) self.assertEqual(str(_text_circuit_drawer(circuit, plot_barriers=False)), expected) def test_text_measure_html(self): """The measure operator. HTML representation.""" expected = "\n".join( [ '<pre style="word-wrap: normal;' "white-space: pre;" "background: #fff0;" "line-height: 1.1;" 'font-family: &quot;Courier New&quot;,Courier,monospace">' " ┌─┐", " q: |0>┤M├", " └╥┘", "c: 0 1/═╩═", " 0 </pre>", ] ) qr = QuantumRegister(1, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) self.assertEqual(_text_circuit_drawer(circuit)._repr_html_(), expected) def test_text_repr(self): """The measure operator. repr.""" expected = "\n".join( [ " ┌─┐", " q: |0>┤M├", " └╥┘", "c: 0 1/═╩═", " 0 ", ] ) qr = QuantumRegister(1, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) self.assertEqual(_text_circuit_drawer(circuit).__repr__(), expected) def test_text_justify_left(self): """Drawing with left justify""" expected = "\n".join( [ " ┌───┐ ", "q1_0: |0>┤ X ├───", " ├───┤┌─┐", "q1_1: |0>┤ H ├┤M├", " └───┘└╥┘", " c1: 0 2/══════╩═", " 1 ", ] ) qr1 = QuantumRegister(2, "q1") cr1 = ClassicalRegister(2, "c1") circuit = QuantumCircuit(qr1, cr1) circuit.x(qr1[0]) circuit.h(qr1[1]) circuit.measure(qr1[1], cr1[1]) self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected) def test_text_justify_right(self): """Drawing with right justify""" expected = "\n".join( [ " ┌───┐", "q1_0: |0>─────┤ X ├", " ┌───┐└┬─┬┘", "q1_1: |0>┤ H ├─┤M├─", " └───┘ └╥┘ ", " c1: 0 2/═══════╩══", " 1 ", ] ) qr1 = QuantumRegister(2, "q1") cr1 = ClassicalRegister(2, "c1") circuit = QuantumCircuit(qr1, cr1) circuit.x(qr1[0]) circuit.h(qr1[1]) circuit.measure(qr1[1], cr1[1]) self.assertEqual(str(_text_circuit_drawer(circuit, justify="right")), expected) def test_text_justify_none(self): """Drawing with none justify""" expected = "\n".join( [ " ┌───┐ ", "q1_0: |0>┤ X ├────────", " └───┘┌───┐┌─┐", "q1_1: |0>─────┤ H ├┤M├", " └───┘└╥┘", " c1: 0 2/═══════════╩═", " 1 ", ] ) qr1 = QuantumRegister(2, "q1") cr1 = ClassicalRegister(2, "c1") circuit = QuantumCircuit(qr1, cr1) circuit.x(qr1[0]) circuit.h(qr1[1]) circuit.measure(qr1[1], cr1[1]) self.assertEqual(str(_text_circuit_drawer(circuit, justify="none")), expected) def test_text_justify_left_barrier(self): """Left justify respects barriers""" expected = "\n".join( [ " ┌───┐ ░ ", "q1_0: |0>┤ H ├─░──────", " └───┘ ░ ┌───┐", "q1_1: |0>──────░─┤ H ├", " ░ └───┘", ] ) qr1 = QuantumRegister(2, "q1") circuit = QuantumCircuit(qr1) circuit.h(qr1[0]) circuit.barrier(qr1) circuit.h(qr1[1]) self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected) def test_text_justify_right_barrier(self): """Right justify respects barriers""" expected = "\n".join( [ " ┌───┐ ░ ", "q1_0: |0>┤ H ├─░──────", " └───┘ ░ ┌───┐", "q1_1: |0>──────░─┤ H ├", " ░ └───┘", ] ) qr1 = QuantumRegister(2, "q1") circuit = QuantumCircuit(qr1) circuit.h(qr1[0]) circuit.barrier(qr1) circuit.h(qr1[1]) self.assertEqual(str(_text_circuit_drawer(circuit, justify="right")), expected) def test_text_barrier_label(self): """Show barrier label""" expected = "\n".join( [ " ┌───┐ ░ ┌───┐ End Y/X ", "q_0: |0>┤ X ├─░─┤ Y ├────░────", " ├───┤ ░ ├───┤ ░ ", "q_1: |0>┤ Y ├─░─┤ X ├────░────", " └───┘ ░ └───┘ ░ ", ] ) qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.x(0) circuit.y(1) circuit.barrier() circuit.y(0) circuit.x(1) circuit.barrier(label="End Y/X") self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_overlap_cx(self): """Overlapping CX gates are drawn not overlapping""" expected = "\n".join( [ " ", "q1_0: |0>──■───────", " │ ", "q1_1: |0>──┼────■──", " │ ┌─┴─┐", "q1_2: |0>──┼──┤ X ├", " ┌─┴─┐└───┘", "q1_3: |0>┤ X ├─────", " └───┘ ", ] ) qr1 = QuantumRegister(4, "q1") circuit = QuantumCircuit(qr1) circuit.cx(qr1[0], qr1[3]) circuit.cx(qr1[1], qr1[2]) self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected) def test_text_overlap_measure(self): """Measure is drawn not overlapping""" expected = "\n".join( [ " ┌─┐ ", "q1_0: |0>┤M├─────", " └╥┘┌───┐", "q1_1: |0>─╫─┤ X ├", " ║ └───┘", " c1: 0 2/═╩══════", " 0 ", ] ) qr1 = QuantumRegister(2, "q1") cr1 = ClassicalRegister(2, "c1") circuit = QuantumCircuit(qr1, cr1) circuit.measure(qr1[0], cr1[0]) circuit.x(qr1[1]) self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected) def test_text_overlap_swap(self): """Swap is drawn in 2 separate columns""" expected = "\n".join( [ " ", "q1_0: |0>─X────", " │ ", "q1_1: |0>─┼──X─", " │ │ ", "q2_0: |0>─X──┼─", " │ ", "q2_1: |0>────X─", " ", ] ) qr1 = QuantumRegister(2, "q1") qr2 = QuantumRegister(2, "q2") circuit = QuantumCircuit(qr1, qr2) circuit.swap(qr1, qr2) self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected) def test_text_justify_right_measure_resize(self): """Measure gate can resize if necessary""" expected = "\n".join( [ " ┌───┐", "q1_0: |0>┤ X ├", " └┬─┬┘", "q1_1: |0>─┤M├─", " └╥┘ ", " c1: 0 2/══╩══", " 1 ", ] ) qr1 = QuantumRegister(2, "q1") cr1 = ClassicalRegister(2, "c1") circuit = QuantumCircuit(qr1, cr1) circuit.x(qr1[0]) circuit.measure(qr1[1], cr1[1]) self.assertEqual(str(_text_circuit_drawer(circuit, justify="right")), expected) def test_text_box_length(self): """The length of boxes is independent of other boxes in the layer https://github.com/Qiskit/qiskit-terra/issues/1882""" expected = "\n".join( [ " ┌───┐ ┌───┐", "q1_0: |0>────┤ H ├────┤ H ├", " └───┘ └───┘", "q1_1: |0>──────────────────", " ┌───────────┐ ", "q1_2: |0>┤ Rz(1e-07) ├─────", " └───────────┘ ", ] ) qr = QuantumRegister(3, "q1") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.rz(0.0000001, qr[2]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_spacing_2378(self): """Small gates in the same layer as long gates. See https://github.com/Qiskit/qiskit-terra/issues/2378""" expected = "\n".join( [ " ", "q_0: |0>──────X──────", " │ ", "q_1: |0>──────X──────", " ┌───────────┐", "q_2: |0>┤ Rz(11111) ├", " └───────────┘", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.swap(qr[0], qr[1]) circuit.rz(11111, qr[2]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) @unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.") def test_text_synth_no_registerless(self): """Test synthesis's label when registerless=False. See https://github.com/Qiskit/qiskit-terra/issues/9363""" expected = "\n".join( [ " ", " a: |0>──■──", " │ ", " b: |0>──■──", " │ ", " c: |0>──o──", " ┌─┴─┐", "return: |0>┤ X ├", " └───┘", ] ) @classical_function def grover_oracle(a: Int1, b: Int1, c: Int1) -> Int1: return a and b and not c circuit = grover_oracle.synth(registerless=False) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) class TestTextDrawerLabels(QiskitTestCase): """Gates with labels.""" def test_label(self): """Test a gate with a label.""" # fmt: off expected = "\n".join([" ┌───────────┐", "q: |0>┤ an H gate ├", " └───────────┘"]) # fmt: on circuit = QuantumCircuit(1) circuit.append(HGate(label="an H gate"), [0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_gate_with_label(self): """Test a controlled gate-with-a-label.""" expected = "\n".join( [ " ", "q_0: |0>──────■──────", " ┌─────┴─────┐", "q_1: |0>┤ an H gate ├", " └───────────┘", ] ) circuit = QuantumCircuit(2) circuit.append(HGate(label="an H gate").control(1), [0, 1]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_label_on_controlled_gate(self): """Test a controlled gate with a label (as a as a whole).""" expected = "\n".join( [ " a controlled H gate ", "q_0: |0>──────────■──────────", " ┌─┴─┐ ", "q_1: |0>────────┤ H ├────────", " └───┘ ", ] ) circuit = QuantumCircuit(2) circuit.append(HGate().control(1, label="a controlled H gate"), [0, 1]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_rzz_on_wide_layer(self): """Test a labeled gate (RZZ) in a wide layer. See https://github.com/Qiskit/qiskit-terra/issues/4838""" expected = "\n".join( [ " ", "q_0: |0>────────────────■──────────────────────", " │ZZ(π/2) ", "q_1: |0>────────────────■──────────────────────", " ┌─────────────────────────────────────┐", "q_2: |0>┤ This is a really long long long box ├", " └─────────────────────────────────────┘", ] ) circuit = QuantumCircuit(3) circuit.rzz(pi / 2, 0, 1) circuit.x(2, label="This is a really long long long box") self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_cu1_on_wide_layer(self): """Test a labeled gate (CU1) in a wide layer. See https://github.com/Qiskit/qiskit-terra/issues/4838""" expected = "\n".join( [ " ", "q_0: |0>────────────────■──────────────────────", " │U1(π/2) ", "q_1: |0>────────────────■──────────────────────", " ┌─────────────────────────────────────┐", "q_2: |0>┤ This is a really long long long box ├", " └─────────────────────────────────────┘", ] ) circuit = QuantumCircuit(3) circuit.append(CU1Gate(pi / 2), [0, 1]) circuit.x(2, label="This is a really long long long box") self.assertEqual(str(_text_circuit_drawer(circuit)), expected) class TestTextDrawerMultiQGates(QiskitTestCase): """Gates implying multiple qubits.""" def test_2Qgate(self): """2Q no params.""" expected = "\n".join( [ " ┌───────┐", "q_1: |0>┤1 ├", " │ twoQ │", "q_0: |0>┤0 ├", " └───────┘", ] ) qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) my_gate2 = Gate(name="twoQ", num_qubits=2, params=[], label="twoQ") circuit.append(my_gate2, [qr[0], qr[1]]) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_2Qgate_cross_wires(self): """2Q no params, with cross wires""" expected = "\n".join( [ " ┌───────┐", "q_1: |0>┤0 ├", " │ twoQ │", "q_0: |0>┤1 ├", " └───────┘", ] ) qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) my_gate2 = Gate(name="twoQ", num_qubits=2, params=[], label="twoQ") circuit.append(my_gate2, [qr[1], qr[0]]) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_3Qgate_cross_wires(self): """3Q no params, with cross wires""" expected = "\n".join( [ " ┌─────────┐", "q_2: |0>┤1 ├", " │ │", "q_1: |0>┤0 threeQ ├", " │ │", "q_0: |0>┤2 ├", " └─────────┘", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) my_gate3 = Gate(name="threeQ", num_qubits=3, params=[], label="threeQ") circuit.append(my_gate3, [qr[1], qr[2], qr[0]]) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_2Qgate_nottogether(self): """2Q that are not together""" expected = "\n".join( [ " ┌───────┐", "q_2: |0>┤1 ├", " │ │", "q_1: |0>┤ twoQ ├", " │ │", "q_0: |0>┤0 ├", " └───────┘", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) my_gate2 = Gate(name="twoQ", num_qubits=2, params=[], label="twoQ") circuit.append(my_gate2, [qr[0], qr[2]]) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_2Qgate_nottogether_across_4(self): """2Q that are 2 bits apart""" expected = "\n".join( [ " ┌───────┐", "q_3: |0>┤1 ├", " │ │", "q_2: |0>┤ ├", " │ twoQ │", "q_1: |0>┤ ├", " │ │", "q_0: |0>┤0 ├", " └───────┘", ] ) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) my_gate2 = Gate(name="twoQ", num_qubits=2, params=[], label="twoQ") circuit.append(my_gate2, [qr[0], qr[3]]) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_unitary_nottogether_across_4(self): """unitary that are 2 bits apart""" expected = "\n".join( [ " ┌──────────┐", "q_0: |0>┤0 ├", " │ │", "q_1: |0>┤ ├", " │ Unitary │", "q_2: |0>┤ ├", " │ │", "q_3: |0>┤1 ├", " └──────────┘", ] ) qr = QuantumRegister(4, "q") qc = QuantumCircuit(qr) qc.append(random_unitary(4, seed=42), [qr[0], qr[3]]) self.assertEqual(str(_text_circuit_drawer(qc)), expected) def test_kraus(self): """Test Kraus. See https://github.com/Qiskit/qiskit-terra/pull/2238#issuecomment-487630014""" # fmt: off expected = "\n".join([" ┌───────┐", "q: |0>┤ kraus ├", " └───────┘"]) # fmt: on error = SuperOp(0.75 * numpy.eye(4) + 0.25 * numpy.diag([1, -1, -1, 1])) qr = QuantumRegister(1, name="q") qc = QuantumCircuit(qr) qc.append(error, [qr[0]]) self.assertEqual(str(_text_circuit_drawer(qc)), expected) def test_multiplexer(self): """Test Multiplexer. See https://github.com/Qiskit/qiskit-terra/pull/2238#issuecomment-487630014""" expected = "\n".join( [ " ┌──────────────┐", "q_0: |0>┤0 ├", " │ Multiplexer │", "q_1: |0>┤1 ├", " └──────────────┘", ] ) cx_multiplexer = UCGate([numpy.eye(2), numpy.array([[0, 1], [1, 0]])]) qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) qc.append(cx_multiplexer, [qr[0], qr[1]]) self.assertEqual(str(_text_circuit_drawer(qc)), expected) def test_label_over_name_2286(self): """If there is a label, it should be used instead of the name See https://github.com/Qiskit/qiskit-terra/issues/2286""" expected = "\n".join( [ " ┌───┐┌───────┐┌────────┐", "q_0: |0>┤ X ├┤ alt-X ├┤0 ├", " └───┘└───────┘│ iswap │", "q_1: |0>──────────────┤1 ├", " └────────┘", ] ) qr = QuantumRegister(2, "q") circ = QuantumCircuit(qr) circ.append(XGate(), [qr[0]]) circ.append(XGate(label="alt-X"), [qr[0]]) circ.append(UnitaryGate(numpy.eye(4), label="iswap"), [qr[0], qr[1]]) self.assertEqual(str(_text_circuit_drawer(circ)), expected) def test_label_turns_to_box_2286(self): """If there is a label, non-boxes turn into boxes See https://github.com/Qiskit/qiskit-terra/issues/2286""" expected = "\n".join( [ " cz label ", "q_0: |0>─■─────■─────", " │ │ ", "q_1: |0>─■─────■─────", " ", ] ) qr = QuantumRegister(2, "q") circ = QuantumCircuit(qr) circ.append(CZGate(), [qr[0], qr[1]]) circ.append(CZGate(label="cz label"), [qr[0], qr[1]]) self.assertEqual(str(_text_circuit_drawer(circ)), expected) def test_control_gate_with_base_label_4361(self): """Control gate has a label and a base gate with a label See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " ┌──────┐ my ch ┌──────┐", "q_0: |0>┤ my h ├───■────┤ my h ├", " └──────┘┌──┴───┐└──┬───┘", "q_1: |0>────────┤ my h ├───■────", " └──────┘ my ch ", ] ) qr = QuantumRegister(2, "q") circ = QuantumCircuit(qr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch") circ.append(hgate, [0]) circ.append(controlh, [0, 1]) circ.append(controlh, [1, 0]) self.assertEqual(str(_text_circuit_drawer(circ)), expected) def test_control_gate_label_with_cond_1_low(self): """Control gate has a label and a conditional (compression=low) See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " my ch ", "q_0: |0>───■────", " │ ", " ┌──┴───┐", "q_1: |0>┤ my h ├", " └──╥───┘", " ┌──╨──┐ ", " c: 0 1/╡ 0x1 ╞═", " └─────┘ ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch").c_if(cr, 1) circ.append(controlh, [0, 1]) self.assertEqual(str(_text_circuit_drawer(circ, vertical_compression="low")), expected) def test_control_gate_label_with_cond_1_low_cregbundle(self): """Control gate has a label and a conditional (compression=low) with cregbundle See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " my ch ", "q_0: |0>───■────", " │ ", " ┌──┴───┐", "q_1: |0>┤ my h ├", " └──╥───┘", " ┌──╨──┐ ", " c: 0 1/╡ 0x1 ╞═", " └─────┘ ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch").c_if(cr, 1) circ.append(controlh, [0, 1]) self.assertEqual( str(_text_circuit_drawer(circ, vertical_compression="low", cregbundle=True)), expected ) def test_control_gate_label_with_cond_1_med(self): """Control gate has a label and a conditional (compression=med) See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " my ch ", "q_0: |0>───■────", " ┌──┴───┐", "q_1: |0>┤ my h ├", " └──╥───┘", " c: 0 ═══■════", " 0x1 ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch").c_if(cr, 1) circ.append(controlh, [0, 1]) self.assertEqual( str(_text_circuit_drawer(circ, cregbundle=False, vertical_compression="medium")), expected, ) def test_control_gate_label_with_cond_1_med_cregbundle(self): """Control gate has a label and a conditional (compression=med) with cregbundle See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " my ch ", "q_0: |0>───■────", " ┌──┴───┐", "q_1: |0>┤ my h ├", " └──╥───┘", " ┌──╨──┐ ", " c: 0 1/╡ 0x1 ╞═", " └─────┘ ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch").c_if(cr, 1) circ.append(controlh, [0, 1]) self.assertEqual( str(_text_circuit_drawer(circ, vertical_compression="medium", cregbundle=True)), expected, ) def test_control_gate_label_with_cond_1_high(self): """Control gate has a label and a conditional (compression=high) See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " my ch ", "q_0: |0>───■────", " ┌──┴───┐", "q_1: |0>┤ my h ├", " └──╥───┘", " c: 0 ═══■════", " 0x1 ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch").c_if(cr, 1) circ.append(controlh, [0, 1]) self.assertEqual( str(_text_circuit_drawer(circ, cregbundle=False, vertical_compression="high")), expected ) def test_control_gate_label_with_cond_1_high_cregbundle(self): """Control gate has a label and a conditional (compression=high) with cregbundle See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " my ch ", "q_0: |0>───■────", " ┌──┴───┐", "q_1: |0>┤ my h ├", " ├──╨──┬┘", " c: 0 1/╡ 0x1 ╞═", " └─────┘ ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch").c_if(cr, 1) circ.append(controlh, [0, 1]) self.assertEqual( str(_text_circuit_drawer(circ, vertical_compression="high", cregbundle=True)), expected ) def test_control_gate_label_with_cond_2_med_space(self): """Control gate has a label and a conditional (on label, compression=med) See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " ┌──────┐", "q_0: |0>┤ my h ├", " └──┬───┘", "q_1: |0>───■────", " my ch ", " ┌──╨──┐ ", " c: 0 1/╡ 0x1 ╞═", " └─────┘ ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch").c_if(cr, 1) circ.append(controlh, [1, 0]) self.assertEqual(str(_text_circuit_drawer(circ, vertical_compression="medium")), expected) def test_control_gate_label_with_cond_2_med(self): """Control gate has a label and a conditional (on label, compression=med) See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " ┌──────┐ ", "q_0: |0>──┤ my h ├─", " └──┬───┘ ", "q_1: |0>─────■─────", " my ctrl-h ", " ║ ", " c: 0 ═════■═════", " 0x1 ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ctrl-h").c_if(cr, 1) circ.append(controlh, [1, 0]) self.assertEqual( str(_text_circuit_drawer(circ, cregbundle=False, vertical_compression="medium")), expected, ) def test_control_gate_label_with_cond_2_med_cregbundle(self): """Control gate has a label and a conditional (on label, compression=med) with cregbundle See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " ┌──────┐", "q_0: |0>┤ my h ├", " └──┬───┘", "q_1: |0>───■────", " my ch ", " ┌──╨──┐ ", " c: 0 1/╡ 0x1 ╞═", " └─────┘ ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch").c_if(cr, 1) circ.append(controlh, [1, 0]) self.assertEqual( str(_text_circuit_drawer(circ, vertical_compression="medium", cregbundle=True)), expected, ) def test_control_gate_label_with_cond_2_low(self): """Control gate has a label and a conditional (on label, compression=low) See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " ┌──────┐", "q_0: |0>┤ my h ├", " └──┬───┘", " │ ", "q_1: |0>───■────", " my ch ", " ║ ", " c: 0 ═══■════", " 0x1 ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch").c_if(cr, 1) circ.append(controlh, [1, 0]) self.assertEqual( str(_text_circuit_drawer(circ, cregbundle=False, vertical_compression="low")), expected ) def test_control_gate_label_with_cond_2_low_cregbundle(self): """Control gate has a label and a conditional (on label, compression=low) with cregbundle See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " ┌──────┐", "q_0: |0>┤ my h ├", " └──┬───┘", " │ ", "q_1: |0>───■────", " my ch ", " ┌──╨──┐ ", " c: 0 1/╡ 0x1 ╞═", " └─────┘ ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch").c_if(cr, 1) circ.append(controlh, [1, 0]) self.assertEqual( str(_text_circuit_drawer(circ, vertical_compression="low", cregbundle=True)), expected ) class TestTextDrawerParams(QiskitTestCase): """Test drawing parameters.""" def test_text_no_parameters(self): """Test drawing with no parameters""" expected = "\n".join( [ " ┌───┐", "q: |0>┤ X ├", " └───┘", ] ) qr = QuantumRegister(1, "q") circuit = QuantumCircuit(qr) circuit.x(0) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_parameters_mix(self): """cu3 drawing with parameters""" expected = "\n".join( [ " ", "q_0: |0>─────────■──────────", " ┌────────┴─────────┐", "q_1: |0>┤ U(π/2,theta,π,0) ├", " └──────────────────┘", ] ) qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.cu(pi / 2, Parameter("theta"), pi, 0, qr[0], qr[1]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_bound_parameters(self): """Bound parameters See: https://github.com/Qiskit/qiskit-terra/pull/3876""" # fmt: off expected = "\n".join([" ┌────────────┐", "qr: |0>┤ my_u2(π,π) ├", " └────────────┘"]) # fmt: on my_u2_circuit = QuantumCircuit(1, name="my_u2") phi = Parameter("phi") lam = Parameter("lambda") my_u2_circuit.u(3.141592653589793, phi, lam, 0) my_u2 = my_u2_circuit.to_gate() qr = QuantumRegister(1, name="qr") circuit = QuantumCircuit(qr, name="circuit") circuit.append(my_u2, [qr[0]]) circuit = circuit.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793}) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_pi_param_expr(self): """Text pi in circuit with parameter expression.""" expected = "\n".join( [ " ┌─────────────────────┐", "q: ┤ Rx((π - x)*(π - y)) ├", " └─────────────────────┘", ] ) x, y = Parameter("x"), Parameter("y") circuit = QuantumCircuit(1) circuit.rx((pi - x) * (pi - y), 0) self.assertEqual(circuit.draw(output="text").single_string(), expected) def test_text_utf8(self): """Test that utf8 characters work in windows CI env.""" # fmt: off expected = "\n".join([" ┌──────────┐", "q: ┤ U(0,φ,λ) ├", " └──────────┘"]) # fmt: on phi, lam = Parameter("φ"), Parameter("λ") circuit = QuantumCircuit(1) circuit.u(0, phi, lam, 0) self.assertEqual(circuit.draw(output="text").single_string(), expected) def test_text_ndarray_parameters(self): """Test that if params are type ndarray, params are not displayed.""" # fmt: off expected = "\n".join([" ┌─────────┐", "q: |0>┤ Unitary ├", " └─────────┘"]) # fmt: on qr = QuantumRegister(1, "q") circuit = QuantumCircuit(qr) circuit.unitary(numpy.array([[0, 1], [1, 0]]), 0) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_qc_parameters(self): """Test that if params are type QuantumCircuit, params are not displayed.""" expected = "\n".join( [ " ┌───────┐", "q_0: |0>┤0 ├", " │ name │", "q_1: |0>┤1 ├", " └───────┘", ] ) my_qc_param = QuantumCircuit(2) my_qc_param.h(0) my_qc_param.cx(0, 1) inst = Instruction("name", 2, 0, [my_qc_param]) qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.append(inst, [0, 1]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) class TestTextDrawerVerticalCompressionLow(QiskitTestCase): """Test vertical_compression='low'""" def test_text_conditional_1(self): """Conditional drawing with 1-bit-length regs.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[1]; creg c1[1]; if(c0==1) x q[0]; if(c1==1) x q[0]; """ expected = "\n".join( [ " ┌───┐┌───┐", "q: |0>┤ X ├┤ X ├", " └─╥─┘└─╥─┘", " ║ ║ ", "c0: 0 ══■════╬══", " 0x1 ║ ", " ║ ", "c1: 0 ═══════■══", " 0x1 ", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual( str(_text_circuit_drawer(circuit, cregbundle=False, vertical_compression="low")), expected, ) def test_text_conditional_1_bundle(self): """Conditional drawing with 1-bit-length regs.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[1]; creg c1[1]; if(c0==1) x q[0]; if(c1==1) x q[0]; """ expected = "\n".join( [ " ┌───┐ ┌───┐ ", " q: |0>─┤ X ├──┤ X ├─", " └─╥─┘ └─╥─┘ ", " ┌──╨──┐ ║ ", "c0: 0 1/╡ 0x1 ╞═══╬═══", " └─────┘ ║ ", " ┌──╨──┐", "c1: 0 1/═══════╡ 0x1 ╞", " └─────┘", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual( str(_text_circuit_drawer(circuit, vertical_compression="low", cregbundle=True)), expected, ) def test_text_conditional_reverse_bits_true(self): """Conditional drawing with 1-bit-length regs.""" cr = ClassicalRegister(2, "cr") cr2 = ClassicalRegister(1, "cr2") qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr, cr, cr2) circuit.h(0) circuit.h(1) circuit.h(2) circuit.x(0) circuit.x(0) circuit.measure(2, 1) circuit.x(2).c_if(cr, 2) expected = "\n".join( [ " ┌───┐ ┌─┐ ┌───┐", "qr_2: |0>┤ H ├─────┤M├─────┤ X ├", " └───┘ └╥┘ └─╥─┘", " ┌───┐ ║ ║ ", "qr_1: |0>┤ H ├──────╫────────╫──", " └───┘ ║ ║ ", " ┌───┐┌───┐ ║ ┌───┐ ║ ", "qr_0: |0>┤ H ├┤ X ├─╫─┤ X ├──╫──", " └───┘└───┘ ║ └───┘ ║ ", " ║ ║ ", " cr2: 0 ═══════════╬════════╬══", " ║ ║ ", " ║ ║ ", " cr_1: 0 ═══════════╩════════■══", " ║ ", " ║ ", " cr_0: 0 ════════════════════o══", " 0x2 ", ] ) self.assertEqual( str( _text_circuit_drawer( circuit, vertical_compression="low", cregbundle=False, reverse_bits=True ) ), expected, ) def test_text_conditional_reverse_bits_false(self): """Conditional drawing with 1-bit-length regs.""" cr = ClassicalRegister(2, "cr") cr2 = ClassicalRegister(1, "cr2") qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr, cr, cr2) circuit.h(0) circuit.h(1) circuit.h(2) circuit.x(0) circuit.x(0) circuit.measure(2, 1) circuit.x(2).c_if(cr, 2) expected = "\n".join( [ " ┌───┐┌───┐┌───┐", "qr_0: |0>┤ H ├┤ X ├┤ X ├", " └───┘└───┘└───┘", " ┌───┐ ", "qr_1: |0>┤ H ├──────────", " └───┘ ", " ┌───┐ ┌─┐ ┌───┐", "qr_2: |0>┤ H ├─┤M├─┤ X ├", " └───┘ └╥┘ └─╥─┘", " ║ ║ ", " cr_0: 0 ═══════╬════o══", " ║ ║ ", " ║ ║ ", " cr_1: 0 ═══════╩════■══", " 0x2 ", " ", " cr2: 0 ═══════════════", " ", ] ) self.assertEqual( str( _text_circuit_drawer( circuit, vertical_compression="low", cregbundle=False, reverse_bits=False ) ), expected, ) def test_text_justify_right(self): """Drawing with right justify""" expected = "\n".join( [ " ┌───┐", "q1_0: |0>─────┤ X ├", " └───┘", " ┌───┐ ┌─┐ ", "q1_1: |0>┤ H ├─┤M├─", " └───┘ └╥┘ ", " ║ ", " c1: 0 2/═══════╩══", " 1 ", ] ) qr1 = QuantumRegister(2, "q1") cr1 = ClassicalRegister(2, "c1") circuit = QuantumCircuit(qr1, cr1) circuit.x(qr1[0]) circuit.h(qr1[1]) circuit.measure(qr1[1], cr1[1]) self.assertEqual( str(_text_circuit_drawer(circuit, justify="right", vertical_compression="low")), expected, ) class TestTextDrawerVerticalCompressionMedium(QiskitTestCase): """Test vertical_compression='medium'""" def test_text_conditional_1(self): """Medium vertical compression avoids box overlap.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[1]; creg c1[1]; if(c0==1) x q[0]; if(c1==1) x q[0]; """ expected = "\n".join( [ " ┌───┐┌───┐", "q: |0>┤ X ├┤ X ├", " └─╥─┘└─╥─┘", "c0: 0 ══■════╬══", " 0x1 ║ ", "c1: 0 ═══════■══", " 0x1 ", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual( str(_text_circuit_drawer(circuit, cregbundle=False, vertical_compression="medium")), expected, ) def test_text_conditional_1_bundle(self): """Medium vertical compression avoids box overlap.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[1]; creg c1[1]; if(c0==1) x q[0]; if(c1==1) x q[0]; """ expected = "\n".join( [ " ┌───┐ ┌───┐ ", " q: |0>─┤ X ├──┤ X ├─", " └─╥─┘ └─╥─┘ ", " ┌──╨──┐ ║ ", "c0: 0 1/╡ 0x1 ╞═══╬═══", " └─────┘┌──╨──┐", "c1: 0 1/═══════╡ 0x1 ╞", " └─────┘", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual( str(_text_circuit_drawer(circuit, vertical_compression="medium", cregbundle=True)), expected, ) def test_text_measure_with_spaces(self): """Measure wire might have extra spaces Found while reproducing https://quantumcomputing.stackexchange.com/q/10194/1859""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; creg c[3]; measure q[0] -> c[1]; if(c==1) x q[1]; """ expected = "\n".join( [ " ┌─┐ ", "q_0: |0>┤M├─────", " └╥┘┌───┐", "q_1: |0>─╫─┤ X ├", " ║ └─╥─┘", " c_0: 0 ═╬═══■══", " ║ ║ ", " c_1: 0 ═╩═══o══", " ║ ", " c_2: 0 ═════o══", " 0x1 ", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual( str(_text_circuit_drawer(circuit, cregbundle=False, vertical_compression="medium")), expected, ) def test_text_measure_with_spaces_bundle(self): """Measure wire might have extra spaces Found while reproducing https://quantumcomputing.stackexchange.com/q/10194/1859""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; creg c[3]; measure q[0] -> c[1]; if(c==1) x q[1]; """ expected = "\n".join( [ " ┌─┐ ", "q_0: |0>┤M├───────", " └╥┘ ┌───┐ ", "q_1: |0>─╫──┤ X ├─", " ║ └─╥─┘ ", " ║ ┌──╨──┐", " c: 0 3/═╩═╡ 0x1 ╞", " 1 └─────┘", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual( str(_text_circuit_drawer(circuit, vertical_compression="medium", cregbundle=True)), expected, ) def test_text_barrier_med_compress_1(self): """Medium vertical compression avoids connection break.""" circuit = QuantumCircuit(4) circuit.cx(1, 3) circuit.x(1) circuit.barrier((2, 3), label="Bar 1") expected = "\n".join( [ " ", "q_0: |0>────────────", " ┌───┐ ", "q_1: |0>──■───┤ X ├─", " │ └───┘ ", " │ Bar 1 ", "q_2: |0>──┼─────░───", " ┌─┴─┐ ░ ", "q_3: |0>┤ X ├───░───", " └───┘ ░ ", ] ) self.assertEqual( str(_text_circuit_drawer(circuit, vertical_compression="medium", cregbundle=False)), expected, ) def test_text_barrier_med_compress_2(self): """Medium vertical compression avoids overprint.""" circuit = QuantumCircuit(4) circuit.barrier((0, 1, 2), label="a") circuit.cx(1, 3) circuit.x(1) circuit.barrier((2, 3), label="Bar 1") expected = "\n".join( [ " a ", "q_0: |0>─░─────────────", " ░ ┌───┐ ", "q_1: |0>─░───■───┤ X ├─", " ░ │ └───┘ ", " ░ │ Bar 1 ", "q_2: |0>─░───┼─────░───", " ░ ┌─┴─┐ ░ ", "q_3: |0>───┤ X ├───░───", " └───┘ ░ ", ] ) self.assertEqual( str(_text_circuit_drawer(circuit, vertical_compression="medium", cregbundle=False)), expected, ) def test_text_barrier_med_compress_3(self): """Medium vertical compression avoids conditional connection break.""" qr = QuantumRegister(1, "qr") qc1 = ClassicalRegister(3, "cr") qc2 = ClassicalRegister(1, "cr2") circuit = QuantumCircuit(qr, qc1, qc2) circuit.x(0).c_if(qc1, 3) circuit.x(0).c_if(qc2[0], 1) expected = "\n".join( [ " ┌───┐┌───┐", " qr: |0>┤ X ├┤ X ├", " └─╥─┘└─╥─┘", "cr_0: 0 ══■════╬══", " ║ ║ ", "cr_2: 0 ══o════╬══", " ║ ║ ", " cr2: 0 ══╬════■══", " ║ ", "cr_1: 0 ══■═══════", " 0x3 ", ] ) self.assertEqual( str( _text_circuit_drawer( circuit, vertical_compression="medium", wire_order=[0, 1, 3, 4, 2], cregbundle=False, ) ), expected, ) class TestTextConditional(QiskitTestCase): """Gates with conditionals""" def test_text_conditional_1_cregbundle(self): """Conditional drawing with 1-bit-length regs and cregbundle.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[1]; creg c1[1]; if(c0==1) x q[0]; if(c1==1) x q[0]; """ expected = "\n".join( [ " ┌───┐ ┌───┐ ", " q: |0>─┤ X ├──┤ X ├─", " ┌┴─╨─┴┐ └─╥─┘ ", "c0: 0 1/╡ 0x1 ╞═══╬═══", " └─────┘┌──╨──┐", "c1: 0 1/═══════╡ 0x1 ╞", " └─────┘", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_1(self): """Conditional drawing with 1-bit-length regs.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[1]; creg c1[1]; if(c0==1) x q[0]; if(c1==1) x q[0]; """ expected = "\n".join( [ " ┌───┐┌───┐", "q: |0>┤ X ├┤ X ├", " └─╥─┘└─╥─┘", "c0: 0 ══■════╬══", " 0x1 ║ ", "c1: 0 ═══════■══", " 0x1 ", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_2_cregbundle(self): """Conditional drawing with 2-bit-length regs with cregbundle""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[2]; creg c1[2]; if(c0==2) x q[0]; if(c1==2) x q[0]; """ expected = "\n".join( [ " ┌───┐ ┌───┐ ", " q: |0>─┤ X ├──┤ X ├─", " ┌┴─╨─┴┐ └─╥─┘ ", "c0: 0 2/╡ 0x2 ╞═══╬═══", " └─────┘┌──╨──┐", "c1: 0 2/═══════╡ 0x2 ╞", " └─────┘", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_2(self): """Conditional drawing with 2-bit-length regs.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[2]; creg c1[2]; if(c0==2) x q[0]; if(c1==2) x q[0]; """ expected = "\n".join( [ " ┌───┐┌───┐", " q: |0>┤ X ├┤ X ├", " └─╥─┘└─╥─┘", "c0_0: 0 ══o════╬══", " ║ ║ ", "c0_1: 0 ══■════╬══", " 0x2 ║ ", "c1_0: 0 ═══════o══", " ║ ", "c1_1: 0 ═══════■══", " 0x2 ", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_3_cregbundle(self): """Conditional drawing with 3-bit-length regs with cregbundle.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[3]; creg c1[3]; if(c0==3) x q[0]; if(c1==3) x q[0]; """ expected = "\n".join( [ " ┌───┐ ┌───┐ ", " q: |0>─┤ X ├──┤ X ├─", " ┌┴─╨─┴┐ └─╥─┘ ", "c0: 0 3/╡ 0x3 ╞═══╬═══", " └─────┘┌──╨──┐", "c1: 0 3/═══════╡ 0x3 ╞", " └─────┘", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_3(self): """Conditional drawing with 3-bit-length regs.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[3]; creg c1[3]; if(c0==3) x q[0]; if(c1==3) x q[0]; """ expected = "\n".join( [ " ┌───┐┌───┐", " q: |0>┤ X ├┤ X ├", " └─╥─┘└─╥─┘", "c0_0: 0 ══■════╬══", " ║ ║ ", "c0_1: 0 ══■════╬══", " ║ ║ ", "c0_2: 0 ══o════╬══", " 0x3 ║ ", "c1_0: 0 ═══════■══", " ║ ", "c1_1: 0 ═══════■══", " ║ ", "c1_2: 0 ═══════o══", " 0x3 ", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_4(self): """Conditional drawing with 4-bit-length regs.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[4]; creg c1[4]; if(c0==4) x q[0]; if(c1==4) x q[0]; """ expected = "\n".join( [ " ┌───┐ ┌───┐ ", " q: |0>─┤ X ├──┤ X ├─", " ┌┴─╨─┴┐ └─╥─┘ ", "c0: 0 4/╡ 0x4 ╞═══╬═══", " └─────┘┌──╨──┐", "c1: 0 4/═══════╡ 0x4 ╞", " └─────┘", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_conditional_5(self): """Conditional drawing with 5-bit-length regs.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[5]; creg c1[5]; if(c0==5) x q[0]; if(c1==5) x q[0]; """ expected = "\n".join( [ " ┌───┐┌───┐", " q: |0>┤ X ├┤ X ├", " └─╥─┘└─╥─┘", "c0_0: 0 ══■════╬══", " ║ ║ ", "c0_1: 0 ══o════╬══", " ║ ║ ", "c0_2: 0 ══■════╬══", " ║ ║ ", "c0_3: 0 ══o════╬══", " ║ ║ ", "c0_4: 0 ══o════╬══", " 0x5 ║ ", "c1_0: 0 ═══════■══", " ║ ", "c1_1: 0 ═══════o══", " ║ ", "c1_2: 0 ═══════■══", " ║ ", "c1_3: 0 ═══════o══", " ║ ", "c1_4: 0 ═══════o══", " 0x5 ", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_cz_no_space_cregbundle(self): """Conditional CZ without space""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cz(qr[0], qr[1]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>───■───", " │ ", "qr_1: |0>───■───", " ┌──╨──┐", " cr: 0 1/╡ 0x1 ╞", " └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_cz_no_space(self): """Conditional CZ without space""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cz(qr[0], qr[1]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>──■──", " │ ", "qr_1: |0>──■──", " ║ ", " cr: 0 ══■══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_cz_cregbundle(self): """Conditional CZ with a wire in the middle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cz(qr[0], qr[1]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>───■───", " │ ", "qr_1: |0>───■───", " ║ ", "qr_2: |0>───╫───", " ┌──╨──┐", " cr: 0 1/╡ 0x1 ╞", " └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_cz(self): """Conditional CZ with a wire in the middle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cz(qr[0], qr[1]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>──■──", " │ ", "qr_1: |0>──■──", " ║ ", "qr_2: |0>──╫──", " ║ ", " cr: 0 ══■══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_cx_ct_cregbundle(self): """Conditional CX (control-target) with a wire in the middle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cx(qr[0], qr[1]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>───■───", " ┌─┴─┐ ", "qr_1: |0>─┤ X ├─", " └─╥─┘ ", "qr_2: |0>───╫───", " ┌──╨──┐", " cr: 0 1/╡ 0x1 ╞", " └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_cx_ct(self): """Conditional CX (control-target) with a wire in the middle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cx(qr[0], qr[1]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>──■──", " ┌─┴─┐", "qr_1: |0>┤ X ├", " └─╥─┘", "qr_2: |0>──╫──", " ║ ", " cr: 0 ══■══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_cx_tc_cregbundle(self): """Conditional CX (target-control) with a wire in the middle with cregbundle.""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cx(qr[1], qr[0]).c_if(cr, 1) expected = "\n".join( [ " ┌───┐ ", "qr_0: |0>─┤ X ├─", " └─┬─┘ ", "qr_1: |0>───■───", " ║ ", "qr_2: |0>───╫───", " ┌──╨──┐", " cr: 0 1/╡ 0x1 ╞", " └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_cx_tc(self): """Conditional CX (target-control) with a wire in the middle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cx(qr[1], qr[0]).c_if(cr, 1) expected = "\n".join( [ " ┌───┐", "qr_0: |0>┤ X ├", " └─┬─┘", "qr_1: |0>──■──", " ║ ", "qr_2: |0>──╫──", " ║ ", " cr: 0 ══■══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_cu3_ct_cregbundle(self): """Conditional Cu3 (control-target) with a wire in the middle with cregbundle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[0], qr[1]]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>─────────■─────────", " ┌────────┴────────┐", "qr_1: |0>┤ U3(π/2,π/2,π/2) ├", " └────────╥────────┘", "qr_2: |0>─────────╫─────────", " ┌──╨──┐ ", " cr: 0 1/══════╡ 0x1 ╞══════", " └─────┘ ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_cu3_ct(self): """Conditional Cu3 (control-target) with a wire in the middle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[0], qr[1]]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>─────────■─────────", " ┌────────┴────────┐", "qr_1: |0>┤ U3(π/2,π/2,π/2) ├", " └────────╥────────┘", "qr_2: |0>─────────╫─────────", " ║ ", " cr: 0 ═════════■═════════", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_cu3_tc_cregbundle(self): """Conditional Cu3 (target-control) with a wire in the middle with cregbundle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[1], qr[0]]).c_if(cr, 1) expected = "\n".join( [ " ┌─────────────────┐", "qr_0: |0>┤ U3(π/2,π/2,π/2) ├", " └────────┬────────┘", "qr_1: |0>─────────■─────────", " ║ ", "qr_2: |0>─────────╫─────────", " ┌──╨──┐ ", " cr: 0 1/══════╡ 0x1 ╞══════", " └─────┘ ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_cu3_tc(self): """Conditional Cu3 (target-control) with a wire in the middle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[1], qr[0]]).c_if(cr, 1) expected = "\n".join( [ " ┌─────────────────┐", "qr_0: |0>┤ U3(π/2,π/2,π/2) ├", " └────────┬────────┘", "qr_1: |0>─────────■─────────", " ║ ", "qr_2: |0>─────────╫─────────", " ║ ", " cr: 0 ═════════■═════════", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_ccx_cregbundle(self): """Conditional CCX with a wire in the middle with cregbundle""" qr = QuantumRegister(4, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>───■───", " │ ", "qr_1: |0>───■───", " ┌─┴─┐ ", "qr_2: |0>─┤ X ├─", " └─╥─┘ ", "qr_3: |0>───╫───", " ┌──╨──┐", " cr: 0 1/╡ 0x1 ╞", " └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_ccx(self): """Conditional CCX with a wire in the middle""" qr = QuantumRegister(4, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>──■──", " │ ", "qr_1: |0>──■──", " ┌─┴─┐", "qr_2: |0>┤ X ├", " └─╥─┘", "qr_3: |0>──╫──", " ║ ", " cr: 0 ══■══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_ccx_no_space_cregbundle(self): """Conditional CCX without space with cregbundle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>───■───", " │ ", "qr_1: |0>───■───", " ┌─┴─┐ ", "qr_2: |0>─┤ X ├─", " ┌┴─╨─┴┐", " cr: 0 1/╡ 0x1 ╞", " └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_ccx_no_space(self): """Conditional CCX without space""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>──■──", " │ ", "qr_1: |0>──■──", " ┌─┴─┐", "qr_2: |0>┤ X ├", " └─╥─┘", " cr: 0 ══■══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_h_cregbundle(self): """Conditional H with a wire in the middle with cregbundle""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]).c_if(cr, 1) expected = "\n".join( [ " ┌───┐ ", "qr_0: |0>─┤ H ├─", " └─╥─┘ ", "qr_1: |0>───╫───", " ┌──╨──┐", " cr: 0 1/╡ 0x1 ╞", " └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_h(self): """Conditional H with a wire in the middle""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]).c_if(cr, 1) expected = "\n".join( [ " ┌───┐", "qr_0: |0>┤ H ├", " └─╥─┘", "qr_1: |0>──╫──", " ║ ", " cr: 0 ══■══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_swap_cregbundle(self): """Conditional SWAP with cregbundle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.swap(qr[0], qr[1]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>───X───", " │ ", "qr_1: |0>───X───", " ║ ", "qr_2: |0>───╫───", " ┌──╨──┐", " cr: 0 1/╡ 0x1 ╞", " └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_swap(self): """Conditional SWAP""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.swap(qr[0], qr[1]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>──X──", " │ ", "qr_1: |0>──X──", " ║ ", "qr_2: |0>──╫──", " ║ ", " cr: 0 ══■══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_cswap_cregbundle(self): """Conditional CSwap with cregbundle""" qr = QuantumRegister(4, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cswap(qr[0], qr[1], qr[2]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>───■───", " │ ", "qr_1: |0>───X───", " │ ", "qr_2: |0>───X───", " ║ ", "qr_3: |0>───╫───", " ┌──╨──┐", " cr: 0 1/╡ 0x1 ╞", " └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_cswap(self): """Conditional CSwap""" qr = QuantumRegister(4, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cswap(qr[0], qr[1], qr[2]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>──■──", " │ ", "qr_1: |0>──X──", " │ ", "qr_2: |0>──X──", " ║ ", "qr_3: |0>──╫──", " ║ ", " cr: 0 ══■══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_conditional_reset_cregbundle(self): """Reset drawing with cregbundle.""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.reset(qr[0]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>──|0>──", " ║ ", "qr_1: |0>───╫───", " ┌──╨──┐", " cr: 0 1/╡ 0x1 ╞", " └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_conditional_reset(self): """Reset drawing.""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.reset(qr[0]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>─|0>─", " ║ ", "qr_1: |0>──╫──", " ║ ", " cr: 0 ══■══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_conditional_multiplexer_cregbundle(self): """Test Multiplexer with cregbundle.""" cx_multiplexer = UCGate([numpy.eye(2), numpy.array([[0, 1], [1, 0]])]) qr = QuantumRegister(3, name="qr") cr = ClassicalRegister(1, "cr") qc = QuantumCircuit(qr, cr) qc.append(cx_multiplexer.c_if(cr, 1), [qr[0], qr[1]]) expected = "\n".join( [ " ┌──────────────┐", "qr_0: |0>┤0 ├", " │ Multiplexer │", "qr_1: |0>┤1 ├", " └──────╥───────┘", "qr_2: |0>───────╫────────", " ┌──╨──┐ ", " cr: 0 1/════╡ 0x1 ╞═════", " └─────┘ ", ] ) self.assertEqual(str(_text_circuit_drawer(qc, cregbundle=True)), expected) def test_conditional_multiplexer(self): """Test Multiplexer.""" cx_multiplexer = UCGate([numpy.eye(2), numpy.array([[0, 1], [1, 0]])]) qr = QuantumRegister(3, name="qr") cr = ClassicalRegister(1, "cr") qc = QuantumCircuit(qr, cr) qc.append(cx_multiplexer.c_if(cr, 1), [qr[0], qr[1]]) expected = "\n".join( [ " ┌──────────────┐", "qr_0: |0>┤0 ├", " │ Multiplexer │", "qr_1: |0>┤1 ├", " └──────╥───────┘", "qr_2: |0>───────╫────────", " ║ ", " cr: 0 ═══════■════════", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(qc, cregbundle=False)), expected) def test_text_conditional_measure_cregbundle(self): """Conditional with measure on same clbit with cregbundle""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.measure(qr[0], cr[0]) circuit.h(qr[1]).c_if(cr, 1) expected = "\n".join( [ " ┌───┐┌─┐ ", "qr_0: |0>┤ H ├┤M├───────", " └───┘└╥┘ ┌───┐ ", "qr_1: |0>──────╫──┤ H ├─", " ║ ┌┴─╨─┴┐", " cr: 0 2/══════╩═╡ 0x1 ╞", " 0 └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_measure(self): """Conditional with measure on same clbit""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.measure(qr[0], cr[0]) circuit.h(qr[1]).c_if(cr, 1) expected = "\n".join( [ " ┌───┐┌─┐ ", "qr_0: |0>┤ H ├┤M├─────", " └───┘└╥┘┌───┐", "qr_1: |0>──────╫─┤ H ├", " ║ └─╥─┘", " cr_0: 0 ══════╩═══■══", " ║ ", " cr_1: 0 ══════════o══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_bit_conditional(self): """Test bit conditions on gates""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]).c_if(cr[0], 1) circuit.h(qr[1]).c_if(cr[1], 0) expected = "\n".join( [ " ┌───┐ ", "qr_0: |0>┤ H ├─────", " └─╥─┘┌───┐", "qr_1: |0>──╫──┤ H ├", " ║ └─╥─┘", " cr_0: 0 ══■════╬══", " ║ ", " cr_1: 0 ═══════o══", " ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_bit_conditional_cregbundle(self): """Test bit conditions on gates when cregbundle=True""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]).c_if(cr[0], 1) circuit.h(qr[1]).c_if(cr[1], 0) expected = "\n".join( [ " ┌───┐ ", "qr_0: |0>───┤ H ├────────────────", " └─╥─┘ ┌───┐ ", "qr_1: |0>─────╫─────────┤ H ├────", " ║ └─╥─┘ ", " ┌────╨─────┐┌────╨─────┐", " cr: 0 2/╡ cr_0=0x1 ╞╡ cr_1=0x0 ╞", " └──────────┘└──────────┘", ] ) self.assertEqual( str(_text_circuit_drawer(circuit, cregbundle=True, vertical_compression="medium")), expected, ) def test_text_condition_measure_bits_true(self): """Condition and measure on single bits cregbundle true""" bits = [Qubit(), Qubit(), Clbit(), Clbit()] cr = ClassicalRegister(2, "cr") crx = ClassicalRegister(3, "cs") circuit = QuantumCircuit(bits, cr, [Clbit()], crx) circuit.x(0).c_if(crx[1], 0) circuit.measure(0, bits[3]) expected = "\n".join( [ " ┌───┐ ┌─┐", " 0: ───┤ X ├────┤M├", " └─╥─┘ └╥┘", " 1: ─────╫───────╫─", " ║ ║ ", " 0: ═════╬═══════╬═", " ║ ║ ", " 1: ═════╬═══════╩═", " ║ ", "cr: 2/═════╬═════════", " ║ ", " 4: ═════╬═════════", " ┌────╨─────┐ ", "cs: 3/╡ cs_1=0x0 ╞═══", " └──────────┘ ", ] ) self.assertEqual( str(_text_circuit_drawer(circuit, cregbundle=True, initial_state=False)), expected ) def test_text_condition_measure_bits_false(self): """Condition and measure on single bits cregbundle false""" bits = [Qubit(), Qubit(), Clbit(), Clbit()] cr = ClassicalRegister(2, "cr") crx = ClassicalRegister(3, "cs") circuit = QuantumCircuit(bits, cr, [Clbit()], crx) circuit.x(0).c_if(crx[1], 0) circuit.measure(0, bits[3]) expected = "\n".join( [ " ┌───┐┌─┐", " 0: ┤ X ├┤M├", " └─╥─┘└╥┘", " 1: ──╫───╫─", " ║ ║ ", " 0: ══╬═══╬═", " ║ ║ ", " 1: ══╬═══╩═", " ║ ", "cr_0: ══╬═════", " ║ ", "cr_1: ══╬═════", " ║ ", " 4: ══╬═════", " ║ ", "cs_0: ══╬═════", " ║ ", "cs_1: ══o═════", " ", "cs_2: ════════", " ", ] ) self.assertEqual( str(_text_circuit_drawer(circuit, cregbundle=False, initial_state=False)), expected ) def test_text_conditional_reverse_bits_1(self): """Classical condition on 2q2c circuit with cregbundle=False and reverse bits""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.measure(qr[0], cr[0]) circuit.h(qr[1]).c_if(cr, 1) expected = "\n".join( [ " ┌───┐", "qr_1: |0>────────┤ H ├", " ┌───┐┌─┐└─╥─┘", "qr_0: |0>┤ H ├┤M├──╫──", " └───┘└╥┘ ║ ", " cr_1: 0 ══════╬═══o══", " ║ ║ ", " cr_0: 0 ══════╩═══■══", " 0x1 ", ] ) self.assertEqual( str(_text_circuit_drawer(circuit, cregbundle=False, reverse_bits=True)), expected ) def test_text_conditional_reverse_bits_2(self): """Classical condition on 3q3c circuit with cergbundle=False and reverse bits""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]).c_if(cr, 6) circuit.h(qr[1]).c_if(cr, 1) circuit.h(qr[2]).c_if(cr, 2) circuit.cx(0, 1).c_if(cr, 3) expected = "\n".join( [ " ┌───┐ ", "qr_2: |0>──────────┤ H ├─────", " ┌───┐└─╥─┘┌───┐", "qr_1: |0>─────┤ H ├──╫──┤ X ├", " ┌───┐└─╥─┘ ║ └─┬─┘", "qr_0: |0>┤ H ├──╫────╫────■──", " └─╥─┘ ║ ║ ║ ", " cr_2: 0 ══■════o════o════o══", " ║ ║ ║ ║ ", " cr_1: 0 ══■════o════■════■══", " ║ ║ ║ ║ ", " cr_0: 0 ══o════■════o════■══", " 0x6 0x1 0x2 0x3 ", ] ) self.assertEqual( str(_text_circuit_drawer(circuit, cregbundle=False, reverse_bits=True)), expected ) def test_text_condition_bits_reverse(self): """Condition and measure on single bits cregbundle true and reverse_bits true""" bits = [Qubit(), Qubit(), Clbit(), Clbit()] cr = ClassicalRegister(2, "cr") crx = ClassicalRegister(3, "cs") circuit = QuantumCircuit(bits, cr, [Clbit()], crx) circuit.x(0).c_if(bits[3], 0) expected = "\n".join( [ " ", " 1: ─────", " ┌───┐", " 0: ┤ X ├", " └─╥─┘", "cs: 3/══╬══", " ║ ", " 4: ══╬══", " ║ ", "cr: 2/══╬══", " ║ ", " 1: ══o══", " ", " 0: ═════", " ", ] ) self.assertEqual( str( _text_circuit_drawer( circuit, cregbundle=True, initial_state=False, reverse_bits=True ) ), expected, ) class TestTextIdleWires(QiskitTestCase): """The idle_wires option""" def test_text_h(self): """Remove QuWires.""" # fmt: off expected = "\n".join([" ┌───┐", "q1_1: |0>┤ H ├", " └───┘"]) # fmt: on qr1 = QuantumRegister(3, "q1") circuit = QuantumCircuit(qr1) circuit.h(qr1[1]) self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected) def test_text_measure(self): """Remove QuWires and ClWires.""" expected = "\n".join( [ " ┌─┐ ", "q2_0: |0>┤M├───", " └╥┘┌─┐", "q2_1: |0>─╫─┤M├", " ║ └╥┘", " c2: 0 2/═╩══╩═", " 0 1 ", ] ) qr1 = QuantumRegister(2, "q1") cr1 = ClassicalRegister(2, "c1") qr2 = QuantumRegister(2, "q2") cr2 = ClassicalRegister(2, "c2") circuit = QuantumCircuit(qr1, qr2, cr1, cr2) circuit.measure(qr2, cr2) self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected) def test_text_empty_circuit(self): """Remove everything in an empty circuit.""" expected = "" circuit = QuantumCircuit() self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected) def test_text_barrier(self): """idle_wires should ignore barrier See https://github.com/Qiskit/qiskit-terra/issues/4391""" # fmt: off expected = "\n".join([" ┌───┐ ░ ", "qr_1: |0>┤ H ├─░─", " └───┘ ░ "]) # fmt: on qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[1]) circuit.barrier(qr[1], qr[2]) self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected) def test_text_barrier_delay(self): """idle_wires should ignore delay""" # fmt: off expected = "\n".join([" ┌───┐ ░ ", "qr_1: |0>┤ H ├─░──", " └───┘ ░ "]) # fmt: on qr = QuantumRegister(4, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[1]) circuit.barrier() circuit.delay(100, qr[2]) self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected) def test_does_not_mutate_circuit(self): """Using 'idle_wires=False' should not mutate the circuit. Regression test of gh-8739.""" circuit = QuantumCircuit(1) before_qubits = circuit.num_qubits circuit.draw(idle_wires=False) self.assertEqual(circuit.num_qubits, before_qubits) class TestTextNonRational(QiskitTestCase): """non-rational numbers are correctly represented""" def test_text_pifrac(self): """u drawing with -5pi/8 fraction""" # fmt: off expected = "\n".join( [" ┌──────────────┐", "q: |0>┤ U(π,-5π/8,0) ├", " └──────────────┘"] ) # fmt: on qr = QuantumRegister(1, "q") circuit = QuantumCircuit(qr) circuit.u(pi, -5 * pi / 8, 0, qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_complex(self): """Complex numbers show up in the text See https://github.com/Qiskit/qiskit-terra/issues/3640""" expected = "\n".join( [ " ┌────────────────────────────────────┐", "q_0: ┤0 ├", " │ Initialize(0.5+0.1j,0,0,0.86023j) │", "q_1: ┤1 ├", " └────────────────────────────────────┘", ] ) ket = numpy.array([0.5 + 0.1 * 1j, 0, 0, 0.8602325267042626 * 1j]) circuit = QuantumCircuit(2) circuit.initialize(ket, [0, 1]) self.assertEqual(circuit.draw(output="text").single_string(), expected) def test_text_complex_pireal(self): """Complex numbers including pi show up in the text See https://github.com/Qiskit/qiskit-terra/issues/3640""" expected = "\n".join( [ " ┌────────────────────────────────┐", "q_0: |0>┤0 ├", " │ Initialize(π/10,0,0,0.94937j) │", "q_1: |0>┤1 ├", " └────────────────────────────────┘", ] ) ket = numpy.array([0.1 * numpy.pi, 0, 0, 0.9493702944526474 * 1j]) circuit = QuantumCircuit(2) circuit.initialize(ket, [0, 1]) self.assertEqual(circuit.draw(output="text", initial_state=True).single_string(), expected) def test_text_complex_piimaginary(self): """Complex numbers including pi show up in the text See https://github.com/Qiskit/qiskit-terra/issues/3640""" expected = "\n".join( [ " ┌────────────────────────────────┐", "q_0: |0>┤0 ├", " │ Initialize(0.94937,0,0,π/10j) │", "q_1: |0>┤1 ├", " └────────────────────────────────┘", ] ) ket = numpy.array([0.9493702944526474, 0, 0, 0.1 * numpy.pi * 1j]) circuit = QuantumCircuit(2) circuit.initialize(ket, [0, 1]) self.assertEqual(circuit.draw(output="text", initial_state=True).single_string(), expected) class TestTextInstructionWithBothWires(QiskitTestCase): """Composite instructions with both kind of wires See https://github.com/Qiskit/qiskit-terra/issues/2973""" def test_text_all_1q_1c(self): """Test q0-c0 in q0-c0""" expected = "\n".join( [ " ┌───────┐", "qr: |0>┤0 ├", " │ name │", " cr: 0 ╡0 ╞", " └───────┘", ] ) qr1 = QuantumRegister(1, "qr") cr1 = ClassicalRegister(1, "cr") inst = QuantumCircuit(qr1, cr1, name="name").to_instruction() circuit = QuantumCircuit(qr1, cr1) circuit.append(inst, qr1[:], cr1[:]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_all_2q_2c(self): """Test q0-q1-c0-c1 in q0-q1-c0-c1""" expected = "\n".join( [ " ┌───────┐", "qr_0: |0>┤0 ├", " │ │", "qr_1: |0>┤1 ├", " │ name │", " cr_0: 0 ╡0 ╞", " │ │", " cr_1: 0 ╡1 ╞", " └───────┘", ] ) qr2 = QuantumRegister(2, "qr") cr2 = ClassicalRegister(2, "cr") inst = QuantumCircuit(qr2, cr2, name="name").to_instruction() circuit = QuantumCircuit(qr2, cr2) circuit.append(inst, qr2[:], cr2[:]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_all_2q_2c_cregbundle(self): """Test q0-q1-c0-c1 in q0-q1-c0-c1. Ignore cregbundle=True""" expected = "\n".join( [ " ┌───────┐", "qr_0: |0>┤0 ├", " │ │", "qr_1: |0>┤1 ├", " │ name │", " cr_0: 0 ╡0 ╞", " │ │", " cr_1: 0 ╡1 ╞", " └───────┘", ] ) qr2 = QuantumRegister(2, "qr") cr2 = ClassicalRegister(2, "cr") inst = QuantumCircuit(qr2, cr2, name="name").to_instruction() circuit = QuantumCircuit(qr2, cr2) circuit.append(inst, qr2[:], cr2[:]) with self.assertWarns(RuntimeWarning): self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_4q_2c(self): """Test q1-q2-q3-q4-c1-c2 in q0-q1-q2-q3-q4-q5-c0-c1-c2-c3-c4-c5""" expected = "\n".join( [ " ", "q_0: |0>─────────", " ┌───────┐", "q_1: |0>┤0 ├", " │ │", "q_2: |0>┤1 ├", " │ │", "q_3: |0>┤2 ├", " │ │", "q_4: |0>┤3 ├", " │ name │", "q_5: |0>┤ ├", " │ │", " c_0: 0 ╡ ╞", " │ │", " c_1: 0 ╡0 ╞", " │ │", " c_2: 0 ╡1 ╞", " └───────┘", " c_3: 0 ═════════", " ", " c_4: 0 ═════════", " ", " c_5: 0 ═════════", " ", ] ) qr4 = QuantumRegister(4) cr4 = ClassicalRegister(2) inst = QuantumCircuit(qr4, cr4, name="name").to_instruction() qr6 = QuantumRegister(6, "q") cr6 = ClassicalRegister(6, "c") circuit = QuantumCircuit(qr6, cr6) circuit.append(inst, qr6[1:5], cr6[1:3]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_2q_1c(self): """Test q0-c0 in q0-q1-c0 See https://github.com/Qiskit/qiskit-terra/issues/4066""" expected = "\n".join( [ " ┌───────┐", "q_0: |0>┤0 ├", " │ │", "q_1: |0>┤ Name ├", " │ │", " c: 0 ╡0 ╞", " └───────┘", ] ) qr = QuantumRegister(2, name="q") cr = ClassicalRegister(1, name="c") circuit = QuantumCircuit(qr, cr) inst = QuantumCircuit(1, 1, name="Name").to_instruction() circuit.append(inst, [qr[0]], [cr[0]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_3q_3c_qlabels_inverted(self): """Test q3-q0-q1-c0-c1-c_10 in q0-q1-q2-q3-c0-c1-c2-c_10-c_11 See https://github.com/Qiskit/qiskit-terra/issues/6178""" expected = "\n".join( [ " ┌───────┐", "q_0: |0>┤1 ├", " │ │", "q_1: |0>┤2 ├", " │ │", "q_2: |0>┤ ├", " │ │", "q_3: |0>┤0 ├", " │ Name │", " c_0: 0 ╡0 ╞", " │ │", " c_1: 0 ╡1 ╞", " │ │", " c_2: 0 ╡ ╞", " │ │", "c1_0: 0 ╡2 ╞", " └───────┘", "c1_1: 0 ═════════", " ", ] ) qr = QuantumRegister(4, name="q") cr = ClassicalRegister(3, name="c") cr1 = ClassicalRegister(2, name="c1") circuit = QuantumCircuit(qr, cr, cr1) inst = QuantumCircuit(3, 3, name="Name").to_instruction() circuit.append(inst, [qr[3], qr[0], qr[1]], [cr[0], cr[1], cr1[0]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_3q_3c_clabels_inverted(self): """Test q0-q1-q3-c_11-c0-c_10 in q0-q1-q2-q3-c0-c1-c2-c_10-c_11 See https://github.com/Qiskit/qiskit-terra/issues/6178""" expected = "\n".join( [ " ┌───────┐", "q_0: |0>┤0 ├", " │ │", "q_1: |0>┤1 ├", " │ │", "q_2: |0>┤ ├", " │ │", "q_3: |0>┤2 ├", " │ │", " c_0: 0 ╡1 Name ╞", " │ │", " c_1: 0 ╡ ╞", " │ │", " c_2: 0 ╡ ╞", " │ │", "c1_0: 0 ╡2 ╞", " │ │", "c1_1: 0 ╡0 ╞", " └───────┘", ] ) qr = QuantumRegister(4, name="q") cr = ClassicalRegister(3, name="c") cr1 = ClassicalRegister(2, name="c1") circuit = QuantumCircuit(qr, cr, cr1) inst = QuantumCircuit(3, 3, name="Name").to_instruction() circuit.append(inst, [qr[0], qr[1], qr[3]], [cr1[1], cr[0], cr1[0]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_3q_3c_qclabels_inverted(self): """Test q3-q1-q2-c_11-c0-c_10 in q0-q1-q2-q3-c0-c1-c2-c_10-c_11 See https://github.com/Qiskit/qiskit-terra/issues/6178""" expected = "\n".join( [ " ", "q_0: |0>─────────", " ┌───────┐", "q_1: |0>┤1 ├", " │ │", "q_2: |0>┤2 ├", " │ │", "q_3: |0>┤0 ├", " │ │", " c_0: 0 ╡1 ╞", " │ Name │", " c_1: 0 ╡ ╞", " │ │", " c_2: 0 ╡ ╞", " │ │", "c1_0: 0 ╡2 ╞", " │ │", "c1_1: 0 ╡0 ╞", " └───────┘", ] ) qr = QuantumRegister(4, name="q") cr = ClassicalRegister(3, name="c") cr1 = ClassicalRegister(2, name="c1") circuit = QuantumCircuit(qr, cr, cr1) inst = QuantumCircuit(3, 3, name="Name").to_instruction() circuit.append(inst, [qr[3], qr[1], qr[2]], [cr1[1], cr[0], cr1[0]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) class TestTextDrawerAppendedLargeInstructions(QiskitTestCase): """Composite instructions with more than 10 qubits See https://github.com/Qiskit/qiskit-terra/pull/4095""" def test_text_11q(self): """Test q0-...-q10 in q0-...-q10""" expected = "\n".join( [ " ┌────────┐", " q_0: |0>┤0 ├", " │ │", " q_1: |0>┤1 ├", " │ │", " q_2: |0>┤2 ├", " │ │", " q_3: |0>┤3 ├", " │ │", " q_4: |0>┤4 ├", " │ │", " q_5: |0>┤5 Name ├", " │ │", " q_6: |0>┤6 ├", " │ │", " q_7: |0>┤7 ├", " │ │", " q_8: |0>┤8 ├", " │ │", " q_9: |0>┤9 ├", " │ │", "q_10: |0>┤10 ├", " └────────┘", ] ) qr = QuantumRegister(11, "q") circuit = QuantumCircuit(qr) inst = QuantumCircuit(11, name="Name").to_instruction() circuit.append(inst, qr) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_11q_1c(self): """Test q0-...-q10-c0 in q0-...-q10-c0""" expected = "\n".join( [ " ┌────────┐", " q_0: |0>┤0 ├", " │ │", " q_1: |0>┤1 ├", " │ │", " q_2: |0>┤2 ├", " │ │", " q_3: |0>┤3 ├", " │ │", " q_4: |0>┤4 ├", " │ │", " q_5: |0>┤5 ├", " │ Name │", " q_6: |0>┤6 ├", " │ │", " q_7: |0>┤7 ├", " │ │", " q_8: |0>┤8 ├", " │ │", " q_9: |0>┤9 ├", " │ │", "q_10: |0>┤10 ├", " │ │", " c: 0 ╡0 ╞", " └────────┘", ] ) qr = QuantumRegister(11, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) inst = QuantumCircuit(11, 1, name="Name").to_instruction() circuit.append(inst, qr, cr) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) class TestTextControlledGate(QiskitTestCase): """Test controlled gates""" def test_cch_bot(self): """Controlled CH (bottom)""" expected = "\n".join( [ " ", "q_0: |0>──■──", " │ ", "q_1: |0>──■──", " ┌─┴─┐", "q_2: |0>┤ H ├", " └───┘", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(2), [qr[0], qr[1], qr[2]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_cch_mid(self): """Controlled CH (middle)""" expected = "\n".join( [ " ", "q_0: |0>──■──", " ┌─┴─┐", "q_1: |0>┤ H ├", " └─┬─┘", "q_2: |0>──■──", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(2), [qr[0], qr[2], qr[1]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_cch_top(self): """Controlled CH""" expected = "\n".join( [ " ┌───┐", "q_0: |0>┤ H ├", " └─┬─┘", "q_1: |0>──■──", " │ ", "q_2: |0>──■──", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(2), [qr[2], qr[1], qr[0]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_c3h(self): """Controlled Controlled CH""" expected = "\n".join( [ " ", "q_0: |0>──■──", " │ ", "q_1: |0>──■──", " │ ", "q_2: |0>──■──", " ┌─┴─┐", "q_3: |0>┤ H ├", " └───┘", ] ) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(3), [qr[0], qr[1], qr[2], qr[3]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_c3h_middle(self): """Controlled Controlled CH (middle)""" expected = "\n".join( [ " ", "q_0: |0>──■──", " ┌─┴─┐", "q_1: |0>┤ H ├", " └─┬─┘", "q_2: |0>──■──", " │ ", "q_3: |0>──■──", " ", ] ) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(3), [qr[0], qr[3], qr[2], qr[1]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_c3u2(self): """Controlled Controlled U2""" expected = "\n".join( [ " ", "q_0: |0>───────■───────", " ┌──────┴──────┐", "q_1: |0>┤ U2(π,-5π/8) ├", " └──────┬──────┘", "q_2: |0>───────■───────", " │ ", "q_3: |0>───────■───────", " ", ] ) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.append(U2Gate(pi, -5 * pi / 8).control(3), [qr[0], qr[3], qr[2], qr[1]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_edge(self): """Controlled composite gates (edge) See: https://github.com/Qiskit/qiskit-terra/issues/3546""" expected = "\n".join( [ " ┌──────┐", "q_0: |0>┤0 ├", " │ │", "q_1: |0>■ ├", " │ ghz │", "q_2: |0>┤1 ├", " │ │", "q_3: |0>┤2 ├", " └──────┘", ] ) ghz_circuit = QuantumCircuit(3, name="ghz") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() cghz = ghz.control(1) circuit = QuantumCircuit(4) circuit.append(cghz, [1, 0, 2, 3]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_top(self): """Controlled composite gates (top)""" expected = "\n".join( [ " ", "q_0: |0>───■────", " ┌──┴───┐", "q_1: |0>┤0 ├", " │ │", "q_2: |0>┤2 ghz ├", " │ │", "q_3: |0>┤1 ├", " └──────┘", ] ) ghz_circuit = QuantumCircuit(3, name="ghz") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() cghz = ghz.control(1) circuit = QuantumCircuit(4) circuit.append(cghz, [0, 1, 3, 2]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_bot(self): """Controlled composite gates (bottom)""" expected = "\n".join( [ " ┌──────┐", "q_0: |0>┤1 ├", " │ │", "q_1: |0>┤0 ghz ├", " │ │", "q_2: |0>┤2 ├", " └──┬───┘", "q_3: |0>───■────", " ", ] ) ghz_circuit = QuantumCircuit(3, name="ghz") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() cghz = ghz.control(1) circuit = QuantumCircuit(4) circuit.append(cghz, [3, 1, 0, 2]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_top_bot(self): """Controlled composite gates (top and bottom)""" expected = "\n".join( [ " ", "q_0: |0>───■────", " ┌──┴───┐", "q_1: |0>┤0 ├", " │ │", "q_2: |0>┤1 ghz ├", " │ │", "q_3: |0>┤2 ├", " └──┬───┘", "q_4: |0>───■────", " ", ] ) ghz_circuit = QuantumCircuit(3, name="ghz") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() ccghz = ghz.control(2) circuit = QuantumCircuit(5) circuit.append(ccghz, [4, 0, 1, 2, 3]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_all(self): """Controlled composite gates (top, bot, and edge)""" expected = "\n".join( [ " ", "q_0: |0>───■────", " ┌──┴───┐", "q_1: |0>┤0 ├", " │ │", "q_2: |0>■ ├", " │ ghz │", "q_3: |0>┤1 ├", " │ │", "q_4: |0>┤2 ├", " └──┬───┘", "q_5: |0>───■────", " ", ] ) ghz_circuit = QuantumCircuit(3, name="ghz") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() ccghz = ghz.control(3) circuit = QuantumCircuit(6) circuit.append(ccghz, [0, 2, 5, 1, 3, 4]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_even_label(self): """Controlled composite gates (top and bottom) with a even label length""" expected = "\n".join( [ " ", "q_0: |0>────■────", " ┌───┴───┐", "q_1: |0>┤0 ├", " │ │", "q_2: |0>┤1 cghz ├", " │ │", "q_3: |0>┤2 ├", " └───┬───┘", "q_4: |0>────■────", " ", ] ) ghz_circuit = QuantumCircuit(3, name="cghz") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() ccghz = ghz.control(2) circuit = QuantumCircuit(5) circuit.append(ccghz, [4, 0, 1, 2, 3]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) class TestTextOpenControlledGate(QiskitTestCase): """Test open controlled gates""" def test_ch_bot(self): """Open controlled H (bottom)""" # fmt: off expected = "\n".join( [" ", "q_0: |0>──o──", " ┌─┴─┐", "q_1: |0>┤ H ├", " └───┘"] ) # fmt: on qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(1, ctrl_state=0), [qr[0], qr[1]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_cz_bot(self): """Open controlled Z (bottom)""" # fmt: off expected = "\n".join([" ", "q_0: |0>─o─", " │ ", "q_1: |0>─■─", " "]) # fmt: on qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.append(ZGate().control(1, ctrl_state=0), [qr[0], qr[1]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_ccz_bot(self): """Closed-Open controlled Z (bottom)""" expected = "\n".join( [ " ", "q_0: |0>─■─", " │ ", "q_1: |0>─o─", " │ ", "q_2: |0>─■─", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(ZGate().control(2, ctrl_state="01"), [qr[0], qr[1], qr[2]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_cccz_conditional(self): """Closed-Open controlled Z (with conditional)""" expected = "\n".join( [ " ", "q_0: |0>───■───", " │ ", "q_1: |0>───o───", " │ ", "q_2: |0>───■───", " │ ", "q_3: |0>───■───", " ┌──╨──┐", " c: 0 1/╡ 0x1 ╞", " └─────┘", ] ) qr = QuantumRegister(4, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) circuit.append( ZGate().control(3, ctrl_state="101").c_if(cr, 1), [qr[0], qr[1], qr[2], qr[3]] ) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_cch_bot(self): """Controlled CH (bottom)""" expected = "\n".join( [ " ", "q_0: |0>──o──", " │ ", "q_1: |0>──■──", " ┌─┴─┐", "q_2: |0>┤ H ├", " └───┘", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(2, ctrl_state="10"), [qr[0], qr[1], qr[2]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_cch_mid(self): """Controlled CH (middle)""" expected = "\n".join( [ " ", "q_0: |0>──o──", " ┌─┴─┐", "q_1: |0>┤ H ├", " └─┬─┘", "q_2: |0>──■──", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(2, ctrl_state="10"), [qr[0], qr[2], qr[1]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_cch_top(self): """Controlled CH""" expected = "\n".join( [ " ┌───┐", "q_0: |0>┤ H ├", " └─┬─┘", "q_1: |0>──o──", " │ ", "q_2: |0>──■──", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(2, ctrl_state="10"), [qr[1], qr[2], qr[0]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_c3h(self): """Controlled Controlled CH""" expected = "\n".join( [ " ", "q_0: |0>──o──", " │ ", "q_1: |0>──o──", " │ ", "q_2: |0>──■──", " ┌─┴─┐", "q_3: |0>┤ H ├", " └───┘", ] ) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(3, ctrl_state="100"), [qr[0], qr[1], qr[2], qr[3]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_c3h_middle(self): """Controlled Controlled CH (middle)""" expected = "\n".join( [ " ", "q_0: |0>──o──", " ┌─┴─┐", "q_1: |0>┤ H ├", " └─┬─┘", "q_2: |0>──o──", " │ ", "q_3: |0>──■──", " ", ] ) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(3, ctrl_state="010"), [qr[0], qr[3], qr[2], qr[1]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_c3u2(self): """Controlled Controlled U2""" expected = "\n".join( [ " ", "q_0: |0>───────o───────", " ┌──────┴──────┐", "q_1: |0>┤ U2(π,-5π/8) ├", " └──────┬──────┘", "q_2: |0>───────■───────", " │ ", "q_3: |0>───────o───────", " ", ] ) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.append( U2Gate(pi, -5 * pi / 8).control(3, ctrl_state="100"), [qr[0], qr[3], qr[2], qr[1]] ) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_edge(self): """Controlled composite gates (edge) See: https://github.com/Qiskit/qiskit-terra/issues/3546""" expected = "\n".join( [ " ┌──────┐", "q_0: |0>┤0 ├", " │ │", "q_1: |0>o ├", " │ ghz │", "q_2: |0>┤1 ├", " │ │", "q_3: |0>┤2 ├", " └──────┘", ] ) ghz_circuit = QuantumCircuit(3, name="ghz") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() cghz = ghz.control(1, ctrl_state="0") circuit = QuantumCircuit(4) circuit.append(cghz, [1, 0, 2, 3]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_top(self): """Controlled composite gates (top)""" expected = "\n".join( [ " ", "q_0: |0>───o────", " ┌──┴───┐", "q_1: |0>┤0 ├", " │ │", "q_2: |0>┤2 ghz ├", " │ │", "q_3: |0>┤1 ├", " └──────┘", ] ) ghz_circuit = QuantumCircuit(3, name="ghz") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() cghz = ghz.control(1, ctrl_state="0") circuit = QuantumCircuit(4) circuit.append(cghz, [0, 1, 3, 2]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_bot(self): """Controlled composite gates (bottom)""" expected = "\n".join( [ " ┌──────┐", "q_0: |0>┤1 ├", " │ │", "q_1: |0>┤0 ghz ├", " │ │", "q_2: |0>┤2 ├", " └──┬───┘", "q_3: |0>───o────", " ", ] ) ghz_circuit = QuantumCircuit(3, name="ghz") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() cghz = ghz.control(1, ctrl_state="0") circuit = QuantumCircuit(4) circuit.append(cghz, [3, 1, 0, 2]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_top_bot(self): """Controlled composite gates (top and bottom)""" expected = "\n".join( [ " ", "q_0: |0>───o────", " ┌──┴───┐", "q_1: |0>┤0 ├", " │ │", "q_2: |0>┤1 ghz ├", " │ │", "q_3: |0>┤2 ├", " └──┬───┘", "q_4: |0>───■────", " ", ] ) ghz_circuit = QuantumCircuit(3, name="ghz") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() ccghz = ghz.control(2, ctrl_state="01") circuit = QuantumCircuit(5) circuit.append(ccghz, [4, 0, 1, 2, 3]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_all(self): """Controlled composite gates (top, bot, and edge)""" expected = "\n".join( [ " ", "q_0: |0>───o────", " ┌──┴───┐", "q_1: |0>┤0 ├", " │ │", "q_2: |0>o ├", " │ ghz │", "q_3: |0>┤1 ├", " │ │", "q_4: |0>┤2 ├", " └──┬───┘", "q_5: |0>───o────", " ", ] ) ghz_circuit = QuantumCircuit(3, name="ghz") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() ccghz = ghz.control(3, ctrl_state="000") circuit = QuantumCircuit(6) circuit.append(ccghz, [0, 2, 5, 1, 3, 4]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_open_controlled_x(self): """Controlled X gates. See https://github.com/Qiskit/qiskit-terra/issues/4180""" expected = "\n".join( [ " ", "qr_0: |0>──o────o────o────o────■──", " ┌─┴─┐ │ │ │ │ ", "qr_1: |0>┤ X ├──o────■────■────o──", " └───┘┌─┴─┐┌─┴─┐ │ │ ", "qr_2: |0>─────┤ X ├┤ X ├──o────o──", " └───┘└───┘┌─┴─┐┌─┴─┐", "qr_3: |0>───────────────┤ X ├┤ X ├", " └───┘└─┬─┘", "qr_4: |0>──────────────────────■──", " ", ] ) qreg = QuantumRegister(5, "qr") circuit = QuantumCircuit(qreg) control1 = XGate().control(1, ctrl_state="0") circuit.append(control1, [0, 1]) control2 = XGate().control(2, ctrl_state="00") circuit.append(control2, [0, 1, 2]) control2_2 = XGate().control(2, ctrl_state="10") circuit.append(control2_2, [0, 1, 2]) control3 = XGate().control(3, ctrl_state="010") circuit.append(control3, [0, 1, 2, 3]) control3 = XGate().control(4, ctrl_state="0101") circuit.append(control3, [0, 1, 4, 2, 3]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_open_controlled_y(self): """Controlled Y gates. See https://github.com/Qiskit/qiskit-terra/issues/4180""" expected = "\n".join( [ " ", "qr_0: |0>──o────o────o────o────■──", " ┌─┴─┐ │ │ │ │ ", "qr_1: |0>┤ Y ├──o────■────■────o──", " └───┘┌─┴─┐┌─┴─┐ │ │ ", "qr_2: |0>─────┤ Y ├┤ Y ├──o────o──", " └───┘└───┘┌─┴─┐┌─┴─┐", "qr_3: |0>───────────────┤ Y ├┤ Y ├", " └───┘└─┬─┘", "qr_4: |0>──────────────────────■──", " ", ] ) qreg = QuantumRegister(5, "qr") circuit = QuantumCircuit(qreg) control1 = YGate().control(1, ctrl_state="0") circuit.append(control1, [0, 1]) control2 = YGate().control(2, ctrl_state="00") circuit.append(control2, [0, 1, 2]) control2_2 = YGate().control(2, ctrl_state="10") circuit.append(control2_2, [0, 1, 2]) control3 = YGate().control(3, ctrl_state="010") circuit.append(control3, [0, 1, 2, 3]) control3 = YGate().control(4, ctrl_state="0101") circuit.append(control3, [0, 1, 4, 2, 3]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_open_controlled_z(self): """Controlled Z gates.""" expected = "\n".join( [ " ", "qr_0: |0>─o──o──o──o──■─", " │ │ │ │ │ ", "qr_1: |0>─■──o──■──■──o─", " │ │ │ │ ", "qr_2: |0>────■──■──o──o─", " │ │ ", "qr_3: |0>──────────■──■─", " │ ", "qr_4: |0>─────────────■─", " ", ] ) qreg = QuantumRegister(5, "qr") circuit = QuantumCircuit(qreg) control1 = ZGate().control(1, ctrl_state="0") circuit.append(control1, [0, 1]) control2 = ZGate().control(2, ctrl_state="00") circuit.append(control2, [0, 1, 2]) control2_2 = ZGate().control(2, ctrl_state="10") circuit.append(control2_2, [0, 1, 2]) control3 = ZGate().control(3, ctrl_state="010") circuit.append(control3, [0, 1, 2, 3]) control3 = ZGate().control(4, ctrl_state="0101") circuit.append(control3, [0, 1, 4, 2, 3]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_open_controlled_u1(self): """Controlled U1 gates.""" expected = "\n".join( [ " ", "qr_0: |0>─o─────────o─────────o─────────o─────────■────────", " │U1(0.1) │ │ │ │ ", "qr_1: |0>─■─────────o─────────■─────────■─────────o────────", " │U1(0.2) │U1(0.3) │ │ ", "qr_2: |0>───────────■─────────■─────────o─────────o────────", " │U1(0.4) │ ", "qr_3: |0>───────────────────────────────■─────────■────────", " │U1(0.5) ", "qr_4: |0>─────────────────────────────────────────■────────", " ", ] ) qreg = QuantumRegister(5, "qr") circuit = QuantumCircuit(qreg) control1 = U1Gate(0.1).control(1, ctrl_state="0") circuit.append(control1, [0, 1]) control2 = U1Gate(0.2).control(2, ctrl_state="00") circuit.append(control2, [0, 1, 2]) control2_2 = U1Gate(0.3).control(2, ctrl_state="10") circuit.append(control2_2, [0, 1, 2]) control3 = U1Gate(0.4).control(3, ctrl_state="010") circuit.append(control3, [0, 1, 2, 3]) control3 = U1Gate(0.5).control(4, ctrl_state="0101") circuit.append(control3, [0, 1, 4, 2, 3]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_open_controlled_swap(self): """Controlled SWAP gates.""" expected = "\n".join( [ " ", "qr_0: |0>─o──o──o──o─", " │ │ │ │ ", "qr_1: |0>─X──o──■──■─", " │ │ │ │ ", "qr_2: |0>─X──X──X──o─", " │ │ │ ", "qr_3: |0>────X──X──X─", " │ ", "qr_4: |0>──────────X─", " ", ] ) qreg = QuantumRegister(5, "qr") circuit = QuantumCircuit(qreg) control1 = SwapGate().control(1, ctrl_state="0") circuit.append(control1, [0, 1, 2]) control2 = SwapGate().control(2, ctrl_state="00") circuit.append(control2, [0, 1, 2, 3]) control2_2 = SwapGate().control(2, ctrl_state="10") circuit.append(control2_2, [0, 1, 2, 3]) control3 = SwapGate().control(3, ctrl_state="010") circuit.append(control3, [0, 1, 2, 3, 4]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_open_controlled_rzz(self): """Controlled RZZ gates.""" expected = "\n".join( [ " ", "qr_0: |0>─o───────o───────o───────o──────", " │ │ │ │ ", "qr_1: |0>─■───────o───────■───────■──────", " │ZZ(1) │ │ │ ", "qr_2: |0>─■───────■───────■───────o──────", " │ZZ(1) │ZZ(1) │ ", "qr_3: |0>─────────■───────■───────■──────", " │ZZ(1) ", "qr_4: |0>─────────────────────────■──────", " ", ] ) qreg = QuantumRegister(5, "qr") circuit = QuantumCircuit(qreg) control1 = RZZGate(1).control(1, ctrl_state="0") circuit.append(control1, [0, 1, 2]) control2 = RZZGate(1).control(2, ctrl_state="00") circuit.append(control2, [0, 1, 2, 3]) control2_2 = RZZGate(1).control(2, ctrl_state="10") circuit.append(control2_2, [0, 1, 2, 3]) control3 = RZZGate(1).control(3, ctrl_state="010") circuit.append(control3, [0, 1, 2, 3, 4]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_open_out_of_order(self): """Out of order CXs See: https://github.com/Qiskit/qiskit-terra/issues/4052#issuecomment-613736911""" expected = "\n".join( [ " ", "q_0: |0>──■──", " │ ", "q_1: |0>──■──", " ┌─┴─┐", "q_2: |0>┤ X ├", " └─┬─┘", "q_3: |0>──o──", " ", "q_4: |0>─────", " ", ] ) qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.append(XGate().control(3, ctrl_state="101"), [qr[0], qr[3], qr[1], qr[2]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) class TestTextWithLayout(QiskitTestCase): """The with_layout option""" def test_with_no_layout(self): """A circuit without layout""" expected = "\n".join( [ " ", "q_0: |0>─────", " ┌───┐", "q_1: |0>┤ H ├", " └───┘", "q_2: |0>─────", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.h(qr[1]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_mixed_layout(self): """With a mixed layout.""" expected = "\n".join( [ " ┌───┐", " v_0 -> 0 |0>┤ H ├", " └───┘", "ancilla_1 -> 1 |0>─────", " ", "ancilla_0 -> 2 |0>─────", " ┌───┐", " v_1 -> 3 |0>┤ H ├", " └───┘", ] ) qr = QuantumRegister(2, "v") ancilla = QuantumRegister(2, "ancilla") circuit = QuantumCircuit(qr, ancilla) circuit.h(qr) pass_ = ApplyLayout() pass_.property_set["layout"] = Layout({qr[0]: 0, ancilla[1]: 1, ancilla[0]: 2, qr[1]: 3}) circuit_with_layout = pass_(circuit) self.assertEqual(str(_text_circuit_drawer(circuit_with_layout)), expected) def test_partial_layout(self): """With a partial layout. See: https://github.com/Qiskit/qiskit-terra/issues/4757""" expected = "\n".join( [ " ┌───┐", "v_0 -> 0 |0>┤ H ├", " └───┘", " 1 |0>─────", " ", " 2 |0>─────", " ┌───┐", "v_1 -> 3 |0>┤ H ├", " └───┘", ] ) qr = QuantumRegister(2, "v") pqr = QuantumRegister(4, "physical") circuit = QuantumCircuit(pqr) circuit.h(0) circuit.h(3) circuit._layout = TranspileLayout( Layout({0: qr[0], 1: None, 2: None, 3: qr[1]}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) circuit._layout.initial_layout.add_register(qr) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_with_classical_regs(self): """Involving classical registers""" expected = "\n".join( [ " ", "qr1_0 -> 0 |0>──────", " ", "qr1_1 -> 1 |0>──────", " ┌─┐ ", "qr2_0 -> 2 |0>┤M├───", " └╥┘┌─┐", "qr2_1 -> 3 |0>─╫─┤M├", " ║ └╥┘", " cr: 0 2/═╩══╩═", " 0 1 ", ] ) qr1 = QuantumRegister(2, "qr1") qr2 = QuantumRegister(2, "qr2") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr1, qr2, cr) circuit.measure(qr2[0], cr[0]) circuit.measure(qr2[1], cr[1]) pass_ = ApplyLayout() pass_.property_set["layout"] = Layout({qr1[0]: 0, qr1[1]: 1, qr2[0]: 2, qr2[1]: 3}) circuit_with_layout = pass_(circuit) self.assertEqual(str(_text_circuit_drawer(circuit_with_layout)), expected) def test_with_layout_but_disable(self): """With parameter without_layout=False""" expected = "\n".join( [ " ", "q_0: |0>──────", " ", "q_1: |0>──────", " ┌─┐ ", "q_2: |0>┤M├───", " └╥┘┌─┐", "q_3: |0>─╫─┤M├", " ║ └╥┘", "cr: 0 2/═╩══╩═", " 0 1 ", ] ) pqr = QuantumRegister(4, "q") qr1 = QuantumRegister(2, "qr1") cr = ClassicalRegister(2, "cr") qr2 = QuantumRegister(2, "qr2") circuit = QuantumCircuit(pqr, cr) circuit._layout = Layout({qr1[0]: 0, qr1[1]: 1, qr2[0]: 2, qr2[1]: 3}) circuit.measure(pqr[2], cr[0]) circuit.measure(pqr[3], cr[1]) self.assertEqual(str(_text_circuit_drawer(circuit, with_layout=False)), expected) def test_after_transpile(self): """After transpile, the drawing should include the layout""" expected = "\n".join( [ " ┌─────────┐┌─────────┐┌───┐┌─────────┐┌─┐ ", " userqr_0 -> 0 ┤ U2(0,π) ├┤ U2(0,π) ├┤ X ├┤ U2(0,π) ├┤M├───", " ├─────────┤├─────────┤└─┬─┘├─────────┤└╥┘┌─┐", " userqr_1 -> 1 ┤ U2(0,π) ├┤ U2(0,π) ├──■──┤ U2(0,π) ├─╫─┤M├", " └─────────┘└─────────┘ └─────────┘ ║ └╥┘", " ancilla_0 -> 2 ───────────────────────────────────────╫──╫─", " ║ ║ ", " ancilla_1 -> 3 ───────────────────────────────────────╫──╫─", " ║ ║ ", " ancilla_2 -> 4 ───────────────────────────────────────╫──╫─", " ║ ║ ", " ancilla_3 -> 5 ───────────────────────────────────────╫──╫─", " ║ ║ ", " ancilla_4 -> 6 ───────────────────────────────────────╫──╫─", " ║ ║ ", " ancilla_5 -> 7 ───────────────────────────────────────╫──╫─", " ║ ║ ", " ancilla_6 -> 8 ───────────────────────────────────────╫──╫─", " ║ ║ ", " ancilla_7 -> 9 ───────────────────────────────────────╫──╫─", " ║ ║ ", " ancilla_8 -> 10 ───────────────────────────────────────╫──╫─", " ║ ║ ", " ancilla_9 -> 11 ───────────────────────────────────────╫──╫─", " ║ ║ ", "ancilla_10 -> 12 ───────────────────────────────────────╫──╫─", " ║ ║ ", "ancilla_11 -> 13 ───────────────────────────────────────╫──╫─", " ║ ║ ", " c0_0: ═══════════════════════════════════════╩══╬═", " ║ ", " c0_1: ══════════════════════════════════════════╩═", " ", ] ) qr = QuantumRegister(2, "userqr") cr = ClassicalRegister(2, "c0") qc = QuantumCircuit(qr, cr) qc.h(qr) qc.cx(qr[0], qr[1]) qc.measure(qr, cr) coupling_map = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] qc_result = transpile( qc, basis_gates=["u1", "u2", "u3", "cx", "id"], coupling_map=coupling_map, optimization_level=0, seed_transpiler=0, ) self.assertEqual(qc_result.draw(output="text", cregbundle=False).single_string(), expected) class TestTextInitialValue(QiskitTestCase): """Testing the initial_state parameter""" def setUp(self) -> None: super().setUp() qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") self.circuit = QuantumCircuit(qr, cr) self.circuit.measure(qr, cr) def test_draw_initial_value_default(self): """Text drawer (.draw) default initial_state parameter (False).""" expected = "\n".join( [ " ┌─┐ ", "q_0: ┤M├───", " └╥┘┌─┐", "q_1: ─╫─┤M├", " ║ └╥┘", "c_0: ═╩══╬═", " ║ ", "c_1: ════╩═", " ", ] ) self.assertEqual( self.circuit.draw(output="text", cregbundle=False).single_string(), expected ) def test_draw_initial_value_true(self): """Text drawer .draw(initial_state=True).""" expected = "\n".join( [ " ┌─┐ ", "q_0: |0>┤M├───", " └╥┘┌─┐", "q_1: |0>─╫─┤M├", " ║ └╥┘", " c_0: 0 ═╩══╬═", " ║ ", " c_1: 0 ════╩═", " ", ] ) self.assertEqual( self.circuit.draw(output="text", initial_state=True, cregbundle=False).single_string(), expected, ) def test_initial_value_false(self): """Text drawer with initial_state parameter False.""" expected = "\n".join( [ " ┌─┐ ", "q_0: ┤M├───", " └╥┘┌─┐", "q_1: ─╫─┤M├", " ║ └╥┘", "c: 2/═╩══╩═", " 0 1 ", ] ) self.assertEqual(str(_text_circuit_drawer(self.circuit, initial_state=False)), expected) class TestTextHamiltonianGate(QiskitTestCase): """Testing the Hamiltonian gate drawer""" def test_draw_hamiltonian_single(self): """Text Hamiltonian gate with single qubit.""" # fmt: off expected = "\n".join([" ┌─────────────┐", "q0: ┤ Hamiltonian ├", " └─────────────┘"]) # fmt: on qr = QuantumRegister(1, "q0") circuit = QuantumCircuit(qr) matrix = numpy.zeros((2, 2)) theta = Parameter("theta") circuit.append(HamiltonianGate(matrix, theta), [qr[0]]) circuit = circuit.bind_parameters({theta: 1}) self.assertEqual(circuit.draw(output="text").single_string(), expected) def test_draw_hamiltonian_multi(self): """Text Hamiltonian gate with mutiple qubits.""" expected = "\n".join( [ " ┌──────────────┐", "q0_0: ┤0 ├", " │ Hamiltonian │", "q0_1: ┤1 ├", " └──────────────┘", ] ) qr = QuantumRegister(2, "q0") circuit = QuantumCircuit(qr) matrix = numpy.zeros((4, 4)) theta = Parameter("theta") circuit.append(HamiltonianGate(matrix, theta), [qr[0], qr[1]]) circuit = circuit.bind_parameters({theta: 1}) self.assertEqual(circuit.draw(output="text").single_string(), expected) class TestTextPhase(QiskitTestCase): """Testing the draweing a circuit with phase""" def test_bell(self): """Text Bell state with phase.""" expected = "\n".join( [ "global phase: \u03C0/2", " ┌───┐ ", "q_0: ┤ H ├──■──", " └───┘┌─┴─┐", "q_1: ─────┤ X ├", " └───┘", ] ) qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.global_phase = 3.141592653589793 / 2 circuit.h(0) circuit.cx(0, 1) self.assertEqual(circuit.draw(output="text").single_string(), expected) def test_empty(self): """Text empty circuit (two registers) with phase.""" # fmt: off expected = "\n".join(["global phase: 3", " ", "q_0: ", " ", "q_1: ", " "]) # fmt: on qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.global_phase = 3 self.assertEqual(circuit.draw(output="text").single_string(), expected) def test_empty_noregs(self): """Text empty circuit (no registers) with phase.""" expected = "\n".join(["global phase: 4.21"]) circuit = QuantumCircuit() circuit.global_phase = 4.21 self.assertEqual(circuit.draw(output="text").single_string(), expected) def test_registerless_one_bit(self): """Text circuit with one-bit registers and registerless bits.""" # fmt: off expected = "\n".join([" ", "qrx_0: ", " ", "qrx_1: ", " ", " 2: ", " ", " 3: ", " ", " qry: ", " ", " 0: ", " ", " 1: ", " ", "crx: 2/", " "]) # fmt: on qrx = QuantumRegister(2, "qrx") qry = QuantumRegister(1, "qry") crx = ClassicalRegister(2, "crx") circuit = QuantumCircuit(qrx, [Qubit(), Qubit()], qry, [Clbit(), Clbit()], crx) self.assertEqual(circuit.draw(output="text", cregbundle=True).single_string(), expected) class TestCircuitVisualizationImplementation(QiskitVisualizationTestCase): """Tests utf8 and cp437 encoding.""" text_reference_utf8 = path_to_diagram_reference("circuit_text_ref_utf8.txt") text_reference_cp437 = path_to_diagram_reference("circuit_text_ref_cp437.txt") def sample_circuit(self): """Generate a sample circuit that includes the most common elements of quantum circuits. """ qr = QuantumRegister(3, "q") cr = ClassicalRegister(3, "c") circuit = QuantumCircuit(qr, cr) circuit.x(qr[0]) circuit.y(qr[0]) circuit.z(qr[0]) circuit.barrier(qr[0]) circuit.barrier(qr[1]) circuit.barrier(qr[2]) circuit.h(qr[0]) circuit.s(qr[0]) circuit.sdg(qr[0]) circuit.t(qr[0]) circuit.tdg(qr[0]) circuit.sx(qr[0]) circuit.sxdg(qr[0]) circuit.i(qr[0]) circuit.reset(qr[0]) circuit.rx(pi, qr[0]) circuit.ry(pi, qr[0]) circuit.rz(pi, qr[0]) circuit.append(U1Gate(pi), [qr[0]]) circuit.append(U2Gate(pi, pi), [qr[0]]) circuit.append(U3Gate(pi, pi, pi), [qr[0]]) circuit.swap(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cy(qr[0], qr[1]) circuit.cz(qr[0], qr[1]) circuit.ch(qr[0], qr[1]) circuit.append(CU1Gate(pi), [qr[0], qr[1]]) circuit.append(CU3Gate(pi, pi, pi), [qr[0], qr[1]]) circuit.crz(pi, qr[0], qr[1]) circuit.cry(pi, qr[0], qr[1]) circuit.crx(pi, qr[0], qr[1]) circuit.ccx(qr[0], qr[1], qr[2]) circuit.cswap(qr[0], qr[1], qr[2]) circuit.measure(qr, cr) return circuit def test_text_drawer_utf8(self): """Test that text drawer handles utf8 encoding.""" filename = "current_textplot_utf8.txt" qc = self.sample_circuit() output = _text_circuit_drawer( qc, filename=filename, fold=-1, initial_state=True, cregbundle=False, encoding="utf8" ) try: encode(str(output), encoding="utf8") except UnicodeEncodeError: self.fail("_text_circuit_drawer() should be utf8.") self.assertFilesAreEqual(filename, self.text_reference_utf8, "utf8") os.remove(filename) def test_text_drawer_cp437(self): """Test that text drawer handles cp437 encoding.""" filename = "current_textplot_cp437.txt" qc = self.sample_circuit() output = _text_circuit_drawer( qc, filename=filename, fold=-1, initial_state=True, cregbundle=False, encoding="cp437" ) try: encode(str(output), encoding="cp437") except UnicodeEncodeError: self.fail("_text_circuit_drawer() should be cp437.") self.assertFilesAreEqual(filename, self.text_reference_cp437, "cp437") os.remove(filename) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit qc = QuantumCircuit(1, 1) qc.h(0) qc.measure(0,0) qc.x(0).c_if(0, 0) qc.draw(output='mpl') from qiskit import QuantumRegister, ClassicalRegister q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') qc = QuantumCircuit(q, c) qc.h([0, 1, 2]) qc.barrier() qc.measure(q, c) qc.draw('mpl') print(bin(3)) print(bin(7)) qc.x(2).c_if(c, 3) # for the 011 case qc.x(2).c_if(c, 7) # for the 111 case qc.draw(output='mpl') nq = 2 m = 2 q = QuantumRegister(nq, 'q') c = ClassicalRegister(m, 'c') qc_S = QuantumCircuit(q,c) qc_S.h(0) qc_S.x(1) qc_S.draw('mpl') from math import pi cu_circ = QuantumCircuit(2) cu_circ.cp(pi/2, 0, 1) cu_circ.draw('mpl') for _ in range(2 ** (m - 1)): qc_S.cp(pi/2, 0, 1) qc_S.draw('mpl') def x_measurement(qc, qubit, cbit): """Measure 'qubit' in the X-basis, and store the result in 'cbit'""" qc.h(qubit) qc.measure(qubit, cbit) x_measurement(qc_S, q[0], c[0]) qc_S.draw('mpl') qc_S.reset(0) qc_S.h(0) qc_S.draw('mpl') qc_S.p(-pi/2, 0).c_if(c, 1) qc_S.draw('mpl') ## 2^t c-U operations (with t=m-2) for _ in range(2 ** (m - 2)): qc_S.cp(pi/2, 0, 1) x_measurement(qc_S, q[0], c[1]) qc_S.draw('mpl') import matplotlib.pyplot as plt from qiskit.tools.visualization import plot_histogram from qiskit_aer.primitives import Sampler sampler = Sampler() job = sampler.run(qc_S) result = job.result() dist0 = result.quasi_dists[0] key_new = [str(key/2**m) for key in list(dist0.keys())] dist1 = dict(zip(key_new, dist0.values())) fig, ax = plt.subplots(1,2) plot_histogram(dist0, ax=ax[0]) plot_histogram(dist1, ax=ax[1]) plt.tight_layout() nq = 3 # number of qubits m = 3 # number of classical bits q = QuantumRegister(nq,'q') c = ClassicalRegister(m,'c') qc = QuantumCircuit(q,c) qc.h(0) qc.x([1, 2]) qc.draw('mpl') cu_circ = QuantumCircuit(nq) cu_circ.mcp(pi/4, [0, 1], 2) cu_circ.draw('mpl') for _ in range(2 ** (m - 1)): qc.mcp(pi/4, [0, 1], 2) qc.draw('mpl') x_measurement(qc, q[0], c[0]) qc.draw('mpl') qc.reset(0) qc.h(0) qc.draw('mpl') qc.p(-pi/2, 0).c_if(c, 1) qc.draw('mpl') for _ in range(2 ** (m - 2)): qc.mcp(pi/4, [0, 1], 2) x_measurement(qc, q[0], c[1]) qc.draw('mpl') # initialization of qubit q0 qc.reset(0) qc.h(0) # phase correction qc.p(-pi/4, 0).c_if(c, 1) qc.p(-pi/2, 0).c_if(c, 2) qc.p(-3*pi/2, 0).c_if(c, 3) # c-U operations for _ in range(2 ** (m - 3)): qc.mcp(pi/4, [0, 1], 2) # X measurement qc.h(0) qc.measure(0, 2) qc.draw('mpl') result = sampler.run(qc).result() dist0 = result.quasi_dists[0] key_new = [str(key/2**m) for key in list(dist0.keys())] dist1 = dict(zip(key_new, dist0.values())) fig, ax = plt.subplots(1,2) plot_histogram(dist0, ax=ax[0]) plot_histogram(dist1, ax=ax[1]) plt.tight_layout() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/carstenblank/dc-qiskit-qml
carstenblank
import logging import unittest import numpy import qiskit from qiskit.providers import BackendV2, JobV1 from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler, Normalizer from dc_qiskit_qml.distance_based.hadamard.state import QmlGenericStateCircuitBuilder from dc_qiskit_qml.distance_based.hadamard.state.sparsevector import MottonenStatePreparation from dc_qiskit_qml.encoding_maps import IdentityEncodingMap logging.basicConfig(format=logging.BASIC_FORMAT, level='INFO') log = logging.getLogger(__name__) class MottonenStatePreparationTest(unittest.TestCase): def runTest(self): from sklearn.datasets import load_iris X, y = load_iris(return_X_y=True) X = numpy.asarray([x[0:2] for x, yy in zip(X, y) if yy != 2]) y = numpy.asarray([yy for x, yy in zip(X, y) if yy != 2]) preprocessing_pipeline = Pipeline([ ('scaler', StandardScaler()), ('l2norm', Normalizer(norm='l2', copy=True)) ]) X = preprocessing_pipeline.fit_transform(X, y) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.10, random_state=42) encoding_map = IdentityEncodingMap() initial_state_builder = QmlGenericStateCircuitBuilder(MottonenStatePreparation()) qc = initial_state_builder.build_circuit("test", [encoding_map.map(e) for e in X_train], y_train, encoding_map.map(X_test[0])) statevector_backend = qiskit.Aer.get_backend('statevector_simulator') # type: BackendV2 job = qiskit.execute(qc, statevector_backend, shots=1) # type: JobV1 simulator_state_vector = numpy.asarray(job.result().get_statevector()) input_state_vector = initial_state_builder.get_last_state_vector() phase = set(numpy.angle(simulator_state_vector)[numpy.abs(simulator_state_vector) > 1e-3]).pop() simulator_state_vector[numpy.abs(simulator_state_vector) < 1e-3] = 0 simulator_state_vector = numpy.exp(-1.0j * phase) * simulator_state_vector for i, s in zip(input_state_vector.toarray(), simulator_state_vector): log.debug("{:.4f} == {:.4f}".format(i[0], s)) self.assertAlmostEqual(i[0], s, places=3)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import torch from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 123456 _ = torch.manual_seed(123456) # suppress output import numpy as np num_dim = 2 num_discrete_values = 8 num_qubits = num_dim * int(np.log2(num_discrete_values)) from scipy.stats import multivariate_normal coords = np.linspace(-2, 2, num_discrete_values) rv = multivariate_normal(mean=[0.0, 0.0], cov=[[1, 0], [0, 1]], seed=algorithm_globals.random_seed) grid_elements = np.transpose([np.tile(coords, len(coords)), np.repeat(coords, len(coords))]) prob_data = rv.pdf(grid_elements) prob_data = prob_data / np.sum(prob_data) import matplotlib.pyplot as plt from matplotlib import cm mesh_x, mesh_y = np.meshgrid(coords, coords) grid_shape = (num_discrete_values, num_discrete_values) fig, ax = plt.subplots(figsize=(9, 9), subplot_kw={"projection": "3d"}) prob_grid = np.reshape(prob_data, grid_shape) surf = ax.plot_surface(mesh_x, mesh_y, prob_grid, cmap=cm.coolwarm, linewidth=0, antialiased=False) fig.colorbar(surf, shrink=0.5, aspect=5) plt.show() from qiskit import QuantumCircuit from qiskit.circuit.library import EfficientSU2 qc = QuantumCircuit(num_qubits) qc.h(qc.qubits) ansatz = EfficientSU2(num_qubits, reps=6) qc.compose(ansatz, inplace=True) qc.decompose().draw("mpl") qc.num_parameters from qiskit.primitives import Sampler shots = 10000 sampler = Sampler(options={"shots": shots, "seed": algorithm_globals.random_seed}) from qiskit_machine_learning.connectors import TorchConnector from qiskit_machine_learning.neural_networks import SamplerQNN def create_generator() -> TorchConnector: qnn = SamplerQNN( circuit=qc, sampler=sampler, input_params=[], weight_params=qc.parameters, sparse=False, ) initial_weights = algorithm_globals.random.random(qc.num_parameters) return TorchConnector(qnn, initial_weights) from torch import nn class Discriminator(nn.Module): def __init__(self, input_size): super(Discriminator, self).__init__() self.linear_input = nn.Linear(input_size, 20) self.leaky_relu = nn.LeakyReLU(0.2) self.linear20 = nn.Linear(20, 1) self.sigmoid = nn.Sigmoid() def forward(self, input: torch.Tensor) -> torch.Tensor: x = self.linear_input(input) x = self.leaky_relu(x) x = self.linear20(x) x = self.sigmoid(x) return x generator = create_generator() discriminator = Discriminator(num_dim) def adversarial_loss(input, target, w): bce_loss = target * torch.log(input) + (1 - target) * torch.log(1 - input) weighted_loss = w * bce_loss total_loss = -torch.sum(weighted_loss) return total_loss from torch.optim import Adam lr = 0.01 # learning rate b1 = 0.7 # first momentum parameter b2 = 0.999 # second momentum parameter generator_optimizer = Adam(generator.parameters(), lr=lr, betas=(b1, b2), weight_decay=0.005) discriminator_optimizer = Adam( discriminator.parameters(), lr=lr, betas=(b1, b2), weight_decay=0.005 ) from IPython.display import clear_output def plot_training_progress(): # we don't plot if we don't have enough data if len(generator_loss_values) < 2: return clear_output(wait=True) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 9)) # Generator Loss ax1.set_title("Loss") ax1.plot(generator_loss_values, label="generator loss", color="royalblue") ax1.plot(discriminator_loss_values, label="discriminator loss", color="magenta") ax1.legend(loc="best") ax1.set_xlabel("Iteration") ax1.set_ylabel("Loss") ax1.grid() # Relative Entropy ax2.set_title("Relative entropy") ax2.plot(entropy_values) ax2.set_xlabel("Iteration") ax2.set_ylabel("Relative entropy") ax2.grid() plt.show() import time from scipy.stats import multivariate_normal, entropy n_epochs = 50 num_qnn_outputs = num_discrete_values**num_dim generator_loss_values = [] discriminator_loss_values = [] entropy_values = [] start = time.time() for epoch in range(n_epochs): valid = torch.ones(num_qnn_outputs, 1, dtype=torch.float) fake = torch.zeros(num_qnn_outputs, 1, dtype=torch.float) # Configure input real_dist = torch.tensor(prob_data, dtype=torch.float).reshape(-1, 1) # Configure samples samples = torch.tensor(grid_elements, dtype=torch.float) disc_value = discriminator(samples) # Generate data gen_dist = generator(torch.tensor([])).reshape(-1, 1) # Train generator generator_optimizer.zero_grad() generator_loss = adversarial_loss(disc_value, valid, gen_dist) # store for plotting generator_loss_values.append(generator_loss.detach().item()) generator_loss.backward(retain_graph=True) generator_optimizer.step() # Train Discriminator discriminator_optimizer.zero_grad() real_loss = adversarial_loss(disc_value, valid, real_dist) fake_loss = adversarial_loss(disc_value, fake, gen_dist.detach()) discriminator_loss = (real_loss + fake_loss) / 2 # Store for plotting discriminator_loss_values.append(discriminator_loss.detach().item()) discriminator_loss.backward() discriminator_optimizer.step() entropy_value = entropy(gen_dist.detach().squeeze().numpy(), prob_data) entropy_values.append(entropy_value) plot_training_progress() elapsed = time.time() - start print(f"Fit in {elapsed:0.2f} sec") with torch.no_grad(): generated_probabilities = generator().numpy() fig = plt.figure(figsize=(18, 9)) # Generated CDF gen_prob_grid = np.reshape(np.cumsum(generated_probabilities), grid_shape) ax1 = fig.add_subplot(1, 3, 1, projection="3d") ax1.set_title("Generated CDF") ax1.plot_surface(mesh_x, mesh_y, gen_prob_grid, linewidth=0, antialiased=False, cmap=cm.coolwarm) ax1.set_zlim(-0.05, 1.05) # Real CDF real_prob_grid = np.reshape(np.cumsum(prob_data), grid_shape) ax2 = fig.add_subplot(1, 3, 2, projection="3d") ax2.set_title("True CDF") ax2.plot_surface(mesh_x, mesh_y, real_prob_grid, linewidth=0, antialiased=False, cmap=cm.coolwarm) ax2.set_zlim(-0.05, 1.05) # Difference ax3 = fig.add_subplot(1, 3, 3, projection="3d") ax3.set_title("Difference between CDFs") ax3.plot_surface( mesh_x, mesh_y, real_prob_grid - gen_prob_grid, linewidth=2, antialiased=False, cmap=cm.coolwarm ) ax3.set_zlim(-0.05, 0.1) plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/magn5452/QiskitQaoa
magn5452
import numpy as np from matplotlib import pyplot as plt from qiskit import Aer from qiskit.visualization import plot_histogram from scipy.optimize import minimize from VehicleRouting.standard.factories.MaxCutFactories import TwoConnectedMaxCutFactory from VehicleRouting.standard.problems.MaxCutProblem import MaxCutProblem from VehicleRouting.functions.functionsMaxCut import get_expectation, get_execute_circuit, create_qaoa_circuit from VehicleRouting.standard.plotter.GraphPlotter import GraphPlotter number_of_vertices = 4 problem_factory = TwoConnectedMaxCutFactory() problem = MaxCutProblem(problem_factory) plotter = GraphPlotter(problem) plotter.plot_problem() graph = problem.get_graph() expectation = get_expectation(graph, p=1) # Returns a function to be optimized p = 4 expectation = get_execute_circuit(graph) # Optimize initial_parameter = np.ones(2 * p) optimization_method = 'COBYLA' optimization_object = minimize(expectation, initial_parameter, method=optimization_method) print(optimization_object) backend = Aer.get_backend('aer_simulator') backend.shots = 2 ^ 12 # Create Circuit with Optimized Parameters optimized_parameters = optimization_object.x qc_res = create_qaoa_circuit(graph, optimized_parameters) qc_res.draw(output="mpl") counts = backend.run(qc_res, seed_simulator=10).result().get_counts() print(counts) plot_histogram(counts) plt.show()
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
# -*- coding: utf-8 -*- # 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. """ The Variational Quantum Eigensolver algorithm. See https://arxiv.org/abs/1304.3061 """ import logging import functools import numpy as np from qiskit import ClassicalRegister, QuantumCircuit from qiskit.aqua.algorithms.adaptive.vq_algorithm import VQAlgorithm from qiskit.aqua import AquaError, Pluggable, PluggableType, get_pluggable_class from qiskit.aqua.utils.backend_utils import is_aer_statevector_backend from qiskit.aqua.utils import find_regs_by_name logger = logging.getLogger(__name__) class VQE(VQAlgorithm): """ The Variational Quantum Eigensolver algorithm. See https://arxiv.org/abs/1304.3061 """ CONFIGURATION = { 'name': 'VQE', 'description': 'VQE Algorithm', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'vqe_schema', 'type': 'object', 'properties': { 'operator_mode': { 'type': 'string', 'default': 'matrix', 'oneOf': [ {'enum': ['matrix', 'paulis', 'grouped_paulis']} ] }, 'initial_point': { 'type': ['array', 'null'], "items": { "type": "number" }, 'default': None }, 'max_evals_grouped': { 'type': 'integer', 'default': 1 } }, 'additionalProperties': False }, 'problems': ['energy', 'ising'], 'depends': [ {'pluggable_type': 'optimizer', 'default': { 'name': 'L_BFGS_B' } }, {'pluggable_type': 'variational_form', 'default': { 'name': 'RYRZ' } }, ], } def __init__(self, operator, var_form, optimizer, operator_mode='matrix', initial_point=None, max_evals_grouped=1, aux_operators=None, callback=None): """Constructor. Args: operator (Operator): Qubit operator operator_mode (str): operator mode, used for eval of operator var_form (VariationalForm): parametrized variational form. optimizer (Optimizer): the classical optimization algorithm. initial_point (numpy.ndarray): optimizer initial point. max_evals_grouped (int): max number of evaluations performed simultaneously aux_operators (list of Operator): Auxiliary operators to be evaluated at each eigenvalue callback (Callable): a callback that can access the intermediate data during the optimization. Internally, four arguments are provided as follows the index of evaluation, parameters of variational form, evaluated mean, evaluated standard devation. """ self.validate(locals()) super().__init__(var_form=var_form, optimizer=optimizer, cost_fn=self._energy_evaluation, initial_point=initial_point) self._optimizer.set_max_evals_grouped(max_evals_grouped) self._callback = callback if initial_point is None: self._initial_point = var_form.preferred_init_points self._operator = operator self._operator_mode = operator_mode self._eval_count = 0 if aux_operators is None: self._aux_operators = [] else: self._aux_operators = [aux_operators] if not isinstance(aux_operators, list) else aux_operators logger.info(self.print_settings()) @classmethod def init_params(cls, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance. Args: params (dict): parameters dictionary algo_input (EnergyInput): EnergyInput instance Returns: VQE: vqe object """ if algo_input is None: raise AquaError("EnergyInput instance is required.") operator = algo_input.qubit_op vqe_params = params.get(Pluggable.SECTION_KEY_ALGORITHM) operator_mode = vqe_params.get('operator_mode') initial_point = vqe_params.get('initial_point') max_evals_grouped = vqe_params.get('max_evals_grouped') # Set up variational form, we need to add computed num qubits # Pass all parameters so that Variational Form can create its dependents var_form_params = params.get(Pluggable.SECTION_KEY_VAR_FORM) var_form_params['num_qubits'] = operator.num_qubits var_form = get_pluggable_class(PluggableType.VARIATIONAL_FORM, var_form_params['name']).init_params(params) # Set up optimizer opt_params = params.get(Pluggable.SECTION_KEY_OPTIMIZER) optimizer = get_pluggable_class(PluggableType.OPTIMIZER, opt_params['name']).init_params(params) return cls(operator, var_form, optimizer, operator_mode=operator_mode, initial_point=initial_point, max_evals_grouped=max_evals_grouped, aux_operators=algo_input.aux_ops) @property def setting(self): """Prepare the setting of VQE as a string.""" ret = "Algorithm: {}\n".format(self._configuration['name']) params = "" for key, value in self.__dict__.items(): if key != "_configuration" and key[0] == "_": if "initial_point" in key and value is None: params += "-- {}: {}\n".format(key[1:], "Random seed") else: params += "-- {}: {}\n".format(key[1:], value) ret += "{}".format(params) return ret def print_settings(self): """ Preparing the setting of VQE into a string. Returns: str: the formatted setting of VQE """ ret = "\n" ret += "==================== Setting of {} ============================\n".format(self.configuration['name']) ret += "{}".format(self.setting) ret += "===============================================================\n" ret += "{}".format(self._var_form.setting) ret += "===============================================================\n" ret += "{}".format(self._optimizer.setting) ret += "===============================================================\n" return ret def construct_circuit(self, parameter, backend=None, use_simulator_operator_mode=False): """Generate the circuits. Args: parameters (numpy.ndarray): parameters for variational form. backend (qiskit.BaseBackend): backend object. use_simulator_operator_mode (bool): is backend from AerProvider, if True and mode is paulis, single circuit is generated. Returns: [QuantumCircuit]: the generated circuits with Hamiltonian. """ input_circuit = self._var_form.construct_circuit(parameter) if backend is None: warning_msg = "Circuits used in VQE depends on the backend type, " from qiskit import BasicAer if self._operator_mode == 'matrix': temp_backend_name = 'statevector_simulator' else: temp_backend_name = 'qasm_simulator' backend = BasicAer.get_backend(temp_backend_name) warning_msg += "since operator_mode is '{}', '{}' backend is used.".format( self._operator_mode, temp_backend_name) logger.warning(warning_msg) circuit = self._operator.construct_evaluation_circuit(self._operator_mode, input_circuit, backend, use_simulator_operator_mode) return circuit def _eval_aux_ops(self, threshold=1e-12, params=None): if params is None: params = self.optimal_params wavefn_circuit = self._var_form.construct_circuit(params) circuits = [] values = [] params = [] for operator in self._aux_operators: if not operator.is_empty(): temp_circuit = QuantumCircuit() + wavefn_circuit circuit = operator.construct_evaluation_circuit(self._operator_mode, temp_circuit, self._quantum_instance.backend, self._use_simulator_operator_mode) params.append(operator.aer_paulis) else: circuit = None circuits.append(circuit) if len(circuits) > 0: to_be_simulated_circuits = functools.reduce(lambda x, y: x + y, [c for c in circuits if c is not None]) if self._use_simulator_operator_mode: extra_args = {'expectation': { 'params': params, 'num_qubits': self._operator.num_qubits} } else: extra_args = {} result = self._quantum_instance.execute(to_be_simulated_circuits, **extra_args) for operator, circuit in zip(self._aux_operators, circuits): if circuit is None: mean, std = 0.0, 0.0 else: mean, std = operator.evaluate_with_result(self._operator_mode, circuit, self._quantum_instance.backend, result, self._use_simulator_operator_mode) mean = mean.real if abs(mean.real) > threshold else 0.0 std = std.real if abs(std.real) > threshold else 0.0 values.append((mean, std)) if len(values) > 0: aux_op_vals = np.empty([1, len(self._aux_operators), 2]) aux_op_vals[0, :] = np.asarray(values) self._ret['aux_ops'] = aux_op_vals def _run(self): """ Run the algorithm to compute the minimum eigenvalue. Returns: Dictionary of results """ if not self._quantum_instance.is_statevector and self._operator_mode == 'matrix': logger.warning('Qasm simulation does not work on {} mode, changing ' 'the operator_mode to "paulis"'.format(self._operator_mode)) self._operator_mode = 'paulis' self._use_simulator_operator_mode = \ is_aer_statevector_backend(self._quantum_instance.backend) \ and self._operator_mode != 'matrix' self._quantum_instance.circuit_summary = True self._eval_count = 0 self._ret = self.find_minimum(initial_point=self.initial_point, var_form=self.var_form, cost_fn=self._energy_evaluation, optimizer=self.optimizer) if self._ret['num_optimizer_evals'] is not None and self._eval_count >= self._ret['num_optimizer_evals']: self._eval_count = self._ret['num_optimizer_evals'] self._eval_time = self._ret['eval_time'] logger.info('Optimization complete in {} seconds.\nFound opt_params {} in {} evals'.format( self._eval_time, self._ret['opt_params'], self._eval_count)) self._ret['eval_count'] = self._eval_count self._ret['energy'] = self.get_optimal_cost() self._ret['eigvals'] = np.asarray([self.get_optimal_cost()]) self._ret['eigvecs'] = np.asarray([self.get_optimal_vector()]) self._eval_aux_ops() return self._ret # This is the objective function to be passed to the optimizer that is uses for evaluation def _energy_evaluation(self, parameters): """ Evaluate energy at given parameters for the variational form. Args: parameters (numpy.ndarray): parameters for variational form. Returns: float or list of float: energy of the hamiltonian of each parameter. """ num_parameter_sets = len(parameters) // self._var_form.num_parameters circuits = [] parameter_sets = np.split(parameters, num_parameter_sets) mean_energy = [] std_energy = [] for idx in range(len(parameter_sets)): parameter = parameter_sets[idx] circuit = self.construct_circuit(parameter, self._quantum_instance.backend, self._use_simulator_operator_mode) circuits.append(circuit) to_be_simulated_circuits = functools.reduce(lambda x, y: x + y, circuits) if self._use_simulator_operator_mode: extra_args = {'expectation': { 'params': [self._operator.aer_paulis], 'num_qubits': self._operator.num_qubits} } else: extra_args = {} result = self._quantum_instance.execute(to_be_simulated_circuits, **extra_args) for idx in range(len(parameter_sets)): mean, std = self._operator.evaluate_with_result( self._operator_mode, circuits[idx], self._quantum_instance.backend, result, self._use_simulator_operator_mode) mean_energy.append(np.real(mean)) std_energy.append(np.real(std)) self._eval_count += 1 if self._callback is not None: self._callback(self._eval_count, parameter_sets[idx], np.real(mean), np.real(std)) logger.info('Energy evaluation {} returned {}'.format(self._eval_count, np.real(mean))) return mean_energy if len(mean_energy) > 1 else mean_energy[0] def get_optimal_cost(self): if 'opt_params' not in self._ret: raise AquaError("Cannot return optimal cost before running the algorithm to find optimal params.") return self._ret['min_val'] def get_optimal_circuit(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal circuit before running the algorithm to find optimal params.") return self._var_form.construct_circuit(self._ret['opt_params']) def get_optimal_vector(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal vector before running the algorithm to find optimal params.") qc = self.get_optimal_circuit() if self._quantum_instance.is_statevector: ret = self._quantum_instance.execute(qc) self._ret['min_vector'] = ret.get_statevector(qc, decimals=16) else: c = ClassicalRegister(qc.width(), name='c') q = find_regs_by_name(qc, 'q') qc.add_register(c) qc.barrier(q) qc.measure(q, c) ret = self._quantum_instance.execute(qc) self._ret['min_vector'] = ret.get_counts(qc) return self._ret['min_vector'] @property def optimal_params(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal params before running the algorithm.") return self._ret['opt_params']
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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. """UnitaryGate tests""" import json import numpy from numpy.testing import assert_allclose import qiskit from qiskit.extensions.unitary import UnitaryGate from qiskit.test import QiskitTestCase from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.transpiler import PassManager from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info.operators import Operator from qiskit.transpiler.passes import CXCancellation class TestUnitaryGate(QiskitTestCase): """Tests for the Unitary class.""" def test_set_matrix(self): """Test instantiation""" try: UnitaryGate([[0, 1], [1, 0]]) # pylint: disable=broad-except except Exception as err: self.fail(f"unexpected exception in init of Unitary: {err}") def test_set_matrix_raises(self): """test non-unitary""" try: UnitaryGate([[1, 1], [1, 0]]) # pylint: disable=broad-except except Exception: pass else: self.fail("setting Unitary with non-unitary did not raise") def test_set_init_with_unitary(self): """test instantiation of new unitary with another one (copy)""" uni1 = UnitaryGate([[0, 1], [1, 0]]) uni2 = UnitaryGate(uni1) self.assertEqual(uni1, uni2) self.assertFalse(uni1 is uni2) def test_conjugate(self): """test conjugate""" ymat = numpy.array([[0, -1j], [1j, 0]]) uni = UnitaryGate([[0, 1j], [-1j, 0]]) self.assertTrue(numpy.array_equal(uni.conjugate().to_matrix(), ymat)) def test_adjoint(self): """test adjoint operation""" uni = UnitaryGate([[0, 1j], [-1j, 0]]) self.assertTrue(numpy.array_equal(uni.adjoint().to_matrix(), uni.to_matrix())) class TestUnitaryCircuit(QiskitTestCase): """Matrix gate circuit tests.""" def test_1q_unitary(self): """test 1 qubit unitary matrix""" qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) matrix = numpy.array([[1, 0], [0, 1]]) qc.x(qr[0]) qc.append(UnitaryGate(matrix), [qr[0]]) # test of qasm output self.log.info(qc.qasm()) # test of text drawer self.log.info(qc) dag = circuit_to_dag(qc) dag_nodes = dag.named_nodes("unitary") self.assertTrue(len(dag_nodes) == 1) dnode = dag_nodes[0] self.assertIsInstance(dnode.op, UnitaryGate) self.assertEqual(dnode.qargs, (qr[0],)) assert_allclose(dnode.op.to_matrix(), matrix) def test_2q_unitary(self): """test 2 qubit unitary matrix""" qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) sigmax = numpy.array([[0, 1], [1, 0]]) sigmay = numpy.array([[0, -1j], [1j, 0]]) matrix = numpy.kron(sigmax, sigmay) qc.x(qr[0]) uni2q = UnitaryGate(matrix) qc.append(uni2q, [qr[0], qr[1]]) passman = PassManager() passman.append(CXCancellation()) qc2 = passman.run(qc) # test of qasm output self.log.info(qc2.qasm()) # test of text drawer self.log.info(qc2) dag = circuit_to_dag(qc) nodes = dag.two_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, UnitaryGate) self.assertEqual(dnode.qargs, (qr[0], qr[1])) assert_allclose(dnode.op.to_matrix(), matrix) qc3 = dag_to_circuit(dag) self.assertEqual(qc2, qc3) def test_3q_unitary(self): """test 3 qubit unitary matrix on non-consecutive bits""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) sigmax = numpy.array([[0, 1], [1, 0]]) sigmay = numpy.array([[0, -1j], [1j, 0]]) matrix = numpy.kron(sigmay, numpy.kron(sigmax, sigmay)) qc.x(qr[0]) uni3q = UnitaryGate(matrix) qc.append(uni3q, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) # test of text drawer self.log.info(qc) dag = circuit_to_dag(qc) nodes = dag.multi_qubit_ops() self.assertEqual(len(nodes), 1) dnode = nodes[0] self.assertIsInstance(dnode.op, UnitaryGate) self.assertEqual(dnode.qargs, (qr[0], qr[1], qr[3])) assert_allclose(dnode.op.to_matrix(), matrix) def test_1q_unitary_int_qargs(self): """test single qubit unitary matrix with 'int' and 'list of ints' qubits argument""" sigmax = numpy.array([[0, 1], [1, 0]]) sigmaz = numpy.array([[1, 0], [0, -1]]) # new syntax qr = QuantumRegister(2) qc = QuantumCircuit(qr) qc.unitary(sigmax, 0) qc.unitary(sigmax, qr[1]) qc.unitary(sigmaz, [0, 1]) # expected circuit qc_target = QuantumCircuit(qr) qc_target.append(UnitaryGate(sigmax), [0]) qc_target.append(UnitaryGate(sigmax), [qr[1]]) qc_target.append(UnitaryGate(sigmaz), [[0, 1]]) self.assertEqual(qc, qc_target) def test_qobj_with_unitary_matrix(self): """test qobj output with unitary matrix""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) sigmax = numpy.array([[0, 1], [1, 0]]) sigmay = numpy.array([[0, -1j], [1j, 0]]) matrix = numpy.kron(sigmay, numpy.kron(sigmax, sigmay)) qc.rx(numpy.pi / 4, qr[0]) uni = UnitaryGate(matrix) qc.append(uni, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) qobj = qiskit.compiler.assemble(qc) instr = qobj.experiments[0].instructions[1] self.assertEqual(instr.name, "unitary") assert_allclose(numpy.array(instr.params[0]).astype(numpy.complex64), matrix) # check conversion to dict qobj_dict = qobj.to_dict() class NumpyEncoder(json.JSONEncoder): """Class for encoding json str with complex and numpy arrays.""" def default(self, obj): if isinstance(obj, numpy.ndarray): return obj.tolist() if isinstance(obj, complex): return (obj.real, obj.imag) return json.JSONEncoder.default(self, obj) # check json serialization self.assertTrue(isinstance(json.dumps(qobj_dict, cls=NumpyEncoder), str)) def test_labeled_unitary(self): """test qobj output with unitary matrix""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) sigmax = numpy.array([[0, 1], [1, 0]]) sigmay = numpy.array([[0, -1j], [1j, 0]]) matrix = numpy.kron(sigmax, sigmay) uni = UnitaryGate(matrix, label="xy") qc.append(uni, [qr[0], qr[1]]) qobj = qiskit.compiler.assemble(qc) instr = qobj.experiments[0].instructions[0] self.assertEqual(instr.name, "unitary") self.assertEqual(instr.label, "xy") def test_qasm_unitary_only_one_def(self): """test that a custom unitary can be converted to qasm and the definition is only written once""" qr = QuantumRegister(2, "q0") cr = ClassicalRegister(1, "c0") qc = QuantumCircuit(qr, cr) matrix = numpy.array([[1, 0], [0, 1]]) unitary_gate = UnitaryGate(matrix) qc.x(qr[0]) qc.append(unitary_gate, [qr[0]]) qc.append(unitary_gate, [qr[1]]) expected_qasm = ( "OPENQASM 2.0;\n" 'include "qelib1.inc";\n' "gate unitary q0 { u(0,0,0) q0; }\n" "qreg q0[2];\ncreg c0[1];\n" "x q0[0];\n" "unitary q0[0];\n" "unitary q0[1];\n" ) self.assertEqual(expected_qasm, qc.qasm()) def test_qasm_unitary_twice(self): """test that a custom unitary can be converted to qasm and that if the qasm is called twice it is the same every time""" qr = QuantumRegister(2, "q0") cr = ClassicalRegister(1, "c0") qc = QuantumCircuit(qr, cr) matrix = numpy.array([[1, 0], [0, 1]]) unitary_gate = UnitaryGate(matrix) qc.x(qr[0]) qc.append(unitary_gate, [qr[0]]) qc.append(unitary_gate, [qr[1]]) expected_qasm = ( "OPENQASM 2.0;\n" 'include "qelib1.inc";\n' "gate unitary q0 { u(0,0,0) q0; }\n" "qreg q0[2];\ncreg c0[1];\n" "x q0[0];\n" "unitary q0[0];\n" "unitary q0[1];\n" ) self.assertEqual(expected_qasm, qc.qasm()) self.assertEqual(expected_qasm, qc.qasm()) def test_qasm_2q_unitary(self): """test that a 2 qubit custom unitary can be converted to qasm""" qr = QuantumRegister(2, "q0") cr = ClassicalRegister(1, "c0") qc = QuantumCircuit(qr, cr) matrix = numpy.asarray([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]]) unitary_gate = UnitaryGate(matrix) qc.x(qr[0]) qc.append(unitary_gate, [qr[0], qr[1]]) qc.append(unitary_gate, [qr[1], qr[0]]) expected_qasm = ( "OPENQASM 2.0;\n" 'include "qelib1.inc";\n' "gate unitary q0,q1 { u(pi,-pi/2,pi/2) q0; u(pi,pi/2,-pi/2) q1; }\n" "qreg q0[2];\n" "creg c0[1];\n" "x q0[0];\n" "unitary q0[0],q0[1];\n" "unitary q0[1],q0[0];\n" ) self.assertEqual(expected_qasm, qc.qasm()) def test_qasm_unitary_noop(self): """Test that an identity unitary can be converted to OpenQASM 2""" qc = QuantumCircuit(QuantumRegister(3, "q0")) qc.unitary(numpy.eye(8), qc.qubits) expected_qasm = ( "OPENQASM 2.0;\n" 'include "qelib1.inc";\n' "gate unitary q0,q1,q2 { }\n" "qreg q0[3];\n" "unitary q0[0],q0[1],q0[2];\n" ) self.assertEqual(expected_qasm, qc.qasm()) def test_unitary_decomposition(self): """Test decomposition for unitary gates over 2 qubits.""" qc = QuantumCircuit(3) qc.unitary(random_unitary(8, seed=42), [0, 1, 2]) self.assertTrue(Operator(qc).equiv(Operator(qc.decompose()))) def test_unitary_decomposition_via_definition(self): """Test decomposition for 1Q unitary via definition.""" mat = numpy.array([[0, 1], [1, 0]]) self.assertTrue(numpy.allclose(Operator(UnitaryGate(mat).definition).data, mat)) def test_unitary_decomposition_via_definition_2q(self): """Test decomposition for 2Q unitary via definition.""" mat = numpy.array([[0, 0, 1, 0], [0, 0, 0, -1], [1, 0, 0, 0], [0, -1, 0, 0]]) self.assertTrue(numpy.allclose(Operator(UnitaryGate(mat).definition).data, mat)) def test_unitary_control(self): """Test parameters of controlled - unitary.""" mat = numpy.array([[0, 1], [1, 0]]) gate = UnitaryGate(mat).control() self.assertTrue(numpy.allclose(gate.params, mat)) self.assertTrue(numpy.allclose(gate.base_gate.params, mat))
https://github.com/urwin419/QiskitChecker
urwin419
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### replaced cx gate ### qc.cy(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) return qc
https://github.com/bayesian-randomized-benchmarking/qiskit-advocates-bayes-RB
bayesian-randomized-benchmarking
import numpy as np import copy from qiskit_experiments.library import StandardRB, InterleavedRB from qiskit_experiments.framework import ParallelExperiment from qiskit_experiments.library.randomized_benchmarking import RBUtils import qiskit.circuit.library as circuits # for retrieving gate calibration from datetime import datetime import qiskit.providers.aer.noise.device as dv # import the bayesian packages import pymc3 as pm import arviz as az import unif_bayesian_fitter as bf simulation = False # make your choice here if simulation: from qiskit.providers.aer import AerSimulator from qiskit.test.mock import FakeParis backend = AerSimulator.from_backend(FakeParis()) else: from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_bogota') # type here hardware backend # for WIP import importlib importlib.reload(bf) # describe RB experiment interleaved_gate ='' physical_qubits = qubits = (0,1) nQ = len(qubits) scale = (2 ** nQ - 1) / 2 ** nQ # defined for the 2-qubit run lengths = np.arange(1, 200, 30) lengths_1_qubit = np.arange(1, 2225, 225) num_samples = 10 seed = 1010 # Run a 1-qubit RB expriment on each qubit to determine the error-per-gate of 1-qubit gates expdata_1q = {} epg_1q = [] for qubit in qubits: exp = StandardRB([qubit], lengths_1_qubit, num_samples=num_samples, seed=seed) expdata = exp.run(backend).block_for_results() expdata_1q[qubit] = expdata epg_1q += expdata.analysis_results() # Run an RB experiment on 2 qubits exp2 = StandardRB(qubits, lengths, num_samples=num_samples, seed=seed) # Use the EPG data of the 1-qubit runs to ensure correct 2-qubit EPG computation exp2.set_analysis_options(epg_1_qubit=epg_1q) # Run the 2-qubit experiment expdata2 = exp2.run(backend).block_for_results() # View result data results2 = expdata2.analysis_results() # View result data display(expdata2.figure(0)) for result in results2: print(result) # example of interpolated EPC_cal for hardware experiments # EPC0 + (t_exp - tO) * (EPC1 - EPC0) / (t1 - t0) # code here: epc_calib = 0.010745 + (22+40/60-7)*(0.008261 - 0.010745)/24 print('EPC calibration: {0:0.4e}'.format(epc_calib)) popt = expdata2.analysis_results()[0].value.value pcov = expdata2.analysis_results()[0].extra['covariance_mat'] epc_est_fm = expdata2.analysis_results()[2].value.value epc_est_fm_err = expdata2.analysis_results()[2].value.stderr EPG_dic = {} EPG_key = 'cx' #expdata2.analysis_results()[3].name EPG_dic[EPG_key] = expdata2.analysis_results()[3].value.value nQ = len(qubits) scale = (2 ** nQ - 1) / 2 ** nQ desired_gate ='cx' # get count data Y = bf.get_GSP_counts(expdata2._data, len(lengths),range(num_samples)) experiment_type = expdata2._data[0]['metadata']['experiment_type'] physical_qubits = expdata2._data[0]['metadata']['physical_qubits'] shots = expdata2._data[0]['shots'] #build model S2QBp_model = bf.build_bayesian_model(model_type="pooled",Y=Y, shots=shots,m_gates=lengths, popt = popt, pcov = pcov) pm.model_to_graphviz(S2QBp_model) trace_p2 = bf.get_trace(S2QBp_model, target_accept = 0.95) bf.RB_bayesian_results(S2QBp_model, trace_p2, lengths, epc_est_fm, epc_est_fm_err, experiment_type, scale, num_samples, Y, shots, physical_qubits, interleaved_gate, backend, EPG_dic = EPG_dic, routine = 'build_bayesian_model') # example of interpolated EPC_cal for hardware experiments # EPC0 + (t_exp - tO) * (EPC1 - EPC0) / (t1 - t0) # code here: epc_calib = 0.010745 + (22+40/60-7)*(0.008261 - 0.010745)/24 print('EPC calibration: {0:0.4e}'.format(epc_calib)) #build model S2QBh_model = bf.build_bayesian_model(model_type="h_sigma",Y=Y,shots=shots,m_gates=lengths, popt = popt, pcov = pcov, sigma_theta=0.001,sigma_theta_l=0.0005,sigma_theta_u=0.0015) pm.model_to_graphviz(S2QBh_model) trace_h2 = bf.get_trace(S2QBh_model) bf.RB_bayesian_results(S2QBh_model, trace_h2, lengths, epc_est_fm, epc_est_fm_err, experiment_type, scale, num_samples, Y, shots, physical_qubits, interleaved_gate, backend, EPG_dic = EPG_dic, routine = 'build_bayesian_model') # example of interpolated EPC_cal for hardware experiments # EPC0 + (t_exp - tO) * (EPC1 - EPC0) / (t1 - t0) # code here: epc_calib = 0.010745 + (22+40/60-7)*(0.008261 - 0.010745)/24 print('EPC calibration: {0:0.4e}'.format(epc_calib)) # describe RB experiment interleaved_gate = "cx" physical_qubits = qubits = [0,1] interleaved_circuit = circuits.CXGate() lengths = np.arange(1, 200, 30) num_samples = 10 seed = 1010 # example of interpolated EPC_cal for hardware experiments # EPC0 + (t_exp - tO) * (EPC1 - EPC0) / (t1 - t0) # code here: epc_calib = 0.010745 + (22+19/60-7)*(0.008261 - 0.010745)/24 print('EPC calibration: {0:0.4e}'.format(epc_calib)) # Run an interleaved RB experiment int_exp2 = InterleavedRB(interleaved_circuit, qubits, lengths, num_samples=num_samples, seed=seed) # Run int_expdata2 = int_exp2.run(backend).block_for_results() int_results2 = int_expdata2.analysis_results() # View result data display(int_expdata2.figure(0)) for result in int_results2: print(result) popt = int_expdata2.analysis_results()[0].value.value pcov = int_expdata2.analysis_results()[0].extra['covariance_mat'] popt[2] = popt[1]/popt[2] # replace alpha_C by p_tilde epc_est_fm = int_expdata2.analysis_results()[3].value.value epc_est_fm_err = int_expdata2.analysis_results()[3].value.stderr nQ = len(qubits) scale = (2 ** nQ - 1) / 2 ** nQ interleaved_gate ='cx' # get count data Y1 = bf.get_GSP_counts(int_expdata2._data, len(lengths), range(0,2*num_samples-1,2)) Y2 = bf.get_GSP_counts(int_expdata2._data, len(lengths), range(1,2*num_samples,2)) int_expdata2._data[1] experiment_type = int_expdata2._data[0]['metadata']['experiment_type'] physical_qubits = int_expdata2._data[0]['metadata']['physical_qubits'] shots = int_expdata2._data[0]['shots'] Y = np.vstack((Y1,Y2)) RvsI = np.vstack((np.ones_like(Y1),np.zeros_like(Y2))) IvsR = np.vstack((np.zeros_like(Y1),np.ones_like(Y2))) tilde3 = bf.build_bayesian_model("tilde",Y=Y,shots=shots, m_gates=lengths, popt = popt, pcov = pcov, RvsI=RvsI,IvsR=IvsR) pm.model_to_graphviz(tilde3) trace_t3 = bf.get_trace(tilde3) bf.RB_bayesian_results(tilde3, trace_t3, lengths, epc_est_fm, epc_est_fm_err, experiment_type, scale, num_samples, Y, shots, physical_qubits, interleaved_gate, backend, epc_calib = epc_calib, Y1 = Y1, Y2 = Y2, routine = 'build_bayesian_model') # use 2m length array RvsI_h = np.ravel(np.vstack((np.ones_like(lengths),np.zeros_like(lengths)))) IvsR_h = np.ravel(np.vstack((np.zeros_like(lengths),np.ones_like(lengths)))) tilde4 = bf.build_bayesian_model("h_tilde",Y=np.hstack((Y1,Y2)), shots=shots, m_gates=lengths, popt = popt, pcov = pcov, RvsI = RvsI_h, IvsR = IvsR_h, sigma_theta=0.005,sigma_theta_l=0.001,sigma_theta_u=0.05) pm.model_to_graphviz(tilde4) trace_t4 = bf.get_trace(tilde4, target_accept = .99) bf.RB_bayesian_results(tilde4, trace_t4, lengths, epc_est_fm, epc_est_fm_err, experiment_type, scale, num_samples, Y, shots, physical_qubits, interleaved_gate, backend, epc_calib = epc_calib, Y1 = Y1, Y2 = Y2, routine = 'build_bayesian_model')
https://github.com/CodeJP97/QHT-2022-WoQ
CodeJP97
import numpy as np from qiskit_textbook.tools import random_state # Importing standard Qiskit libraries from qiskit import QuantumCircuit,QuantumRegister, ClassicalRegister, transpile, Aer, IBMQ, assemble, execute from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit_textbook.tools import random_state from qiskit.extensions import Initialize from qiskit.providers.aer.noise import NoiseModel import qiskit.quantum_info as qi # Loading your IBM Quantum account(s) provider = IBMQ.load_account() qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical bits crx = ClassicalRegister(1, name="crx") # in 2 different register teleportation_circuit = QuantumCircuit(qr, crz, crx) def psi_00(circuit, q1, q2): circuit.h(q1) circuit.cx(q1,q2) return circuit def Bell_measurement(circuit, q1, q2,crx, crz): # FILL YOUR CODE HERE circuit.cx(q2,q1) circuit.h(q2) circuit.measure(q1,crx) circuit.measure(q2,crz) return circuit def conditional_gates(circuit, q0, crx, crz): circuit.x(q0).c_if(crx,1) circuit.z(q0).c_if(crz,1) return circuit qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") #Classical Registers teleportation_circuit = QuantumCircuit(qr, crz, crx) #STEP 1: Create the Bell state between q0 and q1 psi_00(teleportation_circuit, 0, 1 ) #STEP 2: Bell Measurement teleportation_circuit.barrier() Bell_measurement(teleportation_circuit, 1, 2, crx, crz) #STEP 3: Conditional Gates teleportation_circuit.barrier() conditional_gates(teleportation_circuit,0, crx, crz) teleportation_circuit.draw() def new_conditional_gates(circuit, q0): # FILL YOUR CODE HERE def new_Bell_measurement(circuit, q1, q2): # FILL YOUR CODE HERE inverse_init_gate = init_gate.gates_to_uncompute() psi = random_state(1) init_gate = Initialize(psi) init_gate.label = "init" qr = QuantumRegister(3) # Protocol uses 3 qubits cr=ClassicalRegister(1) teleportation_circuit = QuantumCircuit(qr, cr) # STEP 0: let's initialize Bob's q2 teleportation_circuit.append(init_gate, [2]) teleportation_circuit.barrier() #STEP 1: Create the Bell state between q0 and q1 psi_00(teleportation_circuit, 0, 1 ) #STEP 2: Bell Measurement teleportation_circuit.barrier() new_Bell_measurement(teleportation_circuit, 1, 2) #STEP 3: Conditional Gates teleportation_circuit.barrier() new_conditional_gates(teleportation_circuit,0) # teleportation_circuit.append(inverse_init_gate, [0]) teleportation_circuit.measure(0,0) teleportation_circuit.draw() # Build noise model from backend properties # provider = IBMQ.load_account() backend = provider.get_backend('ibmq_belem') noise_model = NoiseModel.from_backend(backend) # Get coupling map from backend coupling_map = backend.configuration().coupling_map # Get basis gates from noise model basis_gates = noise_model.basis_gates # Perform a noise simulation result = execute(teleportation_circuit, Aer.get_backend('qasm_simulator'), coupling_map=coupling_map, basis_gates=basis_gates, noise_model=noise_model).result() counts = result.get_counts() plot_histogram(counts) #Without Noise Model # backend = provider.get_backend('aer_simulator') result = execute(teleportation_circuit, Aer.get_backend('qasm_simulator'), coupling_map=coupling_map).result() counts2 = result.get_counts() plot_histogram(counts2) # FILL YOUR CODE HERE to calculate fidelity plot_histogram(counts) print(state1)