repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/theflyingrahul/qiskitsummerschool2020
theflyingrahul
!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/achilles-d/qiskitsummerjam
achilles-d
# Set up your quantum environment. from qiskit import IBMQ IBMQ.save_account('PASTE QUANTUM KEY HERE') print('Setup Done')
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/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts 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("./") 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) # 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(qc, targets=[0,1,2]) # decode # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time t1 = time.perf_counter() qc = qc.bind_parameters({dt: target_time / num_steps}) t2 = time.perf_counter() print("created qc,", t2 - t1, "s") # Generate state tomography circuits to evaluate fidelity of simulation t1 = time.perf_counter() st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN === t2 = time.perf_counter() print("created st_qcs (length:", len(st_qcs), "),", t2 - t1, "s") # remove barriers t1 = time.perf_counter() st_qcs = [RemoveBarriers()(qc) for qc in st_qcs] t2 = time.perf_counter() print("removed barriers from st_qcs,", t2 - t1, "s") # optimize circuit t1 = time.perf_counter() t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("created t3_st_qcs (length:", len(t3_st_qcs), "),", t2 - t1, "s") t3_st_qcs[0].draw("mpl") # zne wrapping t1 = time.perf_counter() zne_qcs = zne_wrapper(t3_st_qcs) t2 = time.perf_counter() print("created zne_qcs (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("decomposed zne_qcs into basis gates (length:", len(zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"]) t2 = time.perf_counter() print("optimized zne_qcs -> create t3_zne_qcs (length:", len(t3_zne_qcs), "),", t2 - t1, "s") t1 = time.perf_counter() t3_zne_qcs = transpile(t3_zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout) t2 = time.perf_counter() print("fit the t3_zne_qcs to the initial layoit (length:", len(t3_zne_qcs), "),", t2 - t1, "s") 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-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/mrvee-qC-bee/SCQC23
mrvee-qC-bee
import numpy as np # for plotting results import matplotlib.pyplot as plt # Import Scikit-learn(QML library for Python) from sklearn import datasets from sklearn.model_selection import train_test_split # for splitting test data from sklearn.svm import SVC # SVM Classification from sklearn.decomposition import PCA # Principal component analysis from sklearn.preprocessing import StandardScaler, MinMaxScaler # for standardization, normalization scale conversion # Import Qiskit from qiskit import Aer, execute from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap from qiskit_machine_learning.kernels import QuantumKernel # Reads two classes of data (0 and 1) from a numeric data set digits = datasets.load_digits(n_class=2) # Plot the first 100 images loaded fig, axes = plt.subplots(10, 10, figsize=(15, 15), subplot_kw={'xticks':[], 'yticks':[]}, gridspec_kw=dict(hspace=0.5, wspace=0.5)) for i, ax in enumerate(axes.flat): ax.set_axis_off() ax.imshow(digits.images[i], cmap=plt.cm.gray_r, interpolation='nearest') ax.set_title(digits.target[i]) print(digits.images[0]) # Splitting the dataset sample_train, sample_test, labels_train, labels_test = train_test_split( digits.data, digits.target, test_size=0.2, random_state=22) # Delete dimension n_dim = 4 pca = PCA(n_components=n_dim).fit(sample_train) sample_train = pca.transform(sample_train) sample_test = pca.transform(sample_test) # Standardize std_scale = StandardScaler().fit(sample_train) sample_train = std_scale.transform(sample_train) sample_test = std_scale.transform(sample_test) # Normalize 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 100 for training and 20 for testing train_size = 100 sample_train = sample_train[:train_size] labels_train = labels_train[:train_size] test_size = 20 sample_test = sample_test[:test_size] labels_test = labels_test[:test_size] # Display each of the first data print(sample_train[0], labels_train[0]) print(sample_test[0], labels_test[0]) # ZZFeatureMap with 4 features and depth (number of iterations)1 zz_map = ZZFeatureMap(feature_dimension=4, reps=1, entanglement='linear', insert_barriers=True) zz_map.decompose().draw('mpl') 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() zzpc_svc = SVC(kernel='precomputed') zzpc_svc.fit(matrix_train, labels_train) # Train zzpc_score = zzpc_svc.score(matrix_test, labels_test) # Determine the percentage of correct answers print(f'Kernel classification test score: {zzpc_score}') # General imports import os import gzip import numpy as np import matplotlib.pyplot as plt from pylab import cm import warnings warnings.filterwarnings("ignore") # Import Scikit-learn(QML library for Python) 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 # Import Qiskit 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 data DATA_PATH = 'fashion.npz' data = np.load(DATA_PATH) sample_train = data['sample_train'] labels_train = data['labels_train'] sample_test = data['sample_test'] # Splitting the dataset sample_train, sample_test, labels_train, labels_test = train_test_split( sample_train, labels_train, test_size=0.2, random_state=42) # Show data fig = plt.figure() LABELS = [2,3] num_labels = len(LABELS) for i in range(num_labels): ax = fig.add_subplot(2, num_labels, i+1) img = sample_train[labels_train==LABELS[i]][0].reshape((28, 28)) ax.imshow(img, cmap="Greys") # change the dimension N_DIM = 4 pca = PCA(n_components=N_DIM).fit(sample_train) sample_train = pca.transform(sample_train) sample_test = pca.transform(sample_test) # standardize std_scale = StandardScaler().fit(sample_train) sample_train = std_scale.transform(sample_train) sample_test = std_scale.transform(sample_test) # normalize 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) # Display each of the first data print(sample_train[0], labels_train[0]) print(sample_test[0], labels_test[0]) zz_map = # Write your featuremap here zz_map.decompose().draw('mpl') zz_kernel = # Construct your kernel here 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 = # Write your code here matrix_test = # Write your code here 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() zzpc_svc = # Write your code here zzpc_svc.fit(matrix_train, labels_train) # Train zzpc_score = zzpc_svc.score(matrix_test, labels_test) # Determine the percentage of correct answers print(f'Kernel classification test score: {zzpc_score}')
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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. """Test the piecewise polynomial Pauli rotations.""" import unittest from collections import defaultdict import numpy as np from ddt import ddt, data, unpack from qiskit.test.base import QiskitTestCase from qiskit import BasicAer, execute from qiskit.circuit import QuantumCircuit from qiskit.circuit.library.arithmetic.piecewise_polynomial_pauli_rotations import ( PiecewisePolynomialPauliRotations, ) @ddt class TestPiecewisePolynomialRotations(QiskitTestCase): """Test the piecewise polynomial Pauli rotations.""" def assertFunctionIsCorrect(self, function_circuit, reference): """Assert that ``function_circuit`` implements the reference function ``reference``.""" num_state_qubits = function_circuit.num_state_qubits num_ancilla_qubits = function_circuit.num_ancillas circuit = QuantumCircuit(num_state_qubits + 1 + num_ancilla_qubits) circuit.h(list(range(num_state_qubits))) circuit.append(function_circuit.to_instruction(), list(range(circuit.num_qubits))) backend = BasicAer.get_backend("statevector_simulator") statevector = execute(circuit, backend).result().get_statevector() probabilities = defaultdict(float) for i, statevector_amplitude in enumerate(statevector): i = bin(i)[2:].zfill(circuit.num_qubits)[num_ancilla_qubits:] probabilities[i] += np.real(np.abs(statevector_amplitude) ** 2) unrolled_probabilities = [] unrolled_expectations = [] for i, probability in probabilities.items(): x, last_qubit = int(i[1:], 2), i[0] if last_qubit == "0": expected_amplitude = np.cos(reference(x)) / np.sqrt(2**num_state_qubits) else: expected_amplitude = np.sin(reference(x)) / np.sqrt(2**num_state_qubits) unrolled_probabilities += [probability] unrolled_expectations += [np.real(np.abs(expected_amplitude) ** 2)] np.testing.assert_almost_equal(unrolled_probabilities, unrolled_expectations) @data( (1, [0], [[1]]), (2, [0, 2], [[2], [-0.5, 1]]), (3, [0, 2, 5], [[1, 0, -1], [2, 1], [1, 1, 1]]), (4, [2, 5, 7, 16], [[1, -1], [1, 2, 3], [1, 2, 3, 4]]), (3, [0, 1], [[1, 0], [1, -2]]), ) @unpack def test_piecewise_polynomial_function(self, num_state_qubits, breakpoints, coeffs): """Test the piecewise linear rotations.""" def pw_poly(x): for i, point in enumerate(reversed(breakpoints[: len(coeffs)])): if x >= point: # Rescale the coefficients to take into account the 2 * theta argument from the # rotation gates rescaled_c = [coeff / 2 for coeff in coeffs[-(i + 1)][::-1]] return np.poly1d(rescaled_c)(x) return 0 pw_polynomial_rotations = PiecewisePolynomialPauliRotations( num_state_qubits, breakpoints, coeffs ) self.assertFunctionIsCorrect(pw_polynomial_rotations, pw_poly) def test_piecewise_polynomial_rotations_mutability(self): """Test the mutability of the linear rotations circuit.""" def pw_poly(x): for i, point in enumerate(reversed(breakpoints[: len(coeffs)])): if x >= point: # Rescale the coefficients to take into account the 2 * theta argument from the # rotation gates rescaled_c = [coeff / 2 for coeff in coeffs[-(i + 1)][::-1]] return np.poly1d(rescaled_c)(x) return 0 pw_polynomial_rotations = PiecewisePolynomialPauliRotations() with self.subTest(msg="missing number of state qubits"): with self.assertRaises(AttributeError): # no state qubits set print(pw_polynomial_rotations.draw()) with self.subTest(msg="default setup, just setting number of state qubits"): pw_polynomial_rotations.num_state_qubits = 2 self.assertFunctionIsCorrect(pw_polynomial_rotations, lambda x: 1 / 2) with self.subTest(msg="setting non-default values"): breakpoints = [0, 2] coeffs = [[0, -2 * 1.2], [-2 * 1, 2 * 1, 2 * 3]] pw_polynomial_rotations.breakpoints = breakpoints pw_polynomial_rotations.coeffs = coeffs self.assertFunctionIsCorrect(pw_polynomial_rotations, pw_poly) with self.subTest(msg="changing all values"): pw_polynomial_rotations.num_state_qubits = 4 breakpoints = [1, 3, 6] coeffs = [[0, -2 * 1.2], [-2 * 1, 2 * 1, 2 * 3], [-2 * 2]] pw_polynomial_rotations.breakpoints = breakpoints pw_polynomial_rotations.coeffs = coeffs self.assertFunctionIsCorrect(pw_polynomial_rotations, pw_poly) if __name__ == "__main__": unittest.main()
https://github.com/1chooo/Quantum-Oracle
1chooo
#program 5.1a Define classical oracle f1 and test it def f1(x): return '1' print(f1('000'),f1('001'),f1('010'),f1('011'),f1('100'),f1('101'),f1('110'),f1('111')) #program 5.1b Define classical oracle f2 and test it def f2(x): if x[0]=='0': return '0' else: return '1' print(f2('000'),f2('001'),f2('010'),f2('011'),f2('100'),f2('101'),f2('110'),f2('111')) #Program 5.1c Solve constant-balanced function decision (CBFD) prob. with classical code import itertools def cbfd_test(f,n): count0=count1=0 iter = itertools.product([0,1], repeat=n) lst = [''.join(map(str, item)) for item in iter] for s in lst: if f(s)=='0': count0+=1 else: count1+=1 if count0>0 and count1>0: return True #for balanced function elif count0>2**(n-1) or count1>2**(n-1): return False #for constant function print(cbfd_test(f1,3)) print(cdfd_test(f2,3)) #Program 5.2 Define a quantum oracle from qiskit import QuantumRegister,QuantumCircuit qrx = QuantumRegister(3,'x') qry = QuantumRegister(1,'y') qc = QuantumCircuit(qrx,qry) qc.x(qry) qc.draw('mpl') #Program 5.3a Build quantum circuit of Deutsch-Jozsa alg. from qiskit import QuantumRegister,ClassicalRegister,QuantumCircuit qrx = QuantumRegister(3,'x') qry = QuantumRegister(1,'y') cr = ClassicalRegister(3,'c') qc = QuantumCircuit(qrx,qry,cr) qc.h(qrx) qc.x(qry) qc.h(qry) qc.barrier() qc.x(qry) qc.barrier() qc.h(qrx) qc.measure(qrx,cr) qc.draw('mpl') #Program 5.3b Run Deutsch-Jozsa alg. with simulator 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 5.4 Define another quantum oracle from qiskit import QuantumRegister,QuantumCircuit qrx = QuantumRegister(3,'x') qry = QuantumRegister(1,'y') qc = QuantumCircuit(qrx,qry) qc.cx(qrx[0],qry) qc.draw('mpl') #Program 5.5a Build quantum circuit of Deutsch-Jozsa alg. from qiskit import QuantumRegister,ClassicalRegister,QuantumCircuit qrx = QuantumRegister(3,'x') qry = QuantumRegister(1,'y') cr = ClassicalRegister(3,'c') qc = QuantumCircuit(qrx,qry,cr) qc.h(qrx) qc.x(qry) qc.h(qry) qc.barrier() qc.cx(qrx[0],qry) qc.barrier() qc.h(qrx) qc.measure(qrx,cr) qc.draw('mpl') #Program 5.5b Run Deutsch-Jozsa alg. with simulator 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 5.6 Show phase kickback of CNOT gate from qiskit import QuantumCircuit, Aer from qiskit.visualization import array_to_latex, plot_bloch_multivector sim = Aer.get_backend('aer_simulator') qc1 = QuantumCircuit(2) qc1.h(0) qc1.x(1) qc1.h(1) qc1.save_statevector() state1 = sim.run(qc1).result().get_statevector() display(qc1.draw('mpl')) display(array_to_latex(state1, prefix='\\text{Statevector before CNOT gate: }')) display(plot_bloch_multivector(state1)) print('='*60) qc2 = QuantumCircuit(2) qc2.h(0) qc2.x(1) qc2.h(1) qc2.cx(0,1) qc2.save_statevector() state2 = sim.run(qc2).result().get_statevector() display(qc2.draw('mpl')) display(array_to_latex(state2, prefix='\\text{Statevector after CNOT gate: }')) display(plot_bloch_multivector(state2)) # Program 5.7 Show phase kickback of CCNOT gate from qiskit import QuantumCircuit, Aer from qiskit.visualization import array_to_latex, plot_bloch_multivector sim = Aer.get_backend('aer_simulator') qc1 = QuantumCircuit(3) qc1.h([0,1]) qc1.x(2) qc1.h(2) qc1.save_statevector() state1 = sim.run(qc1).result().get_statevector() display(qc1.draw('mpl')) display(array_to_latex(state1, prefix="\\text{Statevector before CCNOT gate: }")) display(plot_bloch_multivector(state1)) print('='*80) qc2 = QuantumCircuit(3) qc2.h([0,1]) qc2.x(2) qc2.h(2) qc2.ccx(0,1,2) qc2.save_statevector() state2 = sim.run(qc2).result().get_statevector() display(qc2.draw('mpl')) display(array_to_latex(state2, prefix="\\text{Statevector before CCNOT gate: }")) display(plot_bloch_multivector(state2)) #Program 5.8 Show circuit containing CZ gate and CZ gate's unitary matrix from qiskit import QuantumCircuit, Aer from qiskit.visualization import array_to_latex sim = Aer.get_backend('aer_simulator') qc1 = QuantumCircuit(2) qc1.cz(0,1) qc1.save_unitary() unitary1 = sim.run(qc1).result().get_unitary() print("CZ Gate (q0 as control bit, q1 as target bit):") display(qc1.draw('mpl')) display(array_to_latex(unitary1, prefix="\\text{Unitray Matrix of CZ Gate (MSB as Target): }")) print('='*60) qc2 = QuantumCircuit(2) qc2.cz(1,0) qc2.save_unitary() unitary2 = sim.run(qc2).result().get_unitary() print("CZ Gate (q1 as control bit, q0 as target bit):") display(qc2.draw('mpl')) display(array_to_latex(unitary2, prefix="\\text{Unitray Matrix of CZ Gate (LSB as Target): }")) #Program 5.9 Show quantum circuit with CZ, CP, CS, CT gates from qiskit import QuantumCircuit from math import pi qc = QuantumCircuit(8) qc.cz(0,1) qc.cp(pi,2,3) qc.cp(pi/2,4,5) qc.cp(pi/4,6,7) display(qc.draw('mpl'))
https://github.com/Ilan-Bondarevsky/qiskit_algorithm
Ilan-Bondarevsky
import sys import os current_dir = os.getcwd() sys.path.append(os.path.dirname(os.path.abspath(current_dir))) from Grover.grover_num_list_cirq import find_num, find_num_list from Backend.fake_backend import FakeBackend from Backend.backend import Backend from Backend.ibm_backend import IBM_backend from Result.result import ResultData from qiskit.visualization import plot_histogram, plot_coupling_map from backend_operation import run_simulator, get_transpiled_circuits_of_circuit, get_fake_backend_list,get_unitary, get_fake_backend, get_fake_backend_list from qiskit import transpile import qiskit.providers.fake_provider from qiskit_ibm_provider import IBMProvider from qiskit.transpiler.passes import RemoveBarriers from qiskit_aer import AerSimulator, Aer from itertools import permutations # Sample of Find Number Grover Circuit find_num_in_world_obj = find_num() find_num_in_world_obj.build_iteration(winner_num_list=[0], circuit_nqubits=3, block_diagram=False) find_num_in_world_obj.create_grover(num_solutions=1, prep_value=[], block_diagram=False) cur_experiments = find_num_in_world_obj.measure_qc print(f"Number of Grover circuits : {len(cur_experiments)}") cur_experiments[0].draw('mpl') backend = qiskit.providers.fake_provider.GenericBackendV2(num_qubits=3) backend.coupling_map.draw() # Transpile the ideal circuit to a circuit that can be directly executed by the backend transpiled_circuit = transpile(cur_experiments[0], backend, optimization_level=0) transpiled_circuit.draw('mpl') transpiled_circuit = transpile(cur_experiments[0], backend, optimization_level=3) transpiled_circuit.draw('mpl') find_num_obj = find_num() num_qubits = 3 qc_find_num_list = [] for value in range(2**num_qubits): find_num_obj.build_iteration(winner_num_list=[value], circuit_nqubits=num_qubits, block_diagram=False) find_num_obj.create_grover(num_solutions=1, prep_value=[], block_diagram=False) qc_find_num_list.append(find_num_obj.measure_qc[0]) generic_backend = Backend(num_qubits) backend_names = FakeBackend.get_ibm_fake_backend_names_with_limit(num_qubits) fake_auckland_backend = FakeBackend.get_ibm_fake_backend('fake_auckland') print(f"Fake Auckland number of qubits = {fake_auckland_backend.num_qubits}") fake_backend_name = 'fake_auckland' fake_backend = FakeBackend(fake_backend_name) position_layout = permutations(range(fake_backend.get_backend_qubits()), num_qubits) position_layout = permutations(range(num_qubits), num_qubits) qc_find_num_list_without_barriar = [RemoveBarriers()(qc) for qc in qc_find_num_list] # Add the Generic Aer Full Connectivity qc_transpiled_list = [ generic_backend.transpile_save_param(qc=qc, optimization_level=0, initial_layout=None, seed_transpiler=None, input_search = index) for index, qc in enumerate(qc_find_num_list_without_barriar) ] qc_transpiled_list = qc_transpiled_list + [ generic_backend.transpile_save_param(qc=qc, optimization_level=3, initial_layout=None, seed_transpiler=None, input_search = index) for index, qc in enumerate(qc_find_num_list_without_barriar) ] position_layout = list(position_layout) # Add the fake backend for layout in [None] + position_layout: qc_transpiled_list = qc_transpiled_list + [ fake_backend.transpile_save_param(qc=qc, optimization_level=0, initial_layout=layout, seed_transpiler=None, input_search = index) for index, qc in enumerate(qc_find_num_list_without_barriar) ] qc_transpiled_list = qc_transpiled_list + [ fake_backend.transpile_save_param(qc=qc, optimization_level=3, initial_layout=layout, seed_transpiler=None, input_search = index) for index, qc in enumerate(qc_find_num_list_without_barriar) ] # Sample that we entered an input value to the result parameters to save qc_transpiled_list[60].backend_name qc_res = [ qc_param.backend.run(qc_param.transpiled_qc,shots=1024) for qc_param in qc_transpiled_list ] len(qc_res) result = ResultData(qc_res[60]) result.job result.to_dict() result.to_dict().keys() result.get_result_time_taken(0) result.to_dict()['time_taken'] result.to_dict()['results'][0].keys() result.to_dict()['results'][0]['time_taken'] result.get_counts() result.get_data() result.to_dict().keys() result.to_dict()['results'][0].keys() result.to_dict()['results'][0]['time_taken'] result.to_dict()['results'][0]['header'] result.to_dict()['results'][0]['data'] result.to_dict()['results'][0]['metadata']
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can choose different colors for the real and imaginary parts of the density matrix. from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = DensityMatrix(qc) plot_state_city(state, color=['midnightblue', 'crimson'], title="New State City")
https://github.com/Keerthiraj-Nagaraj/IBM-quantum-challenge-2020
Keerthiraj-Nagaraj
from IPython.display import Image, display Image('4lightsout_ex.png') from qiskit import * from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit import IBMQ, Aer, execute provider = IBMQ.load_account() address = QuantumRegister(2) data = QuantumRegister(3) c = ClassicalRegister(5) qc = QuantumCircuit(address,data,c) # address preparation qc.h([address[0],address[1]]) qc.barrier() # address 0 -> data = 1 qc.x([address[0],address[1]]) qc.ccx(address[0],address[1],data[2]) qc.x([address[0],address[1]]) qc.barrier() # address 1 -> data = 2 qc.x(address[0]) qc.ccx(address[0],address[1],data[1]) qc.x(address[0]) qc.barrier() # address 2 -> data = 5 qc.x(address[1]) qc.ccx(address[0],address[1],data[2]) qc.ccx(address[0],address[1],data[0]) qc.x(address[1]) qc.barrier() # address 3 -> data = 7 qc.ccx(address[0],address[1],data[2]) qc.ccx(address[0],address[1],data[1]) qc.ccx(address[0],address[1],data[0]) qc.barrier() #Check the qRAM status qc.measure(address[0:2], c[0:2]) qc.measure(data[0:3], c[2:5]) # Reverse the output string. qc = qc.reverse_bits() #backend = provider.get_backend('ibmq_qasm_simulator') backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend=backend, shots=8000, seed_simulator=12345, backend_options={"fusion_enable":True}) #job = execute(qc, backend=backend, shots=8192) result = job.result() count =result.get_counts() print(count) qc.draw(output='mpl') Image('circuit_ex.png') Image('gatesynthesis_ex.png') Image('4lightsout_pr.png') lightsout4=[[1, 1, 1, 0, 0, 0, 1, 0, 0],[1, 0, 1, 0, 0, 0, 1, 1, 0],[1, 0, 1, 1, 1, 1, 0, 0, 1],[1, 0, 0, 0, 0, 0, 1, 0, 0]] def week2b_ans_func(lightout4): ##### Build your cirucuit here #### In addition, please make it a function that can solve the problem even with different inputs (lightout4). We do validation with different inputs. return qc # Submission code from qc_grader import prepare_ex2b, grade_ex2b, submit_ex2b # Execute your circuit with following prepare_ex2b() function. # The prepare_ex2b() function works like the execute() function with only QuantumCircuit as an argument. job = prepare_ex2b(week2b_ans_func) result = job.result() count = result.get_counts() original_problem_set_counts = count[0] original_problem_set_counts # The bit string with the highest number of observations is treated as the solution. # Check your answer by executing following code. # The quantum cost of the QuantumCircuit is obtained as the score. The quantum cost is related to rank only in the third week. grade_ex2b(job) # Submit your results by executing following code. You can submit as many times as you like during the period. submit_ex2b(job)
https://github.com/sorin-bolos/QiskitCampAsia2019
sorin-bolos
# useful additional packages import matplotlib.pyplot as plt import matplotlib.axes as axes %matplotlib inline import numpy as np import networkx as nx from qiskit import BasicAer from qiskit.tools.visualization import plot_histogram from qiskit.aqua import run_algorithm from qiskit.aqua.input import EnergyInput from qiskit.aqua.translators.ising import max_cut, tsp from qiskit.aqua.algorithms import VQE, ExactEigensolver from qiskit.aqua.components.optimizers import SPSA from qiskit.aqua.components.variational_forms import RY from qiskit.aqua import QuantumInstance from qiskit.quantum_info import Pauli from qiskit.aqua.operators import WeightedPauliOperator from collections import OrderedDict import math # setup aqua logging import logging from qiskit.aqua import set_qiskit_aqua_logging def get_knapsack_operator(values, weights, max_weight): if len(values) != len(weights): raise ValueError("The values and weights must have the same length") if any(v < 0 for v in values) or any(w < 0 for w in weights): raise ValueError("The values and weights cannot be negative") if all(v == 0 for v in values): raise ValueError("The values cannot all be 0") if max_weight < 0: raise ValueError("max_weight cannot be negative") y_size = int(math.log(max_weight, 2)) + 1 if max_weight > 0 else 1 print(y_size) n = len(values) num_values = n + y_size pauli_list = [] shift = 0 M = 2000000 #10 * np.sum(values) # term for sum(x_i*w_i)**2 for i in range(n): for j in range(n): coefficient = -1 * 0.25 * weights[i] * weights[j] * M xp = np.zeros(num_values, dtype=np.bool) zp = np.zeros(num_values, dtype=np.bool) zp[j] = not zp[j] pauli_list.append([coefficient, Pauli(zp, xp)]) shift -= coefficient xp = np.zeros(num_values, dtype=np.bool) zp = np.zeros(num_values, dtype=np.bool) zp[i] = not zp[i] pauli_list.append([coefficient, Pauli(zp, xp)]) shift -= coefficient coefficient = -1 * coefficient xp = np.zeros(num_values, dtype=np.bool) zp = np.zeros(num_values, dtype=np.bool) zp[i] = not zp[i] zp[j] = not zp[j] pauli_list.append([coefficient, Pauli(zp, xp)]) shift -= coefficient # term for sum(2**j*y_j)**2 for i in range(y_size): for j in range(y_size): coefficient = -1 * 0.25 * (2 ** i) * (2 ** j) * M xp = np.zeros(num_values, dtype=np.bool) zp = np.zeros(num_values, dtype=np.bool) zp[n + j] = not zp[n + j] pauli_list.append([coefficient, Pauli(zp, xp)]) shift -= coefficient xp = np.zeros(num_values, dtype=np.bool) zp = np.zeros(num_values, dtype=np.bool) zp[n + i] = not zp[n + i] pauli_list.append([coefficient, Pauli(zp, xp)]) shift -= coefficient coefficient = -1 * coefficient xp = np.zeros(num_values, dtype=np.bool) zp = np.zeros(num_values, dtype=np.bool) zp[n + i] = not zp[n + i] zp[n + j] = not zp[n + j] pauli_list.append([coefficient, Pauli(zp, xp)]) shift -= coefficient # term for -2*W_max*sum(x_i*w_i) for i in range(n): coefficient = max_weight * weights[i] * M xp = np.zeros(num_values, dtype=np.bool) zp = np.zeros(num_values, dtype=np.bool) zp[i] = not zp[i] pauli_list.append([coefficient, Pauli(zp, xp)]) shift -= coefficient # term for -2*W_max*sum(2**j*y_j) for j in range(y_size): coefficient = max_weight * (2 ** j) * M xp = np.zeros(num_values, dtype=np.bool) zp = np.zeros(num_values, dtype=np.bool) zp[n + j] = not zp[n + j] pauli_list.append([coefficient, Pauli(zp, xp)]) shift -= coefficient for i in range(n): for j in range(y_size): coefficient = -1 * 0.5 * weights[i] * (2 ** j) * M xp = np.zeros(num_values, dtype=np.bool) zp = np.zeros(num_values, dtype=np.bool) zp[n + j] = not zp[n + j] pauli_list.append([coefficient, Pauli(zp, xp)]) shift -= coefficient xp = np.zeros(num_values, dtype=np.bool) zp = np.zeros(num_values, dtype=np.bool) zp[i] = not zp[i] pauli_list.append([coefficient, Pauli(zp, xp)]) shift -= coefficient coefficient = -1 * coefficient xp = np.zeros(num_values, dtype=np.bool) zp = np.zeros(num_values, dtype=np.bool) zp[i] = not zp[i] zp[n + j] = not zp[n + j] pauli_list.append([coefficient, Pauli(zp, xp)]) shift -= coefficient # term for sum(x_i*v_i) for i in range(n): coefficient = 0.5 * values[i] xp = np.zeros(num_values, dtype=np.bool) zp = np.zeros(num_values, dtype=np.bool) zp[i] = not zp[i] pauli_list.append([coefficient, Pauli(zp, xp)]) shift -= coefficient return WeightedPauliOperator(paulis=pauli_list), shift def get_solution(x, values): return x[:len(values)] def knapsack_value_weight(solution, values, weights): value = np.sum(solution * values) weight = np.sum(solution * weights) return value, weight def sample_most_likely(state_vector): if isinstance(state_vector, dict) or isinstance(state_vector, OrderedDict): # get the binary string with the largest count binary_string = sorted(state_vector.items(), key=lambda kv: kv[1])[-1][0] x = np.asarray([int(y) for y in reversed(list(binary_string))]) return x else: n = int(np.log2(state_vector.shape[0])) k = np.argmax(np.abs(state_vector)) x = np.zeros(n) for i in range(n): x[i] = k % 2 k >>= 1 return x # values = [680, 120, 590, 178] # weights = [13, 6, 15, 9] # w_max = 32 values = [8, 2] weights = [3, 1] w_max = 3 qubitOp, offset = get_knapsack_operator(values, weights, w_max) algo_input = EnergyInput(qubitOp) ee = ExactEigensolver(qubitOp, k=1) result = ee.run() most_lightly = result['eigvecs'][0] x = sample_most_likely(most_lightly) print(x) print('result=' + str(x[:len(values)])) seed = 10598 spsa = SPSA(max_trials=10000) ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear') vqe = VQE(qubitOp, ry, spsa) backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed) result_statevector = vqe.run(quantum_instance) most_lightly_sv = result_statevector['eigvecs'][0] x_statevector = sample_most_likely(most_lightly_sv) print(x_statevector) print('result usig statevector_simulator =' + str(x_statevector[:len(values)])) # run quantum algorithm with shots seed = 10598 spsa = SPSA(max_trials=1000) ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear') vqe = VQE(qubitOp, ry, spsa) backend = BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed) result_shots = vqe.run(quantum_instance) most_lightly_shots = result_shots['eigvecs'][0] x_shots = sample_most_likely(most_lightly_shots) print(x_shots) print('result usig qasm_simulator =' + str(x_shots[:len(values)])) math.log(8, 2)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) # plot using a Statevector state = Statevector(qc) plot_state_city(state)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(3, 'q') anc = QuantumRegister(1, 'ancilla') cr = ClassicalRegister(3, 'c') qc = QuantumCircuit(qr, anc, cr) qc.x(anc[0]) qc.h(anc[0]) qc.h(qr[0:3]) qc.cx(qr[0:3], anc[0]) qc.h(qr[0:3]) qc.barrier(qr) qc.measure(qr, cr) qc.draw('mpl')
https://github.com/PaulaGarciaMolina/QNLP_Qiskit_Hackathon
PaulaGarciaMolina
import numpy as np import pickle import qiskit qiskit.__qiskit_version__ from discopy import Ty, Word # Import the classes for the type of word and for the word s, n = Ty('s'), Ty('n') # Define the types s and n nphr, adj, tv, iv, vphr = Ty('NP'), Ty('ADJ'), Ty('TV'), Ty('IV'), Ty('VP') # Define the words (notice that we include both meaning and grammar) # nouns man, woman, kid = Word('man', n), Word('woman', n), Word('kid', n) # adjectives morose, irascible = Word('morose', n @ n.l), Word('irascible', n @ n.l) frightened, cheerful = Word('frightened', n @ n.l), Word('cheerful', n @ n.l) gloomy, furious = Word('gloomy', n @ n.l), Word('furious', n @ n.l) terrified, joyful = Word('terrified', n @ n.l), Word('joyful', n @ n.l) downcast, miserable = Word('downcast', n @ n.l), Word('miserable', n @ n.l) old, young = Word('old', n @ n.l), Word('young', n @ n.l) # Intransitive verbs cries, shouts = Word('cries', n.r @ s), Word('shouts', n.r @ s) laughs, snaps = Word('laughs', n.r @ s), Word('snaps', n.r @ s) # Transitive verbs grieves, startles = Word('grieves', n.r @ s @ n.l), Word('startles', n.r @ s @ n.l) entertains, irritates = Word('entertains', n.r @ s @ n.l), Word('irritates', n.r @ s @ n.l) nouns = [man, woman, kid] adjectives = [morose, irascible, frightened, cheerful, gloomy, furious, terrified, joyful, downcast, miserable, old, young] int_verbs = [cries, shouts, laughs, snaps] t_verbs = [grieves, startles, entertains, irritates] vocab = nouns + int_verbs + t_verbs + adjectives from discopy import Cup, Id, pregroup grammar = Id(n) @ Cup(n.l, n) @ Id(n.r @ s) >> Cup(n, n.r) @ Id(s) >> Id(s) sentence = joyful @ woman @ laughs >> grammar pregroup.draw(sentence) grammar = Cup(n, n.r) @ Id(s) @ Cup(n.l, n) sentence = woman @ grieves @ kid >> grammar pregroup.draw(sentence) from discopy import Diagram from discopy.grammar import draw # Store the grammatical structures in a dictionary grammar_dict = { 'ADJ_N_IV' : Id(n) @ Cup(n.l, n) @ Id(n.r @ s) >> Cup(n, n.r) @ Id(s) >> Id(s), 'N_TV_N': Cup(n, n.r) @ Id(s) @ Cup(n.l, n), 'ADJ_N_TV_N': Id(n) @ Cup(n.l, n) @ Id(n.r @ s) @ Cup(n.l, n) >> Cup(n, n.r) @ Id(s) >> Id(s), 'N_TV_ADJ_N': Cup(n, n.r) @ Id(s) @ Cup(n.l, n) @ Cup(n.l, n) >> Id(s)} # Create parsing (grammatical analysis) dictionary where the grammatical sentences # are the keys and the associated values are the diagrams (words + grammar) data_psr = {} # Intransitive sentences parsing_int = {"{} {} {}.".format(adj, noun, int_verb): adj @ noun @ int_verb >> grammar_dict['ADJ_N_IV'] for adj in adjectives for noun in nouns for int_verb in int_verbs} sentences_int = list(parsing_int.keys()) for sentence in sentences_int: diagram = parsing_int[sentence] data_psr[sentence] = parsing_int[sentence] # Transitive sentences (without adjective) parsing_tra = {"{} {} {}.".format(subj, t_verb, obj): subj @ t_verb @ obj >> grammar_dict['N_TV_N'] for subj in nouns for t_verb in t_verbs for obj in nouns} #Due to time limitations, we are exlcuding transitive sentences with adjectives in this implementation """ # Transitive sentences (with adjective) parsing_tra_ladj = {"{} {} {} {}.".format(adj, subj, t_verb, obj): adj @ subj @ t_verb @ obj >> grammar_dict['ADJ_N_TV_N'] for adj in adjectives for subj in nouns for t_verb in t_verbs for obj in nouns} parsing_tra_radj = {"{} {} {} {}.".format(subj, t_verb, adj, obj): subj @ t_verb @ adj @ obj >> grammar_dict['N_TV_ADJ_N'] for subj in nouns for t_verb in t_verbs for adj in adjectives for obj in nouns} parsing_tra.update(parsing_tra_ladj) #merges transitive adjectives into original dict parsing_tra.update(parsing_tra_radj) """ sentences_tra = list(parsing_tra.keys()) for sentence in sentences_tra: diagram = parsing_tra[sentence] data_psr[sentence] = parsing_tra[sentence] with open('../sentiment_analysis_dataset.txt') as f: data = f.readlines() labels_dict = {} # Dictionary with the labels for each sentence data_psr_dict = {} # Dictionary with the parsing for each sentence sent_type = {} # Dictionary with the sentence type for each sentence adjective_words = [a.name for a in adjectives] for sentence in data: sentstr = sentence[:-7] #seperates the sentence string from the data at the end if sentence[-6:-3] == 'int': diagram = parsing_int[sentstr] data_psr_dict[sentstr] = diagram labels_dict[sentstr] = sentence[-2] sent_type[sentstr] = 'int' elif sentence[-6:-3] == 'tra': diagram = parsing_tra[sentstr] data_psr_dict[sentstr] = diagram labels_dict[sentstr] = sentence[-2] #ignoring transitive adjective sentences in this run """if len(sentstr.split()) == 4: if sentstr.split()[0] in adjective_words: sent_type[sentstr] = 'tra_' + 'l' #adjective on the left else: sent_type[sentstr] = 'tra_' + 'r' #adjective on the right else: sent_type[sentstr] = 'tra' #the simple transitive verb sentence type """ sent_type[sentstr] = 'tra' c0 = 0 c1 = 0 c2 = 0 c3 = 0 for value in labels_dict.values(): if value == '0': c0 +=1 elif value == '1': c1 += 1 elif value == '2': c2 += 1 elif value == '3': c3 += 1 print('Number of elements for each sentiment') print('Happy: ', c0) print('Sad: ', c1) print('Angry: ', c2) print('Scared: ', c3) print('Total', len(data_psr_dict)) from discopy import Cap, Box woman2 = Box('woman', n.l, Ty()) words_new = (Cap(n, n.l)) >> (joyful @ Id(n) @ woman2 @ laughs) sentence = words_new >> grammar_dict['ADJ_N_IV'] sentence = sentence.normal_form() sentence.draw() woman2 = Box('woman', n.r, Ty()) kid2 = Box('kid', n.l, Ty()) words_new = (Cap(n.r, n) @ Cap(n, n.l)) >> (woman2 @ Id(n) @ grieves @ Id(n) @ kid2) sentence = words_new >> grammar_dict['N_TV_N'] sentence = sentence.normal_form() sentence.draw() data_psr['morose man grieves woman.'].draw() # Code of this cell addapted from https://github.com/CQCL/qnlp_lorenz_etal_2021_resources #iterates through all sentences and reshapes them as above according to their type data_new_psr_dict = {} for sentstr in data_psr_dict.keys(): num_words = len(sentstr.split(' ')) words = data_psr_dict[sentstr].boxes[:num_words] if sent_type[sentstr] == 'int': noun = Box(words[1].name, n.l, Ty()) words_new = (Cap(n, n.l)) >> (words[0] @ Id(n) @ noun @ words[2]) sentence = words_new >> grammar_dict['ADJ_N_IV'] data_new_psr_dict[sentstr] = sentence.normal_form() elif 'tra' in sent_type[sentstr]: if sent_type[sentstr] == 'tra': noun1 = Box(words[0].name, n.r, Ty()) noun2 = Box(words[2].name, n.l, Ty()) words_new = (Cap(n.r, n) @ Cap(n, n.l)) >> (noun1 @ Id(n) @ words[1] @ Id(n) @ noun2) sentence = words_new >> grammar_dict['N_TV_N'] data_new_psr_dict[sentstr] = sentence.normal_form() """ elif sent_type[sentstr] == 'tra_l': #adjective at beginning noun1 = Box(words[1].name, n.l, Ty()) noun2 = Box(words[3].name, n.l, Ty()) words_new = (Cap(n, n.l) @ Cap(n, n.l)) >> (words[0] @ Id(n) @ noun1 @ words[2] @ Id(n) @ noun2) sentence = words_new >> grammar_dict['ADJ_N_TV_N'] data_new_psr_dict[sentstr] = sentence.normal_form() elif sent_type[sentstr] == 'tra_r': #adjective on second noun noun1 = Box(words[0].name, n.r, Ty()) noun2 = Box(words[3].name, n.l, Ty()) words_new = (Cap(n.r, n) @ Cap(n, n.l)) >> (noun1 @ Id(n) @ words[1] @ words[2] @ Id(n) @ noun2) sentence = words_new >> grammar_dict['N_TV_ADJ_N'] data_new_psr_dict[sentstr] = sentence.normal_form() """ vocab_psr = [] for word in vocab: if word.cod == Ty('n'): vocab_psr.append(Box(word.name, n.r, Ty())) # n.l case is dealt with in definition of quantum functor else: vocab_psr.append(word) # Code of this cell from https://github.com/CQCL/qnlp_lorenz_etal_2021_resources from discopy.quantum import Ket, IQPansatz, Bra, qubit from discopy.quantum.circuit import Functor, Id from discopy.quantum.circuit import Circuit from functools import reduce, partial import numpy as np q_s = 2 # number of qubits for type s (sentence) q_n = 2 # number of qubits for type n (noun) depth = 1 # depth of the IQPansatz # Define the dimensions of the objects of the circuit functor ob = {s: q_s, n: q_n} ob_cqmap = {s: qubit ** q_s, n: qubit ** q_n} # Define the ansätze for states and effects def ansatz_state(state, params): arity = sum(ob[Ty(factor.name)] for factor in state.cod) return Ket(*tuple([0 for i in range(arity)])) >> IQPansatz(arity, params) def ansatz_effect(effect, params): arity = sum(ob[Ty(factor.name)] for factor in effect.dom) return IQPansatz(arity, params) >> Bra(*tuple([0 for i in range(arity)])) def ansatz(box,params): dom_type = box.dom cod_type = box.cod if len(dom_type) == 0 and len(cod_type) != 0: return ansatz_state(box, params) if len(dom_type) != 0 and len(cod_type) == 0: return ansatz_effect(box, params) # Construct the circuit functor def F(params): ar = dict() for i in range(len(vocab_psr)): pgbox = vocab_psr[i] qbox = ansatz(vocab_psr[i], params[i]) ar.update({pgbox: qbox}) if pgbox.cod == Ty(): ar.update({Box(pgbox.name, n.l, Ty()): qbox}) return Functor(ob_cqmap, ar) # Code of this cell from https://github.com/CQCL/qnlp_lorenz_etal_2021_resources #***************************************************** # Functions to deal with the parametrisation #***************************************************** def paramshapes(vocab_psr): parshapes = [] for box in vocab_psr: dom_type = box.dom cod_type = box.cod dom_arity = sum(ob[Ty(factor.name)] for factor in box.dom) cod_arity = sum(ob[Ty(factor.name)] for factor in box.cod) if dom_arity == 0 or cod_arity == 0: # states and effects arity = max(dom_arity, cod_arity) assert arity != 0 parshapes.append((depth, arity-1)) return parshapes def randparams(par_shapes): params = np.array([]) for i in range(len(par_shapes)): params = np.concatenate((params, np.ravel(np.random.rand(*par_shapes[i])))) # np.ravel flattens an array return params def reshape_params(unshaped_pars, par_shapes): pars_reshaped = [[] for ii in range(len(par_shapes))] shift = 0 for ss, s in enumerate(par_shapes): idx0 = 0 + shift if len(s) == 1: idx1 = s[0] + shift elif len(s) == 2: idx1 = s[0] * s[1] + shift pars_reshaped[ss] = np.reshape(unshaped_pars[idx0:idx1], s) if len(s) == 1: shift += s[0] elif len(s) == 2: shift += s[0] * s[1] return pars_reshaped #**************************************** # Parameters of the current model #**************************************** par_shapes = paramshapes(vocab_psr) rand_unshaped_pars = randparams(par_shapes) rand_shaped_pars = reshape_params(rand_unshaped_pars, par_shapes) print('Number of parameters: ', len(rand_unshaped_pars)) # Print the quantum circuit for each sentence func = F(rand_shaped_pars) for sentstr in data_new_psr_dict: print(sentstr) print(data_new_psr_dict[sentstr]) #func(data_new_psr_dict[sentstr]).draw(draw_box_labels=True, figsize=(5, 5)) from sklearn.model_selection import train_test_split psr_diagrams = [] psr_diagrams_dict = {} psr_labels = [] sentences = [] for sentstr in data_new_psr_dict.keys(): sentences.append(sentstr) diagram = data_new_psr_dict[sentstr] psr_diagrams.append(diagram) psr_diagrams_dict[sentstr] = diagram label = int(labels_dict[sentstr]) psr_labels.append(label) #create lists of sentences and corresponding diagram and labels train_data_psr, test_data_psr, orig_train_labels, orig_test_labels = \ train_test_split(psr_diagrams, psr_labels, test_size=0.25, random_state=42) train_sent, test_sent, train_labels_sent, test_labels_sent = \ train_test_split(sentences, psr_labels, test_size=0.25, random_state=42) def num_to_vec(x): if x: return [0,1] #True else: return [1,0] data_sets_labels = {} for i, cla in enumerate(['happy', 'sad', 'angry', 'scared']): data_sets_labels[cla] = {} tr_labels = [num_to_vec(i == t) for t in orig_train_labels] data_sets_labels[cla]['train'] = tr_labels te_labels = [num_to_vec(i == t) for t in orig_test_labels] data_sets_labels[cla]['test'] = te_labels from qiskit import BasicAer, execute, ClassicalRegister from pytket.extensions.qiskit import tk_to_qiskit from qiskit.quantum_info import Statevector func(data_new_psr_dict['morose woman cries.']).draw() func(data_new_psr_dict['woman grieves man.']).draw() def get_qiskit_results(circ, sent, retries=10): """Function to get the Qiskit's results from a DisCoPy circuit. Args: circ: DisCoPy circuit. sent: English sentence for circ Returns: array: results from the postselection measurement. """ #Finds the sentence's type to determine the number of qubits and position of the sentence qubits s_type = sent_type[sent] if s_type == 'int': n_qubits = 4 post = 2 elif s_type == 'tra': n_qubits = 3 post = 1 elif s_type == 'tra_l': n_qubits = 5 post = 2 else: assert s_type == 'tra_r' n_qubits = 5 post = 1 #the diagrams are initially in discopy, so we first convert them to tket and then to qiskit qc = tk_to_qiskit(circ.to_tk()) qc.remove_final_measurements() state_dict = Statevector(qc).to_dict() #The only values we care about are the ones when the non-sentence qubits are all zero. #This leaves only two possible states - the sentence qubit is 0 or 1 (and the rest are all 0) selections = ['0' * post + val + '0' * (n_qubits - post - 1) for val in ['0', '1']] return [np.abs(state_dict[sel])**2 for sel in selections] #returns the amplitude for the two states from qiskit.algorithms.optimizers import SPSA import time global_costs = [] #global variable to keep track of cost during training def cost_ce(unshaped_params): #finds cross entropy cost #creates a functor which turns a sentence diagram into a circuit parameterized by unshaped_params func = F(reshape_params(unshaped_params, par_shapes)) #Applies this functor to every training diagram circs = [func(diag) for diag in train_data_psr] #Finds the post-selected qiskit results for each circuit results = np.array([get_qiskit_results(circs[i], train_sent[i]) for i in range(len(train_sent))]) #Turns each result into a probability distribution results_tweaked = [np.abs(np.array(res) - 1e-9) for res in results] pred_labels_distrs = [res.flatten() / np.sum(res) for res in results_tweaked] #finds the cross entropy cross_entropies = np.array([np.sum(train_labels[s] * np.log2(pred_labels_distrs[s])) for s in range(len(train_labels))]) cost = -1 / len(train_data_psr) * np.sum(cross_entropies) #stores the cost in a global list so we can track progress global_costs.append(cost) if len(global_costs) % 100 == 0: #since SPSA calls the cost function twice per iteration, this prints every 50 iterations print("at iteration", len(global_costs)/2, time.time() - begin_time) return cost rand_unshaped_pars = randparams(par_shapes) num_vars = len(rand_unshaped_pars) bounds = [[0.0, 1.0] for _ in range(len(rand_unshaped_pars))] ps = {} n_iterations = 1000 #creates a classifier 1vall classifier for each sentiment for cla in ['happy', 'sad', 'angry', 'scared']: #chooses random starting parameters rand_unshaped_pars = randparams(par_shapes) #finds the labels for the current classifier train_labels = data_sets_labels[cla]['train'] test_labels = data_sets_labels[cla]['test'] a = time.time() #creates a qiskit optimizer opt = SPSA(maxiter=n_iterations) print("\n\ncalibrating", cla) opt.calibrate(cost_ce, initial_point=rand_unshaped_pars) #calibrates according to cost function print("training") global_costs = [] o = opt.optimize(num_vars, cost_ce, initial_point=rand_unshaped_pars, variable_bounds=bounds) #performs optimization ps[cla] = [o, global_costs.copy()] #saves parameters and cost history print("took", time.time() - a) final_train_predictions = [(0,'') for _ in range(len(orig_train_labels))] # list of tuples of the form (probability, class) final_test_predictions = [(0,'') for _ in range(len(orig_test_labels))] test_predictions_dict = {} individual_train_predictions = {} individual_test_predictions = {} classes = ['happy', 'sad', 'angry', 'scared'] for j, cla in enumerate(classes): params = ps[cla][0][0] func = F(reshape_params(params, par_shapes)) train_data = train_data_psr #train_data = data_sets[cla]['train'] train_labels = data_sets_labels[cla]['train'] test_labels = data_sets_labels[cla]['test'] final_train_circuits = [func(diag) for diag in train_data_psr] train_results = [get_qiskit_results(final_train_circuits[i], train_sent[i]) for i in range(len(train_sent))] final_test_circuits = [func(diag) for diag in test_data_psr] test_results = [get_qiskit_results(final_test_circuits[i], test_sent[i]) for i in range(len(test_sent))] train_results_tweaked = [np.abs(np.array(res) - 1e-9) for res in train_results] test_results_tweaked = [np.abs(np.array(res) - 1e-9) for res in test_results] pred_train_results = [res.flatten() / np.sum(res) for res in train_results_tweaked] pred_test_results = [res.flatten() / np.sum(res) for res in test_results_tweaked] test_predictions_dict[cla] = ([np.argmax(r) for r in pred_test_results], test_labels) #Since each tuple (p, j) in these lists represents a probability that sentence i is in class j, this update keeps #track of the most likely prediction so far final_train_predictions = [max(final_train_predictions[i], (pred_train_results[i][1], j)) for i in range(len(pred_train_results))] final_test_predictions = [max(final_test_predictions[i], (pred_test_results[i][1], j)) for i in range(len(pred_test_results))] individual_train_predictions[cla] = [np.argmax(pred) for pred in pred_train_results] individual_test_predictions[cla] = [np.argmax(pred) for pred in pred_test_results] #individual accuracy for cla in classes: train_pred = individual_train_predictions[cla] train_actual = data_sets_labels[cla]['train'] acc = [train_pred[i] == np.argmax(train_actual[i]) for i in range(len(train_pred))] print("\n\nfor", cla, ": train accuracy =", sum(acc)/len(acc)) test_pred = individual_test_predictions[cla] test_actual = data_sets_labels[cla]['test'] acc = [test_pred[i] == np.argmax(test_actual[i]) for i in range(len(test_pred))] print("for", cla, ": test accuracy =", sum(acc)/len(acc)) from sklearn.metrics import confusion_matrix for cla in classes: print("\n\n for", cla, "\n", confusion_matrix([np.argmax(t) for t in test_predictions_dict[cla][1]], test_predictions_dict[cla][0])) #true, pred confusion_matrix(orig_test_labels, [r[1] for r in final_test_predictions]) correct = 0 for i, res in enumerate(final_train_predictions): pred_result = res[1] train_result = orig_train_labels[i] #print(train_sent[i]) #print(res.flatten()) #print(pred_result,train_result) if train_result == pred_result: correct += 1 #print(f'Result: {train_array, train_result}, Predicted result: {res, pred_result}') print('Correct overall predictions (train):',correct/len(train_results_tweaked)) correct = 0 for i, res in enumerate(final_test_predictions): pred_result = res[1] test_result = orig_test_labels[i] if test_result == pred_result: correct += 1 print('Correct overall predictions (test):',correct/len(test_results_tweaked)) pickle.dump(ps, open("results/sentiment_analysis_qiskit_1vall.p", "wb")) fig, axs = plt.subplots(2,2, figsize=(15,10)) import matplotlib.pyplot as plt colours = ['blue', 'red', 'orange', 'green'] for i in range(4): costs = ps[classes[i]][1][51:] #excluding the first 51 values since they are used for calibration n = ps[cla][0][-1] costs = [(costs[j*2] + costs[j*2 + 1])/2 for j in range(n//2)] #averages over xplus and xminus values axs[i//2, i%2].plot(ps[classes[i]][1][51:], color=colours[i]) axs[i//2, i%2].set_title(classes[i]) axs[i//2, i%2].set_xlabel('iterations') axs[i//2, i%2].set_ylabel('cost') axs[i//2, i%2].set_ylim(0,2.5)
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. """Depth pass testing""" import unittest from qiskit import QuantumCircuit, QuantumRegister from qiskit.converters import circuit_to_dag from qiskit.transpiler.passes import Depth from qiskit.test import QiskitTestCase class TestDepthPass(QiskitTestCase): """Tests for Depth analysis methods.""" def test_empty_dag(self): """Empty DAG has 0 depth""" circuit = QuantumCircuit() dag = circuit_to_dag(circuit) pass_ = Depth() _ = pass_.run(dag) self.assertEqual(pass_.property_set["depth"], 0) def test_just_qubits(self): """A dag with 8 operations and no classic bits""" # ┌───┐ ┌───┐┌───┐ # q0_0: ┤ H ├──■────■────■────■──┤ X ├┤ X ├ # ├───┤┌─┴─┐┌─┴─┐┌─┴─┐┌─┴─┐└─┬─┘└─┬─┘ # q0_1: ┤ H ├┤ X ├┤ X ├┤ X ├┤ X ├──■────■── # └───┘└───┘└───┘└───┘└───┘ qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[1], qr[0]) dag = circuit_to_dag(circuit) pass_ = Depth() _ = pass_.run(dag) self.assertEqual(pass_.property_set["depth"], 7) def test_depth_one(self): """A dag with operations in parallel and depth 1""" qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[1]) dag = circuit_to_dag(circuit) pass_ = Depth() _ = pass_.run(dag) self.assertEqual(pass_.property_set["depth"], 1) def test_depth_control_flow(self): """A DAG with control flow still gives an estimate.""" qc = QuantumCircuit(5, 1) qc.h(0) qc.measure(0, 0) with qc.if_test((qc.clbits[0], True)) as else_: qc.x(1) qc.cx(2, 3) with else_: qc.x(1) with qc.for_loop(range(3)): qc.z(2) with qc.for_loop((4, 0, 1)): qc.z(2) with qc.while_loop((qc.clbits[0], True)): qc.h(0) qc.measure(0, 0) pass_ = Depth(recurse=True) pass_(qc) self.assertEqual(pass_.property_set["depth"], 16) if __name__ == "__main__": unittest.main()
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. """Helper function for converting a circuit to an instruction.""" from qiskit.exceptions import QiskitError from qiskit.circuit.instruction import Instruction from qiskit.circuit.quantumregister import QuantumRegister from qiskit.circuit.classicalregister import ClassicalRegister, Clbit def circuit_to_instruction(circuit, parameter_map=None, equivalence_library=None, label=None): """Build an :class:`~.circuit.Instruction` object from a :class:`.QuantumCircuit`. The instruction is anonymous (not tied to a named quantum register), and so can be inserted into another circuit. The instruction will have the same string name as the circuit. Args: circuit (QuantumCircuit): the input circuit. parameter_map (dict): For parameterized circuits, a mapping from parameters in the circuit to parameters to be used in the instruction. If None, existing circuit parameters will also parameterize the instruction. equivalence_library (EquivalenceLibrary): Optional equivalence library where the converted instruction will be registered. label (str): Optional instruction label. Raises: QiskitError: if parameter_map is not compatible with circuit Return: qiskit.circuit.Instruction: an instruction equivalent to the action of the input circuit. Upon decomposition, this instruction will yield the components comprising the original circuit. Example: .. code-block:: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.converters import circuit_to_instruction 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) circuit_to_instruction(circ) """ # pylint: disable=cyclic-import from qiskit.circuit.quantumcircuit import QuantumCircuit if parameter_map is None: parameter_dict = {p: p for p in circuit.parameters} else: parameter_dict = circuit._unroll_param_dict(parameter_map) if parameter_dict.keys() != circuit.parameters: raise QiskitError( ( "parameter_map should map all circuit parameters. " "Circuit parameters: {}, parameter_map: {}" ).format(circuit.parameters, parameter_dict) ) out_instruction = Instruction( name=circuit.name, num_qubits=circuit.num_qubits, num_clbits=circuit.num_clbits, params=[*parameter_dict.values()], label=label, ) out_instruction.condition = None target = circuit.assign_parameters(parameter_dict, inplace=False) if equivalence_library is not None: equivalence_library.add_equivalence(out_instruction, target) regs = [] if out_instruction.num_qubits > 0: q = QuantumRegister(out_instruction.num_qubits, "q") regs.append(q) if out_instruction.num_clbits > 0: c = ClassicalRegister(out_instruction.num_clbits, "c") regs.append(c) qubit_map = {bit: q[idx] for idx, bit in enumerate(circuit.qubits)} clbit_map = {bit: c[idx] for idx, bit in enumerate(circuit.clbits)} definition = [ instruction.replace( qubits=[qubit_map[y] for y in instruction.qubits], clbits=[clbit_map[y] for y in instruction.clbits], ) for instruction in target.data ] # fix condition for rule in definition: condition = getattr(rule.operation, "condition", None) if condition: reg, val = condition if isinstance(reg, Clbit): rule.operation.condition = (clbit_map[reg], val) elif reg.size == c.size: rule.operation.condition = (c, val) else: raise QiskitError( "Cannot convert condition in circuit with " "multiple classical registers to instruction" ) qc = QuantumCircuit(*regs, name=out_instruction.name) for instruction in definition: qc._append(instruction) if circuit.global_phase: qc.global_phase = circuit.global_phase out_instruction.definition = qc return out_instruction
https://github.com/martynscn/Masters-Thesis-on-Quantum-Cryptography
martynscn
# This code has been adapted and modified from IBM Qiskit 2021 and also from https://github.com/ttlion/ShorAlgQiskit. # It uses the implementation as contained in the work of Stephane Beauregard (https://arxiv.org/abs/quant-ph/0205095) # Many thanks to IBM Qiskit team, Tiago Miguel (ttlion), Qubit by Qubit, Peter Shor and Stephane Beauregard. from typing import Optional, Union, Tuple, List import math import array import fractions import logging import numpy as np from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, execute, IBMQ, transpile,BasicAer, Aer, assemble from qiskit.circuit import Gate, Instruction, ParameterVector from qiskit.circuit.library import QFT from qiskit.providers import BaseBackend, Backend from qiskit.quantum_info import partial_trace from qiskit.utils import summarize_circuits from qiskit.utils.arithmetic import is_power from qiskit.utils.validation import validate_min from qiskit.utils.quantum_instance import QuantumInstance import qiskit.visualization from qiskit.providers.aer import QasmSimulator from datetime import datetime import csv # provider = IBMQ.enable_account("PUT TOKEN HERE") backend = QasmSimulator() from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" #"last_expr" or "all" # """ Function to check if N is of type q^p""" def check_if_power(N): # """ Check if N is a perfect power in O(n^3) time, n=ceil(logN) """ b=2 while (2**b) <= N: a = 1 c = N while (c-a) >= 2: m = int( (a+c)/2 ) if (m**b) < (N+1): p = int( (m**b) ) else: p = int(N+1) if int(p) == int(N): print('N is {0}^{1}'.format(int(m),int(b)) ) return True if p<N: a = int(m) else: c = int(m) b=b+1 return False def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m def create_QFT(circuit,up_reg,n,with_swaps): i=n-1 while i>=0: circuit.h(up_reg[i]) j=i-1 while j>=0: if (np.pi)/(pow(2,(i-j))) > 0: circuit.cu1( (np.pi)/(pow(2,(i-j))) , up_reg[i] , up_reg[j] ) j=j-1 i=i-1 if with_swaps==1: i=0 while i < ((n-1)/2): circuit.swap(up_reg[i], up_reg[n-1-i]) i=i+1 def create_inverse_QFT(circuit,up_reg,n,with_swaps): if with_swaps==1: i=0 while i < ((n-1)/2): circuit.swap(up_reg[i], up_reg[n-1-i]) i=i+1 i=0 while i<n: circuit.h(up_reg[i]) if i != n-1: j=i+1 y=i while y>=0: if (np.pi)/(pow(2,(j-y))) > 0: circuit.cu1( - (np.pi)/(pow(2,(j-y))) , up_reg[j] , up_reg[y] ) y=y-1 i=i+1 def getAngle(a, N): s=bin(int(a))[2:].zfill(N) angle = 0 for i in range(0, N): if s[N-1-i] == '1': angle += math.pow(2, -(N-i)) angle *= np.pi return angle def getAngles(a,N): s=bin(int(a))[2:].zfill(N) angles=np.zeros([N]) for i in range(0, N): for j in range(i,N): if s[j]=='1': angles[N-i-1]+=math.pow(2, -(j-i)) angles[N-i-1]*=np.pi return angles def ccphase(circuit, angle, ctl1, ctl2, tgt): circuit.cu1(angle/2,ctl1,tgt) circuit.cx(ctl2,ctl1) circuit.cu1(-angle/2,ctl1,tgt) circuit.cx(ctl2,ctl1) circuit.cu1(angle/2,ctl2,tgt) def phiADD(circuit, q, a, N, inv): angle=getAngles(a,N) for i in range(0,N): if inv==0: circuit.u1(angle[i],q[i]) else: circuit.u1(-angle[i],q[i]) def cphiADD(circuit, q, ctl, a, n, inv): angle=getAngles(a,n) for i in range(0,n): if inv==0: circuit.cu1(angle[i],ctl,q[i]) else: circuit.cu1(-angle[i],ctl,q[i]) def ccphiADD(circuit,q,ctl1,ctl2,a,n,inv): angle=getAngles(a,n) for i in range(0,n): if inv==0: ccphase(circuit,angle[i],ctl1,ctl2,q[i]) else: ccphase(circuit,-angle[i],ctl1,ctl2,q[i]) def ccphiADDmodN(circuit, q, ctl1, ctl2, aux, a, N, n): ccphiADD(circuit, q, ctl1, ctl2, a, n, 0) phiADD(circuit, q, N, n, 1) # phiADD(circuit, q, a,N, 1) create_inverse_QFT(circuit, q, n, 0) circuit.cx(q[n-1],aux) create_QFT(circuit,q,n,0) cphiADD(circuit, q, aux, N, n, 0) # cphiADD(circuit, q, aux, a, n, 0) ccphiADD(circuit, q, ctl1, ctl2, a, n, 1) create_inverse_QFT(circuit, q, n, 0) circuit.x(q[n-1]) circuit.cx(q[n-1], aux) circuit.x(q[n-1]) create_QFT(circuit,q,n,0) ccphiADD(circuit, q, ctl1, ctl2, a, n, 0) def ccphiADDmodN_inv(circuit, q, ctl1, ctl2, aux, a, N, n): ccphiADD(circuit, q, ctl1, ctl2, a, n, 1) create_inverse_QFT(circuit, q, n, 0) circuit.x(q[n-1]) circuit.cx(q[n-1],aux) circuit.x(q[n-1]) create_QFT(circuit, q, n, 0) ccphiADD(circuit, q, ctl1, ctl2, a, n, 0) cphiADD(circuit, q, aux, N, n, 1) # cphiADD(circuit, q, aux, a, n, 1) create_inverse_QFT(circuit, q, n, 0) circuit.cx(q[n-1], aux) create_QFT(circuit, q, n, 0) phiADD(circuit, q, N, n, 0) # phiADD(circuit, q, a, N, 0) ccphiADD(circuit, q, ctl1, ctl2, a, n, 1) def cMULTmodN(circuit, ctl, q, aux, a, N, n): # up_reg = QuantumRegister(1, name = "up_reg") # down_reg = QuantumRegister(n, name = "down_reg") # up_classic = ClassicalRegister(2*n, name="up_classic") # c_aux = ClassicalRegister(1, name = "aux_classic") # cMULTmodN_circuit = QuantumCircuit( # up_reg ,down_reg , aux,up_classic, c_aux, # name=r"${0}^{{{1}^{{{2}}}}} mod{3}$".format(2,2,int(math.log(math.log(a,2),2)), N) # ) # create_QFT(cMULTmodN_circuit,aux,n+1,0) # for i in range(0, n): # ccphiADDmodN(cMULTmodN_circuit, aux, q[i], ctl, aux[n+1], (2**i)*a % N, N, n+1) # create_inverse_QFT(cMULTmodN_circuit, aux, n+1, 0) # for i in range(0, n): # circuit.cswap(ctl,q[i],aux[i]) # cMULTmodN_circuit.cswap(ctl,q[i],aux[i]) # create_QFT(cMULTmodN_circuit, aux, n+1, 0) # ccphiADDmodN_inv(cMULTmodN_circuit, aux, q[i], ctl, aux[n+1], math.pow(2,i)*a_inv % N, N, n+1) # create_inverse_QFT(cMULTmodN_circuit, aux, n+1, 0) # cMULTmodN_circuit_instruction = cMULTmodN_circuit.to_instruction() # circuit.append(cMULTmodN_circuit_instruction, [ctl, *down_reg, *aux]) create_QFT(circuit,aux,n+1,0) for i in range(0, n): ccphiADDmodN(circuit, aux, q[i], ctl, aux[n+1], (2**i)*a % N, N, n+1) create_inverse_QFT(circuit, aux, n+1, 0) for i in range(0, n): circuit.cswap(ctl,q[i],aux[i]) a_inv = modinv(a, N) create_QFT(circuit, aux, n+1, 0) i = n-1 while i >= 0: ccphiADDmodN_inv(circuit, aux, q[i], ctl, aux[n+1], math.pow(2,i)*a_inv % N, N, n+1) i -= 1 create_inverse_QFT(circuit, aux, n+1, 0) def calculate_continued_fraction(b: array.array) -> int: # """Calculate the continued fraction of x/T from the current terms of expansion b.""" x_over_T = 0 for i in reversed(range(len(b) - 1)): x_over_T = 1 / (b[i + 1] + x_over_T) x_over_T += b[0] frac = fractions.Fraction(x_over_T).limit_denominator() return frac.denominator def get_factors(N: int, a: int, measurement: str) -> Optional[List[int]]: # """Apply the continued fractions to find r and the gcd to find the desired factors.""" x_final = int(measurement, 2) #print('In decimal, x_final value for this result is: {}.'.format(x_final)) if x_final <= 0: fail_reason = 'x_final value is <= 0, there are no continued fractions.' else: fail_reason = None #print('Running continued fractions for this case.') # Calculate T and x/T T_upper = len(measurement) T = pow(2, T_upper) x_over_T = x_final / T ## this is our theta # Cycle in which each iteration corresponds to putting one more term in the # calculation of the Continued Fraction (CF) of x/T # Initialize the first values according to CF rule i = 0 b = array.array('i') t = array.array('f') b.append(math.floor(x_over_T)) t.append(x_over_T - b[i]) exponential = 0.0 while i < N and fail_reason is None: # From the 2nd iteration onwards, calculate the new terms of the CF based on the previous terms as the rule suggests if i > 0: try: b_temp = math.floor(1 / t[i - 1]) except ZeroDivisionError as err: b_temp = 0 b.append(b_temp) try: t_temp = (1 / t[i - 1]) - b[i] except ZeroDivisionError as err: t_temp = 0 t.append(t_temp) # type: ignore # Calculate the denominator of the CF using the known terms denominator = calculate_continued_fraction(b) # Increment i for next iteration i += 1 if denominator % 2 == 1: #print('Odd denominator, will try next iteration of continued fractions.') continue # Denominator is even, try to get factors of N. Get the exponential a^(r/2) if denominator < 1000: try: exponential = pow(a, denominator / 2) except OverflowError as err: exponential = 999999999 # Check if the value is too big or not if exponential > 1000000: if exponential == 999999999: fail_reason = 'OverflowError' else: fail_reason = 'denominator of continued fraction is too big (> 10^3).' else: # The value is not too big, get the right values and do the proper gcd() putting_plus = int(exponential + 1) putting_minus = int(exponential - 1) one_factor = math.gcd(putting_plus, N) other_factor = math.gcd(putting_minus, N) # Check if the factors found are trivial factors or are the desired factors if any(factor in {1, N} for factor in (one_factor, other_factor)): #print('Found just trivial factors, not good enough.') # Check if the number has already been found, (use i - 1 because i was already incremented) if t[i - 1] == 0: fail_reason = 'the continued fractions found exactly x_final/(2^(2n)).' else: return sorted((one_factor, other_factor)) return None def process_results(sim_result, circuit, shots, N, a, n): counts_result = sim_result.get_counts(circuit) total_counts = len(counts_result) counts_result_sorted = sorted(counts_result.items(), key=lambda x: x[1], reverse=True) counts_result_keys = list(counts_result.keys()) counts_result_values = list(counts_result.values()) prob_success=0 prob_failure=0 result_successful_counts = 0 result_failure_counts = 0 for initial_undesired_measurement, frequency in counts_result_sorted: measurement = initial_undesired_measurement.split(" ")[1] x_value = int(measurement, 2) prob_this_result = 100 * frequency/shots factors = get_factors(N, a, measurement) if factors: prob_success = prob_success + prob_this_result result_successful_counts = result_successful_counts + 1 if factors not in result_factors: result_factors.append(factors) elif not factors: prob_failure = prob_failure + prob_this_result result_failure_counts = result_failure_counts + 1 return [result_factors, prob_success, prob_failure, total_counts, result_successful_counts,result_failure_counts] def my_shor(a,N,shots): start_time_number = datetime.now() start_time = start_time_number.strftime("%H:%M:%S") summary_result = dict() validate_min('N', N, 3) validate_min('a', a, 2) if N < 1 or N % 2 == 0: raise ValueError('The input needs to be an odd integer greater than 1.') if a >= N or math.gcd(a, N) != 1: raise ValueError('The integer a needs to satisfy a < N and gcd(a, N) = 1.') n = math.ceil(math.log(N,2)) global result_factors result_factors = [] tf, b, p = is_power(N, return_decomposition=True) if tf: print('The input integer is a power: {0}={1}^{2}.'.format(N, b, p)) result_factors.append(b) # """auxilliary quantum register used in addition and multiplication""" aux = QuantumRegister(size = n+2, name="aux_reg") # """single qubit where the sequential QFT is performed""" up_reg = QuantumRegister(1, name = "up_reg") down_reg = QuantumRegister(n, name = "down_reg") # """classical register where the measured values of the sequential QFT are stored""" up_classic = ClassicalRegister(2*n, name="up_classic") # """classical bit used to reset the state of the top qubit to 0 if the previous measurement was 1""" c_aux = ClassicalRegister(1, name = "aux_classic") # """ Create Quantum Circuit """ circuit = QuantumCircuit(up_reg ,down_reg , aux,up_classic, c_aux) circuit.x(down_reg[0]) # circuit.draw(filename = "shor_semiclassical_QFT_initialization") for i in range(0, 2*n): circuit.x(up_reg).c_if(c_aux, 1) circuit.h(up_reg) cMULTmodN(circuit, up_reg[0], down_reg, aux, a**(2**(2*n-1-i)), N, n) # later confirm if this should be up_reg[i] instead of up_reg[0] for j in range(0, 2**i): circuit.u1(getAngle(j, i), up_reg[0]).c_if(up_classic, j) circuit.h(up_reg) circuit.measure(up_reg[0], up_classic[i]) circuit.measure(up_reg[0], c_aux[0]) # circuit.draw(filename = "shor_semiclassical_QFT_final_circuit") circuit.draw() qc_compiled = transpile(circuit, backend, optimization_level = 3) job_sim_1 = backend.run(qc_compiled, shots=shots) sim_result=job_sim_1.result() # counts_result = sim_result.get_counts(circuit) # len(counts_result) # measurement_plot = qiskit.visualization.plot_histogram(counts_result,figsize=(20, 12) ,number_to_keep = 30,bar_labels=True, title = "Measurement results from shor_standard_QFT circuit variant" ) # measurement_plot.savefig("shor_semiclassical_QFT_measurement_result") # measurement_plot processed_result = process_results(sim_result, circuit, shots, N, a, n) end_time_number = datetime.now() end_time = end_time_number.strftime("%H:%M:%S") duration = end_time_number - start_time_number print("Current Start Time =", start_time) print(processed_result) print("Current End Time =", end_time) circuit_count_ops = circuit.count_ops() circuit_decomposed = circuit.decompose() circuit_decomposed_count_ops = circuit_decomposed.count_ops() qc_compiled_count_ops = qc_compiled.count_ops() summary_result["num_qubits"] = n summary_result["Number(N)"] = N summary_result["a"] = a summary_result["start_time"] = start_time summary_result["end_time"] = end_time summary_result["duration"] = duration summary_result["result_factors"] = processed_result[0] summary_result["prob_success"] = processed_result[1] summary_result["prob_failure"] = processed_result[2] summary_result["total_counts"] = processed_result[3] summary_result["result_successful_counts"] = processed_result[4] summary_result["result_failure_counts"] = processed_result[5] summary_result["circuit_width"] = circuit.width() summary_result["circuit_depth"] = circuit.depth() summary_result["circuit_size"] = circuit.size() summary_result["circuit_num_nonlocal_gates"] = circuit.num_nonlocal_gates() summary_result["circuit_num_ancillas"] = circuit.num_ancillas summary_result["circuit_num_clbits"] = circuit.num_clbits summary_result["circuit_num_qubits"] = circuit.num_qubits summary_result["circuit_num_ancillas"] = circuit.num_ancillas summary_result["circuit_num_of_count_ops"] = len(circuit_count_ops) summary_result["circuit_num_of_x"] = circuit_count_ops.get('x') summary_result["circuit_num_of_measure"] = circuit_count_ops.get('measure') summary_result["circuit_num_of_h"] = circuit_count_ops.get('h') summary_result["circuit_num_of_cswap"] = circuit_count_ops.get('cswap') summary_result["circuit_num_of_swap"] = circuit_count_ops.get('swap') summary_result["circuit_num_of_cx"] = circuit_count_ops.get('cx') summary_result["circuit_num_of_toffoli"] = circuit_count_ops.get('toffoli') summary_result["circuit_num_of_p"] = circuit_count_ops.get('p') summary_result["circuit_num_of_t"] = circuit_count_ops.get('t') summary_result["circuit_decomposed_width"] = circuit_decomposed.width() summary_result["circuit_decomposed_depth"] = circuit_decomposed.depth() summary_result["circuit_decomposed_size"] = circuit_decomposed.size() summary_result["circuit_decomposed_num_nonlocal_gates"] = circuit_decomposed.num_nonlocal_gates() summary_result["circuit_decomposed_num_ancillas"] = circuit_decomposed.num_ancillas summary_result["circuit_decomposed_num_clbits"] = circuit_decomposed.num_clbits summary_result["circuit_decomposed_num_qubits"] = circuit_decomposed.num_qubits summary_result["circuit_decomposed_num_ancillas"] = circuit_decomposed.num_ancillas summary_result["circuit_decomposed_num_of_count_ops"] = len(circuit_decomposed_count_ops) summary_result["circuit_decomposed_num_of_x"] = circuit_decomposed_count_ops.get('x') summary_result["circuit_decomposed_num_of_measure"] = circuit_decomposed_count_ops.get('measure') summary_result["circuit_decomposed_num_of_h"] = circuit_decomposed_count_ops.get('h') summary_result["circuit_decomposed_num_of_cswap"] = circuit_decomposed_count_ops.get('cswap') summary_result["circuit_decomposed_num_of_swap"] = circuit_decomposed_count_ops.get('swap') summary_result["circuit_decomposed_num_of_cx"] = circuit_decomposed_count_ops.get('cx') summary_result["circuit_decomposed_num_of_toffoli"] = circuit_decomposed_count_ops.get('toffoli') summary_result["circuit_decomposed_num_of_p"] = circuit_decomposed_count_ops.get('p') summary_result["circuit_decomposed_num_of_t"] = circuit_decomposed_count_ops.get('t') summary_result["qc_compiled_width"] = qc_compiled.width() summary_result["qc_compiled_depth"] = qc_compiled.depth() summary_result["qc_compiled_size"] = qc_compiled.size() summary_result["qc_compiled_num_nonlocal_gates"] = qc_compiled.num_nonlocal_gates() summary_result["qc_compiled_num_ancillas"] = qc_compiled.num_ancillas summary_result["qc_compiled_num_clbits"] = qc_compiled.num_clbits summary_result["qc_compiled_num_qubits"] = qc_compiled.num_qubits summary_result["qc_compiled_num_ancillas"] = qc_compiled.num_ancillas summary_result["qc_compiled_num_of_count_ops"] = len(qc_compiled_count_ops) summary_result["qc_compiled_num_of_x"] = qc_compiled_count_ops.get('x') summary_result["qc_compiled_num_of_measure"] = qc_compiled_count_ops.get('measure') summary_result["qc_compiled_num_of_h"] = qc_compiled_count_ops.get('h') summary_result["qc_compiled_num_of_cswap"] = qc_compiled_count_ops.get('cswap') summary_result["qc_compiled_num_of_swap"] = qc_compiled_count_ops.get('swap') summary_result["qc_compiled_num_of_cx"] = qc_compiled_count_ops.get('cx') summary_result["qc_compiled_num_of_toffoli"] = qc_compiled_count_ops.get('toffoli') summary_result["qc_compiled_num_of_p"] = qc_compiled_count_ops.get('p') summary_result["qc_compiled_num_of_t"] = qc_compiled_count_ops.get('t') return summary_result # Run for just a single number N %%time N = 21 shots = 1024 global result_factors all_summary_result_temp = [] for random_a in range(2, N): if math.gcd(random_a,N) > 1: continue a = random_a summary_result = my_shor(a,N,shots) print("Finished running for a = {} and N = {}\n".format(a, N)) all_summary_result_temp.append(summary_result) summary_result_list = [] for key, value in summary_result.items(): summary_result_list.append([key,value]) summary_result_list with open("a({0})_N({1})_semiclassical.csv".format(a, N), 'a') as myfile: write = csv.writer(myfile) #write.writerow(fields) write.writerows(summary_result_list) all_summary_result_temp # Run for many numbers N. %%time shots = 1024 global result_factors all_summary_result = [] for N in [15, 21, 33, 35, 39, 51, 55, 57]: for a in range(2, N): if math.gcd(a,N) > 1: continue print("Beginning running for a = {} and N = {}".format(a, N)) summary_result = my_shor(a,N,shots) print("Finished running for a = {} and N = {}\n\n".format(a, N)) all_summary_result.append(summary_result) all_summary_result %qiskit_copyright
https://github.com/Gopal-Dahale/qiskit-qulacs
Gopal-Dahale
import numpy as np # Import Qiskit from qiskit import QuantumCircuit, transpile from qiskit_qulacs import QulacsProvider from qiskit_qulacs.qulacs_backend import QulacsBackend from qiskit.visualization import plot_histogram, plot_state_city import qiskit.quantum_info as qi seed = 42 np.random.seed(seed) provider = QulacsProvider() qulacs_simulator = provider.get_backend("qulacs_simulator") qulacs_simulator qulacs_simulator.available_devices() # Create circuit circ = QuantumCircuit(2) circ.h(0) circ.cx(0, 1) # Transpile for simulator qulacs_simulator = QulacsBackend() circ = transpile(circ, qulacs_simulator) # Run and get statevector result = qulacs_simulator.run(circ).result() statevector = result.get_statevector() plot_state_city(statevector, title="Bell state") result = qulacs_simulator.run(circ, shots=1024, seed_simulator=seed).result() counts = result.get_counts() plot_histogram(counts, title="Bell-State counts") # Run and get memory result = qulacs_simulator.run(circ, shots=10, seed_simulator=seed).result() memory = result.get_memory() print(memory) # Create circuit circ = QuantumCircuit(1) for i in range(1000): circ.h(0) qulacs_simulator = QulacsBackend() backend_options = { "qco_enable": True, # Enables the QuantumCircuitOptimizer "qco_method": "light", # Uses light method for circuit optimization from qulacs } qulacs_simulator.set_options(**backend_options) # Run and get statevector result = qulacs_simulator.run(circ).result() statevector = result.get_statevector() print(statevector.real) import qiskit qiskit.__version__
https://github.com/Qiskit/feedback
Qiskit
from qiskit_nature.hdf5 import load_from_hdf5, save_to_hdf5 from qiskit_nature.drivers.second_quantization import PySCFDriver, GaussianForcesDriver from qiskit_nature.properties.second_quantization.vibrational.bases import HarmonicBasis electronic_driver = PySCFDriver( atom="H 0.0 0.0 0.0; Li 0.0 0.0 1.3", basis="sto-3g", ) electronic_structure_driver_result = electronic_driver.run() print(electronic_structure_driver_result) save_to_hdf5(electronic_structure_driver_result, "tmp_electronic_structure_driver_result.hdf5", replace=True) new_electronic_structure_driver_result = load_from_hdf5("tmp_electronic_structure_driver_result.hdf5") print(new_electronic_structure_driver_result) vibrational_driver = GaussianForcesDriver( logfile="test/drivers/second_quantization/gaussiand/test_driver_gaussian_log_C01.txt" ) vibrational_structure_driver_result = vibrational_driver.run() vibrational_structure_driver_result.basis = HarmonicBasis(num_modals_per_mode=2) print(vibrational_structure_driver_result) save_to_hdf5(vibrational_structure_driver_result, "tmp_vibrational_structure_driver_result.hdf5", replace=True) new_vibrational_structure_driver_result = load_from_hdf5("tmp_vibrational_structure_driver_result.hdf5") print(new_vibrational_structure_driver_result) from __future__ import annotations from typing import Protocol import h5py class HDF5Storable(Protocol): """A Protocol implemented by those classes which support conversion methods for HDF5.""" def to_hdf5(self, parent: h5py.Group) -> None: """Stores this instance in an HDF5 group inside of the provided parent group. ... """ ... @staticmethod def from_hdf5(h5py_group: h5py.Group) -> HDF5Storable: """Constructs a new instance from the data stored in the provided HDF5 group. ... """ ... class Molecule: VERSION = 1 def to_hdf5(self, parent: h5py.Group) -> None: group = parent.require_group(self.__class__.__name__) group.attrs["__class__"] = self.__class__.__name__ group.attrs["__module__"] = self.__class__.__module__ group.attrs["__version__"] = self.VERSION geometry_group = group.create_group("geometry", track_order=True) for idx, geom in enumerate(self._geometry): symbol, coords = geom geometry_group.create_dataset(str(idx), data=coords) geometry_group[str(idx)].attrs["symbol"] = symbol group.attrs["units"] = self.units.value group.attrs["multiplicity"] = self.multiplicity group.attrs["charge"] = self.charge if self._masses: group.create_dataset("masses", data=self._masses) @staticmethod def from_hdf5(h5py_group: h5py.Group) -> Molecule: geometry = [] for atom in h5py_group["geometry"].values(): geometry.append((atom.attrs["symbol"], list(atom[...]))) units: UnitsType for unit in UnitsType: if unit.value == h5py_group.attrs["units"]: units = unit break else: units = UnitsType.ANGSTROM multiplicity = h5py_group.attrs["multiplicity"] charge = h5py_group.attrs["charge"] masses = None if "masses" in h5py_group.keys(): masses = list(h5py_group["masses"]) return Molecule( geometry, multiplicity=multiplicity, charge=charge, units=units, masses=masses, ) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import ( ElectronicStructureDriverType, ElectronicStructureMoleculeDriver, PySCFDriver, ) from qiskit_nature.problems.second_quantization import ElectronicStructureProblem from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer from qiskit_nature.settings import settings settings.dict_aux_operators = True molecule = Molecule( geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]], charge=0, multiplicity=1 ) driver = ElectronicStructureMoleculeDriver( molecule, basis="sto3g", driver_type=ElectronicStructureDriverType.PYSCF ) # or equivalently: driver = PySCFDriver.from_molecule(molecule, basis="sto3g") transformer = FreezeCoreTransformer() problem = ElectronicStructureProblem(driver, transformers=[transformer]) # Note: at this point, `driver.run()` has NOT been called yet. We can trigger this indirectly like so: second_q_ops = problem.second_q_ops() hamiltonian = second_q_ops["ElectronicEnergy"] print(hamiltonian) from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo from qiskit_nature.second_q.transformers import FreezeCoreTransformer molecule = MoleculeInfo(["H", "H"], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.735)], charge=0, multiplicity=1) driver = PySCFDriver.from_molecule(molecule, basis="sto3g") # this is now done explicitly problem = driver.run() transformer = FreezeCoreTransformer() # and you also apply transformers explicitly problem = transformer.transform(problem) hamiltonian = problem.hamiltonian.second_q_op() print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."])) from qiskit_nature.drivers import Molecule from qiskit_nature.drivers.second_quantization import PySCFDriver molecule = Molecule( geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]], charge=0, multiplicity=1 ) driver = PySCFDriver.from_molecule(molecule) result = driver.run() print(type(result)) from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.formats.molecule_info import MoleculeInfo molecule = MoleculeInfo(["H", "H"], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.735)], charge=0, multiplicity=1) driver = PySCFDriver.from_molecule(molecule, basis="sto3g") result = driver.run() print(type(result)) from qiskit_nature.drivers.second_quantization import FCIDumpDriver path_to_fcidump = "aux_files/h2.fcidump" driver = FCIDumpDriver(path_to_fcidump) result = driver.run() print(type(result)) from qiskit_nature.second_q.formats.fcidump import FCIDump path_to_fcidump = "aux_files/h2.fcidump" fcidump = FCIDump.from_file(path_to_fcidump) print(type(fcidump)) from qiskit_nature.second_q.formats.fcidump_translator import fcidump_to_problem problem = fcidump_to_problem(fcidump) print(type(problem)) from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer transformer = FreezeCoreTransformer() driver = PySCFDriver() transformed_result = transformer.transform(driver.run()) print(type(transformed_result)) from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.transformers import FreezeCoreTransformer transformer = FreezeCoreTransformer() driver = PySCFDriver() transformed_result = transformer.transform(driver.run()) print(type(transformed_result)) from qiskit_nature.drivers.second_quantization import PySCFDriver from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer driver = PySCFDriver() transformer = FreezeCoreTransformer() problem = ElectronicStructureProblem(driver, transformers=[transformer]) # we trigger driver.run() implicitly like so: second_q_ops = problem.second_q_ops() hamiltonian_op = second_q_ops.pop("ElectronicEnergy") aux_ops = second_q_ops from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.transformers import FreezeCoreTransformer driver = PySCFDriver() problem = driver.run() transformer = FreezeCoreTransformer() problem = transformer.transform(problem) hamiltonian_op, aux_ops = problem.second_q_ops() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.compiler import transpile from qiskit.transpiler import PassManager circ = QuantumCircuit(3) circ.ccx(0, 1, 2) circ.draw(output='mpl') from qiskit.transpiler.passes import Unroller pass_ = Unroller(['u1', 'u2', 'u3', 'cx']) pm = PassManager(pass_) new_circ = pm.run(circ) new_circ.draw(output='mpl') from qiskit.transpiler import passes [pass_ for pass_ in dir(passes) if pass_[0].isupper()] from qiskit.transpiler import CouplingMap, Layout from qiskit.transpiler.passes import BasicSwap, LookaheadSwap, StochasticSwap coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]] circuit = QuantumCircuit(7) circuit.h(3) circuit.cx(0, 6) circuit.cx(6, 0) circuit.cx(0, 1) circuit.cx(3, 1) circuit.cx(3, 0) coupling_map = CouplingMap(couplinglist=coupling) bs = BasicSwap(coupling_map=coupling_map) pass_manager = PassManager(bs) basic_circ = pass_manager.run(circuit) ls = LookaheadSwap(coupling_map=coupling_map) pass_manager = PassManager(ls) lookahead_circ = pass_manager.run(circuit) ss = StochasticSwap(coupling_map=coupling_map) pass_manager = PassManager(ss) stochastic_circ = pass_manager.run(circuit) circuit.draw(output='mpl') basic_circ.draw(output='mpl') lookahead_circ.draw(output='mpl') stochastic_circ.draw(output='mpl') import math from qiskit.providers.fake_provider import FakeTokyo backend = FakeTokyo() # mimics the tokyo device in terms of coupling map and basis gates qc = QuantumCircuit(10) random_state = [ 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)] qc.initialize(random_state, range(4)) qc.draw() optimized_0 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=0) print('gates = ', optimized_0.count_ops()) print('depth = ', optimized_0.depth()) optimized_1 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=1) print('gates = ', optimized_1.count_ops()) print('depth = ', optimized_1.depth()) optimized_2 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=2) print('gates = ', optimized_2.count_ops()) print('depth = ', optimized_2.depth()) optimized_3 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=3) print('gates = ', optimized_3.count_ops()) print('depth = ', optimized_3.depth()) from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit 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) circ.draw(output='mpl') from qiskit.converters import circuit_to_dag from qiskit.tools.visualization import dag_drawer dag = circuit_to_dag(circ) dag_drawer(dag) dag.op_nodes() node = dag.op_nodes()[3] print("node name: ", node.name) print("node op: ", node.op) print("node qargs: ", node.qargs) print("node cargs: ", node.cargs) print("node condition: ", node.op.condition) from qiskit.circuit.library import HGate dag.apply_operation_back(HGate(), qargs=[q[0]]) dag_drawer(dag) from qiskit.circuit.library import CCXGate dag.apply_operation_front(CCXGate(), qargs=[q[0], q[1], q[2]], cargs=[]) dag_drawer(dag) from qiskit.circuit.library import CHGate, U2Gate, CXGate mini_dag = DAGCircuit() p = QuantumRegister(2, "p") mini_dag.add_qreg(p) mini_dag.apply_operation_back(CHGate(), qargs=[p[1], p[0]]) mini_dag.apply_operation_back(U2Gate(0.1, 0.2), qargs=[p[1]]) # substitute the cx node with the above mini-dag cx_node = dag.op_nodes(op=CXGate).pop() dag.substitute_node_with_dag(node=cx_node, input_dag=mini_dag, wires=[p[0], p[1]]) dag_drawer(dag) from qiskit.converters import dag_to_circuit circuit = dag_to_circuit(dag) circuit.draw(output='mpl') from copy import copy from qiskit.transpiler.basepasses import TransformationPass from qiskit.transpiler import Layout from qiskit.circuit.library import SwapGate class BasicSwap(TransformationPass): """Maps (with minimum effort) a DAGCircuit onto a `coupling_map` adding swap gates.""" def __init__(self, coupling_map, initial_layout=None): """Maps a DAGCircuit onto a `coupling_map` using swap gates. Args: coupling_map (CouplingMap): Directed graph represented a coupling map. initial_layout (Layout): initial layout of qubits in mapping """ super().__init__() self.coupling_map = coupling_map self.initial_layout = initial_layout def run(self, dag): """Runs the BasicSwap pass on `dag`. Args: dag (DAGCircuit): DAG to map. Returns: DAGCircuit: A mapped DAG. Raises: TranspilerError: if the coupling map or the layout are not compatible with the DAG. """ new_dag = DAGCircuit() for qreg in dag.qregs.values(): new_dag.add_qreg(qreg) for creg in dag.cregs.values(): new_dag.add_creg(creg) if self.initial_layout is None: if self.property_set["layout"]: self.initial_layout = self.property_set["layout"] else: self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values()) if len(dag.qubits) != len(self.initial_layout): raise TranspilerError('The layout does not match the amount of qubits in the DAG') if len(self.coupling_map.physical_qubits) != len(self.initial_layout): raise TranspilerError( "Mappers require to have the layout to be the same size as the coupling map") canonical_register = dag.qregs['q'] trivial_layout = Layout.generate_trivial_layout(canonical_register) current_layout = trivial_layout.copy() for layer in dag.serial_layers(): subdag = layer['graph'] for gate in subdag.two_qubit_ops(): physical_q0 = current_layout[gate.qargs[0]] physical_q1 = current_layout[gate.qargs[1]] if self.coupling_map.distance(physical_q0, physical_q1) != 1: # Insert a new layer with the SWAP(s). swap_layer = DAGCircuit() swap_layer.add_qreg(canonical_register) path = self.coupling_map.shortest_undirected_path(physical_q0, physical_q1) for swap in range(len(path) - 2): connected_wire_1 = path[swap] connected_wire_2 = path[swap + 1] qubit_1 = current_layout[connected_wire_1] qubit_2 = current_layout[connected_wire_2] # create the swap operation swap_layer.apply_operation_back(SwapGate(), qargs=[qubit_1, qubit_2], cargs=[]) # layer insertion order = current_layout.reorder_bits(new_dag.qubits) new_dag.compose(swap_layer, qubits=order) # update current_layout for swap in range(len(path) - 2): current_layout.swap(path[swap], path[swap + 1]) order = current_layout.reorder_bits(new_dag.qubits) new_dag.compose(subdag, qubits=order) return new_dag q = QuantumRegister(7, 'q') in_circ = QuantumCircuit(q) in_circ.h(q[0]) in_circ.cx(q[0], q[4]) in_circ.cx(q[2], q[3]) in_circ.cx(q[6], q[1]) in_circ.cx(q[5], q[0]) in_circ.rz(0.1, q[2]) in_circ.cx(q[5], q[0]) from qiskit.transpiler import PassManager from qiskit.transpiler import CouplingMap from qiskit import BasicAer pm = PassManager() coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]] coupling_map = CouplingMap(couplinglist=coupling) pm.append([BasicSwap(coupling_map)]) out_circ = pm.run(in_circ) in_circ.draw(output='mpl') out_circ.draw(output='mpl') import logging logging.basicConfig(level='DEBUG') from qiskit.providers.fake_provider import FakeTenerife log_circ = QuantumCircuit(2, 2) log_circ.h(0) log_circ.h(1) log_circ.h(1) log_circ.x(1) log_circ.cx(0, 1) log_circ.measure([0,1], [0,1]) backend = FakeTenerife() transpile(log_circ, backend); logging.getLogger('qiskit.transpiler').setLevel('INFO') transpile(log_circ, backend); # Change log level back to DEBUG logging.getLogger('qiskit.transpiler').setLevel('DEBUG') # Transpile multiple circuits circuits = [log_circ, log_circ] transpile(circuits, backend); formatter = logging.Formatter('%(name)s - %(processName)-10s - %(levelname)s: %(message)s') handler = logging.getLogger().handlers[0] handler.setFormatter(formatter) transpile(circuits, backend); import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module # pylint: disable=attribute-defined-outside-init,unsubscriptable-object import os from qiskit import QuantumCircuit from qiskit.compiler import transpile class QUEKOTranspilerBench: params = ([0, 1, 2, 3], [None, "sabre"]) param_names = ["optimization level", "routing/layout method"] timeout = 600 # pylint: disable=unused-argument def setup(self, optimization_level, routing_method): self.rochester_coupling_map = [ [0, 5], [0, 1], [1, 2], [1, 0], [2, 3], [2, 1], [3, 4], [3, 2], [4, 6], [4, 3], [5, 9], [5, 0], [6, 13], [6, 4], [7, 16], [7, 8], [8, 9], [8, 7], [9, 10], [9, 8], [9, 5], [10, 11], [10, 9], [11, 17], [11, 12], [11, 10], [12, 13], [12, 11], [13, 14], [13, 12], [13, 6], [14, 15], [14, 13], [15, 18], [15, 14], [16, 19], [16, 7], [17, 23], [17, 11], [18, 27], [18, 15], [19, 20], [19, 16], [20, 21], [20, 19], [21, 28], [21, 22], [21, 20], [22, 23], [22, 21], [23, 24], [23, 22], [23, 17], [24, 25], [24, 23], [25, 29], [25, 26], [25, 24], [26, 27], [26, 25], [27, 26], [27, 18], [28, 32], [28, 21], [29, 36], [29, 25], [30, 39], [30, 31], [31, 32], [31, 30], [32, 33], [32, 31], [32, 28], [33, 34], [33, 32], [34, 40], [34, 35], [34, 33], [35, 36], [35, 34], [36, 37], [36, 35], [36, 29], [37, 38], [37, 36], [38, 41], [38, 37], [39, 42], [39, 30], [40, 46], [40, 34], [41, 50], [41, 38], [42, 43], [42, 39], [43, 44], [43, 42], [44, 51], [44, 45], [44, 43], [45, 46], [45, 44], [46, 47], [46, 45], [46, 40], [47, 48], [47, 46], [48, 52], [48, 49], [48, 47], [49, 50], [49, 48], [50, 49], [50, 41], [51, 44], [52, 48], ] self.tokyo_coupling_map = [ [0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [1, 6], [1, 7], [2, 6], [2, 7], [3, 8], [3, 9], [4, 8], [4, 9], [5, 6], [6, 7], [7, 8], [8, 9], [5, 10], [5, 11], [6, 10], [6, 11], [7, 12], [7, 13], [8, 12], [8, 13], [9, 14], [10, 11], [11, 12], [12, 13], [13, 14], [10, 15], [11, 16], [11, 17], [12, 16], [12, 17], [13, 18], [13, 19], [14, 18], [14, 19], [15, 16], [16, 17], [17, 18], [18, 19], ] self.sycamore_coupling_map = [ [0, 6], [1, 6], [1, 7], [2, 7], [2, 8], [3, 8], [3, 9], [4, 9], [4, 10], [5, 10], [5, 11], [6, 12], [6, 13], [7, 13], [7, 14], [8, 14], [8, 15], [9, 15], [9, 16], [10, 16], [10, 17], [11, 17], [12, 18], [13, 18], [13, 19], [14, 19], [14, 20], [15, 20], [15, 21], [16, 21], [16, 22], [17, 22], [17, 23], [18, 24], [18, 25], [19, 25], [19, 26], [20, 26], [20, 27], [21, 27], [21, 28], [22, 28], [22, 29], [23, 29], [24, 30], [25, 30], [25, 31], [26, 31], [26, 32], [27, 32], [27, 33], [28, 33], [28, 34], [29, 34], [29, 35], [30, 36], [30, 37], [31, 37], [31, 38], [32, 38], [32, 39], [33, 39], [33, 40], [34, 40], [34, 41], [35, 41], [36, 42], [37, 42], [37, 43], [38, 43], [38, 44], [39, 44], [39, 45], [40, 45], [40, 46], [41, 46], [41, 47], [42, 48], [42, 49], [43, 49], [43, 50], [44, 50], [44, 51], [45, 51], [45, 52], [46, 52], [46, 53], [47, 53], ] self.basis_gates = ["id", "rz", "sx", "x", "cx"] self.qasm_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "qasm")) self.bigd = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "20QBT_45CYC_.0D1_.1D2_3.qasm") ) self.bss = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "53QBT_100CYC_QSE_3.qasm") ) self.bntf = QuantumCircuit.from_qasm_file( os.path.join(self.qasm_path, "54QBT_25CYC_QSE_3.qasm") ) def track_depth_bntf_optimal_depth_25(self, optimization_level, routing_method): return transpile( self.bntf, coupling_map=self.sycamore_coupling_map, basis_gates=self.basis_gates, routing_method=routing_method, layout_method=routing_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def track_depth_bss_optimal_depth_100(self, optimization_level, routing_method): return transpile( self.bss, coupling_map=self.rochester_coupling_map, basis_gates=self.basis_gates, routing_method=routing_method, layout_method=routing_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def track_depth_bigd_optimal_depth_45(self, optimization_level, routing_method): return transpile( self.bigd, coupling_map=self.tokyo_coupling_map, basis_gates=self.basis_gates, routing_method=routing_method, layout_method=routing_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def time_transpile_bntf(self, optimization_level, routing_method): transpile( self.bntf, coupling_map=self.sycamore_coupling_map, basis_gates=self.basis_gates, routing_method=routing_method, layout_method=routing_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def time_transpile_bss(self, optimization_level, routing_method): transpile( self.bss, coupling_map=self.rochester_coupling_map, basis_gates=self.basis_gates, routing_method=routing_method, layout_method=routing_method, optimization_level=optimization_level, seed_transpiler=0, ).depth() def time_transpile_bigd(self, optimization_level, routing_method): transpile( self.bigd, coupling_map=self.tokyo_coupling_map, basis_gates=self.basis_gates, routing_method=routing_method, layout_method=routing_method, optimization_level=optimization_level, seed_transpiler=0, ).depth()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2023. # # 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 RemoveFinalReset pass""" import unittest from qiskit import QuantumRegister, QuantumCircuit from qiskit.passmanager.flow_controllers import DoWhileController from qiskit.transpiler import PassManager from qiskit.transpiler.passes import RemoveFinalReset, DAGFixedPoint from qiskit.converters import circuit_to_dag from test import QiskitTestCase # pylint: disable=wrong-import-order class TestRemoveFinalReset(QiskitTestCase): """Test remove-reset-in-zero-state optimizations.""" def test_optimize_single_reset(self): """Remove a single final reset qr0:--[H]--|0>-- ==> qr0:--[H]-- """ qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.h(0) circuit.reset(qr) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.h(0) pass_ = RemoveFinalReset() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_dont_optimize_non_final_reset(self): """Do not remove reset if not final instruction qr0:--|0>--[H]-- ==> qr0:--|0>--[H]-- """ qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.reset(qr) circuit.h(qr) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.reset(qr) expected.h(qr) pass_ = RemoveFinalReset() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) def test_optimize_single_reset_in_diff_qubits(self): """Remove a single final reset in different qubits qr0:--[H]--|0>-- qr0:--[H]-- ==> qr1:--[X]--|0>-- qr1:--[X]---- """ qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.h(0) circuit.x(1) circuit.reset(qr) dag = circuit_to_dag(circuit) expected = QuantumCircuit(qr) expected.h(0) expected.x(1) pass_ = RemoveFinalReset() after = pass_.run(dag) self.assertEqual(circuit_to_dag(expected), after) class TestRemoveFinalResetFixedPoint(QiskitTestCase): """Test RemoveFinalReset in a transpiler, using fixed point.""" def test_two_resets(self): """Remove two final resets qr0:--[H]-|0>-|0>-- ==> qr0:--[H]-- """ qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.reset(qr[0]) circuit.reset(qr[0]) expected = QuantumCircuit(qr) expected.h(qr[0]) pass_manager = PassManager() pass_manager.append( DoWhileController( [RemoveFinalReset(), DAGFixedPoint()], do_while=lambda property_set: not property_set["dag_fixed_point"], ) ) after = pass_manager.run(circuit) self.assertEqual(expected, after) if __name__ == "__main__": unittest.main()
https://github.com/hamburgerguy/Quantum-Algorithm-Implementations
hamburgerguy
"""Qiskit code for running Simon's algorithm on quantum hardware for 2 qubits and b = '11' """ # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, execute # import basic plot tools from qiskit.visualization import plot_histogram from qiskit_textbook.tools import simon_oracle #set b equal to '11' b = '11' #1) initialize qubits n = 2 simon_circuit_2 = QuantumCircuit(n*2, n) #2) Apply Hadamard gates before querying the oracle simon_circuit_2.h(range(n)) #3) Query oracle simon_circuit_2 += simon_oracle(b) #5) Apply Hadamard gates to the input register simon_circuit_2.h(range(n)) #3) and 6) Measure qubits simon_circuit_2.measure(range(n), range(n)) # Load saved IBMQ accounts and get the least busy backend device IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= n and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Execute and monitor the job from qiskit.tools.monitor import job_monitor shots = 1024 job = execute(simon_circuit_2, backend=backend, shots=shots, optimization_level=3) job_monitor(job, interval = 2) # Get results and plot counts device_counts = job.result().get_counts() plot_histogram(device_counts) #additionally, function for calculating dot product of results def bdotz(b, z): accum = 0 for i in range(len(b)): accum += int(b[i]) * int(z[i]) return (accum % 2) print('b = ' + b) for z in device_counts: print( '{}.{} = {} (mod 2) ({:.1f}%)'.format(b, z, bdotz(b,z), device_counts[z]*100/shots)) #the most significant results are those for which b dot z=0(mod 2). '''b = 11 11.00 = 0 (mod 2) (45.0%) 11.01 = 1 (mod 2) (6.2%) 11.10 = 1 (mod 2) (6.4%) 11.11 = 0 (mod 2) (42.4%)'''
https://github.com/1chooo/Quantum-Oracle
1chooo
from qiskit import QuantumCircuit,execute from qiskit.providers.aer import AerSimulator from qiskit.visualization import plot_histogram import math qc = QuantumCircuit(1,1) qc.initialize([math.sqrt(1/3), math.sqrt(2/3)],0) qc.x(0) qc.measure([0],[0]) print(qc) simulator=AerSimulator() job=execute(qc, backend=simulator, shots=1000) result=job.result() counts=result.get_counts(qc) print("Counts:",counts) plot_histogram(counts)
https://github.com/ShabaniLab/qiskit-hackaton-2019
ShabaniLab
import numpy as np from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister from ising_kitaev import initialize_chain, run_adiabatic_zeeman_change, rotate_to_measurement_basis, add_measurement from ising_kitaev import move_chain zeeman_ferro = 0.01 # value of on-site magnetic field for ferromagnetic domain zeeman_para = 10 # value of on-site magnetic field for paramagnetic domain initial_config = np.array([zeeman_ferro, zeeman_ferro, zeeman_ferro, zeeman_para, zeeman_para, zeeman_para]) final_config = np.array([zeeman_para, zeeman_para, zeeman_para, zeeman_ferro, zeeman_ferro, zeeman_ferro]) qreg = QuantumRegister(6) creg = ClassicalRegister(3) qcirc = QuantumCircuit(qreg, creg) initialize_chain(qcirc, qreg, initial_config, 'logical_zero') qcirc.draw() move_chain(qcirc, qreg, initial_config, final_config, 0, 0.25, 0.25, 2, 10, method = "both") qcirc.depth() rotate_to_measurement_basis(qcirc, qreg, [3, 4, 5]) add_measurement(qcirc, qreg, creg, [3, 4, 5]) from qiskit import Aer, execute backend = Aer.get_backend('qasm_simulator') job = execute(qcirc, backend, shots=2000) job.status() result = job.result() result.get_counts()
https://github.com/minnukota381/Quantum-Computing-Qiskit
minnukota381
from qiskit import * from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram # Create a quantum circuit with a single qubit # The default initial state of qubit will be |0> or [1,0] qc = QuantumCircuit(1) #Apply the Pauli X-gate on the qubit to make the input to y gate as |1> qc.x(0) #Apply the Pauli z-gate on the |1> qubit qc.z(0) #Draw the circuit # qc.draw() qc.draw('mpl') #Get the backend for the circuit (simulator or realtime system) backend = Aer.get_backend('statevector_simulator') #execute the circuit using the backend out = execute(qc,backend).result().get_statevector() #plot the result as a bloch sphere visualization plot_bloch_multivector(out) # visualize the output as an animation visualize_transition(qc) #execute the circuit and get the plain result out = execute(qc,backend).result() #getting the count of the result counts = out.get_counts() #plotting the histogram plot_histogram(counts)
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/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/suvoooo/Qubits-Qiskit
suvoooo
# !pip3 install qiskit # !pip3 install pylatexenc import qiskit as q import numpy as np import matplotlib.pyplot as plt qr = q.QuantumRegister(3, name="q") crz, crx = q.ClassicalRegister(1, name="crz"), q.ClassicalRegister(1, name="crx") teleport_circuit = q.QuantumCircuit(qr, crz, crx) teleport_circuit.draw() def epr_pair(qc, a, b): ''' qc is the quantum circuit a, b are two different qubits ''' qc.h(a) qc.cx(a, b) epr_pair(teleport_circuit, qr[1], qr[2]) # we leave 0th qubit (this will be used later as Alice's qubit the she wants to teleport) teleport_circuit.draw() # assume alice owns q_1 and bob owns q_2 # now we are ready to take the transformations that Alice applies # the qubit she wants to teleport is control bit and the epr member bit is the target bit def alice_steps(qc, psi, a): qc.cx(psi, a) qc.h(psi) teleport_circuit.barrier() # barrier ensures the epr pair creation part isn't hampered/optimized by whatever happens next alice_steps(teleport_circuit, qr[0], qr[1]) teleport_circuit.draw() # after this alice applies the measurement def alice_measure(qc, a, b): qc.barrier() qc.measure(a, 0) # measures the first qubit and put it into first classical register # measure goes as # Measure quantum bit into classical bit (tuples). # Args: # qubit (QuantumRegister|list|tuple): quantum register # cbit (ClassicalRegister|list|tuple): classical register qc.measure(b, 1) alice_measure(teleport_circuit, 0, 1) # 0th qubit is the one she wants to send and 1st qubit is one of the EPR pairs teleport_circuit.draw() def bob_transform(qc, bob_bit, crz, crx): qc.x(bob_bit).c_if(crx, 1) #c_if Add classical condition on register classical and value val c_if(self, classical, val) qc.z(bob_bit).c_if(crz, 1) # apply x and z gate only when if any of then are in the state '1' teleport_circuit.barrier() bob_transform(teleport_circuit, qr[2], crz, crx) teleport_circuit.draw() from qiskit.quantum_info import random_statevector psi = random_statevector(2, seed=10) print ('check the qubit Alice wants to teleport: ', psi, type(psi), type(psi.data)) q.visualization.plot_bloch_multivector(psi) from qiskit.extensions import Initialize init_qubit = Initialize(psi.data) init_qubit.label = "init" inverse_init_qubit = init_qubit.gates_to_uncompute() #initialization start from zero to psi, we reverse this initialization so it takes us back to zero qc_new_teleport = q.QuantumCircuit(qr, crz, crx) qc_new_teleport.append(init_qubit, [qr[0]]) qc_new_teleport.barrier() epr_pair(qc_new_teleport, qr[1], qr[2]) qc_new_teleport.barrier() alice_steps(qc_new_teleport, qr[0], qr[1]) alice_measure(qc_new_teleport, qr[0], qr[1]) bob_transform(qc_new_teleport, qr[2], crz, crx) qc_new_teleport.draw() from google.colab import drive drive.mount('/content/drive') path = '/content/drive/My Drive/' style = {'backgroundcolor': 'lavender', 'dpi':200, 'subfontsize':10} qc_new_teleport.draw(output='mpl',scale=0.8, style=style, filename=path+'teleport_1.png') statevec_sim = q.Aer.get_backend('statevector_simulator') qobj = q.assemble(qc_new_teleport) out_vector = statevec_sim.run(qobj).result().get_statevector() q.visualization.plot_bloch_multivector(out_vector,) qc_teleport_check = q.QuantumCircuit(qr, crz, crx) qc_teleport_check.append(init_qubit, [qr[0]]) qc_teleport_check.barrier() epr_pair(qc_teleport_check, qr[1], qr[2]) qc_teleport_check.barrier() alice_steps(qc_teleport_check, qr[0], qr[1]) alice_measure(qc_teleport_check, qr[0], qr[1]) bob_transform(qc_teleport_check, qr[2], crz, crx) qc_teleport_check.append(inverse_init_qubit, [qr[2]]) style = {'backgroundcolor': 'lavender'} qc_teleport_check.draw(output='mpl',scale=0.8, style=style) cr_result = q.ClassicalRegister(1) # we need another register to measure if we get 0 or not qc_teleport_check.add_register(cr_result) qc_teleport_check.measure(qr[2], 2) # measure the last qubit and put it into the last classical register qc_teleport_check.draw(output='mpl', scale=0.8, style={'backgroundcolor': 'lavender', 'subfontsize':12}) simulator = q.Aer.get_backend(name='qasm_simulator') results = q.execute(qc_teleport_check, backend=simulator,).result() q.visualization.plot_histogram(results.get_counts(qc_teleport_check))
https://github.com/unitaryfund/mitiq
unitaryfund
# Copyright (C) 2024 qBraid # # This file is part of the qBraid-SDK # # The qBraid-SDK is free software released under the GNU General Public License v3 # or later. You can redistribute and/or modify it under the terms of the GPL v3. # See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>. # # THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3. """ Unit tests for conversions between Cirq circuits and Qiskit circuits. """ import cirq import numpy as np import pytest import qiskit from cirq import Circuit, LineQubit, ops, testing from qiskit import QuantumCircuit from qiskit.circuit.random import random_circuit from qbraid.interface import circuits_allclose from qbraid.programs import load_program from qbraid.programs.exceptions import QasmError from qbraid.transpiler.conversions.cirq import cirq_to_qasm2 from qbraid.transpiler.conversions.qasm2 import qasm2_to_cirq from qbraid.transpiler.conversions.qasm3 import qasm3_to_qiskit from qbraid.transpiler.conversions.qiskit import qiskit_to_qasm2, qiskit_to_qasm3 from qbraid.transpiler.converter import transpile from qbraid.transpiler.exceptions import CircuitConversionError from ..cirq_utils import _equal def test_bell_state_to_from_circuits(): """Tests cirq.Circuit --> qiskit.QuantumCircuit --> cirq.Circuit with a Bell state circuit. """ qreg = cirq.LineQubit.range(2) cirq_circuit = cirq.Circuit([cirq.ops.H.on(qreg[0]), cirq.ops.CNOT.on(qreg[0], qreg[1])]) qiskit_circuit = transpile(cirq_circuit, "qiskit") # Qiskit from Cirq circuit_cirq = transpile(qiskit_circuit, "cirq") # Cirq from Qiskit assert np.allclose(cirq_circuit.unitary(), circuit_cirq.unitary()) def test_bell_state_to_qiskit(): """Tests cirq.Circuit --> qiskit.QuantumCircuit --> cirq.Circuit with a Bell state circuit.""" qreg = LineQubit.range(2) cirq_circuit = Circuit([ops.H.on(qreg[0]), ops.CNOT.on(qreg[0], qreg[1])]) qiskit_circuit = transpile(cirq_circuit, "qiskit") assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True) @pytest.mark.parametrize("num_qubits", [1, 2, 3, 4, 5]) def test_random_circuit_to_qiskit(num_qubits): """Tests converting random Cirq circuits to Qiskit circuits.""" for _ in range(10): cirq_circuit = testing.random_circuit( qubits=num_qubits, n_moments=np.random.randint(1, 6), op_density=1, random_state=np.random.randint(1, 10), ) qiskit_circuit = transpile(cirq_circuit, "qiskit") assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True) def test_bell_state_to_from_qasm(): """Tests cirq.Circuit --> QASM string --> cirq.Circuit with a Bell state circuit. """ qreg = cirq.LineQubit.range(2) cirq_circuit = cirq.Circuit([cirq.ops.H.on(qreg[0]), cirq.ops.CNOT.on(qreg[0], qreg[1])]) qasm = cirq_to_qasm2(cirq_circuit) # Qasm from Cirq circuit_cirq = qasm2_to_cirq(qasm) assert np.allclose(cirq_circuit.unitary(), circuit_cirq.unitary()) def test_random_circuit_to_from_circuits(): """Tests cirq.Circuit --> qiskit.QuantumCircuit --> cirq.Circuit with a random two-qubit circuit. """ cirq_circuit = cirq.testing.random_circuit( qubits=2, n_moments=10, op_density=0.99, random_state=1 ) qiskit_circuit = transpile(cirq_circuit, "qiskit") circuit_cirq = transpile(qiskit_circuit, "cirq") assert np.allclose(cirq_circuit.unitary(), circuit_cirq.unitary()) def test_random_circuit_to_from_qasm(): """Tests cirq.Circuit --> QASM string --> cirq.Circuit with a random one-qubit circuit. """ circuit_0 = cirq.testing.random_circuit(qubits=2, n_moments=10, op_density=0.99, random_state=2) qasm = cirq_to_qasm2(circuit_0) circuit_1 = qasm2_to_cirq(qasm) u_0 = circuit_0.unitary() u_1 = circuit_1.unitary() assert cirq.equal_up_to_global_phase(u_0, u_1) @pytest.mark.parametrize("as_qasm", (True, False)) def test_convert_with_barrier(as_qasm): """Tests converting a Qiskit circuit with a barrier to a Cirq circuit.""" n = 5 qiskit_circuit = qiskit.QuantumCircuit(qiskit.QuantumRegister(n)) qiskit_circuit.barrier() if as_qasm: cirq_circuit = qasm2_to_cirq(qiskit_to_qasm2(qiskit_circuit)) else: cirq_circuit = transpile(qiskit_circuit, "cirq") assert _equal(cirq_circuit, cirq.Circuit()) @pytest.mark.parametrize("as_qasm", (True, False)) def test_convert_with_multiple_barriers(as_qasm): """Tests converting a Qiskit circuit with barriers to a Cirq circuit.""" n = 1 num_ops = 10 qreg = qiskit.QuantumRegister(n) qiskit_circuit = qiskit.QuantumCircuit(qreg) for _ in range(num_ops): qiskit_circuit.h(qreg) qiskit_circuit.barrier() if as_qasm: cirq_circuit = qasm2_to_cirq(qiskit_to_qasm2(qiskit_circuit)) else: cirq_circuit = transpile(qiskit_circuit, "cirq") qbit = cirq.LineQubit(0) correct = cirq.Circuit(cirq.ops.H.on(qbit) for _ in range(num_ops)) assert _equal(cirq_circuit, correct) assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True) def test_bell_state_from_qiskit(): """Tests qiskit.QuantumCircuit --> cirq.Circuit with a Bell state circuit. """ qiskit_circuit = QuantumCircuit(2) qiskit_circuit.h(0) qiskit_circuit.cx(0, 1) cirq_circuit = transpile(qiskit_circuit, "cirq") assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True) def test_common_gates_from_qiskit(): """Tests converting standard gates from Qiskit to Cirq.""" qiskit_circuit = QuantumCircuit(4) qiskit_circuit.h([0, 1, 2, 3]) qiskit_circuit.x([0, 1]) qiskit_circuit.y(2) qiskit_circuit.z(3) qiskit_circuit.s(0) qiskit_circuit.sdg(1) qiskit_circuit.t(2) qiskit_circuit.tdg(3) qiskit_circuit.rx(np.pi / 4, 0) qiskit_circuit.ry(np.pi / 2, 1) qiskit_circuit.rz(3 * np.pi / 4, 2) qiskit_circuit.p(np.pi / 8, 3) qiskit_circuit.sx(0) qiskit_circuit.sxdg(1) qiskit_circuit.iswap(2, 3) qiskit_circuit.swap([0, 1], [2, 3]) qiskit_circuit.cx(0, 1) qiskit_circuit.cp(np.pi / 4, 2, 3) cirq_circuit = transpile(qiskit_circuit, "cirq") assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True) @pytest.mark.parametrize("qubits", ([0, 1], [1, 0])) def test_crz_gate_from_qiskit(qubits): """Tests converting controlled Rz gate from Qiskit to Cirq.""" qiskit_circuit = QuantumCircuit(2) qiskit_circuit.crz(np.pi / 4, *qubits) cirq_circuit = transpile(qiskit_circuit, "cirq", require_native=True) assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True) @pytest.mark.parametrize("qubits", ([0, 1], [1, 0])) @pytest.mark.parametrize("theta", (0, 2 * np.pi, np.pi / 2, np.pi / 4)) def test_rzz_gate_from_qiskit(qubits, theta): """Tests converting Rzz gate from Qiskit to Cirq.""" qiskit_circuit = QuantumCircuit(2) qiskit_circuit.rzz(theta, *qubits) cirq_circuit = transpile(qiskit_circuit, "cirq") assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True) def test_iswap_gate_from_qiskit(): """Tests converting iSwap gate from Qiskit to Cirq.""" qiskit_circuit = QuantumCircuit(2) qiskit_circuit.h([0, 1]) qiskit_circuit.iswap(0, 1) cirq_circuit = transpile(qiskit_circuit, "cirq") assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True) def test_qiskit_roundtrip(): """Test converting qiskit gates that previously failed qiskit roundtrip test.""" qiskit_circuit = QuantumCircuit(3) qiskit_circuit.ccz(0, 1, 2) qiskit_circuit.ecr(1, 2) qiskit_circuit.cs(2, 0) cirq_circuit = transpile(qiskit_circuit, "cirq", require_native=True) assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=False) def test_qiskit_roundtrip_noncontig(): """Test converting gates that previously failed qiskit roundtrip test with non-contiguous qubits.""" qiskit_circuit = QuantumCircuit(4) qiskit_circuit.ccz(0, 1, 2) qiskit_circuit.ecr(1, 2) qiskit_circuit.cs(2, 0) cirq_circuit = transpile(qiskit_circuit, "cirq", require_native=True) qprogram = load_program(cirq_circuit) qprogram.remove_idle_qubits() qiskit_contig = qprogram.program assert circuits_allclose(qiskit_contig, cirq_circuit, strict_gphase=False) def test_100_random_qiskit(): """Test converting 100 random qiskit circuits to cirq.""" for _ in range(100): qiskit_circuit = random_circuit(4, 1) cirq_circuit = transpile(qiskit_circuit, "cirq", require_native=True) assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=False) def test_qiskit_to_from_qasm3(): """Test converting qiskit circuit to/from OpenQASM 3.0 string""" circuit_in = QuantumCircuit(2) circuit_in.h(0) circuit_in.cx(0, 1) qasm3_str = qiskit_to_qasm3(circuit_in) circuit_out = qasm3_to_qiskit(qasm3_str) assert circuits_allclose(circuit_in, circuit_out, strict_gphase=True) def test_raise_circuit_conversion_error(): """Tests raising error for unsupported gates.""" with pytest.raises(CircuitConversionError): probs = np.random.uniform(low=0, high=0.5) cirq_circuit = Circuit(ops.PhaseDampingChannel(probs).on(*LineQubit.range(1))) transpile(cirq_circuit, "qiskit") def test_raise_qasm_error(): """Test raising error for unsupported gates.""" with pytest.raises(QasmError): qiskit_circuit = QuantumCircuit(1) qiskit_circuit.delay(300, 0) qasm2 = qiskit_to_qasm2(qiskit_circuit) _ = qasm2_to_cirq(qasm2)
https://github.com/mickahell/quantum_pokemon-fight
mickahell
%pip install qiskit %pip install qiskit[visualization] %pip install numpy %pip install matplotlib import math from random import * from IPython.display import Image, display, YouTubeVideo import numpy as np import qiskit from qiskit import Aer, QuantumCircuit, execute, IBMQ, QuantumRegister, ClassicalRegister from qiskit.visualization import plot_histogram, plot_bloch_multivector qiskit.__qiskit_version__ # Initialize Qasm simulator backend qasm = Aer.get_backend('qasm_simulator') # Initialize Real Quantum computer # If you run qiskit on a real computer for the first time, you will need to create an account on https://quantum-computing.ibm.com/login # and run the following line with you token. #IBMQ.save_account('MY_API_TOKEN') IBMQ.load_account() provider = IBMQ.get_provider('ibm-q') quantum_computer = provider.get_backend('ibmq_16_melbourne') # Here we will use the local simulator --> Aer backend_sim = qasm # Choose your backend : <quantum_computer> or <qasm> YouTubeVideo('C19O5xm51dk') Image("images_jupyter/structure.png", width="700") attack = 0.7 # Accuracy of the attack, most of the attacks are of precision 100%, 90% or 70% crit = 0.0417 # Critical burn = 0.1 poison = 0.3 para = 0.3 freeze = 0.1 speedtie = 0.5 qc = QuantumCircuit(1, 1) qc.rx(math.pi * attack, 0) # The gate RX is like a NOT gate which allows us to define the angle theta and apply rotation qc.measure(0, 0) qc.draw() job = execute(qc, backend_sim, shots=1, memory=True) result_job = job.result().get_memory() to_return = int(result_job[0], 2) if to_return == 1: print("Result : {}, the attack succeeded!".format(to_return)) else: print("Result : {}, the attack missed the target!".format(to_return)) Image("images_jupyter/types_graph.png", width="500") def diffuser(nqubits): qc = QuantumCircuit(nqubits) for qubit in range(nqubits): qc.h(qubit) for qubit in range(nqubits): qc.x(qubit) qc.h(nqubits - 1) qc.mct(list(range(nqubits - 1)), nqubits - 1) qc.h(nqubits - 1) for qubit in range(nqubits): qc.x(qubit) for qubit in range(nqubits): qc.h(qubit) U_s = qc.to_gate() U_s.name = "$Diff$" return U_s algo = QuantumRegister(3, 'algo') oracle = QuantumRegister(1, 'oracle') c = ClassicalRegister(3, 'measurement') qc = QuantumCircuit(algo, oracle, c) qc.append(diffuser(3), [0, 1, 2]) qc.draw() algo = QuantumRegister(3, 'algo') oracle = QuantumRegister(1, 'oracle') c = ClassicalRegister(3, 'measurement') qc = QuantumCircuit(algo, oracle, c) # Init qc.h(algo) qc.x(oracle) qc.h(oracle) qc.barrier() # Algorithm qc.mcx(algo, oracle) qc.barrier() # Diffuser qc.append(diffuser(3), [0, 1, 2]) # Measure of the ouputs qc.barrier() qc.measure(algo, c) qc.draw() job = execute(qc, backend_sim, shots=512) result_job = job.result() plot_histogram(result_job.get_counts()) # We have our Blastoise (Tortank in French) with 4 attacks : hydroblast, earthquake, ice beam, giga-impact # We want to map all our attacks to their respective type(s) like: # [hydroblast : water, earthquake : ground , ice beam : ice , giga-impact : normal] # Init register qram_q = QuantumRegister(2, 'qram') # We have 4 elements to map to 2 qubits are enough normal_q = QuantumRegister(1, 'normal') fire_q = QuantumRegister(1, 'fire') grass_q = QuantumRegister(1, 'grass') ground_q = QuantumRegister(1, 'ground') fly_q = QuantumRegister(1, 'fly') water_q = QuantumRegister(1, 'water') elec_q = QuantumRegister(1, 'electric') ice_q = QuantumRegister(1, 'ice') bug_q = QuantumRegister(1, 'bug') steel_q = QuantumRegister(1, 'steel') qc_init = QuantumCircuit(qram_q) # Init qubits qc_init.h(qram_q) # Init our inputs to superposition #qc.barrier() qc_qram = QuantumCircuit(qram_q, normal_q, fire_q, grass_q, ground_q, fly_q, water_q, elec_q, ice_q, bug_q, steel_q, c) # Mapping attacks ## First attack is going to be on the address 00, hydroblast qc_qram.x(qram_q) qc_qram.ccx(qram_q[0], qram_q[1], water_q) qc_qram.x(qram_q) qc_qram.barrier() ## Second attack -> 01, earthquake qc_qram.x(qram_q[0]) qc_qram.ccx(qram_q[0], qram_q[1], ground_q) qc_qram.x(qram_q[0]) qc_qram.barrier() ## Third attack -> 10, ice beam qc_qram.x(qram_q[1]) qc_qram.ccx(qram_q[0], qram_q[1], ice_q) qc_qram.x(qram_q[1]) qc_qram.barrier() ## Fourth attack -> 11, giga impact qc_qram.ccx(qram_q[0], qram_q[1], normal_q) qc_qram.barrier() qc_initQram = qc_init + qc_qram qc_initQram.draw() c = ClassicalRegister(8, 'measure') qram_measure = QuantumCircuit(c) qc = qc_initQram + qram_measure qc.measure(range(8), range(8)) qc = qc.reverse_bits() job = execute(qc, backend_sim, shots=512) result_job = job.result() plot_histogram(result_job.get_counts()) # Init type qubits fire_q = QuantumRegister(1, 'fire') grass_q = QuantumRegister(1, 'grass') ground_q = QuantumRegister(1, 'ground') fly_q = QuantumRegister(1, 'fly') water_q = QuantumRegister(1, 'water') elec_q = QuantumRegister(1, 'electrick') ice_q = QuantumRegister(1, 'ice') bug_q = QuantumRegister(1, 'bug') steel_q = QuantumRegister(1, 'steel') qc_types = QuantumCircuit(fire_q, grass_q, ground_q, fly_q, water_q, elec_q, ice_q, bug_q, steel_q) # Init charizard fire_weak = [water_q, ground_q] fly_weak = [elec_q, ice_q] fire_resist = [fire_q, bug_q, grass_q, steel_q, ice_q] fly_resist = [grass_q, bug_q] fire_immune = ["None"] fly_immune = [ground_q] # Charamenter type map weakFire_q = QuantumRegister(1, 'weak_fire') weakFly_q = QuantumRegister(1, 'weak_fly') checkWeak_q = QuantumRegister(1, 'check_weak') resistFire_q = QuantumRegister(1, 'resist_fire') resistFly_q = QuantumRegister(1, 'resist_fly') immuneFire_q = QuantumRegister(1, 'immunity_fire') immuneFly_q = QuantumRegister(1, 'immunity_fly') qc_charizard = QuantumCircuit(weakFire_q, weakFly_q, checkWeak_q, resistFire_q, resistFly_q, immuneFire_q, immuneFly_q) qc_defenderMapping = qc_types + qc_charizard # Apply gates ## Weakness if fire_weak[0] != "None": for i in fire_weak: qc_defenderMapping.cx(i, weakFire_q) if fly_weak[0] != "None": for i in fly_weak: qc_defenderMapping.cx(i, weakFly_q) qc_defenderMapping.barrier() ## Resistances if fire_resist[0] != "None": for i in fire_resist: qc_defenderMapping.cx(i, resistFire_q) if fly_resist[0] != "None": for i in fly_resist: qc_defenderMapping.cx(i, resistFly_q) qc_defenderMapping.barrier() ## Immunity if fire_immune[0] != "None": for i in fire_immune: qc_defenderMapping.cx(i, immuneFire_q) if fly_immune[0] != "None": for i in fly_immune: qc_defenderMapping.cx(i, immuneFly_q) # Check of the weakness def or_weak(qc): qc.barrier() qc.cx(weakFire_q[0], checkWeak_q[0]) qc.cx(weakFly_q[0], checkWeak_q[0]) qc.ccx(weakFly_q[0], weakFire_q[0], checkWeak_q[0]) qc.barrier() qc_orweak = qc_types + qc_charizard or_weak(qc_orweak) (qc_defenderMapping + qc_orweak).draw() qc_algo = qc_init + qc_qram + qc_defenderMapping + qc_orweak qc_algo.draw() oracle_q = QuantumRegister(1, 'oracle') qc_oracle = QuantumCircuit(oracle_q) qc_oracle.x(oracle_q) qc_oracle.h(oracle_q) # Glueing everything together qc_finale = qc_oracle + qc_init + qc_qram + qc_defenderMapping + qc_orweak qc_finale.x([resistFire_q[0], resistFly_q[0], immuneFire_q[0], immuneFly_q[0]]) qc_finale.mcx([checkWeak_q, resistFire_q, resistFly_q, immuneFire_q, immuneFly_q], oracle_q) qc_finale.x([resistFire_q[0], resistFly_q[0], immuneFire_q[0], immuneFly_q[0]]) qc_finale.barrier() qc_finale.draw() def diffuser(nqubits): qc = QuantumCircuit(nqubits) for qubit in range(nqubits): qc.h(qubit) for qubit in range(nqubits): qc.x(qubit) qc.h(nqubits - 1) qc.mct(list(range(nqubits - 1)), nqubits - 1) qc.h(nqubits - 1) for qubit in range(nqubits): qc.x(qubit) for qubit in range(nqubits): qc.h(qubit) U_s = qc.to_gate() U_s.name = "$U_s$" return qc qc_finale = qc_oracle + qc_init for i in range(1): qc_finale = qc_finale + qc_qram + qc_defenderMapping + qc_orweak qc_finale.x([resistFire_q[0], resistFly_q[0], immuneFire_q[0], immuneFly_q[0]]) qc_finale.mcx([checkWeak_q, resistFire_q, resistFly_q, immuneFire_q, immuneFly_q], oracle_q) qc_finale.x([resistFire_q[0], resistFly_q[0], immuneFire_q[0], immuneFly_q[0]]) qc_finale = qc_finale + qc_orweak + qc_defenderMapping + qc_qram qc_finale.append(diffuser(2), [1, 2]) qc_finale.barrier() qc_finale.measure(qram_q, range(2)) qc_finale.draw() qc = qc_finale.reverse_bits() job = execute(qc, backend_sim, shots=512) result_job = job.result() plot_histogram(result_job.get_counts()) oracle_q = QuantumRegister(1, 'oracle') qram_q = QuantumRegister(2, 'qram') fire_q = QuantumRegister(1, 'fire') grass_q = QuantumRegister(1, 'grass') ground_q = QuantumRegister(1, 'ground') fly_q = QuantumRegister(1, 'fly') water_q = QuantumRegister(1, 'water') elec_q = QuantumRegister(1, 'electrick') ice_q = QuantumRegister(1, 'ice') bug_q = QuantumRegister(1, 'bug') steel_q = QuantumRegister(1, 'steel') normal_q = QuantumRegister(1, 'normal') resistFire_q = QuantumRegister(1, 'resist_fire') resistFly_q = QuantumRegister(1, 'resist_fly') immuneFire_q = QuantumRegister(1, 'immunity_fire') immuneFly_q = QuantumRegister(1, 'immunity_fly') weakFire_q = QuantumRegister(1, 'weak_fire') weakFly_q = QuantumRegister(1, 'weak_fly') checkWeak_q = QuantumRegister(1, 'check_weak') c = ClassicalRegister(2, 'measure') qc = QuantumCircuit(oracle_q, qram_q, fire_q, grass_q, ground_q, fly_q, water_q, elec_q, ice_q, bug_q, steel_q, normal_q, resistFire_q, resistFly_q, immuneFire_q, immuneFly_q, weakFire_q, weakFly_q, checkWeak_q, c) def qram(nqubits): qc = QuantumCircuit(nqubits) U_s = qc.to_gate() U_s.name = "$QRAM$" return U_s def defenderMapping(nqubits): qc = QuantumCircuit(nqubits) U_s = qc.to_gate() U_s.name = "$mappingChara$" return U_s def orweak(nqubits): qc = QuantumCircuit(nqubits) U_s = qc.to_gate() U_s.name = "$weakCheck$" return U_s def diffuser(nqubits): qc = QuantumCircuit(nqubits) U_s = qc.to_gate() U_s.name = "$diffuser$" return U_s # Init qc.x(oracle_q) qc.h(oracle_q) qc.h(qram_q) qc.barrier() for i in range(1): # Qram qc.append(qram(12), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) # Algo qc.append(defenderMapping(16), [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]) qc.append(orweak(3), [17, 18, 19]) # Oracle qc.barrier() qc.x([resistFire_q[0], resistFly_q[0], immuneFire_q[0], immuneFly_q[0]]) qc.mcx([checkWeak_q, resistFire_q, resistFly_q, immuneFire_q, immuneFly_q], oracle_q) qc.x([resistFire_q[0], resistFly_q[0], immuneFire_q[0], immuneFly_q[0]]) qc.barrier() # Uncompute qc.append(orweak(3), [17, 18, 19]) qc.append(defenderMapping(16), [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]) qc.append(qram(12), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) # Diffuser qc.append(diffuser(2), [1, 2]) qc.barrier() qc.measure(qram_q, range(2)) qc.draw()
https://github.com/hkhetawat/QArithmetic
hkhetawat
# Import the Qiskit SDK from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute, Aer from QArithmetic import add_ripple # Input N N = 4 a = QuantumRegister(N) b = QuantumRegister(N+1) ca = ClassicalRegister(N) cb = ClassicalRegister(N+1) qc = QuantumCircuit(a, b, ca, cb) # Input Superposition # a = 1110 qc.x(a[1]) qc.x(a[2]) qc.x(a[3]) # b = 01011 qc.x(b[0]) qc.x(b[1]) qc.x(b[3]) add_ripple(qc, a, b, N) qc.measure(a, ca) qc.measure(b, cb) 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/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt try: import cplex from cplex.exceptions import CplexError except: print("Warning: Cplex not found.") import math from qiskit.utils import algorithm_globals from qiskit.algorithms.minimum_eigensolvers import SamplingVQE from qiskit.algorithms.optimizers import SPSA from qiskit.circuit.library import RealAmplitudes from qiskit.primitives import Sampler # Initialize the problem by defining the parameters n = 3 # number of nodes + depot (n+1) K = 2 # number of vehicles # Get the data class Initializer: def __init__(self, n): self.n = n def generate_instance(self): n = self.n # np.random.seed(33) np.random.seed(1543) xc = (np.random.rand(n) - 0.5) * 10 yc = (np.random.rand(n) - 0.5) * 10 instance = np.zeros([n, n]) for ii in range(0, n): for jj in range(ii + 1, n): instance[ii, jj] = (xc[ii] - xc[jj]) ** 2 + (yc[ii] - yc[jj]) ** 2 instance[jj, ii] = instance[ii, jj] return xc, yc, instance # Initialize the problem by randomly generating the instance initializer = Initializer(n) xc, yc, instance = initializer.generate_instance() class ClassicalOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n # number of nodes self.K = K # number of vehicles def compute_allowed_combinations(self): f = math.factorial return f(self.n) / f(self.K) / f(self.n - self.K) def cplex_solution(self): # refactoring instance = self.instance n = self.n K = self.K my_obj = list(instance.reshape(1, n**2)[0]) + [0.0 for x in range(0, n - 1)] my_ub = [1 for x in range(0, n**2 + n - 1)] my_lb = [0 for x in range(0, n**2)] + [0.1 for x in range(0, n - 1)] my_ctype = "".join(["I" for x in range(0, n**2)]) + "".join( ["C" for x in range(0, n - 1)] ) my_rhs = ( 2 * ([K] + [1 for x in range(0, n - 1)]) + [1 - 0.1 for x in range(0, (n - 1) ** 2 - (n - 1))] + [0 for x in range(0, n)] ) my_sense = ( "".join(["E" for x in range(0, 2 * n)]) + "".join(["L" for x in range(0, (n - 1) ** 2 - (n - 1))]) + "".join(["E" for x in range(0, n)]) ) 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 = [] 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 = [x for x in range(0 + ii, n**2, n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) # Sub-tour elimination constraints: for ii in range(0, n): for jj in range(0, n): if (ii != jj) and (ii * jj > 0): col = [ii + (jj * n), n**2 + ii - 1, n**2 + jj - 1] coef = [1, 1, -1] rows.append([col, coef]) for ii in range(0, n): col = [(ii) * (n + 1)] coef = [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(instance, n, K) # Print number of feasible solutions print("Number of feasible solutions = " + str(classical_optimizer.compute_allowed_combinations())) # Solve the problem in a classical fashion via CPLEX x = None z = None try: x, classical_cost = classical_optimizer.cplex_solution() # Put the solution in the z variable z = [x[ii] for ii in range(n**2) if ii // n != ii % n] # Print the solution print(z) except: print("CPLEX may be missing.") # 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.15, yc[i]), size=16, color="r") plt.plot(xc[0], yc[0], "r*", ms=20) plt.grid() for ii in range(0, n**2): if x[ii] > 0: ix = ii // n iy = ii % n plt.arrow( xc[ix], yc[ix], xc[iy] - xc[ix], yc[iy] - yc[ix], length_includes_head=True, head_width=0.25, ) plt.title(title_str + " cost = " + str(int(C * 100) / 100.0)) plt.show() if x is not None: visualize_solution(xc, yc, x, classical_cost, n, K, "Classical") from qiskit_optimization import QuadraticProgram from qiskit_optimization.algorithms import MinimumEigenOptimizer class QuantumOptimizer: def __init__(self, instance, n, K): self.instance = instance self.n = n self.K = K def binary_representation(self, x_sol=0): instance = self.instance n = self.n K = self.K A = np.max(instance) * 100 # A parameter of cost function # Determine the weights w instance_vec = instance.reshape(n**2) w_list = [instance_vec[x] for x in range(n**2) if instance_vec[x] > 0] w = np.zeros(n * (n - 1)) for ii in range(len(w_list)): w[ii] = w_list[ii] # Some variables I will use Id_n = np.eye(n) Im_n_1 = np.ones([n - 1, n - 1]) Iv_n_1 = np.ones(n) Iv_n_1[0] = 0 Iv_n = np.ones(n - 1) neg_Iv_n_1 = np.ones(n) - Iv_n_1 v = np.zeros([n, n * (n - 1)]) for ii in range(n): count = ii - 1 for jj in range(n * (n - 1)): if jj // (n - 1) == ii: count = ii if jj // (n - 1) != ii and jj % (n - 1) == count: v[ii][jj] = 1.0 vn = np.sum(v[1:], axis=0) # Q defines the interactions between variables Q = A * (np.kron(Id_n, Im_n_1) + np.dot(v.T, v)) # g defines the contribution from the individual variables g = ( w - 2 * A * (np.kron(Iv_n_1, Iv_n) + vn.T) - 2 * A * K * (np.kron(neg_Iv_n_1, Iv_n) + v[0].T) ) # c is the constant offset c = 2 * A * (n - 1) + 2 * A * (K**2) try: max(x_sol) # Evaluates the cost distance from a binary representation of a path fun = ( lambda x: np.dot(np.around(x), np.dot(Q, np.around(x))) + np.dot(g, np.around(x)) + c ) cost = fun(x_sol) except: cost = 0 return Q, g, c, cost def construct_problem(self, Q, g, c) -> QuadraticProgram: qp = QuadraticProgram() for i in range(n * (n - 1)): qp.binary_var(str(i)) qp.objective.quadratic = Q qp.objective.linear = g qp.objective.constant = c return qp def solve_problem(self, qp): algorithm_globals.random_seed = 10598 vqe = SamplingVQE(sampler=Sampler(), optimizer=SPSA(), ansatz=RealAmplitudes()) optimizer = MinimumEigenOptimizer(min_eigen_solver=vqe) result = optimizer.solve(qp) # compute cost of the obtained result _, _, _, level = self.binary_representation(x_sol=result.x) return result.x, level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(instance, n, K) # Check if the binary representation is correct try: if z is not None: Q, g, c, binary_cost = quantum_optimizer.binary_representation(x_sol=z) print("Binary cost:", binary_cost, "classical cost:", classical_cost) if np.abs(binary_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the binary formulation") else: print("Could not verify the correctness, due to CPLEX solution being unavailable.") Q, g, c, binary_cost = quantum_optimizer.binary_representation() print("Binary cost:", binary_cost) except NameError as e: print("Warning: Please run the cells above first.") print(e) qp = quantum_optimizer.construct_problem(Q, g, c) quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp) print(quantum_solution, quantum_cost) # Put the solution in a way that is compatible with the classical variables x_quantum = np.zeros(n**2) kk = 0 for ii in range(n**2): if ii // n != ii % n: x_quantum[ii] = quantum_solution[kk] kk += 1 # visualize the solution visualize_solution(xc, yc, x_quantum, quantum_cost, n, K, "Quantum") # and visualize the classical for comparison if x is not None: visualize_solution(xc, yc, x, classical_cost, n, K, "Classical") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
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) filename = "job_ids_ibmq_jakarta_100step_20220413_030821_.pkl" # change here with open(filename, "rb") as f: job_ids_dict = pickle.load(f) job_ids = job_ids_dict["job_ids"] cal_job_id = job_ids_dict["cal_job_id"] retrieved_jobs = [] for job_id in job_ids: retrieved_jobs.append(backend.retrieve_job(job_id)) retrieved_cal_job = backend.retrieve_job(cal_job_id) 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))) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts 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("./") 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) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") 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(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"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs) print("created zne_qcs (length:", len(zne_qcs), ")") 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-utokyo', group='internal', project='hirashi-jst') provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") # QREM shots = 1 << 13 qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) shots = 1 << 13 reps = 8 # unused jobs = [] for _ in range(reps): job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) jobs.append(job) dt_now = datetime.datetime.now() import pickle with open("jobs_jakarta_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("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "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_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f: pickle.dump(backend.properties(), f) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) # Compute tomography fidelities for each repetition raw_fids = [] for result in results: fid = state_tomo(result, st_qcs) raw_fids.append(fid) # print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) # Compute tomography fidelities for each repetition fids = [] for result in mit_results: fid = state_tomo(result, st_qcs) fids.append(fid) # print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids))) plt.clf() plt.style.use('ggplot') plt.figure(dpi=200) plt.title("state fidelity from Trotter step 1 to "+str(trotter_steps)) plt.plot(trotter_steps, raw_fids, label="raw fidelity") plt.plot(trotter_steps, fids, label="fidelity after QREM") plt.xlabel("number of trotter steps") plt.ylabel("fidelity") plt.grid(linestyle='dotted') for step, fid in zip(trotter_steps, raw_fids): print(step, fid) for step, fid in zip(trotter_steps, fids): print(step, fid)
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)) depths = [] for _ in range(100): depths.append( transpile( ghz, backend, layout_method='trivial' # Fixed layout mapped in circuit order ).depth() ) plt.figure(figsize=(8, 6)) plt.hist(depths, align='left', color='#AC557C') plt.xlabel('Depth', fontsize=14) plt.ylabel('Counts', fontsize=14);
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.pulse_v2 import draw, IQXDebugging from qiskit.providers.fake_provider import FakeBoeblingen qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.measure_all() qc = transpile(qc, FakeBoeblingen(), layout_method='trivial') sched = schedule(qc, FakeBoeblingen()) draw(sched, style=IQXDebugging(), backend=FakeBoeblingen())
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2023 # # 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-module-docstring,missing-class-docstring,missing-function-docstring import itertools import math import sys import ddt import qiskit.qasm2 from qiskit.test import QiskitTestCase @ddt.ddt class TestSimple(QiskitTestCase): def test_unary_constants(self): program = "qreg q[1]; U(-(0.5 + 0.5), +(+1 - 2), -+-+2) q[0];" parsed = qiskit.qasm2.loads(program) expected = [-1.0, -1.0, 2.0] self.assertEqual(list(parsed.data[0].operation.params), expected) def test_unary_symbolic(self): program = """ gate u(a, b, c) q { U(-(a + a), +(+b - c), -+-+c) q; } qreg q[1]; u(0.5, 1.0, 2.0) q[0]; """ parsed = qiskit.qasm2.loads(program) expected = [-1.0, -1.0, 2.0] actual = [float(x) for x in parsed.data[0].operation.definition.data[0].operation.params] self.assertEqual(list(actual), expected) @ddt.data( ("+", lambda a, b: a + b), ("-", lambda a, b: a - b), ("*", lambda a, b: a * b), ("/", lambda a, b: a / b), ("^", lambda a, b: a**b), ) @ddt.unpack def test_binary_constants(self, str_op, py_op): program = f"qreg q[1]; U(0.25{str_op}0.5, 1.0{str_op}0.5, 3.2{str_op}-0.8) q[0];" parsed = qiskit.qasm2.loads(program) expected = [py_op(0.25, 0.5), py_op(1.0, 0.5), py_op(3.2, -0.8)] # These should be bit-for-bit exact. self.assertEqual(list(parsed.data[0].operation.params), expected) @ddt.data( ("+", lambda a, b: a + b), ("-", lambda a, b: a - b), ("*", lambda a, b: a * b), ("/", lambda a, b: a / b), ("^", lambda a, b: a**b), ) @ddt.unpack def test_binary_symbolic(self, str_op, py_op): program = f""" gate u(a, b, c) q {{ U(a {str_op} b, a {str_op} (b {str_op} c), 0.0) q; }} qreg q[1]; u(1.0, 2.0, 3.0) q[0]; """ parsed = qiskit.qasm2.loads(program) outer = [1.0, 2.0, 3.0] abstract_op = parsed.data[0].operation self.assertEqual(list(abstract_op.params), outer) expected = [py_op(1.0, 2.0), py_op(1.0, py_op(2.0, 3.0)), 0.0] actual = [float(x) for x in abstract_op.definition.data[0].operation.params] self.assertEqual(list(actual), expected) @ddt.data( ("cos", math.cos), ("exp", math.exp), ("ln", math.log), ("sin", math.sin), ("sqrt", math.sqrt), ("tan", math.tan), ) @ddt.unpack def test_function_constants(self, function_str, function_py): program = f"qreg q[1]; U({function_str}(0.5),{function_str}(1.0),{function_str}(pi)) q[0];" parsed = qiskit.qasm2.loads(program) expected = [function_py(0.5), function_py(1.0), function_py(math.pi)] # These should be bit-for-bit exact. self.assertEqual(list(parsed.data[0].operation.params), expected) @ddt.data( ("cos", math.cos), ("exp", math.exp), ("ln", math.log), ("sin", math.sin), ("sqrt", math.sqrt), ("tan", math.tan), ) @ddt.unpack def test_function_symbolic(self, function_str, function_py): program = f""" gate u(a, b, c) q {{ U({function_str}(a), {function_str}(b), {function_str}(c)) q; }} qreg q[1]; u(0.5, 1.0, pi) q[0]; """ parsed = qiskit.qasm2.loads(program) outer = [0.5, 1.0, math.pi] abstract_op = parsed.data[0].operation self.assertEqual(list(abstract_op.params), outer) expected = [function_py(x) for x in outer] actual = [float(x) for x in abstract_op.definition.data[0].operation.params] self.assertEqual(list(actual), expected) class TestPrecedenceAssociativity(QiskitTestCase): def test_precedence(self): # OQ3's precedence rules are the same as Python's, so we can effectively just eval. expr = " 1.0 + 2.0 * -3.0 ^ 1.5 - 0.5 / +0.25" expected = 1.0 + 2.0 * -(3.0**1.5) - 0.5 / +0.25 program = f"qreg q[1]; U({expr}, 0, 0) q[0];" parsed = qiskit.qasm2.loads(program) self.assertEqual(parsed.data[0].operation.params[0], expected) def test_addition_left(self): # `eps` is the smallest floating-point value such that `1 + eps != 1`. That means that if # addition is correctly parsed and resolved as left-associative, then the first parameter # should first calculate `1 + (eps / 2)`, which will be 1, and then the same again, whereas # the second will do `(eps / 2) + (eps / 2) = eps`, then `eps + 1` will be different. eps = sys.float_info.epsilon program = f"qreg q[1]; U(1 + {eps / 2} + {eps / 2}, {eps / 2} + {eps / 2} + 1, 0) q[0];" parsed = qiskit.qasm2.loads(program) self.assertNotEqual(1.0 + eps, 1.0) # Sanity check for the test. self.assertEqual(list(parsed.data[0].operation.params), [1.0, 1.0 + eps, 0.0]) def test_multiplication_left(self): # A similar principle to the epsilon test for addition; if multiplication associates right, # then `(0.5 * 2.0 * fmax)` is `inf`, otherwise it's `fmax`. fmax = sys.float_info.max program = f"qreg q[1]; U({fmax} * 0.5 * 2.0, 2.0 * 0.5 * {fmax}, 2.0 * {fmax} * 0.5) q[0];" parsed = qiskit.qasm2.loads(program) self.assertEqual(list(parsed.data[0].operation.params), [fmax, fmax, math.inf]) def test_subtraction_left(self): # If subtraction associated right, we'd accidentally get 2. program = "qreg q[1]; U(2.0 - 1.0 - 1.0, 0, 0) q[0];" parsed = qiskit.qasm2.loads(program) self.assertEqual(list(parsed.data[0].operation.params), [0.0, 0.0, 0.0]) def test_division_left(self): # If division associated right, we'd accidentally get 4. program = "qreg q[1]; U(4.0 / 2.0 / 2.0, 0, 0) q[0];" parsed = qiskit.qasm2.loads(program) self.assertEqual(list(parsed.data[0].operation.params), [1.0, 0.0, 0.0]) def test_power_right(self): # If the power operator associated left, we'd accidentally get 64 instead. program = "qreg q[1]; U(2.0 ^ 3.0 ^ 2.0, 0, 0) q[0];" parsed = qiskit.qasm2.loads(program) self.assertEqual(list(parsed.data[0].operation.params), [512.0, 0.0, 0.0]) class TestCustomClassical(QiskitTestCase): def test_evaluation_order(self): """We should be evaluating all functions, including custom user ones the exact number of times we expect, and left-to-right in parameter lists.""" # pylint: disable=invalid-name order = itertools.count() def f(): return next(order) program = """ qreg q[1]; U(f(), 2 * f() + f(), atan2(f(), f()) - f()) q[0]; """ parsed = qiskit.qasm2.loads( program, custom_classical=[ qiskit.qasm2.CustomClassical("f", 0, f), qiskit.qasm2.CustomClassical("atan2", 2, math.atan2), ], ) self.assertEqual( list(parsed.data[0].operation.params), [0, 2 * 1 + 2, math.atan2(3, 4) - 5] ) self.assertEqual(next(order), 6) @ddt.ddt class TestErrors(QiskitTestCase): @ddt.data("0.0", "(1.0 - 1.0)") def test_refuses_to_divide_by_zero(self, denom): program = f"qreg q[1]; U(2.0 / {denom}, 0.0, 0.0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "divide by zero"): qiskit.qasm2.loads(program) program = f"gate rx(a) q {{ U(a / {denom}, 0.0, 0.0) q; }}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "divide by zero"): qiskit.qasm2.loads(program) @ddt.data("0.0", "1.0 - 1.0", "-2.0", "2.0 - 3.0") def test_refuses_to_ln_non_positive(self, operand): program = f"qreg q[1]; U(ln({operand}), 0.0, 0.0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "ln of non-positive"): qiskit.qasm2.loads(program) program = f"gate rx(a) q {{ U(a + ln({operand}), 0.0, 0.0) q; }}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "ln of non-positive"): qiskit.qasm2.loads(program) @ddt.data("-2.0", "2.0 - 3.0") def test_refuses_to_sqrt_negative(self, operand): program = f"qreg q[1]; U(sqrt({operand}), 0.0, 0.0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "sqrt of negative"): qiskit.qasm2.loads(program) program = f"gate rx(a) q {{ U(a + sqrt({operand}), 0.0, 0.0) q; }}" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "sqrt of negative"): qiskit.qasm2.loads(program) @ddt.data("*", "/", "^") def test_cannot_use_nonunary_operators_in_unary_position(self, operator): program = f"qreg q[1]; U({operator}1.0, 0.0, 0.0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not a valid unary operator"): qiskit.qasm2.loads(program) @ddt.data("+", "-", "*", "/", "^") def test_missing_binary_operand_errors(self, operator): program = f"qreg q[1]; U(1.0 {operator}, 0.0, 0.0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "missing operand"): qiskit.qasm2.loads(program) program = f"qreg q[1]; U((1.0 {operator}), 0.0, 0.0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "missing operand"): qiskit.qasm2.loads(program) def test_parenthesis_must_be_closed(self): program = "qreg q[1]; U((1 + 1 2), 3, 2) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "needed a closing parenthesis"): qiskit.qasm2.loads(program) def test_premature_right_parenthesis(self): program = "qreg q[1]; U(sin(), 0.0, 0.0) q[0];" with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "did not find an .* expression"): qiskit.qasm2.loads(program)
https://github.com/renatawong/classical-shadow-vqe
renatawong
''' (C) 2023 Renata Wong Electronic structure problem with classical shadows, as presented in https://arxiv.org/abs/2103.07510 This code uses Qiskit as platform. The shadow is constructed based on derandomized Hamiltonian. The molecules tested are: H2 (6-31s basis), LiH (sto3g basis), BeH2 (sto3g), H2O (sto3g), and NH3 (sto3g). The coordinates for NH3 were taken from 'Algorithms for Computer Detection of Symmetry Elementsin Molecular Systems'. ''' import time import numpy as np from collections import Counter import matplotlib.pyplot as plt from qiskit import QuantumCircuit, execute from qiskit_aer.primitives import Estimator as AerEstimator from qiskit_aer import QasmSimulator from qiskit.quantum_info import SparsePauliOp from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.algorithms import GroundStateEigensolver from qiskit_nature.second_q.mappers import BravyiKitaevMapper, JordanWignerMapper, ParityMapper from qiskit_nature.second_q.circuit.library import UCCSD, HartreeFock from qiskit_nature.second_q.algorithms import VQEUCCFactory from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA # Estimator primitive is based on the Statevector construct = algebraic simulation from qiskit.primitives import Estimator from qiskit.utils import algorithm_globals from modified_derandomization import modified_derandomized_classical_shadow from predicting_quantum_properties.data_acquisition_shadow import derandomized_classical_shadow from predicting_quantum_properties.prediction_shadow import estimate_exp import qiskit_nature qiskit_nature.settings.use_pauli_sum_op = False import h5py H5PY_DEFAULT_READONLY=1 ''' DEFINING DRIVERS FOR THE MOLECULES ''' H2_driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.735", basis="6-31g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) LiH_driver = PySCFDriver( atom="Li 0 0 0; H 0 0 1.599", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) BeH2_driver = PySCFDriver( atom="Be 0 0 0; H 0 0 1.3264; H 0 0 -1.3264", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) H2O_driver = PySCFDriver( atom="O 0.0 0.0 0.0; H 0.757 0.586 0.0; H -0.757 0.586 0.0", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) NH3_driver = PySCFDriver( atom="N 0 0 0; H 0 0 1.008000; H 0.950353 0 -0.336000; H -0.475176 -0.823029 -0.336000", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) ''' FORMATTING HAMILTONIAN ''' def process_hamiltonian(hamiltonian, derandomize = False): hamiltonian_observables = [] hamiltonian_coefficients = [] for observable in hamiltonian.paulis: op_list = [] for op_index, pauli_op in enumerate(observable): pauli_op = str(pauli_op) if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z': op_list.append((pauli_op, op_index)) hamiltonian_observables.append(op_list) hamiltonian_coefficients = hamiltonian.coeffs.real system_size = len(hamiltonian_observables[0]) # removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left # these observables are needed for estimate_exp() observables_xyze = [] for observable in hamiltonian_observables: XYZE = [] for pauli in observable: if pauli[0] != 'I': XYZE.append(pauli) observables_xyze.append(XYZE) # derandomisation procedure requires that coefficients are non-negative if derandomize == True: absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients] # removing the empty list as well # these observables are needed for derandomisation procedure observables_xyz = [] for idx, observable in enumerate(observables_xyze): if observable: observables_xyz.append(observable) else: absolute_coefficients.pop(idx) return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients return system_size, observables_xyze, hamiltonian_coefficients ''' COST FUNCTION AND HELPER FUNCTIONS ''' def basis_change_circuit(pauli_op): # Generating circuit with just the basis change operators # # pauli_op: n-qubit Pauli operator basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits) for idx, op in enumerate(pauli_op): if op == 'X': basis_change.h(idx) if op == 'Y': basis_change.h(idx) basis_change.p(-np.pi/2, idx) return basis_change def ground_state_energy_from_shadow(operators, params): backend = QasmSimulator(method='statevector', shots=1) pauli_op_dict = Counter(tuple(x) for x in operators) shadow = [] for pauli_op in pauli_op_dict: qc = ansatz.bind_parameters(params) qc = qc.compose(basis_change_circuit(pauli_op)) qc.measure(reversed(range(system_size)), range(system_size)) result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result() counts = result.get_counts() # given in order q0 q1 ... qn-1 after register reversal in qc.measure for count in counts: for _ in range(counts[count]): # number of repeated measurement values output_str = list(count) output = [int(i) for i in output_str] eigenvals = [x+1 if x == 0 else x-2 for x in output] snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)] shadow.append(snapshot) expectation_value = 0.0 for term, weight in zip(observables_xyze, hamiltonian_coefficients): sum_product, match_count = estimate_exp(shadow, term) if match_count != 0: expectation_value += (weight * sum_product / match_count) return expectation_value ''' EXPERIMENTS ''' start_time = time.time() all_molecules_rmse_errors = [] # CALCULATING FERMIONIC HAMILTONIAN AND CONVERTING TO QUBIT HAMILTONIAN MOLECULES = ['H2O'] for molecule in MOLECULES: rmse_errors = [] if molecule == 'H2': problem = H2_driver.run() if molecule == 'LiH': problem = LiH_driver.run() if molecule == 'BeH2': problem = BeH2_driver.run() if molecule == 'H2O': problem = H2O_driver.run() if molecule == 'NH3': problem = NH3_driver.run() hamiltonian = problem.hamiltonian second_q_op = hamiltonian.second_q_op() bk_mapper = BravyiKitaevMapper() bkencoded_hamiltonian = bk_mapper.map(second_q_op) #print('Qubit Hamiltonian in Bravyi-Kitaev encoding', bkencoded_hamiltonian) # process the Hamiltonian to obtain properly formatted data hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = True) system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients = hamiltonian_data ''' VARIATIONAL ANSATZ ''' ansatz = UCCSD( problem.num_spatial_orbitals, problem.num_particles, bk_mapper, initial_state=HartreeFock( problem.num_spatial_orbitals, problem.num_particles, bk_mapper, ), ) ''' Running VQE on the Hamiltonian obtained from PySCFDriver using Statevector simulator (Estimator primitive) ''' #estimator = Estimator() # If shots = None, it calculates the exact expectation values. Otherwise, it samples from normal distributions # with standard errors as standard deviations using normal distribution approximation. #estimator.set_options(shots = None) #estimator = AerEstimator() #estimator.set_options(approximation=True, shots=None) vqe_solver = VQE(Estimator(), ansatz, SLSQP()) vqe_solver.initial_point = np.zeros(ansatz.num_parameters) calc = GroundStateEigensolver(bk_mapper, vqe_solver) result = calc.solve(problem) print(result.raw_result) #print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n') measurement_range = [50, 250, 500, 750, 1000, 1250, 1500, 1750] for num_operators in measurement_range: derandomized_hamiltonian = derandomized_classical_shadow(observables_xyz, 50, system_size, weight=absolute_coefficients) tuples = (tuple(pauli) for pauli in derandomized_hamiltonian) counts = Counter(tuples) print('Original derandomized Hamiltonian', counts) # derandomized classical shadow will usually either undergenerate or overgenerate derandomized operators # adjusting for this issue: while sum(counts.values()) != num_operators: for key, value in zip(counts.keys(), counts.values()): sum_counts = sum(counts.values()) if sum_counts == num_operators: break if sum_counts < num_operators: # generate additional operators from the existing ones by increasing the number of counts counts[key] += 1 if sum_counts > num_operators: # remove the element with highest count max_element_key = [k for k, v in counts.items() if v == max(counts.values())][0] counts[max_element_key] -= 1 print('Size-adjusted derandomized Hamiltonian', counts) # translate the Counter to a set of derandomized operators new_derandomized_hamiltonian = [] for key, value in counts.items(): for _ in range(value): new_derandomized_hamiltonian.append(list(key)) #print('Size-adjusted derandomized Hamiltonian', new_derandomized_hamiltonian) expectation_values = [] num_experiments = 10 for iteration in range(num_experiments): expectation_value = ground_state_energy_from_shadow(new_derandomized_hamiltonian, result.raw_result.optimal_point) expectation_values.append(expectation_value) print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, expectation_value)) rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - result.raw_result.optimal_value)**2 for i in range(num_experiments)])/num_experiments) rmse_errors.append(rmse_derandomised_cs) print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs)) all_molecules_rmse_errors.append(rmse_errors) elapsed_time = time.time() - start_time print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time))) import matplotlib.pyplot as plt points = measurement_range num_points = len(points) plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='derandomized classical shadow') plt.xlabel('Number of measurements') plt.ylabel('Average RMSE error') plt.legend(loc=1)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.result import QuasiDistribution from qiskit_aer.primitives import Sampler from qiskit_finance.applications.optimization import PortfolioOptimization from qiskit_finance.data_providers import RandomDataProvider from qiskit_optimization.algorithms import MinimumEigenOptimizer import numpy as np import matplotlib.pyplot as plt import datetime # set number of assets (= number of qubits) num_assets = 4 seed = 123 # Generate expected return and covariance matrix from (random) time-series stocks = [("TICKER%s" % i) for i in range(num_assets)] data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() mu = data.get_period_return_mean_vector() sigma = data.get_period_return_covariance_matrix() # plot sigma plt.imshow(sigma, interpolation="nearest") plt.show() q = 0.5 # set risk factor budget = num_assets // 2 # set budget penalty = num_assets # set parameter to scale the budget penalty term portfolio = PortfolioOptimization( expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget ) qp = portfolio.to_quadratic_program() qp def print_result(result): selection = result.x value = result.fval print("Optimal: selection {}, value {:.4f}".format(selection, value)) eigenstate = result.min_eigen_solver_result.eigenstate probabilities = ( eigenstate.binary_probabilities() if isinstance(eigenstate, QuasiDistribution) else {k: np.abs(v) ** 2 for k, v in eigenstate.to_dict().items()} ) print("\n----------------- Full result ---------------------") print("selection\tvalue\t\tprobability") print("---------------------------------------------------") probabilities = sorted(probabilities.items(), key=lambda x: x[1], reverse=True) for k, v in probabilities: x = np.array([int(i) for i in list(reversed(k))]) value = portfolio.to_quadratic_program().objective.evaluate(x) print("%10s\t%.4f\t\t%.4f" % (x, value, v)) exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(qp) print_result(result) from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=500) ry = TwoLocal(num_assets, "ry", "cz", reps=3, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(qp) print_result(result) 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(qp) print_result(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import transpile from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeVigoV2 backend = FakeVigoV2() qc = QuantumCircuit(2, 1) qc.h(0) qc.x(1) qc.cp(np.pi/4, 0, 1) qc.h(0) qc.measure([0], [0]) qc_basis = transpile(qc, backend) qc_basis.draw(output='mpl')
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/epelaaez/QuantumLibrary
epelaaez
import config import random from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, IBMQ, Aer, execute from qiskit.visualization import plot_histogram from qiskit.providers.ibmq import least_busy def d_oracle(qc, oracle, choice): """ Add oracle for Deutsch's algoritm, in the form of a gate, to quantum circuit. Parameters: ----------- qc: QuantumCircuit Quantum circuit with 2 qubits. oracle: int Type of oracle. 0 for balanced and 1 for constant. choice: int Choice of oracle type. For a balanced oracle, 0 will make f(x)=x and 1 will make f(x)=¬x. For a constant oracle, 0 will make f(x)=0 and 1 will make f(x)=1. Returns: -------- qc: QuantumCircuit Quantum circuit with Deutsch's algorithm oracle added at the end. """ qreg = QuantumRegister(2, 'q') oracle_circuit = QuantumCircuit(qreg, name='$U_f$') # Balanced oracle if oracle == 0: if choice == 0: oracle_circuit.cx(0, 1) elif choice == 1: oracle_circuit.cx(0, 1) oracle_circuit.x(1) # Constant oracle elif oracle == 1: if choice == 0: pass # qubit is already initialized to 0 elif choice == 1: oracle_circuit.x(1) # Turn oracle into single gate and append to qc oracle_gate = oracle_circuit.to_gate() qc.append(oracle_gate, [0, 1]) return qc def deutsch(oracle = None, choice = None): """ Create quantum circuit implementing Deutsch's algorithm. Parameters: ----------- oracle: int Type of oracle. 0 for balanced and 1 for constant. choice: int Choice of oracle type. For a balanced oracle, 0 will make f(x)=x and 1 will make f(x)=¬x. For a constant oracle, 0 will make f(x)=0 and 1 will make f(x)=1. NOTE: if any parameter is set to none (default), the value will be randomized. Returns: -------- qc: QuantumCircuit Quantum circuit implementing Deutsch's algorithm. """ # Randomize oracle and choice if not given if oracle == None: oracle = random.randint(0, 1) if choice == None: choice = random.randint(0, 1) qreg = QuantumRegister(2, 'q') creg = ClassicalRegister(1, 'c') qc = QuantumCircuit(qreg, creg) # Prepare initial state qc.x(qreg[1]) qc.barrier() # Put into superpusition qc.h(qreg) qc.barrier() # Add oracle d_oracle(qc, oracle, choice) qc.barrier() # Apply interference qc.h(qreg[0]) qc.barrier() # Measure first qubit qc.measure(qreg[0], creg) # Return circuit return qc circ = deutsch() circ.draw() circ_balanced = deutsch(0) circ_constant = deutsch(1) # We will let the choice be random for both circuits IBMQ.save_account(f"{config.IBM_KEY}", overwrite = True) IBMQ.load_account() backend = Aer.get_backend('qasm_simulator') # Uncomment below to run on hardware # provider = IBMQ.get_provider(hub='ibm-q') # backend = least_busy(provider.backends()) result = execute(circ_balanced, backend, shots=1024).result() count_b = result.get_counts(circ_balanced) plot_histogram(count_b) backend = Aer.get_backend('qasm_simulator') # Uncomment below to run on hardware # provider = IBMQ.get_provider(hub='ibm-q') # backend = least_busy(provider.backends()) result = execute(circ_constant, backend, shots=1024).result() count_c = result.get_counts(circ_constant) plot_histogram(count_c) def dj_oracle(qc, n, oracle, choice, to_gate=True): """ Add oracle for Deutsch-Jozsa algoritm, in the form of a gate, to quantum circuit. Parameters: ----------- qc: QuantumCircuit Quantum circuit with n+1 qubits. n: int Number of qubits in first register. n-input to Deutsch-Jozsa. Should be one less that the total size of the circuit. oracle: int Type of oracle. 0 for balanced and 1 for constant. choice: int Choice of oracle type. For a balanced oracle, this parameter is irrelevant. For a constant oracle, 0 will make f(x)=0 and 1 will make f(x)=1. to_gate: bool If true, the oracle will be added as a gate to the original circuit. If false, the individual gates will be added to the original circuit. Returns: -------- qc: QuantumCircuit Quantum circuit with Deutsch-Jozsa oracle added at the end. """ qc_len = 0 for qr in qc.qregs: qc_len += len(qr) if qc_len != n + 1: raise Exception(('Length of oracle and circuit given do not match correctly.' ' Parameter n should be one less than number of qubits in parameter qc.')) if to_gate: qreg_input = QuantumRegister(n, 'x') qreg_output = QuantumRegister(1, 'y') oracle_circuit = QuantumCircuit(qreg_input, qreg_output, name='$U_f$') # Balanced oracle if oracle == 0: for i in range(n): oracle_circuit.cx(qreg_input[i], qreg_output) # Constant oracle elif oracle == 1: if choice == 0: pass # y is already initialized to 0 elif choice == 1: oracle_circuit.x(qreg_output) oracle_gate = oracle_circuit.to_gate() qc.append(oracle_gate, range(n+1)) else: # Balanced oracle if oracle == 0: for i in range(n): qc.cx(i, n) # Constant oracle elif oracle == 1: if choice == 0: pass # y is already initialized to 0 elif choice == 1: qc.x(n) return qc def deutsch_jozsa(n, oracle=None, choice=None, oracle_gate=True): """ Create quantum circuit implementing n-input Deutsch-Jozsa algorithm. Parameters: ----------- n: int Number of qubits in first register. n-input to Deutsch-Jozsa. Should be one less that the total size of the circuit. oracle: int Type of oracle. 0 for balanced and 1 for constant. choice: int Choice of oracle type. For a balanced oracle, this parameter is irrelevant. For a constant oracle, 0 will make f(x)=0 and 1 will make f(x)=1. oracle_gate: bool If true, the oracle will be added as a gate to the original circuit. If false, the individual gates enclosed by barriers will be added to the original circuit. Returns: -------- qc: QuantumCircuit Quantum circuit with Deutsch-Jozsa oracle added at the end. """ # Randomize oracle and choice if not given if oracle == None: oracle = random.randint(0, 1) if choice == None: choice = random.randint(0, 1) qreg_in = QuantumRegister(n, 'x') qreg_out = QuantumRegister(1, 'y') creg = ClassicalRegister(n, 'c') qc = QuantumCircuit(qreg_in, qreg_out, creg) # Prepare initial state qc.x(qreg_in) qc.barrier() # Put into superpusition qc.h(range(n+1)) qc.barrier() # Add oracle dj_oracle(qc, n, oracle, choice, oracle_gate) qc.barrier() # Apply interference qc.h(qreg_in) qc.barrier() # Measure first qubit qc.measure(qreg_in, creg) return qc qc = deutsch_jozsa(3, oracle=0, oracle_gate=False) qc.draw() backend = Aer.get_backend('qasm_simulator') # Uncomment below to run on hardware # provider = IBMQ.get_provider(hub='ibm-q') # backend = least_busy(provider.backends()) result = execute(qc, backend, shots=1024).result() counts = result.get_counts(qc) plot_histogram(counts)
https://github.com/Pitt-JonesLab/slam_decomposition
Pitt-JonesLab
import logging logger = logging.getLogger() logger.setLevel(logging.INFO) %matplotlib widget import numpy as np from slam.utils.polytopes.coverage_plot import plot_coverage_set from slam.basis import MixedOrderBasisCircuitTemplate from slam.utils.gates.custom_gates import ConversionGainGate # #coverage of an arbitrary gate # # will load coverage polytope from file in template constructor or create it if it doesn't exist # base_gate = ConversionGainGate(0,0, np.pi/8, 3*np.pi/8, 1/2) # template = MixedOrderBasisCircuitTemplate(base_gates=[base_gate], chatty_build=0, bare_cost=True) # plot_coverage_set(template.coverage[:], save=0, filename=f"coverage_set_custom") iswap = np.pi / 2, 0, 1, "iSwap", 3 sqiswap = np.pi / 2, 0, 1 / 2, "sqiSwap", 3 cnot = np.pi / 4, np.pi / 4, 1, "CNOT", 3 sqcnot = np.pi / 4, np.pi / 4, 1 / 2, "sqCNOT", 6 b = 3 * np.pi / 8, np.pi / 8, 1, "B", 2 sqb = 3 * np.pi / 8, np.pi / 8, 1 / 2, "sqB", 4 gate_list = [iswap, sqiswap, cnot, sqcnot, b, sqb] use_smush = 0 for gate_prop in gate_list[1:2]: base_gate = ConversionGainGate(0, 0, *gate_prop[:3]) template = MixedOrderBasisCircuitTemplate( base_gates=[base_gate], chatty_build=0, bare_cost=True, use_smush_polytope=use_smush, ) fname = f"coverage_set_{gate_prop[3]}" if use_smush: fname += "_smush" poly_list = template.coverage fig = plot_coverage_set(poly_list[:], save=1, filename=fname) # take 3d axis of fig, and turn into gif with small rotations, stereoscopic view import matplotlib.pyplot as pltFigure 1 from matplotlib.animation import FuncAnimation from mpl_toolkits.mplot3d import Axes3D for i in range(len(fig.axes)): ax = fig.axes[i] ax.view_init(30, 45) ax.set_xlabel("X") ax.set_ylabel("Y") ax.set_zlabel("Z") ax.set_xlim(-1, 1) ax.set_ylim(-1, 1) ax.set_zlim(-1, 1) ax.set_aspect("equal") def update(i): ax.view_init(30, 45 + i) return fig, anim = FuncAnimation(fig, update, frames=np.arange(0, 15, 1), interval=20) anim.save(f"{fname}_3d.gif", dpi=80, writer="imagemagick")
https://github.com/WhenTheyCry96/qiskitHackathon2022
WhenTheyCry96
%load_ext autoreload %autoreload 2 import os import warnings import numpy as np import pandas as pd import qiskit_metal as metal from numpy import pi from scipy.constants import c, h, pi, hbar, e from qiskit_metal import designs, draw, MetalGUI, Dict, Headings from qiskit_metal.qlibrary.qubits.transmon_pocket_6 import TransmonPocket6 from qiskit_metal.qlibrary.qubits.transmon_pocket_cl import TransmonPocketCL from qiskit_metal.qlibrary.tlines.meandered import RouteMeander from qiskit_metal.qlibrary.terminations.open_to_ground import OpenToGround from qiskit_metal.qlibrary.lumped.cap_3_interdigital import Cap3Interdigital from qiskit_metal.qlibrary.terminations.launchpad_wb_coupled import LaunchpadWirebondCoupled from qiskit_metal.analyses.em.cpw_calculations import guided_wavelength from qiskit_metal.analyses.quantization import LOManalysis, EPRanalysis from qiskit_metal.analyses.quantization.lumped_capacitive import load_q3d_capacitance_matrix from qiskit_metal.analyses.quantization.lom_core_analysis import CompositeSystem, Cell, Subsystem, QuantumSystemRegistry ws_path = os.getcwd() warnings.filterwarnings("ignore") design = designs.DesignPlanar() design.overwrite_enabled = True #constants: phi0 = h/(2*e) varphi0 = phi0/(2*pi) # project target parameters f_qList = np.around(np.linspace(5.25, 5.75, 4),2) # GHz f_rList = f_qList + 1.8 # GHz L_JJList = np.around(varphi0**2/((f_qList*1e9+300e6)**2/(8*300e6))/h*1e9, 2) # nH # initial CPW readout lengths def find_resonator_length(frequency, line_width, line_gap, N): #frequency in GHz #line_width/line_gap in um #N -> 2 for lambda/2, 4 for lambda/4 [lambdaG, etfSqrt, q] = guided_wavelength(frequency*10**9, line_width*10**-6, line_gap*10**-6, 750*10**-6, 200*10**-9) return str(lambdaG/N*10**3)+" mm" find_resonator_length(f_rList, 10, 6, 2) find_resonator_length(np.around(np.linspace(8, 9, 4),2), 10, 6, 2) chipX = 9 chipY = 9 design.chips.main.size_x = str(chipX)+"mm" design.chips.main.size_y = str(chipY)+"mm" gui = MetalGUI(design) design.delete_all_components() # basic parameters for inital cut C_JJ = 2 pad_g = 30 pad_w = 450 pad_h = 150 readout_g = 30 buslineL_g = 30 buslineH_g = 30 C_JJU = str(C_JJ)+"fF" pad_g = str(pad_g)+"um" pad_w = str(pad_w)+"um" pad_h = str(pad_h)+"um" readout_g = str(readout_g)+"um" buslineL_g = str(buslineL_g)+"um" buslineH_g = str(buslineH_g)+"um" connector1_pads_options = dict( cR = dict(loc_W=0, loc_H=1, pad_width='80 um', pad_gap=readout_g, pad_height='30 um'), # readout resonator cL = dict(loc_W=1, loc_H=-1, pad_width='80 um', pad_gap=buslineL_g, pad_height='30 um'), # bus line for lower frequency cH = dict(loc_W=-1, loc_H=-1, pad_width='80 um', pad_gap=buslineH_g, pad_height='30 um') # bus line for higher frequency ) connector2_pads_options = dict( cR = dict(loc_W=0, loc_H=1, pad_width='80 um', pad_gap=readout_g, pad_height='30 um'), # readout resonator cL = dict(loc_W=1, loc_H=-1, pad_width='80 um', pad_gap=buslineL_g, pad_height='30 um'), # bus line for lower frequency cH = dict(loc_W=-1, loc_H=-1, pad_width='80 um', pad_gap=buslineH_g, pad_height='30 um') # bus line for higher frequency ) connector3_pads_options = dict( cR = dict(loc_W=0, loc_H=1, pad_width='80 um', pad_gap=readout_g, pad_height='30 um'), # readout resonator cL = dict(loc_W=1, loc_H=-1, pad_width='80 um', pad_gap=buslineL_g, pad_height='30 um'), # bus line for lower frequency cH = dict(loc_W=-1, loc_H=-1, pad_width='80 um', pad_gap=buslineH_g, pad_height='30 um') # bus line for higher frequency ) connector4_pads_options = dict( cR = dict(loc_W=0, loc_H=1, pad_width='80 um', pad_gap=readout_g, pad_height='30 um'), # readout resonator cL = dict(loc_W=1, loc_H=-1, pad_width='80 um', pad_gap=buslineL_g, pad_height='30 um'), # bus line for lower frequency cH = dict(loc_W=-1, loc_H=-1, pad_width='80 um', pad_gap=buslineH_g, pad_height='30 um') # bus line for higher frequency ) # target f: 5.25 connection1_pads_options = dict( B1 = dict(loc_W=1, loc_H=-1), R= dict(loc_W=1, loc_H=1), B2 = dict(loc_W=-1, loc_H=-1) ) Q1 = TransmonPocketCL(design, 'Q1', options=dict(pos_x=f'0mm', pos_y=f'0mm', pad_gap = pad_g, pad_width = pad_w, pad_height = pad_h, orientation=0, connection_pads=dict(**connection1_pads_options))) gui.rebuild() gui.autoscale() from qiskit_metal.analyses.quantization import EPRanalysis eig_qres = EPRanalysis(design, "hfss") hfss = eig_qres.sim.renderer hfss.start() hfss.activate_ansys_design("Q1Readout", 'eigenmode') hfss.render_design(['Q1'], []) # Analysis properties setup = hfss.pinfo.setup setup.n_modes = 1 setup.passes = 10 setup.box_plus_buffer =True print(f""" Number of eigenmodes to find = {setup.n_modes} Number of simulation passes = {setup.passes} Convergence freq max delta percent diff = {setup.delta_f} """) pinfo = hfss.pinfo pinfo.design.set_variable('Lj', str(L_JJList[0])+'nH') pinfo.design.set_variable('Cj', C_JJU) setup.analyze() eig_qres.sim.convergence_t, eig_qres.sim.convergence_f, _ = hfss.get_convergences() eig_qres.sim.plot_convergences() import pyEPR as epr pinfo = hfss.pinfo pinfo.junctions['jj'] = {'Lj_variable': 'Lj', 'rect': 'JJ_rect_Lj_Q1_rect_jj', 'line': 'JJ_Lj_Q1_rect_jj_', 'Cj_variable': 'Cj'} pinfo.validate_junction_info() # Check that valid names of variables and objects have been supplied pinfo.dissipative['dielectrics_bulk'] = ['main'] # Dissipative elements: specify eprd = epr.DistributedAnalysis(pinfo) print(eprd) ℰ_elec = eprd.calc_energy_electric() ℰ_elec_substrate = eprd.calc_energy_electric(None, 'main') ℰ_mag = eprd.calc_energy_magnetic() print(f""" ℰ_elec_all = {ℰ_elec} ℰ_elec_substrate = {ℰ_elec_substrate} EPR of substrate = {ℰ_elec_substrate / ℰ_elec * 100 :.1f}% ℰ_mag_all = {ℰ_mag} ℰ_mag % of ℰ_elec_all = {ℰ_mag / ℰ_elec * 100 :.1f}% """) eprd.do_EPR_analysis() # 4a. Perform Hamiltonian spectrum post-analysis, building on mw solutions using EPR epra = epr.QuantumAnalysis(eprd.data_filename) epra.analyze_all_variations(cos_trunc = 8, fock_trunc = 7) hfss.modeler._modeler.ShowWindow() hfss.plot_fields('main')
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=cyclic-import """ ========= Schedules ========= .. currentmodule:: qiskit.pulse Schedules are Pulse programs. They describe instruction sequences for the control hardware. The Schedule is one of the most fundamental objects to this pulse-level programming module. A ``Schedule`` is a representation of a *program* in Pulse. Each schedule tracks the time of each instruction occuring in parallel over multiple signal *channels*. .. autosummary:: :toctree: ../stubs/ Schedule ScheduleBlock """ import abc import copy import functools import itertools import multiprocessing as mp import re import sys import warnings from typing import List, Tuple, Iterable, Union, Dict, Callable, Set, Optional, Any import numpy as np import rustworkx as rx from qiskit.circuit.parameter import Parameter from qiskit.circuit.parameterexpression import ParameterExpression, ParameterValueType from qiskit.pulse.channels import Channel from qiskit.pulse.exceptions import PulseError, UnassignedReferenceError from qiskit.pulse.instructions import Instruction, Reference from qiskit.pulse.utils import instruction_duration_validation from qiskit.pulse.reference_manager import ReferenceManager from qiskit.utils.multiprocessing import is_main_process Interval = Tuple[int, int] """An interval type is a tuple of a start time (inclusive) and an end time (exclusive).""" TimeSlots = Dict[Channel, List[Interval]] """List of timeslots occupied by instructions for each channel.""" class Schedule: """A quantum program *schedule* with exact time constraints for its instructions, operating over all input signal *channels* and supporting special syntaxes for building. Pulse program representation for the original Qiskit Pulse model [1]. Instructions are not allowed to overlap in time on the same channel. This overlap constraint is immediately evaluated when a new instruction is added to the ``Schedule`` object. It is necessary to specify the absolute start time and duration for each instruction so as to deterministically fix its execution time. The ``Schedule`` program supports some syntax sugar for easier programming. - Appending an instruction to the end of a channel .. code-block:: python sched = Schedule() sched += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) - Appending an instruction shifted in time by a given amount .. code-block:: python sched = Schedule() sched += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) << 30 - Merge two schedules .. code-block:: python sched1 = Schedule() sched1 += Play(Gaussian(160, 0.1, 40), DriveChannel(0)) sched2 = Schedule() sched2 += Play(Gaussian(160, 0.1, 40), DriveChannel(1)) sched2 = sched1 | sched2 A :obj:`.PulseError` is immediately raised when the overlap constraint is violated. In the schedule representation, we cannot parametrize the duration of instructions. Thus we need to create a new schedule object for each duration. To parametrize an instruction's duration, the :class:`~qiskit.pulse.ScheduleBlock` representation may be used instead. References: [1]: https://arxiv.org/abs/2004.06755 """ # Prefix to use for auto naming. prefix = "sched" # Counter to count instance number. instances_counter = itertools.count() def __init__( self, *schedules: Union["ScheduleComponent", Tuple[int, "ScheduleComponent"]], name: Optional[str] = None, metadata: Optional[dict] = None, ): """Create an empty schedule. Args: *schedules: Child Schedules of this parent Schedule. May either be passed as the list of schedules, or a list of ``(start_time, schedule)`` pairs. name: Name of this schedule. Defaults to an autogenerated string if not provided. metadata: Arbitrary key value metadata to associate with the schedule. This gets stored as free-form data in a dict in the :attr:`~qiskit.pulse.Schedule.metadata` attribute. It will not be directly used in the schedule. Raises: TypeError: if metadata is not a dict. """ from qiskit.pulse.parameter_manager import ParameterManager if name is None: name = self.prefix + str(next(self.instances_counter)) if sys.platform != "win32" and not is_main_process(): name += f"-{mp.current_process().pid}" self._name = name self._parameter_manager = ParameterManager() if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} self._duration = 0 # These attributes are populated by ``_mutable_insert`` self._timeslots = {} self._children = [] for sched_pair in schedules: try: time, sched = sched_pair except TypeError: # recreate as sequence starting at 0. time, sched = 0, sched_pair self._mutable_insert(time, sched) @classmethod def initialize_from(cls, other_program: Any, name: Optional[str] = None) -> "Schedule": """Create new schedule object with metadata of another schedule object. Args: other_program: Qiskit program that provides metadata to new object. name: Name of new schedule. Name of ``schedule`` is used by default. Returns: New schedule object with name and metadata. Raises: PulseError: When `other_program` does not provide necessary information. """ try: name = name or other_program.name if other_program.metadata: metadata = other_program.metadata.copy() else: metadata = None return cls(name=name, metadata=metadata) except AttributeError as ex: raise PulseError( f"{cls.__name__} cannot be initialized from the program data " f"{other_program.__class__.__name__}." ) from ex @property def name(self) -> str: """Name of this Schedule""" return self._name @property def metadata(self) -> Dict[str, Any]: """The user provided metadata associated with the schedule. User provided ``dict`` of metadata for the schedule. The metadata contents do not affect the semantics of the program but are used to influence the execution of the schedule. It is expected to be passed between all transforms of the schedule and that providers will associate any schedule metadata with the results it returns from the execution of that schedule. """ return self._metadata @metadata.setter def metadata(self, metadata): """Update the schedule metadata""" if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} @property def timeslots(self) -> TimeSlots: """Time keeping attribute.""" return self._timeslots @property def duration(self) -> int: """Duration of this schedule.""" return self._duration @property def start_time(self) -> int: """Starting time of this schedule.""" return self.ch_start_time(*self.channels) @property def stop_time(self) -> int: """Stopping time of this schedule.""" return self.duration @property def channels(self) -> Tuple[Channel]: """Returns channels that this schedule uses.""" return tuple(self._timeslots.keys()) @property def children(self) -> Tuple[Tuple[int, "ScheduleComponent"], ...]: """Return the child schedule components of this ``Schedule`` in the order they were added to the schedule. Notes: Nested schedules are returned as-is. If you want to collect only instructions, use py:meth:`~Schedule.instructions` instead. Returns: A tuple, where each element is a two-tuple containing the initial scheduled time of each ``NamedValue`` and the component itself. """ return tuple(self._children) @property def instructions(self) -> Tuple[Tuple[int, Instruction]]: """Get the time-ordered instructions from self.""" def key(time_inst_pair): inst = time_inst_pair[1] return time_inst_pair[0], inst.duration, sorted(chan.name for chan in inst.channels) return tuple(sorted(self._instructions(), key=key)) @property def parameters(self) -> Set: """Parameters which determine the schedule behavior.""" return self._parameter_manager.parameters def ch_duration(self, *channels: Channel) -> int: """Return the time of the end of the last instruction over the supplied channels. Args: *channels: Channels within ``self`` to include. """ return self.ch_stop_time(*channels) def ch_start_time(self, *channels: Channel) -> int: """Return the time of the start of the first instruction over the supplied channels. Args: *channels: Channels within ``self`` to include. """ try: chan_intervals = (self._timeslots[chan] for chan in channels if chan in self._timeslots) return min(intervals[0][0] for intervals in chan_intervals) except ValueError: # If there are no instructions over channels return 0 def ch_stop_time(self, *channels: Channel) -> int: """Return maximum start time over supplied channels. Args: *channels: Channels within ``self`` to include. """ try: chan_intervals = (self._timeslots[chan] for chan in channels if chan in self._timeslots) return max(intervals[-1][1] for intervals in chan_intervals) except ValueError: # If there are no instructions over channels return 0 def _instructions(self, time: int = 0): """Iterable for flattening Schedule tree. Args: time: Shifted time due to parent. Yields: Iterable[Tuple[int, Instruction]]: Tuple containing the time each :class:`~qiskit.pulse.Instruction` starts at and the flattened :class:`~qiskit.pulse.Instruction` s. """ for insert_time, child_sched in self.children: yield from child_sched._instructions(time + insert_time) def shift(self, time: int, name: Optional[str] = None, inplace: bool = False) -> "Schedule": """Return a schedule shifted forward by ``time``. Args: time: Time to shift by. name: Name of the new schedule. Defaults to the name of self. inplace: Perform operation inplace on this schedule. Otherwise return a new ``Schedule``. """ if inplace: return self._mutable_shift(time) return self._immutable_shift(time, name=name) def _immutable_shift(self, time: int, name: Optional[str] = None) -> "Schedule": """Return a new schedule shifted forward by `time`. Args: time: Time to shift by name: Name of the new schedule if call was mutable. Defaults to name of self """ shift_sched = Schedule.initialize_from(self, name) shift_sched.insert(time, self, inplace=True) return shift_sched def _mutable_shift(self, time: int) -> "Schedule": """Return this schedule shifted forward by `time`. Args: time: Time to shift by Raises: PulseError: if ``time`` is not an integer. """ if not isinstance(time, int): raise PulseError("Schedule start time must be an integer.") timeslots = {} for chan, ch_timeslots in self._timeslots.items(): timeslots[chan] = [(ts[0] + time, ts[1] + time) for ts in ch_timeslots] _check_nonnegative_timeslot(timeslots) self._duration = self._duration + time self._timeslots = timeslots self._children = [(orig_time + time, child) for orig_time, child in self.children] return self def insert( self, start_time: int, schedule: "ScheduleComponent", name: Optional[str] = None, inplace: bool = False, ) -> "Schedule": """Return a new schedule with ``schedule`` inserted into ``self`` at ``start_time``. Args: start_time: Time to insert the schedule. schedule: Schedule to insert. name: Name of the new schedule. Defaults to the name of self. inplace: Perform operation inplace on this schedule. Otherwise return a new ``Schedule``. """ if inplace: return self._mutable_insert(start_time, schedule) return self._immutable_insert(start_time, schedule, name=name) def _mutable_insert(self, start_time: int, schedule: "ScheduleComponent") -> "Schedule": """Mutably insert `schedule` into `self` at `start_time`. Args: start_time: Time to insert the second schedule. schedule: Schedule to mutably insert. """ self._add_timeslots(start_time, schedule) self._children.append((start_time, schedule)) self._parameter_manager.update_parameter_table(schedule) return self def _immutable_insert( self, start_time: int, schedule: "ScheduleComponent", name: Optional[str] = None, ) -> "Schedule": """Return a new schedule with ``schedule`` inserted into ``self`` at ``start_time``. Args: start_time: Time to insert the schedule. schedule: Schedule to insert. name: Name of the new ``Schedule``. Defaults to name of ``self``. """ new_sched = Schedule.initialize_from(self, name) new_sched._mutable_insert(0, self) new_sched._mutable_insert(start_time, schedule) return new_sched def append( self, schedule: "ScheduleComponent", name: Optional[str] = None, inplace: bool = False ) -> "Schedule": r"""Return a new schedule with ``schedule`` inserted at the maximum time over all channels shared between ``self`` and ``schedule``. .. math:: t = \textrm{max}(\texttt{x.stop_time} |\texttt{x} \in \texttt{self.channels} \cap \texttt{schedule.channels}) Args: schedule: Schedule to be appended. name: Name of the new ``Schedule``. Defaults to name of ``self``. inplace: Perform operation inplace on this schedule. Otherwise return a new ``Schedule``. """ common_channels = set(self.channels) & set(schedule.channels) time = self.ch_stop_time(*common_channels) return self.insert(time, schedule, name=name, inplace=inplace) def filter( self, *filter_funcs: Callable, channels: Optional[Iterable[Channel]] = None, instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None, time_ranges: Optional[Iterable[Tuple[int, int]]] = None, intervals: Optional[Iterable[Interval]] = None, check_subroutine: bool = True, ) -> "Schedule": """Return a new ``Schedule`` with only the instructions from this ``Schedule`` which pass though the provided filters; i.e. an instruction will be retained iff every function in ``filter_funcs`` returns ``True``, the instruction occurs on a channel type contained in ``channels``, the instruction type is contained in ``instruction_types``, and the period over which the instruction operates is *fully* contained in one specified in ``time_ranges`` or ``intervals``. If no arguments are provided, ``self`` is returned. Args: filter_funcs: A list of Callables which take a (int, Union['Schedule', Instruction]) tuple and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. time_ranges: For example, ``[(0, 5), (6, 10)]``. intervals: For example, ``[(0, 5), (6, 10)]``. check_subroutine: Set `True` to individually filter instructions inside of a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types, time_ranges, intervals) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=False, recurse_subroutines=check_subroutine ) def exclude( self, *filter_funcs: Callable, channels: Optional[Iterable[Channel]] = None, instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None, time_ranges: Optional[Iterable[Tuple[int, int]]] = None, intervals: Optional[Iterable[Interval]] = None, check_subroutine: bool = True, ) -> "Schedule": """Return a ``Schedule`` with only the instructions from this Schedule *failing* at least one of the provided filters. This method is the complement of py:meth:`~self.filter`, so that:: self.filter(args) | self.exclude(args) == self Args: filter_funcs: A list of Callables which take a (int, Union['Schedule', Instruction]) tuple and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. time_ranges: For example, ``[(0, 5), (6, 10)]``. intervals: For example, ``[(0, 5), (6, 10)]``. check_subroutine: Set `True` to individually filter instructions inside of a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types, time_ranges, intervals) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=True, recurse_subroutines=check_subroutine ) def _add_timeslots(self, time: int, schedule: "ScheduleComponent") -> None: """Update all time tracking within this schedule based on the given schedule. Args: time: The time to insert the schedule into self. schedule: The schedule to insert into self. Raises: PulseError: If timeslots overlap or an invalid start time is provided. """ if not np.issubdtype(type(time), np.integer): raise PulseError("Schedule start time must be an integer.") other_timeslots = _get_timeslots(schedule) self._duration = max(self._duration, time + schedule.duration) for channel in schedule.channels: if channel not in self._timeslots: if time == 0: self._timeslots[channel] = copy.copy(other_timeslots[channel]) else: self._timeslots[channel] = [ (i[0] + time, i[1] + time) for i in other_timeslots[channel] ] continue for idx, interval in enumerate(other_timeslots[channel]): if interval[0] + time >= self._timeslots[channel][-1][1]: # Can append the remaining intervals self._timeslots[channel].extend( [(i[0] + time, i[1] + time) for i in other_timeslots[channel][idx:]] ) break try: interval = (interval[0] + time, interval[1] + time) index = _find_insertion_index(self._timeslots[channel], interval) self._timeslots[channel].insert(index, interval) except PulseError as ex: raise PulseError( "Schedule(name='{new}') cannot be inserted into Schedule(name='{old}') at " "time {time} because its instruction on channel {ch} scheduled from time " "{t0} to {tf} overlaps with an existing instruction." "".format( new=schedule.name or "", old=self.name or "", time=time, ch=channel, t0=interval[0], tf=interval[1], ) ) from ex _check_nonnegative_timeslot(self._timeslots) def _remove_timeslots(self, time: int, schedule: "ScheduleComponent"): """Delete the timeslots if present for the respective schedule component. Args: time: The time to remove the timeslots for the ``schedule`` component. schedule: The schedule to insert into self. Raises: PulseError: If timeslots overlap or an invalid start time is provided. """ if not isinstance(time, int): raise PulseError("Schedule start time must be an integer.") for channel in schedule.channels: if channel not in self._timeslots: raise PulseError(f"The channel {channel} is not present in the schedule") channel_timeslots = self._timeslots[channel] other_timeslots = _get_timeslots(schedule) for interval in other_timeslots[channel]: if channel_timeslots: interval = (interval[0] + time, interval[1] + time) index = _interval_index(channel_timeslots, interval) if channel_timeslots[index] == interval: channel_timeslots.pop(index) continue raise PulseError( "Cannot find interval ({t0}, {tf}) to remove from " "channel {ch} in Schedule(name='{name}').".format( ch=channel, t0=interval[0], tf=interval[1], name=schedule.name ) ) if not channel_timeslots: self._timeslots.pop(channel) def _replace_timeslots(self, time: int, old: "ScheduleComponent", new: "ScheduleComponent"): """Replace the timeslots of ``old`` if present with the timeslots of ``new``. Args: time: The time to remove the timeslots for the ``schedule`` component. old: Instruction to replace. new: Instruction to replace with. """ self._remove_timeslots(time, old) self._add_timeslots(time, new) def _renew_timeslots(self): """Regenerate timeslots based on current instructions.""" self._timeslots.clear() for t0, inst in self.instructions: self._add_timeslots(t0, inst) def replace( self, old: "ScheduleComponent", new: "ScheduleComponent", inplace: bool = False, ) -> "Schedule": """Return a ``Schedule`` with the ``old`` instruction replaced with a ``new`` instruction. The replacement matching is based on an instruction equality check. .. code-block:: from qiskit import pulse d0 = pulse.DriveChannel(0) sched = pulse.Schedule() old = pulse.Play(pulse.Constant(100, 1.0), d0) new = pulse.Play(pulse.Constant(100, 0.1), d0) sched += old sched = sched.replace(old, new) assert sched == pulse.Schedule(new) Only matches at the top-level of the schedule tree. If you wish to perform this replacement over all instructions in the schedule tree. Flatten the schedule prior to running:: .. code-block:: sched = pulse.Schedule() sched += pulse.Schedule(old) sched = sched.flatten() sched = sched.replace(old, new) assert sched == pulse.Schedule(new) Args: old: Instruction to replace. new: Instruction to replace with. inplace: Replace instruction by mutably modifying this ``Schedule``. Returns: The modified schedule with ``old`` replaced by ``new``. Raises: PulseError: If the ``Schedule`` after replacements will has a timing overlap. """ from qiskit.pulse.parameter_manager import ParameterManager new_children = [] new_parameters = ParameterManager() for time, child in self.children: if child == old: new_children.append((time, new)) new_parameters.update_parameter_table(new) else: new_children.append((time, child)) new_parameters.update_parameter_table(child) if inplace: self._children = new_children self._parameter_manager = new_parameters self._renew_timeslots() return self else: try: new_sched = Schedule.initialize_from(self) for time, inst in new_children: new_sched.insert(time, inst, inplace=True) return new_sched except PulseError as err: raise PulseError( f"Replacement of {old} with {new} results in overlapping instructions." ) from err def is_parameterized(self) -> bool: """Return True iff the instruction is parameterized.""" return self._parameter_manager.is_parameterized() def assign_parameters( self, value_dict: Dict[ParameterExpression, ParameterValueType], inplace: bool = True ) -> "Schedule": """Assign the parameters in this schedule according to the input. Args: value_dict: A mapping from Parameters to either numeric values or another Parameter expression. inplace: Set ``True`` to override this instance with new parameter. Returns: Schedule with updated parameters. """ if not inplace: new_schedule = copy.deepcopy(self) return new_schedule.assign_parameters(value_dict, inplace=True) return self._parameter_manager.assign_parameters(pulse_program=self, value_dict=value_dict) def get_parameters(self, parameter_name: str) -> List[Parameter]: """Get parameter object bound to this schedule by string name. Because different ``Parameter`` objects can have the same name, this method returns a list of ``Parameter`` s for the provided name. Args: parameter_name: Name of parameter. Returns: Parameter objects that have corresponding name. """ return self._parameter_manager.get_parameters(parameter_name) def __len__(self) -> int: """Return number of instructions in the schedule.""" return len(self.instructions) def __add__(self, other: "ScheduleComponent") -> "Schedule": """Return a new schedule with ``other`` inserted within ``self`` at ``start_time``.""" return self.append(other) def __or__(self, other: "ScheduleComponent") -> "Schedule": """Return a new schedule which is the union of `self` and `other`.""" return self.insert(0, other) def __lshift__(self, time: int) -> "Schedule": """Return a new schedule which is shifted forward by ``time``.""" return self.shift(time) def __eq__(self, other: "ScheduleComponent") -> bool: """Test if two Schedule are equal. Equality is checked by verifying there is an equal instruction at every time in ``other`` for every instruction in this ``Schedule``. .. warning:: This does not check for logical equivalency. Ie., ```python >>> Delay(10, DriveChannel(0)) + Delay(10, DriveChannel(0)) == Delay(20, DriveChannel(0)) False ``` """ # 0. type check, we consider Instruction is a subtype of schedule if not isinstance(other, (type(self), Instruction)): return False # 1. channel check if set(self.channels) != set(other.channels): return False # 2. size check if len(self.instructions) != len(other.instructions): return False # 3. instruction check return all( self_inst == other_inst for self_inst, other_inst in zip(self.instructions, other.instructions) ) def __repr__(self) -> str: name = format(self._name) if self._name else "" instructions = ", ".join([repr(instr) for instr in self.instructions[:50]]) if len(self.instructions) > 25: instructions += ", ..." return f'{self.__class__.__name__}({instructions}, name="{name}")' def _require_schedule_conversion(function: Callable) -> Callable: """A method decorator to convert schedule block to pulse schedule. This conversation is performed for backward compatibility only if all durations are assigned. """ @functools.wraps(function) def wrapper(self, *args, **kwargs): from qiskit.pulse.transforms import block_to_schedule return function(block_to_schedule(self), *args, **kwargs) return wrapper class ScheduleBlock: """Time-ordered sequence of instructions with alignment context. :class:`.ScheduleBlock` supports lazy scheduling of context instructions, i.e. their timeslots is always generated at runtime. This indicates we can parametrize instruction durations as well as other parameters. In contrast to :class:`.Schedule` being somewhat static, :class:`.ScheduleBlock` is a dynamic representation of a pulse program. .. rubric:: Pulse Builder The Qiskit pulse builder is a domain specific language that is developed on top of the schedule block. Use of the builder syntax will improve the workflow of pulse programming. See :ref:`pulse_builder` for a user guide. .. rubric:: Alignment contexts A schedule block is always relatively scheduled. Instead of taking individual instructions with absolute execution time ``t0``, the schedule block defines a context of scheduling and instructions under the same context are scheduled in the same manner (alignment). Several contexts are available in :ref:`pulse_alignments`. A schedule block is instantiated with one of these alignment contexts. The default context is :class:`AlignLeft`, for which all instructions are left-justified, in other words, meaning they use as-soon-as-possible scheduling. If you need an absolute-time interval in between instructions, you can explicitly insert :class:`~qiskit.pulse.instructions.Delay` instructions. .. rubric:: Nested blocks A schedule block can contain other nested blocks with different alignment contexts. This enables advanced scheduling, where a subset of instructions is locally scheduled in a different manner. Note that a :class:`.Schedule` instance cannot be directly added to a schedule block. To add a :class:`.Schedule` instance, wrap it in a :class:`.Call` instruction. This is implicitly performed when a schedule is added through the :ref:`pulse_builder`. .. rubric:: Unsupported operations Because the schedule block representation lacks timeslots, it cannot perform particular :class:`.Schedule` operations such as :meth:`insert` or :meth:`shift` that require instruction start time ``t0``. In addition, :meth:`exclude` and :meth:`filter` methods are not supported because these operations may identify the target instruction with ``t0``. Except for these operations, :class:`.ScheduleBlock` provides full compatibility with :class:`.Schedule`. .. rubric:: Subroutine The timeslots-free representation offers much greater flexibility for writing pulse programs. Because :class:`.ScheduleBlock` only cares about the ordering of the child blocks we can add an undefined pulse sequence as a subroutine of the main program. If your program contains the same sequence multiple times, this representation may reduce the memory footprint required by the program construction. Such a subroutine is realized by the special compiler directive :class:`~qiskit.pulse.instructions.Reference` that is defined by a unique set of reference key strings to the subroutine. The (executable) subroutine is separately stored in the main program. Appended reference directives are resolved when the main program is executed. Subroutines must be assigned through :meth:`assign_references` before execution. .. rubric:: Program Scoping When you call a subroutine from another subroutine, or append a schedule block to another schedule block, the management of references and parameters can be a hard task. Schedule block offers a convenient feature to help with this by automatically scoping the parameters and subroutines. .. code-block:: from qiskit import pulse from qiskit.circuit.parameter import Parameter amp1 = Parameter("amp") with pulse.build() as sched1: pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0)) print(sched1.scoped_parameters()) .. parsed-literal:: (Parameter(root::amp),) The :meth:`~ScheduleBlock.scoped_parameters` method returns all :class:`~.Parameter` objects defined in the schedule block. The parameter name is updated to reflect its scope information, i.e. where it is defined. The outer scope is called "root". Since the "amp" parameter is directly used in the current builder context, it is prefixed with "root". Note that the :class:`Parameter` object returned by :meth:`~ScheduleBlock.scoped_parameters` preserves the hidden `UUID`_ key, and thus the scoped name doesn't break references to the original :class:`Parameter`. You may want to call this program from another program. In this example, the program is called with the reference key "grand_child". You can call a subroutine without specifying a substantial program (like ``sched1`` above which we will assign later). .. code-block:: amp2 = Parameter("amp") with pulse.build() as sched2: with pulse.align_right(): pulse.reference("grand_child") pulse.play(pulse.Constant(200, amp2), pulse.DriveChannel(0)) print(sched2.scoped_parameters()) .. parsed-literal:: (Parameter(root::amp),) This only returns "root::amp" because the "grand_child" reference is unknown. Now you assign the actual pulse program to this reference. .. code-block:: sched2.assign_references({("grand_child", ): sched1}) print(sched2.scoped_parameters()) .. parsed-literal:: (Parameter(root::amp), Parameter(root::grand_child::amp)) Now you get two parameters "root::amp" and "root::grand_child::amp". The second parameter name indicates it is defined within the referred program "grand_child". The program calling the "grand_child" has a reference program description which is accessed through :attr:`ScheduleBlock.references`. .. code-block:: print(sched2.references) .. parsed-literal:: ReferenceManager: - ('grand_child',): ScheduleBlock(Play(Constant(duration=100, amp=amp,... Finally, you may want to call this program from another program. Here we try a different approach to define subroutine. Namely, we call a subroutine from the root program with the actual program ``sched2``. .. code-block:: amp3 = Parameter("amp") with pulse.build() as main: pulse.play(pulse.Constant(300, amp3), pulse.DriveChannel(0)) pulse.call(sched2, name="child") print(main.scoped_parameters()) .. parsed-literal:: (Parameter(root::amp), Parameter(root::child::amp), Parameter(root::child::grand_child::amp)) This implicitly creates a reference named "child" within the root program and assigns ``sched2`` to it. You get three parameters "root::amp", "root::child::amp", and "root::child::grand_child::amp". As you can see, each parameter name reflects the layer of calls from the root program. If you know the scope of a parameter, you can directly get the parameter object using :meth:`ScheduleBlock.search_parameters` as follows. .. code-block:: main.search_parameters("root::child::grand_child::amp") You can use a regular expression to specify the scope. The following returns the parameters defined within the scope of "ground_child" regardless of its parent scope. This is sometimes convenient if you want to extract parameters from a deeply nested program. .. code-block:: main.search_parameters("\\S::grand_child::amp") Note that the root program is only aware of its direct references. .. code-block:: print(main.references) .. parsed-literal:: ReferenceManager: - ('child',): ScheduleBlock(ScheduleBlock(ScheduleBlock(Play(Con... As you can see the main program cannot directly assign a subroutine to the "grand_child" because this subroutine is not called within the root program, i.e. it is indirectly called by "child". However, the returned :class:`.ReferenceManager` is a dict-like object, and you can still reach to "grand_child" via the "child" program with the following chained dict access. .. code-block:: main.references[("child", )].references[("grand_child", )] Note that :attr:`ScheduleBlock.parameters` and :meth:`ScheduleBlock.scoped_parameters()` still collect all parameters also from the subroutine once it's assigned. .. _UUID: https://docs.python.org/3/library/uuid.html#module-uuid """ __slots__ = ( "_parent", "_name", "_reference_manager", "_parameter_manager", "_alignment_context", "_blocks", "_metadata", ) # Prefix to use for auto naming. prefix = "block" # Counter to count instance number. instances_counter = itertools.count() def __init__( self, name: Optional[str] = None, metadata: Optional[dict] = None, alignment_context=None ): """Create an empty schedule block. Args: name: Name of this schedule. Defaults to an autogenerated string if not provided. metadata: Arbitrary key value metadata to associate with the schedule. This gets stored as free-form data in a dict in the :attr:`~qiskit.pulse.ScheduleBlock.metadata` attribute. It will not be directly used in the schedule. alignment_context (AlignmentKind): ``AlignmentKind`` instance that manages scheduling of instructions in this block. Raises: TypeError: if metadata is not a dict. """ from qiskit.pulse.parameter_manager import ParameterManager from qiskit.pulse.transforms import AlignLeft if name is None: name = self.prefix + str(next(self.instances_counter)) if sys.platform != "win32" and not is_main_process(): name += f"-{mp.current_process().pid}" # This points to the parent schedule object in the current scope. # Note that schedule block can be nested without referencing, e.g. .append(child_block), # and parent=None indicates the root program of the current scope. # The nested schedule block objects should not have _reference_manager and # should refer to the one of the root program. # This also means referenced program should be assigned to the root program, not to child. self._parent = None self._name = name self._parameter_manager = ParameterManager() self._reference_manager = ReferenceManager() self._alignment_context = alignment_context or AlignLeft() self._blocks = [] # get parameters from context self._parameter_manager.update_parameter_table(self._alignment_context) if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} @classmethod def initialize_from(cls, other_program: Any, name: Optional[str] = None) -> "ScheduleBlock": """Create new schedule object with metadata of another schedule object. Args: other_program: Qiskit program that provides metadata to new object. name: Name of new schedule. Name of ``block`` is used by default. Returns: New block object with name and metadata. Raises: PulseError: When ``other_program`` does not provide necessary information. """ try: name = name or other_program.name if other_program.metadata: metadata = other_program.metadata.copy() else: metadata = None try: alignment_context = other_program.alignment_context except AttributeError: alignment_context = None return cls(name=name, metadata=metadata, alignment_context=alignment_context) except AttributeError as ex: raise PulseError( f"{cls.__name__} cannot be initialized from the program data " f"{other_program.__class__.__name__}." ) from ex @property def name(self) -> str: """Return name of this schedule""" return self._name @property def metadata(self) -> Dict[str, Any]: """The user provided metadata associated with the schedule. User provided ``dict`` of metadata for the schedule. The metadata contents do not affect the semantics of the program but are used to influence the execution of the schedule. It is expected to be passed between all transforms of the schedule and that providers will associate any schedule metadata with the results it returns from the execution of that schedule. """ return self._metadata @metadata.setter def metadata(self, metadata): """Update the schedule metadata""" if not isinstance(metadata, dict) and metadata is not None: raise TypeError("Only a dictionary or None is accepted for schedule metadata") self._metadata = metadata or {} @property def alignment_context(self): """Return alignment instance that allocates block component to generate schedule.""" return self._alignment_context def is_schedulable(self) -> bool: """Return ``True`` if all durations are assigned.""" # check context assignment for context_param in self._alignment_context._context_params: if isinstance(context_param, ParameterExpression): return False # check duration assignment for elm in self.blocks: if isinstance(elm, ScheduleBlock): if not elm.is_schedulable(): return False else: try: if not isinstance(elm.duration, int): return False except UnassignedReferenceError: return False return True @property @_require_schedule_conversion def duration(self) -> int: """Duration of this schedule block.""" return self.duration @property def channels(self) -> Tuple[Channel]: """Returns channels that this schedule block uses.""" chans = set() for elm in self.blocks: if isinstance(elm, Reference): raise UnassignedReferenceError( f"This schedule contains unassigned reference {elm.ref_keys} " "and channels are ambiguous. Please assign the subroutine first." ) chans = chans | set(elm.channels) return tuple(chans) @property @_require_schedule_conversion def instructions(self) -> Tuple[Tuple[int, Instruction]]: """Get the time-ordered instructions from self.""" return self.instructions @property def blocks(self) -> Tuple["BlockComponent", ...]: """Get the block elements added to self. .. note:: The sequence of elements is returned in order of addition. Because the first element is schedule first, e.g. FIFO, the returned sequence is roughly time-ordered. However, in the parallel alignment context, especially in the as-late-as-possible scheduling, or :class:`.AlignRight` context, the actual timing of when the instructions are issued is unknown until the :class:`.ScheduleBlock` is scheduled and converted into a :class:`.Schedule`. """ blocks = [] for elm in self._blocks: if isinstance(elm, Reference): elm = self.references.get(elm.ref_keys, None) or elm blocks.append(elm) return tuple(blocks) @property def parameters(self) -> Set[Parameter]: """Return unassigned parameters with raw names.""" # Need new object not to mutate parameter_manager.parameters out_params = set() out_params |= self._parameter_manager.parameters for subroutine in self.references.values(): if subroutine is None: continue out_params |= subroutine.parameters return out_params def scoped_parameters(self) -> Tuple[Parameter]: """Return unassigned parameters with scoped names. .. note:: If a parameter is defined within a nested scope, it is prefixed with all parent-scope names with the delimiter string, which is "::". If a reference key of the scope consists of multiple key strings, it will be represented by a single string joined with ",". For example, "root::xgate,q0::amp" for the parameter "amp" defined in the reference specified by the key strings ("xgate", "q0"). """ return tuple( sorted( _collect_scoped_parameters(self, current_scope="root").values(), key=lambda p: p.name, ) ) @property def references(self) -> ReferenceManager: """Return a reference manager of the current scope.""" if self._parent is not None: return self._parent.references return self._reference_manager @_require_schedule_conversion def ch_duration(self, *channels: Channel) -> int: """Return the time of the end of the last instruction over the supplied channels. Args: *channels: Channels within ``self`` to include. """ return self.ch_duration(*channels) def append( self, block: "BlockComponent", name: Optional[str] = None, inplace: bool = True ) -> "ScheduleBlock": """Return a new schedule block with ``block`` appended to the context block. The execution time is automatically assigned when the block is converted into schedule. Args: block: ScheduleBlock to be appended. name: Name of the new ``Schedule``. Defaults to name of ``self``. inplace: Perform operation inplace on this schedule. Otherwise, return a new ``Schedule``. Returns: Schedule block with appended schedule. Raises: PulseError: When invalid schedule type is specified. """ if not isinstance(block, (ScheduleBlock, Instruction)): raise PulseError( f"Appended `schedule` {block.__class__.__name__} is invalid type. " "Only `Instruction` and `ScheduleBlock` can be accepted." ) if not inplace: schedule = copy.deepcopy(self) schedule._name = name or self.name schedule.append(block, inplace=True) return schedule if isinstance(block, Reference) and block.ref_keys not in self.references: self.references[block.ref_keys] = None elif isinstance(block, ScheduleBlock): block = copy.deepcopy(block) # Expose subroutines to the current main scope. # Note that this 'block' is not called. # The block is just directly appended to the current scope. if block.is_referenced(): if block._parent is not None: # This is an edge case: # If this is not a parent, block.references points to the parent's reference # where subroutine not referred within the 'block' may exist. # Move only references existing in the 'block'. # See 'test.python.pulse.test_reference.TestReference.test_appending_child_block' for ref in _get_references(block._blocks): self.references[ref.ref_keys] = block.references[ref.ref_keys] else: # Avoid using dict.update and explicitly call __set_item__ for validation. # Reference manager of appended block is cleared because of data reduction. for ref_keys, ref in block._reference_manager.items(): self.references[ref_keys] = ref block._reference_manager.clear() # Now switch the parent because block is appended to self. block._parent = self self._blocks.append(block) self._parameter_manager.update_parameter_table(block) return self def filter( self, *filter_funcs: List[Callable], channels: Optional[Iterable[Channel]] = None, instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None, check_subroutine: bool = True, ): """Return a new ``ScheduleBlock`` with only the instructions from this ``ScheduleBlock`` which pass though the provided filters; i.e. an instruction will be retained if every function in ``filter_funcs`` returns ``True``, the instruction occurs on a channel type contained in ``channels``, and the instruction type is contained in ``instruction_types``. .. warning:: Because ``ScheduleBlock`` is not aware of the execution time of the context instructions, filtering out some instructions may change the execution time of the remaining instructions. If no arguments are provided, ``self`` is returned. Args: filter_funcs: A list of Callables which take a ``Instruction`` and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. check_subroutine: Set `True` to individually filter instructions inside a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. Returns: ``ScheduleBlock`` consisting of instructions that matches with filtering condition. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=False, recurse_subroutines=check_subroutine ) def exclude( self, *filter_funcs: List[Callable], channels: Optional[Iterable[Channel]] = None, instruction_types: Union[Iterable[abc.ABCMeta], abc.ABCMeta] = None, check_subroutine: bool = True, ): """Return a new ``ScheduleBlock`` with only the instructions from this ``ScheduleBlock`` *failing* at least one of the provided filters. This method is the complement of py:meth:`~self.filter`, so that:: self.filter(args) + self.exclude(args) == self in terms of instructions included. .. warning:: Because ``ScheduleBlock`` is not aware of the execution time of the context instructions, excluding some instructions may change the execution time of the remaining instructions. Args: filter_funcs: A list of Callables which take a ``Instruction`` and return a bool. channels: For example, ``[DriveChannel(0), AcquireChannel(0)]``. instruction_types: For example, ``[PulseInstruction, AcquireInstruction]``. check_subroutine: Set `True` to individually filter instructions inside of a subroutine defined by the :py:class:`~qiskit.pulse.instructions.Call` instruction. Returns: ``ScheduleBlock`` consisting of instructions that do not match with at least one of filtering conditions. """ from qiskit.pulse.filters import composite_filter, filter_instructions filters = composite_filter(channels, instruction_types) filters.extend(filter_funcs) return filter_instructions( self, filters=filters, negate=True, recurse_subroutines=check_subroutine ) def replace( self, old: "BlockComponent", new: "BlockComponent", inplace: bool = True, ) -> "ScheduleBlock": """Return a ``ScheduleBlock`` with the ``old`` component replaced with a ``new`` component. Args: old: Schedule block component to replace. new: Schedule block component to replace with. inplace: Replace instruction by mutably modifying this ``ScheduleBlock``. Returns: The modified schedule block with ``old`` replaced by ``new``. """ if not inplace: schedule = copy.deepcopy(self) return schedule.replace(old, new, inplace=True) if old not in self._blocks: # Avoid unnecessary update of reference and parameter manager return self # Temporarily copies references all_references = ReferenceManager() if isinstance(new, ScheduleBlock): new = copy.deepcopy(new) all_references.update(new.references) new._reference_manager.clear() new._parent = self for ref_key, subroutine in self.references.items(): if ref_key in all_references: warnings.warn( f"Reference {ref_key} conflicts with substituted program {new.name}. " "Existing reference has been replaced with new reference.", UserWarning, ) continue all_references[ref_key] = subroutine # Regenerate parameter table by regenerating elements. # Note that removal of parameters in old is not sufficient, # because corresponding parameters might be also used in another block element. self._parameter_manager.clear() self._parameter_manager.update_parameter_table(self._alignment_context) new_elms = [] for elm in self._blocks: if elm == old: elm = new self._parameter_manager.update_parameter_table(elm) new_elms.append(elm) self._blocks = new_elms # Regenerate reference table # Note that reference is attached to the outer schedule if nested. # Thus, this investigates all references within the scope. self.references.clear() root = self while root._parent is not None: root = root._parent for ref in _get_references(root._blocks): self.references[ref.ref_keys] = all_references[ref.ref_keys] return self def is_parameterized(self) -> bool: """Return True iff the instruction is parameterized.""" return any(self.parameters) def is_referenced(self) -> bool: """Return True iff the current schedule block contains reference to subroutine.""" return len(self.references) > 0 def assign_parameters( self, value_dict: Dict[ParameterExpression, ParameterValueType], inplace: bool = True, ) -> "ScheduleBlock": """Assign the parameters in this schedule according to the input. Args: value_dict: A mapping from Parameters to either numeric values or another Parameter expression. inplace: Set ``True`` to override this instance with new parameter. Returns: Schedule with updated parameters. Raises: PulseError: When the block is nested into another block. """ if not inplace: new_schedule = copy.deepcopy(self) return new_schedule.assign_parameters(value_dict, inplace=True) # Update parameters in the current scope self._parameter_manager.assign_parameters(pulse_program=self, value_dict=value_dict) for subroutine in self._reference_manager.values(): # Also assigning parameters to the references associated with self. # Note that references are always stored in the root program. # So calling assign_parameters from nested block doesn't update references. if subroutine is None: continue subroutine.assign_parameters(value_dict=value_dict, inplace=True) return self def assign_references( self, subroutine_dict: Dict[Union[str, Tuple[str, ...]], "ScheduleBlock"], inplace: bool = True, ) -> "ScheduleBlock": """Assign schedules to references. It is only capable of assigning a schedule block to immediate references which are directly referred within the current scope. Let's see following example: .. code-block:: python from qiskit import pulse with pulse.build() as subroutine: pulse.delay(10, pulse.DriveChannel(0)) with pulse.build() as sub_prog: pulse.reference("A") with pulse.build() as main_prog: pulse.reference("B") In above example, the ``main_prog`` can refer to the subroutine "root::B" and the reference of "B" to program "A", i.e., "B::A", is not defined in the root namespace. This prevents breaking the reference "root::B::A" by the assignment of "root::B". For example, if a user could indirectly assign "root::B::A" from the root program, one can later assign another program to "root::B" that doesn't contain "A" within it. In this situation, a reference "root::B::A" would still live in the reference manager of the root. However, the subroutine "root::B::A" would no longer be used in the actual pulse program. To assign subroutine "A" to ``nested_prog`` as a nested subprogram of ``main_prog``, you must first assign "A" of the ``sub_prog``, and then assign the ``sub_prog`` to the ``main_prog``. .. code-block:: python sub_prog.assign_references({("A", ): nested_prog}, inplace=True) main_prog.assign_references({("B", ): sub_prog}, inplace=True) Alternatively, you can also write .. code-block:: python main_prog.assign_references({("B", ): sub_prog}, inplace=True) main_prog.references[("B", )].assign_references({"A": nested_prog}, inplace=True) Here :attr:`.references` returns a dict-like object, and you can mutably update the nested reference of the particular subroutine. .. note:: Assigned programs are deep-copied to prevent an unexpected update. Args: subroutine_dict: A mapping from reference key to schedule block of the subroutine. inplace: Set ``True`` to override this instance with new subroutine. Returns: Schedule block with assigned subroutine. Raises: PulseError: When reference key is not defined in the current scope. """ if not inplace: new_schedule = copy.deepcopy(self) return new_schedule.assign_references(subroutine_dict, inplace=True) for key, subroutine in subroutine_dict.items(): if key not in self.references: unassigned_keys = ", ".join(map(repr, self.references.unassigned())) raise PulseError( f"Reference instruction with {key} doesn't exist " f"in the current scope: {unassigned_keys}" ) self.references[key] = copy.deepcopy(subroutine) return self def get_parameters(self, parameter_name: str) -> List[Parameter]: """Get parameter object bound to this schedule by string name. Note that we can define different parameter objects with the same name, because these different objects are identified by their unique uuid. For example, .. code-block:: python from qiskit import pulse, circuit amp1 = circuit.Parameter("amp") amp2 = circuit.Parameter("amp") with pulse.build() as sub_prog: pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(sub_prog, name="sub") pulse.play(pulse.Constant(100, amp2), pulse.DriveChannel(0)) main_prog.get_parameters("amp") This returns a list of two parameters ``amp1`` and ``amp2``. Args: parameter_name: Name of parameter. Returns: Parameter objects that have corresponding name. """ matched = [p for p in self.parameters if p.name == parameter_name] return matched def search_parameters(self, parameter_regex: str) -> List[Parameter]: """Search parameter with regular expression. This method looks for the scope-aware parameters. For example, .. code-block:: python from qiskit import pulse, circuit amp1 = circuit.Parameter("amp") amp2 = circuit.Parameter("amp") with pulse.build() as sub_prog: pulse.play(pulse.Constant(100, amp1), pulse.DriveChannel(0)) with pulse.build() as main_prog: pulse.call(sub_prog, name="sub") pulse.play(pulse.Constant(100, amp2), pulse.DriveChannel(0)) main_prog.search_parameters("root::sub::amp") This finds ``amp1`` with scoped name "root::sub::amp". Args: parameter_regex: Regular expression for scoped parameter name. Returns: Parameter objects that have corresponding name. """ pattern = re.compile(parameter_regex) return sorted( _collect_scoped_parameters(self, current_scope="root", filter_regex=pattern).values(), key=lambda p: p.name, ) def __len__(self) -> int: """Return number of instructions in the schedule.""" return len(self.blocks) def __eq__(self, other: "ScheduleBlock") -> bool: """Test if two ScheduleBlocks are equal. Equality is checked by verifying there is an equal instruction at every time in ``other`` for every instruction in this ``ScheduleBlock``. This check is performed by converting the instruction representation into directed acyclic graph, in which execution order of every instruction is evaluated correctly across all channels. Also ``self`` and ``other`` should have the same alignment context. .. warning:: This does not check for logical equivalency. Ie., ```python >>> Delay(10, DriveChannel(0)) + Delay(10, DriveChannel(0)) == Delay(20, DriveChannel(0)) False ``` """ # 0. type check if not isinstance(other, type(self)): return False # 1. transformation check if self.alignment_context != other.alignment_context: return False # 2. size check if len(self) != len(other): return False # 3. instruction check with alignment from qiskit.pulse.transforms.dag import block_to_dag as dag if not rx.is_isomorphic_node_match(dag(self), dag(other), lambda x, y: x == y): return False return True def __repr__(self) -> str: name = format(self._name) if self._name else "" blocks = ", ".join([repr(instr) for instr in self.blocks[:50]]) if len(self.blocks) > 25: blocks += ", ..." return '{}({}, name="{}", transform={})'.format( self.__class__.__name__, blocks, name, repr(self.alignment_context) ) def __add__(self, other: "BlockComponent") -> "ScheduleBlock": """Return a new schedule with ``other`` inserted within ``self`` at ``start_time``.""" return self.append(other) def _common_method(*classes): """A function decorator to attach the function to specified classes as a method. .. note:: For developer: A method attached through this decorator may hurt readability of the codebase, because the method may not be detected by a code editor. Thus, this decorator should be used to a limited extent, i.e. huge helper method. By using this decorator wisely, we can reduce code maintenance overhead without losing readability of the codebase. """ def decorator(method): @functools.wraps(method) def wrapper(*args, **kwargs): return method(*args, **kwargs) for cls in classes: setattr(cls, method.__name__, wrapper) return method return decorator @_common_method(Schedule, ScheduleBlock) def draw( self, style: Optional[Dict[str, Any]] = None, backend=None, # importing backend causes cyclic import time_range: Optional[Tuple[int, int]] = None, time_unit: str = "dt", disable_channels: Optional[List[Channel]] = None, show_snapshot: bool = True, show_framechange: bool = True, show_waveform_info: bool = True, show_barrier: bool = True, plotter: str = "mpl2d", axis: Optional[Any] = None, ): """Plot the schedule. Args: style: Stylesheet options. This can be dictionary or preset stylesheet classes. See :py:class:`~qiskit.visualization.pulse_v2.stylesheets.IQXStandard`, :py:class:`~qiskit.visualization.pulse_v2.stylesheets.IQXSimple`, and :py:class:`~qiskit.visualization.pulse_v2.stylesheets.IQXDebugging` for details of preset stylesheets. backend (Optional[BaseBackend]): Backend object to play the input pulse program. If provided, the plotter may use to make the visualization hardware aware. time_range: Set horizontal axis limit. Tuple `(tmin, tmax)`. time_unit: The unit of specified time range either `dt` or `ns`. The unit of `ns` is available only when `backend` object is provided. disable_channels: A control property to show specific pulse channel. Pulse channel instances provided as a list are not shown in the output image. show_snapshot: Show snapshot instructions. show_framechange: Show frame change instructions. The frame change represents instructions that modulate phase or frequency of pulse channels. show_waveform_info: Show additional information about waveforms such as their name. show_barrier: Show barrier lines. plotter: Name of plotter API to generate an output image. One of following APIs should be specified:: mpl2d: Matplotlib API for 2D image generation. Matplotlib API to generate 2D image. Charts are placed along y axis with vertical offset. This API takes matplotlib.axes.Axes as ``axis`` input. ``axis`` and ``style`` kwargs may depend on the plotter. axis: Arbitrary object passed to the plotter. If this object is provided, the plotters use a given ``axis`` instead of internally initializing a figure object. This object format depends on the plotter. See plotter argument for details. Returns: Visualization output data. The returned data type depends on the ``plotter``. If matplotlib family is specified, this will be a ``matplotlib.pyplot.Figure`` data. """ # pylint: disable=cyclic-import from qiskit.visualization import pulse_drawer return pulse_drawer( program=self, style=style, backend=backend, time_range=time_range, time_unit=time_unit, disable_channels=disable_channels, show_snapshot=show_snapshot, show_framechange=show_framechange, show_waveform_info=show_waveform_info, show_barrier=show_barrier, plotter=plotter, axis=axis, ) def _interval_index(intervals: List[Interval], interval: Interval) -> int: """Find the index of an interval. Args: intervals: A sorted list of non-overlapping Intervals. interval: The interval for which the index into intervals will be found. Returns: The index of the interval. Raises: PulseError: If the interval does not exist. """ index = _locate_interval_index(intervals, interval) found_interval = intervals[index] if found_interval != interval: raise PulseError(f"The interval: {interval} does not exist in intervals: {intervals}") return index def _locate_interval_index(intervals: List[Interval], interval: Interval, index: int = 0) -> int: """Using binary search on start times, find an interval. Args: intervals: A sorted list of non-overlapping Intervals. interval: The interval for which the index into intervals will be found. index: A running tally of the index, for recursion. The user should not pass a value. Returns: The index into intervals that new_interval would be inserted to maintain a sorted list of intervals. """ if not intervals or len(intervals) == 1: return index mid_idx = len(intervals) // 2 mid = intervals[mid_idx] if interval[1] <= mid[0] and (interval != mid): return _locate_interval_index(intervals[:mid_idx], interval, index=index) else: return _locate_interval_index(intervals[mid_idx:], interval, index=index + mid_idx) def _find_insertion_index(intervals: List[Interval], new_interval: Interval) -> int: """Using binary search on start times, return the index into `intervals` where the new interval belongs, or raise an error if the new interval overlaps with any existing ones. Args: intervals: A sorted list of non-overlapping Intervals. new_interval: The interval for which the index into intervals will be found. Returns: The index into intervals that new_interval should be inserted to maintain a sorted list of intervals. Raises: PulseError: If new_interval overlaps with the given intervals. """ index = _locate_interval_index(intervals, new_interval) if index < len(intervals): if _overlaps(intervals[index], new_interval): raise PulseError("New interval overlaps with existing.") return index if new_interval[1] <= intervals[index][0] else index + 1 return index def _overlaps(first: Interval, second: Interval) -> bool: """Return True iff first and second overlap. Note: first.stop may equal second.start, since Interval stop times are exclusive. """ if first[0] == second[0] == second[1]: # They fail to overlap if one of the intervals has duration 0 return False if first[0] > second[0]: first, second = second, first return second[0] < first[1] def _check_nonnegative_timeslot(timeslots: TimeSlots): """Test that a channel has no negative timeslots. Raises: PulseError: If a channel timeslot is negative. """ for chan, chan_timeslots in timeslots.items(): if chan_timeslots: if chan_timeslots[0][0] < 0: raise PulseError(f"An instruction on {chan} has a negative starting time.") def _get_timeslots(schedule: "ScheduleComponent") -> TimeSlots: """Generate timeslots from given schedule component. Args: schedule: Input schedule component. Raises: PulseError: When invalid schedule type is specified. """ if isinstance(schedule, Instruction): duration = schedule.duration instruction_duration_validation(duration) timeslots = {channel: [(0, duration)] for channel in schedule.channels} elif isinstance(schedule, Schedule): timeslots = schedule.timeslots else: raise PulseError(f"Invalid schedule type {type(schedule)} is specified.") return timeslots def _get_references(block_elms: List["BlockComponent"]) -> Set[Reference]: """Recursively get reference instructions in the current scope. Args: block_elms: List of schedule block elements to investigate. Returns: A set of unique reference instructions. """ references = set() for elm in block_elms: if isinstance(elm, ScheduleBlock): references |= _get_references(elm._blocks) elif isinstance(elm, Reference): references.add(elm) return references def _collect_scoped_parameters( schedule: ScheduleBlock, current_scope: str, filter_regex: Optional[re.Pattern] = None, ) -> Dict[Tuple[str, int], Parameter]: """A helper function to collect parameters from all references in scope-aware fashion. Parameter object is renamed with attached scope information but its UUID is remained. This means object is treated identically on the assignment logic. This function returns a dictionary of all parameters existing in the target program including its reference, which is keyed on the unique identifier consisting of scoped parameter name and parameter object UUID. This logic prevents parameter clash in the different scope. For example, when two parameter objects with the same UUID exist in different references, both of them appear in the output dictionary, even though they are technically the same object. This feature is particularly convenient to search parameter object with associated scope. Args: schedule: Schedule to get parameters. current_scope: Name of scope where schedule exist. filter_regex: Optional. Compiled regex to sort parameter by name. Returns: A dictionary of scoped parameter objects. """ parameters_out = {} for param in schedule._parameter_manager.parameters: new_name = f"{current_scope}{Reference.scope_delimiter}{param.name}" if filter_regex and not re.search(filter_regex, new_name): continue scoped_param = Parameter.__new__(Parameter, new_name, uuid=getattr(param, "_uuid")) scoped_param.__init__(new_name) unique_key = new_name, hash(param) parameters_out[unique_key] = scoped_param for sub_namespace, subroutine in schedule.references.items(): if subroutine is None: continue composite_key = Reference.key_delimiter.join(sub_namespace) full_path = f"{current_scope}{Reference.scope_delimiter}{composite_key}" sub_parameters = _collect_scoped_parameters( subroutine, current_scope=full_path, filter_regex=filter_regex ) parameters_out.update(sub_parameters) return parameters_out # These type aliases are defined at the bottom of the file, because as of 2022-01-18 they are # imported into other parts of Terra. Previously, the aliases were at the top of the file and used # forwards references within themselves. This was fine within the same file, but causes scoping # issues when the aliases are imported into different scopes, in which the `ForwardRef` instances # would no longer resolve. Instead, we only use forward references in the annotations of _this_ # file to reference the aliases, which are guaranteed to resolve in scope, so the aliases can all be # concrete. ScheduleComponent = Union[Schedule, Instruction] """An element that composes a pulse schedule.""" BlockComponent = Union[ScheduleBlock, Instruction] """An element that composes a pulse schedule block."""
https://github.com/theflyingrahul/qiskitsummerschool2020
theflyingrahul
!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/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np from qiskit import QuantumCircuit from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2 pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits) pw_approximation._build() qc = QuantumCircuit(pw_approximation.num_qubits) qc.h(list(range(num_state_qubits))) qc.append(pw_approximation.to_instruction(), qc.qubits) qc.draw(output='mpl')
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts # 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("./") 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] # scale_factors = [1.0, 2.0, 3.0] # Initialize quantum circuit for 3 qubits qr = QuantumRegister(num_qubits, name="lq") 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(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"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors) print("created zne_qcs (length:", len(zne_qcs), ")") 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-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors=scale_factors, fac_type="lin") target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_right(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=80 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog.draw()
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ QasmSimulator Integration Tests for circuit library standard gates """ from ddt import ddt, unpack, data from numpy.random import default_rng from qiskit import execute from qiskit.quantum_info import Statevector, state_fidelity from qiskit.providers.qrack import QasmSimulator # from qiskit.providers.aer.extensions import * from qiskit.circuit.library.standard_gates import ( CXGate, CYGate, CZGate, DCXGate, HGate, IGate, SGate, SXGate, SXdgGate, SdgGate, SwapGate, XGate, YGate, ZGate, TGate, TdgGate, iSwapGate, C3XGate, C4XGate, CCXGate, CHGate, CSXGate, CSwapGate, CPhaseGate, CRXGate, CRYGate, CRZGate, CU1Gate, CU3Gate, CUGate, PhaseGate, RC3XGate, RCCXGate, RGate, RXGate, RXXGate, RYGate, RYYGate, RZGate, RZXGate, RZZGate, U1Gate, U2Gate, U3Gate, UGate) GATES = [ # Clifford Gates (CXGate, 0), (CYGate, 0), (CZGate, 0), (DCXGate, 0), (HGate, 0), (IGate, 0), (SGate, 0), (SXGate, 0), (SXdgGate, 0), (SdgGate, 0), (SwapGate, 0), (XGate, 0), (YGate, 0), (ZGate, 0), (TGate, 0), # Non-Clifford Gates (TdgGate, 0), (iSwapGate, 0), (C3XGate, 0), (C4XGate, 0), (CCXGate, 0), (CHGate, 0), (CSXGate, 0), (CSwapGate, 0), # Parameterized Gates (CPhaseGate, 1), (CRXGate, 1), (CRYGate, 1), (CRZGate, 1), (CU1Gate, 1), (CU3Gate, 3), (CUGate, 4), (PhaseGate, 1), (RC3XGate, 0), (RCCXGate, 0), (RGate, 2), (RXGate, 1), (RXXGate, 1), (RYGate, 1), (RYYGate, 1), (RZGate, 1), (RZXGate, 1), (RZZGate, 1), (U1Gate, 1), (U2Gate, 2), (U3Gate, 3), (UGate, 3) ] @ddt class QasmStandardGateStatevectorTests: """QasmSimulator standard gate library tests.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} SEED = 8181 RNG = default_rng(seed=SEED) @data(*GATES) @unpack def test_gate_statevector(self, gate_cls, num_params): """Test standard gate simulation test.""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'matrix_product_state' ] circuit = self.gate_circuit(gate_cls, num_params=num_params, rng=self.RNG) target = Statevector.from_instruction(circuit) # Add snapshot and execute #circuit.snapshot_statevector('final') backend_options = self.BACKEND_OPTS method = backend_options.pop('method', 'automatic') backend = self.SIMULATOR backend.set_options(method=method) result = execute(circuit, backend, shots=1, **backend_options).result() # Check results success = getattr(result, 'success', False) msg = '{}, method = {}'.format(gate_cls.__name__, method) if method not in SUPPORTED_METHODS: self.assertFalse(success) else: self.assertTrue(success, msg=msg) self.assertSuccess(result) #snapshots = result.data(0).get("snapshots", {}).get("statevector", {}) #value = snapshots.get('final', [None])[0] #fidelity = state_fidelity(target, value) #self.assertGreater(fidelity, 0.99999, msg=msg) @ddt class QasmStandardGateDensityMatrixTests: """QasmSimulator standard gate library tests.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} SEED = 9997 RNG = default_rng(seed=SEED) @data(*GATES) @unpack def test_gate_density_matrix(self, gate_cls, num_params): """Test standard gate simulation test.""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'density_matrix', 'density_matrix_gpu', 'density_matrix_thrust' ] circuit = self.gate_circuit(gate_cls, num_params=num_params, rng=self.RNG) target = Statevector.from_instruction(circuit) # Add snapshot and execute #circuit.snapshot_density_matrix('final') backend_options = self.BACKEND_OPTS method = backend_options.pop('method', 'automatic') backend = self.SIMULATOR backend.set_options(method=method) result = execute(circuit, backend, shots=1, **backend_options).result() # Check results success = getattr(result, 'success', False) msg = '{}, method = {}'.format(gate_cls.__name__, method) if method not in SUPPORTED_METHODS: self.assertFalse(success) else: self.assertTrue(success, msg=msg) self.assertSuccess(result) #snapshots = result.data(0).get("snapshots", # {}).get("density_matrix", {}) #value = snapshots.get('final', [{'value': None}])[0]['value'] #fidelity = state_fidelity(target, value) #self.assertGreater(fidelity, 0.99999, msg=msg)
https://github.com/apozas/qaoa-color
apozas
from qiskit.tools.visualization import plot_histogram import matplotlib.pyplot as plt import numpy as np import numpy.random as rand import networkx as nx from random_graph import random_graph from itertools import product from ast import literal_eval import qutip as qt import os def get_probs(filename): with open(filename) as file: amplitudes = file.read() result = [[literal_eval(amplitude)] for amplitude in amplitudes[1:].split('\n ')] n_qubits = int(np.log2(len(result))) q_state = qt.Qobj(result, dims=[[2]*n_qubits, [1]*n_qubits]) prob_vector = np.abs(q_state.full())**2 n_qubits = len(q_state.dims[0]) strings = product('01', repeat=n_qubits) return {''.join(string): prob[0] for string, prob in zip(strings, prob_vector)} def draw_best_coloring_2colors(probs, edges): labels = list(probs.keys()) probabilities = list(probs.values()) best_prob = np.max(probabilities) best_coloring = labels[np.argmax(probabilities)].replace('0', 'r').replace('1', 'b') print('Probability of coloring: ' + str(np.round(best_prob, 4))) nx.draw(nx.Graph(edges), node_color=best_coloring, with_labels=False) def draw_best_coloring_4colors(probs, edges): labels = list(probs.keys()) probabilities = list(probs.values()) best_prob = np.max(probabilities) best_coloring = labels[np.argmax(probabilities)] best_colors = [best_coloring[2*i:2*(i+1)] for i in range(int(len(best_coloring) / 2))] color_dict = {'00': 'r', '01': 'g', '10': 'b', '11': 'k'} best_colors =[color_dict[color] for color in best_colors] print('Probability of coloring: ' + str(np.round(best_prob, 4))) nx.draw(nx.Graph(edges), node_color=best_colors, with_labels=False) to_graph_2colors = [file for file in os.listdir('results') if (file[-10:] == 'binary.txt') and (file.split('_')[2] == '2colors')] to_graph_4colors = [file for file in os.listdir('results') if (file[-10:] == 'binary.txt') and (file.split('_')[2] == '4colors')] structures_2colors = [file.split('_')[1] for file in to_graph_2colors] structures_4colors = [file.split('_')[1] for file in to_graph_4colors] graphs = {'triang': [(0, 1), (1, 2), (2, 0)], 'line': [(0, 1), (1, 2), (2, 3)], 'square1diag': [(0, 1), (1, 2), (2, 3), (3, 0), (0, 2)]} for graph, structure in zip(to_graph_2colors, structures_2colors): probs = get_probs('results/' + graph) print('---------------' + graph[:-11] + '---------------') draw_best_coloring_2colors(probs, graphs[structure]) plt.show() for graph, structure in zip(to_graph_4colors, structures_4colors): probs = get_probs('results/' + graph) print('---------------' + graph[:-11] + '---------------') draw_best_coloring_4colors(probs, graphs[structure]) plt.show()
https://github.com/abbarreto/qiskit3
abbarreto
%run init.ipynb c00,c01,c10,c11 = symbols('c_{00} c_{01} c_{10} c_{11}') psiAB = Matrix([[c00],[c01],[c10],[c11]]); psiAB rhoAB = psiAB*conjugate(psiAB.T); rhoAB rhoA = ptraceB(2,2,rhoAB); rhoB = ptraceA(2,2,rhoAB) rhoA, rhoB pauli(3)*pauli(1)*pauli(3), pauli(3)*pauli(2)*pauli(3), comm(pauli(3),pauli(1)), comm(pauli(3),pauli(2)) %run init.ipynb def pTraceL_num(dl, dr, 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): 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 def coh_l1(rho): d = rho.shape[0]; C = 0 for j in range(0,d-1): for k in range(j+1,d): C += np.abs(rho[j,k]) return 2*C from numpy import linalg as LA def Econc_(rho): s2 = np.array([[0,-1j],[1j,0]]) R = rho@np.kron(s2,s2)@np.matrix.conjugate(rho)@np.kron(s2,s2) w, v = LA.eig(R) evm = max(abs(w[0]), abs(w[1]), abs(w[2]), abs(w[3])) Ec = 2*math.sqrt(abs(evm)) - math.sqrt(abs(w[0])) - math.sqrt(abs(w[1]))\ - math.sqrt(abs(w[2])) - math.sqrt(abs(w[3])) if Ec < 0.0: Ec = 0.0 return Ec import scipy.linalg.lapack as lapak def Econc(rho): s2 = np.array([[0,-1j],[1j,0]]) R = rho@np.kron(s2,s2)@np.matrix.conjugate(rho)@np.kron(s2,s2) ev = lapak.zheevd(R) evm = max(abs(ev[0][0]), abs(ev[0][1]), abs(ev[0][2]), abs(ev[0][3])) Ec = 2*math.sqrt(abs(evm)) - math.sqrt(abs(ev[0][0])) - math.sqrt(abs(ev[0][1]))\ - math.sqrt(abs(ev[0][2])) - math.sqrt(abs(ev[0][3])) if Ec < 0.0: Ec = 0.0 return Ec def concurrence_psi(rho): rho_r = pTraceL_num(2,2,rho) return math.sqrt(2*abs(1-np.matrix.trace(rho_r@rho_r))) def predict_jb(rho): return abs(rho[0,0]-rho[1,1]) import qiskit from qiskit import * nshots = 8192 IBMQ.load_account() #provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main') provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibmq_manila') 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 q_exp = np.arange(0,1.1,0.1); N = len(q_exp) th_xi = np.zeros(N); th_xi = 2*np.arccos(np.sqrt(1-q_exp)) th_eta = np.zeros(N); th_eta = 2*np.arccos(np.sqrt(q_exp)) E_sim_10 = np.zeros(N); C_sim_0 = np.zeros(N); P_sim_0 = np.zeros(N) jobs_ids = [] for j in range(0,N): qr = QuantumRegister(5); qc = QuantumCircuit(qr) # prepara xi qc.u(th_xi[j],0,0,qr[1]) qc.cx(qr[1],qr[2]) qc.h([qr[1],qr[2]]) # prepara eta qc.u(th_eta[j],0,0,qr[3]) qc.cx(qr[3],qr[4]) qc.h([qr[3],qr[4]]) # tomografia qstc = state_tomography_circuits(qc, [qr[1],qr[2]]) job_sim = qiskit.execute(qstc, backend = simulator, shots=nshots) qstf_sim = StateTomographyFitter(job_sim.result(), qstc) rho_10_sim = qstf_sim.fit(method='lstsq') E_sim_10[j] = concurrence_psi(rho_10_sim) rho_0_sim = pTraceL_num(2, 2, rho_10_sim) C_sim_0[j] = coh_l1(rho_0_sim) P_sim_0[j] = predict_jb(rho_0_sim) qc.draw(output='mpl') q_exp = np.arange(0,1.1,0.1); N = len(q_exp) th_xi = np.zeros(N); th_xi = 2*np.arccos(np.sqrt(1-q_exp)) th_eta = np.zeros(N); th_eta = 2*np.arccos(np.sqrt(q_exp)) jobs_ids = [] for j in range(0,N): qr = QuantumRegister(5); qc = QuantumCircuit(qr) # prepara xi qc.u(th_xi[j],0,0,qr[1]) qc.cx(qr[1],qr[2]) qc.h([qr[1],qr[2]]) # prepara eta qc.u(th_eta[j],0,0,qr[3]) qc.cx(qr[3],qr[4]) qc.h([qr[3],qr[4]]) # tomografia qstc = state_tomography_circuits(qc, [qr[1],qr[2]]) job_exp = qiskit.execute(qstc, backend = device, shots=nshots) jobs_ids.append(job_exp.job_id()) print(job_exp.job_id()) job_monitor(job_exp) print(jobs_ids) f = open("jobs_ids_ES_pre_bbm.txt", "w") f.write(str(jobs_ids)) f.close() f = open("jobs_ids_ES_pre_bbm.txt","r") #jobs_ids_list = f.read() list_ids = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",") f.close() list_ids[0] print(list_ids) print(jobs_ids_list) len_ids = len('6368049443e1f0708afdaf73') print(len_ids) list_ids = [] for j in range(0,N): s = 0 if j > 0: s = 2 print(jobs_ids_list[(j*(len_ids+2+s)+2):(j+1)*(len_ids+2)+j*s]) list_ids.append(jobs_ids_list[(j*(len_ids+2+s)+2):(j+1)*(len_ids+2)+j*s]) list_ids[0] q_exp = np.arange(0,1.1,0.1); N = len(q_exp) E_exp_10 = np.zeros(N); C_exp_0 = np.zeros(N); P_exp_0 = np.zeros(N) for j in range(0,N): job = device.retrieve_job(list_ids[j]) qstf_exp = StateTomographyFitter(job.result(), qstc) rho_10_exp = qstf_exp.fit(method='lstsq'); E_exp_10[j] = Econc_(rho_10_exp) print(E_exp_10[j]) rho_0_exp = pTraceL_num(2, 2, rho_10_exp) C_exp_0[j] = coh_l1(rho_0_exp) P_exp[j] = predict_jb(rho_0_exp) import matplotlib matplotlib.rcParams.update({'font.size':11}); plt.figure(figsize = (7,5), dpi = 100) q = np.arange(0,1.01,0.01) Ei2 = 4*q*(1-q) Ci2 = (2*q-1)**2 Pi2 = np.zeros(len(q)) Pm = 1-2*q*(1-q) plt.plot(q, Ei2, '-', label=r'$E_{conc}(\xi_{AC})^2$') plt.plot(q, Ci2, '--', label=r'$C_{l_1}(\xi_C)^2$') plt.plot(q, Pi2, '-.', label=r'$P(\xi_C)^2$') plt.plot(q, Ei2+Ci2, ':', label=r'$E_{conc}(\xi_{AC})^{2}+C_{l_{1}}(\xi_{C})^{2}+P(\xi_C)^2$') plt.plot(q_exp, E_sim_10**2, 'X', label=r'$E_{conc}(\xi_{AC})^2_{sim}$') plt.plot(q_exp, C_sim_0**2, 'h', label=r'$C_{l_1}(\xi_C)^2_{sim}$') plt.plot(q_exp, P_sim_0**2, '>', label=r'$P(\xi_C)^2_{sim}$') plt.plot(q_exp, E_sim_10**2+C_sim_0**2+P_sim_0**2, '*', label=r'$E_{conc}(\xi_{AC})^{2}_{sim}+C_{l_{1}}(\xi_{C})^{2}_{sim}+P(\xi_C)^2_{sim}$') plt.plot(q_exp, E_exp_10**2, 's', label=r'$E_{conc}(\xi_{AC})^2_{exp}$') plt.plot(q_exp, C_exp_0**2, 'o', label=r'$C_{l_1}(\xi_C)^2_{exp}$') plt.plot(q_exp, P_exp_0**2, 'v', label=r'$P(\xi_C)^2_{exp}$') plt.plot(q_exp, E_exp_10**2+C_exp_0**2+P_exp_0**2, 'd', label=r'$E_{conc}(\xi_{AC})^{2}_{exp}+C_{l_{1}}(\xi_{C})^{2}_{exp}+P(\xi_C)^2_{exp}$') plt.legend(bbox_to_anchor=(1.75, 1.0), loc='upper right') plt.xlabel(r'$q$') plt.show() # error mitigation qr = QuantumRegister(5); qubit_list = [1,2] meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr) job = qiskit.execute(meas_calibs, backend = device, shots = nshots) print(job.job_id()) job_monitor(job) job = device.retrieve_job('636d895d04e46a1feb6227a9') meas_fitter = CompleteMeasFitter(job.result(), state_labels) q_exp = np.arange(0,1.1,0.1); N = len(q_exp) for j in range(0,N): job = device.retrieve_job(list_ids[j]) mitigated_results = meas_fitter.filter.apply(job.result()) qstf_exp = StateTomographyFitter(mitigated_results, qstc) rho_10_exp = qstf_exp.fit(method='lstsq'); E_exp_10[j] = Econc_(rho_10_exp) print(E_exp_10[j]) rho_0_exp = pTraceL_num(2, 2, rho_10_exp) C_exp_0[j] = coh_l1(rho_0_exp) P_exp[j] = predict_jb(rho_0_exp) import matplotlib matplotlib.rcParams.update({'font.size':11}); plt.figure(figsize = (7,5), dpi = 100) q = np.arange(0,1.01,0.01) Ei2 = 4*q*(1-q) Ci2 = (2*q-1)**2 Pi2 = np.zeros(len(q)) Pm = 1-2*q*(1-q) plt.plot(q, Ei2, '-', label=r'$E_{conc}(\xi_{AC})^2$') plt.plot(q, Ci2, '--', label=r'$C_{l_1}(\xi_C)^2$') plt.plot(q, Pi2, '-.', label=r'$P(\xi_C)^2$') plt.plot(q, Ei2+Ci2, ':', label=r'$E_{conc}(\xi_{AC})^{2}+C_{l_{1}}(\xi_{C})^{2}+P(\xi_C)^2$') plt.plot(q_exp, E_sim_10**2, 'X', label=r'$E_{conc}(\xi_{AC})^2_{sim}$') plt.plot(q_exp, C_sim_0**2, 'h', label=r'$C_{l_1}(\xi_C)^2_{sim}$') plt.plot(q_exp, P_sim_0**2, '>', label=r'$P(\xi_C)^2_{sim}$') plt.plot(q_exp, E_sim_10**2+C_sim_0**2+P_sim_0**2, '*', label=r'$E_{conc}(\xi_{AC})^{2}_{sim}+C_{l_{1}}(\xi_{C})^{2}_{sim}+P(\xi_C)^2_{sim}$') plt.plot(q_exp, E_exp_10**2, '^', label=r'$E_{conc}(\xi_{AC})^2_{exp}$') plt.plot(q_exp, C_exp_0**2, 'o', label=r'$C_{l_1}(\xi_C)^2_{exp}$') plt.plot(q_exp, P_exp_0**2, '.', label=r'$P(\xi_C)^2_{exp}$') plt.plot(q_exp, E_exp_10**2+C_exp_0**2+P_exp_0**2, 'd', label=r'$E_{conc}(\xi_{AC})^{2}_{exp}+C_{l_{1}}(\xi_{C})^{2}_{exp}+P(\xi_C)^2_{exp}$') plt.legend(bbox_to_anchor=(1.75, 1.0), loc='upper right') plt.xlabel(r'$q$') plt.savefig('fig_Eswap_pre_bbm.pdf') plt.show() qc.draw(output='mpl') def pTrace_3_num(rho_abc, da, db, dc): rho_ac = np.zeros(da*dc*da*dc, dtype=complex).reshape(da*dc,da*dc) for j in range(0,da): for l in range(0,dc): cj = j*dc+l ccj = j*db*dc+l for m in range(0,da): for o in range(0,dc): ck = m*dc+o cck = m*db*dc+o for k in range(0,db): rho_ac[cj,ck] = rho_ac[cj,ck] + rho_abc[ccj+k*dc,cck+k*dc] return rho_ac import numpy as np import math # projetores para a pos-seleção I2 = np.array([[1,0],[0,1]], dtype=complex) P00 = np.kron(np.kron(I2,np.array([[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],dtype=complex)), I2) # PhiP P01 = np.kron(np.kron(I2,np.array([[0,0,0,0],[0,1,0,0],[0,0,0,0],[0,0,0,0]],dtype=complex)), I2) # PsiP P10 = np.kron(np.kron(I2,np.array([[0,0,0,0],[0,0,0,0],[0,0,1,0],[0,0,0,0]],dtype=complex)), I2) # PhiM P11 = np.kron(np.kron(I2,np.array([[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]],dtype=complex)), I2) # PsiM #P00+P01+P10+P11 q_exp = np.arange(0,1.1,0.1); N = len(q_exp) q_exp[0] = 0.03; q_exp[N-1] = 1-q_exp[0] th_xi = np.zeros(N); th_xi = 2*np.arccos(np.sqrt(1-q_exp)) th_eta = np.zeros(N); th_eta = 2*np.arccos(np.sqrt(q_exp)) E_phiP_04_sim = np.zeros(N); E_psiM_04_sim = np.zeros(N) E_psiP_04_sim = np.zeros(N); E_phiM_04_sim = np.zeros(N) C2_sim = np.zeros(N) for j in range(0,N): qr = QuantumRegister(5); qc = QuantumCircuit(qr) # prepara xi qc.u(th_xi[j],0,0,qr[0]) qc.cx(qr[0],qr[1]) qc.h([qr[0],qr[1]]) # prepara eta qc.u(th_eta[j],0,0,qr[3]) qc.cx(qr[3],qr[4]) qc.h([qr[3],qr[4]]) # BBM qc.cx(qr[1],qr[3]) qc.h(qr[1]) # circuito para tomografia qstc = state_tomography_circuits(qc, [qr[4],qr[3],qr[1],qr[0]]) # Simulacao job_sim = qiskit.execute(qstc, backend = simulator, shots=nshots) qstf_sim = StateTomographyFitter(job_sim.result(), qstc) rho_4310_sim = qstf_sim.fit(method='lstsq') # pos-selecao rho_PhiP = P00@rho_4310_sim@P00 pr_phiP = np.real(np.trace(rho_PhiP)) rho_PhiP = (1/pr_phiP)*rho_PhiP rho_PsiP = P01@rho_4310_sim@P01 pr_psiP = np.real(np.trace(rho_PsiP)) rho_PsiP = (1/pr_psiP)*rho_PsiP rho_PhiM = P10@rho_4310_sim@P10 pr_phiM = np.real(np.trace(rho_PhiM)) rho_PhiM = (1/pr_phiM)*rho_PhiM rho_PsiM = P11@rho_4310_sim@P11 pr_psiM = np.real(np.trace(rho_PsiM)) rho_PsiM = (1/pr_psiM)*rho_PsiM # estados reduzidos rho_PhiP_04 = pTrace_3_num(rho_PhiP,2,4,2) rho_PsiP_04 = pTrace_3_num(rho_PsiP,2,4,2) rho_PhiM_04 = pTrace_3_num(rho_PhiM,2,4,2) rho_PsiM_04 = pTrace_3_num(rho_PsiM,2,4,2) # emaranhamentos e probabilidades E_phiP_04_sim[j] = Econc_(rho_PhiP_04) E_phiM_04_sim[j] = Econc_(rho_PhiM_04) E_psiP_04_sim[j] = Econc_(rho_PsiP_04) E_psiM_04_sim[j] = Econc_(rho_PsiM_04) C2_sim[j] = 1 - 2*(pr_phiP+pr_psiP) provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibmq_manila') q_exp = np.arange(0,1.1,0.1); N = len(q_exp) q_exp[0] = 0.03; q_exp[N-1] = 1-q_exp[0] th_xi = np.zeros(N); th_xi = 2*np.arccos(np.sqrt(1-q_exp)) th_eta = np.zeros(N); th_eta = 2*np.arccos(np.sqrt(q_exp)) #jobs_ids2 = [] for j in range(N-1,N): qr = QuantumRegister(5); qc = QuantumCircuit(qr) # prepara xi qc.u(th_xi[j],0,0,qr[1]) qc.cx(qr[1],qr[2]) qc.h([qr[1],qr[2]]) # prepara eta qc.u(th_eta[j],0,0,qr[3]) qc.cx(qr[3],qr[4]) qc.h([qr[3],qr[4]]) # BBM qc.cx(qr[2],qr[3]) qc.h(qr[2]) # circuito para tomografia qstc = state_tomography_circuits(qc, [qr[4],qr[3],qr[2],qr[1]]) # Experimento job_exp = qiskit.execute(qstc, backend = device, shots=nshots) #jobs_ids2.append(job_exp.job_id()) print(job_exp.job_id()) job_monitor(job_exp) jobs_ids2.append('636e2c8910cc1925ad755b77') qc.draw(output='mpl') f = open("jobs_ids_ES_post_bbm.txt", "w") f.write(str(jobs_ids2)) f.close() f = open("jobs_ids_ES_post_bbm.txt","r") list_ids2 = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",") f.close() print(list_ids2) q_exp = np.arange(0,1.1,0.1); N = len(q_exp) q_exp[0] = 0.03; q_exp[N-1] = 1-q_exp[0] E_phiP_04_exp = np.zeros(N); E_psiM_04_exp = np.zeros(N) E_psiP_04_exp = np.zeros(N); E_phiM_04_exp = np.zeros(N) C2_exp = np.zeros(N) for j in range(0,N): job = device.retrieve_job(list_ids2[j]) qstf_exp = StateTomographyFitter(job.result(), qstc) rho_4310_exp = qstf_exp.fit(method='lstsq') # pos-selecao rho_PhiP = P00@rho_4310_exp@P00 pr_phiP = np.real(np.trace(rho_PhiP)) rho_PhiP = (1/pr_phiP)*rho_PhiP rho_PsiP = P01@rho_4310_exp@P01 pr_psiP = np.real(np.trace(rho_PsiP)) rho_PsiP = (1/pr_psiP)*rho_PsiP rho_PhiM = P10@rho_4310_exp@P10 pr_phiM = np.real(np.trace(rho_PhiM)) rho_PhiM = (1/pr_phiM)*rho_PhiM rho_PsiM = P11@rho_4310_exp@P11 pr_psiM = np.real(np.trace(rho_PsiM)) rho_PsiM = (1/pr_psiM)*rho_PsiM # estados reduzidos rho_PhiP_04 = pTrace_3_num(rho_PhiP,2,4,2) rho_PsiP_04 = pTrace_3_num(rho_PsiP,2,4,2) rho_PhiM_04 = pTrace_3_num(rho_PhiM,2,4,2) rho_PsiM_04 = pTrace_3_num(rho_PsiM,2,4,2) # emaranhamentos e probabilidades E_phiP_04_exp[j] = Econc_(rho_PhiP_04) E_phiM_04_exp[j] = Econc_(rho_PhiM_04) E_psiP_04_exp[j] = Econc_(rho_PsiP_04) E_psiM_04_exp[j] = Econc_(rho_PsiM_04) C2_exp[j] = 1 - 2*(pr_phiP+pr_psiP) print(C2_exp[j]) import matplotlib from matplotlib import pyplot as plt matplotlib.rcParams.update({'font.size':11}); plt.figure(figsize = (6,4), dpi = 100) q = np.arange(0,1.01,0.01) Ep = np.ones(len(q)); Em = (2*q*(1-q))/(1-2*q+2*q**2); C2 = 1-4*q*(1-q) plt.plot(q, Ep, '-', label=r'$E(\hat{\phi}_+)=E(\hat{\psi}_+)$') plt.plot(q, Em, '--', label=r'$E(\hat{\phi}_-)=E(\hat{\psi}_-)$') plt.plot(q, C2, '-.', label=r'$1-2(Pr(\hat{\phi}_+)+Pr(\hat{\psi}_+))$') plt.plot(q_exp, E_phiP_04_sim, 'o', label=r'$E(\hat{\phi}_+)_{sim}$') plt.plot(q_exp, E_phiM_04_sim, '*', label=r'$E(\hat{\phi}_-)_{sim}$') #plt.plot(q_exp, E_psiP_04_sim, 'X', label=r'$E(\hat{\psi}_+)_{sim}$') #plt.plot(q_exp, E_psiM_04_sim, '.', label=r'$E(\hat{\psi}_-)_{sim}$') plt.plot(q_exp, C2_sim, 'X', label=r'$1-2(Pr(\hat{\phi}_+)_{sim}+Pr(\hat{\psi}_+)_{sim})$') plt.plot(q_exp, E_phiP_04_exp, '<', label=r'$E(\hat{\phi}_+)_{exp}$') plt.plot(q_exp, E_phiM_04_exp, '>', label=r'$E(\hat{\phi}_-)_{exp}$') #plt.plot(q_exp, E_psiP_04_exp, '^', label=r'$E(\hat{\psi}_+)_{exp}$') #plt.plot(q_exp, E_psiM_04_exp, '.', label=r'$E(\hat{\psi}_-)_{exp}$') plt.plot(q_exp, C2_exp, '^', label=r'$1-2(Pr(\hat{\phi}_+)_{exp}+Pr(\hat{\psi}_+)_{exp})$') plt.xlabel(r'$q$') plt.legend(bbox_to_anchor=(1.8, 1.0), loc='upper right') plt.show() # error mitigation qr = QuantumRegister(5)#; qc = QuantumCircuit(qr) qubit_list = [1,2,3,4] meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr) job = qiskit.execute(meas_calibs, backend = device, shots = nshots) print(job.job_id()) job_monitor(job) job = device.retrieve_job('636e3407fb0a57272187586a') meas_fitter = CompleteMeasFitter(job.result(), state_labels) q_exp = np.arange(0,1.1,0.1); N = len(q_exp) q_exp[0] = 0.03; q_exp[N-1] = 1-q_exp[0] E_phiP_04_exp = np.zeros(N); E_psiM_04_exp = np.zeros(N) E_psiP_04_exp = np.zeros(N); E_phiM_04_exp = np.zeros(N) C2_exp = np.zeros(N) for j in range(0,N): job = device.retrieve_job(list_ids2[j]) mitigated_results = meas_fitter.filter.apply(job.result()) # error mitigation qstf_exp = StateTomographyFitter(mitigated_results, qstc) # error mitigation rho_4310_exp = qstf_exp.fit(method='lstsq') # pos-selecao rho_PhiP = P00@rho_4310_exp@P00 pr_phiP = np.real(np.trace(rho_PhiP)) rho_PhiP = (1/pr_phiP)*rho_PhiP rho_PsiP = P01@rho_4310_exp@P01 pr_psiP = np.real(np.trace(rho_PsiP)) rho_PsiP = (1/pr_psiP)*rho_PsiP rho_PhiM = P10@rho_4310_exp@P10 pr_phiM = np.real(np.trace(rho_PhiM)) rho_PhiM = (1/pr_phiM)*rho_PhiM rho_PsiM = P11@rho_4310_exp@P11 pr_psiM = np.real(np.trace(rho_PsiM)) rho_PsiM = (1/pr_psiM)*rho_PsiM # estados reduzidos rho_PhiP_04 = pTrace_3_num(rho_PhiP,2,4,2) rho_PsiP_04 = pTrace_3_num(rho_PsiP,2,4,2) rho_PhiM_04 = pTrace_3_num(rho_PhiM,2,4,2) rho_PsiM_04 = pTrace_3_num(rho_PsiM,2,4,2) # emaranhamentos e probabilidades E_phiP_04_exp[j] = Econc_(rho_PhiP_04) E_phiM_04_exp[j] = Econc_(rho_PhiM_04) E_psiP_04_exp[j] = Econc_(rho_PsiP_04) E_psiM_04_exp[j] = Econc_(rho_PsiM_04) C2_exp[j] = 1 - 2*(pr_phiP+pr_psiP) print(C2_exp[j]) import matplotlib from matplotlib import pyplot as plt matplotlib.rcParams.update({'font.size':11}); plt.figure(figsize = (6,4), dpi = 100) q = np.arange(0,1.01,0.01) Ep = np.ones(len(q)); Em = (2*q*(1-q))/(1-2*q+2*q**2); C2 = 1-4*q*(1-q) plt.plot(q, Ep, '-', label=r'$E(\hat{\phi}_+)=E(\hat{\psi}_+)$') plt.plot(q, Em, '--', label=r'$E(\hat{\phi}_-)=E(\hat{\psi}_-)$') plt.plot(q, C2, '-.', label=r'$1-2(Pr(\hat{\phi}_+)+Pr(\hat{\psi}_+))$') plt.plot(q_exp, E_phiP_04_sim, 'o', label=r'$E(\hat{\phi}_+)_{sim}$') plt.plot(q_exp, E_phiM_04_sim, '*', label=r'$E(\hat{\phi}_-)_{sim}$') #plt.plot(q_exp, E_psiP_04_sim, 'X', label=r'$E(\hat{\psi}_+)_{sim}$') #plt.plot(q_exp, E_psiM_04_sim, '.', label=r'$E(\hat{\psi}_-)_{sim}$') plt.plot(q_exp, C2_sim, 'X', label=r'$1-2(Pr(\hat{\phi}_+)_{sim}+Pr(\hat{\psi}_+)_{sim})$') plt.plot(q_exp, E_phiP_04_exp, '<', label=r'$E(\hat{\phi}_+)_{exp}$') plt.plot(q_exp, E_phiM_04_exp, '>', label=r'$E(\hat{\phi}_-)_{exp}$') #plt.plot(q_exp, E_psiP_04_exp, '^', label=r'$E(\hat{\psi}_+)_{exp}$') #plt.plot(q_exp, E_psiM_04_exp, '.', label=r'$E(\hat{\psi}_-)_{exp}$') plt.plot(q_exp, C2_exp, '^', label=r'$1-2(Pr(\hat{\phi}_+)_{exp}+Pr(\hat{\psi}_+)_{exp})$') plt.xlabel(r'$q$') plt.legend(bbox_to_anchor=(1.8, 1.0), loc='upper right') plt.savefig('fig_Eswap_post_bbm.pdf') plt.show() C = np.arange(0,1.1,0.1); E_PhiP = (1-C**2)/(1+C**2) E_PhiM = np.ones(len(C)) plt.plot(C, E_PhiP, '*'); plt.plot(C, E_PhiM, '.') plt.show() from qiskit import * qr = QuantumRegister(4); %run init.ipynb p,q = symbols('p q') ket_xi = Matrix([[sqrt(p)],[sqrt((1-p)/2)],[sqrt((1-p)/2)],[0]]) ket_eta = Matrix([[sqrt(q)],[sqrt((1-q)/2)],[sqrt((1-q)/2)],[0]]) ket_xi, ket_eta rho_xi = ket_xi*ket_xi.T rho_eta = ket_eta*ket_eta.T rho_xi, rho_eta def ptraceA(da, db, rho): rhoB = zeros(db,db) for j in range(0, db): for k in range(0, db): for l in range(0, da): rhoB[j,k] += rho[l*db+j,l*db+k] return rhoB def ptraceB(da, db, rho): rhoA = zeros(da,da) for j in range(0, da): for k in range(0, da): for l in range(0, db): rhoA[j,k] += rho[j*db+l,k*db+l] return rhoA rho_xi_A = ptraceB(2,2,rho_xi); rho_xi_C = ptraceA(2,2,rho_xi) rho_xi_A, rho_xi_C rho_eta_Cp = ptraceB(2,2,rho_eta); rho_eta_B = ptraceA(2,2,rho_eta) rho_eta_Cp, rho_eta_B c00,c01,c10,c11 = symbols('c_{00} c_{01} c_{10} c_{11}') d00,d01,d10,d11 = symbols('d_{00} d_{01} d_{10} d_{11}') def two_qb_basis(): zz = Matrix([[1],[0],[0],[0]]) zu = Matrix([[0],[1],[0],[0]]) uz = Matrix([[0],[0],[1],[0]]) uu = Matrix([[0],[0],[0],[1]]) return zz,zu,uz,uu zz,zu,uz,uu = two_qb_basis(); zz,zu,uz,uu def psi_p(c00,c01,c10,c11,d00,d01,d10,d11): zz,zu,uz,uu = two_qb_basis() psi = (c00*d00+c01*d10)*zz + (c00*d01+c01*d11)*zu + (c10*d00+c11*d10)*uz + (c10*d01+c11*d11)*uu return psi/sqrt(2) def psi_m(c00,c01,c10,c11,d00,d01,d10,d11): zz,zu,uz,uu = two_qb_basis() psi = (c00*d00-c01*d10)*zz + (c00*d01-c01*d11)*zu + (c10*d00-c11*d10)*uz + (c10*d01-c11*d11)*uu return psi/sqrt(2) def phi_p(c00,c01,c10,c11,d00,d01,d10,d11): zz,zu,uz,uu = two_qb_basis() psi = (c00*d10+c01*d00)*zz + (c00*d11+c01*d01)*zu + (c10*d10+c11*d00)*uz + (c10*d11+c11*d01)*uu return psi/sqrt(2) def phi_m(c00,c01,c10,c11,d00,d01,d10,d11): zz,zu,uz,uu = two_qb_basis() psi = (c00*d10-c01*d00)*zz + (c00*d11-c01*d01)*zu + (c10*d10-c11*d00)*uz + (c10*d11-c11*d01)*uu return psi/sqrt(2) c00 = sqrt(p); c01 = sqrt((1-p)/2); c10 = sqrt((1-p)/2); c11 = 0 d00 = sqrt(q); d01 = sqrt((1-q)/2); d10 = sqrt((1-q)/2); d11 = 0 psip = psi_p(c00,c01,c10,c11,d00,d01,d10,d11); psim = psi_m(c00,c01,c10,c11,d00,d01,d10,d11) phip = phi_p(c00,c01,c10,c11,d00,d01,d10,d11); phim = phi_m(c00,c01,c10,c11,d00,d01,d10,d11) simplify(psip), simplify(psim), simplify(phip), simplify(phim) psip_norm2 = psip.T*psip; simplify(psip_norm2) psim_norm2 = psim.T*psim; simplify(psim_norm2) phip_norm2 = phip.T*phip; simplify(phip_norm2) phim_norm2 = phim.T*phim; simplify(phim_norm2)
https://github.com/amyami187/QiskitML
amyami187
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 def to_numbers(tensor_list): num_list = [] for tensor in tensor_list: num_list += [tensor.item()] return num_list class QiskitCircuit(): # Specify initial parameters and the quantum circuit def __init__(self,shots): self.theta = Parameter('Theta') self.shots = shots def create_circuit(): qr = QuantumRegister(1,'q') cr = ClassicalRegister(1,'c') ckt = QuantumCircuit(qr,cr) ckt.h(qr[0]) ckt.barrier() ckt.ry(self.theta,qr[0]) ckt.barrier() ckt.measure(qr,cr) return ckt self.circuit = create_circuit() def N_qubit_expectation_Z(self,counts, shots, nr_qubits): expects = np.zeros(nr_qubits) for key in counts.keys(): perc = counts[key]/shots check = np.array([(float(key[i])-1/2)*2*perc for i in range(nr_qubits)]) expects += check return expects def bind(self, parameters): [self.theta] = to_numbers(parameters) self.circuit.data[2][0]._params = to_numbers(parameters) def run(self, i): self.bind(i) backend = Aer.get_backend('qasm_simulator') job_sim = execute(self.circuit,backend,shots=self.shots) result_sim = job_sim.result() counts = result_sim.get_counts(self.circuit) return self.N_qubit_expectation_Z(counts,self.shots,1) class TorchCircuit(Function): @staticmethod def forward(ctx, i): if not hasattr(ctx, 'QiskitCirc'): ctx.QiskitCirc = QiskitCircuit(shots=100) exp_value = ctx.QiskitCirc.run(i[0]) result = torch.tensor([exp_value]) # store the result as a torch tensor ctx.save_for_backward(result, i) return result @staticmethod def backward(ctx, grad_output): s = np.pi/2 forward_tensor, i = ctx.saved_tensors # Obtain paramaters input_numbers = to_numbers(i[0]) gradient = [] for k in range(len(input_numbers)): input_plus_s = input_numbers input_plus_s[k] = input_numbers[k] + s # Shift up by s exp_value_plus = ctx.QiskitCirc.run(torch.tensor(input_plus_s))[0] result_plus_s = torch.tensor([exp_value_plus]) input_minus_s = input_numbers input_minus_s[k] = input_numbers[k] - s # Shift down by s exp_value_minus = ctx.QiskitCirc.run(torch.tensor(input_minus_s))[0] result_minus_s = torch.tensor([exp_value_minus]) gradient_result = (result_plus_s - result_minus_s) gradient.append(gradient_result) result = torch.tensor([gradient]) return result.float() * grad_output.float() transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors mnist_trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transform) labels = mnist_trainset.targets # get the labels for the data labels = labels.numpy() idx1 = np.where(labels == 0) # filter on zeros idx2 = np.where(labels == 1) # filter on ones # Specify number of datapoints per class (i.e. there will be n pictures of 1 and n pictures of 0 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 mnist_trainset.targets = labels[idx] mnist_trainset.data = mnist_trainset.data[idx] train_loader = torch.utils.data.DataLoader(mnist_trainset, batch_size=1, shuffle=True) qc = TorchCircuit.apply class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.h1 = nn.Linear(320, 50) self.h2 = nn.Linear(50, 1) def forward(self, x): x = F.relu(F.max_pool2d(self.conv1(x), 2)) x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) x = x.view(-1, 320) x = F.relu(self.h1(x)) x = F.dropout(x, training=self.training) x = self.h2(x) x = qc(x) x = (x+1)/2 # Normalise the inputs to 1 or 0 x = torch.cat((x, 1-x), -1) return x network = Net() optimizer = optim.Adam(network.parameters(), lr=0.001) epochs = 30 loss_list = [] for epoch in range(epochs): total_loss = [] target_list = [] for batch_idx, (data, target) in enumerate(train_loader): target_list.append(target.item()) optimizer.zero_grad() output = network(data) loss = F.nll_loss(output, target) loss.backward() optimizer.step() total_loss.append(loss.item()) loss_list.append(sum(total_loss)/len(total_loss)) print(loss_list[-1]) # Normalise the loss between 0 and 1 for i in range(len(loss_list)): loss_list[i] += 1 # Plot the loss per epoch plt.plot(loss_list)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.drivers import PySCFDriver driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.72" # Two Hydrogen atoms, 0.72 Angstrom apart ) molecule = driver.run() from qiskit_nature.second_q.mappers import QubitConverter, ParityMapper qubit_converter = QubitConverter(ParityMapper()) hamiltonian = qubit_converter.convert(molecule.second_q_ops()[0]) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver sol = NumPyMinimumEigensolver().compute_minimum_eigenvalue(hamiltonian) real_solution = molecule.interpret(sol) real_solution.groundenergy from qiskit_ibm_runtime import QiskitRuntimeService, Estimator, Session, Options service = QiskitRuntimeService() backend = "ibmq_qasm_simulator" from qiskit.algorithms.minimum_eigensolvers import VQE # Use RealAmplitudes circuit to create trial states from qiskit.circuit.library import RealAmplitudes ansatz = RealAmplitudes(num_qubits=2, reps=2) # Search for better states using SPSA algorithm from qiskit.algorithms.optimizers import SPSA optimizer = SPSA(150) # Set a starting point for reproduceability import numpy as np np.random.seed(6) initial_point = np.random.uniform(-np.pi, np.pi, 12) # Create an object to store intermediate results from dataclasses import dataclass @dataclass class VQELog: values: list parameters: list def update(self, count, parameters, mean, _metadata): self.values.append(mean) self.parameters.append(parameters) print(f"Running circuit {count} of ~350", end="\r", flush=True) log = VQELog([],[]) # Main calculation with Session(service=service, backend=backend) as session: options = Options() options.optimization_level = 3 vqe = VQE(Estimator(session=session, options=options), ansatz, optimizer, callback=log.update, initial_point=initial_point) result = vqe.compute_minimum_eigenvalue(hamiltonian) print("Experiment complete.".ljust(30)) print(f"Raw result: {result.optimal_value}") if 'simulator' not in backend: # Run once with ZNE error mitigation options.resilience_level = 2 vqe = VQE(Estimator(session=session, options=options), ansatz, SPSA(1), initial_point=result.optimal_point) result = vqe.compute_minimum_eigenvalue(hamiltonian) print(f"Mitigated result: {result.optimal_value}") import matplotlib.pyplot as plt plt.rcParams["font.size"] = 14 # Plot energy and reference value plt.figure(figsize=(12, 6)) plt.plot(log.values, label="Estimator VQE") plt.axhline(y=real_solution.groundenergy, color="tab:red", ls="--", label="Target") plt.legend(loc="best") plt.xlabel("Iteration") plt.ylabel("Energy [H]") plt.title("VQE energy") plt.show() import qiskit_ibm_runtime qiskit_ibm_runtime.version.get_version_info() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
%run init.ipynb !pip install -U qiskit==0.39.4 import qiskit from qiskit import * nshots = 8192 IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibmq_quito') simulator = Aer.get_backend('qasm_simulator') from qiskit.tools.monitor import job_monitor qr = QuantumRegister(1) qc = QuantumCircuit(qr) qc.h(qr[0]) qc.draw() from qiskit_experiments.library import StateTomography # essa é com o novo qiskit 039 qcst = StateTomography(qc, measurement_qubits = [0]) data = qcst.run(simulator) rho = data.block_for_results().analysis_results(0).value from qiskit.visualization import array_to_latex array_to_latex(rho) d = rho.dims()[0]; print(rho.dims(), d) rhoM = rho.to_operator().data; print(rhoM) rhoM[0,0], abs(rhoM[0,0]) job_exp = qcst.run(device, shots=nshots)#.block_for_results() print(job_exp.experiment_id) job_exp.job_status() sudo apt install jupyter-core rho = job_exp.block_for_results().analysis_results(0).value rhoM = rho.to_operator().data; print(rhoM) for j in range(0,10): print("\r %d"%j,end=" ") data = device.retrieve_job('03834ee2-0c74-45ff-b744-2cfa3d74f860') rho = data.block_for_results().analysis_results(0).value rhoM = rho.to_operator().data; print(rhoM) !pip install -U qiskit==0.36.2 # como sempre, importa tudo do qiskit from qiskit import * import qiskit qiskit.__qiskit_version__ # importa também funcoes para determinar os circuitos a serem tomografados e pra ajustar os dados from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter # cria os circuitos, sem medidas qr = QuantumRegister(1); qc = qiskit.QuantumCircuit(qr); # cria o circuito qc.h(qr[0]); # visualiza o circuito qc.draw(output='mpl') # Determina de qual circuito e de qual qubit fazer TEQ qstc = state_tomography_circuits(qc, qr[0]) # No. de medidas pra estimar cada dist. de probabilidade nshots = 8192 # testa/executa no simulador job = qiskit.execute(qstc, Aer.get_backend('qasm_simulator'), shots=nshots) # 'ajusta' os resultados conforme o esperado do circuit qst qstf = StateTomographyFitter(job.result(), qstc) # extrai o operador densidade tomografado rho = qstf.fit(method='lstsq') # note que o que retorna é um array do numpy rho # funcionou mudando a versao do qiskit com o novo ambiente conda import numpy as np from matplotlib import pyplot as plt # grafica a parte real de um estado de um qubit def plot_rho1qb(rho): from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm result = [rho[0,0], rho[0,1], rho[1,0], rho[1,1]] result = np.array(result, dtype=float) fig = plt.figure(figsize=(4, 4), dpi=100) ax1 = fig.add_subplot(111, projection='3d') xlabels = np.array([r'$|0\rangle$', r'$|1\rangle$']); xpos = np.arange(xlabels.shape[0]) ylabels = np.array([r'$|1\rangle$', r'$|0\rangle$']); ypos = np.arange(ylabels.shape[0]) xposM, yposM = np.meshgrid(xpos, ypos, copy=False); zpos = result dx = 0.5; dy = 0.5; dz = zpos ax1.set_xlim(0, 1.5); ax1.set_ylim(0, 1.5); ax1.set_zlim(-1, 1) ax1.w_xaxis.set_ticks(xpos + dx/2.0); ax1.w_xaxis.set_ticklabels(xlabels) ax1.w_yaxis.set_ticks(ypos + dy/2.0); ax1.w_yaxis.set_ticklabels(ylabels) values = np.linspace(0.2, 1.0, xposM.ravel().shape[0]); colors = cm.rainbow(values) ax1.bar3d(xposM.ravel(), yposM.ravel(), dz*0, dx, dy, dz, color=colors) plt.show() plot_rho1qb(rho.real), plot_rho1qb(rho.imag) # carrega minha conta no IBMQ (o ID foi incluido no outro arquivo, nao precisa incluir aqui) qiskit.IBMQ.load_account(); #provider = IBMQ.get_provider('ibm-q') provider = IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main') # determina em qual backend vamos executar o circuito device = provider.get_backend('ibmq_quito') # para monitorar a execucao from qiskit.tools.monitor import job_monitor # executa os circuitos para TEQ no chip job = qiskit.execute(qstc, backend = device, shots = nshots) print(job.job_id()); job_monitor(job) # 'ajusta' os resultados conforme o esperado do circuit qst qstf = StateTomographyFitter(job.result(), qstc) # extrai o operador densidade tomografado rho = qstf.fit(method='lstsq'); rho plot_rho1qb(rho.real), plot_rho1qb(rho.imag)
https://github.com/renatawong/classical-shadow-vqe
renatawong
''' (C) 2023 Renata Wong Electronic structure problem with classical shadows, as presented in https://arxiv.org/abs/2103.07510 This code uses Qiskit as platform. The shadow is constructed based on derandomized Hamiltonian. The molecules tested are: H2 (6-31s basis), LiH (sto3g basis), BeH2 (sto3g), H2O (sto3g), and NH3 (sto3g). The coordinates for NH3 were taken from 'Algorithms for Computer Detection of Symmetry Elementsin Molecular Systems'. ''' import time import numpy as np from collections import Counter import matplotlib.pyplot as plt from qiskit import QuantumCircuit, execute from qiskit_aer import QasmSimulator from qiskit.quantum_info import SparsePauliOp from qiskit_nature.units import DistanceUnit from qiskit_nature.second_q.drivers import PySCFDriver from qiskit_nature.second_q.algorithms import GroundStateEigensolver from qiskit_nature.second_q.mappers import BravyiKitaevMapper, JordanWignerMapper, ParityMapper from qiskit_nature.second_q.circuit.library import UCCSD, HartreeFock from qiskit_nature.second_q.algorithms import VQEUCCFactory from qiskit.algorithms.minimum_eigensolvers import VQE from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA # Estimator primitive is based on the Statevector construct = algebraic simulation from qiskit.primitives import Estimator from qiskit.utils import algorithm_globals from modified_derandomization import modified_derandomized_classical_shadow from predicting_quantum_properties.data_acquisition_shadow import derandomized_classical_shadow from predicting_quantum_properties.prediction_shadow import estimate_exp import qiskit_nature qiskit_nature.settings.use_pauli_sum_op = False import h5py H5PY_DEFAULT_READONLY=1 ''' DEFINING DRIVERS FOR THE MOLECULES ''' H2_driver = PySCFDriver( atom="H 0 0 0; H 0 0 0.735", basis="6-31g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) LiH_driver = PySCFDriver( atom="Li 0 0 0.5; H 0 0 0", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) BeH2_driver = PySCFDriver( atom="Be 0 0 0; H 0 0 1.3264; H 0 0 -1.3264", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) H2O_driver = PySCFDriver( atom="O 0.0 0.0 0.0; H 0.757 0.586 0.0; H -0.757 0.586 0.0", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) NH3_driver = PySCFDriver( atom="N 0 0 0; H 0 0 1.008000; H 0.950353 0 -0.336000; H -0.475176 -0.823029 -0.336000", basis="sto3g", charge=0, spin=0, unit=DistanceUnit.ANGSTROM, ) ''' FORMATTING HAMILTONIAN ''' def process_hamiltonian(hamiltonian, derandomize = False): hamiltonian_observables = [] hamiltonian_coefficients = [] for observable in hamiltonian.paulis: op_list = [] for op_index, pauli_op in enumerate(observable): pauli_op = str(pauli_op) if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z': op_list.append((pauli_op, op_index)) hamiltonian_observables.append(op_list) hamiltonian_coefficients = hamiltonian.coeffs.real system_size = len(hamiltonian_observables[0]) # removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left # these observables are needed for estimate_exp() observables_xyze = [] for observable in hamiltonian_observables: XYZE = [] for pauli in observable: if pauli[0] != 'I': XYZE.append(pauli) observables_xyze.append(XYZE) # derandomisation procedure requires that coefficients are non-negative if derandomize == True: absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients] # removing the empty list as well # these observables are needed for derandomisation procedure observables_xyz = [] for idx, observable in enumerate(observables_xyze): if observable: observables_xyz.append(observable) else: absolute_coefficients.pop(idx) return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients return system_size, observables_xyze, hamiltonian_coefficients ''' COST FUNCTION AND HELPER FUNCTIONS ''' def basis_change_circuit(pauli_op): # Generating circuit with just the basis change operators # # pauli_op: n-qubit Pauli operator basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits) for idx, op in enumerate(pauli_op): if op == 'X': basis_change.h(idx) if op == 'Y': basis_change.h(idx) basis_change.p(-np.pi/2, idx) return basis_change def ground_state_energy_from_shadow(operators, params): backend = QasmSimulator(method='statevector', shots=1) pauli_op_dict = Counter(tuple(x) for x in operators) shadow = [] for pauli_op in pauli_op_dict: qc = ansatz.bind_parameters(params) qc = qc.compose(basis_change_circuit(pauli_op)) qc.measure(reversed(range(system_size)), range(system_size)) result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result() counts = result.get_counts() # given in order q0 q1 ... qn-1 after register reversal in qc.measure for count in counts: for _ in range(counts[count]): # number of repeated measurement values output_str = list(count) output = [int(i) for i in output_str] eigenvals = [x+1 if x == 0 else x-2 for x in output] snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)] shadow.append(snapshot) expectation_value = 0.0 for term, weight in zip(observables_xyze, hamiltonian_coefficients): sum_product, match_count = estimate_exp(shadow, term) if match_count != 0: expectation_value += (weight * sum_product / match_count) return expectation_value ''' EXPERIMENTS ''' start_time = time.time() all_molecules_rmse_errors = [] # CALCULATING FERMIONIC HAMILTONIAN AND CONVERTING TO QUBIT HAMILTONIAN MOLECULES = ['H2', 'LiH', 'BeH2', 'H2O', 'NH3'] for molecule in MOLECULES: rmse_errors = [] if molecule == 'H2': problem = H2_driver.run() if molecule == 'LiH': problem = LiH_driver.run() if molecule == 'BeH2': problem = BeH2_driver.run() if molecule == 'H2O': problem = H2O_driver.run() if molecule == 'NH3': problem = NH3_driver.run() hamiltonian = problem.hamiltonian second_q_op = hamiltonian.second_q_op() bk_mapper = BravyiKitaevMapper() bkencoded_hamiltonian = bk_mapper.map(second_q_op) #print('Qubit Hamiltonian in Bravyi-Kitaev encoding', bkencoded_hamiltonian) # process the Hamiltonian to obtain properly formatted data hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = True) system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients = hamiltonian_data ''' VARIATIONAL ANSATZ ''' ansatz = UCCSD( problem.num_spatial_orbitals, problem.num_particles, bk_mapper, initial_state=HartreeFock( problem.num_spatial_orbitals, problem.num_particles, bk_mapper, ), ) ''' Running VQE on the Hamiltonian obtained from PySCFDriver using Statevector simulator (Estimator primitive) ''' #estimator = Estimator() # If shots = None, it calculates the exact expectation values. Otherwise, it samples from normal distributions # with standard errors as standard deviations using normal distribution approximation. #estimator.set_options(shots = None) vqe_solver = VQE(Estimator(), ansatz, SLSQP()) vqe_solver.initial_point = np.zeros(ansatz.num_parameters) calc = GroundStateEigensolver(bk_mapper, vqe_solver) result = calc.solve(problem) print(result.raw_result) #print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n') measurement_range = [50]#, 250, 500, 750, 1000, 1250, 1500, 1750] molecules_avg_rmse = [] for num_operators in measurement_range: derandomized_hamiltonian = derandomized_classical_shadow(observables_xyz, num_operators, system_size, weight=absolute_coefficients) tuples = (tuple(pauli) for pauli in derandomized_hamiltonian) counts = Counter(tuples) # derandomized classical shadow will usually either undergenerate or overgenerate derandomized operators # Therefore, a modification may be necessary. expectation_values = [] num_experiments = 1 for iteration in range(num_experiments): expectation_value = ground_state_energy_from_shadow(derandomized_hamiltonian, result.raw_result.optimal_point) expectation_values.append(expectation_value) print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, expectation_value)) rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - result.raw_result.optimal_value)**2 for i in range(num_experiments)])/num_experiments) rmse_errors.append(rmse_derandomised_cs) print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs)) all_molecules_rmse_errors.append(rmse_errors) elapsed_time = time.time() - start_time print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time))) print(all_molecules_rmse_errors)
https://github.com/qiskit-community/community.qiskit.org
qiskit-community
from qiskit import * from qiskit.tools.visualization import plot_histogram from qiskit.providers.aer import noise import numpy as np coupling_map = [[1, 0], [2, 0], [2, 1], [3, 2], [3, 4], [4, 2]] noise_dict = {'errors': [{'type': 'qerror', 'operations': ['u2'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0004721766167523067, 0.0004721766167523067, 0.0004721766167523067, 0.9985834701497431], 'gate_qubits': [[0]]}, {'type': 'qerror', 'operations': ['u2'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0005151090708174488, 0.0005151090708174488, 0.0005151090708174488, 0.9984546727875476], 'gate_qubits': [[1]]}, {'type': 'qerror', 'operations': ['u2'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0005151090708174488, 0.0005151090708174488, 0.0005151090708174488, 0.9984546727875476], 'gate_qubits': [[2]]}, {'type': 'qerror', 'operations': ['u2'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.000901556048412383, 0.000901556048412383, 0.000901556048412383, 0.9972953318547628], 'gate_qubits': [[3]]}, {'type': 'qerror', 'operations': ['u2'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0011592423249461303, 0.0011592423249461303, 0.0011592423249461303, 0.9965222730251616], 'gate_qubits': [[4]]}, {'type': 'qerror', 'operations': ['u3'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0009443532335046134, 0.0009443532335046134, 0.0009443532335046134, 0.9971669402994862], 'gate_qubits': [[0]]}, {'type': 'qerror', 'operations': ['u3'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0010302181416348977, 0.0010302181416348977, 0.0010302181416348977, 0.9969093455750953], 'gate_qubits': [[1]]}, {'type': 'qerror', 'operations': ['u3'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0010302181416348977, 0.0010302181416348977, 0.0010302181416348977, 0.9969093455750953], 'gate_qubits': [[2]]}, {'type': 'qerror', 'operations': ['u3'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.001803112096824766, 0.001803112096824766, 0.001803112096824766, 0.9945906637095256], 'gate_qubits': [[3]]}, {'type': 'qerror', 'operations': ['u3'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0023184846498922607, 0.0023184846498922607, 0.0023184846498922607, 0.9930445460503232], 'gate_qubits': [[4]]}, {'type': 'qerror', 'operations': ['cx'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'x', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.002182844139394187, 0.9672573379090872], 'gate_qubits': [[1, 0]]}, {'type': 'qerror', 'operations': ['cx'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'x', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.0020007412998552473, 0.9699888805021712], 'gate_qubits': [[2, 0]]}, {'type': 'qerror', 'operations': ['cx'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'x', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.002485439516158936, 0.9627184072576159], 'gate_qubits': [[2, 1]]}, {'type': 'qerror', 'operations': ['cx'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'x', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.0037502825428055767, 0.9437457618579164], 'gate_qubits': [[3, 2]]}, {'type': 'qerror', 'operations': ['cx'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'x', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.004401224333760022, 0.9339816349935997], 'gate_qubits': [[3, 4]]}, {'type': 'qerror', 'operations': ['cx'], 'instructions': [[{'name': 'x', 'qubits': [0]}], [{'name': 'y', 'qubits': [0]}], [{'name': 'z', 'qubits': [0]}], [{'name': 'x', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'x', 'qubits': [1]}], [{'name': 'y', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'y', 'qubits': [1]}], [{'name': 'z', 'qubits': [1]}], [{'name': 'x', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'y', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'z', 'qubits': [0]}, {'name': 'z', 'qubits': [1]}], [{'name': 'id', 'qubits': [0]}]], 'probabilities': [0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.0046188825262438934, 0.9307167621063416], 'gate_qubits': [[4, 2]]}, {'type': 'roerror', 'operations': ['measure'], 'probabilities': [[0.9372499999999999, 0.06275000000000008], [0.06275000000000008, 0.9372499999999999]], 'gate_qubits': [[0]]}, {'type': 'roerror', 'operations': ['measure'], 'probabilities': [[0.9345, 0.0655], [0.0655, 0.9345]], 'gate_qubits': [[1]]}, {'type': 'roerror', 'operations': ['measure'], 'probabilities': [[0.97075, 0.029249999999999998], [0.029249999999999998, 0.97075]], 'gate_qubits': [[2]]}, {'type': 'roerror', 'operations': ['measure'], 'probabilities': [[0.9742500000000001, 0.02574999999999994], [0.02574999999999994, 0.9742500000000001]], 'gate_qubits': [[3]]}, {'type': 'roerror', 'operations': ['measure'], 'probabilities': [[0.8747499999999999, 0.12525000000000008], [0.12525000000000008, 0.8747499999999999]], 'gate_qubits': [[4]]}], 'x90_gates': []} noise_model = noise.noise_model.NoiseModel.from_dict( noise_dict ) qr = QuantumRegister(5, 'qr') cr = ClassicalRegister(1, 'cr') backend = Aer.get_backend('qasm_simulator') def AND (input1,input2, q_1=0,q_2=1,q_out=2): # The keyword q_1 specifies the qubit used to encode input1 # The keyword q_2 specifies qubit used to encode input2 # The keyword q_out specifies qubit to be as output qc = QuantumCircuit(qr, cr) # prepare input on qubits q1 and q2 if input1=='1': qc.x( qr[ q_1 ] ) if input2=='1': qc.x( qr[ q_2 ] ) qc.ccx(qr[ q_1 ],qr[ q_2 ],qr[ q_out ]) # the AND just needs a c qc.measure(qr[ q_out ],cr[0]) # output from qubit 1 is measured # the circuit is run on a simulator, but we do it so that the noise and connectivity of Tenerife are also reproduced job = execute(qc, backend, shots=10000, noise_model=noise_model, coupling_map=coupling_map, basis_gates=noise_model.basis_gates) output = job.result().get_counts() return output result = AND('0','0') print( result ) plot_histogram( result ) worst = 1 for input1 in ['0','1']: for input2 in ['0','1']: print('\nProbability of correct answer for inputs',input1,input2) prob = AND(input1,input2, q_1=0,q_2=1,q_out=2)[str(int( input1=='1' and input2=='1' ))]/10000 print( prob ) worst = min(worst,prob) print('\nThe lowest of these probabilities was',worst)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# useful additional packages import matplotlib.pyplot as plt import numpy as np import networkx as nx from qiskit_aer import Aer from qiskit.tools.visualization import plot_histogram from qiskit.circuit.library import TwoLocal from qiskit_optimization.applications import Maxcut, Tsp from qiskit.algorithms.minimum_eigensolvers import SamplingVQE, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import SPSA from qiskit.utils import algorithm_globals from qiskit.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer # Generating a graph of 4 nodes n = 4 # Number of nodes in graph G = nx.Graph() G.add_nodes_from(np.arange(0, n, 1)) elist = [(0, 1, 1.0), (0, 2, 1.0), (0, 3, 1.0), (1, 2, 1.0), (2, 3, 1.0)] # tuple is (i,j,weight) where (i,j) is the edge G.add_weighted_edges_from(elist) colors = ["r" for node in G.nodes()] pos = nx.spring_layout(G) def draw_graph(G, colors, pos): default_axes = plt.axes(frameon=True) nx.draw_networkx(G, node_color=colors, node_size=600, alpha=0.8, ax=default_axes, pos=pos) edge_labels = nx.get_edge_attributes(G, "weight") nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels) draw_graph(G, colors, pos) # Computing the weight matrix from the random graph w = np.zeros([n, n]) for i in range(n): for j in range(n): temp = G.get_edge_data(i, j, default=0) if temp != 0: w[i, j] = temp["weight"] print(w) best_cost_brute = 0 for b in range(2**n): x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))] cost = 0 for i in range(n): for j in range(n): cost = cost + w[i, j] * x[i] * (1 - x[j]) if best_cost_brute < cost: best_cost_brute = cost xbest_brute = x print("case = " + str(x) + " cost = " + str(cost)) colors = ["r" if xbest_brute[i] == 0 else "c" for i in range(n)] draw_graph(G, colors, pos) print("\nBest solution = " + str(xbest_brute) + " cost = " + str(best_cost_brute)) max_cut = Maxcut(w) qp = max_cut.to_quadratic_program() print(qp.prettyprint()) qubitOp, offset = qp.to_ising() print("Offset:", offset) print("Ising Hamiltonian:") print(str(qubitOp)) # solving Quadratic Program using exact classical eigensolver exact = MinimumEigenOptimizer(NumPyMinimumEigensolver()) result = exact.solve(qp) print(result.prettyprint()) # Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector ee = NumPyMinimumEigensolver() result = ee.compute_minimum_eigenvalue(qubitOp) x = max_cut.sample_most_likely(result.eigenstate) print("energy:", result.eigenvalue.real) print("max-cut objective:", result.eigenvalue.real + offset) print("solution:", x) print("solution objective:", qp.objective.evaluate(x)) colors = ["r" if x[i] == 0 else "c" for i in range(n)] draw_graph(G, colors, pos) algorithm_globals.random_seed = 123 seed = 10598 # construct SamplingVQE optimizer = SPSA(maxiter=300) ry = TwoLocal(qubitOp.num_qubits, "ry", "cz", reps=5, entanglement="linear") vqe = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=optimizer) # run SamplingVQE result = vqe.compute_minimum_eigenvalue(qubitOp) # print results x = max_cut.sample_most_likely(result.eigenstate) print("energy:", result.eigenvalue.real) print("time:", result.optimizer_time) print("max-cut objective:", result.eigenvalue.real + offset) print("solution:", x) print("solution objective:", qp.objective.evaluate(x)) # plot results colors = ["r" if x[i] == 0 else "c" for i in range(n)] draw_graph(G, colors, pos) # create minimum eigen optimizer based on SamplingVQE vqe_optimizer = MinimumEigenOptimizer(vqe) # solve quadratic program result = vqe_optimizer.solve(qp) print(result.prettyprint()) colors = ["r" if result.x[i] == 0 else "c" for i in range(n)] draw_graph(G, colors, pos) # Generating a graph of 3 nodes n = 3 num_qubits = n**2 tsp = Tsp.create_random_instance(n, seed=123) adj_matrix = nx.to_numpy_array(tsp.graph) print("distance\n", adj_matrix) colors = ["r" for node in tsp.graph.nodes] pos = [tsp.graph.nodes[node]["pos"] for node in tsp.graph.nodes] draw_graph(tsp.graph, colors, pos) from itertools import permutations def brute_force_tsp(w, N): a = list(permutations(range(1, N))) last_best_distance = 1e10 for i in a: distance = 0 pre_j = 0 for j in i: distance = distance + w[j, pre_j] pre_j = j distance = distance + w[pre_j, 0] order = (0,) + i if distance < last_best_distance: best_order = order last_best_distance = distance print("order = " + str(order) + " Distance = " + str(distance)) return last_best_distance, best_order best_distance, best_order = brute_force_tsp(adj_matrix, n) print( "Best order from brute force = " + str(best_order) + " with total distance = " + str(best_distance) ) def draw_tsp_solution(G, order, colors, pos): G2 = nx.DiGraph() G2.add_nodes_from(G) n = len(order) for i in range(n): j = (i + 1) % n G2.add_edge(order[i], order[j], weight=G[order[i]][order[j]]["weight"]) default_axes = plt.axes(frameon=True) nx.draw_networkx( G2, node_color=colors, edge_color="b", node_size=600, alpha=0.8, ax=default_axes, pos=pos ) edge_labels = nx.get_edge_attributes(G2, "weight") nx.draw_networkx_edge_labels(G2, pos, font_color="b", edge_labels=edge_labels) draw_tsp_solution(tsp.graph, best_order, colors, pos) qp = tsp.to_quadratic_program() print(qp.prettyprint()) from qiskit_optimization.converters import QuadraticProgramToQubo qp2qubo = QuadraticProgramToQubo() qubo = qp2qubo.convert(qp) qubitOp, offset = qubo.to_ising() print("Offset:", offset) print("Ising Hamiltonian:") print(str(qubitOp)) result = exact.solve(qubo) print(result.prettyprint()) # Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector ee = NumPyMinimumEigensolver() result = ee.compute_minimum_eigenvalue(qubitOp) print("energy:", result.eigenvalue.real) print("tsp objective:", result.eigenvalue.real + offset) x = tsp.sample_most_likely(result.eigenstate) print("feasible:", qubo.is_feasible(x)) z = tsp.interpret(x) print("solution:", z) print("solution objective:", tsp.tsp_value(z, adj_matrix)) draw_tsp_solution(tsp.graph, z, colors, pos) algorithm_globals.random_seed = 123 seed = 10598 optimizer = SPSA(maxiter=300) ry = TwoLocal(qubitOp.num_qubits, "ry", "cz", reps=5, entanglement="linear") vqe = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=optimizer) result = vqe.compute_minimum_eigenvalue(qubitOp) print("energy:", result.eigenvalue.real) print("time:", result.optimizer_time) x = tsp.sample_most_likely(result.eigenstate) print("feasible:", qubo.is_feasible(x)) z = tsp.interpret(x) print("solution:", z) print("solution objective:", tsp.tsp_value(z, adj_matrix)) draw_tsp_solution(tsp.graph, z, colors, pos) algorithm_globals.random_seed = 123 seed = 10598 # create minimum eigen optimizer based on SamplingVQE vqe_optimizer = MinimumEigenOptimizer(vqe) # solve quadratic program result = vqe_optimizer.solve(qp) print(result.prettyprint()) z = tsp.interpret(x) print("solution:", z) print("solution objective:", tsp.tsp_value(z, adj_matrix)) draw_tsp_solution(tsp.graph, z, colors, pos) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle # plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts 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("./") 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="lq") 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"]) print("created t3_st_qcs (length:", len(t3_st_qcs), ")") # zne wrapping zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors) print("created zne_qcs (length:", len(zne_qcs), ")") 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-utokyo', group='internal', project='hirashi-jst') # provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') # print("provider:", provider) # backend = provider.get_backend("ibmq_jakarta") shots = 1 << 13 reps = 1 # unused # Number of trotter steps print("trotter step: ", num_steps) # execute: reps = 1 job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた? print('Job ID', job.job_id()) # QREM qr = QuantumRegister(num_qubits) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout) print('Job ID', cal_job.job_id()) cal_results = cal_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') mit_results = meas_fitter.filter.apply(job.result()) zne_expvals = zne_decoder(num_qubits, mit_results) target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!! rho = expvals_to_valid_rho(num_qubits, zne_expvals) fidelity = state_fidelity(rho, target_state) print(fidelity)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from __future__ import annotations import numpy as np import networkx as nx num_nodes = 4 w = np.array([[0., 1., 1., 0.], [1., 0., 1., 1.], [1., 1., 0., 1.], [0., 1., 1., 0.]]) G = nx.from_numpy_array(w) layout = nx.random_layout(G, seed=10) colors = ['r', 'g', 'b', 'y'] nx.draw(G, layout, node_color=colors) labels = nx.get_edge_attributes(G, 'weight') nx.draw_networkx_edge_labels(G, pos=layout, edge_labels=labels); def objective_value(x: np.ndarray, w: np.ndarray) -> float: """Compute the value of a cut. Args: x: Binary string as numpy array. w: Adjacency matrix. Returns: Value of the cut. """ X = np.outer(x, (1 - x)) w_01 = np.where(w != 0, 1, 0) return np.sum(w_01 * X) def bitfield(n: int, L: int) -> list[int]: result = np.binary_repr(n, L) return [int(digit) for digit in result] # [2:] to chop off the "0b" part # use the brute-force way to generate the oracle L = num_nodes max = 2**L sol = np.inf for i in range(max): cur = bitfield(i, L) how_many_nonzero = np.count_nonzero(cur) if how_many_nonzero * 2 != L: # not balanced continue cur_v = objective_value(np.array(cur), w) if cur_v < sol: sol = cur_v print(f'Objective value computed by the brute-force method is {sol}') from qiskit.quantum_info import Pauli, SparsePauliOp def get_operator(weight_matrix: np.ndarray) -> tuple[SparsePauliOp, float]: r"""Generate Hamiltonian for the graph partitioning Notes: Goals: 1 Separate the vertices into two set of the same size. 2 Make sure the number of edges between the two set is minimized. Hamiltonian: H = H_A + H_B H_A = sum\_{(i,j)\in E}{(1-ZiZj)/2} H_B = (sum_{i}{Zi})^2 = sum_{i}{Zi^2}+sum_{i!=j}{ZiZj} H_A is for achieving goal 2 and H_B is for achieving goal 1. Args: weight_matrix: Adjacency matrix. Returns: Operator for the Hamiltonian A constant shift for the obj function. """ num_nodes = len(weight_matrix) pauli_list = [] coeffs = [] shift = 0 for i in range(num_nodes): for j in range(i): if weight_matrix[i, j] != 0: x_p = np.zeros(num_nodes, dtype=bool) z_p = np.zeros(num_nodes, dtype=bool) z_p[i] = True z_p[j] = True pauli_list.append(Pauli((z_p, x_p))) coeffs.append(-0.5) shift += 0.5 for i in range(num_nodes): for j in range(num_nodes): if i != j: x_p = np.zeros(num_nodes, dtype=bool) z_p = np.zeros(num_nodes, dtype=bool) z_p[i] = True z_p[j] = True pauli_list.append(Pauli((z_p, x_p))) coeffs.append(1.0) else: shift += 1 return SparsePauliOp(pauli_list, coeffs=coeffs), shift qubit_op, offset = get_operator(w) from qiskit.algorithms.minimum_eigensolvers import QAOA from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.primitives import Sampler from qiskit.quantum_info import Pauli, Statevector from qiskit.result import QuasiDistribution from qiskit.utils import algorithm_globals sampler = Sampler() def sample_most_likely(state_vector: QuasiDistribution | Statevector) -> np.ndarray: """Compute the most likely binary string from state vector. Args: state_vector: State vector or quasi-distribution. Returns: Binary string as an array of ints. """ if isinstance(state_vector, QuasiDistribution): values = list(state_vector.values()) else: values = state_vector n = int(np.log2(len(values))) k = np.argmax(np.abs(values)) x = bitfield(k, n) x.reverse() return np.asarray(x) algorithm_globals.random_seed = 10598 optimizer = COBYLA() qaoa = QAOA(sampler, optimizer, reps=2) result = qaoa.compute_minimum_eigenvalue(qubit_op) x = sample_most_likely(result.eigenstate) print(x) print(f'Objective value computed by QAOA is {objective_value(x, w)}') from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit.quantum_info import Operator npme = NumPyMinimumEigensolver() result = npme.compute_minimum_eigenvalue(Operator(qubit_op)) x = sample_most_likely(result.eigenstate) print(x) print(f'Objective value computed by the NumPyMinimumEigensolver is {objective_value(x, w)}') from qiskit.algorithms.minimum_eigensolvers import SamplingVQE from qiskit.circuit.library import TwoLocal from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 10598 optimizer = COBYLA() ansatz = TwoLocal(qubit_op.num_qubits, "ry", "cz", reps=2, entanglement="linear") sampling_vqe = SamplingVQE(sampler, ansatz, optimizer) result = sampling_vqe.compute_minimum_eigenvalue(qubit_op) x = sample_most_likely(result.eigenstate) print(x) print(f"Objective value computed by VQE is {objective_value(x, w)}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/quantum-tokyo/qiskit-handson
quantum-tokyo
# importing Qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, execute # import basic plot tools from qiskit.visualization import plot_histogram from qiskit_textbook.tools import simon_oracle b = '110' n = len(b) #=> 3 simon_circuit = QuantumCircuit(n*2, n) #=> QuantumCircuit(6, 3) # 最初の3量子ビットにアダマール変換する simon_circuit.h(range(n)) # Apply barrier for visual separation simon_circuit.barrier() # ビット列b に従って動く f (x) のオラクルを回路に追加する simon_circuit += simon_oracle(b) # Apply barrier for visual separation simon_circuit.barrier() # 最初の3量子ビットにアダマール変換する simon_circuit.h(range(n)) # 測定する simon_circuit.measure(range(n), range(n)) simon_circuit.draw() # use local simulator backend = BasicAer.get_backend('qasm_simulator') shots = 1024 results = execute(simon_circuit, backend=backend, shots=shots).result() counts = results.get_counts() plot_histogram(counts) # 結果に対して、ドット積を計算する。 def bdotz(b, z): accum = 0 for i in range(len(b)): accum += int(b[i]) * int(z[i]) return (accum % 2) for z in counts: print( '{}.{} = {} (mod 2)'.format(b, z, bdotz(b,z)) ) b = '11' n = len(b) simon_circuit_2 = QuantumCircuit(n*2, n) # 最初の2量子ビットにアダマール変換する simon_circuit_2.h(range(n)) # ビット列b に従って動く f (x) のオラクルを回路に追加する simon_circuit_2 += simon_oracle(b) # 最初の2量子ビットにアダマール変換する simon_circuit_2.h(range(n)) # 測定する simon_circuit_2.measure(range(n), range(n)) simon_circuit_2.draw() # Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= n and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Execute and monitor the job from qiskit.tools.monitor import job_monitor shots = 1024 job = execute(simon_circuit_2, backend=backend, shots=shots, optimization_level=3) job_monitor(job, interval = 2) # Get results and plot counts device_counts = job.result().get_counts() plot_histogram(device_counts) # 結果に対して、ドット積を計算する。 def bdotz(b, z): accum = 0 for i in range(len(b)): accum += int(b[i]) * int(z[i]) return (accum % 2) print('b = ' + b) for z in device_counts: print( '{}.{} = {} (mod 2) ({:.1f}%)'.format(b, z, bdotz(b,z), device_counts[z]*100/shots))
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. """A module for visualizing device coupling maps.""" import math from typing import List import numpy as np from qiskit.exceptions import MissingOptionalLibraryError, QiskitError from qiskit.providers.backend import BackendV2 from qiskit.tools.visualization import HAS_MATPLOTLIB, VisualizationError from qiskit.visualization.utils import matplotlib_close_if_inline def plot_gate_map( backend, figsize=None, plot_directed=False, label_qubits=True, qubit_size=None, line_width=4, font_size=None, qubit_color=None, qubit_labels=None, line_color=None, font_color="w", ax=None, filename=None, qubit_coordinates=None, ): """Plots the gate map of a device. Args: backend (BaseBackend): The backend instance that will be used to plot the device gate map. figsize (tuple): Output figure size (wxh) in inches. plot_directed (bool): Plot directed coupling map. label_qubits (bool): Label the qubits. qubit_size (float): Size of qubit marker. line_width (float): Width of lines. font_size (int): Font size of qubit labels. qubit_color (list): A list of colors for the qubits qubit_labels (list): A list of qubit labels line_color (list): A list of colors for each line from coupling_map. font_color (str): The font color for the qubit labels. ax (Axes): A Matplotlib axes instance. filename (str): file path to save image to. Returns: Figure: A Matplotlib figure instance. Raises: QiskitError: if tried to pass a simulator, or if the backend is None, but one of num_qubits, mpl_data, or cmap is None. MissingOptionalLibraryError: if matplotlib not installed. Example: .. jupyter-execute:: :hide-code: :hide-output: from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') .. jupyter-execute:: from qiskit import QuantumCircuit, execute, IBMQ from qiskit.visualization import plot_gate_map %matplotlib inline provider = IBMQ.load_account() accountProvider = IBMQ.get_provider(hub='ibm-q') backend = accountProvider.get_backend('ibmq_vigo') plot_gate_map(backend) """ if not HAS_MATPLOTLIB: raise MissingOptionalLibraryError( libname="Matplotlib", name="plot_gate_map", pip_install="pip install matplotlib", ) if isinstance(backend, BackendV2): pass elif backend.configuration().simulator: raise QiskitError("Requires a device backend, not simulator.") qubit_coordinates_map = {} qubit_coordinates_map[1] = [[0, 0]] qubit_coordinates_map[5] = [[1, 0], [0, 1], [1, 1], [1, 2], [2, 1]] qubit_coordinates_map[7] = [[0, 0], [0, 1], [0, 2], [1, 1], [2, 0], [2, 1], [2, 2]] qubit_coordinates_map[20] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 0], [1, 1], [1, 2], [1, 3], [1, 4], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [3, 0], [3, 1], [3, 2], [3, 3], [3, 4], ] qubit_coordinates_map[15] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 7], [1, 6], [1, 5], [1, 4], [1, 3], [1, 2], [1, 1], [1, 0], ] qubit_coordinates_map[16] = [ [1, 0], [1, 1], [2, 1], [3, 1], [1, 2], [3, 2], [0, 3], [1, 3], [3, 3], [4, 3], [1, 4], [3, 4], [1, 5], [2, 5], [3, 5], [1, 6], ] qubit_coordinates_map[27] = [ [1, 0], [1, 1], [2, 1], [3, 1], [1, 2], [3, 2], [0, 3], [1, 3], [3, 3], [4, 3], [1, 4], [3, 4], [1, 5], [2, 5], [3, 5], [1, 6], [3, 6], [0, 7], [1, 7], [3, 7], [4, 7], [1, 8], [3, 8], [1, 9], [2, 9], [3, 9], [3, 10], ] qubit_coordinates_map[28] = [ [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 2], [1, 6], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [3, 0], [3, 4], [3, 8], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], ] qubit_coordinates_map[53] = [ [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [1, 2], [1, 6], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [3, 0], [3, 4], [3, 8], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], [5, 2], [5, 6], [6, 0], [6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6], [6, 7], [6, 8], [7, 0], [7, 4], [7, 8], [8, 0], [8, 1], [8, 2], [8, 3], [8, 4], [8, 5], [8, 6], [8, 7], [8, 8], [9, 2], [9, 6], ] qubit_coordinates_map[65] = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9], [1, 0], [1, 4], [1, 8], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [2, 9], [2, 10], [3, 2], [3, 6], [3, 10], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], [4, 9], [4, 10], [5, 0], [5, 4], [5, 8], [6, 0], [6, 1], [6, 2], [6, 3], [6, 4], [6, 5], [6, 6], [6, 7], [6, 8], [6, 9], [6, 10], [7, 2], [7, 6], [7, 10], [8, 1], [8, 2], [8, 3], [8, 4], [8, 5], [8, 6], [8, 7], [8, 8], [8, 9], [8, 10], ] if isinstance(backend, BackendV2): num_qubits = backend.num_qubits coupling_map = backend.plot_coupling_map else: config = backend.configuration() num_qubits = config.n_qubits coupling_map = config.coupling_map # don't reference dictionary if provided as a parameter if qubit_coordinates is None: qubit_coordinates = qubit_coordinates_map.get(num_qubits) # try to adjust num_qubits to match the next highest hardcoded grid size if qubit_coordinates is None: if any([num_qubits < key for key in qubit_coordinates_map.keys()]): num_qubits_roundup = max(qubit_coordinates_map.keys()) for key in qubit_coordinates_map.keys(): if key < num_qubits_roundup and key > num_qubits: num_qubits_roundup = key qubit_coordinates = qubit_coordinates_map.get(num_qubits_roundup) return plot_coupling_map( num_qubits, qubit_coordinates, coupling_map, figsize, plot_directed, label_qubits, qubit_size, line_width, font_size, qubit_color, qubit_labels, line_color, font_color, ax, filename, ) def plot_coupling_map( num_qubits: int, qubit_coordinates: List[List[int]], coupling_map: List[List[int]], figsize=None, plot_directed=False, label_qubits=True, qubit_size=None, line_width=4, font_size=None, qubit_color=None, qubit_labels=None, line_color=None, font_color="w", ax=None, filename=None, ): """Plots an arbitrary coupling map of qubits (embedded in a plane). Args: num_qubits (int): The number of qubits defined and plotted. qubit_coordinates (List[List[int]]): A list of two-element lists, with entries of each nested list being the planar coordinates in a 0-based square grid where each qubit is located. coupling_map (List[List[int]]): A list of two-element lists, with entries of each nested list being the qubit numbers of the bonds to be plotted. figsize (tuple): Output figure size (wxh) in inches. plot_directed (bool): Plot directed coupling map. label_qubits (bool): Label the qubits. qubit_size (float): Size of qubit marker. line_width (float): Width of lines. font_size (int): Font size of qubit labels. qubit_color (list): A list of colors for the qubits qubit_labels (list): A list of qubit labels line_color (list): A list of colors for each line from coupling_map. font_color (str): The font color for the qubit labels. ax (Axes): A Matplotlib axes instance. filename (str): file path to save image to. Returns: Figure: A Matplotlib figure instance. Raises: MissingOptionalLibraryError: if matplotlib not installed. QiskitError: If length of qubit labels does not match number of qubits. Example: .. jupyter-execute:: from qiskit.visualization import plot_coupling_map %matplotlib inline num_qubits = 8 coupling_map = [[0, 1], [1, 2], [2, 3], [3, 5], [4, 5], [5, 6], [2, 4], [6, 7]] qubit_coordinates = [[0, 1], [1, 1], [1, 0], [1, 2], [2, 0], [2, 2], [2, 1], [3, 1]] plot_coupling_map(num_qubits, coupling_map, qubit_coordinates) """ if not HAS_MATPLOTLIB: raise MissingOptionalLibraryError( libname="Matplotlib", name="plot_coupling_map", pip_install="pip install matplotlib", ) import matplotlib.patches as mpatches import matplotlib.pyplot as plt input_axes = False if ax: input_axes = True if font_size is None: font_size = 12 if qubit_size is None: qubit_size = 24 if num_qubits > 20: qubit_size = 28 font_size = 10 if qubit_labels is None: qubit_labels = list(range(num_qubits)) else: if len(qubit_labels) != num_qubits: raise QiskitError("Length of qubit labels does not equal number of qubits.") if qubit_coordinates is not None: grid_data = qubit_coordinates else: if not input_axes: fig, ax = plt.subplots(figsize=(5, 5)) ax.axis("off") if filename: fig.savefig(filename) return fig x_max = max(d[1] for d in grid_data) y_max = max(d[0] for d in grid_data) max_dim = max(x_max, y_max) if figsize is None: if num_qubits == 1 or (x_max / max_dim > 0.33 and y_max / max_dim > 0.33): figsize = (5, 5) else: figsize = (9, 3) if ax is None: fig, ax = plt.subplots(figsize=figsize) ax.axis("off") # set coloring if qubit_color is None: qubit_color = ["#648fff"] * num_qubits if line_color is None: line_color = ["#648fff"] * len(coupling_map) if coupling_map else [] # Add lines for couplings if num_qubits != 1: for ind, edge in enumerate(coupling_map): is_symmetric = False if edge[::-1] in coupling_map: is_symmetric = True y_start = grid_data[edge[0]][0] x_start = grid_data[edge[0]][1] y_end = grid_data[edge[1]][0] x_end = grid_data[edge[1]][1] if is_symmetric: if y_start == y_end: x_end = (x_end - x_start) / 2 + x_start elif x_start == x_end: y_end = (y_end - y_start) / 2 + y_start else: x_end = (x_end - x_start) / 2 + x_start y_end = (y_end - y_start) / 2 + y_start ax.add_artist( plt.Line2D( [x_start, x_end], [-y_start, -y_end], color=line_color[ind], linewidth=line_width, zorder=0, ) ) if plot_directed: dx = x_end - x_start dy = y_end - y_start if is_symmetric: x_arrow = x_start + dx * 0.95 y_arrow = -y_start - dy * 0.95 dx_arrow = dx * 0.01 dy_arrow = -dy * 0.01 head_width = 0.15 else: x_arrow = x_start + dx * 0.5 y_arrow = -y_start - dy * 0.5 dx_arrow = dx * 0.2 dy_arrow = -dy * 0.2 head_width = 0.2 ax.add_patch( mpatches.FancyArrow( x_arrow, y_arrow, dx_arrow, dy_arrow, head_width=head_width, length_includes_head=True, edgecolor=None, linewidth=0, facecolor=line_color[ind], zorder=1, ) ) # Add circles for qubits for var, idx in enumerate(grid_data): # add check if num_qubits had been rounded up if var >= num_qubits: break _idx = [idx[1], -idx[0]] ax.add_artist( mpatches.Ellipse( _idx, qubit_size / 48, qubit_size / 48, # This is here so that the changes color=qubit_color[var], zorder=1, ) ) # to how qubits are plotted does if label_qubits: # not affect qubit size kwarg. ax.text( *_idx, s=qubit_labels[var], horizontalalignment="center", verticalalignment="center", color=font_color, size=font_size, weight="bold", ) ax.set_xlim([-1, x_max + 1]) ax.set_ylim([-(y_max + 1), 1]) ax.set_aspect("equal") if not input_axes: matplotlib_close_if_inline(fig) if filename: fig.savefig(filename) return fig return None def plot_circuit_layout(circuit, backend, view="virtual", qubit_coordinates=None): """Plot the layout of a circuit transpiled for a given target backend. Args: circuit (QuantumCircuit): Input quantum circuit. backend (BaseBackend): Target backend. view (str): Layout view: either 'virtual' or 'physical'. Returns: Figure: A matplotlib figure showing layout. Raises: QiskitError: Invalid view type given. VisualizationError: Circuit has no layout attribute. Example: .. jupyter-execute:: :hide-code: :hide-output: from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') .. jupyter-execute:: import numpy as np from qiskit import QuantumCircuit, IBMQ, transpile from qiskit.visualization import plot_histogram, plot_gate_map, plot_circuit_layout from qiskit.tools.monitor import job_monitor import matplotlib.pyplot as plt %matplotlib inline IBMQ.load_account() ghz = QuantumCircuit(3, 3) ghz.h(0) for idx in range(1,3): ghz.cx(0,idx) ghz.measure(range(3), range(3)) provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_vigo') new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend) """ if circuit._layout is None: raise QiskitError("Circuit has no layout. Perhaps it has not been transpiled.") if isinstance(backend, BackendV2): num_qubits = backend.num_qubits else: num_qubits = backend.configuration().n_qubits qubits = [] qubit_labels = [None] * num_qubits bit_locations = { bit: {"register": register, "index": index} for register in circuit._layout.get_registers() for index, bit in enumerate(register) } for index, qubit in enumerate(circuit._layout.get_virtual_bits()): if qubit not in bit_locations: bit_locations[qubit] = {"register": None, "index": index} if view == "virtual": for key, val in circuit._layout.get_virtual_bits().items(): bit_register = bit_locations[key]["register"] if bit_register is None or bit_register.name != "ancilla": qubits.append(val) qubit_labels[val] = bit_locations[key]["index"] elif view == "physical": for key, val in circuit._layout.get_physical_bits().items(): bit_register = bit_locations[val]["register"] if bit_register is None or bit_register.name != "ancilla": qubits.append(key) qubit_labels[key] = key else: raise VisualizationError("Layout view must be 'virtual' or 'physical'.") qcolors = ["#648fff"] * num_qubits for k in qubits: qcolors[k] = "k" if isinstance(backend, BackendV2): cmap = backend.plot_coupling_map else: cmap = backend.configuration().coupling_map lcolors = ["#648fff"] * len(cmap) for idx, edge in enumerate(cmap): if edge[0] in qubits and edge[1] in qubits: lcolors[idx] = "k" fig = plot_gate_map( backend, qubit_color=qcolors, qubit_labels=qubit_labels, line_color=lcolors, qubit_coordinates=qubit_coordinates, ) return fig def plot_error_map(backend, figsize=(12, 9), show_title=True): """Plots the error map of a given backend. Args: backend (IBMQBackend): Given backend. figsize (tuple): Figure size in inches. show_title (bool): Show the title or not. Returns: Figure: A matplotlib figure showing error map. Raises: VisualizationError: Input is not IBMQ backend. VisualizationError: The backend does not provide gate errors for the 'sx' gate. MissingOptionalLibraryError: If seaborn is not installed Example: .. jupyter-execute:: :hide-code: :hide-output: from qiskit.test.ibmq_mock import mock_get_backend mock_get_backend('FakeVigo') .. jupyter-execute:: from qiskit import QuantumCircuit, execute, IBMQ from qiskit.visualization import plot_error_map %matplotlib inline IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') backend = provider.get_backend('ibmq_vigo') plot_error_map(backend) """ try: import seaborn as sns except ImportError as ex: raise MissingOptionalLibraryError( libname="seaborn", name="plot_error_map", pip_install="pip install seaborn", ) from ex if not HAS_MATPLOTLIB: raise MissingOptionalLibraryError( libname="Matplotlib", name="plot_error_map", pip_install="pip install matplotlib", ) import matplotlib import matplotlib.pyplot as plt from matplotlib import gridspec, ticker color_map = sns.cubehelix_palette(reverse=True, as_cmap=True) props = backend.properties().to_dict() config = backend.configuration().to_dict() num_qubits = config["n_qubits"] # sx error rates single_gate_errors = [0] * num_qubits for gate in props["gates"]: if gate["gate"] == "sx": _qubit = gate["qubits"][0] for param in gate["parameters"]: if param["name"] == "gate_error": single_gate_errors[_qubit] = param["value"] break else: raise VisualizationError( f"Backend '{backend}' did not supply an error for the 'sx' gate." ) # Convert to percent single_gate_errors = 100 * np.asarray(single_gate_errors) avg_1q_err = np.mean(single_gate_errors) single_norm = matplotlib.colors.Normalize( vmin=min(single_gate_errors), vmax=max(single_gate_errors) ) q_colors = [color_map(single_norm(err)) for err in single_gate_errors] cmap = config["coupling_map"] directed = False line_colors = [] if cmap: directed = False if num_qubits < 20: for edge in cmap: if [edge[1], edge[0]] not in cmap: directed = True break cx_errors = [] for line in cmap: for item in props["gates"]: if item["qubits"] == line: cx_errors.append(item["parameters"][0]["value"]) break else: continue # Convert to percent cx_errors = 100 * np.asarray(cx_errors) avg_cx_err = np.mean(cx_errors) cx_norm = matplotlib.colors.Normalize(vmin=min(cx_errors), vmax=max(cx_errors)) line_colors = [color_map(cx_norm(err)) for err in cx_errors] # Measurement errors read_err = [] for qubit in range(num_qubits): for item in props["qubits"][qubit]: if item["name"] == "readout_error": read_err.append(item["value"]) read_err = 100 * np.asarray(read_err) avg_read_err = np.mean(read_err) max_read_err = np.max(read_err) fig = plt.figure(figsize=figsize) gridspec.GridSpec(nrows=2, ncols=3) grid_spec = gridspec.GridSpec( 12, 12, height_ratios=[1] * 11 + [0.5], width_ratios=[2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2], ) left_ax = plt.subplot(grid_spec[2:10, :1]) main_ax = plt.subplot(grid_spec[:11, 1:11]) right_ax = plt.subplot(grid_spec[2:10, 11:]) bleft_ax = plt.subplot(grid_spec[-1, :5]) if cmap: bright_ax = plt.subplot(grid_spec[-1, 7:]) qubit_size = 28 if num_qubits <= 5: qubit_size = 20 plot_gate_map( backend, qubit_color=q_colors, line_color=line_colors, qubit_size=qubit_size, line_width=5, plot_directed=directed, ax=main_ax, ) main_ax.axis("off") main_ax.set_aspect(1) if cmap: single_cb = matplotlib.colorbar.ColorbarBase( bleft_ax, cmap=color_map, norm=single_norm, orientation="horizontal" ) tick_locator = ticker.MaxNLocator(nbins=5) single_cb.locator = tick_locator single_cb.update_ticks() single_cb.update_ticks() bleft_ax.set_title(f"H error rate (%) [Avg. = {round(avg_1q_err, 3)}]") if cmap is None: bleft_ax.axis("off") bleft_ax.set_title(f"H error rate (%) = {round(avg_1q_err, 3)}") if cmap: cx_cb = matplotlib.colorbar.ColorbarBase( bright_ax, cmap=color_map, norm=cx_norm, orientation="horizontal" ) tick_locator = ticker.MaxNLocator(nbins=5) cx_cb.locator = tick_locator cx_cb.update_ticks() bright_ax.set_title(f"CNOT error rate (%) [Avg. = {round(avg_cx_err, 3)}]") if num_qubits < 10: num_left = num_qubits num_right = 0 else: num_left = math.ceil(num_qubits / 2) num_right = num_qubits - num_left left_ax.barh(range(num_left), read_err[:num_left], align="center", color="#DDBBBA") left_ax.axvline(avg_read_err, linestyle="--", color="#212121") left_ax.set_yticks(range(num_left)) left_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)]) left_ax.set_yticklabels([str(kk) for kk in range(num_left)], fontsize=12) left_ax.invert_yaxis() left_ax.set_title("Readout Error (%)", fontsize=12) for spine in left_ax.spines.values(): spine.set_visible(False) if num_right: right_ax.barh( range(num_left, num_qubits), read_err[num_left:], align="center", color="#DDBBBA", ) right_ax.axvline(avg_read_err, linestyle="--", color="#212121") right_ax.set_yticks(range(num_left, num_qubits)) right_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)]) right_ax.set_yticklabels( [str(kk) for kk in range(num_left, num_qubits)], fontsize=12 ) right_ax.invert_yaxis() right_ax.invert_xaxis() right_ax.yaxis.set_label_position("right") right_ax.yaxis.tick_right() right_ax.set_title("Readout Error (%)", fontsize=12) else: right_ax.axis("off") for spine in right_ax.spines.values(): spine.set_visible(False) if show_title: fig.suptitle(f"{backend.name()} Error Map", fontsize=24, y=0.9) matplotlib_close_if_inline(fig) return fig
https://github.com/ardieb/QiskitPlayground
ardieb
from qiskit import * from qiskit.quantum_info import * from qiskit.visualization import * from qiskit.circuit.library import * import matplotlib.pyplot as plt import numpy as np import pandas as pd import itertools import collections import typing %matplotlib inline Array = np.ndarray def teleporter(phi: Array): assert phi.shape[0] == 2, "initialized state must have 2 entries (single qubit)" qr = QuantumRegister(3, 'q') crz = ClassicalRegister(1, 'crz') crx = ClassicalRegister(1, 'crx') circ = QuantumCircuit(qr, crz, crx) circ.reset(qr[1]) circ.reset(qr[2]) circ.h(qr[1]) circ.cx(qr[1], qr[2]) circ.initialize(phi, qr[0]) circ.barrier() circ.cx(qr[0], qr[1]) circ.h(qr[0]) circ.barrier() circ.measure(qr[1], crx) circ.measure(qr[0], crz) circ.barrier() circ.x(qr[2]).c_if(crx, 1) circ.z(qr[2]).c_if(crz, 1) return circ sv_simulator = Aer.get_backend('statevector_simulator') # Let's teleport the state 1/sqrt(2) [1, exp(i pi / 4)] phi = np.array([1/np.sqrt(2), 1/np.sqrt(2) * np.exp(1j * np.pi / 4)]) circ = teleporter(phi) display(circ.draw('mpl')) result = execute(circ, sv_simulator).result() display(plot_bloch_multivector(result.get_statevector(circ, decimals = 3))) def key_update(a: int, b: int, c: int, d: int): assert all(0 <= x <= 1 for x in [a,b,c,d]), "inputs must be an integer modulo 2" return {'H': f'{b}{a}', 'X': f'{a}{b}', 'Z': f'{a}{b}', 'S': f'{a}{a ^ b}', 'cX': f'{a}{b ^ d}{a ^ c}{d}'} df = [] for a in (0, 1): for b in (0, 1): for c in (0, 1): for d in (0, 1): update = key_update(a, b, c, d) update['abcd'] = f'{a}{b}{c}{d}' df.append(update) df = pd.DataFrame(df) df.set_index('abcd', inplace = True) print(df) # rho = 1/2 * np.array([[1,3], [3, 1]]) # tau = 0.8 qr = QuantumRegister(5, 'q') cr = ClassicalRegister(5, 'c') qpce = QuantumCircuit(qr, cr) # prepare the state theta1, theta2, alpha = 0.643, 2.498, 2.094 qpce.h(qr[3]) qpce.x(qr[3]) qpce.cu(theta1, 0, 0, 0, qr[3], qr[4]) qpce.x(qr[3]) qpce.cu(theta2, 0, 0, 0, qr[3], qr[4]) qpce.barrier() # phase estimation qpce.h(qr[1]) qpce.h(qr[2]) qpce.cu(-np.pi/2, -np.pi/2, np.pi/2, 0, qr[2], qr[3]) qpce.p(3*np.pi/4, qr[2]) qpce.cx(qr[1], qr[3]) qpce.swap(qr[1], qr[2]) qpce.h(qr[2]) qpce.cp(-np.pi/2, qr[1], qr[2]) qpce.h(qr[1]) qpce.barrier() # Controlled rotation qpce.cx(qr[1], qr[2]) qpce.cu(alpha, 0, 0, 0, qr[1], qr[0]) qpce.cu(alpha, 0, 0, 0, qr[2], qr[0]) qpce.cx(qr[1], qr[2]) qpce.barrier() # Inverse phase estimation qpce.h(qr[1]) qpce.cp(np.pi/2, qr[1], qr[2]) qpce.h(qr[2]) qpce.swap(qr[1], qr[2]) qpce.cx(qr[1], qr[3]) qpce.h(qr[1]) qpce.p(-3*np.pi/4, qr[2]) qpce.cu(-np.pi/2, -np.pi/2, np.pi/2, 0, qr[2], qr[3]) qpce.h(qr[2]) qpce.barrier() # Measurement qpce.measure(qr[0], cr[0]) qpce.measure(qr[1], cr[1]) qpce.measure(qr[2], cr[2]) qpce.measure(qr[3], cr[3]) qpce.measure(qr[4], cr[4]) qpce.draw('mpl') qasm_simulator = Aer.get_backend('qasm_simulator') result = execute(qpce, qasm_simulator, shots=2048).result() display(plot_histogram(result.get_counts())) # The operation is HTHT # a0, b0 = 1, 1 qr = QuantumRegister(5, 'q') cr = ClassicalRegister(5, 'c') qku = QuantumCircuit(qr, cr) # initialize qku.reset(qr[0]) qku.reset(qr[1]) qku.reset(qr[3]) qku.h(qr[0]) qku.h(qr[1]) qku.h(qr[3]) qku.x(qr[0]) qku.cx(qr[1], qr[2]) qku.cx(qr[3], qr[4]) qku.z(qr[0]) qku.t(qr[0]) qku.swap(qr[0], qr[1]) qku.h(qr[0]) qku.s(qr[1]) qku.t(qr[0]) qku.cx(qr[1], qr[2]) qku.h(qr[1]) qku.swap(qr[0], qr[3]) qku.h(qr[0]) qku.s(qr[3]) qku.cx(qr[3], qr[4]) qku.h(qr[3]) qku.barrier() qku.measure(qr[4], cr[4]) qku.measure(qr[3], cr[3]) qku.measure(qr[2], cr[2]) qku.measure(qr[1], cr[1]) qku.measure(qr[0], cr[0]) qku.draw('mpl') result = execute(qku, qasm_simulator, shots=2048).result() display(plot_histogram(result.get_counts(), figsize=(10,10))) # The operation is HTHT # a0, b0 = 0, 1 qr = QuantumRegister(5, 'q') cr = ClassicalRegister(5, 'c') qku = QuantumCircuit(qr, cr) # initialize qku.reset(qr[0]) qku.reset(qr[1]) qku.reset(qr[3]) qku.h(qr[0]) qku.h(qr[1]) qku.h(qr[3]) # qku.x(qr[0]) a = 0 qku.cx(qr[1], qr[2]) qku.cx(qr[3], qr[4]) qku.z(qr[0]) qku.t(qr[0]) qku.swap(qr[0], qr[1]) qku.h(qr[0]) qku.s(qr[1]) qku.t(qr[0]) qku.cx(qr[1], qr[2]) qku.h(qr[1]) qku.swap(qr[0], qr[3]) qku.h(qr[0]) qku.s(qr[3]) qku.cx(qr[3], qr[4]) qku.h(qr[3]) qku.barrier() #ra(2) qku.measure(qr[4], cr[4]) #rb(2) qku.measure(qr[3], cr[3]) #ra(1) qku.measure(qr[2], cr[2]) #rb(1) qku.measure(qr[1], cr[1]) #q0 qku.measure(qr[0], cr[0]) qku.draw('mpl') result = execute(qku, qasm_simulator, shots=2048).result() display(plot_histogram(result.get_counts(), figsize=(10,10))) # Select 4 measurements with high probability, here we choose > 0.05 import random sample = [] counts = list(result.get_counts().items()) total = sum(x for _, x in counts) while len(sample) < 4: state, count = counts[random.randint(0,len(counts)-1)] if count / total >= 0.05: sample.append(state) print(sample) a0, b0 = 0, 1 for state in sample: ra2, rb2, ra1, rb1, q0 = [int(c) for c in state] af = b0 ^ ra1 ^ rb1 ^ rb2 bf = a0 ^ b0 ^ rb1 ^ ra2 print(f'Measurements are {state}') print(f'Final decyption keys: {af}, {bf}') print(f'Final state measurement: {q0}') # here we find the opposite of the researchers result, where if af = 0 we measure q0 = 0 and if af = 1 we measure q0 = 1
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
%matplotlib inline import matplotlib import numpy as np import matplotlib.pyplot as plt import sympy from sympy import * import itertools from IPython.display import display init_printing() #allows nice math displays class QuantumMatrix(): def __init__(self, m, coeff = 1): self.matrix = sympy.Matrix(m) self.coefficient = coeff self.canonize() def canonize(self): a = next((x for x in self.matrix if x != 0), None) if a is not None: #zero vector for i,j in itertools.product([0,1], [0,1]): self.matrix[i,j] = sympy.simplify(self.matrix[i,j] / a) self.coefficient = sympy.simplify(self.coefficient * a) def __str__(self): coeff_string = "" if self.coefficient != 1: coeff_string = "{} * ".format(self.coefficient) return "{}[[{}, {}], [{}, {}]]".format(coeff_string,self.matrix[0], self.matrix[1], self.matrix[2], self.matrix[3]) def __mul__(self, rhs): return QuantumMatrix(self.matrix * rhs.matrix, self.coefficient * rhs.coefficient) def __add__(self, rhs): temp_rhs_matrix = sympy.Matrix([[1,0],[0,1]]) for i,j in itertools.product([0,1], [0,1]): temp_rhs_matrix[i,j] = sympy.simplify((rhs.matrix[i,j] * self.coefficient) / rhs.coefficient) return QuantumMatrix(self.matrix + temp_rhs_matrix, self.coefficient * 1/sympy.sqrt(2)) def __sub__(self, rhs): return self + QuantumMatrix(rhs.matrix, rhs.coefficient * -1) def __eq__(self, rhs): return (self.matrix == rhs.matrix and self.coefficient == rhs.coefficient) def equiv(self, rhs): return (self.matrix == rhs.matrix) def __iter__(self): for x in self.matrix: yield x X = QuantumMatrix( [[0,1], [1,0]]) Y = QuantumMatrix( [[0,-sympy.I], [sympy.I,0]]) Z = QuantumMatrix( [[1,0], [0,-1]]) I = QuantumMatrix( [[1,0], [0,1]]) print ("The Pauli matrices (when neglecting the global phase):") print ("Identity: I=") display(sympy.Matrix(I.matrix)) print ("X=") display(sympy.Matrix(X.matrix)) print ("Y=") display(sympy.Matrix(Y.matrix)) print ("Z=") display(sympy.Matrix(Z.matrix)) print ("The Pauli gates X,Y,Z are of order 2:") A=X*X print ("X*X=") display(sympy.Matrix(A.matrix)) A=Y*Y print ("Y*Y=") display(sympy.Matrix(A.matrix)) A=Z*Z print ("Z*Z=") display(sympy.Matrix(A.matrix)) print ("For example, one can verify that X*Y=Y*X=Z:") A=X*Y B=Y*X print ("X*Y = Z =") display(sympy.Matrix(A.matrix)) print ("Y*X = Z =") display(sympy.Matrix(B.matrix)) print ("Similarly, X*Z=Z*X=Y, Y*Z=Z*Y=X") H = QuantumMatrix( [[1,1], [1,-1]], 1/sympy.sqrt(2)) print ("Hadamard gate: H=") display(sympy.Matrix(H.matrix)) print ("H is of order 2:") A=H*H print ("H*H =") display(sympy.Matrix(A.matrix)) print ("H operates on the Pauli gates by conjugation as a reflection: X<-->Z:") A=H*X*H print("H*X*H = Z =") display(sympy.Matrix(A.matrix)) A=H*Z*H print("H*Z*H = X =") display(sympy.Matrix(A.matrix)) A=H*Y*H print("H*Y*H = Y =") display(sympy.Matrix(A.matrix)) S = QuantumMatrix( [[1,0], [0,sympy.I]]) print ("Phase gate: S=") display(sympy.Matrix(S.matrix)) print ("Z=S*S, thus S has order 4, and the inverse of S is S*Z:") A=S*S print ("S*S = Z =") display(sympy.Matrix(A.matrix)) print ("The inverse of S: Sdg = S*Z =") Sdg = S*Z display(sympy.Matrix(Sdg.matrix)) print ("Indeed, S*Sdg =") A = S*Sdg display(sympy.Matrix(A.matrix)) print ("S operates on the Pauli gates by conjugation as a reflection: Y<-->Z:") A = S*X*Sdg # =Y print ("S*X*Sdg = Y =") display(sympy.Matrix(A.matrix)) print ("S*Y*Sdg = X =") A = S*Y*Sdg # =X display(sympy.Matrix(A.matrix)) print ("S*Z*Sdg = Z =") A = S*Z*Sdg # =Z display(sympy.Matrix(A.matrix)) print ("We therefore get the commutator relations:") print ("S*X = Y*S and Sdg*Y = X*Sdg") print ("S*Y = X*S and Sdg*X = Y*Sdg") print ("S*Z = Z*S = Sdg and Sdg*Z = Z*Sdg = S") V = H*S*H*S print ("Let: V = H*S*H*S =") display(sympy.Matrix(V.matrix)) print ("V is of order 3:") A=V*V*V print ("V*V*V =") display(sympy.Matrix(A.matrix)) print ("Hence, V = Sdg*H =") A=Sdg*H display(sympy.Matrix(A.matrix)) print ("The inverse of V is: W = S*Z*H*S*Z*H = H*S = ") W=H*S display(sympy.Matrix(W.matrix)) print ("Indeed, W = V*V =") A=V*V display(sympy.Matrix(A.matrix)) print ("V operates on the Pauli gates by conjugation as a rotation: Z-->X-->Y-->Z:") A=W*X*V print("W*X*V = Y =") display(sympy.Matrix(A.matrix)) A=W*Y*V print("W*Y*V = Z =") display(sympy.Matrix(A.matrix)) A=W*Z*V print("W*Z*V = X = ") display(sympy.Matrix(A.matrix)) print ("I=") display(sympy.Matrix(I.matrix)) print ("X=") display(sympy.Matrix(X.matrix)) print ("Y=") display(sympy.Matrix(Y.matrix)) print ("Z=") display(sympy.Matrix(Z.matrix)) print ("V=") display(sympy.Matrix(V.matrix)) A=V*X print ("V*X=") display(sympy.Matrix(A.matrix)) A=V*Y print ("V*Y=") display(sympy.Matrix(A.matrix)) A=V*Z print ("V*Z=") display(sympy.Matrix(A.matrix)) print ("W=") display(sympy.Matrix(W.matrix)) A=W*X print ("W*X=") display(sympy.Matrix(A.matrix)) A=W*Y print ("W*Y=") display(sympy.Matrix(A.matrix)) A=W*Z print ("W*Z=") display(sympy.Matrix(A.matrix)) print ("H=") display(sympy.Matrix(H.matrix)) A=H*X print ("H*X=") display(sympy.Matrix(A.matrix)) A=H*Y print ("H*Y=") display(sympy.Matrix(A.matrix)) A=H*Z print ("H*Z=") display(sympy.Matrix(A.matrix)) print ("H*V=") A=H*V display(sympy.Matrix(A.matrix)) A=H*V*X print ("H*V*X=") display(sympy.Matrix(A.matrix)) A=H*V*Y print ("H*V*Y=") display(sympy.Matrix(A.matrix)) A=H*V*Z print ("H*V*Z=") display(sympy.Matrix(A.matrix)) print ("H*W=") A=H*W display(sympy.Matrix(A.matrix)) A=H*W*X print ("H*W*X=") display(sympy.Matrix(A.matrix)) A=H*W*Y print ("H*W*Y=") display(sympy.Matrix(A.matrix)) A=H*W*Z print ("H*W*Z=") display(sympy.Matrix(A.matrix)) print ("H*V = H*H*S*H*S = S*H*S =") A=S*H*S #H*V display(sympy.Matrix(A.matrix)) A=Sdg*H*S #H*V*Y print ("H*V*Y = H*H*S*H*S*Y = S*H*S*Y = S*H*X*S = S*Z*H*S = Sdg*H*S =") display(sympy.Matrix(A.matrix)) A=S*H*Sdg #H*V*Z print ("H*V*Z = H*H*S*H*S*Z = S*H*Sdg =") display(sympy.Matrix(A.matrix)) print ("H*W = H*H*S = S =") A=S #H*W display(sympy.Matrix(A.matrix)) A= S*X #H*W*X print ("H*W*X = S*X = ") display(sympy.Matrix(A.matrix)) A=S*Y #H*W*Y print ("H*W*Y = S*Y =") display(sympy.Matrix(A.matrix)) A=Sdg #H*W*Z print ("H*W*Z = Sdg =") display(sympy.Matrix(A.matrix)) Class1Size = 2*2*3*3*4*4 print ("The size of Class 1 is: ", Class1Size) Class2Size = 2*2*3*3*3*3*4*4 print ("The size of Class 2 is: ", Class2Size) Class3Size = 2*2*3*3*3*3*4*4 print ("The size of Class 3 is: ", Class3Size) Class4Size = 2*2*3*3*4*4 print ("The size of Class 4 is: ", Class4Size) TotalSize = Class1Size + Class2Size + Class3Size + Class4Size print ("The size of the 2-qubit Clifford group is: ", TotalSize)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 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. """ Stabilizer state class. """ from __future__ import annotations import numpy as np from qiskit.exceptions import QiskitError from qiskit.quantum_info.operators.op_shape import OpShape from qiskit.quantum_info.operators.operator import Operator from qiskit.quantum_info.operators.symplectic import Clifford, Pauli, PauliList from qiskit.quantum_info.operators.symplectic.clifford_circuits import _append_x from qiskit.quantum_info.states.quantum_state import QuantumState from qiskit.circuit import QuantumCircuit, Instruction class StabilizerState(QuantumState): """StabilizerState class. Stabilizer simulator using the convention from reference [1]. Based on the internal class :class:`~qiskit.quantum_info.Clifford`. .. code-block:: from qiskit import QuantumCircuit from qiskit.quantum_info import StabilizerState, Pauli # Bell state generation circuit qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) stab = StabilizerState(qc) # Print the StabilizerState print(stab) # Calculate the StabilizerState measurement probabilities dictionary print (stab.probabilities_dict()) # Calculate expectation value of the StabilizerState print (stab.expectation_value(Pauli('ZZ'))) .. parsed-literal:: StabilizerState(StabilizerTable: ['+XX', '+ZZ']) {'00': 0.5, '11': 0.5} 1 References: 1. S. Aaronson, D. Gottesman, *Improved Simulation of Stabilizer Circuits*, Phys. Rev. A 70, 052328 (2004). `arXiv:quant-ph/0406196 <https://arxiv.org/abs/quant-ph/0406196>`_ """ def __init__( self, data: StabilizerState | Clifford | Pauli | QuantumCircuit | Instruction, validate: bool = True, ): """Initialize a StabilizerState object. Args: data (StabilizerState or Clifford or Pauli or QuantumCircuit or qiskit.circuit.Instruction): Data from which the stabilizer state can be constructed. validate (boolean): validate that the stabilizer state data is a valid Clifford. """ # Initialize from another StabilizerState if isinstance(data, StabilizerState): self._data = data._data # Initialize from a Pauli elif isinstance(data, Pauli): self._data = Clifford(data.to_instruction()) # Initialize from a Clifford, QuantumCircuit or Instruction else: self._data = Clifford(data, validate) # Initialize super().__init__(op_shape=OpShape.auto(num_qubits_r=self._data.num_qubits, num_qubits_l=0)) def __eq__(self, other): return (self._data.stab == other._data.stab).all() def __repr__(self): return f"StabilizerState({self._data.stabilizer})" @property def clifford(self): """Return StabilizerState Clifford data""" return self._data def is_valid(self, atol=None, rtol=None): """Return True if a valid StabilizerState.""" return self._data.is_unitary() def _add(self, other): raise NotImplementedError(f"{type(self)} does not support addition") def _multiply(self, other): raise NotImplementedError(f"{type(self)} does not support scalar multiplication") def trace(self) -> float: """Return the trace of the stabilizer state as a density matrix, which equals to 1, since it is always a pure state. Returns: float: the trace (should equal 1). Raises: QiskitError: if input is not a StabilizerState. """ if not self.is_valid(): raise QiskitError("StabilizerState is not a valid quantum state.") return 1.0 def purity(self) -> float: """Return the purity of the quantum state, which equals to 1, since it is always a pure state. Returns: float: the purity (should equal 1). Raises: QiskitError: if input is not a StabilizerState. """ if not self.is_valid(): raise QiskitError("StabilizerState is not a valid quantum state.") return 1.0 def to_operator(self) -> Operator: """Convert state to matrix operator class""" return Clifford(self.clifford).to_operator() def conjugate(self): """Return the conjugate of the operator.""" ret = self.copy() ret._data = ret._data.conjugate() return ret def tensor(self, other: StabilizerState) -> StabilizerState: """Return the tensor product stabilizer state self ⊗ other. Args: other (StabilizerState): a stabilizer state object. Returns: StabilizerState: the tensor product operator self ⊗ other. Raises: QiskitError: if other is not a StabilizerState. """ if not isinstance(other, StabilizerState): other = StabilizerState(other) ret = self.copy() ret._data = self.clifford.tensor(other.clifford) return ret def expand(self, other: StabilizerState) -> StabilizerState: """Return the tensor product stabilizer state other ⊗ self. Args: other (StabilizerState): a stabilizer state object. Returns: StabilizerState: the tensor product operator other ⊗ self. Raises: QiskitError: if other is not a StabilizerState. """ if not isinstance(other, StabilizerState): other = StabilizerState(other) ret = self.copy() ret._data = self.clifford.expand(other.clifford) return ret def evolve( self, other: Clifford | QuantumCircuit | Instruction, qargs: list | None = None ) -> StabilizerState: """Evolve a stabilizer state by a Clifford operator. Args: other (Clifford or QuantumCircuit or qiskit.circuit.Instruction): The Clifford operator to evolve by. qargs (list): a list of stabilizer subsystem positions to apply the operator on. Returns: StabilizerState: the output stabilizer state. Raises: QiskitError: if other is not a StabilizerState. QiskitError: if the operator dimension does not match the specified StabilizerState subsystem dimensions. """ if not isinstance(other, StabilizerState): other = StabilizerState(other) ret = self.copy() ret._data = self.clifford.compose(other.clifford, qargs=qargs) return ret def expectation_value(self, oper: Pauli, qargs: None | list = None) -> complex: """Compute the expectation value of a Pauli operator. Args: oper (Pauli): a Pauli operator to evaluate expval. qargs (None or list): subsystems to apply the operator on. Returns: complex: the expectation value (only 0 or 1 or -1 or i or -i). Raises: QiskitError: if oper is not a Pauli operator. """ if not isinstance(oper, Pauli): raise QiskitError("Operator for expectation value is not a Pauli operator.") num_qubits = self.clifford.num_qubits if qargs is None: qubits = range(num_qubits) else: qubits = qargs # Construct Pauli on num_qubits pauli = Pauli(num_qubits * "I") phase = 0 pauli_phase = (-1j) ** oper.phase if oper.phase else 1 for pos, qubit in enumerate(qubits): pauli.x[qubit] = oper.x[pos] pauli.z[qubit] = oper.z[pos] phase += pauli.x[qubit] & pauli.z[qubit] # Check if there is a stabilizer that anti-commutes with an odd number of qubits # If so the expectation value is 0 for p in range(num_qubits): num_anti = 0 num_anti += np.count_nonzero(pauli.z & self.clifford.stab_x[p]) num_anti += np.count_nonzero(pauli.x & self.clifford.stab_z[p]) if num_anti % 2 == 1: return 0 # Otherwise pauli is (-1)^a prod_j S_j^b_j for Clifford stabilizers # If pauli anti-commutes with D_j then b_j = 1. # Multiply pauli by stabilizers with anti-commuting destabilizers pauli_z = (pauli.z).copy() # Make a copy of pauli.z for p in range(num_qubits): # Check if destabilizer anti-commutes num_anti = 0 num_anti += np.count_nonzero(pauli.z & self.clifford.destab_x[p]) num_anti += np.count_nonzero(pauli.x & self.clifford.destab_z[p]) if num_anti % 2 == 0: continue # If anti-commutes multiply Pauli by stabilizer phase += 2 * self.clifford.stab_phase[p] phase += np.count_nonzero(self.clifford.stab_z[p] & self.clifford.stab_x[p]) phase += 2 * np.count_nonzero(pauli_z & self.clifford.stab_x[p]) pauli_z = pauli_z ^ self.clifford.stab_z[p] # For valid stabilizers, `phase` can only be 0 (= 1) or 2 (= -1) at this point. if phase % 4 != 0: return -pauli_phase return pauli_phase def equiv(self, other: StabilizerState) -> bool: """Return True if the two generating sets generate the same stabilizer group. Args: other (StabilizerState): another StabilizerState. Returns: bool: True if other has a generating set that generates the same StabilizerState. """ if not isinstance(other, StabilizerState): try: other = StabilizerState(other) except QiskitError: return False num_qubits = self.num_qubits if other.num_qubits != num_qubits: return False pauli_orig = PauliList.from_symplectic( self._data.stab_z, self._data.stab_x, 2 * self._data.stab_phase ) pauli_other = PauliList.from_symplectic( other._data.stab_z, other._data.stab_x, 2 * other._data.stab_phase ) # Check that each stabilizer from the original set commutes with each stabilizer # from the other set if not np.all([pauli.commutes(pauli_other) for pauli in pauli_orig]): return False # Compute the expected value of each stabilizer from the original set on the stabilizer state # determined by the other set. The two stabilizer states coincide if and only if the # expected value is +1 for each stabilizer for i in range(num_qubits): exp_val = self.expectation_value(pauli_other[i]) if exp_val != 1: return False return True def probabilities(self, qargs: None | list = None, decimals: None | int = None) -> np.ndarray: """Return the subsystem measurement probability vector. Measurement probabilities are with respect to measurement in the computation (diagonal) basis. Args: qargs (None or list): subsystems to return probabilities for, if None return for all subsystems (Default: None). decimals (None or int): the number of decimal places to round values. If None no rounding is done (Default: None). Returns: np.array: The Numpy vector array of probabilities. """ probs_dict = self.probabilities_dict(qargs, decimals) if qargs is None: qargs = range(self.clifford.num_qubits) probs = np.zeros(2 ** len(qargs)) for key, value in probs_dict.items(): place = int(key, 2) probs[place] = value return probs def probabilities_dict(self, qargs: None | list = None, decimals: None | int = None) -> dict: """Return the subsystem measurement probability dictionary. Measurement probabilities are with respect to measurement in the computation (diagonal) basis. This dictionary representation uses a Ket-like notation where the dictionary keys are qudit strings for the subsystem basis vectors. If any subsystem has a dimension greater than 10 comma delimiters are inserted between integers so that subsystems can be distinguished. Args: qargs (None or list): subsystems to return probabilities for, if None return for all subsystems (Default: None). decimals (None or int): the number of decimal places to round values. If None no rounding is done (Default: None). Returns: dict: The measurement probabilities in dict (ket) form. """ if qargs is None: qubits = range(self.clifford.num_qubits) else: qubits = qargs outcome = ["X"] * len(qubits) outcome_prob = 1.0 probs = {} # probabilities dictionary self._get_probablities(qubits, outcome, outcome_prob, probs) if decimals is not None: for key, value in probs.items(): probs[key] = round(value, decimals) return probs def reset(self, qargs: list | None = None) -> StabilizerState: """Reset state or subsystems to the 0-state. Args: qargs (list or None): subsystems to reset, if None all subsystems will be reset to their 0-state (Default: None). Returns: StabilizerState: the reset state. Additional Information: If all subsystems are reset this will return the ground state on all subsystems. If only some subsystems are reset this function will perform a measurement on those subsystems and evolve the subsystems so that the collapsed post-measurement states are rotated to the 0-state. The RNG seed for this sampling can be set using the :meth:`seed` method. """ # Resetting all qubits does not require sampling or RNG if qargs is None: return StabilizerState(Clifford(np.eye(2 * self.clifford.num_qubits))) randbits = self._rng.integers(2, size=len(qargs)) ret = self.copy() for bit, qubit in enumerate(qargs): # Apply measurement and get classical outcome outcome = ret._measure_and_update(qubit, randbits[bit]) # Use the outcome to apply X gate to any qubits left in the # |1> state after measure, then discard outcome. if outcome == 1: _append_x(ret.clifford, qubit) return ret def measure(self, qargs: list | None = None) -> tuple: """Measure subsystems and return outcome and post-measure state. Note that this function uses the QuantumStates internal random number generator for sampling the measurement outcome. The RNG seed can be set using the :meth:`seed` method. Args: qargs (list or None): subsystems to sample measurements for, if None sample measurement of all subsystems (Default: None). Returns: tuple: the pair ``(outcome, state)`` where ``outcome`` is the measurement outcome string label, and ``state`` is the collapsed post-measurement stabilizer state for the corresponding outcome. """ if qargs is None: qargs = range(self.clifford.num_qubits) randbits = self._rng.integers(2, size=len(qargs)) ret = self.copy() outcome = "" for bit, qubit in enumerate(qargs): outcome = str(ret._measure_and_update(qubit, randbits[bit])) + outcome return outcome, ret def sample_memory(self, shots: int, qargs: None | list = None) -> np.ndarray: """Sample a list of qubit measurement outcomes in the computational basis. Args: shots (int): number of samples to generate. qargs (None or list): subsystems to sample measurements for, if None sample measurement of all subsystems (Default: None). Returns: np.array: list of sampled counts if the order sampled. Additional Information: This function implements the measurement :meth:`measure` method. The seed for random number generator used for sampling can be set to a fixed value by using the stats :meth:`seed` method. """ memory = [] for _ in range(shots): # copy the StabilizerState since measure updates it stab = self.copy() memory.append(stab.measure(qargs)[0]) return memory # ----------------------------------------------------------------------- # Helper functions for calculating the measurement # ----------------------------------------------------------------------- def _measure_and_update(self, qubit, randbit): """Measure a single qubit and return outcome and post-measure state. Note that this function uses the QuantumStates internal random number generator for sampling the measurement outcome. The RNG seed can be set using the :meth:`seed` method. Note that stabilizer state measurements only have three probabilities: (p0, p1) = (0.5, 0.5), (1, 0), or (0, 1) The random case happens if there is a row anti-commuting with Z[qubit] """ num_qubits = self.clifford.num_qubits clifford = self.clifford stab_x = self.clifford.stab_x # Check if there exists stabilizer anticommuting with Z[qubit] # in this case the measurement outcome is random z_anticommuting = np.any(stab_x[:, qubit]) if z_anticommuting == 0: # Deterministic outcome - measuring it will not change the StabilizerState aux_pauli = Pauli(num_qubits * "I") for i in range(num_qubits): if clifford.x[i][qubit]: aux_pauli = self._rowsum_deterministic(clifford, aux_pauli, i + num_qubits) outcome = aux_pauli.phase return outcome else: # Non-deterministic outcome outcome = randbit p_qubit = np.min(np.nonzero(stab_x[:, qubit])) p_qubit += num_qubits # Updating the StabilizerState for i in range(2 * num_qubits): # the last condition is not in the AG paper but we seem to need it if (clifford.x[i][qubit]) and (i != p_qubit) and (i != (p_qubit - num_qubits)): self._rowsum_nondeterministic(clifford, i, p_qubit) clifford.destab[p_qubit - num_qubits] = clifford.stab[p_qubit - num_qubits].copy() clifford.x[p_qubit] = np.zeros(num_qubits) clifford.z[p_qubit] = np.zeros(num_qubits) clifford.z[p_qubit][qubit] = True clifford.phase[p_qubit] = outcome return outcome @staticmethod def _phase_exponent(x1, z1, x2, z2): """Exponent g of i such that Pauli(x1,z1) * Pauli(x2,z2) = i^g Pauli(x1+x2,z1+z2)""" # pylint: disable=invalid-name phase = (x2 * z1 * (1 + 2 * z2 + 2 * x1) - x1 * z2 * (1 + 2 * z1 + 2 * x2)) % 4 if phase < 0: phase += 4 # now phase in {0, 1, 3} if phase == 2: raise QiskitError("Invalid rowsum phase exponent in measurement calculation.") return phase @staticmethod def _rowsum(accum_pauli, accum_phase, row_pauli, row_phase): """Aaronson-Gottesman rowsum helper function""" newr = 2 * row_phase + 2 * accum_phase for qubit in range(row_pauli.num_qubits): newr += StabilizerState._phase_exponent( row_pauli.x[qubit], row_pauli.z[qubit], accum_pauli.x[qubit], accum_pauli.z[qubit] ) newr %= 4 if (newr != 0) & (newr != 2): raise QiskitError("Invalid rowsum in measurement calculation.") accum_phase = int(newr == 2) accum_pauli.x ^= row_pauli.x accum_pauli.z ^= row_pauli.z return accum_pauli, accum_phase @staticmethod def _rowsum_nondeterministic(clifford, accum, row): """Updating StabilizerState Clifford in the non-deterministic rowsum calculation. row and accum are rows in the StabilizerState Clifford.""" row_phase = clifford.phase[row] accum_phase = clifford.phase[accum] z = clifford.z x = clifford.x row_pauli = Pauli((z[row], x[row])) accum_pauli = Pauli((z[accum], x[accum])) accum_pauli, accum_phase = StabilizerState._rowsum( accum_pauli, accum_phase, row_pauli, row_phase ) clifford.phase[accum] = accum_phase x[accum] = accum_pauli.x z[accum] = accum_pauli.z @staticmethod def _rowsum_deterministic(clifford, aux_pauli, row): """Updating an auxilary Pauli aux_pauli in the deterministic rowsum calculation. The StabilizerState itself is not updated.""" row_phase = clifford.phase[row] accum_phase = aux_pauli.phase accum_pauli = aux_pauli row_pauli = Pauli((clifford.z[row], clifford.x[row])) accum_pauli, accum_phase = StabilizerState._rowsum( accum_pauli, accum_phase, row_pauli, row_phase ) aux_pauli = accum_pauli aux_pauli.phase = accum_phase return aux_pauli # ----------------------------------------------------------------------- # Helper functions for calculating the probabilities # ----------------------------------------------------------------------- def _get_probablities(self, qubits, outcome, outcome_prob, probs): """Recursive helper function for calculating the probabilities""" qubit_for_branching = -1 ret = self.copy() for i in range(len(qubits)): qubit = qubits[len(qubits) - i - 1] if outcome[i] == "X": is_deterministic = not any(ret.clifford.stab_x[:, qubit]) if is_deterministic: single_qubit_outcome = ret._measure_and_update(qubit, 0) if single_qubit_outcome: outcome[i] = "1" else: outcome[i] = "0" else: qubit_for_branching = i if qubit_for_branching == -1: str_outcome = "".join(outcome) probs[str_outcome] = outcome_prob return for single_qubit_outcome in range(0, 2): new_outcome = outcome.copy() if single_qubit_outcome: new_outcome[qubit_for_branching] = "1" else: new_outcome[qubit_for_branching] = "0" stab_cpy = ret.copy() stab_cpy._measure_and_update( qubits[len(qubits) - qubit_for_branching - 1], single_qubit_outcome ) stab_cpy._get_probablities(qubits, new_outcome, 0.5 * outcome_prob, probs)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse d0 = pulse.DriveChannel(0) d1 = pulse.DriveChannel(1) with pulse.build() as pulse_prog: with pulse.align_right(): # this pulse will start at t=0 pulse.play(pulse.Constant(100, 1.0), d0) # this pulse will start at t=80 pulse.play(pulse.Constant(20, 1.0), d1) pulse_prog.draw()
https://github.com/usamisaori/qLipschitz
usamisaori
from sklearn import datasets import pennylane as qml import numpy as np from pennylane.optimize import AdamOptimizer import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') X_train, Y_train = datasets.make_circles(n_samples=200, noise=0.09, factor=0.4) X_test, Y_test = datasets.make_circles(n_samples=50, noise=0.09, factor=0.4) print('Training Data:') print(X_train[:10]) print('\nTraining Label:') print(Y_train[:10]) plt.scatter(X_train[:, 0], X_train[:, 1], c=Y_train) plt.show() print(f'Total datas: {len(X_train)}') print(f'labels: {list(set(Y_train))}') print(f'label 0 datas: {len(list(filter(lambda x: x==0, Y_train)))}') print(f'label 1 datas: {len(list(filter(lambda x: x==1, Y_train)))}') Z_train = (X_train[:, 0] ** 2 + X_train[:, 1] ** 2) ** 0.5 temp = np.zeros((X_train.shape[0], len(X_train[0]) + 1)) temp[:, :-1] = X_train temp[:, -1] = Z_train X_train2 = temp Z_test = (X_test[:, 0] ** 2 + X_test[:, 1] ** 2) ** 0.5 temp = np.zeros((X_test.shape[0], len(X_test[0]) + 1)) temp[:, :-1] = X_test temp[:, -1] = Z_test X_test2 = temp print('Solved Training Data:') print(X_train2[:10]) def plot3D(X, Y): fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111, projection='3d') ax.scatter( X[:, 0], X[:, 1], X[:, 2], zdir='z', s=30, c=Y, depthshade=True ) plt.show() plot3D(X_train2, Y_train) print(f'Total datas: {len(X_train2)}') print(f'labels: {list(set(Y_train))}') print(f'label 0 datas: {len(list(filter(lambda x: x==0, Y_train)))}') print(f'label 1 datas: {len(list(filter(lambda x: x==1, Y_train)))}') qubits_num = 3 layers_num = 2 dev = qml.device("default.qubit", wires=qubits_num) class VQC: def __init__(self): # 3 => U3(theta, phi, lambda) self.params = (0.05 * np.random.randn(layers_num, qubits_num, 3)) self.bestparams = self.params self.bestcost = 10 self.opt = AdamOptimizer(0.08) self.weights = [] self.costs = [] self.accuracies = [] def fit(self, X_train, Y_train, epoch=300): batch_size = 20 for turn in range(epoch): # Update the weights by one optimizer step batch_index = np.random.randint(0, len(X_train), (batch_size,)) X_train_batch = X_train[batch_index] Y_train_batch = Y_train[batch_index] self.params = self.opt.step(lambda v: cost(v, X_train_batch, Y_train_batch), self.params) cost_now = cost(self.params, X_train, Y_train) acc_now = accuracy(self.params, X_train, Y_train) if cost_now < self.bestcost: self.bestcost = cost_now self.bestparams = self.params self.weights.append(self.params) self.costs.append(cost_now) self.accuracies.append(acc_now) print( "Turn: {:5d} | Cost: {:0.7f} | Accuracy: {:0.2f}% ".format( turn + 1, cost_now, acc_now * 100 )) def score(self, X_test, Y_test): predictions = [ predict(self.bestparams, data) for data in X_test ] acc = accuracy(self.bestparams, X_test, Y_test) print("FINAL ACCURACY: {:0.2f}%".format(acc * 100)) @qml.qnode(dev) def circuit(params, data): angles = [ i * np.pi for i in data ] for i in range(qubits_num): qml.RX(angles[i], wires=i) qml.Rot( *params[0, i], wires=i ) qml.CZ(wires=[1, 0]) qml.CZ(wires=[1, 2]) qml.CZ(wires=[0, 2]) for i in range(qubits_num): qml.Rot( *params[1, i], wires=i ) # PauliZ measure => 1 -> |0> while -1 -> |1> return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliZ(2)) import qiskit import numpy as np from qiskit import QuantumCircuit from qiskit import Aer, execute unitary_backend = Aer.get_backend('unitary_simulator') qasm_backend = Aer.get_backend('qasm_simulator') def predict(params, data): qcircuit = QuantumCircuit(3, 3) qubits = qcircuit.qubits for i, d in enumerate(data): qcircuit.rx(d * np.pi, qubits[i]) for i in range(qubits_num): qcircuit.u3(*params[0][i], qubits[i]) qcircuit.cz(qubits[0], qubits[1]) qcircuit.cz(qubits[1], qubits[2]) qcircuit.cz(qubits[0], qubits[2]) for i in range(qubits_num): qcircuit.u3(*params[1][i], qubits[i]) # the measurement qcircuit.measure([0, 1, 2], [0, 1, 2]) # job execution shots = 1000 job_sim = execute(qcircuit, qasm_backend, shots=shots) result_sim = job_sim.result() counts = result_sim.get_counts(qcircuit) p1 = (counts.get('100', 0) + counts.get('111', 0) + counts.get('101', 0) + counts.get('110', 0)) / shots if p1 > 0.5: return 1 else: return 0 def cost(weights, datas, labels): loss = 0 for i, data in enumerate(datas): # like [-1, 1, 1] measured = circuit(weights, data) p = measured[0] if labels[i] == 0: loss += (1 - p) ** 2 else: loss += (-1 - p) ** 2 return loss / len(datas) def accuracy(weights, datas, labels): predictions = [ predict(weights, data) for data in datas ] acc = 0 for i, p in enumerate(predictions): if p == labels[i]: acc += 1 return acc / len(predictions) vqc = VQC() # vqc.params = np.array([[[-1.18991246e-01, -8.69694713e-01, 1.43722811e-03], # [ 3.47641545e+00, -4.73632073e-02, 1.97135609e+00], # [ 1.95775707e+00, -1.12139160e-02, -6.21796144e-03]], # [[ 2.02460380e-02, -2.25797547e+00, 5.14234265e-03], # [-1.71552299e-02, 2.46283604e-03, -1.03805722e-02], # [-2.37244982e-03, -3.35799404e-03, 6.10191152e-03]]]) vqc.fit(X_train2, Y_train, epoch=10) print(cost(vqc.bestparams, X_train2, Y_train)) print(cost(vqc.bestparams, X_test2, Y_test)) vqc.score(X_test2, Y_test) def createCircuit(params, data): qcircuit = QuantumCircuit(3, 3) qubits = qcircuit.qubits for i, d in enumerate(data): qcircuit.rx(d * np.pi, qubits[i]) for i in range(qubits_num): qcircuit.u3(*params[0][i], qubits[i]) qcircuit.cz(qubits[0], qubits[1]) qcircuit.cz(qubits[1], qubits[2]) qcircuit.cz(qubits[0], qubits[2]) for i in range(qubits_num): qcircuit.u3(*params[1][i], qubits[i]) return qcircuit qcircuit = createCircuit(vqc.bestparams, X_train2[0]) qcircuit.draw(output='mpl') def measure(qcircuit, label): # the measurement qcircuit.measure([0, 1, 2], [0, 1, 2]) # job execution shots = 1000 job_sim = execute(qcircuit, qasm_backend, shots=shots) result_sim = job_sim.result() counts = result_sim.get_counts(qcircuit) print(f'simulation results: \n{counts}') p1 = (counts.get('100', 0) + counts.get('111', 0) + counts.get('101', 0) + counts.get('110',0)) / shots print(f'p1: {p1}') print(f'Expected label: {label}') example = [3, 30, 35, 70] for index in example: qcircuit = createCircuit(vqc.bestparams, X_train2[index]) measure(qcircuit, Y_train[index]) print() # origin data plt.scatter(X_train2[:, 0], X_train2[:, 1], c=Y_train) plt.show() predictions = [ predict(vqc.bestparams, data) for data in X_test2 ] Y_ = [ Y_test[i] if Y_test[i] == predictions[i] else 2 for i in range(len(Y_test)) ] plt.scatter(X_test2[:, 0], X_test2[:, 1], c=Y_) plt.show() train_params(X_train2[10:50], Y_train[10:50])
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
import networkx as nx import numpy as np import plotly.graph_objects as go import matplotlib as mpl import pandas as pd from IPython.display import clear_output from plotly.subplots import make_subplots from matplotlib import pyplot as plt from qiskit import Aer from qiskit import QuantumCircuit from qiskit.visualization import plot_state_city from qiskit.algorithms.optimizers import COBYLA, SLSQP, ADAM from time import time from copy import copy from typing import List from qc_grader.graph_util import display_maxcut_widget, QAOA_widget, graphs mpl.rcParams['figure.dpi'] = 300 from qiskit.circuit import Parameter, ParameterVector #Parameters are initialized with a simple string identifier parameter_0 = Parameter('θ[0]') parameter_1 = Parameter('θ[1]') circuit = QuantumCircuit(1) #We can then pass the initialized parameters as the rotation angle argument to the Rx and Ry gates circuit.ry(theta = parameter_0, qubit = 0) circuit.rx(theta = parameter_1, qubit = 0) circuit.draw('mpl') parameter = Parameter('θ') circuit = QuantumCircuit(1) circuit.ry(theta = parameter, qubit = 0) circuit.rx(theta = parameter, qubit = 0) circuit.draw('mpl') #Set the number of layers and qubits n=3 num_layers = 2 #ParameterVectors are initialized with a string identifier and an integer specifying the vector length parameters = ParameterVector('θ', n*(num_layers+1)) circuit = QuantumCircuit(n, n) for layer in range(num_layers): #Appending the parameterized Ry gates using parameters from the vector constructed above for i in range(n): circuit.ry(parameters[n*layer+i], i) circuit.barrier() #Appending the entangling CNOT gates for i in range(n): for j in range(i): circuit.cx(j,i) circuit.barrier() #Appending one additional layer of parameterized Ry gates for i in range(n): circuit.ry(parameters[n*num_layers+i], i) circuit.barrier() circuit.draw('mpl') print(circuit.parameters) #Create parameter dictionary with random values to bind param_dict = {parameter: np.random.random() for parameter in parameters} print(param_dict) #Assign parameters using the assign_parameters method bound_circuit = circuit.assign_parameters(parameters = param_dict) bound_circuit.draw('mpl') new_parameters = ParameterVector('Ψ',9) new_circuit = circuit.assign_parameters(parameters = [k*new_parameters[i] for k in range(9)]) new_circuit.draw('mpl') #Run the circuit with assigned parameters on Aer's statevector simulator simulator = Aer.get_backend('statevector_simulator') result = simulator.run(bound_circuit).result() statevector = result.get_statevector(bound_circuit) plot_state_city(statevector) #The following line produces an error when run because 'circuit' still contains non-assigned parameters #result = simulator.run(circuit).result() for key in graphs.keys(): print(key) graph = nx.Graph() #Add nodes and edges graph.add_nodes_from(np.arange(0,6,1)) edges = [(0,1,2.0),(0,2,3.0),(0,3,2.0),(0,4,4.0),(0,5,1.0),(1,2,4.0),(1,3,1.0),(1,4,1.0),(1,5,3.0),(2,4,2.0),(2,5,3.0),(3,4,5.0),(3,5,1.0)] graph.add_weighted_edges_from(edges) graphs['custom'] = graph #Display widget display_maxcut_widget(graphs['custom']) def maxcut_cost_fn(graph: nx.Graph, bitstring: List[int]) -> float: """ Computes the maxcut cost function value for a given graph and cut represented by some bitstring Args: graph: The graph to compute cut values for bitstring: A list of integer values '0' or '1' specifying a cut of the graph Returns: The value of the cut """ #Get the weight matrix of the graph weight_matrix = nx.adjacency_matrix(graph).toarray() size = weight_matrix.shape[0] value = 0. #INSERT YOUR CODE TO COMPUTE THE CUT VALUE HERE for i in range(size): for j in range(size): value+= weight_matrix[i,j]*bitstring[i]*(1-bitstring[j]) return value def plot_maxcut_histogram(graph: nx.Graph) -> None: """ Plots a bar diagram with the values for all possible cuts of a given graph. Args: graph: The graph to compute cut values for """ num_vars = graph.number_of_nodes() #Create list of bitstrings and corresponding cut values bitstrings = ['{:b}'.format(i).rjust(num_vars, '0')[::-1] for i in range(2**num_vars)] values = [maxcut_cost_fn(graph = graph, bitstring = [int(x) for x in bitstring]) for bitstring in bitstrings] #Sort both lists by largest cut value values, bitstrings = zip(*sorted(zip(values, bitstrings))) #Plot bar diagram bar_plot = go.Bar(x = bitstrings, y = values, marker=dict(color=values, colorscale = 'plasma', colorbar=dict(title='Cut Value'))) fig = go.Figure(data=bar_plot, layout = dict(xaxis=dict(type = 'category'), width = 1500, height = 600)) fig.show() plot_maxcut_histogram(graph = graphs['custom']) from qc_grader import grade_lab2_ex1 bitstring = [1, 0, 1, 1, 0, 0] #DEFINE THE CORRECT MAXCUT BITSTRING HERE # Note that the grading function is expecting a list of integers '0' and '1' grade_lab2_ex1(bitstring) from qiskit_optimization import QuadraticProgram quadratic_program = QuadraticProgram('sample_problem') print(quadratic_program.export_as_lp_string()) quadratic_program.binary_var(name = 'x_0') quadratic_program.integer_var(name = 'x_1') quadratic_program.continuous_var(name = 'x_2', lowerbound = -2.5, upperbound = 1.8) quadratic = [[0,1,2],[3,4,5],[0,1,2]] linear = [10,20,30] quadratic_program.minimize(quadratic = quadratic, linear = linear, constant = -5) print(quadratic_program.export_as_lp_string()) def quadratic_program_from_graph(graph: nx.Graph) -> QuadraticProgram: """Constructs a quadratic program from a given graph for a MaxCut problem instance. Args: graph: Underlying graph of the problem. Returns: QuadraticProgram """ #Get weight matrix of graph weight_matrix = nx.adjacency_matrix(graph) shape = weight_matrix.shape size = shape[0] #Build qubo matrix Q from weight matrix W qubo_matrix = np.zeros((size, size)) qubo_vector = np.zeros(size) for i in range(size): for j in range(size): qubo_matrix[i, j] -= weight_matrix[i, j] for i in range(size): for j in range(size): qubo_vector[i] += weight_matrix[i,j] #INSERT YOUR CODE HERE quadratic_program=QuadraticProgram('sample_problem') for i in range(size): quadratic_program.binary_var(name='x_{}'.format(i)) quadratic_program.maximize(quadratic =qubo_matrix, linear = qubo_vector) return quadratic_program quadratic_program = quadratic_program_from_graph(graphs['custom']) print(quadratic_program.export_as_lp_string()) from qc_grader import grade_lab2_ex2 # Note that the grading function is expecting a quadratic program grade_lab2_ex2(quadratic_program) def qaoa_circuit(qubo: QuadraticProgram, p: int = 1): """ Given a QUBO instance and the number of layers p, constructs the corresponding parameterized QAOA circuit with p layers. Args: qubo: The quadratic program instance p: The number of layers in the QAOA circuit Returns: The parameterized QAOA circuit """ size = len(qubo.variables) qubo_matrix = qubo.objective.quadratic.to_array(symmetric=True) qubo_linearity = qubo.objective.linear.to_array() #Prepare the quantum and classical registers qaoa_circuit = QuantumCircuit(size,size) #Apply the initial layer of Hadamard gates to all qubits qaoa_circuit.h(range(size)) #Create the parameters to be used in the circuit gammas = ParameterVector('gamma', p) betas = ParameterVector('beta', p) #Outer loop to create each layer for i in range(p): #Apply R_Z rotational gates from cost layer #INSERT YOUR CODE HERE for j in range(size): qubo_matrix_sum_of_col = 0 for k in range(size): qubo_matrix_sum_of_col+= qubo_matrix[j][k] qaoa_circuit.rz(gammas[i]*(qubo_linearity[j]+qubo_matrix_sum_of_col),j) #Apply R_ZZ rotational gates for entangled qubit rotations from cost layer #INSERT YOUR CODE HERE for j in range(size): for k in range(size): if j!=k: qaoa_circuit.rzz(gammas[i]*qubo_matrix[j][k]*0.5,j,k) # Apply single qubit X - rotations with angle 2*beta_i to all qubits #INSERT YOUR CODE HERE for j in range(size): qaoa_circuit.rx(2*betas[i],j) return qaoa_circuit quadratic_program = quadratic_program_from_graph(graphs['custom']) custom_circuit = qaoa_circuit(qubo = quadratic_program) test = custom_circuit.assign_parameters(parameters=[1.0]*len(custom_circuit.parameters)) from qc_grader import grade_lab2_ex3 # Note that the grading function is expecting a quantum circuit grade_lab2_ex3(test) from qiskit.algorithms import QAOA from qiskit_optimization.algorithms import MinimumEigenOptimizer backend = Aer.get_backend('statevector_simulator') qaoa = QAOA(optimizer = ADAM(), quantum_instance = backend, reps=1, initial_point = [0.1,0.1]) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) quadratic_program = quadratic_program_from_graph(graphs['custom']) result = eigen_optimizer.solve(quadratic_program) print(result) def plot_samples(samples): """ Plots a bar diagram for the samples of a quantum algorithm Args: samples """ #Sort samples by probability samples = sorted(samples, key = lambda x: x.probability) #Get list of probabilities, function values and bitstrings probabilities = [sample.probability for sample in samples] values = [sample.fval for sample in samples] bitstrings = [''.join([str(int(i)) for i in sample.x]) for sample in samples] #Plot bar diagram sample_plot = go.Bar(x = bitstrings, y = probabilities, marker=dict(color=values, colorscale = 'plasma',colorbar=dict(title='Function Value'))) fig = go.Figure( data=sample_plot, layout = dict( xaxis=dict( type = 'category' ) ) ) fig.show() plot_samples(result.samples) graph_name = 'custom' quadratic_program = quadratic_program_from_graph(graph=graphs[graph_name]) trajectory={'beta_0':[], 'gamma_0':[], 'energy':[]} offset = 1/4*quadratic_program.objective.quadratic.to_array(symmetric = True).sum() + 1/2*quadratic_program.objective.linear.to_array().sum() def callback(eval_count, params, mean, std_dev): trajectory['beta_0'].append(params[1]) trajectory['gamma_0'].append(params[0]) trajectory['energy'].append(-mean + offset) optimizers = { 'cobyla': COBYLA(), 'slsqp': SLSQP(), 'adam': ADAM() } qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=1, initial_point = [6.2,1.8],callback = callback) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) result = eigen_optimizer.solve(quadratic_program) fig = QAOA_widget(landscape_file=f'./resources/energy_landscapes/{graph_name}.csv', trajectory = trajectory, samples = result.samples) fig.show() graph_name = 'custom' quadratic_program = quadratic_program_from_graph(graphs[graph_name]) #Create callback to record total number of evaluations max_evals = 0 def callback(eval_count, params, mean, std_dev): global max_evals max_evals = eval_count #Create empty lists to track values energies = [] runtimes = [] num_evals=[] #Run QAOA for different values of p for p in range(1,10): print(f'Evaluating for p = {p}...') qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=p, callback=callback) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) start = time() result = eigen_optimizer.solve(quadratic_program) runtimes.append(time()-start) num_evals.append(max_evals) #Calculate energy of final state from samples avg_value = 0. for sample in result.samples: avg_value += sample.probability*sample.fval energies.append(avg_value) #Create and display plots energy_plot = go.Scatter(x = list(range(1,10)), y =energies, marker=dict(color=energies, colorscale = 'plasma')) runtime_plot = go.Scatter(x = list(range(1,10)), y =runtimes, marker=dict(color=runtimes, colorscale = 'plasma')) num_evals_plot = go.Scatter(x = list(range(1,10)), y =num_evals, marker=dict(color=num_evals, colorscale = 'plasma')) fig = make_subplots(rows = 1, cols = 3, subplot_titles = ['Energy value', 'Runtime', 'Number of evaluations']) fig.update_layout(width=1800,height=600, showlegend=False) fig.add_trace(energy_plot, row=1, col=1) fig.add_trace(runtime_plot, row=1, col=2) fig.add_trace(num_evals_plot, row=1, col=3) clear_output() fig.show() def plot_qaoa_energy_landscape(graph: nx.Graph, cvar: float = None): num_shots = 1000 seed = 42 simulator = Aer.get_backend('qasm_simulator') simulator.set_options(seed_simulator = 42) #Generate circuit circuit = qaoa_circuit(qubo = quadratic_program_from_graph(graph), p=1) circuit.measure(range(graph.number_of_nodes()),range(graph.number_of_nodes())) #Create dictionary with precomputed cut values for all bitstrings cut_values = {} size = graph.number_of_nodes() for i in range(2**size): bitstr = '{:b}'.format(i).rjust(size, '0')[::-1] x = [int(bit) for bit in bitstr] cut_values[bitstr] = maxcut_cost_fn(graph, x) #Perform grid search over all parameters data_points = [] max_energy = None for beta in np.linspace(0,np.pi, 50): for gamma in np.linspace(0, 4*np.pi, 50): bound_circuit = circuit.assign_parameters([beta, gamma]) result = simulator.run(bound_circuit, shots = num_shots).result() statevector = result.get_counts(bound_circuit) energy = 0 measured_cuts = [] for bitstring, count in statevector.items(): measured_cuts = measured_cuts + [cut_values[bitstring]]*count if cvar is None: #Calculate the mean of all cut values energy = sum(measured_cuts)/num_shots else: #raise NotImplementedError() #INSERT YOUR CODE HERE measured_cuts = sorted(measured_cuts, reverse = True) for w in range(int(cvar*num_shots)): energy += measured_cuts[w]/int((cvar*num_shots)) #Update optimal parameters if max_energy is None or energy > max_energy: max_energy = energy optimum = {'beta': beta, 'gamma': gamma, 'energy': energy} #Update data data_points.append({'beta': beta, 'gamma': gamma, 'energy': energy}) #Create and display surface plot from data_points df = pd.DataFrame(data_points) df = df.pivot(index='beta', columns='gamma', values='energy') matrix = df.to_numpy() beta_values = df.index.tolist() gamma_values = df.columns.tolist() surface_plot = go.Surface( x=gamma_values, y=beta_values, z=matrix, coloraxis = 'coloraxis' ) fig = go.Figure(data = surface_plot) fig.show() #Return optimum return optimum graph = graphs['custom'] optimal_parameters = plot_qaoa_energy_landscape(graph = graph) print('Optimal parameters:') print(optimal_parameters) optimal_parameters = plot_qaoa_energy_landscape(graph = graph, cvar = 0.2) print(optimal_parameters) from qc_grader import grade_lab2_ex4 # Note that the grading function is expecting a python dictionary # with the entries 'beta', 'gamma' and 'energy' grade_lab2_ex4(optimal_parameters)
https://github.com/qiskit-community/qiskit-tket-passes
qiskit-community
import unittest from qiskit.transpiler.preset_passmanagers.plugin import ( list_stage_plugins, passmanager_stage_plugins, ) import qiskit_tket_passes.plugins as plgn class TestPassManagerStagePlugins(unittest.TestCase): def test_plugins_are_installed(self): for stage_name in ['init', 'layout', 'routing', 'translation', 'optimization']: installed_plugins = list_stage_plugins(stage_name) self.assertIn('tket', installed_plugins) def test_plugins_are_used(self): plugins = passmanager_stage_plugins('init') self.assertIsInstance(isinstance(plugins['tket'], plgn.TketInitPassManager)) plugins = passmanager_stage_plugins('layout') self.assertIsInstance(plugins['tket'], plgn.TketLayoutPassManager) plugins = passmanager_stage_plugins('routing') self.assertIsInstance(plugins['tket'], plgn.TketRoutingPassManager) plugins = passmanager_stage_plugins('translation') self.assertIsInstance(plugins['tket'], plgn.TketTranslationPassManager) plugins = passmanager_stage_plugins('optimization') self.assertIsInstance(plugins['tket'], plgn.TketOptimizationPassManager) if __name__ == '__main__': unittest.main()
https://github.com/1chooo/Quantum-Oracle
1chooo
""" Balanced: Input equal Output. """ """ Create the quantum Circuit. """ from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister qrx = QuantumRegister(1, 'q0') qry = QuantumRegister(1, 'q1') cr = ClassicalRegister(1, 'c') qc = QuantumCircuit(qrx, qry, cr) qc.h(qrx) qc.x(qry) qc.h(qry) qc.barrier() qc.cx(qrx, qry) qc.barrier() qc.h(qrx) qc.h(qry) qc.measure(qrx, cr) qc.draw("mpl") """ Proof through histogram. """ 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) """ Also in Quantum Computer. """ from qiskit import QuantumCircuit, IBMQ, execute from qiskit.tools.monitor import job_monitor from qiskit.visualization import plot_histogram IBMQ.save_account('your_token') IBMQ.load_account() IBMQ.providers() provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main') qcomp = provider.get_backend('ibmq_manila') job = execute(qc, backend = qcomp, shots = 1000) job_monitor(job) result = job.result() counts = result.get_counts(qc) print("Total counts for qubit states are:", counts) plot_histogram(counts)
https://github.com/kardashin/E91_protocol
kardashin
import numpy as np import pandas as pd import re import random import math # Importing QISKit from qiskit import QuantumProgram import Qconfig # Quantum program setup Q_program = QuantumProgram() Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) # set the APIToken and API url ## Input parameters measurementChoicesLength = 1000 # length of the strings that cointain measurement choices evePresence = False # Presence of an eavesdropper in the channel evePresencePercentage = 1 # Percentage of Eve's interference backend = 'local_qasm_simulator' ## Creating registers qr = Q_program.create_quantum_register("qr", 2) cr = Q_program.create_classical_register("cr", 4) ## Creating a shared entangled state entangledState = Q_program.create_circuit('entangledState', [qr], [cr]) # bell_11 (singlet) stete for the ibmqx2 backend #entangledState.x(qr[0]) #entangledState.x(qr[1]) #entangledState.h(qr[0]) #entangledState.cx(qr[0],qr[1]) # bell_11 (singlet) stete for the ibmqx4 backend entangledState.x(qr[0]) entangledState.x(qr[1]) entangledState.h(qr[1]) entangledState.cx(qr[1],qr[0]) ### Creating measurement circuits ## Alice's measurement circuits # measurement of the spin projection onto the A1 = (1; 0; 0) direction # projection onto the eigenvectors of the matrix X measureA1 = Q_program.create_circuit('measureA1', [qr], [cr]) measureA1.h(qr[0]) measureA1.measure(qr[0],cr[0]) # measurement of the spin projection onto A2 = (1/sqt(2); 0; 1/(sqrt(2)) direction # projection onto the eigenvectors of the matrix W = (Z+X)/sqrt(2) measureA2 = Q_program.create_circuit('measureA2', [qr], [cr]) measureA2.s(qr[0]) measureA2.h(qr[0]) measureA2.t(qr[0]) measureA2.h(qr[0]) measureA2.measure(qr[0],cr[0]) # measurement of the spin projection onto the A3 = (0; 0; 1) vector # standard Z-measurement measureA3 = Q_program.create_circuit('measureA3', [qr], [cr]) measureA3.measure(qr[0],cr[0]) ## Bob's measurement circuits # measurement of the spin projection onto the B1 = (1/sqt(2); 0; 1/(sqrt(2)) direction # projection onto the eigenvectors of the matrix W = (Z+X)/sqrt(2) measureB1 = Q_program.create_circuit('measureB1', [qr], [cr]) measureB1.s(qr[1]) measureB1.h(qr[1]) measureB1.t(qr[1]) measureB1.h(qr[1]) measureB1.measure(qr[1],cr[1]) # measurement of the spin projection onto the B2 = (0; 0; 1) direction # standard Z measurement measureB2 = Q_program.create_circuit('measureB2', [qr], [cr]) measureB2.measure(qr[1],cr[1]) # measurement of the spin projection onto the B3 = (-1/sqt(2); 0; 1/(sqrt(2)) direction # projection onto the eigenvectors of the matrix V = (Z-X)/sqrt(2) measureB3 = Q_program.create_circuit('measureB3', [qr], [cr]) measureB3.s(qr[1]) measureB3.h(qr[1]) measureB3.tdg(qr[1]) measureB3.h(qr[1]) measureB3.measure(qr[1],cr[1]) ## Eve's measuremets # identity gate for Alice's qubit ident0 = Q_program.create_circuit('ident0', [qr], [cr]) ident0.iden(qr[0]) # identity gate for Bob's qubit ident1 = Q_program.create_circuit('ident1', [qr], [cr]) ident1.iden(qr[1]) # measurement of the spin projection of Alice's qubit onto the (1; 0; 0) direction (observable X) measureEA1 = Q_program.create_circuit('measureEA1', [qr], [cr]) measureEA1.h(qr[0]) measureEA1.measure(qr[0],cr[2]) # measurement of the spin projection of Alice's qubit onto the (1/sqt(2); 0; 1/(sqrt(2)) direction (observable W) measureEA2 = Q_program.create_circuit('measureEA2', [qr], [cr]) measureEA2.s(qr[0]) measureEA2.h(qr[0]) measureEA2.t(qr[0]) measureEA2.h(qr[0]) measureEA2.measure(qr[0],cr[2]) # measurement of the spin projection of Alice's qubit onto the (0; 0; 1) direction (observable Z) measureEA3 = Q_program.create_circuit('measureEA3', [qr], [cr]) measureEA3.measure(qr[0],cr[2]) # measurement of the spin projection of Bob's qubit onto the (1/sqt(2); 0; 1/(sqrt(2)) direction (observable W) measureEB1 = Q_program.create_circuit('measureEB1', [qr], [cr]) measureEB1.s(qr[1]) measureEB1.h(qr[1]) measureEB1.t(qr[1]) measureEB1.h(qr[1]) measureEB1.measure(qr[1],cr[3]) # measurement of the spin projection of Bob's qubit onto the (0; 0; 1) direction (observable Z) measureEB2 = Q_program.create_circuit('measureEB2', [qr], [cr]) measureEB2.measure(qr[1],cr[3]) # measurement of the spin projection of Bob's qubit onto the (-1/sqt(2); 0; 1/(sqrt(2)) direction (observable V) measureEB3 = Q_program.create_circuit('measureEB3', [qr], [cr]) measureEB3.s(qr[1]) measureEB3.h(qr[1]) measureEB3.tdg(qr[1]) measureEB3.h(qr[1]) measureEB3.measure(qr[1],cr[3]) ## Lists of Alice's, Bob's and Eve's measurement circuits aliceMeasurements = [measureA1, measureA2, measureA3] bobMeasurements = [measureB1, measureB2, measureB3] eveMeasurements = [ident0, ident1, measureEA1, measureEA2, measureEA3, measureEB1, measureEB2, measureEB3] ## Alice's and Bob's measurement choice strings aliceMeasurementChoices = [] bobMeasurementChoices = [] # random strings generation for i in range(measurementChoicesLength): aliceMeasurementChoices.append(random.randint(1, 3)) bobMeasurementChoices.append(random.randint(1, 3)) ## Eve's optimal measurement choices array # it is efficient for Eve to measure the spin projections of Alice's and Bob's qubits onto the same direction (A2B1 and A3B2) # list of Eve's measurement choices # the first and the second element of each row represents the measurement of Alice's and Bob's qubit, respectively # default values of the list are 1 and 2 (applying identity gate) eveMeasurementChoices = [[1,2] for j in range(measurementChoicesLength)] eveMersurementPerformed = [0] * measurementChoicesLength if evePresence == True: for j in range(measurementChoicesLength): if random.uniform(0, 1) <= evePresencePercentage: eveMersurementPerformed[j] = 1 if random.uniform(0, 1) <= 0.5: # in 50% of cases perform the A2_B1 measurement (observable WW) eveMeasurementChoices[j] = [4, 6] else: # in 50% of cases perform the A3_B2 measurement (observable ZZ) eveMeasurementChoices[j] = [5, 7] circuits = [] # the list in which the created circuits will be stored for k in range(measurementChoicesLength): # create the name of the k-th circuit depending on Alice's, Bob's and Eve's choices of measurement circuitName = str(k) + ':A' + str(aliceMeasurementChoices[k]) + '_B' + str(bobMeasurementChoices[k]) + '_E' + str(eveMeasurementChoices[k][0]) + str(eveMeasurementChoices[k][1]) # create the joint measurement circuit # add Alice's and Bob's measurement circuits to the singlet state curcuit Q_program.add_circuit(circuitName, entangledState + # singlet state circuit eveMeasurements[eveMeasurementChoices[k][0]-1] + # Eve's measurement circuit for Alice's qubit eveMeasurements[eveMeasurementChoices[k][1]-1] + # Eve's measurement circuit for Bob's qubit aliceMeasurements[aliceMeasurementChoices[k]-1] + # measurement circuit of Alice bobMeasurements[bobMeasurementChoices[k]-1] # measurement circuit of Bob ) # add the created circuit to the circuits list circuits.append(circuitName) ## Execute circuits result = Q_program.execute(circuits, backend=backend, shots=1, timeout=180) print(result) ## Recording the measurement results aliceResults = [] # Alice's results bobResults = [] # Bob's results eveResults = [[0, 0] for j in range(measurementChoicesLength)] # list of zeros by default; if the element is 0, then Eve did not perform a measurement # Alice's and Bob's search patterns abPatterns = [ re.compile('..00$'), # search for the '..00' output (Alice obtained -1 and Bob obtained -1) re.compile('..01$'), # search for the '..01' output re.compile('..10$'), # search for the '..10' output (Alice obtained -1 and Bob obtained 1) re.compile('..11$') # search for the '..11' output ] # Eve's search patterns ePatterns = [ re.compile('00..$'), # search for the '00..' result re.compile('01..$'), re.compile('10..$'), re.compile('11..$') ] # Recording results for k in range(measurementChoicesLength): res = list(result.get_counts(circuits[k]).keys())[0] # extract a key from the dict and transform it to str; execution result of the k-th circuit # Alice and Bob if abPatterns[0].search(res): # check if the key is '..00' (if the measurement results are -1,-1) aliceResults.append(-1) # Alice got the result -1 bobResults.append(-1) # Bob got the result -1 if abPatterns[1].search(res): aliceResults.append(1) bobResults.append(-1) if abPatterns[2].search(res): aliceResults.append(-1) bobResults.append(1) if abPatterns[3].search(res): # check if the key is '..11' (if the measurement results are 1,1) aliceResults.append(1) bobResults.append(1) # Eve if eveMersurementPerformed[k] == True: # if Eve has performed a measurement in the k-th circuit if ePatterns[0].search(res): # check if the key is '00..' eveResults[k][0] = -1 # result of the measurement of Alice's qubit eveResults[k][1] = -1 # result of the measurement of Bob's qubit if ePatterns[1].search(res): eveResults[k][0] = 1 eveResults[k][1] = -1 if ePatterns[2].search(res): eveResults[k][0] = -1 eveResults[k][1] = 1 if ePatterns[3].search(res): eveResults[k][0] = 1 eveResults[k][1] = 1 ## Measurement choises check stage # Alice and Bob compare their strings with basis choices # If in the k-th measurement A and B used the same basis, then they record the result of the k-th measurement as the bit of the secret key aliceKey = [] # Alice's key string bobKey = [] # Bob's key string eveKeys = [] # Eve's keys; the 1-st column is the Alice's key, the 2-nd is Bob's # the key consists of the results obtained after projecting the spin onto the same directions (A2_B1 and A3_B2 measurements) for k in range(measurementChoicesLength): # if Alice and Bob measured the WW or ZZ observable if (aliceMeasurementChoices[k] == 2 and bobMeasurementChoices[k] == 1) or (aliceMeasurementChoices[k] == 3 and bobMeasurementChoices[k] == 2): aliceKey.append(aliceResults[k]) # record Alice's k-th result as a key bit bobKey.append(-bobResults[k]) # write Bob's k-th result as a key bit; must be inversed for the singlet state eveKeys.append([eveResults[k][0], -eveResults[k][1]]) keyLength = len(aliceKey) # length of the secret keys ## Comparing the bits of the keys abKeyMismatches = 0 # number of mismatching bits in Alice's and Bob's secret keys eaKeyMismatches = 0 # number of mismatching bits in Alice's and Eve's secret keys ebKeyMismatches = 0 eeKeyMismatches = 0 for k in range(keyLength): if aliceKey[k] != bobKey[k]: abKeyMismatches += 1 if eveKeys[k][0] != aliceKey[k]: eaKeyMismatches += 1 if eveKeys[k][1] != bobKey[k]: ebKeyMismatches += 1 if eveKeys[k][0] != eveKeys[k][1]: eeKeyMismatches += 1 # Eve's knowledge of the keys eaKnowledge = (keyLength - eaKeyMismatches)/keyLength # Eve's knowledge of Alice's key ebKnowledge = (keyLength - ebKeyMismatches)/keyLength # Eve's knowledge of Bob's key averageEveKnowledge = (eaKnowledge + ebKnowledge)/2 # average Eve's knowledge # Quantum bit error rate qber = abKeyMismatches/keyLength ## CHSH inequality test # lists with the counts of measurement results # each element represents the number of (-1,-1), (-1,1), (1,-1) and (1,1) results respectively countA1B1 = [0, 0, 0, 0] countA1B3 = [0, 0, 0, 0] countA3B1 = [0, 0, 0, 0] countA3B3 = [0, 0, 0, 0] for k in range(measurementChoicesLength): res = list(result.get_counts(circuits[k]).keys())[0] # observable XW if (aliceMeasurementChoices[k] == 1 and bobMeasurementChoices[k] == 1): for j in range(4): if abPatterns[j].search(res): countA1B1[j] += 1 # observable XV if (aliceMeasurementChoices[k] == 1 and bobMeasurementChoices[k] == 3): for j in range(4): if abPatterns[j].search(res): countA1B3[j] += 1 # observable ZW if (aliceMeasurementChoices[k] == 3 and bobMeasurementChoices[k] == 1): for j in range(4): if abPatterns[j].search(res): countA3B1[j] += 1 # observable ZV if (aliceMeasurementChoices[k] == 3 and bobMeasurementChoices[k] == 3): for j in range(4): if abPatterns[j].search(res): countA3B3[j] += 1 # number of results obtained from measurements in a particular basis total11 = sum(countA1B1) total13 = sum(countA1B3) total31 = sum(countA3B1) total33 = sum(countA3B3) # expected values of the spin projections onto the A1_B1, A1_B3, A3_B1 and A3_B3 directions expect11 = (countA1B1[0] - countA1B1[1] - countA1B1[2] + countA1B1[3])/total11 # observable XW expect13 = (countA1B3[0] - countA1B3[1] - countA1B3[2] + countA1B3[3])/total31 # observable XV expect31 = (countA3B1[0] - countA3B1[1] - countA3B1[2] + countA3B1[3])/total13 # observable ZW expect33 = (countA3B3[0] - countA3B3[1] - countA3B3[2] + countA3B3[3])/total33 # observable ZV # CHSH correlation value # must be equal to -2*sqrt(2) in the case of the absence of noise and eavesdropping corr = expect11 - expect13 + expect31 + expect33 diff = abs(abs(corr) - 2*math.sqrt(2)) ## Print results # CHSH inequality test print('CHSH correlation value: ' + str(round(corr, 3))) print('Difference from -2*sqrt(2): ' + str(round(diff, 3)) + '\n') # Secret keys print('Length of the secret key: ' + str(keyLength)) print('Number of mismatching bits: ' + str(abKeyMismatches) + '\n') print('QBER: ' + str(round(qber * 100, 2)) + ' %') print('Eve\'s average knowledge: ' + str(round(averageEveKnowledge * 100, 2)) + ' %\n') ## Check measurement errors # Theoretically, the measurement in the A2_B1 and A3_B2 basises gives only the (-1,1) and (1,-1) results # This block counts how many (-1,-1) and (1,1) results obtained after the measurements of the WW and ZZ observables # actual for the execution on the real quantum devices mismatchesList = [] for k in range(measurementChoicesLength): res = list(result.get_counts(circuits[k]).keys())[0] result01 = False # by default result10 = False if abPatterns[1].search(res): result01 = True if abPatterns[2].search(res): result10 = True condition1 = ('A2_B1' in circuits[k] or 'A3_B2' in circuits[k]) and not result01 # if result is not (-1,1) condition2 = ('A2_B1' in circuits[k] or 'A3_B2' in circuits[k]) and not result10 # if result is not (1,-1) if condition1 and condition2 == True: mismatchesList.append([str(circuits[k]), res]) pd.DataFrame(mismatchesList,columns = ['Measurement', 'Result'])
https://github.com/avkhadiev/schwinger-vqe
avkhadiev
from qiskit import * import qiskit.tools.jupyter import numpy as np IBMQ.load_account() # so far, this is an input from a Mathematica notebook — decomposition of target Hamiltonian into pauli basis ops # diag = 9, 12, 15, 16 coeffs = np.array([ # smart sort # greedy sort 0.424179, #1 YY/XX -> YY/XX YY/XX -> YY/XX 0., #2 0., #3 0., #4 0.424179, #5 YY/XX -> YY/XX YY/XX -> YY/XX 0., #6 0.175701, #7 ZX -> ZX ZX -> ZX 0., #8 -0.10018, #9 ZZ -> ZZ ZZ -> ZZ 1.02406, #10 IX -> XX IX -> XX 0., #11 -0.5, #12 IZ -> ZZ IZ -> ZZ 0., #13 0., #14 -1.10018, #15 ZI -> ZZ ZI -> ZZ 1.5 #16 (trace) II -> YY II -> XX ]) # 0.25 * Tr[H * O] for some operators is 0 # find non-zero coefficients, excluding the traceless part; # make 1-indexed rather than 0-indexed nonzero_proj=np.nonzero(coeffs[:-1])[0]+1 diag = np.array([9, 12, 15]) nondiag = np.setdiff1d(nonzero_proj, diag) qubit_order = ['00', '10', '01', '11'] # try various orderings od = { # O(diagonal) # corresponds to outcomes given by qubit_order # TODO add other diagonal form for completeness 1: [1., -1., -1., 1.], # 3: None, # 4: None, 5: [1., -1., -1., 1.], # 6: None, 7: [1., -1., -1., 1.], # 8: None, 9: [1., -1., -1., 1.], 10: [1., -1., 1., -1.], # 11: None, 12: [1., -1., 1., -1.], # 13: None, # 14: None, 15: [1., 1., -1., -1.], } # because IBM ordering and textbook ordering of qubits differs, # associate each diagonal element with qubit ordering explicitly for index, diag_form in od.items(): od[index] = dict(zip(qubit_order, diag_form)) # group non-diagonal operators into groups that have the same circuit # TODO: how to do this automatically? nondiag_circ_groups = [[1,], [5,], [7, 10,]] # TODO circuit indices corresponding to operator indices # all necessary circuits are indexed (from 0); these indices are values of this dict, # keyed on all indices of those Pauli operators that have a non-zero contribution # to the traceless part of the Hamiltonian circ_idx = {} for diag_idx in diag: # assign circuit index 0 to operator indices for diagonal operator; circ_idx[diag_idx] = 0 # assign higher indices to all groups of non-diagonal operators, # where all operators in a group have the same circuit circ_index = 1 for circ_group in nondiag_circ_groups: for nondiag_idx in circ_group: circ_idx[nondiag_idx] = circ_index circ_index += 1 ncircuits = len(np.unique(list(circ_idx.values()))) print(f'There are {ncircuits:d} unique circuits') # stores indexes circuits circ = {} # define number of qubits and bits nqubits = 2 nclbits = 2 # create registers vqs_qreg = QuantumRegister(nqubits, name="q") vqs_creg = ClassicalRegister(nclbits, name="c") regs = [vqs_qreg, vqs_creg] # FIXME: some circuits are the same for different operators # => don't actually need separate measurements; # store operator indices grouped in arrays, # with the same circuit for each array. # Thus, all diagonal operators will have the same circuit, and # some non-diagonal operators will have the same circuit. # This circuit is the same for all diagonal operators for icirc in range(ncircuits): circ[icirc] = QuantumCircuit(*regs, name=str(icirc)) # measurement circuit meas = QuantumCircuit(*regs, name="meas") # .barrier prevents optimizations # from reordering gates across its source line meas.barrier(range(nqubits)) meas.measure(range(nqubits), range(nqubits)) # map qubits to clbits # constructs the non-diagonal circuits for operators 1, 5, and 7 and 10 # 1 circ[circ_idx[1]].h(0) circ[circ_idx[1]].iden(0) ## circ[circ_idx[1]].iden(1) circ[circ_idx[1]].h(1) # 5 ## circ[circ_idx[5]].h(0) circ[circ_idx[5]].iden(1) ## circ[circ_idx[5]].sdg(0) # conjugate of sqrt(Z) gate circ[circ_idx[5]].iden(1) ## circ[circ_idx[5]].iden(0) circ[circ_idx[5]].h(1) ## circ[circ_idx[5]].iden(0) circ[circ_idx[5]].sdg(1) # 7 and 10 circ[circ_idx[7]].iden(0) circ[circ_idx[7]].h(1) # add measurement to all operator circuits for icirc in range(ncircuits): # add measurement # can't see to modify value of this dict # by using an iterator over values: # probably, the QuantumCircuit object is # copied by value to the iterator in that case circ[icirc] = circ[icirc] + meas # can browse through various circuits associated to operators index = 9 print(f'Circuit for O{index:1d}') circ[circ_idx[index]].draw(output='latex', scale=0.5) backend_sim = Aer.get_backend('qasm_simulator') # execute the circuit on qasm_simulator backend; # set repeats (measurement shots) at 1024 (default) # memory = True: # per-shot measurement bitstrings are returned # as well (provided the backend supports it) nshots = 8*1021 # stores results indexed by operator job = {} res = {} for icirc in range(ncircuits): job[icirc] = execute(circ[icirc], backend_sim, shots=nshots, memory=True) res[icirc] = job[icirc].result() # takes in results from a single circuit # with memory=True, and estimates # the uncertanities on the probability of each outcome # (currently with bootstrap) # returns outcome:(pba, std) dictionary def compute_stats(results): # check that there is a single circuit in the results # (ambiguous otherwise) # TODO # pull number of qubits from results # generates all possible outcomes given \ # the number of qubits def _generate_bitstrings(nqubits=2): if (nqubits == 2): return ['00', '10', '01', '11'] else: print("I am hardcoded at the moment") raise # bootstrap specific? # given ensembles of outcomes and a particular outcome # calculates the statistics of that outcome: # returns outcome:(pba, std) estimates for the outcome def _calc_outcome_stats(ensembles, nshots, outcome): cts = np.count_nonzero(ensembles==outcome, axis=0) pba = np.mean(cts)/nshots std = np.std(cts/nshots, ddof = 1) # use unbiased estimator return (pba, std) outcomes = _generate_bitstrings() mem = res.get_memory() # stores pba[i][outcome] = [mean, std] pba[i] = {outcome:[0.,0.] for outcome in outcomes} # build ensembles # TODO retrieve nshots from results nshots = 1024 nens = nshots # choose number of ensemles = number of samples nsam = nshots ensembles = np.random.choice(mem[i], (nens, nsam)) stats = {map(lambda outcome: outcome:_calc_outcome_stats(ensembles, nshots, outcome), outcomes)} return stats import numpy as np # Function to generate all binary strings def _generate_bitstrings(nqubits, all_strings, a_string, irecur): if irecur == nqubits: all_strings.append(''.join([bit for bit in a_string])) return _generate_bitstrings(nqubits, all_strings, a_string + ['0'], irecur + 1) _generate_bitstrings(nqubits, all_strings, a_string + ['1'], irecur + 1) all_strings = [] _generate_bitstrings(2, all_strings, [], 0) print(all_strings) # computes probabilities and statistical uncertainties; # also saves raw counts to bootstrap on H directly mem = {} # stores all measurement results cts = {} # stores a total count of results pba = {} # stores final probabilities outcomes = ['00', '10', '01', '11'] # specific two 2-qubit register for i in range(ncircuits): cts[i] = res[i].get_counts(circ[i]) # this just sets the right shape for cts array mem[i] = res[i].get_memory(circ[i]) pba[i] = {outcome:[0.,0.] for outcome in outcomes} # stores pba[i][outcome] = [mean, std] nens = nshots nsam = nshots ensembles = np.random.choice(mem[i], (nens, nsam)) print(f'{i:d}') for outcome in outcomes: cts[i][outcome] = np.count_nonzero(ensembles==outcome, axis=0) pba[i][outcome][0] = (np.mean(cts[i][outcome])/nshots) pba[i][outcome][1] = (np.std(cts[i][outcome], ddof = 1)/nshots) print(f'{outcome}: {pba[i][outcome][0]:1.3g}, {pba[i][outcome][1]:1.1g}') # get array of operator indices corresponding to a circuit index op_idx = {} for op_index, circ_index in circ_idx.items(): op_idx[circ_index] = op_idx.setdefault(circ_index, []) op_idx[circ_index].append(op_index) # compute the value of identity measurement id_meas = [0.0, 0.0] # value, error # circuit index for diagonal operators is 0 id_mem = res[0].get_memory(circ[0]) # also compute measurement results to bootstrap on H directly id_cts = res[0].get_counts(circ[0]) # this just sets the right shape for cts array for outcome in outcomes: nens = len(id_mem) nsam = len(id_mem) ensembles = np.random.choice(id_mem, (nens, nsam)) id_cts[outcome] = np.count_nonzero(ensembles==outcome, axis=0) id_meas[0] += pba[0][outcome][0] id_meas[1] += pba[0][outcome][1]**2. id_meas[1] = np.sqrt(id_meas[1]) print(id_meas) # expect value = 1.0 from probability normalization # computing expectation values of operators, which have one set of indices # from measurement outcomes, which are indexed by circuits. Some operators correspond to the same circuit # circ_idx[operator_index] is a dictionary of circuit indices keyed on operator indices # also propagating raw measurement results to bootstrap on H directly od_meas = {index:[0.0, 0.0] for index in od.keys()} # store (measurement, uncert) for operators here #od_cts = {} for circ_index in range(ncircuits): # loop over various circuits print(f'circuit index {circ_index:d}') for outcome in outcomes: # probabilities of measurements are associated with circuits print(f'{outcome}: {pba[circ_index][outcome][0]:3.3f}, {pba[circ_index][outcome][1]:3.3f}') print(op_idx[circ_index]) for op_index in op_idx[circ_index]:# consider every operator corresponding to current circuit # copies counts from circuit measurements to corresponding operator #od_cts[op_index] = cts[circ_index][:] # does not modify the counts array #print(od_cts[op_index]) print(f'operator {op_index:d}') for outcome in outcomes: # loop over possible outcomes (measured qubit configurations) # eigenvalues multiplying the probabilities are associated with operators eigenval = od[op_index][outcome] print(f'{outcome}: {eigenval:1.1f}') # propagate counts, weighted by the eigenvalues #od_cts[op_index][outcome] = np.array(od_cts[op_index][outcome], dtype=np.float64) #print(od_cts[op_index][outcome]) #od_cts[op_index][outcome] *= eigenval #print(od_cts[op_index][outcome]) # multiply probabilities of outcomes by corresponding eigenvalue, sum over eigenvalues od_meas[op_index][0] += eigenval * pba[circ_index][outcome][0] # probability * eigenvalue od_meas[op_index][1] += abs(eigenval) * pba[circ_index][outcome][1] # propagated uncertainty ? FIXME # take squre root of sum of squares of uncertainties (assuming uncorrelated projected measurements) # od_meas[op_index][1] = np.sqrt(od_meas[op_index][1]) print(f'{od_meas[op_index][0]:4.4f}, {od_meas[op_index][1]:4.4f}') # combine probabilities and uncertainties to get the the expectation value of H in the fidicial state H_expect = [0.,0.] test = {outcome:0.0 for outcome in outcomes} # counts for i_nz_c in nonzero_proj: coeff = coeffs[i_nz_c-1] # shift back to 0-indexed value = od_meas[i_nz_c][0] error = od_meas[i_nz_c][1] H_expect[0] += coeff*value H_expect[1] += abs(coeff)*error for outcome in outcomes: eigenval = od[op_index][outcome] test[outcome] += (coeff * eigenval * cts[circ_idx[i_nz_c]][outcome] / nshots) test2=np.zeros(nsam) for outcome in outcomes: test2 += test[outcome] test2 += coeffs[15]*(id_cts[outcome]/nshots) # add the trace back mean2= np.mean(test2) std2 = np.std(test2) print((mean2, std2)) # add the trace back H_expect[0] += coeffs[15] * id_meas[0] H_expect[1] += abs(coeffs[15]) * id_meas[1] print(H_expect) mathematica_res = -0.20035992801439712 #print(H_expect) print((mean2, std2)) #print(H_expect[0]+H_expect[1], H_expect[0]-H_expect[1]) print((mean2+std2, mean2-std2)) print(mathematica_res) import matplotlib.pyplot as plt diag_bars = np.arange(len(diag)) avgs = [od_meas[diag_index][0] for diag_index in diag] stds = [od_meas[diag_index][1] for diag_index in diag] fig, ax = plt.subplots() ax.bar(diag_bars, avgs, yerr=stds, align='center', alpha=0.5, ecolor='black', edgecolor='k', error_kw=dict(lw=0.5, capsize=10, capthick=2.0), label='IBM sim') ax.set_ylabel(r'$\langle O \rangle_{\psi_{\mathrm{ini}}}$', fontsize=16) ax.set_xlabel('Diagonal Operators', fontsize=16) ax.set_xticks(diag_bars) ax.set_xticklabels(diag) ax.set_title(f'nshots={nshots:d}', fontsize=16) ax.axhline(y = 1.0, color='r', linewidth = 0.5, label='Mathematica') plt.ylim([0.99, 1.001]) plt.tight_layout() plt.legend(frameon=False, fontsize=16, bbox_to_anchor=(1.04,1), loc="upper left") plt.savefig("op_diag.png", dpi=300) nondiag_bars = np.arange(len(nondiag)) avgs = [od_meas[diag_index][0] for diag_index in nondiag] stds = [od_meas[diag_index][1] for diag_index in nondiag] fig, ax = plt.subplots() ax.bar(nondiag_bars, avgs, yerr=stds, align='center', alpha=0.5, ecolor='black', edgecolor='k', error_kw=dict(lw=0.5, capsize=10, capthick=2.0), label='IBM sim') ax.set_ylabel(r'$\langle O \rangle_{\psi_{\mathrm{ini}}}$', fontsize=16) ax.set_xlabel('Non-Diagonal Operators', fontsize=16) ax.set_xticks(nondiag_bars) ax.set_xticklabels(nondiag) ax.set_title(f'nshots={nshots:d}', fontsize=16) ax.axhline(y = 0.0, color='r', linewidth = 0.5, label='Mathematica') plt.tight_layout() plt.legend(frameon=False, fontsize=16, bbox_to_anchor=(1.04,1), loc="upper left") plt.savefig("op_nondiag.png", dpi=300)
https://github.com/vm6502q/qiskit-qrack-provider
vm6502q
# This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ QasmSimulator Integration Tests """ from test.terra.reference import ref_non_clifford from qiskit import execute from qiskit.providers.qrack import QasmSimulator class QasmNonCliffordTestsTGate: """QasmSimulator T gate tests in default basis.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} # --------------------------------------------------------------------- # Test t-gate # --------------------------------------------------------------------- def test_t_gate_deterministic_default_basis_gates(self): """Test t-gate circuits compiling to backend default basis_gates.""" shots = 100 circuits = ref_non_clifford.t_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.t_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_t_gate_nondeterministic_default_basis_gates(self): """Test t-gate circuits compiling to backend default basis_gates.""" shots = 4000 circuits = ref_non_clifford.t_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.t_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test tdg-gate # --------------------------------------------------------------------- def test_tdg_gate_deterministic_default_basis_gates(self): """Test tdg-gate circuits compiling to backend default basis_gates.""" shots = 100 circuits = ref_non_clifford.tdg_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.tdg_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_tdg_gate_nondeterministic_default_basis_gates(self): """Test tdg-gate circuits compiling to backend default basis_gates.""" shots = 4000 circuits = ref_non_clifford.tdg_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.tdg_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) class QasmNonCliffordTestsCCXGate: """QasmSimulator CCX gate tests in default basis.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} # --------------------------------------------------------------------- # Test ccx-gate # --------------------------------------------------------------------- def test_ccx_gate_deterministic_default_basis_gates(self): """Test ccx-gate circuits compiling to backend default basis_gates.""" shots = 100 circuits = ref_non_clifford.ccx_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.ccx_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_ccx_gate_nondeterministic_default_basis_gates(self): """Test ccx-gate circuits compiling to backend default basis_gates.""" shots = 4000 circuits = ref_non_clifford.ccx_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.ccx_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) class QasmNonCliffordTestsCGates: """QasmSimulator CSwap gate tests in default basis.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} # --------------------------------------------------------------------- # Test cswap-gate (Fredkin) # --------------------------------------------------------------------- def test_cswap_gate_deterministic_default_basis_gates(self): shots = 100 circuits = ref_non_clifford.cswap_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.cswap_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_cswap_gate_nondeterministic_default_basis_gates(self): shots = 4000 circuits = ref_non_clifford.cswap_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.cswap_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test cu1 gate # --------------------------------------------------------------------- def test_cu1_gate_nondeterministic_default_basis_gates(self): """Test cu1-gate gate circuits compiling to default basis.""" shots = 4000 circuits = ref_non_clifford.cu1_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.cu1_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test cu3 gate # --------------------------------------------------------------------- def test_cu3_gate_deterministic_default_basis_gates(self): """Test cu3-gate gate circuits compiling to default basis.""" shots = 100 circuits = ref_non_clifford.cu3_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.cu3_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) class QasmNonCliffordTestsWaltzBasis: """QasmSimulator non-Clifford gate tests in minimal u1,u2,u3,cx basis.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} # --------------------------------------------------------------------- # Test t-gate # --------------------------------------------------------------------- def test_t_gate_deterministic_waltz_basis_gates(self): """Test t-gate gate circuits compiling to u1,u2,u3,cx""" shots = 100 circuits = ref_non_clifford.t_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.t_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_t_gate_nondeterministic_waltz_basis_gates(self): """Test t-gate gate circuits compiling to u1,u2,u3,cx""" shots = 4000 circuits = ref_non_clifford.t_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.t_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test tdg-gate # --------------------------------------------------------------------- def test_tdg_gate_deterministic_waltz_basis_gates(self): """Test tdg-gate gate circuits compiling to u1,u2,u3,cx""" shots = 100 circuits = ref_non_clifford.tdg_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.tdg_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_tdg_gate_nondeterministic_waltz_basis_gates(self): """Test tdg-gate gate circuits compiling to u1,u2,u3,cx""" shots = 4000 circuits = ref_non_clifford.tdg_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.tdg_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test ccx-gate # --------------------------------------------------------------------- def test_ccx_gate_deterministic_waltz_basis_gates(self): """Test ccx-gate gate circuits compiling to u1,u2,u3,cx""" shots = 100 circuits = ref_non_clifford.ccx_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.ccx_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_ccx_gate_nondeterministic_waltz_basis_gates(self): """Test ccx-gate gate circuits compiling to u1,u2,u3,cx""" shots = 4000 circuits = ref_non_clifford.ccx_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.ccx_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test cswap-gate (Fredkin) # --------------------------------------------------------------------- def test_cswap_gate_deterministic_waltz_basis_gates(self): """Test cswap-gate gate circuits compiling to u1,u2,u3,cx""" shots = 100 circuits = ref_non_clifford.cswap_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.cswap_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_cswap_gate_nondeterministic_waltz_basis_gates(self): """Test cswap-gate gate circuits compiling to u1,u2,u3,cx""" shots = 4000 circuits = ref_non_clifford.cswap_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.cswap_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test cu1 gate # --------------------------------------------------------------------- def test_cu1_gate_nondeterministic_waltz_basis_gates(self): """Test cu1-gate gate circuits compiling to u1,u2,u3,cx""" shots = 4000 circuits = ref_non_clifford.cu1_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.cu1_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test cu3 gate # --------------------------------------------------------------------- def test_cu3_gate_deterministic_waltz_basis_gates(self): """Test cu3-gate gate circuits compiling to u1,u2,u3,cx.""" shots = 100 circuits = ref_non_clifford.cu3_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.cu3_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u1', 'u2', 'u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) class QasmNonCliffordTestsMinimalBasis: """QasmSimulator non-Clifford gate tests in minimal U,CX basis.""" SIMULATOR = QasmSimulator() BACKEND_OPTS = {} # --------------------------------------------------------------------- # Test t-gate # --------------------------------------------------------------------- def test_t_gate_deterministic_minimal_basis_gates(self): """Test t-gate gate circuits compiling to u3,cx""" shots = 100 circuits = ref_non_clifford.t_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.t_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx']) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_t_gate_nondeterministic_minimal_basis_gates(self): """Test t-gate gate circuits compiling to u3,cx""" shots = 4000 circuits = ref_non_clifford.t_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.t_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test tdg-gate # --------------------------------------------------------------------- def test_tdg_gate_deterministic_minimal_basis_gates(self): """Test tdg-gate gate circuits compiling to u3,cx""" shots = 100 circuits = ref_non_clifford.tdg_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.tdg_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_tdg_gate_nondeterministic_minimal_basis_gates(self): """Test tdg-gate gate circuits compiling to u3,cx""" shots = 4000 circuits = ref_non_clifford.tdg_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.tdg_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.05 * shots) # --------------------------------------------------------------------- # Test ccx-gate # --------------------------------------------------------------------- def test_ccx_gate_deterministic_minimal_basis_gates(self): """Test ccx-gate gate circuits compiling to u3,cx""" shots = 100 circuits = ref_non_clifford.ccx_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.ccx_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_ccx_gate_nondeterministic_minimal_basis_gates(self): """Test ccx-gate gate circuits compiling to u3,cx""" shots = 4000 circuits = ref_non_clifford.ccx_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.ccx_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.1 * shots) # --------------------------------------------------------------------- # Test cu1 gate # --------------------------------------------------------------------- def test_cu1_gate_nondeterministic_minimal_basis_gates(self): """Test cu1-gate gate circuits compiling to u3,cx""" shots = 4000 circuits = ref_non_clifford.cu1_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.cu1_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.1 * shots) # --------------------------------------------------------------------- # Test cswap-gate (Fredkin) # --------------------------------------------------------------------- def test_cswap_gate_deterministic_minimal_basis_gates(self): """Test cswap-gate gate circuits compiling to u3,cx""" shots = 100 circuits = ref_non_clifford.cswap_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.cswap_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0) def test_cswap_gate_nondeterministic_minimal_basis_gates(self): """Test cswap-gate gate circuits compiling to u3,cx""" shots = 4000 circuits = ref_non_clifford.cswap_gate_circuits_nondeterministic( final_measure=True) targets = ref_non_clifford.cswap_gate_counts_nondeterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0.1 * shots) # --------------------------------------------------------------------- # Test cu3 gate # --------------------------------------------------------------------- def test_cu3_gate_deterministic_default_basis_gates(self): """Test cu3-gate gate circuits compiling to u3, cx.""" shots = 100 circuits = ref_non_clifford.cu3_gate_circuits_deterministic( final_measure=True) targets = ref_non_clifford.cu3_gate_counts_deterministic(shots) job = execute(circuits, self.SIMULATOR, shots=shots, basis_gates=['u3', 'cx'], **self.BACKEND_OPTS) result = job.result() self.assertSuccess(result) self.compare_counts(result, circuits, targets, delta=0)
https://github.com/swe-train/qiskit__qiskit
swe-train
# -*- 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/rishikhurana2/FourQuantumAlgorithms
rishikhurana2
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 19 19:13:26 2023 @author: abdullahalshihry """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 18 19:15:12 2023 @author: abdullahalshihry """ import qiskit as qs import qiskit.visualization as qv import random import qiskit.circuit as qf def Deutsch_Jozsa(circuit): qr = qs.QuantumRegister(5,'q') cr = qs.ClassicalRegister(4,'c') qc = qs.QuantumCircuit(qr,cr) qc.x(qr[4]) qc.barrier(range(5)) qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.h(qr[3]) qc.h(qr[4]) qc.barrier(range(5)) qc = qc.compose(circuit) qc.barrier(range(5)) qc.h(qr[0]) qc.h(qr[1]) qc.h(qr[2]) qc.h(qr[3]) qc.barrier(range(5)) qc.measure(0,0) qc.measure(1,1) qc.measure(2,2) qc.measure(3,3) job1 = qs.execute(qc, qs.Aer.get_backend('aer_simulator'), shots = 1024) output1 = job1.result().get_counts() print(output1) qc.draw('mpl') def Oracle(): qr = qs.QuantumRegister(5,'q') cr = qs.ClassicalRegister(4,'c') qc = qs.QuantumCircuit(qr,cr) qq = qs.QuantumCircuit(5,name='Uf') v = random.randint(1, 2) if v == 1: qc.cx(0,4) qc.cx(1,4) qc.cx(2,4) qc.cx(3,4) print('Balanced (1)') elif v == 2: qq.i(qr[0]) qq.i(qr[1]) qq.i(qr[2]) qq.i(qr[3]) print('Constant (0)') qq =qq.to_gate() qc.append(qq,[0,1,2,3,4]) return qc Deutsch_Jozsa(Oracle())
https://github.com/qclib/qclib
qclib
# Copyright 2021 qclib project. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ n-qubit controlled gate """ from collections import namedtuple import numpy as np import qiskit from qiskit.circuit import Gate from qiskit import QuantumCircuit, QuantumRegister from .util import check_u2, apply_ctrl_state # pylint: disable=maybe-no-member # pylint: disable=protected-access class Ldmcu(Gate): """ Linear Depth Multi-Controlled Unitary ----------------------------------------- Implements gate decomposition of a multi-controlled operator in U(2) according to https://arxiv.org/abs/2203.11882 https://journals.aps.org/pra/abstract/10.1103/PhysRevA.106.042602. """ def __init__(self, unitary, num_controls, ctrl_state: str = None): check_u2(unitary) self.unitary = unitary if num_controls > 0: self.control_qubits = QuantumRegister(num_controls) else: self.control_qubits = [] self.target_qubit = QuantumRegister(1) self.num_qubits = num_controls + 1 self.ctrl_state = ctrl_state super().__init__("Ldmcu", self.num_qubits, [], "Ldmcu") def _define(self): if len(self.control_qubits) > 0: self.definition = QuantumCircuit(self.control_qubits, self.target_qubit) self._apply_ctrl_state() qubits_indexes = list(range(self.num_qubits)) gate_circuit = qiskit.QuantumCircuit(self.num_qubits, name="T" + str(0)) self._c1c2(self.unitary, self.num_qubits, gate_circuit) self._c1c2(self.unitary, self.num_qubits, gate_circuit, step=-1) self._c1c2(self.unitary, self.num_qubits - 1, gate_circuit, False) self._c1c2(self.unitary, self.num_qubits - 1, gate_circuit, False, step=-1) self.definition.append(gate_circuit, [*self.control_qubits, self.target_qubit]) self._apply_ctrl_state() else: self.definition = QuantumCircuit(self.target_qubit) self.definition.unitary(self.unitary, 0) def _c1c2(self, unitary, n_qubits, gate_circ, first=True, step=1): pairs = namedtuple("pairs", ["control", "target"]) if step == 1: start = 0 reverse = True else: start = 1 reverse = False qubit_pairs = [ pairs(control, target) for target in range(n_qubits) for control in range(start, target) ] qubit_pairs.sort(key=lambda e: e.control + e.target, reverse=reverse) for pair in qubit_pairs: exponent = pair.target - pair.control if pair.control == 0: exponent = exponent - 1 param = 2 ** exponent signal = -1 if (pair.control == 0 and not first) else 1 signal = step * signal if pair.target == n_qubits - 1 and first: csqgate = Ldmcu._gate_u(unitary, param, signal) gate_circ.compose(csqgate, qubits=[pair.control, pair.target], inplace=True) else: gate_circ.crx(signal * np.pi / param, pair.control, pair.target) @staticmethod def _gate_u(agate, coef, signal): param = 1 / np.abs(coef) values, vectors = np.linalg.eig(agate) gate = np.power(values[0] + 0j, param) * vectors[:, [0]] @ vectors[:, [0]].conj().T gate = ( gate + np.power(values[1] + 0j, param) * vectors[:, [1]] @ vectors[:, [1]].conj().T ) if signal < 0: gate = np.linalg.inv(gate) sqgate = QuantumCircuit(1, name="U^1/" + str(coef)) sqgate.unitary(gate, 0) # pylint: disable=maybe-no-member csqgate = sqgate.control(1) return csqgate @staticmethod def ldmcu(circuit, unitary, controls, target, ctrl_state=None): circuit.append( Ldmcu(unitary, len(controls), ctrl_state=ctrl_state), [*controls, target] ) Ldmcu._apply_ctrl_state = apply_ctrl_state
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import copy # Problem modelling imports from docplex.mp.model import Model # Qiskit imports from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit.utils.algorithm_globals import algorithm_globals from qiskit_optimization.algorithms import MinimumEigenOptimizer, CplexOptimizer from qiskit_optimization import QuadraticProgram from qiskit_optimization.problems.variable import VarType from qiskit_optimization.converters.quadratic_program_to_qubo import QuadraticProgramToQubo from qiskit_optimization.translators import from_docplex_mp def create_problem(mu: np.array, sigma: np.array, total: int = 3) -> QuadraticProgram: """Solve the quadratic program using docplex.""" mdl = Model() x = [mdl.binary_var("x%s" % i) for i in range(len(sigma))] objective = mdl.sum([mu[i] * x[i] for i in range(len(mu))]) objective -= 2 * mdl.sum( [sigma[i, j] * x[i] * x[j] for i in range(len(mu)) for j in range(len(mu))] ) mdl.maximize(objective) cost = mdl.sum(x) mdl.add_constraint(cost == total) qp = from_docplex_mp(mdl) return qp def relax_problem(problem) -> QuadraticProgram: """Change all variables to continuous.""" relaxed_problem = copy.deepcopy(problem) for variable in relaxed_problem.variables: variable.vartype = VarType.CONTINUOUS return relaxed_problem mu = np.array([3.418, 2.0913, 6.2415, 4.4436, 10.892, 3.4051]) sigma = np.array( [ [1.07978412, 0.00768914, 0.11227606, -0.06842969, -0.01016793, -0.00839765], [0.00768914, 0.10922887, -0.03043424, -0.0020045, 0.00670929, 0.0147937], [0.11227606, -0.03043424, 0.985353, 0.02307313, -0.05249785, 0.00904119], [-0.06842969, -0.0020045, 0.02307313, 0.6043817, 0.03740115, -0.00945322], [-0.01016793, 0.00670929, -0.05249785, 0.03740115, 0.79839634, 0.07616951], [-0.00839765, 0.0147937, 0.00904119, -0.00945322, 0.07616951, 1.08464544], ] ) qubo = create_problem(mu, sigma) print(qubo.prettyprint()) result = CplexOptimizer().solve(qubo) print(result.prettyprint()) qp = relax_problem(QuadraticProgramToQubo().convert(qubo)) print(qp.prettyprint()) sol = CplexOptimizer().solve(qp) print(sol.prettyprint()) c_stars = sol.samples[0].x print(c_stars) algorithm_globals.random_seed = 12345 qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA(), initial_point=[0.0, 1.0]) exact_mes = NumPyMinimumEigensolver() qaoa = MinimumEigenOptimizer(qaoa_mes) qaoa_result = qaoa.solve(qubo) print(qaoa_result.prettyprint()) from qiskit import QuantumCircuit thetas = [2 * np.arcsin(np.sqrt(c_star)) for c_star in c_stars] init_qc = QuantumCircuit(len(sigma)) for idx, theta in enumerate(thetas): init_qc.ry(theta, idx) init_qc.draw(output="mpl") from qiskit.circuit import Parameter beta = Parameter("β") ws_mixer = QuantumCircuit(len(sigma)) for idx, theta in enumerate(thetas): ws_mixer.ry(-theta, idx) ws_mixer.rz(-2 * beta, idx) ws_mixer.ry(theta, idx) ws_mixer.draw(output="mpl") ws_qaoa_mes = QAOA( sampler=Sampler(), optimizer=COBYLA(), initial_state=init_qc, mixer=ws_mixer, initial_point=[0.0, 1.0], ) ws_qaoa = MinimumEigenOptimizer(ws_qaoa_mes) ws_qaoa_result = ws_qaoa.solve(qubo) print(ws_qaoa_result.prettyprint()) def format_qaoa_samples(samples, max_len: int = 10): qaoa_res = [] for s in samples: if sum(s.x) == 3: qaoa_res.append(("".join([str(int(_)) for _ in s.x]), s.fval, s.probability)) res = sorted(qaoa_res, key=lambda x: -x[1])[0:max_len] return [(_[0] + f": value: {_[1]:.3f}, probability: {1e2*_[2]:.1f}%") for _ in res] format_qaoa_samples(qaoa_result.samples) format_qaoa_samples(ws_qaoa_result.samples) from qiskit_optimization.algorithms import WarmStartQAOAOptimizer qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA(), initial_point=[0.0, 1.0]) ws_qaoa = WarmStartQAOAOptimizer( pre_solver=CplexOptimizer(), relax_for_pre_solver=True, qaoa=qaoa_mes, epsilon=0.0 ) ws_result = ws_qaoa.solve(qubo) print(ws_result.prettyprint()) format_qaoa_samples(ws_result.samples) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.quantum_info import SparsePauliOp H2_op = SparsePauliOp.from_list( [ ("II", -1.052373245772859), ("IZ", 0.39793742484318045), ("ZI", -0.39793742484318045), ("ZZ", -0.01128010425623538), ("XX", 0.18093119978423156), ] ) from qiskit.circuit.library import TwoLocal from qiskit.algorithms.optimizers import SLSQP ansatz = TwoLocal(3, rotation_blocks=["ry", "rz"], entanglement_blocks="cz", reps=1) optimizer = SLSQP() ansatz.decompose().draw('mpl') from qiskit.primitives import Sampler, Estimator from qiskit.algorithms.state_fidelities import ComputeUncompute estimator = Estimator() sampler = Sampler() fidelity = ComputeUncompute(sampler) k = 3 betas = [33, 33, 33] counts = [] values = [] steps = [] def callback(eval_count, params, value, meta, step): counts.append(eval_count) values.append(value) steps.append(step) from qiskit.algorithms.eigensolvers import VQD vqd = VQD(estimator, fidelity, ansatz, optimizer, k=k, betas=betas, callback=callback) result = vqd.compute_eigenvalues(operator = H2_op) vqd_values = result.optimal_values print(vqd_values) import numpy as np import pylab pylab.rcParams["figure.figsize"] = (12, 8) steps = np.asarray(steps) counts = np.asarray(counts) values = np.asarray(values) for i in range(1,4): _counts = counts[np.where(steps == i)] _values = values[np.where(steps == i)] pylab.plot(_counts, _values, label=f"State {i-1}") pylab.xlabel("Eval count") pylab.ylabel("Energy") pylab.title("Energy convergence for each computed state") pylab.legend(loc="upper right"); from qiskit.algorithms.eigensolvers import NumPyEigensolver from qiskit.opflow import PauliSumOp exact_solver = NumPyEigensolver(k=3) exact_result = exact_solver.compute_eigenvalues(PauliSumOp(H2_op)) ref_values = exact_result.eigenvalues print(f"Reference values: {ref_values}") print(f"VQD values: {vqd_values}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt import numpy as np from IPython.display import clear_output from qiskit import QuantumCircuit from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit.utils import algorithm_globals from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier, VQC from qiskit_machine_learning.algorithms.regressors import NeuralNetworkRegressor, VQR from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN algorithm_globals.random_seed = 42 num_inputs = 2 num_samples = 20 X = 2 * algorithm_globals.random.random([num_samples, num_inputs]) - 1 y01 = 1 * (np.sum(X, axis=1) >= 0) # in { 0, 1} y = 2 * y01 - 1 # in {-1, +1} y_one_hot = np.zeros((num_samples, 2)) for i in range(num_samples): y_one_hot[i, y01[i]] = 1 for x, y_target in zip(X, y): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() # construct QNN qc = QuantumCircuit(2) feature_map = ZZFeatureMap(2) ansatz = RealAmplitudes(2) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) qc.draw(output="mpl") estimator_qnn = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters ) # QNN maps inputs to [-1, +1] estimator_qnn.forward(X[0, :], algorithm_globals.random.random(estimator_qnn.num_weights)) # callback function that draws a live plot when the .fit() method is called def callback_graph(weights, obj_func_eval): clear_output(wait=True) objective_func_vals.append(obj_func_eval) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() # construct neural network classifier estimator_classifier = NeuralNetworkClassifier( estimator_qnn, optimizer=COBYLA(maxiter=60), callback=callback_graph ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data estimator_classifier.fit(X, y) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier estimator_classifier.score(X, y) # evaluate data points y_predict = estimator_classifier.predict(X) # plot results # red == wrongly classified for x, y_target, y_p in zip(X, y, y_predict): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if y_target != y_p: plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() estimator_classifier.weights # construct feature map feature_map = ZZFeatureMap(num_inputs) # construct ansatz ansatz = RealAmplitudes(num_inputs, reps=1) # construct quantum circuit qc = QuantumCircuit(num_inputs) qc.append(feature_map, range(num_inputs)) qc.append(ansatz, range(num_inputs)) qc.decompose().draw(output="mpl") # parity maps bitstrings to 0 or 1 def parity(x): return "{:b}".format(x).count("1") % 2 output_shape = 2 # corresponds to the number of classes, possible outcomes of the (parity) mapping. # construct QNN sampler_qnn = SamplerQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, interpret=parity, output_shape=output_shape, ) # construct classifier sampler_classifier = NeuralNetworkClassifier( neural_network=sampler_qnn, optimizer=COBYLA(maxiter=30), callback=callback_graph ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data sampler_classifier.fit(X, y01) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier sampler_classifier.score(X, y01) # evaluate data points y_predict = sampler_classifier.predict(X) # plot results # red == wrongly classified for x, y_target, y_p in zip(X, y01, y_predict): if y_target == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if y_target != y_p: plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() sampler_classifier.weights # construct feature map, ansatz, and optimizer feature_map = ZZFeatureMap(num_inputs) ansatz = RealAmplitudes(num_inputs, reps=1) # construct variational quantum classifier vqc = VQC( feature_map=feature_map, ansatz=ansatz, loss="cross_entropy", optimizer=COBYLA(maxiter=30), callback=callback_graph, ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data vqc.fit(X, y_one_hot) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier vqc.score(X, y_one_hot) # evaluate data points y_predict = vqc.predict(X) # plot results # red == wrongly classified for x, y_target, y_p in zip(X, y_one_hot, y_predict): if y_target[0] == 1: plt.plot(x[0], x[1], "bo") else: plt.plot(x[0], x[1], "go") if not np.all(y_target == y_p): plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2) plt.plot([-1, 1], [1, -1], "--", color="black") plt.show() from sklearn.datasets import make_classification from sklearn.preprocessing import MinMaxScaler X, y = make_classification( n_samples=10, n_features=2, n_classes=3, n_redundant=0, n_clusters_per_class=1, class_sep=2.0, random_state=algorithm_globals.random_seed, ) X = MinMaxScaler().fit_transform(X) plt.scatter(X[:, 0], X[:, 1], c=y) y_cat = np.empty(y.shape, dtype=str) y_cat[y == 0] = "A" y_cat[y == 1] = "B" y_cat[y == 2] = "C" print(y_cat) vqc = VQC( num_qubits=2, optimizer=COBYLA(maxiter=30), callback=callback_graph, ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit classifier to data vqc.fit(X, y_cat) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score classifier vqc.score(X, y_cat) predict = vqc.predict(X) print(f"Predicted labels: {predict}") print(f"Ground truth: {y_cat}") num_samples = 20 eps = 0.2 lb, ub = -np.pi, np.pi X_ = np.linspace(lb, ub, num=50).reshape(50, 1) f = lambda x: np.sin(x) X = (ub - lb) * algorithm_globals.random.random([num_samples, 1]) + lb y = f(X[:, 0]) + eps * (2 * algorithm_globals.random.random(num_samples) - 1) plt.plot(X_, f(X_), "r--") plt.plot(X, y, "bo") plt.show() # construct simple feature map param_x = Parameter("x") feature_map = QuantumCircuit(1, name="fm") feature_map.ry(param_x, 0) # construct simple ansatz param_y = Parameter("y") ansatz = QuantumCircuit(1, name="vf") ansatz.ry(param_y, 0) # construct a circuit qc = QuantumCircuit(1) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) # construct QNN regression_estimator_qnn = EstimatorQNN( circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters ) # construct the regressor from the neural network regressor = NeuralNetworkRegressor( neural_network=regression_estimator_qnn, loss="squared_error", optimizer=L_BFGS_B(maxiter=5), callback=callback_graph, ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit to data regressor.fit(X, y) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score the result regressor.score(X, y) # plot target function plt.plot(X_, f(X_), "r--") # plot data plt.plot(X, y, "bo") # plot fitted line y_ = regressor.predict(X_) plt.plot(X_, y_, "g-") plt.show() regressor.weights vqr = VQR( feature_map=feature_map, ansatz=ansatz, optimizer=L_BFGS_B(maxiter=5), callback=callback_graph, ) # create empty array for callback to store evaluations of the objective function objective_func_vals = [] plt.rcParams["figure.figsize"] = (12, 6) # fit regressor vqr.fit(X, y) # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) # score result vqr.score(X, y) # plot target function plt.plot(X_, f(X_), "r--") # plot data plt.plot(X, y, "bo") # plot fitted line y_ = vqr.predict(X_) plt.plot(X_, y_, "g-") plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qgss-2023
qiskit-community
from qiskit.circuit import QuantumCircuit from qiskit.primitives import Estimator, Sampler from qiskit.quantum_info import SparsePauliOp from qiskit.visualization import plot_histogram import numpy as np import matplotlib.pyplot as plt plt.style.use('dark_background') # optional # create excited |1> state qc_1 = QuantumCircuit(1) qc_1.x(0) qc_1.draw('mpl') # create superposition |+> state qc_plus = QuantumCircuit(1) qc_plus.h(0) qc_plus.draw('mpl') qc_1.measure_all() qc_plus.measure_all() sampler = Sampler() job_1 = sampler.run(qc_1) job_plus = sampler.run(qc_plus) job_1.result().quasi_dists job_plus.result().quasi_dists legend = ["Excited State", "Plus State"] # TODO: Excited State does not appear plot_histogram([job_1.result().quasi_dists[0], job_plus.result().quasi_dists[0]], legend=legend) qc_1.remove_final_measurements() qc_plus.remove_final_measurements() # rotate into the X-basis qc_1.h(0) qc_plus.h(0) qc_1.measure_all() qc_plus.measure_all() sampler = Sampler() job_1 = sampler.run(qc_1) job_plus = sampler.run(qc_plus) plot_histogram([job_1.result().quasi_dists[0], job_plus.result().quasi_dists[0]], legend=legend) qc2_1 = QuantumCircuit(1) qc2_1.x(0) qc2_plus = QuantumCircuit(1) qc2_plus.h(0) obsvs = list(SparsePauliOp(['Z', 'X'])) estimator = Estimator() job2_1 = estimator.run([qc2_1]*len(obsvs), observables=obsvs) job2_plus = estimator.run([qc2_plus]*len(obsvs), observables=obsvs) job2_1.result() # TODO: make this into module that outputs a nice table print(f' | <Z> | <X> ') print(f'----|------------------') print(f'|1> | {job2_1.result().values[0]} | {job2_1.result().values[1]}') print(f'|+> | {job2_plus.result().values[0]} | {job2_plus.result().values[1]}') obsv = # create operator for chsh witness from qc_grader.challenges.qgss_2023 import grade_lab2_ex1 grade_lab2_ex1(obsv) from qiskit.circuit import Parameter theta = Parameter('θ') qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) qc.ry(theta, 0) qc.draw('mpl') angles = # create a parameterization of angles that will violate the inequality estimator = Estimator() job = estimator.run([qc]*len(angles), observables=[obsv]*len(angles), parameter_values=angles) exps = job.result().values plt.plot(angles, exps, marker='x', ls='-', color='green') plt.plot(angles, [2]*len(angles), ls='--', color='red', label='Classical Bound') plt.plot(angles, [-2]*len(angles), ls='--', color='red') plt.xlabel('angle (rad)') plt.ylabel('CHSH Witness') plt.legend(loc=4) from qc_grader.challenges.qgss_2023 import grade_lab2_ex2 grade_lab2_ex2(obsv, angles) from qiskit.circuit import ClassicalRegister, QuantumRegister theta = Parameter('θ') qr = QuantumRegister(1, 'q') qc = QuantumCircuit(qr) qc.ry(theta, 0) qc.draw('mpl') tele_qc = qc.copy() bell = QuantumRegister(2, 'Bell') alice = ClassicalRegister(2, 'Alice') bob = ClassicalRegister(1, 'Bob') tele_qc.add_register(bell, alice, bob) tele_qc.draw('mpl') # create Bell state with other two qubits tele_qc.barrier() tele_qc.h(1) tele_qc.cx(1, 2) tele_qc.barrier() tele_qc.draw('mpl') # alice operates on her qubits tele_qc.cx(0, 1) tele_qc.h(0) tele_qc.barrier() tele_qc.draw('mpl') tele_qc.measure([qr[0], bell[0]], alice) tele_qc.draw('mpl') graded_qc = tele_qc.copy() ############################## # add gates to graded_qc here ############################## graded_qc.draw('mpl') graded_qc.barrier() graded_qc.measure(bell[1], bob) graded_qc.draw('mpl') from qc_grader.challenges.qgss_2023 import grade_lab2_ex3 grade_lab2_ex3(graded_qc, theta, 5*np.pi/7) from qiskit_aer.primitives import Sampler angle = 5*np.pi/7 sampler = Sampler() qc.measure_all() job_static = sampler.run(qc.bind_parameters({theta: angle})) job_dynamic = sampler.run(graded_qc.bind_parameters({theta: angle})) print(f"Original Dists: {job_static.result().quasi_dists[0].binary_probabilities()}") print(f"Teleported Dists: {job_dynamic.result().quasi_dists[0].binary_probabilities()}") from qiskit.result import marginal_counts tele_counts = # marginalize counts legend = ['Original State', 'Teleported State'] plot_histogram([job_static.result().quasi_dists[0].binary_probabilities(), tele_counts], legend=legend) from qc_grader.challenges.qgss_2023 import grade_lab2_ex4 grade_lab2_ex4(tele_counts, job_dynamic.result()) import qiskit.tools.jupyter %qiskit_version_table
https://github.com/daimurat/qiskit-implementation
daimurat
# スピン多重度 multiplicity = 1 # 全電荷 charge = 0 # 原子核配置 distance = 0.977 geometry = [["H", [0, 0, 0]], ["H", [0, 0, distance]]] !pip install qulacs pyscf openfermion openfermionpyscf from openfermion.transforms import get_fermion_operator, jordan_wigner from openfermion.hamiltonians import MolecularData from openfermionpyscf import run_pyscf from pyscf import fci # 分子軌道を表現するための基底関数(Slator Type Orbital - 3 gaussian) basis = "sto-3g" # 計算結果の保存場所 description = "tmp" molecule = MolecularData(geometry, basis, multiplicity, charge, description) molecule = run_pyscf(molecule, run_scf=1, run_fci=1) n_qubit = molecule.n_qubits n_electron = molecule.n_electrons # get_molecular_hamiltonianで第二量子化形式のハミルトニアンを計算 fermionic_hamiltonian = get_fermion_operator( molecule.get_molecular_hamiltonian()) # Jordan-Wigner変換によりハミルトニアンをパウリ行列のテンソル積形式に変換 jw_hamiltonian = jordan_wigner(fermionic_hamiltonian) print(jw_hamiltonian) from qiskit.chemistry.drivers import PySCFDriver, UnitsType, Molecule from qiskit.chemistry.transformations import FermionicTransformation,FermionicTransformationType, FermionicQubitMappingType basis = "sto3g" molecule = Molecule(geometry=geometry, charge=charge, multiplicity=multiplicity) driver = PySCFDriver(molecule = molecule, unit=UnitsType.ANGSTROM, basis=basis) transformation = FermionicTransformation( transformation=FermionicTransformationType.FULL, qubit_mapping=FermionicQubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False, freeze_core=False) qubit_op, _ = transformation.transform(driver) print(qubit_op)
https://github.com/urwin419/QiskitChecker
urwin419
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": ### replaced z gate ### qc.x(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) return qc
https://github.com/Axect/QuantumAlgorithms
Axect
#initialization import matplotlib.pyplot as plt import numpy as np import math # importing Qiskit from qiskit import IBMQ, Aer, transpile, assemble from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister # import basic plot tools from qiskit.visualization import plot_histogram qpe = QuantumCircuit(4, 3) qpe.x(3) #Apply Hadamard gate for qubit in range(3): qpe.h(qubit) qpe.draw() repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe.cp(math.pi/4, counting_qubit, 3); # This is CU # we use 2*pi*(1/theta) repetitions *= 2 qpe.draw() 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(-math.pi/float(2**(j-m)), m, j) qc.h(j) qpe.barrier() # Apply inverse QFT qft_dagger(qpe, 3) # Measure qpe.barrier() for n in range(3): qpe.measure(n,n) qpe.draw() aer_sim = Aer.get_backend('aer_simulator') shots = 2048 t_qpe = transpile(qpe, aer_sim) qobj = assemble(t_qpe, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) # Create and set up circuit qpe2 = QuantumCircuit(4, 3) # Apply H-Gates to counting qubits: for qubit in range(3): qpe2.h(qubit) # Prepare our eigenstate |psi>: qpe2.x(3) # Do the controlled-U operations: angle = 2*math.pi/3 repetitions = 1 for counting_qubit in range(3): for i in range(repetitions): qpe2.cp(angle, counting_qubit, 3); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe2, 3) # Measure of course! for n in range(3): qpe2.measure(n,n) qpe2.draw() # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') shots = 4096 t_qpe2 = transpile(qpe2, aer_sim) qobj = assemble(t_qpe2, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) # Create and set up circuit qpe3 = QuantumCircuit(6, 5) # Apply H-Gates to counting qubits: for qubit in range(5): qpe3.h(qubit) # Prepare our eigenstate |psi>: qpe3.x(5) # Do the controlled-U operations: angle = 2*math.pi/3 repetitions = 1 for counting_qubit in range(5): for i in range(repetitions): qpe3.cp(angle, counting_qubit, 5); repetitions *= 2 # Do the inverse QFT: qft_dagger(qpe3, 5) # Measure of course! qpe3.barrier() for n in range(5): qpe3.measure(n,n) qpe3.draw() # Let's see the results! aer_sim = Aer.get_backend('aer_simulator') shots = 4096 t_qpe3 = transpile(qpe3, aer_sim) qobj = assemble(t_qpe3, shots=shots) results = aer_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/JohnBurke4/qaoa_testing_framework
JohnBurke4
# 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. """Prepare a quantum state from the state where all qubits are 0.""" from typing import Union, Optional import math import numpy as np from qiskit.exceptions import QiskitError from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.quantumregister import QuantumRegister, Qubit from qiskit.circuit.gate import Gate from qiskit.circuit.library.standard_gates.x import CXGate, XGate from qiskit.circuit.library.standard_gates.h import HGate from qiskit.circuit.library.standard_gates.s import SGate, SdgGate from qiskit.circuit.library.standard_gates.ry import RYGate from qiskit.circuit.library.standard_gates.rz import RZGate from qiskit.circuit.exceptions import CircuitError from qiskit.quantum_info.states.statevector import ( Statevector, ) # pylint: disable=cyclic-import _EPS = 1e-10 # global variable used to chop very small numbers to zero class StatePreparation(Gate): """Complex amplitude state preparation. Class that implements the (complex amplitude) state preparation of some flexible collection of qubit registers. """ def __init__( self, params: Union[str, list, int, Statevector], num_qubits: Optional[int] = None, inverse: bool = False, label: Optional[str] = None, normalize: bool = False, goalBitString: int = 0 ): r""" Args: params: * Statevector: Statevector to initialize to. * list: vector of complex amplitudes to initialize to. * string: labels of basis states of the Pauli eigenstates Z, X, Y. See :meth:`.Statevector.from_label`. Notice the order of the labels is reversed with respect to the qubit index to be applied to. Example label '01' initializes the qubit zero to :math:`|1\rangle` and the qubit one to :math:`|0\rangle`. * int: an integer that is used as a bitmap indicating which qubits to initialize to :math:`|1\rangle`. Example: setting params to 5 would initialize qubit 0 and qubit 2 to :math:`|1\rangle` and qubit 1 to :math:`|0\rangle`. num_qubits: This parameter is only used if params is an int. Indicates the total number of qubits in the `initialize` call. Example: `initialize` covers 5 qubits and params is 3. This allows qubits 0 and 1 to be initialized to :math:`|1\rangle` and the remaining 3 qubits to be initialized to :math:`|0\rangle`. inverse: if True, the inverse state is constructed. label: An optional label for the gate normalize (bool): Whether to normalize an input array to a unit vector. Raises: QiskitError: ``num_qubits`` parameter used when ``params`` is not an integer When a Statevector argument is passed the state is prepared using a recursive initialization algorithm, including optimizations, from [1], as well as some additional optimizations including removing zero rotations and double cnots. **References:** [1] Shende, Bullock, Markov. Synthesis of Quantum Logic Circuits (2004) [`https://arxiv.org/abs/quant-ph/0406176v5`] """ self._params_arg = params self._inverse = inverse self._name = "state_preparation_dg" if self._inverse else "state_preparation" self.goalBitString = goalBitString if label is None: self._label = ( "State Preparation Dg" if self._inverse else "State Preparation" ) else: self._label = f"{label} Dg" if self._inverse else label if isinstance(params, Statevector): params = params.data if not isinstance(params, int) and num_qubits is not None: raise QiskitError( "The num_qubits parameter to StatePreparation should only be" " used when params is an integer" ) self._from_label = isinstance(params, str) self._from_int = isinstance(params, int) # if initialized from a vector, check that the parameters are normalized if not self._from_label and not self._from_int: norm = np.linalg.norm(params) if normalize: params = np.array(params, dtype=np.complex128) / norm elif not math.isclose(norm, 1.0, abs_tol=_EPS): raise QiskitError(f"Sum of amplitudes-squared is not 1, but {norm}.") num_qubits = self._get_num_qubits(num_qubits, params) params = [params] if isinstance(params, int) else params super().__init__(self._name, num_qubits, params, label=self._label) def _define(self): if self._from_label: self.definition = self._define_from_label() elif self._from_int: self.definition = self._define_from_int() else: self.definition = self._define_synthesis() def _define_from_label(self): q = QuantumRegister(self.num_qubits, "q") initialize_circuit = QuantumCircuit(q, name="init_def") for qubit, param in enumerate(reversed(self.params)): if param == "1": initialize_circuit.append(XGate(), [q[qubit]]) elif param == "+": initialize_circuit.append(HGate(), [q[qubit]]) elif param == "-": initialize_circuit.append(XGate(), [q[qubit]]) initialize_circuit.append(HGate(), [q[qubit]]) elif param == "r": # |+i> initialize_circuit.append(HGate(), [q[qubit]]) initialize_circuit.append(SGate(), [q[qubit]]) elif param == "l": # |-i> initialize_circuit.append(HGate(), [q[qubit]]) initialize_circuit.append(SdgGate(), [q[qubit]]) if self._inverse: initialize_circuit = initialize_circuit.inverse() return initialize_circuit def _define_from_int(self): q = QuantumRegister(self.num_qubits, "q") initialize_circuit = QuantumCircuit(q, name="init_def") # Convert to int since QuantumCircuit converted to complex # and make a bit string and reverse it intstr = f"{int(np.real(self.params[0])):0{self.num_qubits}b}"[::-1] # Raise if number of bits is greater than num_qubits if len(intstr) > self.num_qubits: raise QiskitError( "StatePreparation integer has %s bits, but this exceeds the" " number of qubits in the circuit, %s." % (len(intstr), self.num_qubits) ) for qubit, bit in enumerate(intstr): if bit == "1": initialize_circuit.append(XGate(), [q[qubit]]) # note: X is it's own inverse, so even if self._inverse is True, # we don't need to invert anything return initialize_circuit def _define_synthesis(self): """Calculate a subcircuit that implements this initialization Implements a recursive initialization algorithm, including optimizations, from "Synthesis of Quantum Logic Circuits" Shende, Bullock, Markov https://arxiv.org/abs/quant-ph/0406176v5 Additionally implements some extra optimizations: remove zero rotations and double cnots. """ # call to generate the circuit that takes the desired vector to zero disentangling_circuit = self._gates_to_uncompute() # invert the circuit to create the desired vector from zero (assuming # the qubits are in the zero state) if self._inverse is False: initialize_instr = disentangling_circuit.to_instruction().inverse() else: initialize_instr = disentangling_circuit.to_instruction() q = QuantumRegister(self.num_qubits, "q") initialize_circuit = QuantumCircuit(q, name="init_def") initialize_circuit.append(initialize_instr, q[:]) return initialize_circuit def _get_num_qubits(self, num_qubits, params): """Get number of qubits needed for state preparation""" if isinstance(params, str): num_qubits = len(params) elif isinstance(params, int): if num_qubits is None: num_qubits = int(math.log2(params)) + 1 else: num_qubits = math.log2(len(params)) # Check if param is a power of 2 if num_qubits == 0 or not num_qubits.is_integer(): raise QiskitError( "Desired statevector length not a positive power of 2." ) num_qubits = int(num_qubits) return num_qubits def inverse(self): """Return inverted StatePreparation""" label = ( None if self._label in ("State Preparation", "State Preparation Dg") else self._label ) return StatePreparation( self._params_arg, inverse=not self._inverse, label=label ) def broadcast_arguments(self, qargs, cargs): flat_qargs = [qarg for sublist in qargs for qarg in sublist] if self.num_qubits != len(flat_qargs): raise QiskitError( "StatePreparation parameter vector has %d elements, therefore expects %s " "qubits. However, %s were provided." % (2**self.num_qubits, self.num_qubits, len(flat_qargs)) ) yield flat_qargs, [] def validate_parameter(self, parameter): """StatePreparation instruction parameter can be str, int, float, and complex.""" # StatePreparation instruction parameter can be str if isinstance(parameter, str): if parameter in ["0", "1", "+", "-", "l", "r"]: return parameter raise CircuitError( "invalid param label {} for instruction {}. Label should be " "0, 1, +, -, l, or r ".format(type(parameter), self.name) ) # StatePreparation instruction parameter can be int, float, and complex. if isinstance(parameter, (int, float, complex)): return complex(parameter) elif isinstance(parameter, np.number): return complex(parameter.item()) else: raise CircuitError( f"invalid param type {type(parameter)} for instruction {self.name}" ) def _return_repeat(self, exponent: float) -> "Gate": return Gate( name=f"{self.name}*{exponent}", num_qubits=self.num_qubits, params=[] ) def _gates_to_uncompute(self): """Call to create a circuit with gates that take the desired vector to zero. Returns: QuantumCircuit: circuit to take self.params vector to :math:`|{00\\ldots0}\\rangle` """ q = QuantumRegister(self.num_qubits) circuit = QuantumCircuit(q, name="disentangler") # kick start the peeling loop, and disentangle one-by-one from LSB to MSB remaining_param = self.params for i in range(self.num_qubits): bitValue = (self.goalBitString // (2**i)) % 2 # work out which rotations must be done to disentangle the LSB # qubit (we peel away one qubit at a time) ( remaining_param, thetas, phis, ) = StatePreparation._rotations_to_disentangle(remaining_param, bitValue=bitValue) # perform the required rotations to decouple the LSB qubit (so that # it can be "factored" out, leaving a shorter amplitude vector to peel away) add_last_cnot = True if np.linalg.norm(phis) != 0 and np.linalg.norm(thetas) != 0: add_last_cnot = False if np.linalg.norm(phis) != 0: rz_mult = self._multiplex(RZGate, phis, last_cnot=add_last_cnot) circuit.append(rz_mult.to_instruction(), q[i : self.num_qubits]) if np.linalg.norm(thetas) != 0: ry_mult = self._multiplex(RYGate, thetas, last_cnot=add_last_cnot) circuit.append( ry_mult.to_instruction().reverse_ops(), q[i : self.num_qubits] ) circuit.global_phase -= np.angle(sum(remaining_param)) return circuit @staticmethod def _rotations_to_disentangle(local_param, bitValue): """ Static internal method to work out Ry and Rz rotation angles used to disentangle the LSB qubit. These rotations make up the block diagonal matrix U (i.e. multiplexor) that disentangles the LSB. [[Ry(theta_1).Rz(phi_1) 0 . . 0], [0 Ry(theta_2).Rz(phi_2) . 0], . . 0 0 Ry(theta_2^n).Rz(phi_2^n)]] """ remaining_vector = [] thetas = [] phis = [] param_len = len(local_param) for i in range(param_len // 2): # Ry and Rz rotations to move bloch vector from 0 to "imaginary" # qubit # (imagine a qubit state signified by the amplitudes at index 2*i # and 2*(i+1), corresponding to the select qubits of the # multiplexor being in state |i>) (remains, add_theta, add_phi) = StatePreparation._bloch_angles( local_param[2 * i : 2 * (i + 1)], bitValue=bitValue ) remaining_vector.append(remains) # rotations for all imaginary qubits of the full vector # to move from where it is to zero, hence the negative sign thetas.append(-add_theta) phis.append(-add_phi) return remaining_vector, thetas, phis @staticmethod def _bloch_angles(pair_of_complex, bitValue = 0): """ Static internal method to work out rotation to create the passed-in qubit from the zero vector. """ [a_complex, b_complex] = pair_of_complex # Force a and b to be complex, as otherwise numpy.angle might fail. a_complex = complex(a_complex) b_complex = complex(b_complex) mag_a = abs(a_complex) final_r = np.sqrt(mag_a**2 + np.absolute(b_complex) ** 2) # print(final_r) if final_r < _EPS: theta = 0 phi = 0 final_r = 0 final_t = 0 else: theta = bitValue * np.pi + 2 * np.arccos(mag_a / final_r) a_arg = np.angle(a_complex) b_arg = np.angle(b_complex) final_t = a_arg + b_arg phi = b_arg - a_arg # print(phi) # if phi >= np.pi: # theta = 2 * np.pi - theta # if phi <= -np.pi: # theta = 0 * np.pi - theta # print(pair_of_complex, a_arg, b_arg, theta) return final_r * np.exp(1.0j * final_t / 2), theta, phi def _multiplex(self, target_gate, list_of_angles, last_cnot=True, bitValue=0): """ Return a recursive implementation of a multiplexor circuit, where each instruction itself has a decomposition based on smaller multiplexors. The LSB is the multiplexor "data" and the other bits are multiplexor "select". Args: target_gate (Gate): Ry or Rz gate to apply to target qubit, multiplexed over all other "select" qubits list_of_angles (list[float]): list of rotation angles to apply Ry and Rz last_cnot (bool): add the last cnot if last_cnot = True Returns: DAGCircuit: the circuit implementing the multiplexor's action """ list_len = len(list_of_angles) local_num_qubits = int(math.log2(list_len)) + 1 q = QuantumRegister(local_num_qubits) circuit = QuantumCircuit(q, name="multiplex" + str(local_num_qubits)) lsb = q[0] msb = q[local_num_qubits - 1] # case of no multiplexing: base case for recursion if local_num_qubits == 1: circuit.append(target_gate(list_of_angles[0]), [q[0]]) return circuit # calc angle weights, assuming recursion (that is the lower-level # requested angles have been correctly implemented by recursion angle_weight = np.kron( [[0.5, 0.5], [0.5, -0.5]], np.identity(2 ** (local_num_qubits - 2)) ) # calc the combo angles list_of_angles = angle_weight.dot(np.array(list_of_angles)).tolist() # recursive step on half the angles fulfilling the above assumption multiplex_1 = self._multiplex( target_gate, list_of_angles[0 : (list_len // 2)], False ) circuit.append(multiplex_1.to_instruction(), q[0:-1]) # attach CNOT as follows, thereby flipping the LSB qubit circuit.append(CXGate(), [msb, lsb]) # implement extra efficiency from the paper of cancelling adjacent # CNOTs (by leaving out last CNOT and reversing (NOT inverting) the # second lower-level multiplex) multiplex_2 = self._multiplex( target_gate, list_of_angles[(list_len // 2) :], False ) if list_len > 1: circuit.append(multiplex_2.to_instruction().reverse_ops(), q[0:-1]) else: circuit.append(multiplex_2.to_instruction(), q[0:-1]) # attach a final CNOT if last_cnot: circuit.append(CXGate(), [msb, lsb]) return circuit def prepare_state(self, state, qubits=None, label=None, normalize=False): r"""Prepare qubits in a specific state. This class implements a state preparing unitary. Unlike :class:`qiskit.extensions.Initialize` it does not reset the qubits first. Args: state (str or list or int or Statevector): * Statevector: Statevector to initialize to. * str: labels of basis states of the Pauli eigenstates Z, X, Y. See :meth:`.Statevector.from_label`. Notice the order of the labels is reversed with respect to the qubit index to be applied to. Example label '01' initializes the qubit zero to :math:`|1\rangle` and the qubit one to :math:`|0\rangle`. * list: vector of complex amplitudes to initialize to. * int: an integer that is used as a bitmap indicating which qubits to initialize to :math:`|1\rangle`. Example: setting params to 5 would initialize qubit 0 and qubit 2 to :math:`|1\rangle` and qubit 1 to :math:`|0\rangle`. qubits (QuantumRegister or Qubit or int): * QuantumRegister: A list of qubits to be initialized [Default: None]. * Qubit: Single qubit to be initialized [Default: None]. * int: Index of qubit to be initialized [Default: None]. * list: Indexes of qubits to be initialized [Default: None]. label (str): An optional label for the gate normalize (bool): Whether to normalize an input array to a unit vector. Returns: qiskit.circuit.Instruction: a handle to the instruction that was just initialized Examples: Prepare a qubit in the state :math:`(|0\rangle - |1\rangle) / \sqrt{2}`. .. code-block:: import numpy as np from qiskit import QuantumCircuit circuit = QuantumCircuit(1) circuit.prepare_state([1/np.sqrt(2), -1/np.sqrt(2)], 0) circuit.draw() output: .. parsed-literal:: ┌─────────────────────────────────────┐ q_0: ┤ State Preparation(0.70711,-0.70711) ├ └─────────────────────────────────────┘ Prepare from a string two qubits in the state :math:`|10\rangle`. The order of the labels is reversed with respect to qubit index. More information about labels for basis states are in :meth:`.Statevector.from_label`. .. code-block:: import numpy as np from qiskit import QuantumCircuit circuit = QuantumCircuit(2) circuit.prepare_state('01', circuit.qubits) circuit.draw() output: .. parsed-literal:: ┌─────────────────────────┐ q_0: ┤0 ├ │ State Preparation(0,1) │ q_1: ┤1 ├ └─────────────────────────┘ Initialize two qubits from an array of complex amplitudes .. code-block:: import numpy as np from qiskit import QuantumCircuit circuit = QuantumCircuit(2) circuit.prepare_state([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], circuit.qubits) circuit.draw() output: .. parsed-literal:: ┌───────────────────────────────────────────┐ q_0: ┤0 ├ │ State Preparation(0,0.70711,-0.70711j,0) │ q_1: ┤1 ├ └───────────────────────────────────────────┘ """ if qubits is None: qubits = self.qubits elif isinstance(qubits, (int, np.integer, slice, Qubit)): qubits = [qubits] num_qubits = len(qubits) if isinstance(state, int) else None return self.append( StatePreparation(state, num_qubits, label=label, normalize=normalize), qubits ) QuantumCircuit.prepare_state = prepare_state
https://github.com/abbarreto/qiskit3
abbarreto
%run init.ipynb from qiskit import * nshots = 8192 IBMQ.load_account() provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main') device = provider.get_backend('ibmq_bogota') simulator = Aer.get_backend('qasm_simulator') from qiskit.visualization import plot_histogram from qiskit.tools.monitor import job_monitor from qiskit.quantum_info import state_fidelity
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the Unroll3qOrMore pass""" import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Qubit, Clbit from qiskit.circuit.library import CCXGate, RCCXGate from qiskit.transpiler.passes import Unroll3qOrMore from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.quantum_info.operators import Operator from qiskit.quantum_info.random import random_unitary from qiskit.test import QiskitTestCase from qiskit.extensions import UnitaryGate from qiskit.transpiler import Target class TestUnroll3qOrMore(QiskitTestCase): """Tests the Unroll3qOrMore pass, for unrolling all gates until reaching only 1q or 2q gates.""" def test_ccx(self): """Test decompose CCX.""" qr1 = QuantumRegister(2, "qr1") qr2 = QuantumRegister(1, "qr2") circuit = QuantumCircuit(qr1, qr2) circuit.ccx(qr1[0], qr1[1], qr2[0]) dag = circuit_to_dag(circuit) pass_ = Unroll3qOrMore() after_dag = pass_.run(dag) op_nodes = after_dag.op_nodes() self.assertEqual(len(op_nodes), 15) for node in op_nodes: self.assertIn(node.name, ["h", "t", "tdg", "cx"]) def test_cswap(self): """Test decompose CSwap (recursively).""" qr1 = QuantumRegister(2, "qr1") qr2 = QuantumRegister(1, "qr2") circuit = QuantumCircuit(qr1, qr2) circuit.cswap(qr1[0], qr1[1], qr2[0]) dag = circuit_to_dag(circuit) pass_ = Unroll3qOrMore() after_dag = pass_.run(dag) op_nodes = after_dag.op_nodes() self.assertEqual(len(op_nodes), 17) for node in op_nodes: self.assertIn(node.name, ["h", "t", "tdg", "cx"]) def test_decompose_conditional(self): """Test decompose a 3-qubit gate with a conditional.""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 0) dag = circuit_to_dag(circuit) pass_ = Unroll3qOrMore() after_dag = pass_.run(dag) op_nodes = after_dag.op_nodes() self.assertEqual(len(op_nodes), 15) for node in op_nodes: self.assertIn(node.name, ["h", "t", "tdg", "cx"]) self.assertEqual(node.op.condition, (cr, 0)) def test_decompose_unitary(self): """Test unrolling of unitary gate over 4qubits.""" qr = QuantumRegister(4, "qr") circuit = QuantumCircuit(qr) unitary = random_unitary(16, seed=42) circuit.unitary(unitary, [0, 1, 2, 3]) dag = circuit_to_dag(circuit) pass_ = Unroll3qOrMore() after_dag = pass_.run(dag) after_circ = dag_to_circuit(after_dag) self.assertTrue(Operator(circuit).equiv(Operator(after_circ))) def test_identity(self): """Test unrolling of identity gate over 3qubits.""" qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) gate = UnitaryGate(np.eye(2**3)) circuit.append(gate, range(3)) dag = circuit_to_dag(circuit) pass_ = Unroll3qOrMore() after_dag = pass_.run(dag) after_circ = dag_to_circuit(after_dag) self.assertTrue(Operator(circuit).equiv(Operator(after_circ))) def test_target(self): """Test target is respected by the unroll 3q or more pass.""" target = Target(num_qubits=3) target.add_instruction(CCXGate()) qc = QuantumCircuit(3) qc.ccx(0, 1, 2) qc.append(RCCXGate(), [0, 1, 2]) unroll_pass = Unroll3qOrMore(target=target) res = unroll_pass(qc) self.assertIn("ccx", res.count_ops()) self.assertNotIn("rccx", res.count_ops()) def test_basis_gates(self): """Test basis_gates are respected by the unroll 3q or more pass.""" basis_gates = ["rccx"] qc = QuantumCircuit(3) qc.ccx(0, 1, 2) qc.append(RCCXGate(), [0, 1, 2]) unroll_pass = Unroll3qOrMore(basis_gates=basis_gates) res = unroll_pass(qc) self.assertNotIn("ccx", res.count_ops()) self.assertIn("rccx", res.count_ops()) def test_target_over_basis_gates(self): """Test target is respected over basis_gates by the unroll 3q or more pass.""" target = Target(num_qubits=3) basis_gates = ["rccx"] target.add_instruction(CCXGate()) qc = QuantumCircuit(3) qc.ccx(0, 1, 2) qc.append(RCCXGate(), [0, 1, 2]) unroll_pass = Unroll3qOrMore(target=target, basis_gates=basis_gates) res = unroll_pass(qc) self.assertIn("ccx", res.count_ops()) self.assertNotIn("rccx", res.count_ops()) def test_if_else(self): """Test that a simple if-else over 3+ qubits unrolls correctly.""" pass_ = Unroll3qOrMore(basis_gates=["u", "cx"]) true_body = QuantumCircuit(3, 1) true_body.h(0) true_body.ccx(0, 1, 2) false_body = QuantumCircuit(3, 1) false_body.rccx(2, 1, 0) test = QuantumCircuit(3, 1) test.h(0) test.measure(0, 0) test.if_else((0, True), true_body, false_body, [0, 1, 2], [0]) expected = QuantumCircuit(3, 1) expected.h(0) expected.measure(0, 0) expected.if_else((0, True), pass_(true_body), pass_(false_body), [0, 1, 2], [0]) self.assertEqual(pass_(test), expected) def test_nested_control_flow(self): """Test that the unroller recurses into nested control flow.""" pass_ = Unroll3qOrMore(basis_gates=["u", "cx"]) qubits = [Qubit() for _ in [None] * 3] clbit = Clbit() for_body = QuantumCircuit(qubits, [clbit]) for_body.ccx(0, 1, 2) while_body = QuantumCircuit(qubits, [clbit]) while_body.rccx(0, 1, 2) true_body = QuantumCircuit(qubits, [clbit]) true_body.while_loop((clbit, True), while_body, [0, 1, 2], [0]) test = QuantumCircuit(qubits, [clbit]) test.for_loop(range(2), None, for_body, [0, 1, 2], [0]) test.if_else((clbit, True), true_body, None, [0, 1, 2], [0]) expected_if_body = QuantumCircuit(qubits, [clbit]) expected_if_body.while_loop((clbit, True), pass_(while_body), [0, 1, 2], [0]) expected = QuantumCircuit(qubits, [clbit]) expected.for_loop(range(2), None, pass_(for_body), [0, 1, 2], [0]) expected.if_else(range(2), pass_(expected_if_body), None, [0, 1, 2], [0]) self.assertEqual(pass_(test), expected) def test_if_else_in_basis(self): """Test that a simple if-else over 3+ qubits unrolls correctly.""" pass_ = Unroll3qOrMore(basis_gates=["u", "cx", "if_else", "for_loop", "while_loop"]) true_body = QuantumCircuit(3, 1) true_body.h(0) true_body.ccx(0, 1, 2) false_body = QuantumCircuit(3, 1) false_body.rccx(2, 1, 0) test = QuantumCircuit(3, 1) test.h(0) test.measure(0, 0) test.if_else((0, True), true_body, false_body, [0, 1, 2], [0]) expected = QuantumCircuit(3, 1) expected.h(0) expected.measure(0, 0) expected.if_else((0, True), pass_(true_body), pass_(false_body), [0, 1, 2], [0]) self.assertEqual(pass_(test), expected) def test_nested_control_flow_in_basis(self): """Test that the unroller recurses into nested control flow.""" pass_ = Unroll3qOrMore(basis_gates=["u", "cx", "if_else", "for_loop", "while_loop"]) qubits = [Qubit() for _ in [None] * 3] clbit = Clbit() for_body = QuantumCircuit(qubits, [clbit]) for_body.ccx(0, 1, 2) while_body = QuantumCircuit(qubits, [clbit]) while_body.rccx(0, 1, 2) true_body = QuantumCircuit(qubits, [clbit]) true_body.while_loop((clbit, True), while_body, [0, 1, 2], [0]) test = QuantumCircuit(qubits, [clbit]) test.for_loop(range(2), None, for_body, [0, 1, 2], [0]) test.if_else((clbit, True), true_body, None, [0, 1, 2], [0]) expected_if_body = QuantumCircuit(qubits, [clbit]) expected_if_body.while_loop((clbit, True), pass_(while_body), [0, 1, 2], [0]) expected = QuantumCircuit(qubits, [clbit]) expected.for_loop(range(2), None, pass_(for_body), [0, 1, 2], [0]) expected.if_else(range(2), pass_(expected_if_body), None, [0, 1, 2], [0]) self.assertEqual(pass_(test), expected) def test_custom_block_over_3q(self): """Test a custom instruction is unrolled in a control flow block.""" pass_ = Unroll3qOrMore(basis_gates=["u", "cx", "if_else", "for_loop", "while_loop"]) ghz = QuantumCircuit(5, 5) ghz.h(0) ghz.cx(0, 1) ghz.cx(0, 2) ghz.cx(0, 3) ghz.cx(0, 4) ghz.measure(0, 0) ghz.measure(1, 1) ghz.measure(2, 2) ghz.measure(3, 3) ghz.measure(4, 4) ghz.reset(0) ghz.reset(1) ghz.reset(2) ghz.reset(3) ghz.reset(4) for_block = QuantumCircuit(5, 5, name="ghz") for_block.append(ghz, list(range(5)), list(range(5))) qc = QuantumCircuit(5, 5) qc.for_loop((1,), None, for_block, [2, 4, 1, 3, 0], [0, 1, 2, 3, 4]) result = pass_(qc) expected = QuantumCircuit(5, 5) expected.for_loop((1,), None, ghz, [2, 4, 1, 3, 0], [0, 1, 2, 3, 4]) self.assertEqual(result, expected)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile from qiskit.visualization import plot_circuit_layout from qiskit.providers.fake_provider import FakeVigo backend = FakeVigo() ghz = QuantumCircuit(3, 3) ghz.h(0) ghz.cx(0,range(1,3)) ghz.barrier() ghz.measure(range(3), range(3)) # Virtual -> physical # 0 -> 3 # 1 -> 4 # 2 -> 2 my_ghz = transpile(ghz, backend, initial_layout=[3, 4, 2]) plot_circuit_layout(my_ghz, backend)
https://github.com/qiskit-community/qiskit-scheduling-extension
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the CompactScheduling pass""" from qiskit import QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.transpiler.instruction_durations import InstructionDurations from qiskit.transpiler.passes import PadDelay from qiskit.transpiler.passmanager import PassManager from qiskit_scheduling_extension.compact import CompactScheduleAnalysis class TestCompactScheduling(QiskitTestCase): """Tests the CompactScheduling pass""" def test_compact(self): """Test if Compact scheduling yields expected schedule. (input) ┌───┐ ┌───┐ ░ ┌─┐ q_0: ┤ H ├──■─────────■──┤ H ├─░─┤M├────── └───┘┌─┴─┐ ┌─┴─┐└───┘ ░ └╥┘┌─┐ q_1: ─────┤ X ├──■──┤ X ├──────░──╫─┤M├─── ┌───┐└───┘┌─┴─┐├───┤ ░ ║ └╥┘┌─┐ q_2: ┤ H ├─────┤ X ├┤ H ├──────░──╫──╫─┤M├ └───┘ └───┘└───┘ ░ ║ ║ └╥┘ meas: 3/═════════════════════════════╩══╩══╩═ 0 1 2 (Compact scheduled) ┌───┐ ┌────────────────┐ ┌───┐ ░ ┌─┐ q_0: ──────┤ H ├─────────■──┤ Delay(900[dt]) ├──■────────┤ H ├────────░─┤M├────── ┌─────┴───┴──────┐┌─┴─┐└────────────────┘┌─┴─┐┌─────┴───┴──────┐ ░ └╥┘┌─┐ q_1: ┤ Delay(200[dt]) ├┤ X ├────────■─────────┤ X ├┤ Delay(200[dt]) ├─░──╫─┤M├─── ├────────────────┤├───┤ ┌─┴─┐ ├───┤├────────────────┤ ░ ║ └╥┘┌─┐ q_2: ┤ Delay(700[dt]) ├┤ H ├──────┤ X ├───────┤ H ├┤ Delay(700[dt]) ├─░──╫──╫─┤M├ └────────────────┘└───┘ └───┘ └───┘└────────────────┘ ░ ║ ║ └╥┘ meas: 3/════════════════════════════════════════════════════════════════════╩══╩══╩═ 0 1 2 """ qc = QuantumCircuit(3) qc.h([0, 2]) qc.cx(0, 1) qc.cx(1, 2) qc.cx(0, 1) qc.h([0, 2]) qc.measure_all() durations = InstructionDurations( [("h", None, 200), ("cx", [0, 1], 700), ("cx", [1, 2], 900), ("measure", None, 1000)] ) pm = PassManager([CompactScheduleAnalysis(durations), PadDelay()]) compact_qc = pm.run(qc) expected = QuantumCircuit(3) expected.delay(200, 1) expected.delay(700, 2) expected.h([0, 2]) expected.cx(0, 1) expected.cx(1, 2) expected.delay(900, 0) expected.cx(0, 1) expected.h([0, 2]) expected.delay(200, 1) expected.delay(700, 2) expected.measure_all() self.assertEqual(expected, compact_qc) def test_compact_can_shift_block(self): """Test if Compact scheduling can shift front blocks towards the back and back blocks towards the front. (input) ░ ┌─┐ q_0: ──■─────────────────────────────■─────────────░─┤M├───────── ┌─┴─┐ ┌─┴─┐ ░ └╥┘┌─┐ q_1: ┤ X ├────────────■─────────■──┤ X ├───────────░──╫─┤M├────── └───┘ ┌───┐┌─┴─┐ ┌─┴─┐├───┤ ░ ║ └╥┘┌─┐ q_2: ───────■──┤ H ├┤ X ├──■──┤ X ├┤ H ├──■────────░──╫──╫─┤M├─── ┌───┐┌─┴─┐├───┤└───┘┌─┴─┐├───┤└───┘┌─┴─┐┌───┐ ░ ║ ║ └╥┘┌─┐ q_3: ┤ H ├┤ X ├┤ H ├─────┤ X ├┤ H ├─────┤ X ├┤ H ├─░──╫──╫──╫─┤M├ └───┘└───┘└───┘ └───┘└───┘ └───┘└───┘ ░ ║ ║ ║ └╥┘ meas: 4/═════════════════════════════════════════════════╩══╩══╩══╩═ 0 1 2 3 (Compact scheduled) ┌─────────────────┐ » q_0: ────────■─────────┤ Delay(1000[dt]) ├────────────────────────────» ┌─┴─┐ └─────────────────┘ » q_1: ──────┤ X ├────────────────────────────────────────────■─────────» ┌─────┴───┴──────┐ ┌───┐ ┌─┴─┐ » q_2: ┤ Delay(750[dt]) ├─────────────────────■──┤ H ├──────┤ X ├───────» ├────────────────┤ ┌───┐ ┌─┴─┐├───┤┌─────┴───┴──────┐» q_3: ┤ Delay(700[dt]) ├───────┤ H ├───────┤ X ├┤ H ├┤ Delay(400[dt]) ├» └────────────────┘ └───┘ └───┘└───┘└────────────────┘» meas: 4/═════════════════════════════════════════════════════════════════» » « » « q_0: ───────────────────────────────■────────────────────────────────» « ┌────────────────┐ ┌─┴─┐ » « q_1: ┤ Delay(200[dt]) ├──■────────┤ X ├──────────────────────────────» « └────────────────┘┌─┴─┐ ├───┤ ┌────────────────┐» « q_2: ────────■─────────┤ X ├──────┤ H ├─────────■──┤ Delay(750[dt]) ├» « ┌─┴─┐ ├───┤┌─────┴───┴──────┐┌─┴─┐└─────┬───┬──────┘» « q_3: ──────┤ X ├───────┤ H ├┤ Delay(400[dt]) ├┤ X ├──────┤ H ├───────» « └───┘ └───┘└────────────────┘└───┘ └───┘ » «meas: 4/════════════════════════════════════════════════════════════════» « » « ░ ┌─┐ « q_0: ───────────────────░─┤M├───────── « ░ └╥┘┌─┐ « q_1: ───────────────────░──╫─┤M├────── « ░ ║ └╥┘┌─┐ « q_2: ───────────────────░──╫──╫─┤M├─── « ┌────────────────┐ ░ ║ ║ └╥┘┌─┐ « q_3: ┤ Delay(700[dt]) ├─░──╫──╫──╫─┤M├ « └────────────────┘ ░ ║ ║ ║ └╥┘ «meas: 4/══════════════════════╩══╩══╩══╩═ « 0 1 2 3 """ qc = QuantumCircuit(4) qc.cx(0, 1) qc.h(3) qc.cx(2, 3) qc.h([2, 3]) qc.cx(1, 2) qc.cx(2, 3) qc.cx(1, 2) qc.h([2, 3]) qc.cx(2, 3) qc.h(3) qc.cx(0, 1) qc.measure_all() durations = InstructionDurations( [ ("h", None, 50), ("cx", [0, 1], 1000), ("cx", [1, 2], 400), ("cx", [2, 3], 200), ("measure", None, 1000), ] ) pm = PassManager([CompactScheduleAnalysis(durations), PadDelay()]) compact_qc = pm.run(qc) expected = QuantumCircuit(4) expected.delay(750, 2) expected.delay(700, 3) expected.cx(0, 1) expected.h(3) expected.cx(2, 3) expected.h([2, 3]) expected.delay(400, 3) expected.cx(1, 2) expected.delay(1000, 0) expected.delay(200, 1) expected.cx(2, 3) expected.cx(1, 2) expected.h([2, 3]) expected.delay(400, 3) expected.cx(2, 3) expected.h(3) expected.cx(0, 1) expected.delay(750, 2) expected.delay(700, 3) expected.measure_all() self.assertEqual(expected, compact_qc)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, transpile, schedule from qiskit.visualization.timeline import draw, IQXSimple 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=IQXSimple())
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit, execute from qiskit import Aer import numpy as np import sys N=int(sys.argv[1]) filename = sys.argv[2] backend = Aer.get_backend('unitary_simulator') def GHZ(n): if n<=0: return None circ = QuantumCircuit(n) # Put your code below # ---------------------------- circ.h(0) for x in range(1,n): circ.cx(x-1,x) # ---------------------------- return circ circuit = GHZ(N) job = execute(circuit, backend, shots=8192) result = job.result() array = result.get_unitary(circuit,3) np.savetxt(filename, array, delimiter=",", fmt = "%0.3f")
https://github.com/abbarreto/qiskit2
abbarreto
%run init.ipynb
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from math import pi import numpy as np import rustworkx as rx from qiskit_nature.second_q.hamiltonians.lattices import ( BoundaryCondition, HyperCubicLattice, Lattice, LatticeDrawStyle, LineLattice, SquareLattice, TriangularLattice, ) from qiskit_nature.second_q.hamiltonians import FermiHubbardModel num_nodes = 11 boundary_condition = BoundaryCondition.OPEN line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition) line_lattice.draw() num_nodes = 11 boundary_condition = BoundaryCondition.PERIODIC line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition) line_lattice.draw() line_lattice.draw_without_boundary() num_nodes = 11 boundary_condition = BoundaryCondition.PERIODIC edge_parameter = 1.0 + 1.0j onsite_parameter = 1.0 line_lattice = LineLattice( num_nodes=num_nodes, edge_parameter=edge_parameter, onsite_parameter=onsite_parameter, boundary_condition=boundary_condition, ) set(line_lattice.graph.weighted_edge_list()) line_lattice.to_adjacency_matrix() line_lattice.to_adjacency_matrix(weighted=True) rows = 5 cols = 4 boundary_condition = BoundaryCondition.OPEN square_lattice = SquareLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) square_lattice.draw() rows = 5 cols = 4 boundary_condition = ( BoundaryCondition.OPEN, BoundaryCondition.PERIODIC, ) # open in the x-direction, periodic in the y-direction square_lattice = SquareLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) square_lattice.draw() rows = 5 cols = 4 edge_parameter = (1.0, 1.0 + 1.0j) boundary_condition = ( BoundaryCondition.OPEN, BoundaryCondition.PERIODIC, ) # open in the x-direction, periodic in the y-direction onsite_parameter = 1.0 square_lattice = SquareLattice( rows=rows, cols=cols, edge_parameter=edge_parameter, onsite_parameter=onsite_parameter, boundary_condition=boundary_condition, ) set(square_lattice.graph.weighted_edge_list()) size = (3, 4, 5) boundary_condition = ( BoundaryCondition.OPEN, BoundaryCondition.OPEN, BoundaryCondition.OPEN, ) cubic_lattice = HyperCubicLattice(size=size, boundary_condition=boundary_condition) # function for setting the positions def indextocoord_3d(index: int, size: tuple, angle) -> list: z = index // (size[0] * size[1]) a = index % (size[0] * size[1]) y = a // size[0] x = a % size[0] vec_x = np.array([1, 0]) vec_y = np.array([np.cos(angle), np.sin(angle)]) vec_z = np.array([0, 1]) return_coord = x * vec_x + y * vec_y + z * vec_z return return_coord.tolist() pos = dict([(index, indextocoord_3d(index, size, angle=pi / 4)) for index in range(np.prod(size))]) cubic_lattice.draw(style=LatticeDrawStyle(pos=pos)) rows = 4 cols = 3 boundary_condition = BoundaryCondition.OPEN triangular_lattice = TriangularLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) triangular_lattice.draw() rows = 4 cols = 3 boundary_condition = BoundaryCondition.PERIODIC triangular_lattice = TriangularLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) triangular_lattice.draw() graph = rx.PyGraph(multigraph=False) # multigraph shoud be False graph.add_nodes_from(range(6)) weighted_edge_list = [ (0, 1, 1.0 + 1.0j), (0, 2, -1.0), (2, 3, 2.0), (4, 2, -1.0 + 2.0j), (4, 4, 3.0), (2, 5, -1.0), ] graph.add_edges_from(weighted_edge_list) # make a lattice general_lattice = Lattice(graph) set(general_lattice.graph.weighted_edge_list()) general_lattice.draw() general_lattice.draw(self_loop=True) general_lattice.draw(self_loop=True, style=LatticeDrawStyle(with_labels=True)) square_lattice = SquareLattice(rows=5, cols=4, boundary_condition=BoundaryCondition.PERIODIC) t = -1.0 # the interaction parameter v = 0.0 # the onsite potential u = 5.0 # the interaction parameter U fhm = FermiHubbardModel( square_lattice.uniform_parameters( uniform_interaction=t, uniform_onsite_potential=v, ), onsite_interaction=u, ) ham = fhm.second_q_op().simplify() print(ham) graph = rx.PyGraph(multigraph=False) # multiigraph shoud be False graph.add_nodes_from(range(6)) weighted_edge_list = [ (0, 1, 1.0 + 1.0j), (0, 2, -1.0), (2, 3, 2.0), (4, 2, -1.0 + 2.0j), (4, 4, 3.0), (2, 5, -1.0), ] graph.add_edges_from(weighted_edge_list) general_lattice = Lattice(graph) # the lattice whose weights are seen as the interaction matrix. u = 5.0 # the interaction parameter U fhm = FermiHubbardModel(lattice=general_lattice, onsite_interaction=u) ham = fhm.second_q_op().simplify() print(ham) from qiskit_nature.second_q.problems import LatticeModelProblem num_nodes = 4 boundary_condition = BoundaryCondition.OPEN line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition) fhm = FermiHubbardModel( line_lattice.uniform_parameters( uniform_interaction=t, uniform_onsite_potential=v, ), onsite_interaction=u, ) lmp = LatticeModelProblem(fhm) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms import GroundStateEigensolver from qiskit_nature.second_q.mappers import JordanWignerMapper numpy_solver = NumPyMinimumEigensolver() qubit_mapper = JordanWignerMapper() calc = GroundStateEigensolver(qubit_mapper, numpy_solver) res = calc.solve(lmp) print(res) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
import sys, os sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/../../') from composer.qs_circuit import QSCircuit from qiskit import execute, BasicAer print('AND') for i in range(2 ** 5): a = format(i, '05b')[::-1] SIZE_REG = len(a) a_indexes = list(range(0, SIZE_REG)) result_index = SIZE_REG aux_index = SIZE_REG + 1 CIRCUIT_SIZE = len(a_indexes) + 2 qc = QSCircuit(CIRCUIT_SIZE) qc.set_reg(a, a_indexes) qc.and_list(a_indexes, result_index, aux_index) qc.measure(result_index, 0) backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1) counts = job.result().get_counts(qc) print(i, '-', list(counts.keys())[0][-1]) print('\nOR') for i in range(2 ** 5): a = format(i, '05b')[::-1] SIZE_REG = len(a) a_indexes = list(range(0, SIZE_REG)) result_index = SIZE_REG aux_index = SIZE_REG + 1 CIRCUIT_SIZE = len(a_indexes) + 2 qc = QSCircuit(CIRCUIT_SIZE) qc.set_reg(a, a_indexes) qc.or_list(a_indexes, result_index, aux_index) qc.measure(result_index, 0) backend = BasicAer.get_backend('qasm_simulator') job = execute(qc, backend, shots=1) counts = job.result().get_counts(qc) print(i, '-', list(counts.keys())[0][-1])
https://github.com/kevinab107/QiskitPulseRL
kevinab107
from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import numpy as np import math from qiskit.quantum_info import state_fidelity from qiskit.pulse import DriveChannel from qiskit.compiler import assemble from qiskit.qobj.utils import MeasLevel, MeasReturnType # The pulse simulator from qiskit.providers.aer import PulseSimulator from qiskit import pulse # Object for representing physical models from qiskit.providers.aer.pulse import PulseSystemModel # Mock Armonk backend from qiskit.test.mock.backends.armonk.fake_armonk import FakeArmonk import tensorflow as tf from tf_agents.environments import py_environment from tf_agents.environments import tf_environment from tf_agents.environments import tf_py_environment from tf_agents.environments import utils from tf_agents.specs import array_spec from tf_agents.environments import wrappers from tf_agents.environments import suite_gym from tf_agents.trajectories import time_step as ts from tf_agents.environments import validate_py_environment class QiskitEnv(py_environment.PyEnvironment): """Environment which make use of Qiskit Pulse Simulator and pulse builder to simulate the dynamics of a qubit under the influence of a pulse. The RL agent interact with this environment through action defined as pulse length. Here a constant pulse of amplitude 1 is used and applied for a time "pulse width". "pulse width" is the action that the agent takes here. The agent observes the state obtained with the action along with the Fidelity to the expected final state""" def __init__(self, initial_state, max_time_steps, interval_width): # action spec which is the shape of the action. Here it is (1,) ie the pulse length self._action_spec = array_spec.BoundedArraySpec( shape=(1,), dtype=np.float32, minimum=0, maximum=1, name="action" ) # Observation spec which is the shape of the observation. It is of the form [real part of |0>, imag part of |0>, real part of |1>, imag part of |1>] self._observation_spec = array_spec.BoundedArraySpec( shape=(4,), dtype=np.float32, minimum=0, maximum=1, name="observation" ) self._state = np.array([1, 0]) # | 0 > self._episode_ended = False # Closeness to the final state defined for this program as [0,1] self.fidelity = 0 # Time stamp self.time_stamp = 0 self.max_fidelity = 0 # initial state is [1,0] self.initial_state = initial_state # Maximum time steps self.max_stamp = max_time_steps self.interval_width = interval_width self.actions_list = [] def action_spec(self): return self._action_spec def observation_spec(self): return self._observation_spec def render(self): return self.fidelity def _reset(self): """ reset the state. tensorflow provides the state restart() """ self._episode_ended = False self.fidelity = 0 self.time_stamp = 0 self.max_fidelity = 0 self.actions_list = [] # self.gamma = [random.uniform(0, 1), random.uniform(0, 1)] return ts.restart(np.array([0, 0, 1, 0], dtype=np.float32)) def _step(self, action): """ Result of interaction by agent with the environment. action is the pulse length Returns one of the tensorflow state which has the observation and reward information corresponding to the action - termination (If the interaction has stopped due to max timesteps) - transition (Transition from one state to another) """ # Set episode ended to True if max time steps has exceeded # Terminate with reset in that case self.time_stamp += 1 if self.time_stamp > self.max_stamp: self._episode_ended = True else: self._episode_ended = False if self._episode_ended: self.max_fidelity = 0 self.actions_list = [] return ts.termination(np.array([0, 0, 1, 0], dtype=np.float32), 0) # Get the new state and fidelity new_fidelity, state = self.get_transition_fidelity(action) # reward = 2*new_fidelity - self.fidelity - self.max_fidelity # reward = reward if reward > 0 else 0 # reward = new_fidelity reward = new_fidelity self.fidelity = new_fidelity self.max_fidelity = ( new_fidelity if new_fidelity > self.max_fidelity else self.max_fidelity ) observation = [state[0].real, state[0].imag, state[1].real, state[1].imag] # Set the rewards and state. Reward is only for the final state (of last time interval) achieved and not for the intermediate # states. ies if its a transition from final state and the process has not terminated, then reward is zero. # The neural network will learn to adjust the amplitudes by just looking at the final time step reward if self.time_stamp == self.max_stamp: self.max_fidelity = 0 self.fidelity = 0 # self.gamma = [random.uniform(0, 1), random.uniform(0, 1)] return ts.termination( np.array(observation, dtype=np.float32), reward=reward ) else: return ts.transition( np.array(observation, dtype=np.float32), reward=reward / 10 ) def get_transition_fidelity(self, amplitude): """ Build the pulse based on the action and invoke a IBM Q backend and run the experiment.Simulator is used here. 1. Divide the pulse schedule into discrete intervals of constant length. (Piecewise Constants) 2. Build a pulse schedule with qiskit pulse with amplitude for each interval of the pulse as an input. The schedule is then a function of amplitude of the pulse, followed by a measurement at the end of the drive. 3. At each time step all the all the pulse amplitudes derived till the time step is used. This is contained in the actions_list. actions_list is reset after a single episode """ armonk_backend = FakeArmonk() freq_est = 4.97e9 drive_est = 6.35e7 armonk_backend.defaults().qubit_freq_est = [freq_est] # Define the hamiltonian to avoid randomness armonk_backend.configuration().hamiltonian["h_str"] = [ "wq0*0.5*(I0-Z0)", "omegad0*X0||D0", ] armonk_backend.configuration().hamiltonian["vars"] = { "wq0": 2 * np.pi * freq_est, "omegad0": drive_est, } armonk_backend.configuration().hamiltonian["qub"] = {"0": 2} armonk_backend.configuration().dt = 2.2222222222222221e-10 armonk_model = PulseSystemModel.from_backend(armonk_backend) self.actions_list += [amplitude] # build the pulse with pulse.build( name="pulse_programming_in", backend=armonk_backend ) as pulse_prog: dc = pulse.DriveChannel(0) ac = pulse.acquire_channel(0) for action in self.actions_list: pulse.play([action] * self.interval_width, dc) pulse.delay(self.interval_width * len(self.actions_list) + 10, ac) mem_slot = pulse.measure(0) # Simulate the pulse backend_sim = PulseSimulator(system_model=armonk_model) qobj = assemble(pulse_prog, backend=backend_sim, meas_return="avg", shots=512) sim_result = backend_sim.run(qobj).result() vector = sim_result.get_statevector() fid = state_fidelity(np.array([0, 1]), vector) return fid, vector # if __name__ == "__main__": # environment = QiskitEnv(np.array([0,1]),100) # validate_py_environment(environment, episodes=5) def get_state(self, actions): """ Build the pulse based on the action and invoke a IBM Q backend and run the experiment.Simulator is used here. """ armonk_backend = FakeArmonk() freq_est = 4.97e9 drive_est = 6.35e7 armonk_backend.defaults().qubit_freq_est = [freq_est] # Define the hamiltonian to avoid randomness armonk_backend.configuration().hamiltonian["h_str"] = [ "wq0*0.5*(I0-Z0)", "omegad0*X0||D0", ] armonk_backend.configuration().hamiltonian["vars"] = { "wq0": 2 * np.pi * freq_est, "omegad0": drive_est, } armonk_backend.configuration().hamiltonian["qub"] = {"0": 2} armonk_backend.configuration().dt = 2.2222222222222221e-10 armonk_model = PulseSystemModel.from_backend(armonk_backend) # build the pulse with pulse.build( name="pulse_programming_in", backend=armonk_backend ) as pulse_prog: dc = pulse.DriveChannel(0) ac = pulse.acquire_channel(0) for action in actions: pulse.play([action] * self.interval_width, dc) pulse.delay(self.interval_width * len(self.actions_list) + 10, ac) mem_slot = pulse.measure(0) # Simulate the pulse backend_sim = PulseSimulator(system_model=armonk_model) qobj = assemble(pulse_prog, backend=backend_sim, meas_return="avg", shots=512) sim_result = backend_sim.run(qobj).result() vector = sim_result.get_statevector() fid = state_fidelity(np.array([0, 1]), vector) pulse_prog.draw() return fid, vector, pulse_prog @staticmethod def get_tf_environment(max_step, interval_width): """Return the tensorflow environment of the python environment""" py_env = QiskitEnv(np.array([1, 0]), max_step, interval_width) tf_env = tf_py_environment.TFPyEnvironment(py_env) return tf_env
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(range(2)) qc.measure(range(2), range(2)) # apply x gate if the classical register has the value 2 (10 in binary) qc.x(0).c_if(cr, 2) # apply y gate if bit 0 is set to 1 qc.y(1).c_if(0, 1) qc.draw('mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import transpile from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeVigoV2 backend = FakeVigoV2() qc = QuantumCircuit(2, 1) qc.h(0) qc.x(1) qc.cp(np.pi/4, 0, 1) qc.h(0) qc.measure([0], [0]) qc_basis = transpile(qc, backend) qc_basis.draw(output='mpl')
https://github.com/pedroripper/qiskit_tutoriais
pedroripper
from qiskit import * %matplotlib inline import numpy as np qc = QuantumCircuit(2,2) qc.rx(np.pi/2,0) qc.z(0) qc.draw(output='mpl') qc2 = QuantumCircuit(2,2) qc2.z(0) qc2.rx(-np.pi/2,0) qc2.draw(output='mpl')
https://github.com/qiskit-community/community.qiskit.org
qiskit-community
from qiskit import * # z measurement of qubit 0 measure_z = QuantumCircuit(1,1) measure_z.measure(0,0); # x measurement of qubit 0 measure_x = QuantumCircuit(1,1) measure_x.h(0) measure_x.measure(0,0); qc = QuantumCircuit(1) qc.h(0) # the hadamard qc.x(0) # x gate qc.y(0) # y gate qc.z(0) # z gate # for the following, replace theta by any number theta = 3.14159/4 qc.ry(theta,0); # y axis rotation shots = 2**14 # number of samples used for statistics uncertainty = 0 for measure_circuit in [measure_z, measure_x]: # run the circuit with a the selected measurement and get the number of samples that output each bit value counts = execute(qc+measure_circuit,Aer.get_backend('qasm_simulator'),shots=shots).result().get_counts() # calculate the probabilities for each bit value probs = {} for output in ['0','1']: if output in counts: probs[output] = counts[output]/shots else: probs[output] = 0 uncertainty += ( probs['0'] - probs['1'] )**2 # print the total uncertainty print('The total uncertainty is',uncertainty ) # for the following, replace theta by any number theta = 3.14159/2 qc.rx(theta,0); # x axis rotation # y measurement of qubit 0 measure_y = QuantumCircuit(1,1) measure_y.sdg(0) measure_y.h(0) measure_y.measure(0,0); shots = 2**14 # number of samples used for statistics uncertainty = 0 for measure_circuit in [measure_z, measure_x, measure_y]: # run the circuit with a the selected measurement and get the number of samples that output each bit value counts = execute(qc+measure_circuit,Aer.get_backend('qasm_simulator'),shots=shots).result().get_counts() # calculate the probabilities for each bit value probs = {} for output in ['0','1']: if output in counts: probs[output] = counts[output]/shots else: probs[output] = 0 uncertainty += ( probs['0'] - probs['1'] )**2 # print the total uncertainty print('The total uncertainty is',uncertainty )